@nuralogix.ai/web-measurement-embedded-app 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -132,7 +132,11 @@ type SupportedLanguage = 'en' | 'ja' | 'zh' | 'es' | 'pt' | 'pt-BR' | 'it' | 'fr
132
132
  interface Config {
133
133
  /** Enables all distance, direction, and movement validations */
134
134
  checkConstraints?: boolean;
135
- /** Camera facing mode: 'user' for front camera, 'environment' for back camera */
135
+ /**
136
+ * Camera facing mode: `'user'` (front) or `'environment'` (back). Undefined by
137
+ * default. When set, it takes precedence over `defaultCameraId` — the camera is
138
+ * selected by facing direction and the browser chooses the device.
139
+ */
136
140
  cameraFacingMode?: 'user' | 'environment';
137
141
  /** If true, camera starts automatically without user interaction */
138
142
  cameraAutoStart?: boolean;
@@ -144,6 +148,20 @@ interface Config {
144
148
  debugMode?: boolean;
145
149
  /** If true, enables downloading of measurement payloads */
146
150
  downloadPayloads?: boolean;
151
+ /**
152
+ * Preferred camera `deviceId` to use on startup. Used only when
153
+ * `cameraFacingMode` is not set (a set `cameraFacingMode` takes precedence).
154
+ * Useful when the browser does not expose enough information for WMEA to pick
155
+ * the right camera (e.g. distinguishing the ultra-wide front camera on iPad).
156
+ * Persist the user's selection from a prior session (e.g. in `localStorage`)
157
+ * and pass it back here.
158
+ *
159
+ * - If the dropdown is shown, this becomes the default selection.
160
+ * - If the dropdown is hidden (e.g. `cameraAutoStart` or mobile), this
161
+ * camera is opened directly.
162
+ * - If the ID is not connected, the browser's default camera is used.
163
+ */
164
+ defaultCameraId?: string;
147
165
  }
148
166
  interface Profile extends Omit<Demographics, 'height' | 'weight'> {
149
167
  /** Height in centimetres (120–220) */
package/lib/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var jt="1.0.0";const G={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANCELLED:"cancelled",DESTROYED:"destroyed",LOGS:"logs"};var nt=(t=>(t.measurement="Measurement",t.collector="Collector",t.camera="Camera",t.app="App",t))(nt||{});const y={INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},L={CAMERA_STARTED:"CAMERA_STARTED",APP_LOADED:"APP_LOADED",MEASUREMENT_PREPARED:"MEASUREMENT_PREPARED",ASSETS_DOWNLOADED:"ASSETS_DOWNLOADED",FACE_TRACKER_LOADED:"FACE_TRACKER_LOADED",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"},ze={CAMERA_STARTED:{event:L.CAMERA_STARTED,level:y.INFO},APP_LOADED:{event:L.APP_LOADED,level:y.INFO},MEASUREMENT_PREPARED:{event:L.MEASUREMENT_PREPARED,level:y.INFO},ASSETS_DOWNLOADED:{event:L.ASSETS_DOWNLOADED,level:y.INFO},FACE_TRACKER_LOADED:{event:L.FACE_TRACKER_LOADED,level:y.INFO},MEASUREMENT_STARTED:{event:L.MEASUREMENT_STARTED,level:y.INFO},MEASUREMENT_COMPLETED:{event:L.MEASUREMENT_COMPLETED,level:y.INFO},CAMERA_PERMISSION_GRANTED:{event:L.CAMERA_PERMISSION_GRANTED,level:y.INFO},INTERMEDIATE_RESULTS:{event:L.INTERMEDIATE_RESULTS,level:y.INFO},RESULTS_RECEIVED:{event:L.RESULTS_RECEIVED,level:y.INFO},MEASUREMENT_CANCELED:{event:L.MEASUREMENT_CANCELED,level:y.WARN},CONSTRAINT_VIOLATION:{event:L.CONSTRAINT_VIOLATION,level:y.ERROR},PAGE_UNLOADED:{event:L.PAGE_UNLOADED,level:y.INFO},PAGE_VISIBILITY_CHANGE:{event:L.PAGE_VISIBILITY_CHANGE,level:y.INFO}},se={DESTROY:"destroy",CANCEL:"cancel",SET_THEME:"setTheme",SET_LANGUAGE:"setLanguage",GET_LOGS:"getLogs",SET_APP_SETTINGS:"setAppSettings"};var ot=(t=>(t.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",t.WORKER_ERROR="WORKER_ERROR",t.PROFILE_INFO_NOT_SET="PROFILE_INFO_NOT_SET",t.INVALID_PROFILE="INVALID_PROFILE",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.FACE_NONE="FACE_NONE",t.WEBSOCKET_DISCONNECTED="WEBSOCKET_DISCONNECTED",t.MEASUREMENT_PREPARE_FAILED="MEASUREMENT_PREPARE_FAILED",t.INVALID_MEASUREMENT_OPTIONS="INVALID_MEASUREMENT_OPTIONS",t.ASSET_DOWNLOAD_FAILED="ASSET_DOWNLOAD_FAILED",t))(ot||{}),ct="0.1.0-beta.13",ie=(t=>(t.DELETE="DELETE",t.GET="GET",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.CONNECT="CONNECT",t))(ie||{}),J=(t=>(t.ON_BEFORE_REST_CALL_ERROR="ON_BEFORE_REST_CALL_ERROR",t))(J||{});const lt=typeof DedicatedWorkerGlobalScope<"u",De=async({baseUrl:t,urlFragment:e,method:s,headers:a,data:l},d)=>{const n=`${t}/${e}`;let h={Code:"",Message:""};try{const E=await fetch(n,{method:s,cache:"no-store",credentials:"include",headers:a,...l!=null&&{body:JSON.stringify(l)}}),c=E.headers.get("content-type"),T=E.status.toString();h={Code:"UNSUPPORTED_RESPONSE_CONTENT_TYPE",Message:"UNSUPPORTED_RESPONSE_CONTENT_TYPE"},T==="503"&&(h={Code:"SERVICE_UNAVAILABLE",Message:"Service unavailable"}),T==="429"&&(h={Code:"TOO_MANY_REQUESTS",Message:"Too many requests"}),c!=null&&(c.startsWith("application/json;")&&(h=await E.json()),c.startsWith("text/plain;")&&(h={data:await E.text()}));let p=E.headers;if(lt){const b={};E.headers.forEach((w,C)=>{b[C]=w}),p=b}try{d(T,T==="200"?void 0:h)}catch(b){console.error("Error running onAfterRESTCall callback",b)}return{status:T,headers:p,body:h}}catch(E){return E instanceof SyntaxError?h={Code:"SYNTAX_ERROR",Message:"SYNTAX_ERROR"}:h={Code:"UNEXPECTED_ERROR",Message:"UNEXPECTED_ERROR"},{status:"UNKNOWN",headers:lt?{}:new Headers,body:h}}},Le=()=>new Headers({"Content-Type":"application/json"});var Yt=Object.defineProperty,zt=(t,e,s)=>e in t?Yt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Jt=(t,e,s)=>zt(t,e+"",s);class Je{constructor(e){Jt(this,"parent"),this.parent=e}async onBeforeRESTCall(){try{return this.parent.onBeforeRESTCall(),{Code:"SUCCESS",Message:"SUCCESS"}}catch{return{Code:J.ON_BEFORE_REST_CALL_ERROR,Message:J.ON_BEFORE_REST_CALL_ERROR}}}getDefaults(e){return{baseUrl:JSON.parse(this.parent.getUrl()).http.slice(0,-1),method:ie[e],headers:Le()}}getHeaderWithDeviceToken(){const e=Le();return e.set("Authorization",`Bearer ${this.parent.getSession().deviceToken}`),e}getHeaderWithUserToken(){const e=Le();return e.set("Authorization",`Bearer ${this.parent.getSession().userToken}`),e}getHeaderWithSessionEnabled(){const e=Le();return e.set("x-nura-session","true"),e}}class Xt extends Je{async create(e,s){const{Code:a,Message:l}=await this.onBeforeRESTCall();if(a===J.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:l},headers:new Headers};const{status:d,body:n,headers:h}=await De({...this.getDefaults(ie.POST),headers:s==="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:h}}}class qt extends Je{async retrieveSdkConfigData(e,s){const{Code:a,Message:l}=await this.onBeforeRESTCall();if(a===J.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:l},headers:new Headers};const{status:d,body:n,headers:h}=await De({...this.getDefaults(ie.POST),headers:s==="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:h}}}class Zt extends Je{async renew(e,s){const{Code:a,Message:l}=await this.onBeforeRESTCall();if(a===J.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:l},headers:new Headers};const{status:d,body:n,headers:h}=await De({...this.getDefaults(ie.POST),headers:s==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auths/renew",data:e},this.parent.onAfterRESTCall);if(d==="200"){const E=n.Token,c=n.RefreshToken,T={...s==="user"&&{userToken:E,userRefreshToken:c},...s==="device"&&{deviceToken:E,deviceRefreshToken:c}};this.parent.setSession(T)}return{status:d,body:n,headers:h}}async validate(e){const{Code:s,Message:a}=await this.onBeforeRESTCall();return s===J.ON_BEFORE_REST_CALL_ERROR?{status:s,body:{Code:s,Message:a},headers:new Headers}:await De({...this.getDefaults(ie.GET),headers:e==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auth/v1/validate"},this.parent.onAfterRESTCall)}}var Qt=Object.defineProperty,dt=t=>{throw TypeError(t)},es=(t,e,s)=>e in t?Qt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xe=(t,e,s)=>es(t,typeof e!="symbol"?e+"":e,s),ht=(t,e,s)=>e.has(t)||dt("Cannot "+s),qe=(t,e,s)=>(ht(t,e,"read from private field"),s?s.call(t):e.get(t)),mt=(t,e,s)=>e.has(t)?dt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ie=(t,e,s,a)=>(ht(t,e,"write to private field"),e.set(t,s),s),Ee,ae;class ts{constructor(e){mt(this,Ee,{http:new URL("https://api.deepaffex.ai")}),mt(this,ae),Xe(this,"onBeforeRESTCall"),Xe(this,"onAfterRESTCall"),Xe(this,"http"),Ie(this,ae,{deviceToken:"",deviceRefreshToken:"",userToken:"",userRefreshToken:"",deviceId:"",roleId:"",userId:"",selectedStudy:"",lastMeasurementId:"",studyCfgHash:"",studyCfgData:""}),this.http={measurements:new Xt(this),studies:new qt(this),auths:new Zt(this)},this.onBeforeRESTCall=e?.onBeforeRESTCall?e.onBeforeRESTCall:()=>{},this.onAfterRESTCall=e?.onAfterRESTCall?e.onAfterRESTCall:()=>{},e?.url!=null&&Ie(this,Ee,e.url)}static new(e){return new this(e??void 0)}getUrl(){return JSON.stringify(qe(this,Ee))}setUrl(e){Ie(this,Ee,{http:new URL(e)})}getSession(){return qe(this,ae)}setSession(e){const s=["deviceToken","deviceRefreshToken","userToken","userRefreshToken","deviceId","userId","roleId","selectedStudy","lastMeasurementId","studyCfgHash","studyCfgData"];Object.keys(e).every(d=>s.includes(d)&&typeof e[d]=="string")&&Ie(this,ae,{...qe(this,ae),...e})}}Ee=new WeakMap,ae=new WeakMap;const ss=t=>ts.new(t);var is=Object.defineProperty,ut=t=>{throw TypeError(t)},as=(t,e,s)=>e in t?is(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,rs=(t,e,s)=>as(t,e+"",s),ns=(t,e,s)=>e.has(t)||ut("Cannot "+s),os=(t,e,s)=>e.has(t)?ut("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ze=(t,e,s)=>(ns(t,e,"access private method"),s),pe,Qe,ft;let Et=t=>new Int8Array(t);class cs extends EventTarget{constructor(){super(...arguments),os(this,pe),rs(this,"canDecompress",!1)}static init(){return new this}dispatch(e,s){this.dispatchEvent(new CustomEvent(e,{detail:s}))}getBytesDownloadedEvent(e,s,a,l){return new CustomEvent("bytesDownloaded",{detail:{bytes:e,uncompressedSize:s,url:a,done:l}})}getBytesDownloadErrorEvent(e,s){return new CustomEvent("downloadedError",{detail:{url:e,error:s}})}decompressBrotli(e){const s=atob(e),a=new Uint8Array(s.length);for(let n=0;n<s.length;n++)a[n]=s.charCodeAt(n);const l=new Int8Array(a.length);for(let n=0;n<a.length;n++)l[n]=a[n]>=128?a[n]-256:a[n];return Et(l).buffer}async fetchAsset(e,s,a,l,d){const n=s+a,h=e.find(c=>c.file===a).uncompressedSize,E=(c,T,p,b)=>Ze(this,pe,Qe).call(this,this.getBytesDownloadedEvent(c,T,p,b));try{const T=(await fetch(n)).body?.getReader();if(!T)throw new Error("Failed to get reader from response body.");let p=0;const b=new ReadableStream({async start(C){await v();async function v(){const{done:P,value:z}=await T.read();if(P){C.close(),E(p,h,n,!0);return}z&&(C.enqueue(z),p+=z.length,E(p,h,n,!1)),await v()}}}),w=new Response(b);if(l){const C=await w.json(),{base64EncodedValue:v}=C;if(d==="gzip"){await Ze(this,pe,ft).call(this,v);return}return this.decompressBrotli(v)}else return await w.arrayBuffer()}catch(c){Ze(this,pe,Qe).call(this,this.getBytesDownloadErrorEvent(n,c))}}}pe=new WeakSet,Qe=function(t){this.dispatchEvent(t)},ft=async function(t){const e=Uint8Array.from(atob(t),c=>c.charCodeAt(0)),a=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")),l=await new Response(a).arrayBuffer(),d=new TextDecoder().decode(new Uint8Array(l)),n=new Blob([d],{type:"application/javascript"}),h=URL.createObjectURL(n);Et=(await import(h)).BrotliDecode,this.canDecompress=!0,URL.revokeObjectURL(h)};var ls=Object.defineProperty,ds=(t,e,s)=>e in t?ls(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pt=(t,e,s)=>ds(t,typeof e!="symbol"?e+"":e,s);class hs{constructor(){pt(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""}),pt(this,"debugLogs",[])}appendLog(e){this.debugLogs.push(e)}generateHTMLTable(){return`
1
+ var jt="1.0.1";const G={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANCELLED:"cancelled",DESTROYED:"destroyed",LOGS:"logs"};var nt=(t=>(t.measurement="Measurement",t.collector="Collector",t.camera="Camera",t.app="App",t))(nt||{});const y={INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},L={CAMERA_STARTED:"CAMERA_STARTED",APP_LOADED:"APP_LOADED",MEASUREMENT_PREPARED:"MEASUREMENT_PREPARED",ASSETS_DOWNLOADED:"ASSETS_DOWNLOADED",FACE_TRACKER_LOADED:"FACE_TRACKER_LOADED",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"},ze={CAMERA_STARTED:{event:L.CAMERA_STARTED,level:y.INFO},APP_LOADED:{event:L.APP_LOADED,level:y.INFO},MEASUREMENT_PREPARED:{event:L.MEASUREMENT_PREPARED,level:y.INFO},ASSETS_DOWNLOADED:{event:L.ASSETS_DOWNLOADED,level:y.INFO},FACE_TRACKER_LOADED:{event:L.FACE_TRACKER_LOADED,level:y.INFO},MEASUREMENT_STARTED:{event:L.MEASUREMENT_STARTED,level:y.INFO},MEASUREMENT_COMPLETED:{event:L.MEASUREMENT_COMPLETED,level:y.INFO},CAMERA_PERMISSION_GRANTED:{event:L.CAMERA_PERMISSION_GRANTED,level:y.INFO},INTERMEDIATE_RESULTS:{event:L.INTERMEDIATE_RESULTS,level:y.INFO},RESULTS_RECEIVED:{event:L.RESULTS_RECEIVED,level:y.INFO},MEASUREMENT_CANCELED:{event:L.MEASUREMENT_CANCELED,level:y.WARN},CONSTRAINT_VIOLATION:{event:L.CONSTRAINT_VIOLATION,level:y.ERROR},PAGE_UNLOADED:{event:L.PAGE_UNLOADED,level:y.INFO},PAGE_VISIBILITY_CHANGE:{event:L.PAGE_VISIBILITY_CHANGE,level:y.INFO}},se={DESTROY:"destroy",CANCEL:"cancel",SET_THEME:"setTheme",SET_LANGUAGE:"setLanguage",GET_LOGS:"getLogs",SET_APP_SETTINGS:"setAppSettings"};var ot=(t=>(t.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",t.WORKER_ERROR="WORKER_ERROR",t.PROFILE_INFO_NOT_SET="PROFILE_INFO_NOT_SET",t.INVALID_PROFILE="INVALID_PROFILE",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.FACE_NONE="FACE_NONE",t.WEBSOCKET_DISCONNECTED="WEBSOCKET_DISCONNECTED",t.MEASUREMENT_PREPARE_FAILED="MEASUREMENT_PREPARE_FAILED",t.INVALID_MEASUREMENT_OPTIONS="INVALID_MEASUREMENT_OPTIONS",t.ASSET_DOWNLOAD_FAILED="ASSET_DOWNLOAD_FAILED",t))(ot||{}),ct="0.1.0-beta.15",ie=(t=>(t.DELETE="DELETE",t.GET="GET",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.CONNECT="CONNECT",t))(ie||{}),J=(t=>(t.ON_BEFORE_REST_CALL_ERROR="ON_BEFORE_REST_CALL_ERROR",t))(J||{});const lt=typeof DedicatedWorkerGlobalScope<"u",De=async({baseUrl:t,urlFragment:e,method:s,headers:a,data:l},d)=>{const n=`${t}/${e}`;let h={Code:"",Message:""};try{const E=await fetch(n,{method:s,cache:"no-store",credentials:"include",headers:a,...l!=null&&{body:JSON.stringify(l)}}),c=E.headers.get("content-type"),T=E.status.toString();h={Code:"UNSUPPORTED_RESPONSE_CONTENT_TYPE",Message:"UNSUPPORTED_RESPONSE_CONTENT_TYPE"},T==="503"&&(h={Code:"SERVICE_UNAVAILABLE",Message:"Service unavailable"}),T==="429"&&(h={Code:"TOO_MANY_REQUESTS",Message:"Too many requests"}),c!=null&&(c.startsWith("application/json;")&&(h=await E.json()),c.startsWith("text/plain;")&&(h={data:await E.text()}));let p=E.headers;if(lt){const b={};E.headers.forEach((w,C)=>{b[C]=w}),p=b}try{d(T,T==="200"?void 0:h)}catch(b){console.error("Error running onAfterRESTCall callback",b)}return{status:T,headers:p,body:h}}catch(E){return E instanceof SyntaxError?h={Code:"SYNTAX_ERROR",Message:"SYNTAX_ERROR"}:h={Code:"UNEXPECTED_ERROR",Message:"UNEXPECTED_ERROR"},{status:"UNKNOWN",headers:lt?{}:new Headers,body:h}}},Le=()=>new Headers({"Content-Type":"application/json"});var Yt=Object.defineProperty,zt=(t,e,s)=>e in t?Yt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Jt=(t,e,s)=>zt(t,e+"",s);class Je{constructor(e){Jt(this,"parent"),this.parent=e}async onBeforeRESTCall(){try{return this.parent.onBeforeRESTCall(),{Code:"SUCCESS",Message:"SUCCESS"}}catch{return{Code:J.ON_BEFORE_REST_CALL_ERROR,Message:J.ON_BEFORE_REST_CALL_ERROR}}}getDefaults(e){return{baseUrl:JSON.parse(this.parent.getUrl()).http.slice(0,-1),method:ie[e],headers:Le()}}getHeaderWithDeviceToken(){const e=Le();return e.set("Authorization",`Bearer ${this.parent.getSession().deviceToken}`),e}getHeaderWithUserToken(){const e=Le();return e.set("Authorization",`Bearer ${this.parent.getSession().userToken}`),e}getHeaderWithSessionEnabled(){const e=Le();return e.set("x-nura-session","true"),e}}class Xt extends Je{async create(e,s){const{Code:a,Message:l}=await this.onBeforeRESTCall();if(a===J.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:l},headers:new Headers};const{status:d,body:n,headers:h}=await De({...this.getDefaults(ie.POST),headers:s==="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:h}}}class qt extends Je{async retrieveSdkConfigData(e,s){const{Code:a,Message:l}=await this.onBeforeRESTCall();if(a===J.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:l},headers:new Headers};const{status:d,body:n,headers:h}=await De({...this.getDefaults(ie.POST),headers:s==="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:h}}}class Zt extends Je{async renew(e,s){const{Code:a,Message:l}=await this.onBeforeRESTCall();if(a===J.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:l},headers:new Headers};const{status:d,body:n,headers:h}=await De({...this.getDefaults(ie.POST),headers:s==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auths/renew",data:e},this.parent.onAfterRESTCall);if(d==="200"){const E=n.Token,c=n.RefreshToken,T={...s==="user"&&{userToken:E,userRefreshToken:c},...s==="device"&&{deviceToken:E,deviceRefreshToken:c}};this.parent.setSession(T)}return{status:d,body:n,headers:h}}async validate(e){const{Code:s,Message:a}=await this.onBeforeRESTCall();return s===J.ON_BEFORE_REST_CALL_ERROR?{status:s,body:{Code:s,Message:a},headers:new Headers}:await De({...this.getDefaults(ie.GET),headers:e==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auth/v1/validate"},this.parent.onAfterRESTCall)}}var Qt=Object.defineProperty,dt=t=>{throw TypeError(t)},es=(t,e,s)=>e in t?Qt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xe=(t,e,s)=>es(t,typeof e!="symbol"?e+"":e,s),ht=(t,e,s)=>e.has(t)||dt("Cannot "+s),qe=(t,e,s)=>(ht(t,e,"read from private field"),s?s.call(t):e.get(t)),mt=(t,e,s)=>e.has(t)?dt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ie=(t,e,s,a)=>(ht(t,e,"write to private field"),e.set(t,s),s),Ee,ae;class ts{constructor(e){mt(this,Ee,{http:new URL("https://api.deepaffex.ai")}),mt(this,ae),Xe(this,"onBeforeRESTCall"),Xe(this,"onAfterRESTCall"),Xe(this,"http"),Ie(this,ae,{deviceToken:"",deviceRefreshToken:"",userToken:"",userRefreshToken:"",deviceId:"",roleId:"",userId:"",selectedStudy:"",lastMeasurementId:"",studyCfgHash:"",studyCfgData:""}),this.http={measurements:new Xt(this),studies:new qt(this),auths:new Zt(this)},this.onBeforeRESTCall=e?.onBeforeRESTCall?e.onBeforeRESTCall:()=>{},this.onAfterRESTCall=e?.onAfterRESTCall?e.onAfterRESTCall:()=>{},e?.url!=null&&Ie(this,Ee,e.url)}static new(e){return new this(e??void 0)}getUrl(){return JSON.stringify(qe(this,Ee))}setUrl(e){Ie(this,Ee,{http:new URL(e)})}getSession(){return qe(this,ae)}setSession(e){const s=["deviceToken","deviceRefreshToken","userToken","userRefreshToken","deviceId","userId","roleId","selectedStudy","lastMeasurementId","studyCfgHash","studyCfgData"];Object.keys(e).every(d=>s.includes(d)&&typeof e[d]=="string")&&Ie(this,ae,{...qe(this,ae),...e})}}Ee=new WeakMap,ae=new WeakMap;const ss=t=>ts.new(t);var is=Object.defineProperty,ut=t=>{throw TypeError(t)},as=(t,e,s)=>e in t?is(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,rs=(t,e,s)=>as(t,e+"",s),ns=(t,e,s)=>e.has(t)||ut("Cannot "+s),os=(t,e,s)=>e.has(t)?ut("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ze=(t,e,s)=>(ns(t,e,"access private method"),s),pe,Qe,ft;let Et=t=>new Int8Array(t);class cs extends EventTarget{constructor(){super(...arguments),os(this,pe),rs(this,"canDecompress",!1)}static init(){return new this}dispatch(e,s){this.dispatchEvent(new CustomEvent(e,{detail:s}))}getBytesDownloadedEvent(e,s,a,l){return new CustomEvent("bytesDownloaded",{detail:{bytes:e,uncompressedSize:s,url:a,done:l}})}getBytesDownloadErrorEvent(e,s){return new CustomEvent("downloadedError",{detail:{url:e,error:s}})}decompressBrotli(e){const s=atob(e),a=new Uint8Array(s.length);for(let n=0;n<s.length;n++)a[n]=s.charCodeAt(n);const l=new Int8Array(a.length);for(let n=0;n<a.length;n++)l[n]=a[n]>=128?a[n]-256:a[n];return Et(l).buffer}async fetchAsset(e,s,a,l,d){const n=s+a,h=e.find(c=>c.file===a).uncompressedSize,E=(c,T,p,b)=>Ze(this,pe,Qe).call(this,this.getBytesDownloadedEvent(c,T,p,b));try{const T=(await fetch(n)).body?.getReader();if(!T)throw new Error("Failed to get reader from response body.");let p=0;const b=new ReadableStream({async start(C){await v();async function v(){const{done:P,value:z}=await T.read();if(P){C.close(),E(p,h,n,!0);return}z&&(C.enqueue(z),p+=z.length,E(p,h,n,!1)),await v()}}}),w=new Response(b);if(l){const C=await w.json(),{base64EncodedValue:v}=C;if(d==="gzip"){await Ze(this,pe,ft).call(this,v);return}return this.decompressBrotli(v)}else return await w.arrayBuffer()}catch(c){Ze(this,pe,Qe).call(this,this.getBytesDownloadErrorEvent(n,c))}}}pe=new WeakSet,Qe=function(t){this.dispatchEvent(t)},ft=async function(t){const e=Uint8Array.from(atob(t),c=>c.charCodeAt(0)),a=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")),l=await new Response(a).arrayBuffer(),d=new TextDecoder().decode(new Uint8Array(l)),n=new Blob([d],{type:"application/javascript"}),h=URL.createObjectURL(n);Et=(await import(h)).BrotliDecode,this.canDecompress=!0,URL.revokeObjectURL(h)};var ls=Object.defineProperty,ds=(t,e,s)=>e in t?ls(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pt=(t,e,s)=>ds(t,typeof e!="symbol"?e+"":e,s);class hs{constructor(){pt(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""}),pt(this,"debugLogs",[])}appendLog(e){this.debugLogs.push(e)}generateHTMLTable(){return`
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="UTF-8">
@@ -736,4 +736,4 @@ var jt="1.0.0";const G={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANC
736
736
  <\/script>
737
737
  </body>
738
738
  </html>
739
- `}openLogInNewWindow(){console.log(this.debugLogs);const e=this.generateHTMLTable(),s=new Blob([e],{type:"text/html"}),a=URL.createObjectURL(s);window.open(a,"_blank")}}var ms=Object.defineProperty,us=(t,e,s)=>e in t?ms(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xe=(t,e,s)=>us(t,typeof e!="symbol"?e+"":e,s);class Ye{constructor(e,s){xe(this,"workerUrl"),xe(this,"worker"),this.worker=e,this.workerUrl=s}static init(e,s,a){const l=new Blob([e],{type:"application/javascript"}),d=URL.createObjectURL(l),n=a||`WORKER${String(new Date().getTime())}`,h=new Worker(new URL(d,import.meta.url),{name:n,type:s});return new Ye(h,d)}destroy(){return this.worker?(this.worker.terminate(),URL.revokeObjectURL(this.workerUrl),this.worker=void 0,!0):!1}}const fs=(t,e,s,a)=>{const l=t/e,d=s/a;let n=0,h=0;l>d?(n=t,h=t/d):(h=e,n=e*d);const E=(t-n)/2,c=(e-h)/2;return{width:n||0,height:h||0,offsetX:E||0,offsetY:c||0}},Es=(t,e,s,a)=>{const l=(t-s)/2,d=(e-a)/2;return{width:s||0,height:a||0,offsetX:l||0,offsetY:d||0}},ps=(t,e,s,a)=>{const l=t/e,d=s/a;let n=0,h=0;l>d?(h=e,n=e*d):(n=t,h=t/d);const E=(t-n)/2,c=(e-h)/2;return{width:n||0,height:h||0,offsetX:E||0,offsetY:c||0}},Ts=(t,e)=>{switch(t){case"none":return Es(...e);case"cover":return fs(...e);case"contain":default:return ps(...e)}},Tt=t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(t),Ss=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"),_s=(t,e)=>{const s={...t};if(e.logger)if(Ss(e.logger))s.logger={...s.logger,...e.logger};else return{results:"invalid"};if(e.apiUrl!==void 0)if(typeof e.apiUrl=="string")s.apiUrl=e.apiUrl;else return{results:"invalid"};if(e.metrics!==void 0)if(typeof e.metrics=="boolean")s.metrics=e.metrics;else return{results:"invalid"};if(e.mirrorVideo!==void 0)if(typeof e.mirrorVideo=="boolean")s.mirrorVideo=e.mirrorVideo;else return{results:"invalid"};if(e.displayMediaStream!==void 0)if(typeof e.displayMediaStream=="boolean")s.displayMediaStream=e.displayMediaStream;else return{results:"invalid"};if(e.assetFolder!==void 0)if(typeof e.assetFolder=="string")s.assetFolder=e.assetFolder;else return{results:"invalid"};if(e.mediaElement!==void 0)if(e.mediaElement instanceof HTMLDivElement)s.mediaElement=e.mediaElement;else return{results:"invalid"};if(e.constraintOverrides!==void 0){let a=function(n,h){if(!(n in d))return!1;const E=d[n];return typeof h===E};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,h])=>[n,typeof h]));for(const n in e.constraintOverrides){const h=e.constraintOverrides[n];if(!a(n,h))return{results:"invalid"}}s.constraintOverrides=e.constraintOverrides}return{results:"valid",settings:s}},gs=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 bs=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 St{constructor(e=1e3){xe(this,"timestamps",[]),xe(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,s=this.timestamps.at(-1)-this.timestamps[0]||1;return e/s*1e3}get frameCount(){return this.timestamps.length}reset(){this.timestamps=[]}}var ws=Object.defineProperty,Rs=(t,e,s)=>e in t?ws(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_t=(t,e,s)=>Rs(t,typeof e!="symbol"?e+"":e,s);const ks=()=>{const t=new Date,e=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0"),a=t.getFullYear();let l=t.getHours();const d=t.getMinutes().toString().padStart(2,"0"),n=t.getSeconds().toString().padStart(2,"0"),h=t.getMilliseconds().toString().padStart(3,"0"),E=l>=12?"PM":"AM";return l=l%12||12,`[${e}/${s}/${a}, ${l}:${d}:${n}.${h} ${E}]`};class gt{constructor(){_t(this,"mertics",new hs),_t(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""})}retrieveLogs(e){this.mertics.debugLogs=e,this.mertics.openLogInNewWindow(),this.mertics.debugLogs=[]}setVersion(e){this.version=e,this.mertics.version=e}log(e,s,a,l=!1,d={}){const n=ks();if(l)this.mertics.appendLog({thread:"Main",timestamp:n,category:s,message:e,meta:d});else{const h=`[${s}]`,E=" ",c=e,T=`color:${a}; font-weight:800;`,p=`color:${bs(s)}; font-weight:700;`;console.log("%c%s%c%s%c%s%c%s",T,n,p,h,"background:inherit;",E,"font-style: italic;",c)}}info(e,s){this.log(e,s,"blue")}warn(e,s){this.log(e,s,"orange")}error(e,s){this.log(e,s,"red")}debug(e,s){this.log(e,s,"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 Cs={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},X={SEX_ASSIGNED_AT_BIRTH:1,AGE_YEARS:2,HEIGHT_CM:3,WEIGHT_KG:4,SMOKER:5,BLOOD_PRESSURE_MEDICATION:7,DIABETES:8};var bt=(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))(bt||{});const q={ASSETS_NOT_DOWNLOADED:"ASSETS_NOT_DOWNLOADED",NOT_LOADED:"NOT_LOADED",LOADING:"LOADING",LOADED:"LOADED",READY:"READY"},Fe={COLLECTOR:"COLLECTOR",ASSET_DOWNLOAD:"ASSET_DOWNLOAD",WEB_SOCKET:"WEB_SOCKET"},Me={CONTAIN:"contain",COVER:"cover",NONE:"none"};var N=(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.FACE_TRACKER_INIT_ERROR="FACE_TRACKER_INIT_ERROR",t.SET_ROTATE_180="SET_ROTATE_180",t.GET_LOGS="GET_LOGS",t))(N||{}),As=Object.defineProperty,wt=t=>{throw TypeError(t)},vs=(t,e,s)=>e in t?As(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,k=(t,e,s)=>vs(t,typeof e!="symbol"?e+"":e,s),et=(t,e,s)=>e.has(t)||wt("Cannot "+s),Te=(t,e,s)=>(et(t,e,"read from private field"),e.get(t)),tt=(t,e,s)=>e.has(t)?wt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Se=(t,e,s,a)=>(et(t,e,"write to private field"),e.set(t,s),s),Os=(t,e,s)=>(et(t,e,"access private method"),s),ys=(t,e,s,a)=>({set _(l){Se(t,e,l)},get _(){return Te(t,e)}}),Z,re,st,Rt;const Ns=class Ht{constructor(e,s,a,l){tt(this,st),k(this,"logger"),k(this,"mediaElement"),k(this,"numOfFramesPresented",0),k(this,"workers",[]),k(this,"numOftrackedVideoFrames",0),k(this,"warmupFrameNumber",0),k(this,"videoCallbackId",0),k(this,"numOfWorkers",4),k(this,"isLoggingFaceTrackerWorkers",!1),k(this,"isLoggingSdk",!1),k(this,"workerIndex",0),k(this,"metrics",!1),k(this,"videoFpsTracker",new St(1e3)),k(this,"faceTrackerFpsTracker",new St(1e3)),k(this,"videoElementSize",{width:0,height:0,offsetX:0,offsetY:0}),k(this,"videoElement",document.createElement("video")),k(this,"frameWidth",0),k(this,"frameHeight",0),k(this,"mirrorVideo",!0),k(this,"settings",{faceTrackerWidth:0,faceTrackerHeight:0,displayMediaStream:!0,objectFit:Me.COVER}),k(this,"isExtracting",!1),k(this,"starRating",0),k(this,"scaleFactor",1),k(this,"warmupIndex",0),k(this,"warmingUp",!0),k(this,"ftWorkerIndex",0),k(this,"lastFrameNumber",-1),k(this,"rotate180",!1),tt(this,Z,null),tt(this,re,0),k(this,"on");const{mediaElement:d,mirrorVideo:n,numOfWorkers:h,isLoggingFaceTrackerWorkers:E,isLoggingSdk:c,metrics:T,displayMediaStream:p}=s;this.on=l,this.numOfWorkers=h,this.isLoggingFaceTrackerWorkers=E,this.isLoggingSdk=c,this.metrics=T,this.logger=a,this.settings.displayMediaStream=p,this.mirrorVideo=n,this.mediaElement=d,this.videoFrameCallback=this.videoFrameCallback.bind(this),this.workers=e,this.scaleFactor=s.scaleFactor,this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.preload="auto"}static async init(e,s,a){const{numOfWorkers:l,faceTrackerCode:d}=e,n=[],h=new TextDecoder().decode(new Uint8Array(d));if(l>0)for(let c=1;c<=l;c+=1){const T=Ye.init(h,"module",`FACE_TRACKER_WORKER_${c-1}`);n.push({ft:T,channel:new MessageChannel,isBusy:!1})}const E=new Ht(n,e,s,a);return l>0&&!await E.initWorkerOnMessage(e.models)?null:E}async initWorkerOnMessage(e){const s=window.matchMedia("(orientation: portrait)").matches,a=s?360:640,l=s?640:360,d=this.workers.map((n,h)=>new Promise((E,c)=>{let T=!1;n.ft.worker.onmessage=p=>{const{action:b,payload:w}=p.data;switch(b){case N.INIT_TFJS:break;case N.READY:{const{workerName:C,version:v,workerId:P,backend:z}=w;T||(T=!0,E()),this.on.faceTrackersReady&&this.on.faceTrackersReady(C,v,P,z);break}case N.FACE_TRACKER_INIT_ERROR:{const{error:C}=w;T||(T=!0,c(new Error(`Worker initialization failed: ${C}`)));break}case N.LANDMARKS:{this.faceTrackerFpsTracker.tick(),n.isBusy=!1,this.warmingUp&&this.warmupIndex++;const{face:C,annotations:v,frameTimestamp:P}=w;this.on.landmarksAvailable&&this.on.landmarksAvailable(C,v,P);break}case N.DESTROY:{const{workerId:C}=w;this.workers[C]&&this.workers[C].ft.destroy(),Te(this,Z)&&(ys(this,re)._++,Te(this,re)>=this.workers.length&&(Te(this,Z).call(this,!0),Se(this,Z,null),Se(this,re,0),this.workers=[]));break}case N.GET_LOGS:{const{logs:C,workerId:v}=w;this.on.logsAvailable&&this.on.logsAvailable(C,v);break}}},n.ft.worker.postMessage({action:N.INIT_TFJS,payload:{width:a,height:l,models:e,scaleFactor:this.scaleFactor,workerId:h,isLogging:this.isLoggingFaceTrackerWorkers,metrics:this.metrics}}),n.ft.worker.postMessage({action:N.SET_PORT,payload:{port:n.channel.port2}},[n.channel.port2])}));try{return await Promise.all(d),!0}catch{return await this.destroyWorkers(),!1}}getMediaElement(){return this.mediaElement}setIsExtracting(e){this.isExtracting=e}destroyWorkers(){return Te(this,Z)!==null?Promise.resolve(!1):new Promise(e=>{setTimeout(async()=>{if(this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.workers.length===0){e(!0);return}Se(this,Z,e),Se(this,re,0),this.workers.forEach(s=>{s?.ft?.worker?.postMessage({action:N.DESTROY})})},200)})}createMediaElements(){this.videoElement.addEventListener("ended",async()=>{this.destroyWorkers()});const e=document.createElement("div"),s=this.settings.displayMediaStream?this.videoElement:e,a="white";this.mediaElement.appendChild(s),s.style.width="100%",s.style.height="100%",s.style.boxSizing="border-box",this.settings.displayMediaStream&&(s.style.border=`1px solid ${a}`),s.style.objectFit=this.settings.objectFit,s.style.transform=`scale(${this.mirrorVideo?"-1":"1"},1)`,this.settings.displayMediaStream||(s.style.height=`${this.frameHeight}px`,s.style.width=`${this.frameWidth}px`),new ResizeObserver(d=>{const{contentRect:n,target:h}=d[0],{width:E,height:c}=n,{x:T,y:p}=h.getBoundingClientRect(),{faceTrackerWidth:b,faceTrackerHeight:w}=this.settings;this.videoElementSize=Ts(this.settings.objectFit,[E,c,this.frameWidth,this.frameHeight]);const{width:C,height:v}=this.videoElementSize;if(!this.settings.displayMediaStream){const P=this.settings.objectFit===Me.NONE;s.style.height=`${Math.trunc(P?v:c)}px`,s.style.width=`${Math.trunc(P?C:E)}px`}this.mediaElement.dispatchEvent(new CustomEvent("mediaElementSizeChanged",{detail:{mediaElementSize:{width:E,height:c,x:T,y:p},videoElementSize:this.videoElementSize,frameInfo:{mediaStreamWidth:this.frameWidth,mediaStreamHeight:this.frameHeight,faceTrackerWidth:b,faceTrackerHeight:w},isPortrait:c>E,aspectRatio:E/c}}))}).observe(this.mediaElement)}log(e,s,a){this.isLoggingSdk&&this.logger.info(e,s),this.metrics&&this.logger.log(e,s,"",!0,a)}videoFrameCallback(e,s){const{presentedFrames:a,captureTime:l,expectedDisplayTime:d,mediaTime:n}=s;this.videoFpsTracker.tick();const h=l===void 0?d:l;this.numOfFramesPresented=a;const E=`Number of frames presented: ${this.numOfFramesPresented} - time: ${h}`;let c=0;if(n&&n>0?c=n*1e3:l&&l>0?c=l>1e6?l-performance.timeOrigin:l:c=e,this.log(E,m.sdk,{captureTime:h,presentedFrames:a}),this.warmingUp)if(this.warmupIndex>=this.numOfWorkers)this.warmingUp=!1;else{const T=this.workers[this.warmupIndex];if(!T.isBusy){T.isBusy=!0;const p=new VideoFrame(this.videoElement,{timestamp:c});T.ft.worker.postMessage({action:N.TRACK,payload:{frame:p,frameTimestamp:c,frameNumber:this.numOfFramesPresented}},[p])}}if(!this.warmingUp){const T=new VideoFrame(this.videoElement,{timestamp:c});let p=!1;for(let b=0;b<this.numOfWorkers;b++){this.ftWorkerIndex=(this.ftWorkerIndex+1)%this.numOfWorkers;const w=this.workers[this.ftWorkerIndex];if(w&&!w.isBusy){w.isBusy=!0,this.on.frameAvailable(c,this.numOfFramesPresented,this.lastFrameNumber,!0),w.ft.worker.postMessage({action:N.TRACK,payload:{frame:T,frameTimestamp:c,frameNumber:this.numOfFramesPresented}},[T]),p=!0;break}}p||this.on.frameAvailable(c,this.numOfFramesPresented,this.lastFrameNumber,!1,T)}this.lastFrameNumber=this.numOfFramesPresented,this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback)}setFaceTrackerMediaStreamResolution(e,s){(e<=360||s<=360)&&(this.scaleFactor=1),this.settings.faceTrackerWidth=e*this.scaleFactor,this.settings.faceTrackerHeight=s*this.scaleFactor,this.workers.forEach(a=>a.ft.worker.postMessage({action:N.SCALE_FACTOR_CHANGED,payload:{scaleFactor:this.scaleFactor}})),this.on.scaleFactorChanged&&this.on.scaleFactorChanged(this.scaleFactor)}setRotate180(e){this.rotate180=e,this.workers.forEach(s=>s.ft.worker.postMessage({action:N.SET_ROTATE_180,payload:{rotate180:e}}))}async setMediaStream(e){if(e instanceof MediaStream)try{const s=await Os(this,st,Rt).call(this,e,this.videoElement);await this.videoElement.play(),this.settings.displayMediaStream||(this.videoElement.style.visibility="none");const a=this.videoElement.videoWidth||s.width||1,l=this.videoElement.videoHeight||s.height||1;return this.setFaceTrackerMediaStreamResolution(a,l),this.frameWidth=a,this.frameHeight=l,this.log(`Face tracker resolution: ${this.settings.faceTrackerWidth} x ${this.settings.faceTrackerHeight} pixels. Video resolution: ${this.frameWidth} x ${this.frameHeight} pixels`,m.sdk,{ftWidth:this.settings.faceTrackerWidth,ftHeight:this.settings.faceTrackerHeight,frameWidth:this.frameWidth,frameHeight:this.frameHeight}),this.createMediaElements(),this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback),!0}catch(s){return console.log("Error applying face tracker video track constraints",s),!1}return!1}stopTracking(){this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.videoElement.pause(),this.videoElement.srcObject=null}};Z=new WeakMap,re=new WeakMap,st=new WeakSet,Rt=async function(t,e){e.srcObject=t,await new Promise(a=>e.onloadedmetadata=a);const[s]=t.getVideoTracks();return s.getSettings()};let Ds=Ns;var S=(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.DESTROY="DESTROY",t))(S||{}),I=(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))(I||{}),Ls=Object.defineProperty,kt=t=>{throw TypeError(t)},Is=(t,e,s)=>e in t?Ls(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ct=(t,e,s)=>Is(t,typeof e!="symbol"?e+"":e,s),it=(t,e,s)=>e.has(t)||kt("Cannot "+s),i=(t,e,s)=>(it(t,e,"read from private field"),s?s.call(t):e.get(t)),g=(t,e,s)=>e.has(t)?kt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),u=(t,e,s,a)=>(it(t,e,"write to private field"),e.set(t,s),s),o=(t,e,s)=>(it(t,e,"access private method"),s),xs=(t,e,s,a)=>({set _(l){u(t,e,l)},get _(){return i(t,e,a)}}),U,R,B,O,x,Pe,We,Ue,$e,_e,ge,Be,be,we,_,ne,F,Re,M,Ge,H,$,Q,oe,ce,ke,le,ee,Ce,Ke,de,He,he,Ae,D,ve,V,Oe,K,j,Y,me,ue,r,At,vt,Ot,yt,Nt,Dt,ye,Ve,at,rt,Lt,It,xt,Ft,Mt,Pt,Ne,je,f,Wt,Ut,$t,Bt,Gt,fe,A;const Kt=Symbol("instance_creation_key"),Fs=class Vt{constructor(e){if(g(this,r),g(this,U),g(this,R,{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:{}}),g(this,B,[{file:"decompress.json",uncompressedSize:89469},{file:"extraction_worker_0.1.0-beta.13_js.json",uncompressedSize:47465},{file:"facetracker_worker_0.1.0-beta.13_js.json",uncompressedSize:307098},{file:"extraction_wasm_0.1.0-beta.13.json",uncompressedSize:2142219},{file:"detectorModel_json.json",uncompressedSize:4640},{file:"detectorModel_bin.json",uncompressedSize:242046},{file:"landmarkModel_json.json",uncompressedSize:5036},{file:"landmarkModel_bin.json",uncompressedSize:1704814}]),g(this,O,new gt),g(this,x,cs.init()),g(this,Pe),g(this,We),g(this,Ue),g(this,$e),g(this,_e),g(this,ge),g(this,Be),g(this,be,{version:"",sdkId:""}),g(this,we,""),g(this,_),g(this,ne,0),g(this,F),g(this,Re,q.ASSETS_NOT_DOWNLOADED),g(this,M,""),g(this,Ge,""),g(this,H,!1),g(this,$,!1),g(this,Q,5),g(this,oe,30),g(this,ce,5),g(this,ke,!1),g(this,le,4),g(this,ee),g(this,Ce),g(this,Ke),g(this,de,1e7),g(this,He,0),g(this,he,new Map),g(this,Ae,Promise.resolve()),g(this,D,0),g(this,ve,-1),g(this,V,-1),g(this,Oe,.5),g(this,K,!1),g(this,j,-1),g(this,Y),g(this,me),g(this,ue),Ct(this,"on",{beforeRESTCall:null,afterRESTCall:null,bytesDownloaded:null,faceTrackerStateChanged:null,resultsReceived:null,constraintsUpdated:null,mediaElementResize:null,facialLandmarksUpdated:null,chunkSent:null,error:null}),e!==Kt)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 s=new Vt(Kt);if(!s.setSettings(e))throw new Error("Invalid settings object");u(s,U,ss({url:{http:new URL("https://api.deepaffex.ai")},onBeforeRESTCall:()=>{var n,h;o(n=s,r,It).call(n),o(h=s,r,xt).call(h)},onAfterRESTCall:(n,h)=>{var E,c;o(E=s,r,Ft).call(E,n,h),o(c=s,r,Mt).call(c,n,h)}}));const l=n=>{var h;const{bytes:E,url:c,uncompressedSize:T,done:p}=n.detail;o(h=s,r,f).call(h,`bytesDownloaded event, ${E}, ${T}, ${c}, ${p}`,m.mediaPipe),s.on.bytesDownloaded&&s.on.bytesDownloaded(E,T,c,p)},d=n=>{var h;const{error:E,url:c}=n.detail;o(h=s,r,f).call(h,`downloadError event, ${c}, ${E}`,m.mediaPipe),s.on.error&&s.on.error(Fe.ASSET_DOWNLOAD,{url:c,error:E})};return i(s,x).addEventListener("downloadedError",d),i(s,x).addEventListener("bytesDownloaded",l),i(s,O).setVersion(s.getVersion()),i(s,R).logger&&Object.values(i(s,R).logger).some(n=>n===!0)&&i(s,O).start(),setTimeout(()=>{var n;o(n=s,r,fe).call(n,q.ASSETS_NOT_DOWNLOADED)},500),new Proxy(s,{get(n,h,E){const c=h;return typeof n[c]=="function"?n[c].bind(n):Reflect.get(n,c,E)},set(n,h,E){return console.log(`Setting property "${String(h)}" to "${E}" is not allowed`),!0}})}loadMask(e){if(i(this,_)){let s=!1;const a=i(this,_).mediaElement.querySelector("svg");a&&(s=!0,i(this,_).mediaElement.removeChild(a)),i(this,_).mediaElement.appendChild(e),s&&(i(this,_).mediaElement.style.setProperty("border","1px solid transparent"),setTimeout(()=>{i(this,_).mediaElement.removeAttribute("style")},100))}}setSettings(e){const s=_s(i(this,R),e);return s.results==="valid"?(u(this,R,s.settings),!0):!1}getVersion(){return{webSDK:ct,extractionLib:i(this,be),faceTracker:i(this,we)}}async downloadAssets(){const{assetFolder:e}=i(this,R);if(o(this,r,f).call(this,`Asset base URL ${e}`,m.sdk),o(this,r,f).call(this,"Start downloading decompressor...",m.sdk),await i(this,x).fetchAsset(i(this,B),`${e}/`,"decompress.json",!0,"gzip"),i(this,$))return o(this,r,f).call(this,"Skip downloading assets because the process is being destroyed",m.sdk),!1;if(i(this,x).canDecompress){const s=await o(this,r,Nt).call(this,e),a=await o(this,r,yt).call(this,e);if(i(this,$))return o(this,r,f).call(this,"Skip initializing workers because the process is being destroyed",m.sdk),!1;if(s&&a){await o(this,r,rt).call(this)||o(this,r,f).call(this,"Failed to initialize DFX extraction lib",m.extractionLibWasm);const d=await o(this,r,at).call(this);return d||o(this,r,f).call(this,"Failed to initialize TFJS face tracker",m.mediaPipe),i(this,$)?(i(this,K)&&await o(this,r,ye).call(this),d&&i(this,_)&&await o(this,r,Ve).call(this),!1):(o(this,r,Dt).call(this),!0)}else return!1}else return o(this,r,f).call(this,"Decompressor not ready",m.sdk),!1}setExtractionLibSettings(e=6,s=30,a=5){u(this,Q,e-1),u(this,oe,s),u(this,ce,a)}async setNextChunkAsFinal(){u(this,ke,!0),await o(this,r,A).call(this,S.SHOULD_END_MEASUREMENT_EARLY,{},!0),o(this,r,f).call(this,"Set the action for the next chunk to LAST::PROCESS",m.extractionLibWasm)}async startTracking(){i(this,_)&&(i(this,_).isExtracting||(i(this,_).setIsExtracting(!0),o(this,r,f).call(this,"Start tracking frames",m.mediaPipe),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,de)},!0),await o(this,r,Ne).call(this)))}async stopTracking(){if(i(this,_)){i(this,_).stopTracking(),await o(this,r,Pt).call(this),i(this,_).setIsExtracting(!1),o(this,r,f).call(this,"Stop extracting frames",m.mediaPipe);const{numOfFramesPresented:e,warmupFrameNumber:s,numOftrackedVideoFrames:a}=i(this,_);o(this,r,f).call(this,"Tracking metrics",m.sdk,{numOfFramesPresented:e,warmupFrameNumber:s,numOftrackedVideoFrames:a}),u(this,M,"")}}async disconnect(){if(i(this,H)&&await o(this,r,A).call(this,I.DISCONNECT,{},!0),i(this,R).metrics&&i(this,_)){const e=i(this,_).logger.mertics.debugLogs,s=i(this,O).mertics.debugLogs,a=await o(this,r,A).call(this,S.GET_LOGS,{},!0);u(this,Y,[]),u(this,me,0);const l=new Promise(n=>{u(this,ue,()=>n(void 0))});i(this,_).workers.forEach(n=>{n?.ft?.worker?.postMessage({action:N.GET_LOGS})}),await l;let d=[...s,...e,...a.payload];i(this,Y)&&i(this,Y).forEach(n=>{Array.isArray(n.logs)&&(d=d.concat(n.logs))}),d.sort((n,h)=>{const E=c=>{if(!c.timestamp)return 0;const T=c.timestamp.replace(/\[|\]/g,"");return Date.parse(T.replace(/(AM|PM)/,"").trim())+(T.includes("PM")&&!T.includes("12:")?432e5:0)};return E(n)-E(h)}),i(this,O).retrieveLogs(d)}}async destroy(){u(this,$,!0);let e=!0,s=!0;i(this,_)?.isExtracting&&await this.stopTracking(),i(this,H)&&await this.disconnect(),i(this,K)&&(e=await o(this,r,ye).call(this),o(this,r,f).call(this,"Destroyed",m.extractionLibWasm)),i(this,_)&&(s=await o(this,r,Ve).call(this),o(this,r,f).call(this,"Destroyed",m.mediaPipe)),u(this,$,!1);const a=e&&s;return a||o(this,r,f).call(this,"Failed to destroy all workers",m.sdk),a}async reset(){if(i(this,Re)!==q.ASSETS_NOT_DOWNLOADED){i(this,_)?.isExtracting&&await this.stopTracking(),await this.destroy(),u(this,O,new gt),u(this,be,{version:"",sdkId:""}),u(this,we,""),u(this,ne,0),u(this,M,""),u(this,H,!1),u(this,Q,5),u(this,oe,30),u(this,ce,5),u(this,ke,!1),u(this,ee,void 0),u(this,de,1e7),u(this,He,0),u(this,he,new Map),u(this,Ae,Promise.resolve()),u(this,D,0),u(this,ve,-1),u(this,V,-1),i(this,R).mediaElement.innerHTML="",u(this,j,-1);const e=await o(this,r,rt).call(this),s=await o(this,r,at).call(this);return e&&s}return!1}async setMediaStream(e){if(i(this,_)&&!i(this,_).isExtracting&&i(this,F)){await i(this,_).setMediaStream(e);const s=Object.fromEntries(i(this,_).workers.map((a,l)=>[`port${l+1}`,a.channel.port1]));i(this,F).worker.postMessage({action:S.SET_PORTS,payload:{numOfWorkers:i(this,le),workerPorts:s}},[...i(this,_).workers.map(a=>a.channel.port1)])}}async prepare(e,s,a,l){i(this,U).setSession({userToken:e,userRefreshToken:s});let d=!1;if(i(this,R).apiUrl)d=!0;else{const{status:E,region:c}=await o(this,r,Ut).call(this,"user");d=E==="200",i(this,R).apiUrl=`api.${c}.deepaffex.ai`}i(this,U).setUrl(`https://${i(this,R).apiUrl}`);const n=await o(this,r,$t).call(this,e,s,"user"),h=await o(this,r,Bt).call(this,a,l);return n&&h&&d}async setConstraintsConfig(e){await o(this,r,A).call(this,S.SET_CONSTRAINTS_CONFIG,{...i(this,Ke),...e&&{...i(this,R).constraintOverrides}},!0)}async startMeasurement(e=!1,s={}){if(u(this,ke,!1),u(this,M,""),u(this,j,-1),await o(this,r,Gt).call(this,s),i(this,F)&&i(this,M)!==""){await o(this,r,je).call(this),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,Q)+1},!0),await this.setConstraintsConfig(e),await o(this,r,Lt).call(this),await o(this,r,Ne).call(this);const{userToken:a}=i(this,U).getSession();a?await o(this,r,A).call(this,I.CONNECT,{token:a,measurementId:i(this,M)},!0):o(this,r,f).call(this,"User token is missing. Unable to connect.",m.webSocket)}return i(this,M)}setDemographics(e){return gs(e)?(u(this,ee,e),o(this,r,f).call(this,`Demographics updated ${JSON.stringify(e)}`,m.extractionLibWasm),!0):(o(this,r,f).call(this,`Error updating Demographics ${JSON.stringify(e)}`,m.extractionLibWasm),!1)}setObjectFit(e){return i(this,_)&&Me!==void 0&&Object.values(Me).includes(e)?(i(this,_).settings.objectFit=e,!0):!1}};U=new WeakMap,R=new WeakMap,B=new WeakMap,O=new WeakMap,x=new WeakMap,Pe=new WeakMap,We=new WeakMap,Ue=new WeakMap,$e=new WeakMap,_e=new WeakMap,ge=new WeakMap,Be=new WeakMap,be=new WeakMap,we=new WeakMap,_=new WeakMap,ne=new WeakMap,F=new WeakMap,Re=new WeakMap,M=new WeakMap,Ge=new WeakMap,H=new WeakMap,$=new WeakMap,Q=new WeakMap,oe=new WeakMap,ce=new WeakMap,ke=new WeakMap,le=new WeakMap,ee=new WeakMap,Ce=new WeakMap,Ke=new WeakMap,de=new WeakMap,He=new WeakMap,he=new WeakMap,Ae=new WeakMap,D=new WeakMap,ve=new WeakMap,V=new WeakMap,Oe=new WeakMap,K=new WeakMap,j=new WeakMap,Y=new WeakMap,me=new WeakMap,ue=new WeakMap,r=new WeakSet,At=function(){return/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1},vt=function(t){i(this,_)?.setRotate180(t)},Ot=function(){const t=o(this,r,Wt).call(this),e=o(this,r,At).call(this)&&t==="landscape-primary";o(this,r,vt).call(this,e)},yt=async function(t){o(this,r,f).call(this,"Start downloading TFJS face tracker assets...",m.mediaPipe);const e=`${t}/models/`,[s,a,l,d,n]=await Promise.all([i(this,x).fetchAsset(i(this,B),e,"detectorModel_json.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),e,"detectorModel_bin.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),e,"landmarkModel_json.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),e,"landmarkModel_bin.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),`${t}/`,`facetracker_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);return s&&a&&l&&d&&n?(o(this,r,f).call(this,"TFJS face tracker assets successfully downloaded",m.mediaPipe),u(this,Pe,s),u(this,We,a),u(this,Ue,l),u(this,$e,d),u(this,Be,n),!0):(o(this,r,f).call(this,"Failed to download TFJS face tracker assets",m.mediaPipe),!1)},Nt=async function(t){o(this,r,f).call(this,"Start downloading DFX extraction worker assets...",m.extractionLibWasm);const[e,s]=await Promise.all([i(this,x).fetchAsset(i(this,B),`${t}/extraction/`,`extraction_wasm_${this.getVersion().webSDK}.json`,!0,"brotli"),i(this,x).fetchAsset(i(this,B),`${t}/`,`extraction_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);return e&&s?(o(this,r,f).call(this,"DFX extraction worker assets successfully downloaded",m.extractionLibWasm),u(this,_e,e),u(this,ge,s),!0):(o(this,r,f).call(this,"Failed to download DFX extraction worker assets",m.extractionLibWasm),!1)},Dt=function(){if(i(this,_)){const t=e=>{o(this,r,Ot).call(this),this.on.mediaElementResize&&this.on.mediaElementResize(e)};i(this,R).mediaElement.addEventListener("mediaElementSizeChanged",t)}},ye=async function(){await o(this,r,A).call(this,S.DESTROY,{},!0);const t=i(this,F).destroy();return u(this,K,!1),t},Ve=async function(){let t=!1;return i(this,_)&&(t=await i(this,_).destroyWorkers(),u(this,_,void 0)),t},at=async function(){i(this,_)&&(await o(this,r,Ve).call(this),o(this,r,f).call(this,"Face Tracker workers destroyed",m.mediaPipe)),o(this,r,fe).call(this,q.NOT_LOADED);const t={faceTrackerCode:i(this,Be),numOfWorkers:i(this,le),mediaElement:i(this,R).mediaElement,mirrorVideo:i(this,R).mirrorVideo,metrics:i(this,R).metrics,displayMediaStream:i(this,R).displayMediaStream,isLoggingFaceTrackerWorkers:i(this,R).logger?.faceTrackerWorkers??!1,isLoggingSdk:i(this,R).logger?.sdk??!1,scaleFactor:i(this,Oe),models:{detectorJson:i(this,Pe),detectorBin:i(this,We),landmarkJson:i(this,Ue),landmarkBin:i(this,$e)}};o(this,r,fe).call(this,q.LOADING);const e=await Ds.init(t,i(this,O),{faceTrackersReady:(s,a,l,d)=>{o(this,r,f).call(this,`TFJS face tracker version ${a} loaded. Worker name: ${s} - workerId: ${l} - backend: ${d}`,m.mediaPipe),u(this,we,`${a}-${d}`),u(this,ne,i(this,ne)+1),i(this,O).setVersion(this.getVersion()),i(this,ne)===i(this,le)&&o(this,r,fe).call(this,q.LOADED)},frameAvailable:(s,a,l,d,n)=>{!d&&n?i(this,F).worker.postMessage({action:S.NEW_FRAME,payload:{frameNumber:a,frameTimestamp:s,frame:n,lastFrameNumber:l,tracked:d}},[n]):i(this,F).worker.postMessage({action:S.TRACKING_STATUS,payload:{frameNumber:a,frameTimestamp:s,lastFrameNumber:l,tracked:d}})},landmarksAvailable:(s,a,l)=>{const d=l/1e3;i(this,V)===0&&u(this,V,d),u(this,ve,d),i(this,_).numOftrackedVideoFrames+=1,s.detected||(i(this,_).starRating=0);const{starRating:n}=i(this,_),h=30,E=Math.min(i(this,ve)-i(this,V),h),c=i(this,V)>0?E/h*100:0,T={video:i(this,_).videoFpsTracker.fps.toFixed(1),faceTracker:i(this,_).faceTrackerFpsTracker.fps.toFixed(1)},p={face:s,annotations:a,starRating:n,percentCompleted:c,fps:T};this.on.facialLandmarksUpdated&&this.on.facialLandmarksUpdated(p)},scaleFactorChanged:s=>{u(this,Oe,s),i(this,_).scaleFactor=s,i(this,F).worker.postMessage({action:S.SCALE_FACTOR_CHANGED,payload:{scaleFactor:s}})},logsAvailable:(s,a)=>{i(this,Y)||u(this,Y,[]),i(this,Y).push({workerId:a,logs:s}),u(this,me,(i(this,me)||0)+1),i(this,me)===i(this,le)&&i(this,ue)&&(i(this,ue).call(this),u(this,ue,void 0))}});return i(this,$)&&e?(await e.destroyWorkers(),o(this,r,f).call(this,"Face Tracker workers destroyed",m.mediaPipe),!1):e?(u(this,_,e),!0):!1},rt=async function(){if(i(this,$))return!1;const t=new TextDecoder().decode(new Uint8Array(i(this,ge)));if(i(this,K)&&await o(this,r,ye).call(this),u(this,K,!1),u(this,F,Ye.init(t,"module","EXTRACTION_WORKER")),i(this,$))return i(this,F).destroy(),!1;const{studyCfgData:e}=i(this,U).getSession();if(e&&i(this,_e)&&i(this,ge)){i(this,F).worker.onmessage=async l=>{const{data:d}=l,{id:n,result:h}=d,{action:E,payload:c}=h,T=i(this,he).get(n);if(T||n===-1){switch(E){case S.READY:{const{sdkId:p,version:b,workerName:w}=c;u(this,be,{version:b,sdkId:p}),o(this,r,f).call(this,`DFX extraction worker WASM loaded. SDK ID: ${p} - Version: ${b} - Worker Name: ${w}`,m.extractionLibWasm),await o(this,r,A).call(this,S.SET_MODE,{value:"discrete"},!0),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,de)},!0),await o(this,r,A).call(this,S.SET_TARGET_FPS,{value:i(this,oe)},!0),await o(this,r,A).call(this,S.SET_CHUNK_DURATION_SECONDS,{value:i(this,ce)},!0),await o(this,r,A).call(this,S.SET_FRAME_ORDER,{value:bt.RGBA},!0),await o(this,r,A).call(this,S.GET_CONSTRAINTS_CONFIG,{},!0),u(this,Ke,i(this,Ce));break}case S.SET_MODE:{c&&o(this,r,f).call(this,`Set mode to ${c.mode}`,m.extractionLibWasm);break}case S.SET_NUMBER_OF_CHUNKS:{c&&o(this,r,f).call(this,`Set number of chunks to ${h.number}`,m.extractionLibWasm);break}case S.SET_TARGET_FPS:{c&&o(this,r,f).call(this,`Set target FPS to ${i(this,oe)}`,m.extractionLibWasm);break}case S.SET_CHUNK_DURATION_SECONDS:{c&&o(this,r,f).call(this,`Set chunk duration to ${i(this,ce)} Seconds`,m.extractionLibWasm);break}case S.SET_FRAME_ORDER:{c&&o(this,r,f).call(this,"Set channel order RGBA",m.extractionLibWasm);break}case S.GET_CONSTRAINTS_CONFIG:{c&&(u(this,Ce,c),o(this,r,f).call(this,`Get constraints ${JSON.stringify(c)}`,m.extractionLibWasm));break}case S.SET_CONSTRAINTS_CONFIG:{c&&(u(this,Ce,c),o(this,r,f).call(this,`Set constraints ${JSON.stringify(c)}`,m.extractionLibWasm));break}case S.SET_FACE_ATTRIBUTE:{const{success:p,faceId:b,attribute:w,value:C}=c;p&&o(this,r,f).call(this,`Set face attribute: faceId: ${b}, attribute: ${w}, value: ${C}`,m.extractionLibWasm);break}case S.RESET_COLLECTION:{c&&o(this,r,f).call(this,"Reset collection",m.extractionLibWasm);break}case S.CANCEL_COLLECTION:{c&&o(this,r,f).call(this,"Collecttion cancelled",m.extractionLibWasm);break}case S.START_COLLECTION:{c&&o(this,r,f).call(this,`Collector started - state: ${c}`,m.extractionLibWasm);break}case S.SET_PORTS:{c&&o(this,r,f).call(this,"Ports set",m.extractionLibWasm);break}case S.COLLECTOR_ERROR:{if(c){const{error:p,frameNumber:b}=c;o(this,r,f).call(this,`Collector error on frame ${b}: ${p}`,m.extractionLibWasm),this.on.error&&this.on.error(Fe.COLLECTOR,c),i(this,H)?(o(this,r,f).call(this,"Measurement in progress, Stopping tracking due to collector error",m.extractionLibWasm),await this.stopTracking()):(o(this,r,f).call(this,"No active measurement, resetting and starting collection",m.extractionLibWasm),await o(this,r,je).call(this),await o(this,r,Ne).call(this))}break}case S.STAR_RATING:{i(this,_).starRating=c.rating;break}case S.ALL_FACE_TRACKERS_WARMED_UP:{const{frameNumber:p}=h;i(this,_).warmupFrameNumber=p,o(this,r,f).call(this,"All face tracker workers are warmed up.",m.mediaPipe),o(this,r,fe).call(this,q.READY);break}case S.CONSTRAINTS_UPDATED:{const{feedback:p,status:b}=c;this.on.constraintsUpdated&&this.on.constraintsUpdated(p,b);break}case S.SHOULD_END_MEASUREMENT_EARLY:{const{currentFinalChunkNumber:p,currentResultsOrder:b,newFinalChunkNumber:w}=h;o(this,r,f).call(this,`Request the end measurement early. Current final chunk number: ${p}, Current results order: ${b}, New final chunk number: ${w}`,m.extractionLibWasm);break}case S.GET_LOGS:break;case S.DESTROY:break;case I.CONNECT:{u(this,H,!0),u(this,V,0),o(this,r,f).call(this,c?"Connected":"Connection error",m.webSocket);break}case I.LOGIN_WITH_TOKEN_SUCCESS:{o(this,r,f).call(this,"Successfully logged in with token",m.webSocket);break}case I.SUBSCRIBED_TO_RESULTS:{o(this,r,f).call(this,"Subscribed to the results",m.webSocket);break}case I.CHUNK_SENT:{o(this,r,f).call(this,`Chunk sent ${JSON.stringify(c)}`,m.webSocket),this.on.chunkSent&&this.on.chunkSent(c);break}case I.DISCONNECT:{u(this,H,!1),o(this,r,f).call(this,"Disconnect",m.webSocket);break}case I.DISCONNECTED:{o(this,r,f).call(this,`Disconnected! - code: ${c.code}, reason: ${c.reason}, wasClean: ${c.wasClean}`,m.webSocket),this.on.error&&this.on.error(Fe.WEB_SOCKET,c);break}case I.CHUNK_ACKNOWLEDGED:{o(this,r,f).call(this,`Chunk number ${c.chunkOrder} received by the server!`,m.webSocket),i(this,Q)===c.chunkOrder&&await this.stopTracking();break}case I.RESULTS_RECEIVED:{const{MeasurementID:p,MeasurementDataID:b}=c;p?u(this,j,parseInt(b.split(":")[1],10)):u(this,j,i(this,j)+1),this.on.resultsReceived&&this.on.resultsReceived(c),o(this,r,f).call(this,`Results received: ${JSON.stringify(c)}`,m.webSocket),i(this,j)===i(this,Q)&&(await o(this,r,A).call(this,I.DISCONNECT,{},!0),await o(this,r,je).call(this),await o(this,r,Ne).call(this));break}case I.NETWORK_DELAY:{const{delay:p,description:b,actionId:w}=c;o(this,r,f).call(this,`Round-trip delay for ${b} call with Action ID ${w} was ${p.toFixed(2)} ms`,m.webSocket,{delay:p,actionId:w,description:b});break}case I.ERROR:{o(this,r,f).call(this,"Error",m.webSocket),this.on.error&&this.on.error(Fe.WEB_SOCKET,c);break}}T&&(T.resolve(h),i(this,he).delete(n))}};const a=(await o(this,r,A).call(this,S.INIT,{wasm:i(this,_e),studyConfigData:e,isLogging:i(this,R).logger?.extractionWorker||!1,metrics:i(this,R).metrics||!1,apiUrl:i(this,R).apiUrl,scaleFactor:i(this,Oe)},!0)).action===S.READY;return u(this,K,a),i(this,K)&&i(this,$)?(await o(this,r,ye).call(this),!1):a}else return!1},Lt=async function(){if(i(this,_)){if(!i(this,ee)){o(this,r,f).call(this,"No demographics to set",m.extractionLibWasm);return}const t="1",{age:e,height:s,weight:a,sex:l,smoking:d,bloodPressureMedication:n,diabetes:h}=i(this,ee),E=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.SEX_ASSIGNED_AT_BIRTH,value:l},!0),c=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.AGE_YEARS,value:e},!0),T=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.HEIGHT_CM,value:s},!0),p=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.WEIGHT_KG,value:a},!0),b=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.SMOKER,value:d},!0),w=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.BLOOD_PRESSURE_MEDICATION,value:n},!0),C=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.DIABETES,value:h},!0);o(this,r,f).call(this,`Set demographics for Face ID ${t}, ${JSON.stringify(i(this,ee))}`,m.extractionLibWasm);const v={SEX_ASSIGNED_AT_BIRTH:{success:E.payload.success},AGE_YEARS:{success:c.payload.success},HEIGHT_CM:{success:T.payload.success},WEIGHT_KG:{success:p.payload.success},SMOKER:{success:b.payload.success},BLOOD_PRESSURE_MEDICATION:{success:w.payload.success},DIABETES:{success:C.payload.success}};o(this,r,f).call(this,`Validation results for demographics for Face ID ${t}, ${JSON.stringify(v)}`,m.extractionLibWasm)}},It=function(){},xt=function(){const t=new Date().toISOString();Tt(t)&&(o(this,r,f).call(this,`Action ID: ${i(this,D)}`,m.beforeRESTCall),this.on.beforeRESTCall&&this.on.beforeRESTCall(t,i(this,D)))},Ft=function(t,e){},Mt=function(t,e){const s=new Date().toISOString();Tt(s)&&(o(this,r,f).call(this,`Action ID: ${i(this,D)}, HTTP status code: ${t}, error: ${JSON.stringify(e)}`,m.afterRESTCall),this.on.afterRESTCall&&this.on.afterRESTCall(s,i(this,D),t,e))},Pt=async function(){await o(this,r,A).call(this,S.CANCEL_COLLECTION,{},!0)},Ne=async function(){await o(this,r,A).call(this,S.START_COLLECTION,{},!0)},je=async function(){await o(this,r,A).call(this,S.RESET_COLLECTION,{},!0),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,de)},!0)},f=function(t,e,s){i(this,R).metrics&&i(this,O).log(t,e,"",!0,s),i(this,R).logger?.mediaPipe&&e===m.mediaPipe&&i(this,O).info(t,e),i(this,R).logger?.beforeRESTCall&&e===m.beforeRESTCall&&i(this,O).info(t,e),i(this,R).logger?.afterRESTCall&&e===m.afterRESTCall&&i(this,O).info(t,e),i(this,R).logger?.extractionLibWasm&&e===m.extractionLibWasm&&i(this,O).info(t,e),i(this,R).logger?.apiClient&&e===m.apiClient&&i(this,O).info(t,e),i(this,R).logger?.webSocket&&e===m.webSocket&&i(this,O).info(t,e),i(this,R).logger?.sdk&&e===m.sdk&&i(this,O).info(t,e)},Wt=function(){return screen.orientation.type},Ut=async function(t){u(this,D,0);const e=performance.now(),s=await i(this,U).http.auths.validate(t),a=performance.now()-e,{status:l,body:d}=s;if(o(this,r,f).call(this,l==="200"?"Successfully validated the Token":`Failed to validate token. Status: ${l}`,m.apiClient,{delay:a,actionId:i(this,D),description:"Validate Token"}),l==="200"){const{Region:n}=d;return{region:n,status:l}}else return{status:l,region:""}},$t=async function(t,e,s){u(this,D,2304);const a=performance.now(),l=await i(this,U).http.auths.renew({Token:t,RefreshToken:e},s),d=performance.now()-a,{status:n}=l;return o(this,r,f).call(this,n==="200"?"Successfully refreshed the Token":`Failed to refresh token. Status: ${n}`,m.apiClient,{delay:d,actionId:i(this,D),description:"Refresh Token"}),n==="200"},Bt=async function(t,e){u(this,D,806);const s=performance.now();u(this,Ge,t);const a=await i(this,U).http.studies.retrieveSdkConfigData({StudyID:t,...e&&{sdkId:e}},"user"),l=performance.now()-s,{status:d}=a;return o(this,r,f).call(this,d==="200"?"Retrieve SDK Config Data - success":"Retrieve SDK Config Data - failure",m.apiClient,{delay:l,actionId:i(this,D),description:"Retrieve SDK Config Data"}),d==="200"},Gt=async function(t){o(this,r,f).call(this,"Get Measurement ID",m.apiClient),u(this,D,504);const e=performance.now(),s={StudyID:i(this,Ge),Resolution:100};t.partnerId&&(s.PartnerID=t.partnerId),t.userProfileId&&(s.UserProfileID=t.userProfileId);const a=await i(this,U).http.measurements.create(s,"user"),l=performance.now()-e,{status:d,body:n}=a;let h="";d==="200"?(u(this,M,n.ID),h=`Successfully obtained measurement ID: ${i(this,M)}`):(u(this,M,""),h=`Failed to obtain measurement ID. Status: ${d}`),o(this,r,f).call(this,h,m.apiClient,{delay:l,actionId:i(this,D),measurementId:i(this,M),description:"Get Measurement ID"})},fe=function(t){u(this,Re,t),o(this,r,f).call(this,`Face tracker state changed: ${t}`,m.mediaPipe),this.on.faceTrackerStateChanged&&this.on.faceTrackerStateChanged(i(this,Re))},A=function(t,e,s=!1){return new Promise(a=>{const l=xs(this,He)._++;i(this,he).set(l,{resolve:a,action:t});const d=()=>i(this,F).worker.postMessage({id:l,action:t,payload:e});s?u(this,Ae,i(this,Ae).then(d).catch(n=>console.error(n))):d()})},Ct(Fs,"VERSION",ct);const Ms={DISTANCE:{OK:"OK",TOO_CLOSE:"TOO_CLOSE",TOO_FAR:"TOO_FAR"},DIRECTION:{OK:"OK",TURN_LEFT:"TURN_LEFT",TURN_RIGHT:"TURN_RIGHT",TURN_UP:"TURN_UP",TURN_DOWN:"TURN_DOWN"},ROLL:{OK:"OK",TILT_LEFT:"TILT_LEFT",TILT_RIGHT:"TILT_RIGHT"},MOVEMENT:{OK:"OK",TOO_MUCH_MOVEMENT:"TOO_MUCH_MOVEMENT"},CENTER:{OK:"OK",NOT_CENTERED:"NOT_CENTERED"}};class Ps{static VERSION=jt;#e=document.createElement("div");#s=document.createElement("div");#i=!1;#a=!1;on={results:null,error:null,event:null};constructor(){this.#e.style.height="100%"}async init(e){const{container:s,appPath:a,settings:l,profile:d,config:n,language:h,apiUrl:E}=e;return this.#s=s,new Promise((c,T)=>{const p=s.attachShadow({mode:"open"}),b="app",w=document.createElement("link");w.rel="stylesheet",w.href=`${a}/stylex.css`,p.appendChild(w);const C=document.createElement("link");C.rel="stylesheet",C.href=`${a}/${b}.css`,p.appendChild(C);const v=W=>{this.on.results&&this.on.results({...W.detail})},P=W=>{this.on.error&&this.on.error({...W.detail})},z=W=>{this.on.event&&this.on.event({...W.detail}),W.detail.event===ze.APP_LOADED.event&&(this.#i=!0,c()),W.detail.event===ze.ASSETS_DOWNLOADED.event&&(this.#a=!0)};this.#e.addEventListener(G.RESULTS,v),this.#e.addEventListener(G.ERROR,P),this.#e.addEventListener(G.APPEVENT,z),p.appendChild(this.#e);const te=document.createElement("script");te.type="module",te.src=`${a}/${b}.mjs`,te.onload=()=>{import(/* webpackIgnore: true */ te.src).then(W=>{W.app.init(this.#e,a,l,d,E,n,h)}).catch(W=>{T(new Error("Failed to initialize Measurement Embedded React app: "+W.message))})},te.onerror=()=>{T(new Error("Failed to load the measurement embedded app script"))},p.appendChild(te)})}#t(){if(!this.#i)throw new Error("MeasurementEmbeddedApp is not initialized. Call init() before using this method.")}#r(){if(!this.#a)throw new Error('Assets not downloaded and SDK not initialized. Please wait for the "ASSETS_DOWNLOADED" event before calling this method.')}async destroy(){return this.#t(),this.#r(),new Promise(e=>{const s=l=>{if(this.#e.removeEventListener(G.DESTROYED,s),this.#s){const d=this.#s.cloneNode(!1);this.#s.replaceWith(d)}e(l.detail.destroyed)};this.#e.addEventListener(G.DESTROYED,s);const a=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.DESTROY,data:{}}});this.#e.dispatchEvent(a)})}setTheme(e){this.#t();const s=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.SET_THEME,data:{theme:e}}});this.#e.dispatchEvent(s)}setLanguage(e){this.#t();const s=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.SET_LANGUAGE,data:{language:e}}});this.#e.dispatchEvent(s)}setAppSettings(e,s,a,l={}){this.#t();const d=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.SET_APP_SETTINGS,data:{token:e,refreshToken:s,studyId:a,measurementOptions:l}}});this.#e.dispatchEvent(d)}async cancel(e){return this.#t(),this.#r(),new Promise(s=>{const a=d=>{this.#e.removeEventListener(G.CANCELLED,a),s(d.detail.reset)};this.#e.addEventListener(G.CANCELLED,a);const l=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.CANCEL,data:{reset:e}}});this.#e.dispatchEvent(l)})}getLogs(){return this.#t(),new Promise(e=>{const s=l=>{this.#e.removeEventListener(G.LOGS,s),e(l.detail.logs)};this.#e.addEventListener(G.LOGS,s);const a=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.GET_LOGS,data:{}}});this.#e.dispatchEvent(a)})}}export{ot as ErrorCodes,y as appEventSeverity,ze as appEvents,Ms as constraintCodes,Ps as default,Cs as faceAttributeValue,nt as logCategory};
739
+ `}openLogInNewWindow(){const e=this.generateHTMLTable(),s=new Blob([e],{type:"text/html"}),a=URL.createObjectURL(s);window.open(a,"_blank")}}var ms=Object.defineProperty,us=(t,e,s)=>e in t?ms(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xe=(t,e,s)=>us(t,typeof e!="symbol"?e+"":e,s);class Ye{constructor(e,s){xe(this,"workerUrl"),xe(this,"worker"),this.worker=e,this.workerUrl=s}static init(e,s,a){const l=new Blob([e],{type:"application/javascript"}),d=URL.createObjectURL(l),n=a||`WORKER${String(new Date().getTime())}`,h=new Worker(new URL(d,import.meta.url),{name:n,type:s});return new Ye(h,d)}destroy(){return this.worker?(this.worker.terminate(),URL.revokeObjectURL(this.workerUrl),this.worker=void 0,!0):!1}}const fs=(t,e,s,a)=>{const l=t/e,d=s/a;let n=0,h=0;l>d?(n=t,h=t/d):(h=e,n=e*d);const E=(t-n)/2,c=(e-h)/2;return{width:n||0,height:h||0,offsetX:E||0,offsetY:c||0}},Es=(t,e,s,a)=>{const l=(t-s)/2,d=(e-a)/2;return{width:s||0,height:a||0,offsetX:l||0,offsetY:d||0}},ps=(t,e,s,a)=>{const l=t/e,d=s/a;let n=0,h=0;l>d?(h=e,n=e*d):(n=t,h=t/d);const E=(t-n)/2,c=(e-h)/2;return{width:n||0,height:h||0,offsetX:E||0,offsetY:c||0}},Ts=(t,e)=>{switch(t){case"none":return Es(...e);case"cover":return fs(...e);case"contain":default:return ps(...e)}},Tt=t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(t),Ss=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"),_s=(t,e)=>{const s={...t};if(e.logger)if(Ss(e.logger))s.logger={...s.logger,...e.logger};else return{results:"invalid"};if(e.apiUrl!==void 0)if(typeof e.apiUrl=="string")s.apiUrl=e.apiUrl;else return{results:"invalid"};if(e.metrics!==void 0)if(typeof e.metrics=="boolean")s.metrics=e.metrics;else return{results:"invalid"};if(e.mirrorVideo!==void 0)if(typeof e.mirrorVideo=="boolean")s.mirrorVideo=e.mirrorVideo;else return{results:"invalid"};if(e.displayMediaStream!==void 0)if(typeof e.displayMediaStream=="boolean")s.displayMediaStream=e.displayMediaStream;else return{results:"invalid"};if(e.assetFolder!==void 0)if(typeof e.assetFolder=="string")s.assetFolder=e.assetFolder;else return{results:"invalid"};if(e.mediaElement!==void 0)if(e.mediaElement instanceof HTMLDivElement)s.mediaElement=e.mediaElement;else return{results:"invalid"};if(e.constraintOverrides!==void 0){let a=function(n,h){if(!(n in d))return!1;const E=d[n];return typeof h===E};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,h])=>[n,typeof h]));for(const n in e.constraintOverrides){const h=e.constraintOverrides[n];if(!a(n,h))return{results:"invalid"}}s.constraintOverrides=e.constraintOverrides}return{results:"valid",settings:s}},gs=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 bs=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 St{constructor(e=1e3){xe(this,"timestamps",[]),xe(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,s=this.timestamps.at(-1)-this.timestamps[0]||1;return e/s*1e3}get frameCount(){return this.timestamps.length}reset(){this.timestamps=[]}}var ws=Object.defineProperty,Rs=(t,e,s)=>e in t?ws(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_t=(t,e,s)=>Rs(t,typeof e!="symbol"?e+"":e,s);const ks=()=>{const t=new Date,e=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0"),a=t.getFullYear();let l=t.getHours();const d=t.getMinutes().toString().padStart(2,"0"),n=t.getSeconds().toString().padStart(2,"0"),h=t.getMilliseconds().toString().padStart(3,"0"),E=l>=12?"PM":"AM";return l=l%12||12,`[${e}/${s}/${a}, ${l}:${d}:${n}.${h} ${E}]`};class gt{constructor(){_t(this,"mertics",new hs),_t(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""})}retrieveLogs(e){this.mertics.debugLogs=e,this.mertics.openLogInNewWindow(),this.mertics.debugLogs=[]}setVersion(e){this.version=e,this.mertics.version=e}log(e,s,a,l=!1,d={}){const n=ks();if(l)this.mertics.appendLog({thread:"Main",timestamp:n,category:s,message:e,meta:d});else{const h=`[${s}]`,E=" ",c=e,T=`color:${a}; font-weight:800;`,p=`color:${bs(s)}; font-weight:700;`;console.log("%c%s%c%s%c%s%c%s",T,n,p,h,"background:inherit;",E,"font-style: italic;",c)}}info(e,s){this.log(e,s,"blue")}warn(e,s){this.log(e,s,"orange")}error(e,s){this.log(e,s,"red")}debug(e,s){this.log(e,s,"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 Cs={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},X={SEX_ASSIGNED_AT_BIRTH:1,AGE_YEARS:2,HEIGHT_CM:3,WEIGHT_KG:4,SMOKER:5,BLOOD_PRESSURE_MEDICATION:7,DIABETES:8};var bt=(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))(bt||{});const q={ASSETS_NOT_DOWNLOADED:"ASSETS_NOT_DOWNLOADED",NOT_LOADED:"NOT_LOADED",LOADING:"LOADING",LOADED:"LOADED",READY:"READY"},Fe={COLLECTOR:"COLLECTOR",ASSET_DOWNLOAD:"ASSET_DOWNLOAD",WEB_SOCKET:"WEB_SOCKET"},Me={CONTAIN:"contain",COVER:"cover",NONE:"none"};var N=(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.FACE_TRACKER_INIT_ERROR="FACE_TRACKER_INIT_ERROR",t.SET_ROTATE_180="SET_ROTATE_180",t.GET_LOGS="GET_LOGS",t))(N||{}),As=Object.defineProperty,wt=t=>{throw TypeError(t)},vs=(t,e,s)=>e in t?As(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,k=(t,e,s)=>vs(t,typeof e!="symbol"?e+"":e,s),et=(t,e,s)=>e.has(t)||wt("Cannot "+s),Te=(t,e,s)=>(et(t,e,"read from private field"),e.get(t)),tt=(t,e,s)=>e.has(t)?wt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Se=(t,e,s,a)=>(et(t,e,"write to private field"),e.set(t,s),s),Os=(t,e,s)=>(et(t,e,"access private method"),s),ys=(t,e,s,a)=>({set _(l){Se(t,e,l)},get _(){return Te(t,e)}}),Z,re,st,Rt;const Ns=class Ht{constructor(e,s,a,l){tt(this,st),k(this,"logger"),k(this,"mediaElement"),k(this,"numOfFramesPresented",0),k(this,"workers",[]),k(this,"numOftrackedVideoFrames",0),k(this,"warmupFrameNumber",0),k(this,"videoCallbackId",0),k(this,"numOfWorkers",4),k(this,"isLoggingFaceTrackerWorkers",!1),k(this,"isLoggingSdk",!1),k(this,"workerIndex",0),k(this,"metrics",!1),k(this,"videoFpsTracker",new St(1e3)),k(this,"faceTrackerFpsTracker",new St(1e3)),k(this,"videoElementSize",{width:0,height:0,offsetX:0,offsetY:0}),k(this,"videoElement",document.createElement("video")),k(this,"frameWidth",0),k(this,"frameHeight",0),k(this,"mirrorVideo",!0),k(this,"settings",{faceTrackerWidth:0,faceTrackerHeight:0,displayMediaStream:!0,objectFit:Me.COVER}),k(this,"isExtracting",!1),k(this,"starRating",0),k(this,"scaleFactor",1),k(this,"warmupIndex",0),k(this,"warmingUp",!0),k(this,"ftWorkerIndex",0),k(this,"lastFrameNumber",-1),k(this,"rotate180",!1),tt(this,Z,null),tt(this,re,0),k(this,"on");const{mediaElement:d,mirrorVideo:n,numOfWorkers:h,isLoggingFaceTrackerWorkers:E,isLoggingSdk:c,metrics:T,displayMediaStream:p}=s;this.on=l,this.numOfWorkers=h,this.isLoggingFaceTrackerWorkers=E,this.isLoggingSdk=c,this.metrics=T,this.logger=a,this.settings.displayMediaStream=p,this.mirrorVideo=n,this.mediaElement=d,this.videoFrameCallback=this.videoFrameCallback.bind(this),this.workers=e,this.scaleFactor=s.scaleFactor,this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.preload="auto"}static async init(e,s,a){const{numOfWorkers:l,faceTrackerCode:d}=e,n=[],h=new TextDecoder().decode(new Uint8Array(d));if(l>0)for(let c=1;c<=l;c+=1){const T=Ye.init(h,"module",`FACE_TRACKER_WORKER_${c-1}`);n.push({ft:T,channel:new MessageChannel,isBusy:!1})}const E=new Ht(n,e,s,a);return l>0&&!await E.initWorkerOnMessage(e.models)?null:E}async initWorkerOnMessage(e){const s=window.matchMedia("(orientation: portrait)").matches,a=s?360:640,l=s?640:360,d=this.workers.map((n,h)=>new Promise((E,c)=>{let T=!1;n.ft.worker.onmessage=p=>{const{action:b,payload:w}=p.data;switch(b){case N.INIT_TFJS:break;case N.READY:{const{workerName:C,version:v,workerId:P,backend:z}=w;T||(T=!0,E()),this.on.faceTrackersReady&&this.on.faceTrackersReady(C,v,P,z);break}case N.FACE_TRACKER_INIT_ERROR:{const{error:C}=w;T||(T=!0,c(new Error(`Worker initialization failed: ${C}`)));break}case N.LANDMARKS:{this.faceTrackerFpsTracker.tick(),n.isBusy=!1,this.warmingUp&&this.warmupIndex++;const{face:C,annotations:v,frameTimestamp:P}=w;this.on.landmarksAvailable&&this.on.landmarksAvailable(C,v,P);break}case N.DESTROY:{const{workerId:C}=w;this.workers[C]&&this.workers[C].ft.destroy(),Te(this,Z)&&(ys(this,re)._++,Te(this,re)>=this.workers.length&&(Te(this,Z).call(this,!0),Se(this,Z,null),Se(this,re,0),this.workers=[]));break}case N.GET_LOGS:{const{logs:C,workerId:v}=w;this.on.logsAvailable&&this.on.logsAvailable(C,v);break}}},n.ft.worker.postMessage({action:N.INIT_TFJS,payload:{width:a,height:l,models:e,scaleFactor:this.scaleFactor,workerId:h,isLogging:this.isLoggingFaceTrackerWorkers,metrics:this.metrics}}),n.ft.worker.postMessage({action:N.SET_PORT,payload:{port:n.channel.port2}},[n.channel.port2])}));try{return await Promise.all(d),!0}catch{return await this.destroyWorkers(),!1}}getMediaElement(){return this.mediaElement}setIsExtracting(e){this.isExtracting=e}destroyWorkers(){return Te(this,Z)!==null?Promise.resolve(!1):new Promise(e=>{setTimeout(async()=>{if(this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.workers.length===0){e(!0);return}Se(this,Z,e),Se(this,re,0),this.workers.forEach(s=>{s?.ft?.worker?.postMessage({action:N.DESTROY})})},200)})}createMediaElements(){this.videoElement.addEventListener("ended",async()=>{this.destroyWorkers()});const e=document.createElement("div"),s=this.settings.displayMediaStream?this.videoElement:e,a="white";this.mediaElement.appendChild(s),s.style.width="100%",s.style.height="100%",s.style.boxSizing="border-box",this.settings.displayMediaStream&&(s.style.border=`1px solid ${a}`),s.style.objectFit=this.settings.objectFit,s.style.transform=`scale(${this.mirrorVideo?"-1":"1"},1)`,this.settings.displayMediaStream||(s.style.height=`${this.frameHeight}px`,s.style.width=`${this.frameWidth}px`),new ResizeObserver(d=>{const{contentRect:n,target:h}=d[0],{width:E,height:c}=n,{x:T,y:p}=h.getBoundingClientRect(),{faceTrackerWidth:b,faceTrackerHeight:w}=this.settings;this.videoElementSize=Ts(this.settings.objectFit,[E,c,this.frameWidth,this.frameHeight]);const{width:C,height:v}=this.videoElementSize;if(!this.settings.displayMediaStream){const P=this.settings.objectFit===Me.NONE;s.style.height=`${Math.trunc(P?v:c)}px`,s.style.width=`${Math.trunc(P?C:E)}px`}this.mediaElement.dispatchEvent(new CustomEvent("mediaElementSizeChanged",{detail:{mediaElementSize:{width:E,height:c,x:T,y:p},videoElementSize:this.videoElementSize,frameInfo:{mediaStreamWidth:this.frameWidth,mediaStreamHeight:this.frameHeight,faceTrackerWidth:b,faceTrackerHeight:w},isPortrait:c>E,aspectRatio:E/c}}))}).observe(this.mediaElement)}log(e,s,a){this.isLoggingSdk&&this.logger.info(e,s),this.metrics&&this.logger.log(e,s,"",!0,a)}videoFrameCallback(e,s){const{presentedFrames:a,captureTime:l,expectedDisplayTime:d,mediaTime:n}=s;this.videoFpsTracker.tick();const h=l===void 0?d:l;this.numOfFramesPresented=a;const E=`Number of frames presented: ${this.numOfFramesPresented} - time: ${h}`;let c=0;if(n&&n>0?c=n*1e3:l&&l>0?c=l>1e6?l-performance.timeOrigin:l:c=e,this.log(E,m.sdk,{captureTime:h,presentedFrames:a}),this.warmingUp)if(this.warmupIndex>=this.numOfWorkers)this.warmingUp=!1;else{const T=this.workers[this.warmupIndex];if(!T.isBusy){T.isBusy=!0;const p=new VideoFrame(this.videoElement,{timestamp:c});T.ft.worker.postMessage({action:N.TRACK,payload:{frame:p,frameTimestamp:c,frameNumber:this.numOfFramesPresented}},[p])}}if(!this.warmingUp){const T=new VideoFrame(this.videoElement,{timestamp:c});let p=!1;for(let b=0;b<this.numOfWorkers;b++){this.ftWorkerIndex=(this.ftWorkerIndex+1)%this.numOfWorkers;const w=this.workers[this.ftWorkerIndex];if(w&&!w.isBusy){w.isBusy=!0,this.on.frameAvailable(c,this.numOfFramesPresented,this.lastFrameNumber,!0),w.ft.worker.postMessage({action:N.TRACK,payload:{frame:T,frameTimestamp:c,frameNumber:this.numOfFramesPresented}},[T]),p=!0;break}}p||this.on.frameAvailable(c,this.numOfFramesPresented,this.lastFrameNumber,!1,T)}this.lastFrameNumber=this.numOfFramesPresented,this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback)}setFaceTrackerMediaStreamResolution(e,s){(e<=360||s<=360)&&(this.scaleFactor=1),this.settings.faceTrackerWidth=e*this.scaleFactor,this.settings.faceTrackerHeight=s*this.scaleFactor,this.workers.forEach(a=>a.ft.worker.postMessage({action:N.SCALE_FACTOR_CHANGED,payload:{scaleFactor:this.scaleFactor}})),this.on.scaleFactorChanged&&this.on.scaleFactorChanged(this.scaleFactor)}setRotate180(e){this.rotate180=e,this.workers.forEach(s=>s.ft.worker.postMessage({action:N.SET_ROTATE_180,payload:{rotate180:e}}))}async setMediaStream(e){if(e instanceof MediaStream)try{const s=await Os(this,st,Rt).call(this,e,this.videoElement);await this.videoElement.play(),this.settings.displayMediaStream||(this.videoElement.style.visibility="none");const a=this.videoElement.videoWidth||s.width||1,l=this.videoElement.videoHeight||s.height||1;return this.setFaceTrackerMediaStreamResolution(a,l),this.frameWidth=a,this.frameHeight=l,this.log(`Face tracker resolution: ${this.settings.faceTrackerWidth} x ${this.settings.faceTrackerHeight} pixels. Video resolution: ${this.frameWidth} x ${this.frameHeight} pixels`,m.sdk,{ftWidth:this.settings.faceTrackerWidth,ftHeight:this.settings.faceTrackerHeight,frameWidth:this.frameWidth,frameHeight:this.frameHeight}),this.createMediaElements(),this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback),!0}catch(s){return console.log("Error applying face tracker video track constraints",s),!1}return!1}stopTracking(){this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.videoElement.pause(),this.videoElement.srcObject=null}};Z=new WeakMap,re=new WeakMap,st=new WeakSet,Rt=async function(t,e){e.srcObject=t,await new Promise(a=>e.onloadedmetadata=a);const[s]=t.getVideoTracks();return s.getSettings()};let Ds=Ns;var S=(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.DESTROY="DESTROY",t))(S||{}),I=(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))(I||{}),Ls=Object.defineProperty,kt=t=>{throw TypeError(t)},Is=(t,e,s)=>e in t?Ls(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ct=(t,e,s)=>Is(t,typeof e!="symbol"?e+"":e,s),it=(t,e,s)=>e.has(t)||kt("Cannot "+s),i=(t,e,s)=>(it(t,e,"read from private field"),s?s.call(t):e.get(t)),g=(t,e,s)=>e.has(t)?kt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),u=(t,e,s,a)=>(it(t,e,"write to private field"),e.set(t,s),s),o=(t,e,s)=>(it(t,e,"access private method"),s),xs=(t,e,s,a)=>({set _(l){u(t,e,l)},get _(){return i(t,e,a)}}),U,R,B,O,x,Pe,We,Ue,$e,_e,ge,Be,be,we,_,ne,F,Re,M,Ge,H,$,Q,oe,ce,ke,le,ee,Ce,Ke,de,He,he,Ae,D,ve,V,Oe,K,j,Y,me,ue,r,At,vt,Ot,yt,Nt,Dt,ye,Ve,at,rt,Lt,It,xt,Ft,Mt,Pt,Ne,je,f,Wt,Ut,$t,Bt,Gt,fe,A;const Kt=Symbol("instance_creation_key"),Fs=class Vt{constructor(e){if(g(this,r),g(this,U),g(this,R,{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:{}}),g(this,B,[{file:"decompress.json",uncompressedSize:89469},{file:"extraction_worker_0.1.0-beta.15_js.json",uncompressedSize:47465},{file:"facetracker_worker_0.1.0-beta.15_js.json",uncompressedSize:307098},{file:"extraction_wasm_0.1.0-beta.15.json",uncompressedSize:2142219},{file:"detectorModel_json.json",uncompressedSize:4640},{file:"detectorModel_bin.json",uncompressedSize:242046},{file:"landmarkModel_json.json",uncompressedSize:5036},{file:"landmarkModel_bin.json",uncompressedSize:1704814}]),g(this,O,new gt),g(this,x,cs.init()),g(this,Pe),g(this,We),g(this,Ue),g(this,$e),g(this,_e),g(this,ge),g(this,Be),g(this,be,{version:"",sdkId:""}),g(this,we,""),g(this,_),g(this,ne,0),g(this,F),g(this,Re,q.ASSETS_NOT_DOWNLOADED),g(this,M,""),g(this,Ge,""),g(this,H,!1),g(this,$,!1),g(this,Q,5),g(this,oe,30),g(this,ce,5),g(this,ke,!1),g(this,le,4),g(this,ee),g(this,Ce),g(this,Ke),g(this,de,1e7),g(this,He,0),g(this,he,new Map),g(this,Ae,Promise.resolve()),g(this,D,0),g(this,ve,-1),g(this,V,-1),g(this,Oe,.5),g(this,K,!1),g(this,j,-1),g(this,Y),g(this,me),g(this,ue),Ct(this,"on",{beforeRESTCall:null,afterRESTCall:null,bytesDownloaded:null,faceTrackerStateChanged:null,resultsReceived:null,constraintsUpdated:null,mediaElementResize:null,facialLandmarksUpdated:null,chunkSent:null,error:null}),e!==Kt)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 s=new Vt(Kt);if(!s.setSettings(e))throw new Error("Invalid settings object");u(s,U,ss({url:{http:new URL("https://api.deepaffex.ai")},onBeforeRESTCall:()=>{var n,h;o(n=s,r,It).call(n),o(h=s,r,xt).call(h)},onAfterRESTCall:(n,h)=>{var E,c;o(E=s,r,Ft).call(E,n,h),o(c=s,r,Mt).call(c,n,h)}}));const l=n=>{var h;const{bytes:E,url:c,uncompressedSize:T,done:p}=n.detail;o(h=s,r,f).call(h,`bytesDownloaded event, ${E}, ${T}, ${c}, ${p}`,m.mediaPipe),s.on.bytesDownloaded&&s.on.bytesDownloaded(E,T,c,p)},d=n=>{var h;const{error:E,url:c}=n.detail;o(h=s,r,f).call(h,`downloadError event, ${c}, ${E}`,m.mediaPipe),s.on.error&&s.on.error(Fe.ASSET_DOWNLOAD,{url:c,error:E})};return i(s,x).addEventListener("downloadedError",d),i(s,x).addEventListener("bytesDownloaded",l),i(s,O).setVersion(s.getVersion()),i(s,R).logger&&Object.values(i(s,R).logger).some(n=>n===!0)&&i(s,O).start(),setTimeout(()=>{var n;o(n=s,r,fe).call(n,q.ASSETS_NOT_DOWNLOADED)},500),new Proxy(s,{get(n,h,E){const c=h;return typeof n[c]=="function"?n[c].bind(n):Reflect.get(n,c,E)},set(n,h,E){return console.log(`Setting property "${String(h)}" to "${E}" is not allowed`),!0}})}loadMask(e){if(i(this,_)){let s=!1;const a=i(this,_).mediaElement.querySelector("svg");a&&(s=!0,i(this,_).mediaElement.removeChild(a)),i(this,_).mediaElement.appendChild(e),s&&(i(this,_).mediaElement.style.setProperty("border","1px solid transparent"),setTimeout(()=>{i(this,_).mediaElement.removeAttribute("style")},100))}}setSettings(e){const s=_s(i(this,R),e);return s.results==="valid"?(u(this,R,s.settings),!0):!1}getVersion(){return{webSDK:ct,extractionLib:i(this,be),faceTracker:i(this,we)}}async downloadAssets(){const{assetFolder:e}=i(this,R);if(o(this,r,f).call(this,`Asset base URL ${e}`,m.sdk),o(this,r,f).call(this,"Start downloading decompressor...",m.sdk),await i(this,x).fetchAsset(i(this,B),`${e}/`,"decompress.json",!0,"gzip"),i(this,$))return o(this,r,f).call(this,"Skip downloading assets because the process is being destroyed",m.sdk),!1;if(i(this,x).canDecompress){const s=await o(this,r,Nt).call(this,e),a=await o(this,r,yt).call(this,e);if(i(this,$))return o(this,r,f).call(this,"Skip initializing workers because the process is being destroyed",m.sdk),!1;if(s&&a){await o(this,r,rt).call(this)||o(this,r,f).call(this,"Failed to initialize DFX extraction lib",m.extractionLibWasm);const d=await o(this,r,at).call(this);return d||o(this,r,f).call(this,"Failed to initialize TFJS face tracker",m.mediaPipe),i(this,$)?(i(this,K)&&await o(this,r,ye).call(this),d&&i(this,_)&&await o(this,r,Ve).call(this),!1):(o(this,r,Dt).call(this),!0)}else return!1}else return o(this,r,f).call(this,"Decompressor not ready",m.sdk),!1}setExtractionLibSettings(e=6,s=30,a=5){u(this,Q,e-1),u(this,oe,s),u(this,ce,a)}async setNextChunkAsFinal(){u(this,ke,!0),await o(this,r,A).call(this,S.SHOULD_END_MEASUREMENT_EARLY,{},!0),o(this,r,f).call(this,"Set the action for the next chunk to LAST::PROCESS",m.extractionLibWasm)}async startTracking(){i(this,_)&&(i(this,_).isExtracting||(i(this,_).setIsExtracting(!0),o(this,r,f).call(this,"Start tracking frames",m.mediaPipe),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,de)},!0),await o(this,r,Ne).call(this)))}async stopTracking(){if(i(this,_)){i(this,_).stopTracking(),await o(this,r,Pt).call(this),i(this,_).setIsExtracting(!1),o(this,r,f).call(this,"Stop extracting frames",m.mediaPipe);const{numOfFramesPresented:e,warmupFrameNumber:s,numOftrackedVideoFrames:a}=i(this,_);o(this,r,f).call(this,"Tracking metrics",m.sdk,{numOfFramesPresented:e,warmupFrameNumber:s,numOftrackedVideoFrames:a}),u(this,M,"")}}async disconnect(){if(i(this,H)&&await o(this,r,A).call(this,I.DISCONNECT,{},!0),i(this,R).metrics&&i(this,_)){const e=i(this,_).logger.mertics.debugLogs,s=i(this,O).mertics.debugLogs,a=await o(this,r,A).call(this,S.GET_LOGS,{},!0);u(this,Y,[]),u(this,me,0);const l=new Promise(n=>{u(this,ue,()=>n(void 0))});i(this,_).workers.forEach(n=>{n?.ft?.worker?.postMessage({action:N.GET_LOGS})}),await l;let d=[...s,...e,...a.payload];i(this,Y)&&i(this,Y).forEach(n=>{Array.isArray(n.logs)&&(d=d.concat(n.logs))}),d.sort((n,h)=>{const E=c=>{if(!c.timestamp)return 0;const T=c.timestamp.replace(/\[|\]/g,"");return Date.parse(T.replace(/(AM|PM)/,"").trim())+(T.includes("PM")&&!T.includes("12:")?432e5:0)};return E(n)-E(h)}),i(this,O).retrieveLogs(d)}}async destroy(){u(this,$,!0);let e=!0,s=!0;i(this,_)?.isExtracting&&await this.stopTracking(),i(this,H)&&await this.disconnect(),i(this,K)&&(e=await o(this,r,ye).call(this),o(this,r,f).call(this,"Destroyed",m.extractionLibWasm)),i(this,_)&&(s=await o(this,r,Ve).call(this),o(this,r,f).call(this,"Destroyed",m.mediaPipe)),u(this,$,!1);const a=e&&s;return a||o(this,r,f).call(this,"Failed to destroy all workers",m.sdk),a}async reset(){if(i(this,Re)!==q.ASSETS_NOT_DOWNLOADED){i(this,_)?.isExtracting&&await this.stopTracking(),await this.destroy(),u(this,O,new gt),u(this,be,{version:"",sdkId:""}),u(this,we,""),u(this,ne,0),u(this,M,""),u(this,H,!1),u(this,Q,5),u(this,oe,30),u(this,ce,5),u(this,ke,!1),u(this,ee,void 0),u(this,de,1e7),u(this,He,0),u(this,he,new Map),u(this,Ae,Promise.resolve()),u(this,D,0),u(this,ve,-1),u(this,V,-1),i(this,R).mediaElement.innerHTML="",u(this,j,-1);const e=await o(this,r,rt).call(this),s=await o(this,r,at).call(this);return e&&s}return!1}async setMediaStream(e){if(i(this,_)&&!i(this,_).isExtracting&&i(this,F)){await i(this,_).setMediaStream(e);const s=Object.fromEntries(i(this,_).workers.map((a,l)=>[`port${l+1}`,a.channel.port1]));i(this,F).worker.postMessage({action:S.SET_PORTS,payload:{numOfWorkers:i(this,le),workerPorts:s}},[...i(this,_).workers.map(a=>a.channel.port1)])}}async prepare(e,s,a,l){i(this,U).setSession({userToken:e,userRefreshToken:s});let d=!1;if(i(this,R).apiUrl)d=!0;else{const{status:E,region:c}=await o(this,r,Ut).call(this,"user");d=E==="200",i(this,R).apiUrl=`api.${c}.deepaffex.ai`}i(this,U).setUrl(`https://${i(this,R).apiUrl}`);const n=await o(this,r,$t).call(this,e,s,"user"),h=await o(this,r,Bt).call(this,a,l);return n&&h&&d}async setConstraintsConfig(e){await o(this,r,A).call(this,S.SET_CONSTRAINTS_CONFIG,{...i(this,Ke),...e&&{...i(this,R).constraintOverrides}},!0)}async startMeasurement(e=!1,s={}){if(u(this,ke,!1),u(this,M,""),u(this,j,-1),await o(this,r,Gt).call(this,s),i(this,F)&&i(this,M)!==""){await o(this,r,je).call(this),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,Q)+1},!0),await this.setConstraintsConfig(e),await o(this,r,Lt).call(this),await o(this,r,Ne).call(this);const{userToken:a}=i(this,U).getSession();a?await o(this,r,A).call(this,I.CONNECT,{token:a,measurementId:i(this,M)},!0):o(this,r,f).call(this,"User token is missing. Unable to connect.",m.webSocket)}return i(this,M)}setDemographics(e){return gs(e)?(u(this,ee,e),o(this,r,f).call(this,`Demographics updated ${JSON.stringify(e)}`,m.extractionLibWasm),!0):(o(this,r,f).call(this,`Error updating Demographics ${JSON.stringify(e)}`,m.extractionLibWasm),!1)}setObjectFit(e){return i(this,_)&&Me!==void 0&&Object.values(Me).includes(e)?(i(this,_).settings.objectFit=e,!0):!1}};U=new WeakMap,R=new WeakMap,B=new WeakMap,O=new WeakMap,x=new WeakMap,Pe=new WeakMap,We=new WeakMap,Ue=new WeakMap,$e=new WeakMap,_e=new WeakMap,ge=new WeakMap,Be=new WeakMap,be=new WeakMap,we=new WeakMap,_=new WeakMap,ne=new WeakMap,F=new WeakMap,Re=new WeakMap,M=new WeakMap,Ge=new WeakMap,H=new WeakMap,$=new WeakMap,Q=new WeakMap,oe=new WeakMap,ce=new WeakMap,ke=new WeakMap,le=new WeakMap,ee=new WeakMap,Ce=new WeakMap,Ke=new WeakMap,de=new WeakMap,He=new WeakMap,he=new WeakMap,Ae=new WeakMap,D=new WeakMap,ve=new WeakMap,V=new WeakMap,Oe=new WeakMap,K=new WeakMap,j=new WeakMap,Y=new WeakMap,me=new WeakMap,ue=new WeakMap,r=new WeakSet,At=function(){return/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1},vt=function(t){i(this,_)?.setRotate180(t)},Ot=function(){const t=o(this,r,Wt).call(this),e=o(this,r,At).call(this)&&t==="landscape-primary";o(this,r,vt).call(this,e)},yt=async function(t){o(this,r,f).call(this,"Start downloading TFJS face tracker assets...",m.mediaPipe);const e=`${t}/models/`,[s,a,l,d,n]=await Promise.all([i(this,x).fetchAsset(i(this,B),e,"detectorModel_json.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),e,"detectorModel_bin.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),e,"landmarkModel_json.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),e,"landmarkModel_bin.json",!0,"brotli"),i(this,x).fetchAsset(i(this,B),`${t}/`,`facetracker_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);return s&&a&&l&&d&&n?(o(this,r,f).call(this,"TFJS face tracker assets successfully downloaded",m.mediaPipe),u(this,Pe,s),u(this,We,a),u(this,Ue,l),u(this,$e,d),u(this,Be,n),!0):(o(this,r,f).call(this,"Failed to download TFJS face tracker assets",m.mediaPipe),!1)},Nt=async function(t){o(this,r,f).call(this,"Start downloading DFX extraction worker assets...",m.extractionLibWasm);const[e,s]=await Promise.all([i(this,x).fetchAsset(i(this,B),`${t}/extraction/`,`extraction_wasm_${this.getVersion().webSDK}.json`,!0,"brotli"),i(this,x).fetchAsset(i(this,B),`${t}/`,`extraction_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);return e&&s?(o(this,r,f).call(this,"DFX extraction worker assets successfully downloaded",m.extractionLibWasm),u(this,_e,e),u(this,ge,s),!0):(o(this,r,f).call(this,"Failed to download DFX extraction worker assets",m.extractionLibWasm),!1)},Dt=function(){if(i(this,_)){const t=e=>{o(this,r,Ot).call(this),this.on.mediaElementResize&&this.on.mediaElementResize(e)};i(this,R).mediaElement.addEventListener("mediaElementSizeChanged",t)}},ye=async function(){await o(this,r,A).call(this,S.DESTROY,{},!0);const t=i(this,F).destroy();return u(this,K,!1),t},Ve=async function(){let t=!1;return i(this,_)&&(t=await i(this,_).destroyWorkers(),u(this,_,void 0)),t},at=async function(){i(this,_)&&(await o(this,r,Ve).call(this),o(this,r,f).call(this,"Face Tracker workers destroyed",m.mediaPipe)),o(this,r,fe).call(this,q.NOT_LOADED);const t={faceTrackerCode:i(this,Be),numOfWorkers:i(this,le),mediaElement:i(this,R).mediaElement,mirrorVideo:i(this,R).mirrorVideo,metrics:i(this,R).metrics,displayMediaStream:i(this,R).displayMediaStream,isLoggingFaceTrackerWorkers:i(this,R).logger?.faceTrackerWorkers??!1,isLoggingSdk:i(this,R).logger?.sdk??!1,scaleFactor:i(this,Oe),models:{detectorJson:i(this,Pe),detectorBin:i(this,We),landmarkJson:i(this,Ue),landmarkBin:i(this,$e)}};o(this,r,fe).call(this,q.LOADING);const e=await Ds.init(t,i(this,O),{faceTrackersReady:(s,a,l,d)=>{o(this,r,f).call(this,`TFJS face tracker version ${a} loaded. Worker name: ${s} - workerId: ${l} - backend: ${d}`,m.mediaPipe),u(this,we,`${a}-${d}`),u(this,ne,i(this,ne)+1),i(this,O).setVersion(this.getVersion()),i(this,ne)===i(this,le)&&o(this,r,fe).call(this,q.LOADED)},frameAvailable:(s,a,l,d,n)=>{!d&&n?i(this,F).worker.postMessage({action:S.NEW_FRAME,payload:{frameNumber:a,frameTimestamp:s,frame:n,lastFrameNumber:l,tracked:d}},[n]):i(this,F).worker.postMessage({action:S.TRACKING_STATUS,payload:{frameNumber:a,frameTimestamp:s,lastFrameNumber:l,tracked:d}})},landmarksAvailable:(s,a,l)=>{const d=l/1e3;i(this,V)===0&&u(this,V,d),u(this,ve,d),i(this,_).numOftrackedVideoFrames+=1,s.detected||(i(this,_).starRating=0);const{starRating:n}=i(this,_),h=30,E=Math.min(i(this,ve)-i(this,V),h),c=i(this,V)>0?E/h*100:0,T={video:i(this,_).videoFpsTracker.fps.toFixed(1),faceTracker:i(this,_).faceTrackerFpsTracker.fps.toFixed(1)},p={face:s,annotations:a,starRating:n,percentCompleted:c,fps:T};this.on.facialLandmarksUpdated&&this.on.facialLandmarksUpdated(p)},scaleFactorChanged:s=>{u(this,Oe,s),i(this,_).scaleFactor=s,i(this,F).worker.postMessage({action:S.SCALE_FACTOR_CHANGED,payload:{scaleFactor:s}})},logsAvailable:(s,a)=>{i(this,Y)||u(this,Y,[]),i(this,Y).push({workerId:a,logs:s}),u(this,me,(i(this,me)||0)+1),i(this,me)===i(this,le)&&i(this,ue)&&(i(this,ue).call(this),u(this,ue,void 0))}});return i(this,$)&&e?(await e.destroyWorkers(),o(this,r,f).call(this,"Face Tracker workers destroyed",m.mediaPipe),!1):e?(u(this,_,e),!0):!1},rt=async function(){if(i(this,$))return!1;const t=new TextDecoder().decode(new Uint8Array(i(this,ge)));if(i(this,K)&&await o(this,r,ye).call(this),u(this,K,!1),u(this,F,Ye.init(t,"module","EXTRACTION_WORKER")),i(this,$))return i(this,F).destroy(),!1;const{studyCfgData:e}=i(this,U).getSession();if(e&&i(this,_e)&&i(this,ge)){i(this,F).worker.onmessage=async l=>{const{data:d}=l,{id:n,result:h}=d,{action:E,payload:c}=h,T=i(this,he).get(n);if(T||n===-1){switch(E){case S.READY:{const{sdkId:p,version:b,workerName:w}=c;u(this,be,{version:b,sdkId:p}),o(this,r,f).call(this,`DFX extraction worker WASM loaded. SDK ID: ${p} - Version: ${b} - Worker Name: ${w}`,m.extractionLibWasm),await o(this,r,A).call(this,S.SET_MODE,{value:"discrete"},!0),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,de)},!0),await o(this,r,A).call(this,S.SET_TARGET_FPS,{value:i(this,oe)},!0),await o(this,r,A).call(this,S.SET_CHUNK_DURATION_SECONDS,{value:i(this,ce)},!0),await o(this,r,A).call(this,S.SET_FRAME_ORDER,{value:bt.RGBA},!0),await o(this,r,A).call(this,S.GET_CONSTRAINTS_CONFIG,{},!0),u(this,Ke,i(this,Ce));break}case S.SET_MODE:{c&&o(this,r,f).call(this,`Set mode to ${c.mode}`,m.extractionLibWasm);break}case S.SET_NUMBER_OF_CHUNKS:{c&&o(this,r,f).call(this,`Set number of chunks to ${h.number}`,m.extractionLibWasm);break}case S.SET_TARGET_FPS:{c&&o(this,r,f).call(this,`Set target FPS to ${i(this,oe)}`,m.extractionLibWasm);break}case S.SET_CHUNK_DURATION_SECONDS:{c&&o(this,r,f).call(this,`Set chunk duration to ${i(this,ce)} Seconds`,m.extractionLibWasm);break}case S.SET_FRAME_ORDER:{c&&o(this,r,f).call(this,"Set channel order RGBA",m.extractionLibWasm);break}case S.GET_CONSTRAINTS_CONFIG:{c&&(u(this,Ce,c),o(this,r,f).call(this,`Get constraints ${JSON.stringify(c)}`,m.extractionLibWasm));break}case S.SET_CONSTRAINTS_CONFIG:{c&&(u(this,Ce,c),o(this,r,f).call(this,`Set constraints ${JSON.stringify(c)}`,m.extractionLibWasm));break}case S.SET_FACE_ATTRIBUTE:{const{success:p,faceId:b,attribute:w,value:C}=c;p&&o(this,r,f).call(this,`Set face attribute: faceId: ${b}, attribute: ${w}, value: ${C}`,m.extractionLibWasm);break}case S.RESET_COLLECTION:{c&&o(this,r,f).call(this,"Reset collection",m.extractionLibWasm);break}case S.CANCEL_COLLECTION:{c&&o(this,r,f).call(this,"Collecttion cancelled",m.extractionLibWasm);break}case S.START_COLLECTION:{c&&o(this,r,f).call(this,`Collector started - state: ${c}`,m.extractionLibWasm);break}case S.SET_PORTS:{c&&o(this,r,f).call(this,"Ports set",m.extractionLibWasm);break}case S.COLLECTOR_ERROR:{if(c){const{error:p,frameNumber:b}=c;o(this,r,f).call(this,`Collector error on frame ${b}: ${p}`,m.extractionLibWasm),this.on.error&&this.on.error(Fe.COLLECTOR,c),i(this,H)?(o(this,r,f).call(this,"Measurement in progress, Stopping tracking due to collector error",m.extractionLibWasm),await this.stopTracking()):(o(this,r,f).call(this,"No active measurement, resetting and starting collection",m.extractionLibWasm),await o(this,r,je).call(this),await o(this,r,Ne).call(this))}break}case S.STAR_RATING:{i(this,_).starRating=c.rating;break}case S.ALL_FACE_TRACKERS_WARMED_UP:{const{frameNumber:p}=h;i(this,_).warmupFrameNumber=p,o(this,r,f).call(this,"All face tracker workers are warmed up.",m.mediaPipe),o(this,r,fe).call(this,q.READY);break}case S.CONSTRAINTS_UPDATED:{const{feedback:p,status:b}=c;this.on.constraintsUpdated&&this.on.constraintsUpdated(p,b);break}case S.SHOULD_END_MEASUREMENT_EARLY:{const{currentFinalChunkNumber:p,currentResultsOrder:b,newFinalChunkNumber:w}=h;o(this,r,f).call(this,`Request the end measurement early. Current final chunk number: ${p}, Current results order: ${b}, New final chunk number: ${w}`,m.extractionLibWasm);break}case S.GET_LOGS:break;case S.DESTROY:break;case I.CONNECT:{u(this,H,!0),u(this,V,0),o(this,r,f).call(this,c?"Connected":"Connection error",m.webSocket);break}case I.LOGIN_WITH_TOKEN_SUCCESS:{o(this,r,f).call(this,"Successfully logged in with token",m.webSocket);break}case I.SUBSCRIBED_TO_RESULTS:{o(this,r,f).call(this,"Subscribed to the results",m.webSocket);break}case I.CHUNK_SENT:{o(this,r,f).call(this,`Chunk sent ${JSON.stringify(c)}`,m.webSocket),this.on.chunkSent&&this.on.chunkSent(c);break}case I.DISCONNECT:{u(this,H,!1),o(this,r,f).call(this,"Disconnect",m.webSocket);break}case I.DISCONNECTED:{o(this,r,f).call(this,`Disconnected! - code: ${c.code}, reason: ${c.reason}, wasClean: ${c.wasClean}`,m.webSocket),this.on.error&&this.on.error(Fe.WEB_SOCKET,c);break}case I.CHUNK_ACKNOWLEDGED:{o(this,r,f).call(this,`Chunk number ${c.chunkOrder} received by the server!`,m.webSocket),i(this,Q)===c.chunkOrder&&await this.stopTracking();break}case I.RESULTS_RECEIVED:{const{MeasurementID:p,MeasurementDataID:b}=c;p?u(this,j,parseInt(b.split(":")[1],10)):u(this,j,i(this,j)+1),this.on.resultsReceived&&this.on.resultsReceived(c),o(this,r,f).call(this,`Results received: ${JSON.stringify(c)}`,m.webSocket),i(this,j)===i(this,Q)&&(await o(this,r,A).call(this,I.DISCONNECT,{},!0),await o(this,r,je).call(this),await o(this,r,Ne).call(this));break}case I.NETWORK_DELAY:{const{delay:p,description:b,actionId:w}=c;o(this,r,f).call(this,`Round-trip delay for ${b} call with Action ID ${w} was ${p.toFixed(2)} ms`,m.webSocket,{delay:p,actionId:w,description:b});break}case I.ERROR:{o(this,r,f).call(this,"Error",m.webSocket),this.on.error&&this.on.error(Fe.WEB_SOCKET,c);break}}T&&(T.resolve(h),i(this,he).delete(n))}};const a=(await o(this,r,A).call(this,S.INIT,{wasm:i(this,_e),studyConfigData:e,isLogging:i(this,R).logger?.extractionWorker||!1,metrics:i(this,R).metrics||!1,apiUrl:i(this,R).apiUrl,scaleFactor:i(this,Oe)},!0)).action===S.READY;return u(this,K,a),i(this,K)&&i(this,$)?(await o(this,r,ye).call(this),!1):a}else return!1},Lt=async function(){if(i(this,_)){if(!i(this,ee)){o(this,r,f).call(this,"No demographics to set",m.extractionLibWasm);return}const t="1",{age:e,height:s,weight:a,sex:l,smoking:d,bloodPressureMedication:n,diabetes:h}=i(this,ee),E=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.SEX_ASSIGNED_AT_BIRTH,value:l},!0),c=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.AGE_YEARS,value:e},!0),T=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.HEIGHT_CM,value:s},!0),p=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.WEIGHT_KG,value:a},!0),b=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.SMOKER,value:d},!0),w=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.BLOOD_PRESSURE_MEDICATION,value:n},!0),C=await o(this,r,A).call(this,S.SET_FACE_ATTRIBUTE,{faceId:t,attribute:X.DIABETES,value:h},!0);o(this,r,f).call(this,`Set demographics for Face ID ${t}, ${JSON.stringify(i(this,ee))}`,m.extractionLibWasm);const v={SEX_ASSIGNED_AT_BIRTH:{success:E.payload.success},AGE_YEARS:{success:c.payload.success},HEIGHT_CM:{success:T.payload.success},WEIGHT_KG:{success:p.payload.success},SMOKER:{success:b.payload.success},BLOOD_PRESSURE_MEDICATION:{success:w.payload.success},DIABETES:{success:C.payload.success}};o(this,r,f).call(this,`Validation results for demographics for Face ID ${t}, ${JSON.stringify(v)}`,m.extractionLibWasm)}},It=function(){},xt=function(){const t=new Date().toISOString();Tt(t)&&(o(this,r,f).call(this,`Action ID: ${i(this,D)}`,m.beforeRESTCall),this.on.beforeRESTCall&&this.on.beforeRESTCall(t,i(this,D)))},Ft=function(t,e){},Mt=function(t,e){const s=new Date().toISOString();Tt(s)&&(o(this,r,f).call(this,`Action ID: ${i(this,D)}, HTTP status code: ${t}, error: ${JSON.stringify(e)}`,m.afterRESTCall),this.on.afterRESTCall&&this.on.afterRESTCall(s,i(this,D),t,e))},Pt=async function(){await o(this,r,A).call(this,S.CANCEL_COLLECTION,{},!0)},Ne=async function(){await o(this,r,A).call(this,S.START_COLLECTION,{},!0)},je=async function(){await o(this,r,A).call(this,S.RESET_COLLECTION,{},!0),await o(this,r,A).call(this,S.SET_NUMBER_OF_CHUNKS,{value:i(this,de)},!0)},f=function(t,e,s){i(this,R).metrics&&i(this,O).log(t,e,"",!0,s),i(this,R).logger?.mediaPipe&&e===m.mediaPipe&&i(this,O).info(t,e),i(this,R).logger?.beforeRESTCall&&e===m.beforeRESTCall&&i(this,O).info(t,e),i(this,R).logger?.afterRESTCall&&e===m.afterRESTCall&&i(this,O).info(t,e),i(this,R).logger?.extractionLibWasm&&e===m.extractionLibWasm&&i(this,O).info(t,e),i(this,R).logger?.apiClient&&e===m.apiClient&&i(this,O).info(t,e),i(this,R).logger?.webSocket&&e===m.webSocket&&i(this,O).info(t,e),i(this,R).logger?.sdk&&e===m.sdk&&i(this,O).info(t,e)},Wt=function(){return screen.orientation.type},Ut=async function(t){u(this,D,0);const e=performance.now(),s=await i(this,U).http.auths.validate(t),a=performance.now()-e,{status:l,body:d}=s;if(o(this,r,f).call(this,l==="200"?"Successfully validated the Token":`Failed to validate token. Status: ${l}`,m.apiClient,{delay:a,actionId:i(this,D),description:"Validate Token"}),l==="200"){const{Region:n}=d;return{region:n,status:l}}else return{status:l,region:""}},$t=async function(t,e,s){u(this,D,2304);const a=performance.now(),l=await i(this,U).http.auths.renew({Token:t,RefreshToken:e},s),d=performance.now()-a,{status:n}=l;return o(this,r,f).call(this,n==="200"?"Successfully refreshed the Token":`Failed to refresh token. Status: ${n}`,m.apiClient,{delay:d,actionId:i(this,D),description:"Refresh Token"}),n==="200"},Bt=async function(t,e){u(this,D,806);const s=performance.now();u(this,Ge,t);const a=await i(this,U).http.studies.retrieveSdkConfigData({StudyID:t,...e&&{sdkId:e}},"user"),l=performance.now()-s,{status:d}=a;return o(this,r,f).call(this,d==="200"?"Retrieve SDK Config Data - success":"Retrieve SDK Config Data - failure",m.apiClient,{delay:l,actionId:i(this,D),description:"Retrieve SDK Config Data"}),d==="200"},Gt=async function(t){o(this,r,f).call(this,"Get Measurement ID",m.apiClient),u(this,D,504);const e=performance.now(),s={StudyID:i(this,Ge),Resolution:100};t.partnerId&&(s.PartnerID=t.partnerId),t.userProfileId&&(s.UserProfileID=t.userProfileId);const a=await i(this,U).http.measurements.create(s,"user"),l=performance.now()-e,{status:d,body:n}=a;let h="";d==="200"?(u(this,M,n.ID),h=`Successfully obtained measurement ID: ${i(this,M)}`):(u(this,M,""),h=`Failed to obtain measurement ID. Status: ${d}`),o(this,r,f).call(this,h,m.apiClient,{delay:l,actionId:i(this,D),measurementId:i(this,M),description:"Get Measurement ID"})},fe=function(t){u(this,Re,t),o(this,r,f).call(this,`Face tracker state changed: ${t}`,m.mediaPipe),this.on.faceTrackerStateChanged&&this.on.faceTrackerStateChanged(i(this,Re))},A=function(t,e,s=!1){return new Promise(a=>{const l=xs(this,He)._++;i(this,he).set(l,{resolve:a,action:t});const d=()=>i(this,F).worker.postMessage({id:l,action:t,payload:e});s?u(this,Ae,i(this,Ae).then(d).catch(n=>console.error(n))):d()})},Ct(Fs,"VERSION",ct);const Ms={DISTANCE:{OK:"OK",TOO_CLOSE:"TOO_CLOSE",TOO_FAR:"TOO_FAR"},DIRECTION:{OK:"OK",TURN_LEFT:"TURN_LEFT",TURN_RIGHT:"TURN_RIGHT",TURN_UP:"TURN_UP",TURN_DOWN:"TURN_DOWN"},ROLL:{OK:"OK",TILT_LEFT:"TILT_LEFT",TILT_RIGHT:"TILT_RIGHT"},MOVEMENT:{OK:"OK",TOO_MUCH_MOVEMENT:"TOO_MUCH_MOVEMENT"},CENTER:{OK:"OK",NOT_CENTERED:"NOT_CENTERED"}};class Ps{static VERSION=jt;#e=document.createElement("div");#s=document.createElement("div");#i=!1;#a=!1;on={results:null,error:null,event:null};constructor(){this.#e.style.height="100%"}async init(e){const{container:s,appPath:a,settings:l,profile:d,config:n,language:h,apiUrl:E}=e;return this.#s=s,new Promise((c,T)=>{const p=s.attachShadow({mode:"open"}),b="app",w=document.createElement("link");w.rel="stylesheet",w.href=`${a}/stylex.css`,p.appendChild(w);const C=document.createElement("link");C.rel="stylesheet",C.href=`${a}/${b}.css`,p.appendChild(C);const v=W=>{this.on.results&&this.on.results({...W.detail})},P=W=>{this.on.error&&this.on.error({...W.detail})},z=W=>{this.on.event&&this.on.event({...W.detail}),W.detail.event===ze.APP_LOADED.event&&(this.#i=!0,c()),W.detail.event===ze.ASSETS_DOWNLOADED.event&&(this.#a=!0)};this.#e.addEventListener(G.RESULTS,v),this.#e.addEventListener(G.ERROR,P),this.#e.addEventListener(G.APPEVENT,z),p.appendChild(this.#e);const te=document.createElement("script");te.type="module",te.src=`${a}/${b}.mjs`,te.onload=()=>{import(/* webpackIgnore: true */ te.src).then(W=>{W.app.init(this.#e,a,l,d,E,n,h)}).catch(W=>{T(new Error("Failed to initialize Measurement Embedded React app: "+W.message))})},te.onerror=()=>{T(new Error("Failed to load the measurement embedded app script"))},p.appendChild(te)})}#t(){if(!this.#i)throw new Error("MeasurementEmbeddedApp is not initialized. Call init() before using this method.")}#r(){if(!this.#a)throw new Error('Assets not downloaded and SDK not initialized. Please wait for the "ASSETS_DOWNLOADED" event before calling this method.')}async destroy(){return this.#t(),this.#r(),new Promise(e=>{const s=l=>{if(this.#e.removeEventListener(G.DESTROYED,s),this.#s){const d=this.#s.cloneNode(!1);this.#s.replaceWith(d)}e(l.detail.destroyed)};this.#e.addEventListener(G.DESTROYED,s);const a=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.DESTROY,data:{}}});this.#e.dispatchEvent(a)})}setTheme(e){this.#t();const s=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.SET_THEME,data:{theme:e}}});this.#e.dispatchEvent(s)}setLanguage(e){this.#t();const s=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.SET_LANGUAGE,data:{language:e}}});this.#e.dispatchEvent(s)}setAppSettings(e,s,a,l={}){this.#t();const d=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.SET_APP_SETTINGS,data:{token:e,refreshToken:s,studyId:a,measurementOptions:l}}});this.#e.dispatchEvent(d)}async cancel(e){return this.#t(),this.#r(),new Promise(s=>{const a=d=>{this.#e.removeEventListener(G.CANCELLED,a),s(d.detail.reset)};this.#e.addEventListener(G.CANCELLED,a);const l=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.CANCEL,data:{reset:e}}});this.#e.dispatchEvent(l)})}getLogs(){return this.#t(),new Promise(e=>{const s=l=>{this.#e.removeEventListener(G.LOGS,s),e(l.detail.logs)};this.#e.addEventListener(G.LOGS,s);const a=new CustomEvent("measurement-embedded-app-action",{detail:{action:se.GET_LOGS,data:{}}});this.#e.dispatchEvent(a)})}}export{ot as ErrorCodes,y as appEventSeverity,ze as appEvents,Ms as constraintCodes,Ps as default,Cs as faceAttributeValue,nt as logCategory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuralogix.ai/web-measurement-embedded-app",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Web Measurement Embedded App",
5
5
  "homepage": "https://docs.deepaffex.ai/wmea/",
6
6
  "contributors": [