From 90e724c8e1fd1ca5c52dd670837bd3a04d0502fa Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Wed, 4 Nov 2026 15:46:38 +0200 Subject: [PATCH 1/3] feat(scorm): report each answer as an interaction, keep the state compressed Every `answered` statement the element relays goes into `cmi.interactions.n`: the question's words as the id, the type as SCORM 1.2 names it, the pattern and the response cut to 255, the result from `success` or from the score, the marks, the latency and the time. One index per question, kept with the state and written over on a retry, after `cmi.interactions._count`, so Moodle's interactions report lines learners up. `cmi.suspend_data` is written compressed with lz-string 1.5.0, vendored as `scorm/lz-string.js` (MIT) and shipped in the zip, the written site and the page builder's assets; a plain state from a zip up to 1.4 still reads. A state that does not fit, or a write the LMS refuses, is said once under the content and in the console. Checked in Moodle 4.5 in standard mode: the four interactions in the report, resume with the compressed state, and a 12-chapter book read to its end. Measured on 23 corpus packages: nothing above 1,040 characters compressed. Closes #124 Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 65 ++++++- apps/demo/demo/scorm-page.js | 3 +- apps/demo/demo/scorm.html | 20 ++- docs/compatibility.md | 7 +- packages/embed/README.md | 14 +- packages/embed/bin/h5p-embed.mjs | 3 +- packages/embed/lib/build.mjs | 3 + packages/embed/lib/scorm-browser.mjs | 12 +- packages/embed/lib/scorm-core.mjs | 7 +- packages/embed/lib/scorm.mjs | 1 + packages/embed/package.json | 1 + packages/embed/scorm/index.html | 2 + packages/embed/scorm/lz-string.js | 29 +++ packages/embed/scorm/scorm.js | 254 +++++++++++++++++++++++++-- packages/embed/site/scorm.html | 7 +- packages/embed/tests/build.test.ts | 2 +- packages/embed/tests/scorm.test.ts | 187 ++++++++++++++++++-- 17 files changed, 546 insertions(+), 71 deletions(-) create mode 100644 packages/embed/scorm/lz-string.js diff --git a/AGENTS.md b/AGENTS.md index 1c6e6d30..c5b0902a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -264,7 +264,9 @@ packages/embed/ @missing-elements/h5p-embed — the embed page as a st fetched from the site and the zip a Blob; lib/shared.mjs, EmbedError and the player's file names, for the modules that import no Node (#122) scorm/ the SCORM package's launch page (index.html, its title, language and - build filled in by the writer) and scorm.js, its bridge to the LMS's API + build filled in by the writer), scorm.js, its bridge to the LMS's API, + and lz-string.js, lz-string 1.5.0 as npm publishes it (MIT, its licence + in its header), which the bridge compresses the saved state with (#124) bin/h5p-embed.mjs the command scripts/ build.mjs, dist/scorm-page.js: the SCORM page's script bundled with zip.js and the player's `./plan` for a written site, which has no bundler @@ -2443,22 +2445,62 @@ one row each; an LMS added here gets a row there. The last `finished` counts, as `setFinished` does on an H5P site. On `beforeunload` it sets the session time and `cmi.core.exit` (`suspend` unless finished) and commits; on `pagehide` it sets - both again and calls `LMSFinish`. The commit is ILIAS's (#94, under *ILIAS plays it too*), and + both again and calls `LMSFinish`. + **Each answer goes into `cmi.interactions`** (#124, 2026-11-04, asked for by two of three + commenters on the Reddit demand check): every `answered` statement the element relays, by the + part's `subContentId`, with the question's words as the id, since 1.2 has no description field + and the id is what a report shows (a slug in printable ASCII, which 1.2's `CMIIdentifier` + allows and nothing else; the key for a question with no words; `-2` on a second question with + the same words), the xAPI type as 1.2 names it (`long-fill-in` as `fill-in`, `other` and an + unknown type left out), the pattern and the response cut to 255 (`CMIFeedback`; H5P's `0[,]2` + goes in as it is, which Moodle takes), `correct` or `wrong` from `success`, or from the score + where the content says nothing, as Fill in the Blanks does not (full marks, none, or the marks + themselves, a number 1.2 takes there), `neutral` with neither, the marks as `weighting`, + `result.duration` as `latency`, the time of day. **One index per question, written over on a + retry**, read in Moodle's code: its interactions report has one column per index for every + learner (`get_scorm_question_count` takes the highest index found), so an entry per attempt + would set one learner's columns against another's. The index comes from the questions kept with + the state (`questions` in `suspend_data`, by index), after `cmi.interactions._count`, which 1.2 + lets a SCO read and Moodle reloads from the attempt's tracks; an attempt the LMS started over + counts none, and they start again. The fields are write-only; the reports read them. The commit is ILIAS's (#94, under *ILIAS plays it too*), and only a commit: the content's last save comes after it, and the learner may stay. Moodle's API sends with `navigator.sendBeacon` while unloading, and the `exit` it stored showed that the call arrived. Content with no result of its own stays `incomplete`. Moodle takes `score.raw` as the grade, against the activity's maximum grade (`grademax` is its `maxgrade` in `scorm_grade_item_update`), so the README says to leave that at 100, Moodle's default. + Checked in Moodle 4.5.15 on 2026-11-04 with the demo quiz, three answers right: the four + interactions in the attempt's tracks with the ids from the questions' words, the types, the + patterns and responses, `correct` three times and `wrong` once, the weightings and latencies, + `get_scorm_question_count` 4, and the interactions report with a Response column per index. - **Resume through `cmi.suspend_data`.** The element plays with `resume="host"`. Every `userdata` - event rewrites `{ build, entries }` into `suspend_data` and commits. A launch hands `userData` - back before `src` when the stamp matches. The stamp is the first 16 hex digits of the package's + event rewrites `{ build, entries, questions }` into `suspend_data`, compressed with lz-string's + `compressToBase64` since embed 1.5 (#124: ASCII, as 1.2's `CMIString4096` asks, and + synchronous, so the content's last save on `beforeunload` still lands, where the browser's + `CompressionStream` is asynchronous and could lose it), and commits. A state that begins with + `{`, written plain by a zip up to 1.4, is read as it is, so a learner's place survives the + upgrade. A launch hands `userData` back before `src` when the stamp matches. The stamp is the first 16 hex digits of the package's SHA-256, or, with parts of the pack, of one over the package's and theirs, written into the page's ``. So a teacher who replaces the zip with another package does not hand learners state saved against the old one, and a zip written with other parts starts them over, as a refreshed package does in the player (the owner's rule of 2026-10-18). SCORM 1.2 keeps - 4,096 characters; a larger state is not written, and the last one that fitted stays. Checked in + 4,096 characters; a larger state is not written, and the last one that fitted stays. Until #124 + that was silent; now the page says so once, under the content (`#saving`), and in the console, + as it does when the LMS refuses the write, which the bridge checks `LMSSetValue`'s answer for. + Moodle takes 64,000 when its administrator turns "SCORM 1.2 standard mode" off + (`scormstandard` in `public/mod/scorm/datamodels/scorm_12.php`). Checked in Moodle: a learner left after the first question, the next launch's `entry` was `resume`, and the - quiz reopened on the second question. + quiz reopened on the second question; with the compressed state (220 characters) the same on + 2026-11-04, in standard mode. Measured that day on 23 packages of the corpus, the state as the + bridge writes it after a generic click-through: a quiz 170 to 240 plain and 180 to 210 + compressed, Course Presentations 150 to 370 and 180 to 280, Interactive Books 630 to 2,330 and + 420 to 1,040, so nothing near the limit; a state under about 150 characters comes out longer + compressed, base64 costing a third. The 12-chapter book read to its last chapter in Moodle wrote + 996 characters and came back with its chapters' state, and on its first chapter: Interactive + Book takes its saved place (`urlFragments`, with `h5pbookid`) back only when that id is the + content id, which the boot script draws at random on every load (`integrationFor`), so no book + returns to its chapter in any `resume` mode, a runtime bug outside #124, measured the same day + in the plain player with `resume="device"`. Two corpus books carry Interactive Book 1.3, which + keeps no state at all. - **Outside an LMS** the page finds no API, plays the package and reports nothing. - **Frappe LMS plays it too, and records less.** Checked on 2026-10-30 against Frappe LMS's `develop` branch in its own Docker setup, as an enrolled student in Chrome, with the demo's quiz, @@ -2609,7 +2651,8 @@ one row each; an LMS added here gets a row there. badge where the page has one; the written site loads it as `scripts/build.mjs` bundles it with zip.js and the player's `./plan` (`dist/scorm-page.js`, zip.js's licence in its header, since the site has no bundler), from `scorm.html`, with the launch page and the bridge copied beside it as - `scorm-launch.html` and `scorm.js` and the player's and the pack's versions in `config.js`. The + `scorm-launch.html`, `scorm.js` and `lz-string.js` and the player's and the pack's versions in + `config.js`. The demo reuses the source at `/demo/scorm.html` in the site's own design: the pack's parts as Vite emits them, the four files as `?raw` strings, the player's version from a `define`, and the player's built files from the site root, which a dev middleware serves from the player's `dist/` @@ -2630,7 +2673,13 @@ its refusals in Node. In Chromium it plays the unpacked zip under a page that ho frames the launch page, as Moodle's player does. It covers: - a passed and a failed result, the end of the session, resume, and refusing state saved by - another build; + another build, and reading one a zip up to 1.4 wrote plain; +- the quiz's four answers as interactions, and, through dispatched `xapi` events, the id from + the words and from the key, the second id for the same words, the type map, the 255 cut, the + result from `success` and from the score, one index per question across a retry and a second + session, and an attempt started over; +- a state that fits only compressed, one that does not fit at all and the notice said once, and + a write the LMS refuses; - the commit on `beforeunload` and the finish on `pagehide`, by the event the launch page was dispatching when it called, which is what ILIAS goes by, and a leave the learner stays from; - a result with no score, and a state past 4,096 characters, through the element's events diff --git a/apps/demo/demo/scorm-page.js b/apps/demo/demo/scorm-page.js index 025cfb8d..a663c2de 100644 --- a/apps/demo/demo/scorm-page.js +++ b/apps/demo/demo/scorm-page.js @@ -9,9 +9,10 @@ import { startScormPage } from '@missing-elements/h5p-embed/scorm-page.js' import launch from '@missing-elements/h5p-embed/scorm/index.html?raw' import bridge from '@missing-elements/h5p-embed/scorm/scorm.js?raw' +import lz from '@missing-elements/h5p-embed/scorm/lz-string.js?raw' import css from '@missing-elements/h5p-embed/embed.css?raw' import { pack } from '@missing-elements/h5p-libraries' import libraries from '@missing-elements/h5p-libraries/libraries.txt?raw' import { version as packVersion } from '@missing-elements/h5p-libraries/package.json' -startScormPage({ base: '/', pack, assets: { launch, bridge, css, libraries }, version: __PLAYER_VERSION__, packVersion }) +startScormPage({ base: '/', pack, assets: { launch, bridge, lz, css, libraries }, version: __PLAYER_VERSION__, packVersion }) diff --git a/apps/demo/demo/scorm.html b/apps/demo/demo/scorm.html index c97b7fcd..f0eb9cb1 100644 --- a/apps/demo/demo/scorm.html +++ b/apps/demo/demo/scorm.html @@ -4,14 +4,14 @@ Convert H5P to SCORM in your browser — h5p-offline-player - + - + @@ -19,7 +19,7 @@ - + @@ -59,10 +59,11 @@

H5P to SCORM

In the LMS

Add the zip to a course as a SCORM activity. The LMS records the score out of 100, whether - the content was passed or failed, or completed when it does not say, the time spent, and - the learner's place, so the next launch continues where they left off. Content that reports - no result of its own, an Accordion or a Virtual Tour, stays incomplete. The package plays - with its own code on the LMS's origin, as every SCORM package does. + the content was passed or failed, or completed when it does not say, each question's + answer, the time spent, and the learner's place, so the next launch continues where they + left off. Content that reports no result of its own, an Accordion or a Virtual Tour, stays + incomplete. The package plays with its own code on the LMS's origin, as every SCORM + package does.

@@ -80,8 +81,9 @@

In the LMS

Another LMS that takes SCORM 1.2 may work as well; these are the ones checked, as a learner in Chrome. The LMS has to be served over https, since the player needs its Service Worker. - SCORM 1.2 keeps 4,096 characters of saved state, enough for a quiz; a larger state is not - saved. + SCORM 1.2 keeps 4,096 characters of saved state; the zip writes it compressed, so a quiz + takes about 200 and a twelve-chapter Interactive Book about 1,000. One that does not fit is + not saved, and the learner is told under the content.

What goes in the zip

diff --git a/docs/compatibility.md b/docs/compatibility.md index 175933de..f7a180d4 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -93,9 +93,10 @@ What is covered of the pack itself: the `pack` export, `parts/` with its `index. their options and their types; and `resizer.js`, which speaks H5P's own resizer protocol. - **The SCORM package `--scorm` writes**, and **`buildScorm()`**, with its options and types: SCORM 1.2, the elements its page sets (`cmi.core.score.raw`, `.min` and `.max`, - `cmi.core.lesson_status`, `cmi.core.session_time`, `cmi.core.exit`), and what it keeps in - `cmi.suspend_data`, which a zip written by a later version reads back unless the libraries it - carries from the pack have changed. + `cmi.core.lesson_status`, `cmi.core.session_time`, `cmi.core.exit`, and since 1.5 each + question's `cmi.interactions.n`), and what it keeps in `cmi.suspend_data`, which a zip written + by a later version reads back unless the libraries it carries from the pack have changed: 1.5 + writes it compressed and still reads what 1.4 wrote plain. - **The SCORM page**, `scorm.html` on a written site, and **`buildScormInPage()`** and **`startScormPage()`**, with their options and types: the same zip as `buildScorm()`'s, built in the browser. diff --git a/packages/embed/README.md b/packages/embed/README.md index 57e733e0..5bed5da3 100644 --- a/packages/embed/README.md +++ b/packages/embed/README.md @@ -140,10 +140,18 @@ page that reports to the LMS. Add it to a course as a SCORM activity, in one of - the score out of 100, and `passed` or `failed` when the content says whether it was passed, `completed` when it does not. The content's last result counts, as on an H5P site; +- each question's answer, as `cmi.interactions`: the question's words as the id, its type, the + answer given and the right one, `correct` or `wrong`, the marks it was worth and the time it + took. One interaction per question, written over when it is answered again, which is how + Moodle's interactions report lines learners up. SCORM 1.2 lets the content write these and + never read them; the LMS's reports do; - the time spent in each session; -- the learner's place: the content's saved state goes into `cmi.suspend_data`, and the next - launch continues from it. SCORM 1.2 keeps 4,096 characters, enough for a quiz; a larger state is - not saved. +- the learner's place: the content's saved state goes into `cmi.suspend_data`, compressed, and + the next launch continues from it. SCORM 1.2 keeps 4,096 characters; compressed, a quiz's state + takes about 200, a twelve-chapter Interactive Book about 1,000, and none of 23 real packages + measured passed 1,100. One that does not fit is not saved, the last that fitted stays, and + the page says so under the content, once. Moodle keeps 64,000 when its administrator turns + "SCORM 1.2 standard mode" off. An export from h5p.com or h5p.org, which leaves the libraries out, works as well: the zip carries the ones it needs from the library pack, and only those. For a quiz with formulas, that is 11 diff --git a/packages/embed/bin/h5p-embed.mjs b/packages/embed/bin/h5p-embed.mjs index e11affb2..edbaef62 100755 --- a/packages/embed/bin/h5p-embed.mjs +++ b/packages/embed/bin/h5p-embed.mjs @@ -95,7 +95,8 @@ if (values.scorm !== undefined) { with the player ${zip.version}${supplied}. Add it to a course as a SCORM package. The LMS gets the content's score and whether it passed, -when the content reports them, and the time spent; the learner's place is kept between sessions. +when the content reports them, each question's answer, and the time spent; the learner's place is +kept between sessions. The LMS must be served over https, as the player's Service Worker needs.`) } catch (error) { if (error instanceof EmbedError) { diff --git a/packages/embed/lib/build.mjs b/packages/embed/lib/build.mjs index 341fbbb6..f1fb91cc 100644 --- a/packages/embed/lib/build.mjs +++ b/packages/embed/lib/build.mjs @@ -32,6 +32,7 @@ const PAGE_FILES = ['embed.js', 'embed.css', 'main.js', 'resizer.js', 'scorm-mai const SCORM_FILES = [ ['scorm-launch.html', join(SCORM, 'index.html')], ['scorm.js', join(SCORM, 'scorm.js')], + ['lz-string.js', join(SCORM, 'lz-string.js')], ['scorm-page.js', join(DIST, 'scorm-page.js')] ] @@ -318,6 +319,8 @@ function notice({ version, libraries }) { the SCORM page, which builds a SCORM package of a .h5p in the browser, and the launch page it puts in the zip: MIT. scorm-page.js also carries zip.js, BSD-3-Clause, its licence in its header. + lz-string.js lz-string 1.5.0, which the zip's launch page compresses the learner's saved + state with: MIT, its licence in its header. Caddyfile, nginx.conf, .htaccess, _headers, vercel.json the same headers for five kinds of host; use the one yours reads h5p-player.js, h5p-sw.js, h5p-jobs.js diff --git a/packages/embed/lib/scorm-browser.mjs b/packages/embed/lib/scorm-browser.mjs index e40f5885..9d5432f7 100644 --- a/packages/embed/lib/scorm-browser.mjs +++ b/packages/embed/lib/scorm-browser.mjs @@ -27,16 +27,17 @@ import { EmbedError, PLAYER_FILES } from './shared.mjs' * @property {string} [name] its file name, for the zip's name, the title's fallback and the * messages; a `File`'s own by default * @property {string | URL} [base] the folder that holds the player's three files and - * `frame-assets/`, and, unless `assets` gives them, `scorm-launch.html`, `scorm.js`, `embed.css` - * and `libraries.txt`: this page's own folder by default + * `frame-assets/`, and, unless `assets` gives them, `scorm-launch.html`, `scorm.js`, + * `lz-string.js`, `embed.css` and `libraries.txt`: this page's own folder by default * @property {PackIndex | null} [pack] the library pack, as the `pack` export a bundler resolves; * it wins over `packBase` * @property {string | URL | null} [packBase] the folder of a copy of the pack's `parts/`, which * the written site has as `libraries/`. Without either, a package that does not carry its * libraries is refused - * @property {{ launch?: string, bridge?: string | Blob, css?: string | Blob, libraries?: string | Blob }} [assets] - * the launch page's template, its bridge, the stylesheet and the pack's licence list, for a page - * that bundles them rather than serving them beside the player + * @property {{ launch?: string, bridge?: string | Blob, lz?: string | Blob, css?: string | Blob, libraries?: string | Blob }} [assets] + * the launch page's template, its bridge, the compressor the bridge keeps the saved state with + * (`scorm/lz-string.js`), the stylesheet and the pack's licence list, for a page that bundles + * them rather than serving them beside the player * @property {string} [version] the player's version, for the notice; `unknown` if not given * @property {string | null} [packVersion] the pack's, the same way * @property {(progress: ScormProgress) => void} [onProgress] @@ -148,6 +149,7 @@ export async function buildScormInPage(options) { const files = { launch: assets.launch ?? (await (await fetched(fetchImpl, at('scorm-launch.html'), "The launch page's template")).text()), bridge: assets.bridge !== undefined ? asBlob(assets.bridge) : await blob(at('scorm.js'), 'The launch page\'s script'), + lz: assets.lz !== undefined ? asBlob(assets.lz) : await blob(at('lz-string.js'), 'The launch page\'s compressor'), css: assets.css !== undefined ? asBlob(assets.css) : await blob(at('embed.css'), 'The stylesheet'), player: await blobs(PLAYER_FILES, at, "The player's file"), runtime: await blobs(runtimeFiles(runtimeManifest), (path) => at(`frame-assets/${path}`), "The runtime's file"), diff --git a/packages/embed/lib/scorm-core.mjs b/packages/embed/lib/scorm-core.mjs index 690dc661..486ce769 100644 --- a/packages/embed/lib/scorm-core.mjs +++ b/packages/embed/lib/scorm-core.mjs @@ -89,11 +89,14 @@ ${files.map((file) => ` `).join('\n')} /** @param {{ version: string, source: string, pack: string | null }} zip `pack`, the library pack's version when the zip carries parts of it */ function notice({ version, source, pack }) { return `This is a SCORM 1.2 package written by @missing-elements/h5p-embed. It plays ${source} in an -LMS and reports its score, its result and the time spent, and keeps the learner's place. +LMS and reports its score, its result, each question's answer and the time spent, and keeps the +learner's place. imsmanifest.xml the package's manifest index.html, scorm.js, embed.css the launch page and its bridge to the LMS: MIT + lz-string.js lz-string 1.5.0, which the bridge compresses the learner's saved state + with: MIT, its licence in its header. h5p-player.js, h5p-sw.js, h5p-jobs.js @missing-elements/h5p-offline-player ${version}: MIT. The Service Worker, h5p-sw.js, also carries zip.js, BSD-3-Clause, its licence in its header. @@ -257,6 +260,7 @@ export async function readPackage(blob, name, pack, { useWebWorkers = false } = * @typedef {object} ScormFiles * @property {string} launch the launch page's template, `scorm/index.html` * @property {Blob} bridge `scorm/scorm.js` + * @property {Blob} lz `scorm/lz-string.js`, which the bridge compresses the saved state with * @property {Blob} css `embed.css` * @property {Map} player the player's files, by name * @property {Map} runtime the runtime's files, by path under `frame-assets/` @@ -301,6 +305,7 @@ export function scormEntries({ manifest, source, title, build, version, packVers const entries = [ { name: 'index.html', text: page }, { name: 'scorm.js', blob: files.bridge }, + { name: 'lz-string.js', blob: files.lz }, { name: 'embed.css', blob: files.css }, ...PLAYER_FILES.map((name) => ({ name, blob: given(files.player, name, "The player's file") })), ...[...files.runtime.keys()].sort().map((name) => ({ name: `frame-assets/${name}`, blob: given(files.runtime, name, "The runtime's file") })), diff --git a/packages/embed/lib/scorm.mjs b/packages/embed/lib/scorm.mjs index 62be70ad..01256dde 100644 --- a/packages/embed/lib/scorm.mjs +++ b/packages/embed/lib/scorm.mjs @@ -138,6 +138,7 @@ export async function buildScorm({ h5p, out, force = false }) { files: { launch: await readFile(join(SCORM, 'index.html'), 'utf8'), bridge: await openAsBlob(join(SCORM, 'scorm.js')), + lz: await openAsBlob(join(SCORM, 'lz-string.js')), css: await openAsBlob(join(SITE, 'embed.css')), player: await blobs(PLAYER_FILES, (name) => join(player, name)), runtime: await blobs(await filesUnder(runtime), (name) => join(runtime, name)), diff --git a/packages/embed/package.json b/packages/embed/package.json index 535e60c0..0c244c50 100644 --- a/packages/embed/package.json +++ b/packages/embed/package.json @@ -45,6 +45,7 @@ "./scorm-page.css": "./site/scorm-page.css", "./scorm/index.html": "./scorm/index.html", "./scorm/scorm.js": "./scorm/scorm.js", + "./scorm/lz-string.js": "./scorm/lz-string.js", "./package.json": "./package.json" }, "files": [ diff --git a/packages/embed/scorm/index.html b/packages/embed/scorm/index.html index 7ef72a2b..22e9a380 100644 --- a/packages/embed/scorm/index.html +++ b/packages/embed/scorm/index.html @@ -6,6 +6,7 @@ %TITLE% + @@ -17,5 +18,6 @@ + diff --git a/packages/embed/scorm/lz-string.js b/packages/embed/scorm/lz-string.js new file mode 100644 index 00000000..8248f19d --- /dev/null +++ b/packages/embed/scorm/lz-string.js @@ -0,0 +1,29 @@ +/*! + * lz-string 1.5.0, by pieroxy: https://github.com/pieroxy/lz-string. The launch page's bridge + * (scorm.js) compresses the learner's saved state with it, so that more of it fits in the 4,096 + * characters SCORM 1.2 keeps in cmi.suspend_data. This is the package's own minified build, + * libs/lz-string.min.js as published on npm, under its licence: + * + * MIT License + * + * Copyright (c) 2013 pieroxy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +var LZString=function(){var r=String.fromCharCode,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",e={};function t(r,o){if(!e[r]){e[r]={};for(var n=0;n>>8,n[2*e+1]=s%256}return n},decompressFromUint8Array:function(o){if(null==o)return i.decompress(o);for(var n=new Array(o.length/2),e=0,t=n.length;e>=1}else{for(t=1,e=0;e>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e>=1;0==--l&&(l=Math.pow(2,h),h++),s[p]=f++,c=String(a)}if(""!==c){if(Object.prototype.hasOwnProperty.call(u,c)){if(c.charCodeAt(0)<256){for(e=0;e>=1}else{for(t=1,e=0;e>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e>=1;0==--l&&(l=Math.pow(2,h),h++)}for(t=2,e=0;e>=1;for(;;){if(m<<=1,v==o-1){d.push(n(m));break}v++}return d.join("")},decompress:function(r){return null==r?"":""==r?null:i._decompress(r.length,32768,function(o){return r.charCodeAt(o)})},_decompress:function(o,n,e){var t,i,s,u,a,p,c,l=[],f=4,h=4,d=3,m="",v=[],g={val:e(0),position:n,index:1};for(t=0;t<3;t+=1)l[t]=t;for(s=0,a=Math.pow(2,2),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 2:return""}for(l[3]=c,i=c,v.push(c);;){if(g.index>o)return"";for(s=0,a=Math.pow(2,d),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(c=s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 2:return v.join("")}if(0==f&&(f=Math.pow(2,d),d++),l[c])m=l[c];else{if(c!==h)return null;m=i+i.charAt(0)}v.push(m),l[h++]=i+m.charAt(0),i=m,0==--f&&(f=Math.pow(2,d),d++)}}};return i}();"function"==typeof define&&define.amd?define(function(){return LZString}):"undefined"!=typeof module&&null!=module?module.exports=LZString:"undefined"!=typeof angular&&null!=angular&&angular.module("LZString",[]).factory("LZString",function(){return LZString}); diff --git a/packages/embed/scorm/scorm.js b/packages/embed/scorm/scorm.js index 3867dd02..a5b4b461 100644 --- a/packages/embed/scorm/scorm.js +++ b/packages/embed/scorm/scorm.js @@ -1,8 +1,9 @@ /** * The launch page's script in a SCORM 1.2 package `h5p-embed --scorm` writes: it finds the LMS's * API, opens the session, and plays the package beside this page. The LMS hears what the content - * reports: its score and whether it passed when it finishes, the time spent, and the state it - * saves, which comes back on the next launch so the learner continues where they left off. + * reports: its score and whether it passed when it finishes, each question's answer as it is + * given, the time spent, and the state it saves, which comes back on the next launch so the + * learner continues where they left off. * * Outside an LMS, with no API to find, it plays the package and reports nothing. * @@ -19,8 +20,29 @@ * @property {(empty: string) => string} LMSCommit */ +/** + * lz-string, which the page loads before this script (`lz-string.js`): the saved state goes into + * `cmi.suspend_data` compressed, as base64, so that a long Interactive Book's fits where its JSON + * would not. Without it, a page of its own that left the script out, the state goes plain. + * @typedef {{ compressToBase64: (text: string) => string, decompressFromBase64: (text: string) => string | null }} LzString + */ + /** What SCORM 1.2 keeps of `cmi.suspend_data`: a `CMIString4096`. */ const SUSPEND_DATA_LIMIT = 4096 +/** What it keeps of an interaction's response and its pattern: a `CMIFeedback`, 255 characters. */ +const FEEDBACK_LIMIT = 255 +/** An interaction's id, a `CMIIdentifier`: 255 characters of printable ASCII, no spaces. */ +const IDENTIFIER_LIMIT = 255 +/** The verb of a question answered. */ +const ANSWERED = 'http://adlnet.gov/expapi/verbs/answered' +/** Where the core writes a part's id on every statement about it. */ +const SUB_CONTENT_ID = 'http://h5p.org/x-api/h5p-subContentId' +/** + * xAPI's interaction types as SCORM 1.2 names them: the same eight, and `long-fill-in`, an Essay, + * as `fill-in`. A statement with `other`, or none, writes no type. + * @type {Record} + */ +const INTERACTION_TYPES = { 'true-false': 'true-false', choice: 'choice', 'fill-in': 'fill-in', 'long-fill-in': 'fill-in', matching: 'matching', performance: 'performance', sequencing: 'sequencing', likert: 'likert', numeric: 'numeric' } /** * The `API` object an LMS puts in a window above the content, searched from `start` up to its top @@ -43,6 +65,9 @@ function findApi(start) { return null } +/** @param {number} value */ +const two = (value) => String(value).padStart(2, '0') + /** * `cmi.core.session_time`'s format, a `CMITimespan`: hours, minutes and seconds to the hundredth. * @param {number} ms @@ -52,7 +77,24 @@ function timespan(ms) { const hours = Math.floor(hundredths / 360000) const minutes = Math.floor(hundredths / 6000) % 60 const seconds = (hundredths % 6000) / 100 - return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${seconds.toFixed(2).padStart(5, '0')}` + return `${two(hours)}:${two(minutes)}:${seconds.toFixed(2).padStart(5, '0')}` +} + +/** + * A statement's `result.duration`, an ISO 8601 duration the core writes as `PT12.34S`, as a + * `CMITimespan`; `null` for anything else. + * @param {unknown} duration + */ +function latencyOf(duration) { + const match = typeof duration === 'string' ? /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/.exec(duration) : null + if (!match || duration === 'PT') return null + return timespan((Number(match[1] ?? 0) * 3600 + Number(match[2] ?? 0) * 60 + Number(match[3] ?? 0)) * 1000) +} + +/** The time of day, a `CMITime`: when an interaction was answered. */ +function timeOfDay() { + const now = new Date() + return `${two(now.getHours())}:${two(now.getMinutes())}:${two(now.getSeconds())}` } /** @@ -74,11 +116,79 @@ function scormResult(result) { } } +/** + * A statement about a question, as far as the interaction reads it. + * @typedef {object} AnsweredStatement + * @property {{ id?: unknown, definition?: { description?: unknown, interactionType?: unknown, correctResponsesPattern?: unknown, extensions?: Record } }} [object] + * @property {{ response?: unknown, success?: unknown, duration?: unknown, score?: { raw?: unknown, max?: unknown } }} [result] + */ + +/** + * An interaction's `result`: `correct` or `wrong` as the content says, and where it says nothing, + * as Fill in the Blanks does not, by its score: full marks, none, or the marks themselves, a + * number SCORM 1.2 takes there; `neutral` with no score either. + * @param {NonNullable} result + */ +function outcomeOf(result) { + if (result.success === true) return 'correct' + if (result.success === false) return 'wrong' + const { raw, max } = result.score ?? {} + if (typeof raw !== 'number' || typeof max !== 'number' || max <= 0) return 'neutral' + return raw >= max ? 'correct' : raw <= 0 ? 'wrong' : String(Math.round(raw * 100) / 100) +} + +/** + * Which question a statement is about: the part's id, which the core writes on every statement + * about a part; the content's own, for a question that is the whole package, has none. + * @param {AnsweredStatement} statement + */ +function questionKey(statement) { + const sub = statement.object?.definition?.extensions?.[SUB_CONTENT_ID] + if (typeof sub === 'string' && sub) return sub + return typeof statement.object?.id === 'string' && statement.object.id ? statement.object.id : 'content' +} + +/** + * The question's words, from the statement's description in the content's language, else the + * first it gives; a question type that writes markup there has it taken out. + * @param {AnsweredStatement} statement + * @param {string} language + */ +function questionText(statement, language) { + const description = statement.object?.definition?.description + if (!description || typeof description !== 'object') return '' + const map = /** @type {Record} */ (description) + const text = map[language] ?? map['en-US'] ?? Object.values(map)[0] + return typeof text === 'string' ? text.replace(/<[^>]*>/g, ' ') : '' +} + +/** + * An interaction's id, which is what a report shows, since SCORM 1.2 has no description: the + * question's words as a slug in printable ASCII, else the question's key with anything else + * taken out, else `question`. + * @param {string} text + * @param {string} key + */ +function interactionId(text, key) { + const slug = text + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 80) + .replace(/-+$/, '') + return (slug || key.replace(/[^\x21-\x7e]/g, '')).slice(0, IDENTIFIER_LIMIT) || 'question' +} + /** The package's build, as the writer stamped it: what saved state is kept against. */ const build = document.querySelector('meta[name="h5p-package-build"]')?.getAttribute('content') ?? '' +const language = document.documentElement.lang || 'en' const player = /** @type {H5PPlayerElement} */ (document.querySelector('h5p-player')) const loader = /** @type {HTMLElement} */ (document.getElementById('loader')) const notice = /** @type {HTMLElement} */ (document.getElementById('notice')) +const saving = /** @type {HTMLElement | null} */ (document.getElementById('saving')) +const lz = /** @type {LzString | undefined} */ (/** @type {{ LZString?: LzString }} */ (/** @type {unknown} */ (globalThis)).LZString) const api = findApi(window) ?? (window.opener ? findApi(window.opener) : null) const started = Date.now() @@ -98,37 +208,147 @@ if (initialized) { /* * The learner's place. The content saves its state through the element (`resume="host"`), and - * the whole of it goes into `cmi.suspend_data`, stamped with the package's build so that a teacher - * who replaces the package does not hand its learners state saved against another one. + * the whole of it goes into `cmi.suspend_data`, compressed, stamped with the package's build so + * that a teacher who replaces the package does not hand its learners state saved against another + * one. With it go the questions answered, by interaction index, so that a question keeps its + * index across the sessions of an attempt (below). A state written plain, by a zip from before + * 1.5, is read as it is. */ /** @type {Map} */ const saved = new Map() +/** The question each interaction index is about, by index; kept with the state. @type {(string | null)[]} */ +let questions = [] -if (initialized) { +/** + * `cmi.suspend_data` read back: compressed since embed 1.5, plain JSON before, which begins + * with a brace, as no base64 does. + * @param {string} text + * @returns {unknown} + */ +function readState(text) { + if (!text) return null + const json = text.startsWith('{') ? text : (lz?.decompressFromBase64(text) ?? '') try { - const kept = JSON.parse(get('cmi.suspend_data') || 'null') - if (build && kept?.build === build && Array.isArray(kept.entries)) { - for (const [dataType, subContentId, data] of kept.entries) { - if (typeof data === 'string') saved.set(`${dataType}\n${subContentId}`, { dataType: String(dataType), subContentId: String(subContentId), data }) - } - } + return JSON.parse(json || 'null') } catch { - // Not ours, or cut short by an LMS: the content starts over. + return null + } +} + +if (initialized) { + const kept = /** @type {{ build?: unknown, entries?: unknown, questions?: unknown } | null} */ (readState(get('cmi.suspend_data'))) + // Not ours, or cut short by an LMS: the content starts over. + if (build && kept?.build === build && Array.isArray(kept.entries)) { + for (const [dataType, subContentId, data] of kept.entries) { + if (typeof data === 'string') saved.set(`${dataType}\n${subContentId}`, { dataType: String(dataType), subContentId: String(subContentId), data }) + } + if (Array.isArray(kept.questions)) questions = kept.questions.map((key) => (typeof key === 'string' ? key : null)) } player.setAttribute('resume', 'host') player.userData = [...saved.values()] } +let unsavedSaid = false + +/** + * Said once, under the content, when the state cannot be kept: it does not fit, or the LMS + * refused it. The content plays on; the learner's next launch starts from the last state that + * was kept, and the reason is in the console. + * @param {string} reason + */ +function unsaved(reason) { + console.warn(`The saved state was not kept: ${reason}`) + if (unsavedSaid || !saving) return + unsavedSaid = true + saving.textContent = 'Your progress past this point may not be saved for the next time you open this.' + saving.hidden = false +} + +/** Writes the state and commits it; says so when it cannot. */ +function saveState() { + const json = JSON.stringify({ build, entries: [...saved.values()].map((entry) => [entry.dataType, entry.subContentId, entry.data]), questions }) + const value = lz ? lz.compressToBase64(json) : json + // A state larger than SCORM 1.2 keeps is not written, rather than written cut short; the last + // one that fitted stays. + if (value.length > SUSPEND_DATA_LIMIT) return unsaved(`it is ${value.length} characters, and SCORM 1.2 keeps ${SUSPEND_DATA_LIMIT}.`) + if (!set('cmi.suspend_data', value)) return unsaved('the LMS refused to keep it.') + commit() +} + player.addEventListener('userdata', (event) => { + if (!initialized) return const { dataType, subContentId, data } = /** @type {CustomEvent} */ (event).detail const key = `${dataType}\n${subContentId}` if (data === null) saved.delete(key) else saved.set(key, { dataType, subContentId, data }) - const value = JSON.stringify({ build, entries: [...saved.values()].map((entry) => [entry.dataType, entry.subContentId, entry.data]) }) - // A state larger than SCORM 1.2 keeps is not saved, rather than saved cut short; the last one - // that fitted stays. - if (value.length <= SUSPEND_DATA_LIMIT && set('cmi.suspend_data', value)) commit() + saveState() +}) + +/* + * Each question's answer, as `cmi.interactions`: what Moodle's interactions report shows, a + * column per interaction index for every learner. So a question keeps one index, written over + * when it is answered again, rather than taking a new one on every attempt, which would set one + * learner's columns against another's. The index comes from the questions kept with the state, + * after what the LMS already counts; a new attempt, where the LMS counts none, starts them again. + * SCORM 1.2 lets the content write the fields and never read them, which the report does. + */ + +/** @type {Map} the id written for each question, so two with the same words differ */ +const ids = new Map() + +/** @param {string} key @param {AnsweredStatement} statement */ +function idFor(key, statement) { + const known = ids.get(key) + if (known) return known + const base = interactionId(questionText(statement, language), key) + const taken = new Set(ids.values()) + let id = base + for (let n = 2; taken.has(id); n++) id = `${base.slice(0, IDENTIFIER_LIMIT - 1 - String(n).length)}-${n}` + ids.set(key, id) + return id +} + +/** @param {string} key */ +function interactionIndex(key) { + const count = Math.max(0, Number(get('cmi.interactions._count')) || 0) + // The LMS counts fewer than the state names: a new attempt, which starts them again. + if (questions.length > count) questions = questions.slice(0, count) + let index = questions.indexOf(key) + if (index === -1) { + index = Math.max(questions.length, count) + questions[index] = key + } + return index +} + +/** @param {AnsweredStatement} statement */ +function recordAnswer(statement) { + const key = questionKey(statement) + const index = interactionIndex(key) + /** @param {string} field */ + const at = (field) => `cmi.interactions.${index}.${field}` + // The id first: it is the field that makes the record. + set(at('id'), idFor(key, statement)) + const definition = statement.object?.definition + const type = typeof definition?.interactionType === 'string' ? INTERACTION_TYPES[definition.interactionType] : undefined + if (type) set(at('type'), type) + const pattern = Array.isArray(definition?.correctResponsesPattern) ? definition.correctResponsesPattern[0] : undefined + if (typeof pattern === 'string') set(at('correct_responses.0.pattern'), pattern.slice(0, FEEDBACK_LIMIT)) + const result = statement.result ?? {} + if (typeof result.response === 'string') set(at('student_response'), result.response.slice(0, FEEDBACK_LIMIT)) + set(at('result'), outcomeOf(result)) + if (typeof result.score?.max === 'number') set(at('weighting'), String(result.score.max)) + const latency = latencyOf(result.duration) + if (latency) set(at('latency'), latency) + set(at('time'), timeOfDay()) +} + +player.addEventListener('xapi', (event) => { + if (!initialized) return + const { statement, verb } = /** @type {CustomEvent<{ statement?: AnsweredStatement, verb?: string }>} */ (event).detail + if (verb !== ANSWERED || !statement) return + recordAnswer(statement) }) /* diff --git a/packages/embed/site/scorm.html b/packages/embed/site/scorm.html index 0802a215..21d46b0b 100644 --- a/packages/embed/site/scorm.html +++ b/packages/embed/site/scorm.html @@ -31,9 +31,10 @@

H5P to SCORM

In the LMS

Add the zip to a course as a SCORM activity. The LMS records the score out of 100, whether - the content was passed or failed, or completed when it does not say, the time spent, and - the learner's place, so the next launch continues where they left off. Content that reports - no result of its own, an Accordion or a Virtual Tour, stays incomplete. + the content was passed or failed, or completed when it does not say, each question's + answer, the time spent, and the learner's place, so the next launch continues where they + left off. Content that reports no result of its own, an Accordion or a Virtual Tour, stays + incomplete.

diff --git a/packages/embed/tests/build.test.ts b/packages/embed/tests/build.test.ts index 33b86cdf..9638b2f7 100644 --- a/packages/embed/tests/build.test.ts +++ b/packages/embed/tests/build.test.ts @@ -93,7 +93,7 @@ describe('the site', () => { const out = join(dir, 'locked') const site = await buildSite({ out, packages: 'https://cdn.example.org', ancestors: ['https://school.example'] }) - for (const name of ['index.html', 'main.js', 'embed.js', 'embed.css', 'resizer.js', 'config.js', 'scorm.html', 'scorm-main.js', 'scorm-page.js', 'scorm-page.css', 'scorm-launch.html', 'scorm.js', 'h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js', 'libraries/index.json', 'libraries.txt', 'NOTICE.txt', '_headers', 'vercel.json', 'Caddyfile', 'nginx.conf', '.htaccess']) { + for (const name of ['index.html', 'main.js', 'embed.js', 'embed.css', 'resizer.js', 'config.js', 'scorm.html', 'scorm-main.js', 'scorm-page.js', 'scorm-page.css', 'scorm-launch.html', 'scorm.js', 'lz-string.js', 'h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js', 'libraries/index.json', 'libraries.txt', 'NOTICE.txt', '_headers', 'vercel.json', 'Caddyfile', 'nginx.conf', '.htaccess']) { expect(existsSync(join(out, name)), name).toBe(true) } for (const name of ['frame-boot.js', 'frame.bundle.js', 'h5p.css', 'LICENSE.txt', 'NOTICE.txt']) { diff --git a/packages/embed/tests/scorm.test.ts b/packages/embed/tests/scorm.test.ts index 31c87873..9229fdb8 100644 --- a/packages/embed/tests/scorm.test.ts +++ b/packages/embed/tests/scorm.test.ts @@ -1,5 +1,5 @@ import { execFile } from 'node:child_process' -import { createHash } from 'node:crypto' +import { createHash, randomBytes } from 'node:crypto' import { existsSync } from 'node:fs' import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { createServer, type Server } from 'node:http' @@ -41,7 +41,7 @@ describe('the package', () => { expect(built).toMatchObject({ out, title: 'Do you know what just happened?', libraries: [], build }) const zip = await entriesOf(out) - for (const name of ['imsmanifest.xml', 'index.html', 'scorm.js', 'embed.css', 'h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js', 'package.h5p', 'NOTICE.txt']) { + for (const name of ['imsmanifest.xml', 'index.html', 'scorm.js', 'lz-string.js', 'embed.css', 'h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js', 'package.h5p', 'NOTICE.txt']) { expect(zip.names).toContain(name) } expect(zip.names.filter((name) => name.startsWith('libraries'))).toEqual([]) @@ -250,8 +250,17 @@ const LMS_PAGE = ` window.API = { LMSInitialize: record('LMSInitialize', () => 'true'), LMSFinish: record('LMSFinish', sent('LMSFinish')), - LMSGetValue: record('LMSGetValue', (element) => window.values[element] ?? ''), + // The interactions' count, which SCORM 1.2 lets the content read: one past the highest index written. + LMSGetValue: record('LMSGetValue', (element) => { + if (element === 'cmi.interactions._count') { + const indexes = Object.keys(window.values).map((key) => /^cmi\\.interactions\\.(\\d+)\\.id$/.exec(key)).filter(Boolean).map((match) => Number(match[1])) + return String(indexes.length ? Math.max(...indexes) + 1 : 0) + } + return window.values[element] ?? '' + }), + // An LMS that refuses the saved state, when a test says so. LMSSetValue: record('LMSSetValue', (element, value) => { + if (window.refuse && element === 'cmi.suspend_data') return 'false' window.values[element] = value return 'true' }), @@ -379,6 +388,15 @@ describe('in an LMS', () => { const kept = await values(page) expect(kept).toMatchObject({ 'cmi.core.score.min': '0', 'cmi.core.score.max': '100', 'cmi.core.score.raw': '66.67' }) expect(kept['cmi.core.session_time']).toMatch(/^\d{2,4}:\d{2}:\d{2}\.\d{2}$/) + // Each question's answer as an interaction, by index, as Moodle's report reads them: the + // question's words as the id, since SCORM 1.2 has no description field. + expect(Object.keys(kept).filter((key) => /^cmi\.interactions\.\d+\.id$/.test(key))).toHaveLength(4) + expect(kept['cmi.interactions.0.id']).toMatch(/^[a-z0-9-]{3,80}$/) + expect(kept).toMatchObject({ 'cmi.interactions.0.type': 'choice', 'cmi.interactions.0.result': 'correct', 'cmi.interactions.1.type': 'true-false', 'cmi.interactions.1.result': 'correct', 'cmi.interactions.2.type': 'fill-in', 'cmi.interactions.2.result': 'correct' }) + expect(kept['cmi.interactions.0.student_response']).toBe(kept['cmi.interactions.0.correct_responses.0.pattern']) + expect(kept['cmi.interactions.0.weighting']).toMatch(/^\d+$/) + expect(kept['cmi.interactions.0.latency']).toMatch(/^\d{2,4}:\d{2}:\d{2}\.\d{2}$/) + expect(kept['cmi.interactions.0.time']).toMatch(/^\d{2}:\d{2}:\d{2}$/) const made = await calls(page) expect(made[0]).toEqual(['LMSInitialize', '']) expect(made).toContainEqual(['LMSSetValue', 'cmi.core.lesson_status', 'incomplete']) @@ -434,28 +452,144 @@ describe('in an LMS', () => { await context.close() }) - it('writes no state larger than SCORM 1.2 keeps, and keeps the last that fitted', async () => { + /** What `suspend_data` holds before and after the element saves `data`, and whether the page says it could not. */ + const save = (sco: Frame, data: string) => + sco.evaluate((data) => { + const lms = parent as unknown as { values: Record } + const before = lms.values['cmi.suspend_data'] + const player = document.querySelector('h5p-player') as HTMLElement + player.dispatchEvent(new CustomEvent('userdata', { detail: { dataType: 'state', subContentId: 'large', data } })) + const saying = document.getElementById('saving') as HTMLElement + return { before, after: lms.values['cmi.suspend_data'], said: !saying.hidden, text: saying.textContent } + }, data) + + /** `suspend_data` read back as the bridge reads it: compressed, by the page's own lz-string. */ + const decoded = (sco: Frame, text: string) => + sco.evaluate((text) => JSON.parse((window as unknown as { LZString: { decompressFromBase64: (s: string) => string } }).LZString.decompressFromBase64(text)), text) + + it('writes the state compressed, no larger than SCORM 1.2 keeps, and says once when it does not fit', async () => { const { context, page } = await lmsPage() + const warnings: string[] = [] + page.on('console', (message) => { if (message.type() === 'warning') warnings.push(message.text()) }) const { sco } = await launch(page) - /** What `suspend_data` holds before and after the element saves `data`. */ - const save = (data: string) => - sco.evaluate((data) => { - const lms = parent as unknown as { values: Record } - const before = lms.values['cmi.suspend_data'] - const player = document.querySelector('h5p-player') as HTMLElement - player.dispatchEvent(new CustomEvent('userdata', { detail: { dataType: 'state', subContentId: 'large', data } })) - return { before, after: lms.values['cmi.suspend_data'] } - }, data) - - const large = await save('x'.repeat(5000)) - expect(large.after).toBe(large.before) - const small = await save('small') - expect(JSON.parse(small.after).entries).toContainEqual(['state', 'large', 'small']) + + // A state that compresses: four times what SCORM 1.2 keeps, as JSON repeats itself, fits. + const long = JSON.stringify(Array.from({ length: 400 }, (_, i) => ({ question: i, answers: [0, 2], checked: true }))) + expect(long.length).toBeGreaterThan(4096 * 4) + const fits = await save(sco, long) + expect(fits.after).not.toBe(fits.before) + expect(fits.after).toMatch(/^[A-Za-z0-9+/=]+$/) + expect(fits.after.length).toBeLessThanOrEqual(4096) + expect(fits.said).toBe(false) + expect((await decoded(sco, fits.after)).entries).toContainEqual(['state', 'large', long]) + + // One that does not: random text has nothing to compress. The last state that fitted stays, + // and the page says so, once. + const random = randomBytes(6000).toString('base64') + const large = await save(sco, random) + expect(large.after).toBe(fits.after) + expect(large.said).toBe(true) + expect(large.text).toMatch(/may not be saved/) + expect(warnings.filter((text) => /SCORM 1\.2 keeps 4096/.test(text))).toHaveLength(1) + const again = await save(sco, `${random}x`) + expect(again.after).toBe(fits.after) + expect(warnings.filter((text) => /SCORM 1\.2 keeps 4096/.test(text))).toHaveLength(2) + expect(await sco.locator('#saving').count()).toBe(1) + const written = (await calls(page)).filter((call) => call[0] === 'LMSSetValue' && call[1] === 'cmi.suspend_data') expect(Math.max(...written.map((call) => call[2].length))).toBeLessThanOrEqual(4096) await context.close() }) + it('says once when the LMS refuses the state, and keeps playing', async () => { + const { context, page } = await lmsPage() + const warnings: string[] = [] + page.on('console', (message) => { if (message.type() === 'warning') warnings.push(message.text()) }) + const { sco } = await launch(page) + const kept = await save(sco, 'kept') + expect(kept.said).toBe(false) + await page.evaluate(() => { (window as unknown as { refuse: boolean }).refuse = true }) + const refused = await save(sco, 'refused') + expect(refused.after).toBe(kept.after) + expect(refused.said).toBe(true) + expect(warnings.filter((text) => /the LMS refused/.test(text))).toHaveLength(1) + expect(await sco.evaluate(() => (document.querySelector('h5p-player') as { state?: string }).state)).toBe('ready') + await context.close() + }) + + it('writes each answer as an interaction, one index per question, written over when answered again', async () => { + const ANSWERED = 'http://adlnet.gov/expapi/verbs/answered' + const { context, page } = await lmsPage() + const first = await launch(page) + /** A statement about the part `sub`, as the core writes one, dispatched as the element dispatches it. */ + const answer = (sco: Frame, sub: string, text: string, definition: Record = {}, result: Record = {}) => + sco.evaluate(({ verb, sub, text, definition, result }) => { + const statement = { + verb: { id: verb }, + object: { id: `http://lms.example/package.h5p?subContentId=${sub}`, definition: { description: { 'en-US': text }, interactionType: 'choice', correctResponsesPattern: ['0[,]2'], extensions: { 'http://h5p.org/x-api/h5p-subContentId': sub }, ...definition } }, + result: { response: '0[,]1', success: false, score: { raw: 0, max: 2 }, duration: 'PT12.5S', ...result } + } + ;(document.querySelector('h5p-player') as HTMLElement).dispatchEvent(new CustomEvent('xapi', { detail: { statement, verb } })) + }, { verb: ANSWERED, sub, text, definition, result }) + + await answer(first.sco, 'a', 'Which rivers cross Germany?') + // Another question with the same words takes another id. + await answer(first.sco, 'b', 'Which rivers cross Germany?') + let kept = await values(page) + expect(kept).toMatchObject({ + 'cmi.interactions.0.id': 'which-rivers-cross-germany', + 'cmi.interactions.0.type': 'choice', + 'cmi.interactions.0.correct_responses.0.pattern': '0[,]2', + 'cmi.interactions.0.student_response': '0[,]1', + 'cmi.interactions.0.result': 'wrong', + 'cmi.interactions.0.weighting': '2', + 'cmi.interactions.0.latency': '00:00:12.50', + 'cmi.interactions.1.id': 'which-rivers-cross-germany-2' + }) + expect(kept['cmi.interactions.0.time']).toMatch(/^\d{2}:\d{2}:\d{2}$/) + + // Answered again: the same index, the new answer, nothing added. + await answer(first.sco, 'a', 'Which rivers cross Germany?', {}, { response: '0[,]2', success: true, score: { raw: 2, max: 2 } }) + kept = await values(page) + expect(kept).toMatchObject({ 'cmi.interactions.0.student_response': '0[,]2', 'cmi.interactions.0.result': 'correct' }) + expect(kept['cmi.interactions.2.id']).toBeUndefined() + + // An Essay's long answer, as `fill-in`, cut to what 1.2 keeps; a type 1.2 has not, left out; + // a question with no words, named by its id; a result that says nothing, neutral; one that + // says nothing but scores, as Fill in the Blanks does, by its marks. + await answer(first.sco, 'c', '', { interactionType: 'long-fill-in', correctResponsesPattern: [] }, { response: 'x'.repeat(300), success: undefined, score: undefined, duration: undefined }) + await answer(first.sco, 'd', 'Other', { interactionType: 'other' }, { success: undefined, score: { raw: 1, max: 2 } }) + kept = await values(page) + expect(kept).toMatchObject({ 'cmi.interactions.2.id': 'c', 'cmi.interactions.2.type': 'fill-in', 'cmi.interactions.2.result': 'neutral', 'cmi.interactions.3.id': 'other', 'cmi.interactions.3.result': '1' }) + expect(kept['cmi.interactions.2.student_response']).toHaveLength(255) + expect(kept['cmi.interactions.2.correct_responses.0.pattern']).toBeUndefined() + expect(kept['cmi.interactions.2.latency']).toBeUndefined() + expect(kept['cmi.interactions.3.type']).toBeUndefined() + + // The questions go with the state, so the next session of the attempt keeps their indexes. + await save(first.sco, 'place') + expect((await decoded(first.sco, (await values(page))['cmi.suspend_data'])).questions).toEqual(['a', 'b', 'c', 'd']) + await page.evaluate(() => (window as unknown as { leave: () => void }).leave()) + await page.waitForFunction(() => (window as unknown as { calls: string[][] }).calls.some((call) => call[0] === 'LMSFinish')) + const second = await launch(page) + await answer(second.sco, 'b', 'Which rivers cross Germany?', {}, { response: '2' }) + await answer(second.sco, 'e', 'A new one') + kept = await values(page) + expect(kept).toMatchObject({ 'cmi.interactions.1.student_response': '2', 'cmi.interactions.4.id': 'a-new-one' }) + expect(kept['cmi.interactions.5.id']).toBeUndefined() + + // An attempt the LMS started over, its interactions gone: they start again from the first index. + await page.evaluate(() => { + const lms = window as unknown as { values: Record } + for (const key of Object.keys(lms.values)) if (key.startsWith('cmi.interactions.')) delete lms.values[key] + }) + await answer(second.sco, 'e', 'A new one', {}, { response: '1' }) + kept = await values(page) + expect(kept).toMatchObject({ 'cmi.interactions.0.id': 'a-new-one', 'cmi.interactions.0.student_response': '1' }) + expect(kept['cmi.interactions.1.id']).toBeUndefined() + await context.close() + }) + it('plays an export without its libraries from the parts in the zip, and only those', async () => { const { context, page } = await lmsPage() served.length = 0 @@ -478,9 +612,11 @@ describe('in an LMS', () => { await first.h5p.getByRole('button', { name: /^Next/ }).click() // H5P saves three seconds after a `progressed` statement. await page.waitForFunction(() => (window as unknown as { values: Record }).values['cmi.suspend_data'] !== '', null, { timeout: 30_000 }) - const kept = JSON.parse((await values(page))['cmi.suspend_data']) + const kept = await decoded(first.sco, (await values(page))['cmi.suspend_data']) expect(kept.build).toMatch(/^[0-9a-f]{16}$/) expect(kept.entries.length).toBeGreaterThan(0) + // The first question's answer, as an interaction. + expect((await values(page))['cmi.interactions.0.result']).toBe('correct') await page.evaluate(() => (window as unknown as { leave: () => void }).leave()) await page.waitForFunction(() => (window as unknown as { calls: string[][] }).calls.some((call) => call[0] === 'LMSFinish')) @@ -538,6 +674,19 @@ describe('in an LMS', () => { await context.close() }) + it('reads a state a zip from before wrote plain, so a learner keeps their place across the upgrade', async () => { + const { context, page } = await lmsPage() + const build = createHash('sha256').update(await readFile(quiz)).digest('hex').slice(0, 16) + await page.evaluate((build) => { + const lms = window as unknown as { values: Record } + lms.values['cmi.core.exit'] = 'suspend' + lms.values['cmi.suspend_data'] = JSON.stringify({ build, entries: [['state', 'kept', '{"progress":1}']] }) + }, build) + const { sco } = await launch(page) + expect(await sco.evaluate(() => (document.querySelector('h5p-player') as { userData?: unknown[] }).userData)).toEqual([{ dataType: 'state', subContentId: 'kept', data: '{"progress":1}' }]) + await context.close() + }) + it('plays with no LMS around it, and reports nothing', async () => { const context = await browser.newContext() const page = await context.newPage() From d566e3684792aded668bf8958cace3c6e242cb84 Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Wed, 4 Nov 2026 18:39:19 +0200 Subject: [PATCH 2/3] docs(agents): name #127 for the book's chapter on resume Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index c5b0902a..67ba5694 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2498,7 +2498,7 @@ one row each; an LMS added here gets a row there. 996 characters and came back with its chapters' state, and on its first chapter: Interactive Book takes its saved place (`urlFragments`, with `h5pbookid`) back only when that id is the content id, which the boot script draws at random on every load (`integrationFor`), so no book - returns to its chapter in any `resume` mode, a runtime bug outside #124, measured the same day + returns to its chapter in any `resume` mode, a runtime bug outside #124 (#127), measured the same day in the plain player with `resume="device"`. Two corpus books carry Interactive Book 1.3, which keeps no state at all. - **Outside an LMS** the page finds no API, plays the package and reports nothing. From eff5c371cae28f436f6aa9c17669ad73c439bd2f Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Wed, 4 Nov 2026 19:07:37 +0200 Subject: [PATCH 3/3] fix(scorm): address #126's review - A page that bundles the launch files and gives no compressor, as one written for 1.4 does, gets the one at `base` or a zip without it, whose page names none and whose bridge writes the state plain, rather than an export that fails on `lz-string.js`. - Each question's id is kept with its index in the state, so the second of two questions with the same words keeps its `-2` in a later session. - The state, and so the questions, is written and committed with every answer, since content that keeps no state sends no `userdata`. - The save notice and the launch page's error sit in live regions that are on the page from the start, empty, so a screen reader announces them. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 34 ++++++--- packages/embed/README.md | 7 +- packages/embed/lib/scorm-browser.mjs | 17 ++++- packages/embed/lib/scorm-core.mjs | 23 ++++-- packages/embed/scorm/index.html | 6 +- packages/embed/scorm/scorm.js | 86 ++++++++++++---------- packages/embed/tests/scorm-browser.test.ts | 38 ++++++++++ packages/embed/tests/scorm.test.ts | 49 ++++++++++-- 8 files changed, 194 insertions(+), 66 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 67ba5694..a06eb92d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2459,10 +2459,15 @@ one row each; an LMS added here gets a row there. `result.duration` as `latency`, the time of day. **One index per question, written over on a retry**, read in Moodle's code: its interactions report has one column per index for every learner (`get_scorm_question_count` takes the highest index found), so an entry per attempt - would set one learner's columns against another's. The index comes from the questions kept with - the state (`questions` in `suspend_data`, by index), after `cmi.interactions._count`, which 1.2 - lets a SCO read and Moodle reloads from the attempt's tracks; an attempt the LMS started over - counts none, and they start again. The fields are write-only; the reports read them. The commit is ILIAS's (#94, under *ILIAS plays it too*), and + would set one learner's columns against another's. The index and the id come from the + questions kept with the state (`questions` in `suspend_data`, a `[key, id]` per index, so that + the second of two questions with the same words keeps its `-2` in a later session), after + `cmi.interactions._count`, which 1.2 lets a SCO read and Moodle reloads from the attempt's + tracks; an attempt the LMS started over counts none, and they start again. The state is written + and committed with each answer as well as with each of the content's saves, since content that + keeps no state of its own sends no `userdata`, and its questions would otherwise take a new + index in every session; where the state cannot be written, the answer is still committed (both + found in #126's review). The fields are write-only; the reports read them. The commit is ILIAS's (#94, under *ILIAS plays it too*), and only a commit: the content's last save comes after it, and the learner may stay. Moodle's API sends with `navigator.sendBeacon` while unloading, and the `exit` it stored showed that the call arrived. Content with no result of its own stays `incomplete`. Moodle takes `score.raw` as the @@ -2486,6 +2491,10 @@ one row each; an LMS added here gets a row there. 4,096 characters; a larger state is not written, and the last one that fitted stays. Until #124 that was silent; now the page says so once, under the content (`#saving`), and in the console, as it does when the LMS refuses the write, which the bridge checks `LMSSetValue`'s answer for. + `#saving` and the launch page's error, `#notice`, each sit in a live region that is on the page + from the start, empty (`role="status"`, `role="alert"`), as `ACCESSIBILITY.md` asks of a host, + since a region that appears with its text is not announced by every screen reader; until #126's + review each was the region itself, hidden. Moodle takes 64,000 when its administrator turns "SCORM 1.2 standard mode" off (`scormstandard` in `public/mod/scorm/datamodels/scorm_12.php`). Checked in Moodle: a learner left after the first question, the next launch's `entry` was `resume`, and the @@ -2641,7 +2650,10 @@ one row each; an LMS added here gets a row there. `scorm-browser.mjs`, `./scorm/browser`, is the page's, `buildScormInPage()`: the package a `File`, the player's files, the runtime and the pack fetched from the site the page is on (`base`, `pack` or `packBase`, or `assets` for a page that bundles the launch page, the bridge, the - stylesheet and the licence list), each part checked against the index's SHA-256 since it came + compressor, the stylesheet and the licence list; a page that gives the launch page and not the + compressor, as one bundled for 1.4 does, gets the one at `base` or a zip without it, whose page + names none and whose bridge writes the state plain, rather than an export that fails for a file + it never had to serve), each part checked against the index's SHA-256 since it came over the network, and the zip a `Blob`. The runtime's files are named by a list, `RUNTIME_FILES`, plus the fonts from its `MANIFEST.json`, since a folder on a server cannot be listed; `scorm-browser.test.ts` runs the builder in Node, which has `fetch`, `File` and @@ -2675,11 +2687,13 @@ frames the launch page, as Moodle's player does. It covers: - a passed and a failed result, the end of the session, resume, and refusing state saved by another build, and reading one a zip up to 1.4 wrote plain; - the quiz's four answers as interactions, and, through dispatched `xapi` events, the id from - the words and from the key, the second id for the same words, the type map, the 255 cut, the - result from `success` and from the score, one index per question across a retry and a second - session, and an attempt started over; -- a state that fits only compressed, one that does not fit at all and the notice said once, and - a write the LMS refuses; + the words and from the key, the second id for the same words, kept in a later session, the + type map, the 255 cut, the result from `success` and from the score, the questions written and + committed with each answer, one index per question across a retry and a second session, and an + attempt started over; +- a state that fits only compressed, one that does not fit at all and the notice said once, + both notices' live regions on the page from the start, a write the LMS refuses, and a launch + page without the compressor, which writes the state plain; - the commit on `beforeunload` and the finish on `pagehide`, by the event the launch page was dispatching when it called, which is what ILIAS goes by, and a leave the learner stays from; - a result with no score, and a state past 4,096 characters, through the element's events diff --git a/packages/embed/README.md b/packages/embed/README.md index 5bed5da3..9cc897c9 100644 --- a/packages/embed/README.md +++ b/packages/embed/README.md @@ -245,8 +245,11 @@ and `build`, the stamp saved state is kept against. Every entry ships with TypeS `buildScormInPage` from `@missing-elements/h5p-embed/scorm/browser` is the same build in a page: it takes `file`, a `File` or `Blob`; `base`, the folder with the player's three files and `frame-assets/` (the page's own by default); `pack` or `packBase`, as `startEmbed` takes them; -`assets`, for a page that bundles the launch page's template, its bridge, `embed.css` and the -pack's `libraries.txt` rather than serving them beside the player as the written site does; +`assets`, for a page that bundles the launch page's template, its bridge, its compressor +(`lz`, `scorm/lz-string.js`), `embed.css` and the pack's `libraries.txt` rather than serving them +beside the player as the written site does, where a page that gives the template and not the +compressor gets the one at `base`, or a zip without it that keeps the saved state plain, as 1.4 +did; `version` and `packVersion`, for the zip's notice; and `onProgress`. It returns the zip as a `Blob`, with its `name`, `title`, `libraries`, `build` and `size`. `startScormPage` from `@missing-elements/h5p-embed/scorm-page.js` is the page's script, which reads the page's diff --git a/packages/embed/lib/scorm-browser.mjs b/packages/embed/lib/scorm-browser.mjs index 9d5432f7..9ce18640 100644 --- a/packages/embed/lib/scorm-browser.mjs +++ b/packages/embed/lib/scorm-browser.mjs @@ -37,7 +37,9 @@ import { EmbedError, PLAYER_FILES } from './shared.mjs' * @property {{ launch?: string, bridge?: string | Blob, lz?: string | Blob, css?: string | Blob, libraries?: string | Blob }} [assets] * the launch page's template, its bridge, the compressor the bridge keeps the saved state with * (`scorm/lz-string.js`), the stylesheet and the pack's licence list, for a page that bundles - * them rather than serving them beside the player + * them rather than serving them beside the player. A page that gives the launch page and not the + * compressor gets the one at `base`, or a zip without it, whose bridge writes the saved state + * plain, as embed 1.4 did * @property {string} [version] the player's version, for the notice; `unknown` if not given * @property {string | null} [packVersion] the pack's, the same way * @property {(progress: ScormProgress) => void} [onProgress] @@ -135,6 +137,17 @@ export async function buildScormInPage(options) { onProgress({ step: 'libraries', libraries: parts.length }) /** @param {string} url @param {string} what */ const blob = async (url, what) => (await fetched(fetchImpl, url, what)).blob() + // The compressor came in 1.5, after pages that bundle the launch files were written: such a page + // that does not give it plays on without it, its state plain, rather than fail for a file it + // never had to serve. + const compressor = async () => { + try { + return await blob(at('lz-string.js'), "The launch page's compressor") + } catch (error) { + if (assets.launch !== undefined && error instanceof EmbedError) return null + throw error + } + } /** @param {string[]} names @param {(name: string) => string} url @param {string} what */ const blobs = async (names, url, what) => new Map(await Promise.all(names.map(async (item) => /** @type {[string, Blob]} */ ([item, await blob(url(item), `${what} ${item}`)])))) const partBlobs = await blobs(parts.map((part) => part.folder), (folder) => /** @type {import('./scorm-core.mjs').PackPart} */ (parts.find((part) => part.folder === folder)).url, 'The library part') @@ -149,7 +162,7 @@ export async function buildScormInPage(options) { const files = { launch: assets.launch ?? (await (await fetched(fetchImpl, at('scorm-launch.html'), "The launch page's template")).text()), bridge: assets.bridge !== undefined ? asBlob(assets.bridge) : await blob(at('scorm.js'), 'The launch page\'s script'), - lz: assets.lz !== undefined ? asBlob(assets.lz) : await blob(at('lz-string.js'), 'The launch page\'s compressor'), + lz: assets.lz !== undefined ? asBlob(assets.lz) : await compressor(), css: assets.css !== undefined ? asBlob(assets.css) : await blob(at('embed.css'), 'The stylesheet'), player: await blobs(PLAYER_FILES, at, "The player's file"), runtime: await blobs(runtimeFiles(runtimeManifest), (path) => at(`frame-assets/${path}`), "The runtime's file"), diff --git a/packages/embed/lib/scorm-core.mjs b/packages/embed/lib/scorm-core.mjs index 486ce769..e3a22ebe 100644 --- a/packages/embed/lib/scorm-core.mjs +++ b/packages/embed/lib/scorm-core.mjs @@ -86,8 +86,8 @@ ${files.map((file) => ` `).join('\n')} ` } -/** @param {{ version: string, source: string, pack: string | null }} zip `pack`, the library pack's version when the zip carries parts of it */ -function notice({ version, source, pack }) { +/** @param {{ version: string, source: string, pack: string | null, lz: boolean }} zip `pack`, the library pack's version when the zip carries parts of it; `lz`, whether it carries the compressor */ +function notice({ version, source, pack, lz }) { return `This is a SCORM 1.2 package written by @missing-elements/h5p-embed. It plays ${source} in an LMS and reports its score, its result, each question's answer and the time spent, and keeps the learner's place. @@ -95,9 +95,13 @@ learner's place. imsmanifest.xml the package's manifest index.html, scorm.js, embed.css the launch page and its bridge to the LMS: MIT - lz-string.js lz-string 1.5.0, which the bridge compresses the learner's saved state +${ + lz + ? ` lz-string.js lz-string 1.5.0, which the bridge compresses the learner's saved state with: MIT, its licence in its header. - h5p-player.js, h5p-sw.js, h5p-jobs.js +` + : '' +} h5p-player.js, h5p-sw.js, h5p-jobs.js @missing-elements/h5p-offline-player ${version}: MIT. The Service Worker, h5p-sw.js, also carries zip.js, BSD-3-Clause, its licence in its header. frame-assets/ @missing-elements/h5p-runtime, the H5P core runtime: GPL-3.0-only. Its @@ -260,7 +264,9 @@ export async function readPackage(blob, name, pack, { useWebWorkers = false } = * @typedef {object} ScormFiles * @property {string} launch the launch page's template, `scorm/index.html` * @property {Blob} bridge `scorm/scorm.js` - * @property {Blob} lz `scorm/lz-string.js`, which the bridge compresses the saved state with + * @property {Blob | null} lz `scorm/lz-string.js`, which the bridge compresses the saved state + * with; without it the launch page names none, and the state is written plain, as embed 1.4 + * wrote it * @property {Blob} css `embed.css` * @property {Map} player the player's files, by name * @property {Map} runtime the runtime's files, by path under `frame-assets/` @@ -295,6 +301,9 @@ export function scormEntries({ manifest, source, title, build, version, packVers // The element plans from the zip's index what the writer planned, and plays the package's own // libraries as they are. .replace('%LIBRARIES%', pack ? ` libraries="pack" pack-base="./${LIBRARIES}/" refresh-libraries="off"` : '') + // Without the compressor, which a page that bundles the launch files may not give, the page + // names none, rather than a script the zip lacks. + .replace(/\n[ \t]*') + const listed = [...(await zip.text('imsmanifest.xml')).matchAll(//g)].map((match) => match[1]) + expect(listed.sort()).toEqual([...zip.names].sort()) + expect(await zip.text('NOTICE.txt')).not.toContain('lz-string') + await zip.close() + + // Given it, the zip carries it, as from the site. + const given = await buildScormInPage({ file: await picked(quiz, 'quiz.h5p'), ...onSite(site), assets: { ...assets, lz: 'var LZString = {}' }, fetch: withoutCompressor }) + await writeFile(out, new Uint8Array(await given.blob.arrayBuffer())) + const withIt = await entriesOf(out) + expect(await withIt.text('lz-string.js')).toBe('var LZString = {}') + expect(await withIt.text('index.html')).toContain('') + await withIt.close() + + // A page that takes the launch files from the site takes the compressor from it too, and a + // site without it is refused, naming it. + await expect(buildScormInPage({ file: await picked(quiz, 'quiz.h5p'), ...onSite(site), fetch: withoutCompressor })).rejects.toThrow( + /The launch page's compressor is not at .*\/lz-string\.js: it answered 404\./ + ) + }) }) diff --git a/packages/embed/tests/scorm.test.ts b/packages/embed/tests/scorm.test.ts index 9229fdb8..5c95225d 100644 --- a/packages/embed/tests/scorm.test.ts +++ b/packages/embed/tests/scorm.test.ts @@ -309,6 +309,11 @@ describe('in an LMS', () => { } await zip.close() } + // The quiz's launch page without the compressor, as the page builder writes it for a page that + // bundles the launch files and gives none (`scorm-browser.test.ts`). + const launchPage = await readFile(join(root, 'index.html'), 'utf8') + expect(launchPage).toContain('') + await writeFile(join(root, 'plain.html'), launchPage.replace(/\n[ \t]*