@liascript/exporter
Version:
A generic exporter for LiaScript
2 lines (1 loc) • 12.4 kB
JavaScript
function t(t,e,i,n){Object.defineProperty(t,e,{get:i,set:n,enumerable:!0,configurable:!0})}var e=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;e.register("9p1wx",(function(i,n){t(i.exports,"Connector",(function(){return a}));var s=e("jXXgq"),o=e("fZWR0"),r=e("iKFEu");class a extends s.Connector{handleUnload(){if(!this.active||!this.lrs)return;const t=o.formatDuration(Date.now()-this.startTime),e=o.generateTerminatedStatement(this.actor,this.courseId,this.courseTitle,t);if(navigator.sendBeacon&&this.lrs.endpoint){const t={"Content-Type":"application/json","X-Experience-API-Version":"1.0.3"};this.lrs.auth&&(t.Authorization=this.lrs.auth),navigator.sendBeacon(this.lrs.endpoint,JSON.stringify([e]))}else this.lrs.sendStatement(e)}checkCompletion(){let t=0;this.totalSlides>0&&(t=this.visitedSlides.size/this.totalSlides);let e=!0;return this.maxScore>0&&(e=Object.values(this.quizStates).every((t=>Object.values(t).every((t=>void 0!==t.solved))))),this.maxScore>0?t>=this.progressThreshold&&e:t>=this.progressThreshold}sendCompletionIfNeeded(){if(!this.completionSent&&this.active&&this.lrs&&this.checkCompletion()){const t=!(this.maxScore>0)||this.totalScore/this.maxScore>=.7,e=o.formatDuration(Date.now()-this.startTime),i=o.generateCompletedStatement(this.actor,this.courseId,this.courseTitle,t,this.totalScore,this.maxScore,e);this.lrs.sendStatement(i).then((t=>{this.debug&&console.log("Sent completed statement, ID:",t),this.completionSent=!0})).catch((t=>{console.error("Failed to send completed statement:",t)}))}}open(t,e,i){if(!this.active||!this.lrs)return;this.startTime=Date.now(),this.lastActivityTime=this.startTime,this.completionSent=!1;const n=o.generateInitializedStatement(this.actor,this.courseId,this.courseTitle);this.lrs.sendStatement(n).then((t=>{this.debug&&console.log("Sent initialized statement, ID:",t)})).catch((t=>{console.error("Failed to send initialized statement:",t)})),void 0!==i&&this.slide(i)}slide(t){if(!this.active||!this.lrs)return;this.lastActivityTime=Date.now(),this.visitedSlides.add(t);let e=`Slide ${t}`;window.LIA&&window.LIA.course&&window.LIA.course.slides[t]&&(e=window.LIA.course.slides[t].title||e);const i=o.generateExperiencedStatement(this.actor,this.courseId,this.courseTitle,t,e);if(this.lrs.sendStatement(i).then((t=>{this.debug&&console.log("Sent experienced statement, ID:",t)})).catch((t=>{console.error("Failed to send experienced statement:",t)})),this.totalSlides>0){const t=this.visitedSlides.size/this.totalSlides,e=o.generateProgressedStatement(this.actor,this.courseId,this.courseTitle,t);this.lrs.sendStatement(e).then((()=>{this.sendCompletionIfNeeded()})).catch((t=>{console.error("Failed to send progress statement:",t)}))}}store(t){if(!this.active||!this.lrs)return;this.lastActivityTime=Date.now();const{table:e,id:i,data:n}=t;if("quiz"===e&&n){this.quizStates[i]||(this.quizStates[i]={});for(let t=0;t<n.length;t++){const e=n[t];if(!e)continue;this.quizStates[i][t]=e,void 0!==e.score&&(1===e.solved&&(this.totalScore+=e.score),this.maxScore+=e.score);const s=o.generateAnsweredStatement(this.actor,this.courseId,this.courseTitle,i,t,e.type||"unknown",e.input||e.answer||"",1===e.solved,1===e.solved?e.score||1:0,e.score||1);this.lrs.sendStatement(s).then((t=>{this.debug&&console.log("Sent answered statement, ID:",t),this.sendCompletionIfNeeded()})).catch((t=>{console.error("Failed to send answered statement:",t)}))}}}update(t,e){super.update(t,e),this.store(t)}getSettings(){return super.getSettings()}setSettings(t){super.setSettings(t)}reset(t,e){this.totalScore=0,this.maxScore=0,this.visitedSlides.clear(),this.quizStates={},this.startTime=Date.now(),this.lastActivityTime=this.startTime,this.completionSent=!1,super.reset(t,e)}constructor(t={}){super(),this.active=!1,this.debug=t.debug||!1,this.totalScore=0,this.maxScore=0,this.visitedSlides=new Set,this.totalSlides=0,this.quizStates={},this.startTime=Date.now(),this.lastActivityTime=this.startTime,this.completionSent=!1,this.progressThreshold=.9,this.actor=t.actor||{objectType:"Agent",name:"Anonymous",mbox:"mailto:anonymous@example.com"};const e=window.location.origin;if(this.courseId=t.courseId||new URL(window.location.href,e).href,this.courseTitle=t.courseTitle||document.title||"LiaScript Course",t.endpoint)try{this.lrs=new r.LRSConnection(t.endpoint,t.auth||"","1.0.3",this.debug),this.active=!0,this.debug&&console.log("xAPI connector initialized with LRS endpoint:",t.endpoint),window.addEventListener("beforeunload",this.handleUnload.bind(this))}catch(t){console.error("Failed to initialize LRS connection:",t),this.lrs=null}else console.warn("No LRS endpoint provided, xAPI tracking will be disabled"),this.lrs=null}}})),e.register("jXXgq",(function(i,n){t(i.exports,"Connector",(function(){return r}));var s=e("3MPaZ"),o=e("ayIBF");class r{hasIndex(){return!1}storage(){return new s.LiaStorage}initSettings(t,e=!1){return o.Settings.init(t,e,this.setSettings)}setSettings(t){o.Settings.update(t)}getSettings(){let t="";try{t=localStorage.getItem(o.Settings.PORT)}catch(t){console.warn("cannot write to localStorage")}let e=null;if("string"==typeof t){try{e=JSON.parse(t)}catch(t){console.warn("getSettings =>",t)}e||(e=o.Settings.data),window.innerWidth<=768&&(e.table_of_contents=!1)}return e}open(t,e,i){}load(t){}store(t){}update(t,e){}slide(t){}getIndex(){}deleteFromIndex(t){}async storeToIndex(t){}restoreFromIndex(t,e){}reset(t,e){this.initSettings(null,!0)}async getFromIndex(t){return null}async addMisc(t,e,i,n){console.log("addMisc not implemented")}async getMisc(t,e,i){console.log("getMisc not implemented")}constructor(){}}})),e.register("3MPaZ",(function(e,i){t(e.exports,"LiaStorage",(function(){return n}));class n{getItems(t=[]){"string"==typeof t&&(t=[t]);let e={};for(let i=0;i<t.length;i++){let n=localStorage.getItem(t[i]);e[t[i]]=n?JSON.parse(n):n}return e}setItems(t){this._setLocal(t)}_setLocal(t){if("object"==typeof t)for(const[e,i]of Object.entries(t))localStorage.setItem(e,JSON.stringify(i))}constructor(){}}})),e.register("fZWR0",(function(e,i){function n(t,e,i){return{actor:t,verb:{id:"http://adlnet.gov/expapi/verbs/initialized",display:{"en-US":"initialized"}},object:{id:e,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/course",name:{"en-US":i}}},timestamp:(new Date).toISOString()}}function s(t,e,i,n,s){return{actor:t,verb:{id:"http://adlnet.gov/expapi/verbs/experienced",display:{"en-US":"experienced"}},object:{id:`${e}/slides/${n}`,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/module",name:{"en-US":s||`Slide ${n}`}}},context:{contextActivities:{parent:[{id:e,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/course",name:{"en-US":i}}}]}},timestamp:(new Date).toISOString()}}function o(t,e,i,n,s,o,r,a,c,l){return{actor:t,verb:{id:"http://adlnet.gov/expapi/verbs/answered",display:{"en-US":"answered"}},object:{id:`${e}/slides/${n}/quiz/${s}`,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/question",name:{"en-US":`${o} Question ${s}`}}},result:{success:a,completion:!0,response:JSON.stringify(r),score:{scaled:c/l,raw:c,min:0,max:l}},context:{contextActivities:{parent:[{id:`${e}/slides/${n}`,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/module"}}],grouping:[{id:e,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/course",name:{"en-US":i}}}]}},timestamp:(new Date).toISOString()}}function r(t,e,i,n,s,o,r){return{actor:t,verb:{id:"http://adlnet.gov/expapi/verbs/completed",display:{"en-US":"completed"}},object:{id:e,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/course",name:{"en-US":i}}},result:{success:n,completion:!0,score:{scaled:o>0?s/o:0,raw:s,min:0,max:o},duration:r},timestamp:(new Date).toISOString()}}function a(t,e,i,n){return{actor:t,verb:{id:"http://adlnet.gov/expapi/verbs/progressed",display:{"en-US":"progressed"}},object:{id:e,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/course",name:{"en-US":i}}},result:{completion:n>=1,progress:n},timestamp:(new Date).toISOString()}}function c(t,e,i,n){return{actor:t,verb:{id:"http://adlnet.gov/expapi/verbs/terminated",display:{"en-US":"terminated"}},object:{id:e,objectType:"Activity",definition:{type:"http://adlnet.gov/expapi/activities/course",name:{"en-US":i}}},result:{duration:n},timestamp:(new Date).toISOString()}}function l(t){const e=Math.floor(t/1e3),i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=e%60;let o="PT";return i>0&&(o+=`${i}H`),n>0&&(o+=`${n}M`),(s>0||0===i&&0===n)&&(o+=`${s}S`),o}t(e.exports,"generateInitializedStatement",(function(){return n})),t(e.exports,"generateExperiencedStatement",(function(){return s})),t(e.exports,"generateAnsweredStatement",(function(){return o})),t(e.exports,"generateCompletedStatement",(function(){return r})),t(e.exports,"generateProgressedStatement",(function(){return a})),t(e.exports,"generateTerminatedStatement",(function(){return c})),t(e.exports,"formatDuration",(function(){return l}))})),e.register("iKFEu",(function(e,i){t(e.exports,"LRSConnection",(function(){return n}));class n{async sendStatement(t){try{this.debug&&console.log("Sending statement to LRS:",JSON.stringify(t,null,2));const e=this.ensureStringReferences(t);if(!this.validateStatement(e))return console.error("Invalid statement structure:",e),null;const i=await fetch(this.endpoint+"statements",{method:"POST",headers:{"Content-Type":"application/json","X-Experience-API-Version":this.version,Authorization:this.auth},body:JSON.stringify(e)});if(!i.ok)return console.error("LRS error:",i.status,await i.text()),null;const n=await i.json();return this.debug&&console.log("LRS response:",n),Array.isArray(n)&&n.length>0?n[0]:n&&"object"==typeof n&&n.id||null}catch(t){return console.error("Error sending statement to LRS:",t),null}}async sendStatements(t){try{this.debug&&console.log("Sending statements to LRS:",JSON.stringify(t,null,2));const e=t.map((t=>this.ensureStringReferences(t))),i=await fetch(this.endpoint+"statements",{method:"POST",headers:{"Content-Type":"application/json","X-Experience-API-Version":this.version,Authorization:this.auth},body:JSON.stringify(e)});if(!i.ok)return console.error("LRS error:",i.status,await i.text()),[];const n=await i.json();return this.debug&&console.log("LRS response:",n),Array.isArray(n)?n:[]}catch(t){return console.error("Error sending statements to LRS:",t),[]}}async getStatements(t={}){try{const e=new URLSearchParams;for(const[i,n]of Object.entries(t))null!=n&&("object"==typeof n?e.append(i,JSON.stringify(n)):e.append(i,String(n)));const i=`${this.endpoint}statements${e.toString()?`?${e.toString()}`:""}`;this.debug&&console.log("Getting statements from LRS:",i);const n=await fetch(i,{method:"GET",headers:{"X-Experience-API-Version":this.version,Authorization:this.auth}});if(!n.ok)return console.error("LRS error:",n.status,await n.text()),null;const s=await n.json();return this.debug&&console.log("LRS response:",s),s}catch(t){return console.error("Error getting statements from LRS:",t),null}}async testConnection(){try{let t=this.endpoint;return t.includes("api/v2/statements")?t=t.replace("api/v2/statements","api/v2/about"):t.endsWith("/statements")&&(t=t.replace("/statements","/about")),(await fetch(t,{method:"GET",headers:{"X-Experience-API-Version":this.version,Authorization:this.auth}})).ok}catch(t){return console.error("Error testing LRS connection:",t),!1}}ensureStringReferences(t){if(null==t)return t;if("object"==typeof t){if(Array.isArray(t))return t.map((t=>this.ensureStringReferences(t)));{const e={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=this.ensureStringReferences(t[i]));return e}}return"function"==typeof t?t.toString():t}validateStatement(t){return!!(t&&t.actor&&"object"==typeof t.actor&&t.verb&&"object"==typeof t.verb&&t.verb.id&&"string"==typeof t.verb.id&&t.object&&"object"==typeof t.object&&t.object.id&&"string"==typeof t.object.id)}constructor(t,e,i="1.0.3",n=!1){this.endpoint=t.endsWith("/")?t:t+"/",this.endpoint.endsWith("statements/")&&(this.endpoint=this.endpoint.slice(0,-11)),this.auth=e,this.version=i,this.debug=n,this.debug&&console.log("LRS endpoint configured as:",this.endpoint)}}}));