scorm-again
Version:
A modern SCORM JavaScript run-time library for SCORM 1.2 and SCORM 2004
1 lines • 85 kB
JavaScript
this.Scorm12API=function(){"use strict";const e=e=>{if(!e||0>=e)return"00:00:00";const t=Math.floor(e/3600),i=new Date(1e3*e),s=i.getUTCMinutes(),n=i.getSeconds(),o=e%1;let a="";return r(o)>0&&(a=r(o)>2?o.toFixed(2):o+"",a="."+a.split(".")[1]),(t+":"+s+":"+n).replace(/\b\d\b/g,"0$&")+a},t=o((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 i=e.split(":");return 3600*+i[0]+60*+i[1]+ +i[2]},(e,t)=>`${"string"==typeof e?e:(e??"")+""}:${"string"==typeof t?t:t?.toString()??""}`),i=o((e,t)=>{if("string"==typeof t&&(t=RegExp(t)),!e||!e?.match?.(t))return 0;const[,i,s,r,n,o,a,c]=RegExp(t).exec?.(e)??[];let result=0;return result+=+c||0,result+=60*+a||0,result+=3600*+o||0,result+=86400*+n||0,result+=604800*+r||0,result+=2592e3*+s||0,result+=31536e3*+i||0,result},(e,t)=>`${e??""}:${"string"==typeof t?t:t?.toString()??""}`);function s(e){const result={};return function e(t,i){if(Object(t)!==t)result[i]=t;else if(Array.isArray(t))t.forEach((t,s)=>{e(t,`${i}[${s}]`)}),0===t.length&&(result[i]=[]);else{const s=Object.keys(t).filter(e=>({}.hasOwnProperty.call(t,e))),r=0===s.length;s.forEach(s=>{e(t[s],i?`${i}.${s}`:s)}),r&&i&&(result[i]={})}}(e,""),result}function r(e){if(Math.floor(e)===e||0>(e+"")?.indexOf?.("."))return 0;const t=(""+e).split(".")?.[1];return t?.length??0}function n(e,t){return"string"==typeof e&&RegExp(t).test(e)}function o(e,t){const i=new Map;return function(){for(var s=arguments.length,r=Array(s),n=0;s>n;n++)r[n]=arguments[n];const o=t?t(...r):JSON.stringify(r);return i.has(o)?i.get(o):(()=>{const result=e(...r);return i.set(o,result),result})()}}var a=Object.defineProperty,c=(e,t,i)=>((e,t,i)=>t in e?a(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class l{constructor(e){c(this,"jsonString",!1),c(this,"_cmi_element"),c(this,"_initialized",!1),this._cmi_element=e}get initialized(){return this._initialized}initialize(){this._initialized=!0}}class h extends l{constructor(){super(...arguments),c(this,"_start_time")}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()}}var d=Object.defineProperty,u=(e,t,i)=>((e,t,i)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class _ extends Error{constructor(e,t){super(`${e} : ${""+t}`),u(this,"_errorCode"),this._errorCode=t,Object.setPrototypeOf(this,_.prototype)}get errorCode(){return this._errorCode}}class m extends _{constructor(e,t,i,s){super(e,t),u(this,"_errorMessage"),u(this,"_detailedMessage",""),this.message=`${e} : ${i}`,this._errorMessage=i,s&&(this._detailedMessage=s),Object.setPrototypeOf(this,m.prototype)}get errorMessage(){return this._errorMessage}get detailedMessage(){return this._detailedMessage}}const g="true",f="false",p="raw,min,max",E="id,score,status",S={0:{basicMessage:"No Error",detailMessage:"No error occurred, the previous API call was successful."},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."}},v=S;class y extends m{constructor(e,t){!{}.hasOwnProperty.call(v,t+"")?super(e,101,v[101]?.basicMessage,v[101]?.detailMessage):super(e,t,v[t+""]?.basicMessage||"Unknown error",v[t+""]?.detailMessage),Object.setPrototypeOf(this,y.prototype)}}const O={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};var C=Object.defineProperty,b=(e,t,i)=>((e,t,i)=>t in e?C(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class R extends l{constructor(e){super(e.CMIElement),b(this,"_errorCode"),b(this,"_errorClass"),b(this,"__children"),b(this,"childArray"),this.__children=e.children,this._errorCode=e.errorCode??O.GENERAL,this._errorClass=e.errorClass||_,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}}const L="passed",N="completed",M="unknown",w={_:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,NONE:5},I={autocommit:!1,autocommitSeconds:10,throttleCommits:!1,useAsynchronousCommits:!1,sendFullCommit:!0,lmsCommitUrl:!1,dataCommitFormat:"json",commitRequestDataType:"application/json;charset=UTF-8",autoProgress:!1,logLevel:w.ERROR,selfReportSessionTime:!1,alwaysSendTotalTime:!1,renderCommonCommitFields:!1,autoCompleteLessonStatus:!1,strict_errors:!0,xhrHeaders:{},xhrWithCredentials:!1,fetchMode:"cors",asyncModeBeaconBehavior:"never",responseHandler:async function(e){if(void 0!==e){let t=null;try{if("function"==typeof e.json)t=await e.json();else if("function"==typeof e.text){const i=await e.text();i&&(t=JSON.parse(i))}}catch(e){}return null!==t&&{}.hasOwnProperty.call(t,"result")?{result:t.result,errorCode:"number"==typeof t.errorCode?t.errorCode:!0===t.result||t.result===g?0:101}:200===e.status?{result:g,errorCode:0}:{result:f,errorCode:101}}return{result:f,errorCode:101}},xhrResponseHandler:function(e){if(void 0!==e){let t=null;if(200>e.status||e.status>299)return{result:f,errorCode:101};try{t=JSON.parse(e.responseText)}catch(e){}return null!==t&&{}.hasOwnProperty.call(t,"result")?{result:t.result,errorCode:"number"==typeof t.errorCode?t.errorCode:!0===t.result||t.result===g?0:101}:{result:g,errorCode:0}}return{result:f,errorCode:101}},requestHandler:function(e){return e},onLogMessage:T,mastery_override:!1,score_overrides_status:!1,completion_status_on_failed:"completed",scoItemIds:[],scoItemIdValidator:!1,globalObjectiveIds:[],enableOfflineSupport:!1,courseId:"",syncOnInitialize:!0,syncOnTerminate:!0,maxSyncAttempts:5,scoId:"",autoPopulateCommitMetadata:!1,httpService:null,globalStudentPreferences:!1};function T(e,t){switch(e){case"4":case 4:case"ERROR":case w.ERROR:console.error(t);break;case"3":case 3:case"WARN":case w.WARN:console.warn(t);break;case"2":case 2:case"INFO":case w.INFO:console.info(t);break;case"1":case 1:case"DEBUG":case w.DEBUG:console.debug?console.debug(t):console.log(t)}}const A="^[\\s\\S]{0,255}$",x="^([0-9]+):([0-9]{2}):([0-9]{2})(\\.\\d{1,2})?$",D="^-?([0-9]+)$",j="^-?([0-9]{0,10})(\\.[0-9]*)?$",F="^[\\u0021-\\u007E\\s]{0,255}$",P="^.*$",V="^(passed|completed|failed|incomplete|browsed|not attempted)$",k="0#100",U="^P(?:([.,\\d]+)Y)?(?:([.,\\d]+)M)?(?:([.,\\d]+)W)?(?:([.,\\d]+)D)?(?:T?(?:([.,\\d]+)H)?(?:([.,\\d]+)M)?(?:(\\d+(?:\\.\\d{1,2})?)S)?)?$";var z=Object.defineProperty,G=(e,t,i)=>((e,t,i)=>t in e?z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ${constructor(e,t,i){G(this,"_API"),G(this,"_cancelled",!1),G(this,"_timeout"),G(this,"_callback"),this._API=e,this._timeout=setTimeout(this.wrapper.bind(this),t),this._callback=i}cancel(){this._cancelled=!0,this._timeout&&clearTimeout(this._timeout)}wrapper(){this._cancelled||this._API.isInitialized()&&(async()=>{await this._API.commit(this._callback)})()}}var H=Object.defineProperty,B=(e,t,i)=>((e,t,i)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);const q=class e extends l{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"always",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Map;super("ruleCondition"),B(this,"_condition","always"),B(this,"_operator",null),B(this,"_parameters",new Map),B(this,"_referencedObjective",null),this._condition=e,this._operator=t,this._parameters=i}static setNowProvider(t){"function"==typeof t&&(e._now=t)}static setElapsedSecondsHook(t){e._getElapsedSecondsHook=t}reset(){this._initialized=!1,this._condition="always",this._operator=null,this._parameters=new Map}get condition(){return this._condition}set condition(e){this._condition=e}get operator(){return this._operator}set operator(e){this._operator=e}get parameters(){return this._parameters}set parameters(e){this._parameters=e}get referencedObjective(){return this._referencedObjective}set referencedObjective(e){this._referencedObjective=e}resolveReferencedObjective(e){return this._referencedObjective?e.primaryObjective?.id===this._referencedObjective?e.primaryObjective:(e.objectives||[]).find(e=>e.id===this._referencedObjective)||null:null}evaluate(e){let result;const t=this.resolveReferencedObjective(e);switch(this._condition){case"satisfied":case"objectiveSatisfied":result=t?!0===t.satisfiedStatus:e.successStatus===L||!0===e.objectiveSatisfiedStatus;break;case"objectiveStatusKnown":case"objectiveMeasureKnown":result=t?!!t.measureStatus:!!e.objectiveMeasureStatus;break;case"objectiveMeasureGreaterThan":{const i=this._parameters.get("threshold")||0;result=!!(t?t.measureStatus:e.objectiveMeasureStatus)&&(t?t.normalizedMeasure:e.objectiveNormalizedMeasure)>i;break}case"objectiveMeasureLessThan":{const i=this._parameters.get("threshold")||0;result=!!(t?t.measureStatus:e.objectiveMeasureStatus)&&i>(t?t.normalizedMeasure:e.objectiveNormalizedMeasure);break}case"completed":case"activityCompleted":result=t?t.completionStatus===N:e.isCompleted;break;case"progressKnown":case"activityProgressKnown":result=t?t.completionStatus!==M:"unknown"!==e.completionStatus;break;case"attempted":result=e.attemptCount>0;break;case"attemptLimitExceeded":result=e.hasAttemptLimitExceeded();break;case"timeLimitExceeded":result=this.evaluateTimeLimitExceeded(e);break;case"outsideAvailableTimeRange":result=this.evaluateOutsideAvailableTimeRange(e);break;case"always":result=!0;break;default:result=!1}return"not"===this._operator&&(result=!result),result}evaluateTimeLimitExceeded(t){let s=t.timeLimitDuration;if(!s&&t.attemptAbsoluteDurationLimit&&(s=t.attemptAbsoluteDurationLimit),!s)return!1;const r=i(s,U);if(0>=r)return!1;let n=0;if(e._getElapsedSecondsHook)try{const i=e._getElapsedSecondsHook(t);"number"!=typeof i||Number.isNaN(i)||0>i||(n=i)}catch{n=0}if(0===n&&t.attemptExperiencedDuration){const e=i(t.attemptExperiencedDuration,U);e>0&&(n=e)}if(0===n&&t.attemptAbsoluteStartTime)try{const i=new Date(t.attemptAbsoluteStartTime).getTime(),s=e._now().getTime();Number.isNaN(i)||Number.isNaN(s)||i>s||(n=(s-i)/1e3)}catch{n=0}return n>r}evaluateOutsideAvailableTimeRange(t){const i=t.beginTimeLimit,s=t.endTimeLimit;if(!i&&!s)return!1;const r=e._now();return!(!i||r>=new Date(i))||!(!s||new Date(s)>=r)}parseISO8601Duration(e){return 1e3*i(e,U)}toJSON(){this.jsonString=!0;const result={condition:this._condition,operator:this._operator,parameters:Object.fromEntries(this._parameters)};return this.jsonString=!1,result}};B(q,"_now",()=>new Date),B(q,"_getElapsedSecondsHook");var J=(e=>(e.NEVER="never",e.ONCE="once",e.ON_EACH_NEW_ATTEMPT="onEachNewAttempt",e))(J||{}),W=(e=>(e.NEVER="never",e.ONCE="once",e.ON_EACH_NEW_ATTEMPT="onEachNewAttempt",e))(W||{});class Y{static selectChildrenProcess(e){const t=e.sequencingControls,i=[...e.children];if(t.selectionTiming===J.NEVER)return i;if(t.selectionTiming===J.ONCE&&t.selectionCountStatus)return i;if(t.selectionTiming!==J.ONCE&&!t.selectionCountStatus)return i;const s=t.selectCount;if(null===s||s>=i.length)return t.selectionTiming===J.ONCE&&(t.selectionCountStatus=!0),i;const r=[],n=i.map((e,t)=>t);for(let e=0;s>e&&0!==n.length;e++){const e=Math.floor(Math.random()*n.length),t=n[e];void 0!==t&&i[t]&&r.push(i[t]),n.splice(e,1)}t.selectionTiming===J.ONCE&&(t.selectionCountStatus=!0);for(const e of i)r.includes(e)||(e.isHiddenFromChoice=!0,e.isAvailable=!1);return r}static randomizeChildrenProcess(e){const t=e.sequencingControls,i=[...e.children];if(t.randomizationTiming===W.NEVER)return i;if(t.randomizationTiming===W.ONCE&&t.reorderChildren)return i;if(!t.randomizeChildren)return i;const s=[...i];for(let e=s.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1)),i=s[e],r=s[t];i&&r&&(s[e]=r,s[t]=i)}return t.randomizationTiming===W.ONCE&&(t.reorderChildren=!0),e.children.length=0,e.children.push(...s),s}static applySelectionAndRandomization(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=e.sequencingControls;if(!t&&(e.isActive||e.isSuspended))return e.children;let s=!1,r=!1;i.selectionTiming===J.ON_EACH_NEW_ATTEMPT?(s=t,t&&(i.selectionCountStatus=!0)):i.selectionTiming===J.ONCE&&(s=!i.selectionCountStatus),i.randomizationTiming===W.ON_EACH_NEW_ATTEMPT?(r=t,t&&(i.reorderChildren=!1)):i.randomizationTiming===W.ONCE&&(r=!i.reorderChildren),s&&this.selectChildrenProcess(e),r&&this.randomizeChildrenProcess(e);const n=e.children.filter(e=>e.isAvailable);return e.setProcessedChildren(n),n}static isSelectionNeeded(e){const t=e.sequencingControls;return t.selectionTiming!==J.NEVER&&(t.selectionTiming!==J.ONCE||!t.selectionCountStatus)&&null!==t.selectCount&&e.children.length>t.selectCount}static isRandomizationNeeded(e){const t=e.sequencingControls;return t.randomizationTiming!==W.NEVER&&(t.randomizationTiming!==W.ONCE||!t.reorderChildren)&&t.randomizeChildren}}var Q=Object.defineProperty,Z=(e,t,i)=>((e,t,i)=>t in e?Q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class K{constructor(e,t){Z(this,"settings"),Z(this,"error_codes"),this.settings=e,this.error_codes=t}processHttpRequest(e,t){return this._performAsyncRequest(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0,arguments.length>4?arguments[4]:void 0),{result:g,errorCode:0}}async _performAsyncRequest(e,t,i,s,r){try{const s=this.settings.requestHandler(t);let n;n=i&&"never"!==this.settings.asyncModeBeaconBehavior?await this.performBeacon(e,s):await this.performFetch(e,s);const result=await this.transformResponse(n,r);this._isSuccessResponse(n,result)?r("CommitSuccess"):r("CommitError",void 0,result.errorCode)}catch(e){s("processHttpRequest","Async request failed: "+(e instanceof Error?e.message:e+""),w.ERROR),r("CommitError")}}_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.asyncModeBeaconBehavior)return this.performBeacon(e,t);const{body:i,contentType:s}=this._prepareRequestBody(t),r={method:"POST",mode:this.settings.fetchMode,body:i,headers:{...this.settings.xhrHeaders,"Content-Type":s},keepalive:!0};return this.settings.xhrWithCredentials&&(r.credentials="include"),fetch(e,r)}async performBeacon(e,t){const{body:i,contentType:s}=this._prepareRequestBody(t),r=navigator.sendBeacon(e,new Blob([i],{type:s}));return Promise.resolve({status:r?200:0,ok:r,json:async()=>({result:r?"true":"false",errorCode:r?0:this.error_codes.GENERAL_COMMIT_FAILURE||391}),text:async()=>JSON.stringify({result:r?"true":"false",errorCode:r?0:this.error_codes.GENERAL_COMMIT_FAILURE||391})})}async transformResponse(e,t){let result;try{result="function"==typeof this.settings.responseHandler?await this.settings.responseHandler(e):await e.json()}catch(t){const i=await e.text().catch(()=>"Unable to read response text");return{result:f,errorCode:this.error_codes.GENERAL_COMMIT_FAILURE||391,errorMessage:"Failed to parse LMS response: "+(t instanceof Error?t.message:t+""),errorDetails:JSON.stringify({status:e.status,statusText:e.statusText,url:e.url,responseText:i.substring(0,500),parseError:t instanceof Error?t.message:t+""})}}return Object.hasOwnProperty.call(result,"errorCode")||(result.errorCode=this._isSuccessResponse(e,result)?0:this.error_codes.GENERAL_COMMIT_FAILURE||391),this._isSuccessResponse(e,result)||(result.errorDetails={status:e.status,statusText:e.statusText,url:e.url,...result.errorDetails}),result}_isSuccessResponse(e,result){const t=result.result;return!(200>e.status||e.status>299||!0!==t&&"true"!==t&&t!==g)}updateSettings(e){this.settings=e}}var X=Object.defineProperty;const ee="{target=";function te(e,t){const i=e[t];return void 0===i?(void 0!==console&&console.warn&&console.warn("CMIValueAccessService: Unknown error code key: "+t),e.GENERAL??0):i}class ie{constructor(e){var t;((e,t,i)=>{t in e?X(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i})(this,"context"+"",t),this.context=e}getUndefinedDataModelErrorCode(e){return te(this.context.errorCodes,e?"UNDEFINED_DATA_MODEL":"GENERAL")}setCMIValue(e,t,i,s){if(!i||""===i)return t&&this.context.throwSCORMError(i,te(this.context.errorCodes,"GENERAL_SET_FAILURE"),"The data model element was not specified"),f;this.context.setLastErrorCode("0");const r=i.split(".");let n=this.context.getDataModel(),o=f,a=!1;const c=`The data model element passed to ${e} (${i}) is not a valid SCORM data model element.`,l=this.getUndefinedDataModelErrorCode(t);for(let e=0;r.length>e;e++){if(e===r.length-1){o=this.setFinalAttribute(n,r[e],s,i,t,l,c);break}{const o=this.traverseToNextLevel(n,r,e,s,i,t,a,l,c);if(o.error)break;n=o.refObject,e=o.idx,a=o.foundFirstIndex}}return o===f&&this.context.apiLog(e,`There was an error setting the value for: ${i}, value of: ${s}`,w.WARN),o}getCMIValue(e,t,i){if(!i||""===i)return t&&this.context.throwSCORMError(i,te(this.context.errorCodes,"GENERAL_GET_FAILURE"),"The data model element was not specified"),"";if(t&&i.endsWith("._version")&&"cmi._version"!==i)return this.context.throwSCORMError(i,te(this.context.errorCodes,"GENERAL_GET_FAILURE"),"The _version keyword was used incorrectly"),"";const s=i.split(".");let r=this.context.getDataModel(),n=null;const o=`The data model element passed to ${e} (${i}) has not been initialized.`,a=`The data model element passed to ${e} (${i}) is not a valid SCORM data model element.`,c=this.getUndefinedDataModelErrorCode(t);for(let e=0;s.length>e;e++){n=s[e];const l=this.validateGetAttribute(r,n,i,t,c,a,e===s.length-1);if(void 0!==l.returnValue)return l.returnValue;if(l.error)return"";if(null==n){this.context.throwSCORMError(i,c,a);break}if(r=r[n],void 0===r){this.context.throwSCORMError(i,c,a);break}if(r instanceof R){const t=this.handleGetArrayAccess(r,s,e,i,o);if(t.error)return"";r=t.refObject,e=t.idx}}return null==r?(t||("_children"===n?this.context.throwSCORMError(i,te(this.context.errorCodes,"CHILDREN_ERROR"),void 0):"_count"===n&&this.context.throwSCORMError(i,te(this.context.errorCodes,"COUNT_ERROR"),void 0)),""):r}setFinalAttribute(e,t,i,s,r,o,a){return r&&t?.startsWith(ee)?this.context.isInitialized()?(this.context.throwSCORMError(s,te(this.context.errorCodes,"READ_ONLY_ELEMENT")),f):g:void 0!==t&&this.context.checkObjectHasProperty(e,t)?n(s,"\\.correct_responses\\.\\d+$")&&this.context.isInitialized()&&"pattern"!==t&&(this.context.validateCorrectResponse(s,i),"0"!==this.context.getLastErrorCode())?(this.context.throwSCORMError(s,te(this.context.errorCodes,"TYPE_MISMATCH")),f):r&&"0"!==this.context.getLastErrorCode()?f:void 0===t||"__proto__"===t||"constructor"===t?(this.context.throwSCORMError(s,o,a),f):r&&"id"===t&&this.context.isInitialized()&&this.context.checkForDuplicateId(s,i)?(this.context.throwSCORMError(s,te(this.context.errorCodes,"GENERAL_SET_FAILURE")),f):(e[t]=i,g):(this.context.throwSCORMError(s,o,a),f)}traverseToNextLevel(e,t,i,s,r,n,o,a,c){const l=t[i];if(void 0===l||!this.context.checkObjectHasProperty(e,l))return this.context.throwSCORMError(r,a,c),{refObject:e,idx:i,foundFirstIndex:o,error:!0};if(!(e=e[l]))return this.context.throwSCORMError(r,a,c),{refObject:e,idx:i,foundFirstIndex:o,error:!0};if(e instanceof R){const l=this.handleSetArrayAccess(e,t,i,s,r,n,o,a,c);return l.error?{refObject:e,idx:i,foundFirstIndex:o,error:!0}:l}return{refObject:e,idx:i,foundFirstIndex:o,error:!1}}handleSetArrayAccess(e,t,i,s,r,n,o,a,c){const l=parseInt(t[i+1]||"0",10);if(!isNaN(l)){const t=e.childArray[l];if(t)return{refObject:t,idx:i+1,foundFirstIndex:!0,error:!1};{if(l>e.childArray.length){const t=n?te(this.context.errorCodes,"GENERAL_SET_FAILURE"):te(this.context.errorCodes,"INVALID_SET_VALUE")||te(this.context.errorCodes,"GENERAL_SET_FAILURE");return this.context.throwSCORMError(r,t,`Cannot set array element at index ${l}. Array indices must be sequential. Current array length is ${e.childArray.length}, expected index ${e.childArray.length}.`),{refObject:e,idx:i,foundFirstIndex:o,error:!0}}const t=this.context.getChildElement(r,s,o);return t?(e.initialized&&t.initialize(),e.childArray[l]=t,{refObject:t,idx:i+1,foundFirstIndex:!0,error:!1}):("0"===this.context.getLastErrorCode()&&this.context.throwSCORMError(r,a,c),{refObject:e,idx:i,foundFirstIndex:o,error:!0})}}return{refObject:e,idx:i,foundFirstIndex:o,error:!1}}validateGetAttribute(e,t,i,s,r,n,o){if(s){const s=t+"";if(s.startsWith(ee)&&"function"==typeof e._isTargetValid){const t=s.substring(8,s.length-1);return{error:!1,returnValue:e._isTargetValid(t)}}if(void 0===t||!this.context.checkObjectHasProperty(e,t))return"_children"===t?(this.context.throwSCORMError(i,te(this.context.errorCodes,"GENERAL_GET_FAILURE"),"The data model element does not have children"),{error:!0}):"_count"===t?(this.context.throwSCORMError(i,te(this.context.errorCodes,"GENERAL_GET_FAILURE"),"The data model element is not a collection and therefore does not have a count"),{error:!0}):(this.context.throwSCORMError(i,r,n),{error:!0})}else if(o&&(void 0===t||!this.context.checkObjectHasProperty(e,t)))return"_children"===t?this.context.throwSCORMError(i,te(this.context.errorCodes,"CHILDREN_ERROR")):"_count"===t?this.context.throwSCORMError(i,te(this.context.errorCodes,"COUNT_ERROR")):this.context.throwSCORMError(i,r,n),{error:!0};return{error:!1}}handleGetArrayAccess(e,t,i,s,r){const n=parseInt(t[i+1]||"",10);if(!isNaN(n)){const t=e.childArray[n];return t?{refObject:t,idx:i+1,error:!1}:(this.context.throwSCORMError(s,te(this.context.errorCodes,"VALUE_NOT_INITIALIZED"),r),{refObject:e,idx:i,error:!0})}return{refObject:e,idx:i,error:!1}}}var se=Object.defineProperty,re=(e,t,i)=>((e,t,i)=>t in e?se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);const ne=class e{constructor(){re(this,"_logLevel",w.ERROR),re(this,"_logHandler"),this._logHandler=T}static getInstance(){return e._instance||(e._instance=new e),e._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(w.ERROR,e)}warn(e){this.log(w.WARN,e)}info(e){this.log(w.INFO,e)}debug(e){this.log(w.DEBUG,e)}shouldLog(e){return this.getNumericLevel(e)>=this.getNumericLevel(this._logLevel)}getNumericLevel(e){if(void 0===e)return w.NONE;if("number"==typeof e)return e;switch("string"==typeof e?e.toUpperCase():e){case"1":case"DEBUG":return w.DEBUG;case"2":case"INFO":return w.INFO;case"3":case"WARN":return w.WARN;case"4":case"ERROR":default:return w.ERROR;case"5":case"NONE":return w.NONE}}};re(ne,"_instance");let oe=ne;function ae(){return oe.getInstance()}var ce=Object.defineProperty,le=(e,t,i)=>((e,t,i)=>t in e?ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class he{constructor(e,t,i,s){le(this,"_lastErrorCode","0"),le(this,"_lastDiagnostic",""),le(this,"_errorCodes"),le(this,"_apiLog"),le(this,"_getLmsErrorMessageDetails"),le(this,"_loggingService"),this._errorCodes=e,this._apiLog=t,this._getLmsErrorMessageDetails=i,this._loggingService=s||ae()}get lastErrorCode(){return this._lastErrorCode}set lastErrorCode(e){this._lastErrorCode=e}get lastDiagnostic(){return this._lastDiagnostic}throwSCORMError(e,t,i){this._lastDiagnostic=i||"",i||(i=this._getLmsErrorMessageDetails(t,!0));const s=`SCORM Error ${t}: ${i}${e?` [Element: ${e}]`:""}`;this._apiLog("throwSCORMError",t+": "+i,w.ERROR,e),this._loggingService.error(s),this._lastErrorCode=t+""}clearSCORMError(e){void 0!==e&&e!==f&&(this._lastErrorCode="0")}handleValueAccessException(e,t,i){if(t instanceof m){const s=t;this._lastErrorCode=s.errorCode+"",this._lastDiagnostic="",this._loggingService.warn(`Validation Error ${s.errorCode}: ${s.message} [Element: ${e}]`),i=f}else if(t instanceof Error){const s=t.constructor.name;this._loggingService.error(`${s}: ${t.message} [Element: ${e}]\n${t.stack||""}`),this.throwSCORMError(e,this._errorCodes.GENERAL,`${s}: ${t.message}`),i=f}else{this._loggingService.error(`Unknown error occurred while accessing [Element: ${e}]`);try{const e=JSON.stringify(t);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"),i=f}return i}get errorCodes(){return this._errorCodes}}var de=Object.defineProperty,ue=(e,t,i)=>((e,t,i)=>t in e?de(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class _e{constructor(e){ue(this,"listenerMap",new Map),ue(this,"listenerCount",0),ue(this,"apiLog"),this.apiLog=e}parseListenerName(e){if(!e)return null;const t=e.split("."),i=t[0];let s=null;return t.length>1&&(s=e.replace(i+".","")),{functionName:i??e,CMIElement:s}}on(e,t){if(!t)return;const i=e.split(" ");for(const e of i){const i=this.parseListenerName(e);if(!i)continue;const{functionName:s,CMIElement:r}=i,n=this.listenerMap.get(s)??[];n.push({functionName:s,CMIElement:r,callback:t}),this.listenerMap.set(s,n),this.listenerCount++,this.apiLog("on","Added event listener: "+this.listenerCount,w.INFO,s)}}off(e,t){if(!t)return;const i=e.split(" ");for(const e of i){const i=this.parseListenerName(e);if(!i)continue;const{functionName:s,CMIElement:r}=i,n=this.listenerMap.get(s);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(s),this.apiLog("off","Removed event listener: "+this.listenerCount,w.INFO,s))}}clear(e){const t=e.split(" ");for(const e of t){const t=this.parseListenerName(e);if(!t)continue;const{functionName:i,CMIElement:s}=t;if(this.listenerMap.has(i)){const e=this.listenerMap.get(i),t=null===s?[]:e.filter(e=>e.CMIElement!==s);this.listenerCount-=e.length-t.length,0===t.length?this.listenerMap.delete(i):this.listenerMap.set(i,t)}}}processListeners(e,t,i){this.apiLog(e,i,w.INFO,t);const s=this.listenerMap.get(e);if(s)for(const r of s){const s=!!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;s&&!n||(this.apiLog("processListeners","Processing listener: "+r.functionName,w.DEBUG,t),e.startsWith("Sequence")||"CommitError"===e?r.callback(i):"CommitSuccess"===e?r.callback():r.callback(t,i))}}reset(){this.listenerMap.clear(),this.listenerCount=0}}var me=Object.defineProperty,ge=(e,t,i)=>((e,t,i)=>t in e?me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class fe{constructor(e,t,i){ge(this,"apiLog",i),ge(this,"settings"),ge(this,"error_codes"),ge(this,"storeName","scorm_again_offline_data"),ge(this,"syncQueue","scorm_again_sync_queue"),ge(this,"isOnline",navigator.onLine),ge(this,"syncInProgress",!1),ge(this,"boundOnlineStatusChangeHandler"),ge(this,"boundCustomNetworkStatusHandler"),this.settings=e,this.error_codes=t,this.boundOnlineStatusChangeHandler=this.handleOnlineStatusChange.bind(this),this.boundCustomNetworkStatusHandler=this.handleCustomNetworkStatus.bind(this),window.addEventListener("online",this.boundOnlineStatusChangeHandler),window.addEventListener("offline",this.boundOnlineStatusChangeHandler),window.addEventListener("scorm-again:network-status",this.boundCustomNetworkStatusHandler)}handleOnlineStatusChange(){const e=this.isOnline;this.isOnline=navigator.onLine,!e&&this.isOnline?(this.apiLog("OfflineStorageService","Device is back online, attempting to sync...",w.INFO),this.syncOfflineData().then(e=>{e?this.apiLog("OfflineStorageService","Sync completed successfully",w.INFO):this.apiLog("OfflineStorageService","Sync failed",w.ERROR)},e=>{this.apiLog("OfflineStorageService","Error during sync: "+e,w.ERROR)})):e&&!this.isOnline&&this.apiLog("OfflineStorageService","Device is offline, data will be stored locally",w.INFO)}handleCustomNetworkStatus(e){if(!(e instanceof CustomEvent))return void this.apiLog("OfflineStorageService","Invalid network status event received",w.WARN);const{online:t}=e.detail;if("boolean"!=typeof t)return void this.apiLog("OfflineStorageService","Invalid online status value in custom event",w.WARN);const i=this.isOnline;this.isOnline=t,this.apiLog("OfflineStorageService","Network status updated via custom event: "+(t?"online":"offline"),w.INFO),!i&&this.isOnline?(this.apiLog("OfflineStorageService","Device is back online, attempting to sync...",w.INFO),this.syncOfflineData().then(e=>{e?this.apiLog("OfflineStorageService","Sync completed successfully",w.INFO):this.apiLog("OfflineStorageService","Sync failed",w.ERROR)},e=>{this.apiLog("OfflineStorageService","Error during sync: "+e,w.ERROR)})):i&&!this.isOnline&&this.apiLog("OfflineStorageService","Device is offline, data will be stored locally",w.INFO)}storeOffline(e,t){try{const i={id:`${e}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,courseId:e,timestamp:Date.now(),data:t,syncAttempts:0},s=this.getFromStorage(this.syncQueue)||[];return s.push(i),this.saveToStorage(this.syncQueue,s),this.saveToStorage(`${this.storeName}_${e}`,t),this.apiLog("OfflineStorageService","Stored data offline for course "+e,w.INFO),{result:g,errorCode:0}}catch(t){const i=(t instanceof Error?t.message:t+"").includes("storage quota");return this.apiLog("OfflineStorageService",i?"storage quota exceeded - cannot store offline data for course "+e:"Error storing offline data: "+t,w.ERROR),{result:f,errorCode:this.error_codes.GENERAL??0}}}async getOfflineData(e){try{return this.getFromStorage(`${this.storeName}_${e}`)||null}catch(e){return this.apiLog("OfflineStorageService","Error retrieving offline data: "+e,w.ERROR),null}}async syncOfflineData(){if(this.syncInProgress||!this.isOnline)return!1;this.syncInProgress=!0;try{const e=this.getFromStorage(this.syncQueue)||[];if(0===e.length)return this.syncInProgress=!1,!0;this.apiLog("OfflineStorageService",`Found ${e.length} items to sync`,w.INFO);const t=[];for(const i of e){const e=this.settings.maxSyncAttempts??5;if(e>i.syncAttempts)try{const e=await this.sendDataToLMS(i.data);!0===e.result||e.result===g?this.apiLog("OfflineStorageService","Successfully synced item "+i.id,w.INFO):(i.syncAttempts++,t.push(i),this.apiLog("OfflineStorageService",`Failed to sync item ${i.id}, attempt #${i.syncAttempts}`,w.WARN))}catch(e){i.syncAttempts++,t.push(i),this.apiLog("OfflineStorageService",`Error syncing item ${i.id}: ${e}`,w.ERROR)}else this.apiLog("OfflineStorageService",`Removing abandoned item ${i.id} after ${e} failed sync attempts`,w.WARN)}return this.saveToStorage(this.syncQueue,t),this.apiLog("OfflineStorageService",`Sync completed. ${e.length-t.length} items synced, ${t.length} items remaining`,w.INFO),this.syncInProgress=!1,!0}catch(e){return this.apiLog("OfflineStorageService","Error during sync process: "+e,w.ERROR),this.syncInProgress=!1,!1}}async sendDataToLMS(e){if(!this.settings.lmsCommitUrl)return{result:f,errorCode:this.error_codes.GENERAL||101};try{const t=this.settings.requestHandler(e),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 s=await fetch(this.settings.lmsCommitUrl,i),result="function"==typeof this.settings.responseHandler?await this.settings.responseHandler(s):await s.json();return 200>s.status||s.status>299||!0!==result.result&&result.result!==g?(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,w.ERROR),{result:f,errorCode:this.error_codes.GENERAL||101}}}isDeviceOnline(){return this.isOnline}getFromStorage(e){const t=localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return null}return null}saveToStorage(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(e){if(e instanceof DOMException&&"QuotaExceededError"===e.name)throw Error("storage quota exceeded - localStorage is full",{cause:e});throw e}}async hasPendingOfflineData(e){return(this.getFromStorage(this.syncQueue)||[]).some(t=>t.courseId===e)}updateSettings(e){this.settings=e}destroy(){window.removeEventListener("online",this.boundOnlineStatusChangeHandler),window.removeEventListener("offline",this.boundOnlineStatusChangeHandler),window.removeEventListener("scorm-again:network-status",this.boundCustomNetworkStatusHandler)}}const pe=o((e,t,i,s,r,n)=>{if("string"!=typeof t)return!1;const o=RegExp(i),a=t.match(o);if(n&&""===t)return!0;if(!a||""===a[0])throw new r(e,s);return!0},(e,t,i,s,r,n)=>`${e}:${"string"==typeof t?t:`[${typeof t}]`}:${i}:${s}:${n||!1}`),Ee=o((e,t,i,s,r)=>{const n=i.split("#");if(isNaN(t=+t))throw new r(e,s);const o=n[0],a=n[1],c=void 0!==a&&""!==a&&"*"!==a;if(void 0!==o&&""!==o&&+o>t)throw new r(e,s);if(c&&t>+a)throw new r(e,s);return!0},(e,t,i,s,r)=>`${e}:${t}:${i}:${s}`);var Se=Object.defineProperty,ve=(e,t,i)=>((e,t,i)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ye{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;ve(this,"valid"),ve(this,"targetActivity"),ve(this,"exception"),this.valid=e,this.targetActivity=t,this.exception=i}}ve(class e{constructor(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,n=arguments.length>5?arguments[5]:void 0;ve(this,"activityTree"),ve(this,"rollupProcess"),ve(this,"globalObjectiveMap"),ve(this,"adlNav"),ve(this,"eventCallback"),ve(this,"now"),ve(this,"defaultHideLmsUi"),ve(this,"defaultAuxiliaryResources"),ve(this,"_deliveryInProgress",!1),ve(this,"contentDelivered",!1),ve(this,"checkActivityCallback",null),ve(this,"invalidateCacheCallback",null),ve(this,"updateNavigationValidityCallback",null),ve(this,"clearSuspendedActivityCallback",null),this.activityTree=e,this.rollupProcess=t,this.globalObjectiveMap=i,this.adlNav=s,this.eventCallback=r,this.now=n?.now||(()=>new Date),this.defaultHideLmsUi=n?.defaultHideLmsUi?[...n.defaultHideLmsUi]:[],this.defaultAuxiliaryResources=n?.defaultAuxiliaryResources?n.defaultAuxiliaryResources.map(e=>({...e})):[]}setCheckActivityCallback(e){this.checkActivityCallback=e}setInvalidateCacheCallback(e){this.invalidateCacheCallback=e}setUpdateNavigationValidityCallback(e){this.updateNavigationValidityCallback=e}setClearSuspendedActivityCallback(e){this.clearSuspendedActivityCallback=e}isDeliveryInProgress(){return this._deliveryInProgress}hasContentBeenDelivered(){return this.contentDelivered}resetContentDelivered(){this.contentDelivered=!1}setContentDelivered(e){this.contentDelivered=e}processDeliveryRequest(e){if(this.fireEvent("onDeliveryRequestProcessing",{activity:e.id,timestamp:(new Date).toISOString()}),e.children.length>0)return new ye(!1,null,"DB.1.1-1");const t=this.getActivityPath(e,!0);if(0===t.length)return new ye(!1,null,"DB.1.1-2");for(const e of t)if(this.checkActivityCallback&&!this.checkActivityCallback(e))return new ye(!1,null,"DB.1.1-3");return new ye(!0,e)}contentDeliveryEnvironmentProcess(e){this._deliveryInProgress=!0;try{const t=e.isSuspended;this.activityTree.suspendedActivity&&this.clearSuspendedActivityCallback&&this.clearSuspendedActivityCallback();const i=this.getActivityPath(e,!0);for(const e of i)e.isActive||(t||e.isSuspended?e.isSuspended=!1:e.incrementAttemptCount(),e.isActive=!0,Y.applySelectionAndRandomization(e,1>=e.attemptCount));this.activityTree.currentActivity=e,this.initializeForDelivery(e),this.setupAttemptTracking(e),this.contentDelivered=!0,this.adlNav&&this.updateNavigationValidityCallback&&this.updateNavigationValidityCallback(),this.fireDeliveryEvent(e)}finally{this._deliveryInProgress=!1}}initializeForDelivery(e){"unknown"===e.completionStatus&&0===e.children.length&&(e.completionStatus="not attempted"),null===e.objectiveSatisfiedStatus&&(e.objectiveSatisfiedStatus=!1),null===e.progressMeasure&&(e.progressMeasure=0,e.progressMeasureStatus=!1),null===e.objectiveNormalizedMeasure&&(e.objectiveNormalizedMeasure=0,e.objectiveMeasureStatus=!1),e.attemptAbsoluteDuration="PT0H0M0S",e.attemptExperiencedDuration="PT0H0M0S",e.isAvailable=!0}setupAttemptTracking(e){e.wasSkipped=!1,e.attemptAbsoluteStartTime=this.now().toISOString(),e.location||(e.location=""),e.activityAttemptActive=!0,e.learnerPrefs||(e.learnerPrefs={audioCaptioning:"0",audioLevel:"1",deliverySpeed:"1",language:""})}fireDeliveryEvent(e){try{this.eventCallback&&this.eventCallback("onActivityDelivery",e),console.debug(`Activity delivered: ${e.id} - ${e.title}`)}catch(e){console.warn("Failed to fire activity delivery event: "+e)}}getEffectiveHideLmsUi(t){const i=new Set;for(const e of this.defaultHideLmsUi)i.add(e);let s=t;for(;s;){for(const e of s.hideLmsUi)i.add(e);s=s.parent}return e.HIDE_LMS_UI_ORDER.filter(e=>i.has(e))}getEffectiveAuxiliaryResources(e){const t=new Map;for(const e of this.defaultAuxiliaryResources)e.resourceId&&t.set(e.resourceId,{...e});const i=[];let s=e;for(;s;)i.push(s),s=s.parent;for(const e of i.reverse())for(const i of e.auxiliaryResources)i.resourceId&&t.set(i.resourceId,{...i});return Array.from(t.values())}getContentActivityData(e){return{hideLmsUi:this.getEffectiveHideLmsUi(e),auxiliaryResources:this.getEffectiveAuxiliaryResources(e),location:e.location||"",credit:e.credit||"credit",launchData:e.launchData||"",maxTimeAllowed:e.attemptAbsoluteDurationLimit||"",completionThreshold:e.completionThreshold?.toString()||"",timeLimitAction:e.timeLimitAction||"continue,no message"}}getActivityPath(e){let t=1>=arguments.length||void 0===arguments[1]||arguments[1];const i=[];let s=e;for(;null!==s;)i.unshift(s),s=s.parent;return!t&&i.length>0&&i.pop(),i}fireEvent(e,t){try{this.eventCallback&&this.eventCallback(e,t)}catch(t){console.warn(`Failed to fire sequencing event ${e}: ${t}`)}}},"HIDE_LMS_UI_ORDER",["continue","previous","exit","exitAll","abandon","abandonAll","suspendAll"]);class Oe{loadFromFlattenedJSON(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;if(!s())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 i=t.match(n);if(i){interactions.push({key:t,value:e[t],index:+i[2],field:i[3]||""});continue}const s=t.match(o);if(s){objectives.push({key:t,value:e[t],index:+s[2],field:s[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 i=result,s="";const r=RegExp(pattern);Array.from({length:t.match(RegExp(pattern,"g"))?.length??0},()=>r.exec(t)).forEach(e=>{e&&(i=i[s]??(i[s]=e[2]?[]:{}),s=e[2]||e[1]||"")}),i[s]=e[t]}),result[""]??result}(n),t,i,s,r)})};c(interactions),c(objectives),c(a)}loadFromJSON(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;if(s()){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,i,s,r):i(n,t)}}else a.constructor===Object?this.loadFromJSON(a,o,i,s,r):i(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,i,s,r,n){const o=t||e,a=i?s(e,o):r(e,o);return[w.DEBUG,"1",1,"DEBUG"].includes(n)&&(console.debug("Commit (terminated: "+(e?"yes":"no")+"): "),console.debug(a)),a}}var Ce=Object.defineProperty,be=(e,t,i)=>((e,t,i)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Re{constructor(e,t){be(this,"settings"),be(this,"error_codes"),this.settings=e,this.error_codes=t}processHttpRequest(e,t){return arguments.length>2&&void 0!==arguments[2]&&arguments[2]?this._handleImmediateRequest(e,t):this._performSyncXHR(e,t)}_handleImmediateRequest(e,t){const i=this.settings.requestHandler(t)??t,{body:s}=this._prepareRequestBody(i),r=navigator.sendBeacon(e,new Blob([s],{type:"text/plain;charset=UTF-8"}));return{result:r?"true":"false",errorCode:r?0:this.error_codes.GENERAL_COMMIT_FAILURE||391}}_performSyncXHR(e,t){const i=this.settings.requestHandler(t)??t,{body:s,contentType:r}=this._prepareRequestBody(i),n=new XMLHttpRequest;n.open("POST",e,!1),n.setRequestHeader("Content-Type",r),Object.entries(this.settings.xhrHeaders).forEach(e=>{let[t,i]=e;n.setRequestHeader(t,i+"")}),this.settings.xhrWithCredentials&&(n.withCredentials=!0);try{return n.send(s),this.settings.xhrResponseHandler(n)}catch(e){return{result:f,errorCode:this.error_codes.GENERAL_COMMIT_FAILURE||391,errorMessage:e instanceof Error?e.message:e+""}}}_prepareRequestBody(e){return{body:e instanceof Array?e.join("&"):JSON.stringify(e),contentType:e instanceof Array?"application/x-www-form-urlencoded":this.settings.commitRequestDataType}}updateSettings(e){this.settings=e}}function Le(e,t,i,s){return pe(e,t,i,O.TYPE_MISMATCH,y,s)}function Ne(e,t,i,s){if(""===t)throw new y(e,O.VALUE_OUT_OF_RANGE);return Ee(e,t,i,O.VALUE_OUT_OF_RANGE,y)}const Me=new class{validateScore(e,t,i,s,r,n,o){return pe(e,t,i,r,o)&&(!s||Ee(e,t,s,n,o))}validateScorm12Audio(e,t){return Le(e,t,D)&&Ne(e,t,"-1#100")}validateScorm12Language(e,t){return Le(e,t,A)}validateScorm12Speed(e,t){return Le(e,t,D)&&Ne(e,t,"-100#100")}validateScorm12Text(e,t){return Le(e,t,D)&&Ne(e,t,"-1#1")}validateReadOnly(e,t){if(t)throw new y(e,O.READ_ONLY_ELEMENT)}};var we=Object.defineProperty,Ie=(e,t,i)=>((e,t,i)=>t in e?we(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Te{constructor(e,t,i,s,r,n,o,a,c){if(Ie(this,"_timeout"),Ie(this,"_error_codes"),Ie(this,"_settings",I),Ie(this,"_httpService"),Ie(this,"_eventService"),Ie(this,"_serializationService"),Ie(this,"_errorHandlingService"),Ie(this,"_loggingService"),Ie(this,"_offlineStorageService"),Ie(this,"_cmiValueAccessService"),Ie(this,"_courseId",""),Ie(this,"startingData"),Ie(this,"currentState"),new.target===Te)throw new TypeError("Cannot construct BaseAPI instances directly");this.currentState=0,this._error_codes=e,t&&(this.settings={...I,...t}),void 0!==t?.asyncCommit&&void 0===t.useAsynchronousCommits&&void 0===t.throttleCommits&&(console.warn("DEPRECATED: 'asyncCommit' setting is deprecated and will be removed in a future version. Use 'useAsynchronousCommits: true' and 'throttleCommits: true' instead."),t.asyncCommit&&(this.settings.useAsynchronousCommits=!0,this.settings.throttleCommits=!0)),!this.settings.useAsynchronousCommits&&this.settings.throttleCommits&&(console.warn("throttleCommits cannot be used with synchronous commits. Setting throttleCommits to false."),this.settings.throttleCommits=!1),this._loggingService=a||ae(),this._loggingService.setLogLevel(this.settings.logLevel),this._loggingService.setLogHandler(this.settings.onLogMessage?this.settings.onLogMessage:T),i?this._httpService=i:this.settings.httpService?this._httpService=this.settings.httpService:this.settings.useAsynchronousCommits?(console.warn("WARNING: useAsynchronousCommits=true is not SCORM compliant. Commit failures will not be reported to the SCO, which may cause data loss. This setting should only be used for specific legacy compatibility cases."),this._httpService=new K(this.settings,this._error_codes)):this._httpService=new Re(this.settings,this._error_codes),this._eventService=s||new _e((e,t,i,s)=>this.apiLog(e,t,i,s)),this._serializationService=r||new Oe,this._errorHandlingService=o||new he(this._error_codes,(e,t,i,s)=>this.apiLog(e,t,i||w.ERROR,s),(e,t)=>this.getLmsErrorMessageDetails(e,t),void 0),this.settings.enableOfflineSupport&&(this._offlineStorageService=c||new fe(this.settings,this._error_codes,(e,t,i,s)=>this.apiLog(e,t,i,s)),this.settings.courseId&&(this._courseId=this.settings.courseId),this.settings.syncOnTerminate&&this._eventService.on("BeforeTerminate",()=>{this._offlineStorageService?.isDeviceOnline()&&this._courseId&&this._offlineStorageService.hasPendingOfflineData(this._courseId).then(e=>{if(e)return this.apiLog("BeforeTerminate","Syncing pending offline data before termination",w.INFO),this._offlineStorageService?.syncOfflineData()}).then(e=>{e?this.processListeners("OfflineDataSynced"):!1===e&&this.processListeners("OfflineDataSyncFailed")}).catch(e=>{this.apiLog("BeforeTerminate","Error syncing offline data: "+e,w.ERROR),this.processListeners("OfflineDataSyncFailed")})}),this._offlineStorageService&&this._courseId&&this._offlineStorageService.getOfflineData(this._courseId).then(e=>{e&&(this.apiLog("constructor","Found offline data to restore",w.INFO),this.loadFromJSON(e.runtimeData))}).catch(e=>{this.apiLog("constructor","Error retrieving offline data: "+e,w.ERROR)})),this._cmiValueAccessService=new ie({errorCodes:this._error_codes,getLastErrorCode:()=>this.lastErrorCode,setLastErrorCode:e=>{this.lastErrorCode=e},throwSCORMError:(e,t,i)=>this.throwSCORMError(e,t,i),isInitialized:()=>this.isInitialized(),validateCorrectResponse:(e,t)=>this.v