scorm-again
Version:
A modern SCORM JavaScript run-time library for SCORM 1.2 and SCORM 2004
1 lines • 67.1 kB
JavaScript
this.AICC=function(){"use strict";const e="true",t="false",s={cmi_children:"core,suspend_data,launch_data,comments,objectives,student_data,student_preference,interactions",core_children:"student_id,student_name,lesson_location,credit,lesson_status,entry,score,total_time,lesson_mode,exit,session_time",score_children:"raw,min,max",comments_children:"content,location,time",objectives_children:"id,score,status",correct_responses_children:"pattern",student_data_children:"mastery_score,max_time_allowed,time_limit_action",student_preference_children:"audio,language,speed,text",interactions_children:"id,objectives,time,type,correct_responses,weighting,student_response,result,latency",error_descriptions:{101:{basicMessage:"General Exception",detailMessage:"No specific error code exists to describe the error."},201:{basicMessage:"Invalid argument error",detailMessage:"Indicates that an argument represents an invalid data model element or is otherwise incorrect."},202:{basicMessage:"Element cannot have children",detailMessage:'Indicates that LMSGetValue was called with a data model element name that ends in "_children" for a data model element that does not support the "_children" suffix.'},203:{basicMessage:"Element not an array - cannot have count",detailMessage:'Indicates that LMSGetValue was called with a data model element name that ends in "_count" for a data model element that does not support the "_count" suffix.'},301:{basicMessage:"Not initialized",detailMessage:"Indicates that an API call was made before the call to lmsInitialize."},401:{basicMessage:"Not implemented error",detailMessage:"The data model element indicated in a call to LMSGetValue or LMSSetValue is valid, but was not implemented by this LMS. SCORM 1.2 defines a set of data model elements as being optional for an LMS to implement."},402:{basicMessage:"Invalid set value, element is a keyword",detailMessage:'Indicates that LMSSetValue was called on a data model element that represents a keyword (elements that end in "_children" and "_count").'},403:{basicMessage:"Element is read only",detailMessage:"LMSSetValue was called with a data model element that can only be read."},404:{basicMessage:"Element is write only",detailMessage:"LMSGetValue was called on a data model element that can only be written to."},405:{basicMessage:"Incorrect Data Type",detailMessage:"LMSSetValue was called with a value that is not consistent with the data format of the supplied data model element."},407:{basicMessage:"Element Value Out Of Range",detailMessage:"The numeric value supplied to a LMSSetValue call is outside of the numeric range allowed for the supplied data model element."},408:{basicMessage:"Data Model Dependency Not Established",detailMessage:"Some data model elements cannot be set until another data model element was set. This error condition indicates that the prerequisite element was not set before the dependent element."}}},i={...s,cmi_children:"core,suspend_data,launch_data,comments,objectives,student_data,student_preference,interactions,evaluation",student_preference_children:"audio,language,lesson_type,speed,text,text_color,text_location,text_size,video,windows",student_data_children:"attempt_number,tries,mastery_score,max_time_allowed,time_limit_action",student_demographics_children:"city,class,company,country,experience,familiar_name,instructor_name,title,native_language,state,street_address,telephone,years_experience",tries_children:"time,status,score",attempt_records_children:"score,lesson_status",paths_children:"location_id,date,time,status,why_left,time_in_element"},r={GENERAL:101,INITIALIZATION_FAILED:101,INITIALIZED:101,TERMINATED:101,TERMINATION_FAILURE:101,TERMINATION_BEFORE_INIT:101,MULTIPLE_TERMINATION:101,RETRIEVE_BEFORE_INIT:101,RETRIEVE_AFTER_TERM:101,STORE_BEFORE_INIT:101,STORE_AFTER_TERM:101,COMMIT_BEFORE_INIT:101,COMMIT_AFTER_TERM:101,ARGUMENT_ERROR:101,CHILDREN_ERROR:101,COUNT_ERROR:101,GENERAL_GET_FAILURE:101,GENERAL_SET_FAILURE:101,GENERAL_COMMIT_FAILURE:101,UNDEFINED_DATA_MODEL:101,UNIMPLEMENTED_ELEMENT:101,VALUE_NOT_INITIALIZED:101,INVALID_SET_VALUE:101,READ_ONLY_ELEMENT:101,WRITE_ONLY_ELEMENT:101,TYPE_MISMATCH:101,VALUE_OUT_OF_RANGE:101,DEPENDENCY_NOT_ESTABLISHED:101,RETRIEVE_BEFORE_INIT:301,STORE_BEFORE_INIT:301,COMMIT_BEFORE_INIT:301,ARGUMENT_ERROR:201,CHILDREN_ERROR:202,COUNT_ERROR:203,UNDEFINED_DATA_MODEL:401,UNIMPLEMENTED_ELEMENT:401,VALUE_NOT_INITIALIZED:301,INVALID_SET_VALUE:402,READ_ONLY_ELEMENT:403,WRITE_ONLY_ELEMENT:404,TYPE_MISMATCH:405,VALUE_OUT_OF_RANGE:407,DEPENDENCY_NOT_ESTABLISHED:408},n={CMIString256:"^[\\s\\S]{0,255}$",CMIString4096:"^[\\s\\S]{0,4096}$",CMITime:"^(?:[01]\\d|2[0123]):(?:[012345]\\d):(?:[012345]\\d)$",CMITimespan:"^([0-9]{2,}):([0-9]{2}):([0-9]{2})(.[0-9]{1,2})?$",CMIInteger:"^\\d+$",CMISInteger:"^-?([0-9]+)$",CMIDecimal:"^-?([0-9]{0,3})(\\.[0-9]*)?$",CMIIdentifier:"^[\\u0021-\\u007E\\s]{0,255}$",CMIFeedback:"^.*$",CMIIndex:"[._](\\d+).",CMIStatus:"^(passed|completed|failed|incomplete|browsed)$",CMIStatus2:"^(passed|completed|failed|incomplete|browsed|not attempted)$",CMIExit:"^(time-out|suspend|logout|)$",CMIType:"^(true-false|choice|fill-in|matching|performance|sequencing|likert|numeric)$",CMIResult:"^(correct|wrong|unanticipated|neutral|([0-9]{0,3})?(\\.[0-9]*)?)$",NAVEvent:"^(previous|continue|start|resumeAll|choice|jump|exit|exitAll|abandon|abandonAll|suspendAll|retry|retryAll|_none_)$",score_range:"0#100",audio_range:"-1#100",speed_range:"-100#100",weighting_range:"-100#100",text_range:"-1#1"},o={...n,CMIIdentifier:"^[A-Za-z0-9._-]{1,255}$"};class a extends Error{constructor(e,t){super(`${e} : ${""+t}`),this._errorCode=t,Object.setPrototypeOf(this,a.prototype)}get errorCode(){return this._errorCode}}class c extends a{constructor(e,t,s,i){super(e,t),this._detailedMessage="",this.message=`${e} : ${s}`,this._errorMessage=s,i&&(this._detailedMessage=i),Object.setPrototypeOf(this,c.prototype)}get errorMessage(){return this._errorMessage}get detailedMessage(){return this._detailedMessage}}const h=s.error_descriptions;class l extends c{constructor(e,t){!{}.hasOwnProperty.call(h,t+"")?super(e,101,h[101]?.basicMessage??"General error",h[101]?.detailMessage):super(e,t,h[t+""]?.basicMessage||"Unknown error",h[t+""]?.detailMessage),Object.setPrototypeOf(this,l.prototype)}}class _{constructor(e){this.jsonString=!1,this._initialized=!1,this._cmi_element=e}get initialized(){return this._initialized}initialize(){this._initialized=!0}}class d extends _{get start_time(){return this._start_time}setStartTime(){if(void 0!==this._start_time)throw Error("Start time has already been set.");this._start_time=(new Date).getTime()}}const m=f(e=>{if(!e||0>=e)return"00:00:00";const t=Math.floor(e/3600),s=new Date(1e3*e),i=s.getUTCMinutes(),r=s.getSeconds(),n=e%1;let o="";return p(n)>0&&(o=p(n)>2?n.toFixed(2):n+"",o="."+o.split(".")[1]),(t+":"+i+":"+r).replace(/\b\d\b/g,"0$&")+o}),u=f((e,t)=>{if("number"!=typeof e&&"boolean"!=typeof e||(e+=""),"string"==typeof t&&(t=RegExp(t)),!e)return 0;if(!e.match(t))return/^\d+(?:\.\d+)?$/.test(e)?+e:0;const s=e.split(":");return 3600*+s[0]+60*+s[1]+ +s[2]},(e,t)=>`${"string"==typeof e?e:(e??"")+""}:${"string"==typeof t?t:t?.toString()??""}`);function g(e){const result={};return function e(t,s){if(Object(t)!==t)result[s]=t;else if(Array.isArray(t))t.forEach((t,i)=>{e(t,`${s}[${i}]`)}),0===t.length&&(result[s]=[]);else{const i=Object.keys(t).filter(e=>({}.hasOwnProperty.call(t,e))),r=0===i.length;i.forEach(i=>{e(t[i],s?`${s}.${i}`:i)}),r&&s&&(result[s]={})}}(e,""),result}function p(e){if(Math.floor(e)===e||0>(e+"")?.indexOf?.("."))return 0;const t=(""+e).split(".")?.[1];return t?.length??0}function E(e,t){return"string"==typeof e&&RegExp(t).test(e)}function f(e,t){const s=new Map;return function(){for(var i=arguments.length,r=Array(i),n=0;i>n;n++)r[n]=arguments[n];const o=t?t(...r):JSON.stringify(r);return s.has(o)?s.get(o):(()=>{const result=e(...r);return s.set(o,result),result})()}}const S=f((e,t,s,i,r,n)=>{if("string"!=typeof t)return!1;const o=RegExp(s),a=t.match(o);if(n&&""===t)return!0;if(void 0===t||!a||""===a[0])throw new r(e,i);return!0},(e,t,s,i,r,n)=>`${e}:${"string"==typeof t?t:`[${typeof t}]`}:${s}:${i}:${n||!1}`),O=f((e,t,s,i,r)=>{const n=s.split("#");if(t*=1,n[0]&&t>=n[0]){if(!n[1]||"*"!==n[1]&&t>n[1])throw new r(e,i);return!0}throw new r(e,i)},(e,t,s,i,r)=>`${e}:${t}:${s}:${i}`);function I(e,t,s,i){return S(e,t,s,r.TYPE_MISMATCH,l,i)}function M(e,t,s,i){if(""===t)throw new l(e,r.VALUE_OUT_OF_RANGE);return O(e,t,s,r.VALUE_OUT_OF_RANGE,l)}const C=new class{validateScore(e,t,s,i,r,n,o){return S(e,t,s,r,o)&&(!i||O(e,t,i,n,o))}validateScorm12Audio(e,t){return I(e,t,n.CMISInteger)&&M(e,t,"-1#100")}validateScorm12Language(e,t){return I(e,t,n.CMIString256)}validateScorm12Speed(e,t){return I(e,t,n.CMISInteger)&&M(e,t,"-100#100")}validateScorm12Text(e,t){return I(e,t,n.CMISInteger)&&M(e,t,"-1#1")}validateReadOnly(e,t){if(t)throw new l(e,r.READ_ONLY_ELEMENT)}};class y extends _{constructor(e){super(e.CMIElement),this._raw="",this._min="",this.__children=e.score_children||"raw,min,max",this.__score_range=!!e.score_range&&"0#100",this._max=e.max||""===e.max?e.max:"100",this.__invalid_error_code=e.invalidErrorCode||r.INVALID_SET_VALUE,this.__invalid_type_code=e.invalidTypeCode||r.TYPE_MISMATCH,this.__invalid_range_code=e.invalidRangeCode||r.VALUE_OUT_OF_RANGE,this.__decimal_regex=e.decimalRegex||n.CMIDecimal,this.__error_class=e.errorClass}reset(){this._initialized=!1}get _children(){return this.__children}set _children(_children){throw new this.__error_class(this._cmi_element+"._children",this.__invalid_error_code)}get raw(){return this._raw}set raw(e){C.validateScore(this._cmi_element+".raw",e,this.__decimal_regex,this.__score_range,this.__invalid_type_code,this.__invalid_range_code,this.__error_class)&&(this._raw=e)}get min(){return this._min}set min(e){C.validateScore(this._cmi_element+".min",e,this.__decimal_regex,this.__score_range,this.__invalid_type_code,this.__invalid_range_code,this.__error_class)&&(this._min=e)}get max(){return this._max}set max(e){C.validateScore(this._cmi_element+".max",e,this.__decimal_regex,this.__score_range,this.__invalid_type_code,this.__invalid_range_code,this.__error_class)&&(this._max=e)}getScoreObject(){const e={};return Number.isNaN(Number.parseFloat(this.raw))||(e.raw=Number.parseFloat(this.raw)),Number.isNaN(Number.parseFloat(this.min))||(e.min=Number.parseFloat(this.min)),Number.isNaN(Number.parseFloat(this.max))||(e.max=Number.parseFloat(this.max)),e}toJSON(){this.jsonString=!0;const result={raw:this.raw,min:this.min,max:this.max};return this.jsonString=!1,result}}class w extends _{constructor(){super("cmi.core"),this.__children=s.core_children,this._student_id="",this._student_name="",this._lesson_location="",this._credit="",this._lesson_status="not attempted",this._entry="",this._total_time="",this._lesson_mode="normal",this._exit="",this._session_time="00:00:00",this._suspend_data="",this.score=new y({CMIElement:"cmi.core.score",score_children:"raw,min,max",score_range:"0#100",invalidErrorCode:r.INVALID_SET_VALUE,invalidTypeCode:r.TYPE_MISMATCH,invalidRangeCode:r.VALUE_OUT_OF_RANGE,errorClass:l})}initialize(){super.initialize(),this.score?.initialize()}reset(){this._initialized=!1,this._exit="",this._entry="",this._session_time="00:00:00",this.score?.reset()}get _children(){return this.__children}set _children(_children){throw new l(this._cmi_element+"._children",r.INVALID_SET_VALUE)}get student_id(){return this._student_id}set student_id(student_id){if(this.initialized)throw new l(this._cmi_element+".student_id",r.READ_ONLY_ELEMENT);this._student_id=student_id}get student_name(){return this._student_name}set student_name(student_name){if(this.initialized)throw new l(this._cmi_element+".student_name",r.READ_ONLY_ELEMENT);this._student_name=student_name}get lesson_location(){return this._lesson_location}set lesson_location(lesson_location){I(this._cmi_element+".lesson_location",lesson_location,n.CMIString256,!0)&&(this._lesson_location=lesson_location)}get credit(){return this._credit}set credit(credit){if(this.initialized)throw new l(this._cmi_element+".credit",r.READ_ONLY_ELEMENT);this._credit=credit}get lesson_status(){return this._lesson_status}set lesson_status(lesson_status){this.initialized?I(this._cmi_element+".lesson_status",lesson_status,n.CMIStatus)&&(this._lesson_status=lesson_status):I(this._cmi_element+".lesson_status",lesson_status,n.CMIStatus2)&&(this._lesson_status=lesson_status)}get entry(){return this._entry}set entry(entry){if(this.initialized)throw new l(this._cmi_element+".entry",r.READ_ONLY_ELEMENT);this._entry=entry}get total_time(){return this._total_time}set total_time(total_time){if(this.initialized)throw new l(this._cmi_element+".total_time",r.READ_ONLY_ELEMENT);this._total_time=total_time}get lesson_mode(){return this._lesson_mode}set lesson_mode(lesson_mode){if(this.initialized)throw new l(this._cmi_element+".lesson_mode",r.READ_ONLY_ELEMENT);this._lesson_mode=lesson_mode}get exit(){if(!this.jsonString)throw new l(this._cmi_element+".exit",r.WRITE_ONLY_ELEMENT);return this._exit}set exit(exit){I(this._cmi_element+".exit",exit,n.CMIExit,!0)&&(this._exit=exit)}get session_time(){if(!this.jsonString)throw new l(this._cmi_element+".session_time",r.WRITE_ONLY_ELEMENT);return this._session_time}set session_time(session_time){I(this._cmi_element+".session_time",session_time,n.CMITimespan)&&(this._session_time=session_time)}get suspend_data(){return this._suspend_data}set suspend_data(suspend_data){I(this._cmi_element+".suspend_data",suspend_data,n.CMIString4096,!0)&&(this._suspend_data=suspend_data)}getCurrentTotalTime(e){let t=this._session_time;if(null!=e){const s=(new Date).getTime()-e;t=m(s/1e3)}return s=this._total_time,i=t,"string"==typeof(r=RegExp(n.CMITimespan))&&(r=RegExp(r)),m(u(s,r)+u(i,r));var s,i,r}toJSON(){this.jsonString=!0;const result={student_id:this.student_id,student_name:this.student_name,lesson_location:this.lesson_location,credit:this.credit,lesson_status:this.lesson_status,entry:this.entry,lesson_mode:this.lesson_mode,exit:this.exit,session_time:this.session_time,score:this.score};return this.jsonString=!1,result}}class L extends _{constructor(e){super(e.CMIElement),this.__children=e.children,this._errorCode=e.errorCode||r.GENERAL,this._errorClass=e.errorClass||a,this.childArray=[]}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this._initialized=!1,e)this.childArray=[];else for(let e=0;this.childArray.length>e;e++)this.childArray[e].reset()}get _children(){return this.__children}set _children(_children){throw new this._errorClass(this._cmi_element+"._children",this._errorCode)}get _count(){return this.childArray.length}set _count(_count){throw new this._errorClass(this._cmi_element+"._count",this._errorCode)}toJSON(){this.jsonString=!0;const result={};for(let e=0;this.childArray.length>e;e++)result[e+""]=this.childArray[e];return this.jsonString=!1,result}}class N extends L{constructor(){super({CMIElement:"cmi.objectives",children:"id,score,status",errorCode:r.INVALID_SET_VALUE,errorClass:l})}}class v extends _{constructor(){super("cmi.objectives.n"),this._id="",this._status="",this.score=new y({CMIElement:"cmi.objectives.n.score",score_children:"raw,min,max",score_range:"0#100",invalidErrorCode:r.INVALID_SET_VALUE,invalidTypeCode:r.TYPE_MISMATCH,invalidRangeCode:r.VALUE_OUT_OF_RANGE,errorClass:l})}reset(){this._initialized=!1,this._id="",this._status="",this.score?.reset()}get id(){return this._id}set id(id){I(this._cmi_element+".id",id,n.CMIIdentifier)&&(this._id=id)}get status(){return this._status}set status(status){I(this._cmi_element+".status",status,n.CMIStatus2)&&(this._status=status)}toJSON(){this.jsonString=!0;const result={id:this.id,status:this.status,score:this.score};return this.jsonString=!1,result}}class R extends _{constructor(e){super("cmi.student_data"),this._mastery_score="",this._max_time_allowed="",this._time_limit_action="",this.__children=e||s.student_data_children}reset(){this._initialized=!1}get _children(){return this.__children}set _children(_children){throw new l(this._cmi_element+"._children",r.INVALID_SET_VALUE)}get mastery_score(){return this._mastery_score}set mastery_score(mastery_score){C.validateReadOnly(this._cmi_element+".mastery_score",this.initialized),this._mastery_score=mastery_score}get max_time_allowed(){return this._max_time_allowed}set max_time_allowed(max_time_allowed){C.validateReadOnly(this._cmi_element+".max_time_allowed",this.initialized),this._max_time_allowed=max_time_allowed}get time_limit_action(){return this._time_limit_action}set time_limit_action(time_limit_action){C.validateReadOnly(this._cmi_element+".time_limit_action",this.initialized),this._time_limit_action=time_limit_action}toJSON(){this.jsonString=!0;const result={mastery_score:this.mastery_score,max_time_allowed:this.max_time_allowed,time_limit_action:this.time_limit_action};return this.jsonString=!1,result}}class T extends _{constructor(e){super("cmi.student_preference"),this._audio="",this._language="",this._speed="",this._text="",this.__children=e||"audio,language,speed,text"}reset(){this._initialized=!1}get _children(){return this.__children}set _children(_children){throw new l(this._cmi_element+"._children",r.INVALID_SET_VALUE)}get audio(){return this._audio}set audio(audio){C.validateScorm12Audio(this._cmi_element+".audio",audio)&&(this._audio=audio)}get language(){return this._language}set language(language){C.validateScorm12Language(this._cmi_element+".language",language)&&(this._language=language)}get speed(){return this._speed}set speed(speed){C.validateScorm12Speed(this._cmi_element+".speed",speed)&&(this._speed=speed)}get text(){return this._text}set text(text){C.validateScorm12Text(this._cmi_element+".text",text)&&(this._text=text)}toJSON(){this.jsonString=!0;const result={audio:this.audio,language:this.language,speed:this.speed,text:this.text};return this.jsonString=!1,result}}class A extends L{constructor(){super({CMIElement:"cmi.interactions",children:s.interactions_children,errorCode:r.INVALID_SET_VALUE,errorClass:l})}}class x extends _{constructor(){super("cmi.interactions.n"),this._id="",this._time="",this._type="",this._weighting="",this._student_response="",this._result="",this._latency="",this.objectives=new L({CMIElement:"cmi.interactions.n.objectives",errorCode:r.INVALID_SET_VALUE,errorClass:l,children:"id,score,status"}),this.correct_responses=new L({CMIElement:"cmi.interactions.correct_responses",errorCode:r.INVALID_SET_VALUE,errorClass:l,children:"pattern"})}initialize(){super.initialize(),this.objectives?.initialize(),this.correct_responses?.initialize()}reset(){this._initialized=!1,this._id="",this._time="",this._type="",this._weighting="",this._student_response="",this._result="",this._latency="",this.objectives?.reset(),this.correct_responses?.reset()}get id(){if(!this.jsonString)throw new l(this._cmi_element+".id",r.WRITE_ONLY_ELEMENT);return this._id}set id(id){I(this._cmi_element+".id",id,n.CMIIdentifier)&&(this._id=id)}get time(){if(!this.jsonString)throw new l(this._cmi_element+".time",r.WRITE_ONLY_ELEMENT);return this._time}set time(time){I(this._cmi_element+".time",time,n.CMITime)&&(this._time=time)}get type(){if(!this.jsonString)throw new l(this._cmi_element+".type",r.WRITE_ONLY_ELEMENT);return this._type}set type(type){I(this._cmi_element+".type",type,n.CMIType)&&(this._type=type)}get weighting(){if(!this.jsonString)throw new l(this._cmi_element+".weighting",r.WRITE_ONLY_ELEMENT);return this._weighting}set weighting(weighting){I(this._cmi_element+".weighting",weighting,n.CMIDecimal)&&M(this._cmi_element+".weighting",weighting,"-100#100")&&(this._weighting=weighting)}get student_response(){if(!this.jsonString)throw new l(this._cmi_element+".student_response",r.WRITE_ONLY_ELEMENT);return this._student_response}set student_response(student_response){I(this._cmi_element+".student_response",student_response,"^.*$",!0)&&(this._student_response=student_response)}get result(){if(!this.jsonString)throw new l(this._cmi_element+".result",r.WRITE_ONLY_ELEMENT);return this._result}set result(result){I(this._cmi_element+".result",result,n.CMIResult)&&(this._result=result)}get latency(){if(!this.jsonString)throw new l(this._cmi_element+".latency",r.WRITE_ONLY_ELEMENT);return this._latency}set latency(latency){I(this._cmi_element+".latency",latency,n.CMITimespan)&&(this._latency=latency)}toJSON(){this.jsonString=!0;const result={id:this.id,time:this.time,type:this.type,weighting:this.weighting,student_response:this.student_response,result:this.result,latency:this.latency,objectives:this.objectives,correct_responses:this.correct_responses};return this.jsonString=!1,result}}class b extends _{constructor(){super("cmi.interactions.n.objectives.n"),this._id=""}reset(){this._initialized=!1,this._id=""}get id(){return this._id}set id(id){I(this._cmi_element+".id",id,n.CMIIdentifier)&&(this._id=id)}toJSON(){this.jsonString=!0;const result={id:this.id};return this.jsonString=!1,result}}class D extends _{constructor(){super("cmi.interactions.correct_responses.n"),this._pattern=""}reset(){this._initialized=!1,this._pattern=""}get pattern(){if(!this.jsonString)throw new l(this._cmi_element+".pattern",r.WRITE_ONLY_ELEMENT);return this._pattern}set pattern(pattern){I(this._cmi_element+".pattern",pattern,"^.*$",!0)&&(this._pattern=pattern)}toJSON(){this.jsonString=!0;const result={pattern:this._pattern};return this.jsonString=!1,result}}let z=class extends d{constructor(e,student_data,t){super("cmi"),this.__children="",this.__version="3.4",this._launch_data="",this._comments="",this._comments_from_lms="",t&&this.initialize(),this.__children=e||s.cmi_children,this.core=new w,this.objectives=new N,this.student_data=student_data||new R,this.student_preference=new T,this.interactions=new A}reset(){this._initialized=!1,this._launch_data="",this._comments="",this.core?.reset(),this.objectives=new N,this.interactions=new A,this.student_data?.reset(),this.student_preference?.reset()}initialize(){super.initialize(),this.core?.initialize(),this.objectives?.initialize(),this.student_data?.initialize(),this.student_preference?.initialize(),this.interactions?.initialize()}toJSON(){this.jsonString=!0;const result={suspend_data:this.suspend_data,launch_data:this.launch_data,comments:this.comments,comments_from_lms:this.comments_from_lms,core:this.core,objectives:this.objectives,student_data:this.student_data,student_preference:this.student_preference,interactions:this.interactions};return this.jsonString=!1,result}get _version(){return this.__version}set _version(_version){throw new l(this._cmi_element+"._version",r.INVALID_SET_VALUE)}get _children(){return this.__children}set _children(_children){throw new l(this._cmi_element+"._children",r.INVALID_SET_VALUE)}get suspend_data(){return this.core?.suspend_data}set suspend_data(suspend_data){this.core&&(this.core.suspend_data=suspend_data)}get launch_data(){return this._launch_data}set launch_data(launch_data){if(this.initialized)throw new l(this._cmi_element+".launch_data",r.READ_ONLY_ELEMENT);this._launch_data=launch_data}get comments(){return this._comments}set comments(comments){I(this._cmi_element+".comments",comments,n.CMIString4096,!0)&&(this._comments=comments)}get comments_from_lms(){return this._comments_from_lms}set comments_from_lms(comments_from_lms){if(this.initialized)throw new l(this._cmi_element+".comments_from_lms",r.READ_ONLY_ELEMENT);this._comments_from_lms=comments_from_lms}getCurrentTotalTime(){return this.core.getCurrentTotalTime(this.start_time)}};class F extends _{constructor(){super("cmi.nav"),this._event=""}reset(){this._event="",this._initialized=!1}get event(){return this._event}set event(e){(""===e||I(this._cmi_element+".event",e,n.NAVEvent))&&(this._event=e)}toJSON(){this.jsonString=!0;const result={event:this.event};return this.jsonString=!1,result}}const j={_:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,NONE:5},V={autocommit:!1,autocommitSeconds:10,asyncCommit:!1,sendFullCommit:!0,lmsCommitUrl:!1,dataCommitFormat:"json",commitRequestDataType:"application/json;charset=UTF-8",autoProgress:!1,logLevel:j.ERROR,selfReportSessionTime:!1,alwaysSendTotalTime:!1,renderCommonCommitFields:!1,strict_errors:!0,xhrHeaders:{},xhrWithCredentials:!1,fetchMode:"cors",useBeaconInsteadOfFetch:"never",responseHandler:async function(s){if(void 0!==s){let i=null;try{if("function"==typeof s.json)i=await s.json();else if("function"==typeof s.text){const e=await s.text();e&&(i=JSON.parse(e))}}catch(e){}return null!==i&&{}.hasOwnProperty.call(i,"result")?{result:i.result,errorCode:i.errorCode?i.errorCode:i.result===e?0:101}:200===s.status?{result:e,errorCode:0}:{result:t,errorCode:101}}return{result:t,errorCode:101}},requestHandler:function(e){return e},onLogMessage:$,scoItemIds:[],scoItemIdValidator:!1,globalObjectiveIds:[],enableOfflineSupport:!1,courseId:"",syncOnInitialize:!0,syncOnTerminate:!0,maxSyncAttempts:5};function $(e,t){switch(e){case"4":case 4:case"ERROR":case j.ERROR:console.error(t);break;case"3":case 3:case"WARN":case j.WARN:console.warn(t);break;case"2":case 2:case"INFO":case j.INFO:console.info(t);break;case"1":case 1:case"DEBUG":case j.DEBUG:console.debug?console.debug(t):console.log(t)}}class U{constructor(e,t,s){this._cancelled=!1,this._API=e,this._timeout=setTimeout(this.wrapper.bind(this),t),this._callback=s}cancel(){this._cancelled=!0,this._timeout&&clearTimeout(this._timeout)}wrapper(){this._cancelled||this._API.isInitialized()&&(async()=>{await this._API.commit(this._callback)})()}}class G{constructor(e,t){this.settings=e,this.error_codes=t}async processHttpRequest(e,s){let i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;const n={result:t,errorCode:this.error_codes.GENERAL||101};if(arguments.length>2&&void 0!==arguments[2]&&arguments[2])return this._handleImmediateRequest(e,s,i,r);try{const t=this.settings.requestHandler(s),i=await this.performFetch(e,t);return this.transformResponse(i,r)}catch(t){const s=t instanceof Error?t.message:t+"";i("processHttpRequest",`HTTP request failed to ${e}: ${s}`,j.ERROR),t instanceof Error&&t.stack&&i("processHttpRequest","Stack trace: "+t.stack,j.DEBUG);const o={...n,errorMessage:s,errorDetails:JSON.stringify({url:e,errorType:t instanceof Error?t.constructor.name:typeof t,originalError:s})};return r("CommitError"),o}}_handleImmediateRequest(t,s,i,r){if("never"!==this.settings.useBeaconInsteadOfFetch){const{body:e,contentType:i}=this._prepareRequestBody(s);navigator.sendBeacon(t,new Blob([e],{type:i}))}else this.performFetch(t,s).then(async e=>{await this.transformResponse(e,r)}).catch(e=>{i("processHttpRequest",e instanceof Error?e.message:e+"",j.ERROR),r("CommitError")});return{result:e,errorCode:0}}_prepareRequestBody(e){return{body:e instanceof Array?e.join("&"):JSON.stringify(e),contentType:e instanceof Array?"application/x-www-form-urlencoded":this.settings.commitRequestDataType}}async performFetch(e,t){if("always"===this.settings.useBeaconInsteadOfFetch)return this.performBeacon(e,t);const{body:s,contentType:i}=this._prepareRequestBody(t),r={method:"POST",mode:this.settings.fetchMode,body:s,headers:{...this.settings.xhrHeaders,"Content-Type":i},keepalive:!0};return this.settings.xhrWithCredentials&&(r.credentials="include"),fetch(e,r)}async performBeacon(e,t){const{body:s,contentType:i}=this._prepareRequestBody(t),r=navigator.sendBeacon(e,new Blob([s],{type:i}));return Promise.resolve({status:r?200:0,ok:r,json:async()=>({result:r?"true":"false",errorCode:r?0:this.error_codes.GENERAL}),text:async()=>JSON.stringify({result:r?"true":"false",errorCode:r?0:this.error_codes.GENERAL})})}async transformResponse(e,s){let result;try{result="function"==typeof this.settings.responseHandler?await this.settings.responseHandler(e):await e.json()}catch(s){const i=await e.text().catch(()=>"Unable to read response text");return{result:t,errorCode:this.error_codes.GENERAL||101,errorMessage:"Failed to parse LMS response: "+(s instanceof Error?s.message:s+""),errorDetails:JSON.stringify({status:e.status,statusText:e.statusText,url:e.url,responseText:i.substring(0,500),parseError:s instanceof Error?s.message:s+""})}}return Object.hasOwnProperty.call(result,"errorCode")||(result.errorCode=this._isSuccessResponse(e,result)?0:this.error_codes.GENERAL),this._isSuccessResponse(e,result)||(result.errorDetails={status:e.status,statusText:e.statusText,url:e.url,...result.errorDetails}),this._isSuccessResponse(e,result)?s("CommitSuccess"):s("CommitError",void 0,result.errorCode),result}_isSuccessResponse(t,result){const s=result.result;return!(200>t.status||t.status>299||!0!==s&&"true"!==s&&s!==e)}updateSettings(e){this.settings=e}}class P{constructor(e){this.listenerMap=new Map,this.listenerCount=0,this.apiLog=e}parseListenerName(e){const t=e.split(".");if(0===t.length)return null;const s=t[0];let i=null;return t.length>1&&(i=e.replace(s+".","")),{functionName:s??e,CMIElement:i}}on(e,t){if(!t)return;const s=e.split(" ");for(const e of s){const s=this.parseListenerName(e);if(!s)continue;const{functionName:i,CMIElement:r}=s,n=this.listenerMap.get(i)??[];n.push({functionName:i,CMIElement:r,callback:t}),this.listenerMap.set(i,n),this.listenerCount++,this.apiLog("on","Added event listener: "+this.listenerCount,j.INFO,i)}}off(e,t){if(!t)return;const s=e.split(" ");for(const e of s){const s=this.parseListenerName(e);if(!s)continue;const{functionName:i,CMIElement:r}=s,n=this.listenerMap.get(i);if(!n)continue;const o=n.findIndex(e=>e.CMIElement===r&&e.callback===t);-1!==o&&(n.splice(o,1),this.listenerCount--,0===n.length?this.listenerMap.delete(i):this.listenerMap.set(i,n),this.apiLog("off","Removed event listener: "+this.listenerCount,j.INFO,i))}}clear(e){const t=e.split(" ");for(const e of t){const t=this.parseListenerName(e);if(!t)continue;const{functionName:s,CMIElement:i}=t;if(this.listenerMap.has(s)){const e=this.listenerMap.get(s),t=e.filter(e=>e.CMIElement!==i);this.listenerCount-=e.length-t.length,0===t.length?this.listenerMap.delete(s):this.listenerMap.set(s,t)}}}processListeners(e,t,s){this.apiLog(e,s,j.INFO,t);const i=this.listenerMap.get(e);if(i)for(const r of i){const i=!!r.CMIElement;let n=!1;if(t&&r.CMIElement)if(r.CMIElement.endsWith("*")){const e=r.CMIElement.slice(0,-1);n=t.startsWith(e)}else n=r.CMIElement===t;i&&!n||(this.apiLog("processListeners","Processing listener: "+r.functionName,j.DEBUG,t),e.startsWith("Sequence")||"CommitError"===e?r.callback(s):"CommitSuccess"===e?r.callback():r.callback(t,s))}}reset(){this.listenerMap.clear(),this.listenerCount=0}}class k{loadFromFlattenedJSON(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;if(!i())return void console.error("loadFromFlattenedJSON can only be called before the call to lmsInitialize.");const n=/^(cmi\.interactions\.)(\d+)\.(.*)$/,o=/^(cmi\.objectives\.)(\d+)\.(.*)$/,interactions=[],objectives=[],a=[];for(const t in e)if({}.hasOwnProperty.call(e,t)){const s=t.match(n);if(s){interactions.push({key:t,value:e[t],index:+s[2],field:s[3]||""});continue}const i=t.match(o);if(i){objectives.push({key:t,value:e[t],index:+i[2],field:i[3]||""});continue}a.push({key:t,value:e[t]})}interactions.sort((e,t)=>e.index!==t.index?e.index-t.index:"id"===e.field?-1:"id"===t.field?1:"type"===e.field?-1:"type"===t.field?1:e.field.localeCompare(t.field)),objectives.sort((e,t)=>e.index!==t.index?e.index-t.index:"id"===e.field?-1:"id"===t.field?1:e.field.localeCompare(t.field)),a.sort((e,t)=>e.key.localeCompare(t.key));const c=e=>{e.forEach(e=>{const n={};n[e.key]=e.value,this.loadFromJSON(function(e){if(Object(e)!==e||Array.isArray(e))return e;const result={},pattern=/\.?([^.[\]]+)|\[(\d+)]/g;return Object.keys(e).filter(t=>({}.hasOwnProperty.call(e,t))).forEach(t=>{let s=result,i="";const r=RegExp(pattern);Array.from({length:t.match(RegExp(pattern,"g"))?.length??0},()=>r.exec(t)).forEach(e=>{e&&(s=s[i]??(s[i]=e[2]?[]:{}),i=e[2]||e[1]||"")}),s[i]=e[t]}),result[""]??result}(n),t,s,i,r)})};c(interactions),c(objectives),c(a)}loadFromJSON(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;if(i()){t=void 0!==t?t:"cmi",r(e);for(const n in e)if({}.hasOwnProperty.call(e,n)&&e[n]){const o=(t?t+".":"")+n,a=e[n];if(a.constructor===Array){for(let e=0;a.length>e;e++)if(a[e]){const t=a[e],n=`${o}.${e}`;t.constructor===Object?this.loadFromJSON(t,n,s,i,r):s(n,t)}}else a.constructor===Object?this.loadFromJSON(a,o,s,i,r):s(o,a)}}else console.error("loadFromJSON can only be called before the call to lmsInitialize.")}renderCMIToJSONString(cmi,e){return e?JSON.stringify({cmi:cmi}):JSON.stringify({cmi:cmi},(e,t)=>void 0===t?null:t,2)}renderCMIToJSONObject(cmi,e){return JSON.parse(this.renderCMIToJSONString(cmi,e))}getCommitObject(e,t,s,i,r,n){const o=t||e,a=s?i(e,o):r(e,o);return[j.DEBUG,"1",1,"DEBUG"].includes(n)&&(console.debug("Commit (terminated: "+(e?"yes":"no")+"): "),console.debug(a)),a}}class J{constructor(){this._logLevel=j.ERROR,this._logHandler=$}static getInstance(){return J._instance||(J._instance=new J),J._instance}setLogLevel(e){this._logLevel=e}getLogLevel(){return this._logLevel}setLogHandler(e){this._logHandler=e}log(e,t){this.shouldLog(e)&&this._logHandler(e,t)}error(e){this.log(j.ERROR,e)}warn(e){this.log(j.WARN,e)}info(e){this.log(j.INFO,e)}debug(e){this.log(j.DEBUG,e)}shouldLog(e){return this.getNumericLevel(e)>=this.getNumericLevel(this._logLevel)}getNumericLevel(e){if(void 0===e)return j.NONE;if("number"==typeof e)return e;switch(e){case"1":case"DEBUG":return j.DEBUG;case"2":case"INFO":return j.INFO;case"3":case"WARN":return j.WARN;case"4":case"ERROR":default:return j.ERROR;case"5":case"NONE":return j.NONE}}}function H(){return J.getInstance()}class Y{constructor(e,t,s,i){this._lastErrorCode="0",this._errorCodes=e,this._apiLog=t,this._getLmsErrorMessageDetails=s,this._loggingService=i||H()}get lastErrorCode(){return this._lastErrorCode}set lastErrorCode(e){this._lastErrorCode=e}throwSCORMError(e,t,s){s||(s=this._getLmsErrorMessageDetails(t,!0));const i=`SCORM Error ${t}: ${s}${e?` [Element: ${e}]`:""}`;this._apiLog("throwSCORMError",t+": "+s,j.ERROR,e),this._loggingService.error(i),this._lastErrorCode=t+""}clearSCORMError(e){void 0!==e&&e!==t&&(this._lastErrorCode="0")}handleValueAccessException(e,s,i){if(s instanceof c){const r=s;this._lastErrorCode=r.errorCode+"",this._loggingService.warn(`Validation Error ${r.errorCode}: ${r.message} [Element: ${e}]`),i=t}else if(s instanceof Error){const t=s.constructor.name;this._loggingService.error(`${t}: ${s.message} [Element: ${e}]\n${s.stack||""}`),this.throwSCORMError(e,this._errorCodes.GENERAL,`${t}: ${s.message}`)}else{this._loggingService.error(`Unknown error occurred while accessing [Element: ${e}]`);try{const e=JSON.stringify(s);this._loggingService.error("Error details: "+e)}catch(e){this._loggingService.error("Could not stringify error object for details")}this.throwSCORMError(e,this._errorCodes.GENERAL,"Unknown error")}return i}get errorCodes(){return this._errorCodes}}class B{constructor(e,t,s){this.apiLog=s,this.storeName="scorm_again_offline_data",this.syncQueue="scorm_again_sync_queue",this.isOnline=navigator.onLine,this.syncInProgress=!1,this.settings=e,this.error_codes=t,window.addEventListener("online",this.handleOnlineStatusChange.bind(this)),window.addEventListener("offline",this.handleOnlineStatusChange.bind(this))}handleOnlineStatusChange(){const e=this.isOnline;this.isOnline=navigator.onLine,!e&&this.isOnline?(this.apiLog("OfflineStorageService","Device is back online, attempting to sync...",j.INFO),this.syncOfflineData().then(e=>{e?this.apiLog("OfflineStorageService","Sync completed successfully",j.INFO):this.apiLog("OfflineStorageService","Sync failed",j.ERROR)},e=>{this.apiLog("OfflineStorageService","Error during sync: "+e,j.ERROR)})):e&&!this.isOnline&&this.apiLog("OfflineStorageService","Device is offline, data will be stored locally",j.INFO)}async storeOffline(s,i){try{const t={id:`${s}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,courseId:s,timestamp:Date.now(),data:i,syncAttempts:0},r=await this.getFromStorage(this.syncQueue)||[];return r.push(t),await this.saveToStorage(this.syncQueue,r),await this.saveToStorage(`${this.storeName}_${s}`,i),this.apiLog("OfflineStorageService","Stored data offline for course "+s,j.INFO),{result:e,errorCode:0}}catch(e){return this.apiLog("OfflineStorageService","Error storing offline data: "+e,j.ERROR),{result:t,errorCode:this.error_codes.GENERAL??0}}}async getOfflineData(e){try{return await this.getFromStorage(`${this.storeName}_${e}`)||null}catch(e){return this.apiLog("OfflineStorageService","Error retrieving offline data: "+e,j.ERROR),null}}async syncOfflineData(){if(this.syncInProgress||!this.isOnline)return!1;this.syncInProgress=!0;try{const t=await this.getFromStorage(this.syncQueue)||[];if(0===t.length)return this.syncInProgress=!1,!0;this.apiLog("OfflineStorageService",`Found ${t.length} items to sync`,j.INFO);const s=[];for(const i of t)if(5>i.syncAttempts)try{(await this.sendDataToLMS(i.data)).result===e?this.apiLog("OfflineStorageService","Successfully synced item "+i.id,j.INFO):(i.syncAttempts++,s.push(i),this.apiLog("OfflineStorageService",`Failed to sync item ${i.id}, attempt #${i.syncAttempts}`,j.WARN))}catch(e){i.syncAttempts++,s.push(i),this.apiLog("OfflineStorageService",`Error syncing item ${i.id}: ${e}`,j.ERROR)}else this.apiLog("OfflineStorageService",`Skipping item ${i.id} after 5 failed attempts`,j.WARN);return await this.saveToStorage(this.syncQueue,s),this.apiLog("OfflineStorageService",`Sync completed. ${t.length-s.length} items synced, ${s.length} items remaining`,j.INFO),this.syncInProgress=!1,!0}catch(e){return this.apiLog("OfflineStorageService","Error during sync process: "+e,j.ERROR),this.syncInProgress=!1,!1}}async sendDataToLMS(s){if(!this.settings.lmsCommitUrl)return{result:t,errorCode:this.error_codes.GENERAL||101};try{const t=this.settings.requestHandler(s),i={method:"POST",mode:this.settings.fetchMode,body:JSON.stringify(t),headers:{...this.settings.xhrHeaders,"Content-Type":this.settings.commitRequestDataType}};this.settings.xhrWithCredentials&&(i.credentials="include");const r=await fetch(this.settings.lmsCommitUrl,i),result="function"==typeof this.settings.responseHandler?await this.settings.responseHandler(r):await r.json();return 200>r.status||r.status>299||!0!==result.result&&result.result!==e?(Object.hasOwnProperty.call(result,"errorCode")||(result.errorCode=this.error_codes.GENERAL),result):(Object.hasOwnProperty.call(result,"errorCode")||(result.errorCode=0),result)}catch(e){return this.apiLog("OfflineStorageService","Error sending data to LMS: "+e,j.ERROR),{result:t,errorCode:this.error_codes.GENERAL||101}}}isDeviceOnline(){return this.isOnline}async getFromStorage(e){const t=localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return null}return null}async saveToStorage(e,t){localStorage.setItem(e,JSON.stringify(t))}async hasPendingOfflineData(e){return(await this.getFromStorage(this.syncQueue)||[]).some(t=>t.courseId===e)}updateSettings(e){this.settings=e}}class q{constructor(e,t,s,i,r,n,o,a,c){if(this._settings=V,this._courseId="",new.target===q)throw new TypeError("Cannot construct BaseAPI instances directly");this.currentState=0,this._error_codes=e,t&&(this.settings={...V,...t}),this._loggingService=a||H(),this._loggingService.setLogLevel(this.settings.logLevel),this._loggingService.setLogHandler(this.settings.onLogMessage?this.settings.onLogMessage:$),this._httpService=s||new G(this.settings,this._error_codes),this._eventService=i||new P((e,t,s,i)=>this.apiLog(e,t,s,i)),this._serializationService=r||new k,this._errorHandlingService=o||new Y(this._error_codes,(e,t,s,i)=>this.apiLog(e,t,s||j.ERROR,i),(e,t)=>this.getLmsErrorMessageDetails(e,t),void 0),this.settings.enableOfflineSupport&&(this._offlineStorageService=c||new B(this.settings,this._error_codes,(e,t,s,i)=>this.apiLog(e,t,s,i)),this.settings.courseId&&(this._courseId=this.settings.courseId),this._offlineStorageService&&this._courseId&&this._offlineStorageService.getOfflineData(this._courseId).then(e=>{e&&(this.apiLog("constructor","Found offline data to restore",j.INFO),this.loadFromJSON(e.runtimeData))}).catch(e=>{this.apiLog("constructor","Error retrieving offline data: "+e,j.ERROR)}))}get lastErrorCode(){return this._errorHandlingService?.lastErrorCode??"0"}set lastErrorCode(e){this._errorHandlingService&&(this._errorHandlingService.lastErrorCode=e)}get eventService(){return this._eventService}get loggingService(){return this._loggingService}commonReset(e){this.apiLog("reset","Called",j.INFO),this.settings={...this.settings,...e},this.clearScheduledCommit(),this.currentState=0,this.lastErrorCode="0",this._eventService.reset(),this.startingData={},this._offlineStorageService&&(this._offlineStorageService.updateSettings(this.settings),e?.courseId&&(this._courseId=e.courseId))}initialize(s,i,r){let n=t;return this.isInitialized()?this.throwSCORMError("api",this._error_codes.INITIALIZED,i):this.isTerminated()?this.throwSCORMError("api",this._error_codes.TERMINATED,r):(this.settings.selfReportSessionTime&&this.cmi.setStartTime(),this.currentState=1,this.lastErrorCode="0",n=e,this.processListeners(s),this.settings.enableOfflineSupport&&this._offlineStorageService&&this._courseId&&this.settings.syncOnInitialize&&this._offlineStorageService.isDeviceOnline()&&this._offlineStorageService.hasPendingOfflineData(this._courseId).then(e=>{e&&(this.apiLog(s,"Syncing pending offline data on initialization",j.INFO),this._offlineStorageService?.syncOfflineData().then(e=>{e&&(this.apiLog(s,"Successfully synced offline data",j.INFO),this.processListeners("OfflineDataSynced"))}))})),this.apiLog(s,"returned: "+n,j.INFO),this.clearSCORMError(n),n}apiLog(e,t,s,i){t=function(e,t,s){let i=e.padEnd(20)+": ";return s&&(i+=s,i=i.padEnd(70)),i+=t??"",i}(e,t,i),this._loggingService.log(s,t)}get settings(){return this._settings}set settings(e){const t=this._settings;this._settings={...this._settings,...e},this._httpService?.updateSettings(this._settings),void 0!==e.logLevel&&e.logLevel!==t.logLevel&&this._loggingService?.setLogLevel(e.logLevel),void 0!==e.onLogMessage&&e.onLogMessage!==t.onLogMessage&&this._loggingService?.setLogHandler(e.onLogMessage)}async terminate(s,i){let r=t;if(this.checkState(i,this._error_codes.TERMINATION_BEFORE_INIT??0,this._error_codes.MULTIPLE_TERMINATION??0)){this.currentState=2,this.settings.enableOfflineSupport&&this._offlineStorageService&&this._courseId&&this.settings.syncOnTerminate&&this._offlineStorageService.isDeviceOnline()&&await this._offlineStorageService.hasPendingOfflineData(this._courseId)&&(this.apiLog(s,"Syncing pending offline data before termination",j.INFO),await this._offlineStorageService.syncOfflineData());const result=await this.storeData(!0);(result.errorCode??0)>0&&(result.errorMessage&&this.apiLog("terminate","Terminate failed with error: "+result.errorMessage,j.ERROR),result.errorDetails&&this.apiLog("terminate","Error details: "+JSON.stringify(result.errorDetails),j.DEBUG),this.throwSCORMError("api",result.errorCode??0)),r=result?.result??t,i&&(this.lastErrorCode="0"),r=e,this.processListeners(s)}return this.apiLog(s,"returned: "+r,j.INFO),this.clearSCORMError(r),r}getValue(e,t,s){let i="";if(this.checkState(t,this._error_codes.RETRIEVE_BEFORE_INIT??0,this._error_codes.RETRIEVE_AFTER_TERM??0)){try{i=this.getCMIValue(s)}catch(e){i=this.handleValueAccessException(s,e,i)}this.processListeners(e,s)}return this.apiLog(e,": returned: "+i,j.INFO,s),void 0===i?"":("0"===this.lastErrorCode&&this.clearSCORMError(i),i)}setValue(e,s,i,r,n){void 0!==n&&(n+="");let o=t;if(this.checkState(i,this._error_codes.STORE_BEFORE_INIT??0,this._error_codes.STORE_AFTER_TERM??0)){try{o=this.setCMIValue(r,n)}catch(e){o=this.handleValueAccessException(r,e,o)}this.processListeners(e,r,n)}return void 0===o&&(o=t),this.lastErrorCode+""=="0"&&this.settings.autocommit&&this.scheduleCommit(1e3*this.settings.autocommitSeconds,s),this.apiLog(e,": "+n+": result: "+o,j.INFO,r),"0"===this.lastErrorCode&&this.clearSCORMError(o),o}async commit(e){let s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.clearScheduledCommit();let i=t;if(this.checkState(s,this._error_codes.COMMIT_BEFORE_INIT??0,this._error_codes.COMMIT_AFTER_TERM??0)){const result=await this.storeData(!1);(result.errorCode??0)>0&&(result.errorMessage&&this.apiLog("commit","Commit failed with error: "+result.errorMessage,j.ERROR),result.errorDetails&&this.apiLog("commit","Error details: "+JSON.stringify(result.errorDetails),j.DEBUG),this.throwSCORMError("api",result.errorCode)),i=result?.result??t,this.apiLog(e," Result: "+i,j.DEBUG,"HttpRequest"),s&&(this.lastErrorCode="0"),this.processListeners(e),this.settings.enableOfflineSupport&&this._offlineStorageService&&this._offlineStorageService.isDeviceOnline()&&this._courseId&&this._offlineStorageService.hasPendingOfflineData(this._courseId).then(t=>{t&&(this.apiLog(e,"Syncing pending offline data",j.INFO),this._offlineStorageService?.syncOfflineData().then(t=>{t?(this.apiLog(e,"Successfully synced offline data",j.INFO),this.processListeners("OfflineDataSynced")):this.apiLog(e,"Failed to sync some offline data",j.WARN)}))})}return this.apiLog(e,"returned: "+i,j.INFO),"0"===this.lastErrorCode&&this.clearSCORMError(i),i}getLastError(e){const t=this.lastErrorCode+"";return this.processListeners(e),this.apiLog(e,"returned: "+t,j.INFO),t}getErrorString(e,t){let s="";return null!==t&&""!==t&&(s=this.getLmsErrorMessageDetails(t),this.processListeners(e)),this.apiLog(e,"returned: "+s,j.INFO),s}getDiagnostic(e,t){let s="";return null!==t&&""!==t&&(s=this.getLmsErrorMessageDetails(t,!0),this.processListeners(e)),this.apiLog(e,"returned: "+s,j.INFO),s}checkState(e,t,s){return this.isNotInitialized()?(this.throwSCORMError("api",t),!1):!e||!this.isTerminated()||(this.throwSCORMError("api",s),!1)}getLmsErrorMessageDetails(e){throw Error("The getLmsErrorMessageDetails method has not been implemented")}getCMIValue(e){throw Error("The getCMIValue method has not been implemented")}setCMIValue(e,t){throw Error("The setCMIValue method has not been implemented")}_commonSetCMIValue(s,i,r,n){if(!r||""===r)return t;this.lastErrorCode="0";const o=r.split(".");let a=this,c=t,h=!1;const l=`The data model element passed to ${s} (${r}) is not a valid SCORM data model element.`,_=i?this._error_codes.UNDEFINED_DATA_MODEL:this._error_codes.GENERAL;for(let t=0;o.length>t;t++){const s=o[t];if(t===o.length-1)if(i&&s&&"{target="===s.substring(0,8)){if(this.isInitialized()){this.throwSCORMError(r,this._error_codes.READ_ONLY_ELEMENT);break}a={...a,attribute:n}}else{if(void 0===s||!this._checkObjectHasProperty(a,s)){this.throwSCORMError(r,_,l);break}if(E(r,"\\.correct_responses\\.\\d+$")&&this.isInitialized()&&"pattern"!==s&&(this.validateCorrectResponse(r,n),"0"!==this.lastErrorCode)){this.throwSCORMError(r,this._error_codes.TYPE_MISMATCH);break}if(!i||"0"===this._errorHandlingService.lastErrorCode){if(void 0===s||"__proto__"===s||"constructor"===s){this.throwSCORMError(r,_,l);break}a[s]=n,c=e}}else{if(void 0===s||!this._checkObjectHasProperty(a,s)){this.throwSCORMError(r,_,l);break}if(a=a[s],!a){this.throwSCORMError(r,_,l);break}if(a instanceof L){const e=parseInt(o[t+1]||"0",10);if(!isNaN(e)){const s=a.childArray[e];if(s)a=s,h=!0;else{const t=this.getChildElement(r,n,h);if(h=!0,!t){"0"===this.lastErrorCode&&this.throwSCORMError(r,_,l);break}a.initialized&&t.initialize(),a.childArray[e]=t,a=t}t++}}}}return c===t&&this.apiLog(s,`There was an error setting the value for: ${r}, value of: ${n}`,j.WARN),c}_commonGetCMIValue(e,t,s){if(!s||""===s)return"";const i=s.split(".");let r=this,n=null;const o=`The data model element passed to ${e} (${s}) has not been initialized.`,a=`The data model element passed to ${e} (${s}) is not a valid SCORM data model element.`,c=t?this._error_codes.UNDEFINED_DATA_MODEL:this._error_codes.GENERAL;for(let e=0;i.length>e;e++){if(n=i[e],t){if("{target="===(n+"").substring(0,8)&&"function"==typeof r._isTargetValid)return r._isTargetValid((n+"").substring(8,(n+"").length-9));if(void 0===n||!this._checkObjectHasProperty(r,n))return void this.throwSCORMError(s,c,a)}else if(e===i.length-1&&(void 0===n||!this._checkObjectHasProperty(r,n)))return void this.throwSCORMError(s,c,a);if(null==n){this.throwSCORMError(s,c,a);break}if(r=r[n],void 0===r){this.throwSCORMError(s,c,a);break}if(r instanceof L){const t=parseInt(i[e+1]||"",10);if(!isNaN(t)){const i=r.childArray[t];if(!i){this.throwSCORMError(s,this._error_codes.VALUE_NOT_INITIALIZED,o);break}r=i,e++}}}if(null!=r)return r;t||("_children"===n?this.throwSCORMError(s,this._error_codes.CHILDREN_ERROR,void 0):"_count"===n&&this.throwSCORMError(s,this._error_codes.COUNT_ERROR,void 0))}isInitialized(){return 1===this.currentState}isNotInitialized(){return 0===this.currentState}isTerminated(){return 2===this.currentState}on(e,t){this._eventService.on(e,t)}off(e,t){this._eventService.off(e,t)}clear(e){this._eventService.clear(e)}processListeners(e,t,s){this._eventService.processListeners(e,t,s)}throwSCORMError(e,t,s){this._errorHandlingService.throwSCORMError(e,t??0,s)}clearSCORMError(e){this._errorHandlingService.clearSCORMError(e)}loadFromFlattenedJSON(e,t){t||(t=""),this._serializationService.loadFromFlattenedJSON(e,t,(e,t)=>this.setCMIValue(e,t),()=>this.isNotInitialized(),e=>{this.startingData=e})}getFlattenedCMI(){return g(this.renderCMIToJSONObject())}loadFromJSON(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";t&&""!==t||Object.hasOwnProperty.call(e,"cmi")||Object.hasOwnProperty.call(e,"adl")||(t="cmi"),this._serializationService.loadFromJSON(