diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ddfb1b03..cefdbda6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,3 +81,33 @@ jobs: - run: pnpm test:engine env: H5P_TEST_BROWSER: ${{ matrix.browser }} + + # The VS Code extension in a real VS Code, on a display Xvfb gives it, and the .vsix the owner + # publishes, built from what the tests ran against. The unit tests run in the job above. + vscode: + name: VS Code extension + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v6 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: pnpm + - run: pnpm install --frozen-lockfile + # The player and the runtime, which the extension carries. + - run: pnpm build + # The editor the tests download, about 150 MB, a new stable a month: kept a week at a time. + - id: week + run: echo "week=$(date -u +%G-%V)" >> "$GITHUB_OUTPUT" + - uses: actions/cache@v6 + with: + path: packages/vscode/.vscode-test + key: vscode-test-${{ steps.week.outputs.week }} + restore-keys: vscode-test- + - run: xvfb-run -a pnpm --filter h5p-preview test:vscode + - run: pnpm --filter h5p-preview package + - uses: actions/upload-artifact@v4 + with: + name: h5p-preview-vsix + path: packages/vscode/*.vsix diff --git a/.gitignore b/.gitignore index dfae8aa8..0309098c 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,14 @@ packages/verify/LICENSE packages/cmi5/LICENSE packages/embed/LICENSE +# The VS Code extension's build: the player, runtime and library pack it carries, the licence and +# notice written for its .vsix, the .vsix itself, and the VS Code its tests download. +packages/vscode/assets/ +packages/vscode/LICENSE +packages/vscode/NOTICE.txt +*.vsix +.vscode-test/ + # h5p-verify writes its report and screenshot to .verify/ beside the package by default. *.verify/ diff --git a/AGENTS.md b/AGENTS.md index ba5d861a..1fb9e824 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,8 +28,10 @@ The hard constraints that shape every file here: ## Layout -A pnpm workspace of nine parts: seven packages and two apps, the demo and the skills' test project. Paths elsewhere in this file are relative to the part they -belong to — `src/…` and `scripts/…` mean the player's unless a section says otherwise. +A pnpm workspace of ten parts: eight packages and two apps, the demo and the skills' test project. +Seven of the packages are published to npm; the eighth, the VS Code extension, is a `.vsix`. Paths +elsewhere in this file are relative to the part they belong to — `src/…` and `scripts/…` mean the +player's unless a section says otherwise. ``` packages/player/ @missing-elements/h5p-offline-player — the published package @@ -154,7 +156,10 @@ packages/normalize/ @missing-elements/h5p-normalize — the package rewrit packages/verify/ @missing-elements/h5p-verify — plays a package headless and reports whether it works bin/h5p-verify.mjs the command - lib/verify.mjs the static server, the browser run and the report; lib/page.html the page it drives + lib/verify.mjs the browser run and the report; lib/page.html the page it drives + lib/serve.mjs what the check and the preview share, and no Playwright: the package on + disk, the library sources, the static server for the player and the + runtime; the VS Code extension bundles it (2026-10-26) lib/preview.mjs `--preview`: the package in the person's own browser, served by range until its last tab has closed; lib/preview.html its page tests/ node tests that run the real thing against the demo's committed content; @@ -188,6 +193,25 @@ packages/embed/ @missing-elements/h5p-embed — the embed page as a st normalizer types/ generated, not in git: the declarations of both entries +packages/vscode/ h5p-preview, "H5P Preview by Missing Elements" — the VS Code extension, a .vsix + for the Visual Studio Marketplace and Open VSX, not on npm (see *The VS Code + extension*) + src/extension.mjs activate(): the custom editor, the commands, the settings and trust events + src/previews.mjs the editor provider: documents (a copy for a remote file), previews, the + window's server, Open in Browser, playing again when the file changes + src/server.mjs the window's preview server: the verifier's `serve` and `sendArchive`, + a page per package at /view/, the package at /__package// + src/page.mjs the page the webview frames: the element, and what it reached posted up + src/webview.mjs the webview: the bar (status, Untrusted, Newest libraries) and the frame + scripts/build.mjs dist/extension.cjs (esbuild, the verifier's modules bundled, Playwright + refused), assets/ (the player's files, the runtime, the pack's parts), + NOTICE.txt; scripts/package.mjs the .vsix (vsce, --no-dependencies); + scripts/icon.mjs icon.png from the logo (`pnpm --filter h5p-preview icon`) + tests/ server.test.ts and html.test.ts in Node; vscode/ the suite that runs in a + real VS Code (run.mjs downloads it, suite.cjs runs in its extension host) + README.md, CHANGELOG.md the Marketplace page and its changelog; icon.png the project's logo at + 256 px, rendered in Chromium from the demo's demo/favicon.svg, committed + apps/demo/ the demo app: the dev server for the whole repository, and the hosted site index.html the hosted player page embed.html the embeddable page, /embed: the element alone, driven by the query @@ -326,6 +350,8 @@ pnpm typecheck # every package pnpm build # the player: types, element, both workers; builds the runtime package on the way pnpm normalize course.h5p # rewrite a package so it streams: media stored, mp4 index first pnpm verify course.h5p # play a package in a headless browser and report whether it works +pnpm --filter h5p-preview package # the VS Code extension's .vsix, from the player as pnpm build left it +pnpm --filter h5p-preview test:vscode # its suite in a VS Code it downloads; under xvfb-run on Linux pnpm build:demo # the hosted demo into apps/demo/dist-demo/, what Vercel runs pnpm demo:content # rebuild apps/demo/demo/content/*.h5p from their sources; needs the H5P hub pnpm demo:og # re-render the social card, apps/demo/demo/og-image.png @@ -1793,6 +1819,114 @@ The tests need the player built (`pnpm build`); the package's `test` script does The repository's own sweep does click through content and read its statements (next section), for packages it makes; the verifier, which is handed a stranger's, still does not. +## The VS Code extension + +`packages/vscode` is **H5P Preview by Missing Elements** (`missing-elements.h5p-preview`): a `.h5p` +opens in a read-only custom editor that plays it. Built on 2026-10-26 (#83), the first of the +plugins weighed in the owner's notes: the Marketplace had one H5P extension, for developing content +types, and nothing that played a package. It is not on npm. The owner publishes the `.vsix` to the +Visual Studio Marketplace (publisher `missing-elements`) and to Open VSX, for Cursor and VSCodium. +The name is the owner's, under H5P Group's trademark policy (h5p.org/trademark, 2.5): open-source +code may lead with "H5P" only beside its author, "Acme's H5P interactive Quiz" being its example. +The icon is the project's logo, a play triangle with a hand tapping it, which the owner made on +2026-10-27 in place of the "H5P" tile, which was close to H5P Group's own mark. Its hand is filled, +pale on a dark ground as on a light one: in the first version, the same day, it was cut out of the +triangle and took the ground's colour. One file holds it, the demo's +`demo/favicon.svg`, and everything else is drawn from that: the site's tab and the bar's mark, on +the pages and in the installable app, read it as it is; the app's icons (`pnpm demo:icons`), the +social card (`pnpm demo:og`) and this icon (`pnpm --filter h5p-preview icon`) are rendered from it +and committed, as are the app's install screenshots (`pnpm demo:screenshots`), which show the bar. + +- **A webview frames a page from a server on 127.0.0.1.** A webview's own origin, + `vscode-webview://`, cannot register a Service Worker, since the spec takes `http` and `https` + script URLs only; a page it frames from a local server can. Measured in VS Code 1.143.1 + (Electron 43, Chrome 150) on macOS, 2026-10-26: the frame's worker registers and controls it, the + demo quiz reaches `ready` in 0.5 s, and the Interactive Video's H.264 clip decodes (`canPlayType` + says "probably", `readyState` 4). +- **One server per window, on the first free port from 4646 to 4655.** Every preview in the window + shares it. Each port is an origin with the player's worker and caches of its own, so the address + has to be the same from session to session: the first window takes 4646, a second the next free + port, and only past 4655 does the server take any free one (`serve` takes a list of ports for + this). Until 2026-10-27 it was 4646 or any free port, and every start of a second window's + server was a new origin, the last one's worker and caches left behind (#84's review). The + command's 4645 is left to Open in Browser. A package is served under a hash of its URI, + `/view/` its page and `/__package//` the archive, the same in every session, and + stops being served with its last preview. The server stops with the last preview and starts + again with the next. Not the command's `previewPackage`, which serves one package for as long as + a tab holds it. +- **The verifier's server, bundled from this checkout.** `src/server.mjs` imports `serve` from + `lib/serve.mjs` and `sendArchive` from `lib/preview.mjs` by relative path, as the skills' playback + test imports `previewPackage`. They are `@internal`, so a change to them is a change to the + extension, and its tests are where it shows. `lib/serve.mjs` was split out of `lib/verify.mjs` the + same day, because `verify.mjs` imports Playwright at its top and the preview needs none of it; + `scripts/build.mjs` refuses `playwright-core` with an esbuild plugin, so it stays out. The bundle + is CommonJS, which VS Code's `require` loads, and the verifier's modules find their files by + `import.meta.url`, which CommonJS has not: the build defines it as the bundle's own URL and puts + `preview.html` beside the bundle, for Open in Browser. +- **The extension carries everything it serves.** `assets/` is copied at build from the installed + packages, as the embed builder takes them: the player's three files, the runtime, the library + pack's parts and `libraries.txt`. Content-only exports play offline and nothing leaves the + machine. `vsce package --no-dependencies` ships `dist/` and `assets/` and no node_modules: 13.8 MB + in 141 files on 2026-10-26. `--baseContentUrl` and `--baseImagesUrl` point the README's relative + links at `packages/vscode/`, where vsce's default would point them at the repository's root. +- **Trust follows the workspace.** In Restricted Mode every package plays `untrusted`, the switch + disabled. A trusted workspace plays as the settings say (`h5pPreview.untrusted`, + `h5pPreview.newestLibraries`), with a switch for each in every editor. A change of setting, or + trust granted, plays the open previews again as the settings now say. The page sets `untrusted` + as an attribute, as it sets the others: its script runs before the module defines + ``, and a property set then stays on the element as its own, in front of the class's + accessor. Until 2026-10-27 it set the property. Measured in Chrome, the package still played + untrusted, because every read in the element goes through `this.untrusted`, which found the stray + property; but the attribute was never there, and an element reading it would have played + Restricted Mode's packages trusted while the bar said untrusted. The page's report reads the + attribute, so the suite's untrusted tests check what the element plays by. Restricted Mode is the + server's to keep, not the address's: `startServer` asks the workspace's trust at each page and, + while it is restricted, plays every page untrusted whatever the address says. An untrusted + package's content keeps its links, http and relative, and until 2026-10-27 one to its own page + without the flag, clicked, played it trusted; the page's id, a hash of the file's path, was all + that stood in the way. The tab's switch in a trusted workspace is still the address's alone, a + convenience rather than a boundary. +- **Messages are taken from one sender each.** The page posts what the element reached to its first + ancestor origin only (`location.ancestorOrigins[0]`, the webview). The webview takes the frame's + messages by its window and the server's origin, and relays a state, `ready` and an error and + nothing else; reload and the settings it takes from the extension alone, by its own origin. A + package's own code runs in a frame below the page, on the server's origin. What it posts itself + comes from neither, and played trusted, sharing the page's origin, it can post as the page, so the + most it can do is misreport its own state. Until 2026-10-27 the webview relayed whatever the page + posted, a `mode` among them, which the extension took for the tab's switches and Open in Browser + played by. `tests/html.test.ts` runs both scripts in Node against stand-ins for their elements. +- **A file that is not on this computer is copied first.** `extensionKind` is `ui` alone, so the + extension runs beside the webview, which reaches only this computer's loopback; a remote or + virtual workspace's file is copied to a temporary folder through `workspace.fs`, and copied again + when it changes. Copied again, the file is read whole before the copy is touched, so a read that + fails leaves the copy, and its previews, as they were, with a warning that names the reason; until + 2026-10-27 the read sat outside its `catch`, the failure went unhandled and nothing said so. The + suite plays a package from a file system of its own, a scheme over a folder that can say a file + changed and can fail its reads, which takes this path: played, changed while it cannot be read, + changed again. A real remote, SSH or a container, is not tested. `workspace` was in the + list until 2026-10-27. VS Code for the Web with Codespaces then runs the extension on the remote + machine, as the desktop does when it is installed only there, and the server listened on that + machine's loopback while the webview framed this one's. Having no `browser` entry, the extension + is now unavailable in VS Code for the Web, rather than installed and showing nothing. +- **A file written again plays again**, 500 ms after it last changed. A watcher on the file's folder + sends the reload when an event names the file, and the validator, the file's size and time, makes + it a new package to the element. The folder is watched and the name compared because a name as + the pattern is a glob: until 2026-10-27 it was, and `quiz [v2].h5p` never matched itself, so its + previews never played again. The suite's file is named `package [v2] {draft}.h5p` for that. + +Tests. `tests/*.test.ts` run in Node with the rest of `pnpm test`: the server against the built +player, runtime and pack, with its run of ports and Restricted Mode, and the webview's and the +page's scripts run against stand-ins. `tests/vscode/run.mjs` downloads VS Code into +`.vscode-test/` and runs `suite.cjs` in its extension host. The suite opens the demo's packages and +waits on the extension's `onDidChangeState`, the one thing `activate` exports: the quiz, the +Interactive Video, a content-only export played from the pack, Reload, untrusted by setting and +live, a package on a file system of the suite's own, copied again when it changes and kept when it +cannot be read, and a file written again under a name with brackets and braces. CI runs it on Linux under `xvfb-run`, in the `vscode` job, which +also uploads the `.vsix`. Started from a terminal inside VS Code, the downloaded editor ran as plain +Node, because `ELECTRON_RUN_AS_NODE` is inherited; `run.mjs` deletes it. Not covered: Restricted +Mode in a real editor (the suite opens a trusted folder; the server's side of it is a Node test), +Open in Browser, a real remote, and Windows. + ## Types for the plain-JS packages The normalizer, the verifier and the embed package are JavaScript with JSDoc, and since #60 their @@ -2719,6 +2853,10 @@ libraries.txt` and that file lists every one. Moving our code to the GPL was con GPL dependency is what corporate policies and scanners refuse. MPL-2.0 remains the middle ground if closed forks ever matter. +The VS Code extension is MIT and carries the runtime and the libraries as separate files beside its +bundle, as the embed package's site does; its `NOTICE.txt`, written by its build, says which file is +what, with the versions carried. + **The setups are named, both are self-hosting, and Install comes first.** Decided on 2026-10-09, after the owner's public site was repositioned as a test tool: the player's main benefit is that a host runs H5P on its own infrastructure — no H5P server, no backend, no third-party service in @@ -2765,6 +2903,8 @@ deliberate additions to it, not drift: is how they get the layout the player streams best. - A verifier command. The design has the player play packages; the command has it judge them, headless, for whoever produces packages by machine. +- A VS Code extension. The design has the player on websites; the extension plays a package in + the editor, from a server on the author's own computer. - The libraries are warmed into the cache before the frame boots on a `Range` host. The design reads every entry on demand; on a high-latency host that made the boot a matter of minutes. - A library source that cannot be reached falls back to a bundle downloaded whole from the same diff --git a/apps/demo/app/icons/apple-touch-icon.png b/apps/demo/app/icons/apple-touch-icon.png index 2cb7fa85..b78c5915 100644 Binary files a/apps/demo/app/icons/apple-touch-icon.png and b/apps/demo/app/icons/apple-touch-icon.png differ diff --git a/apps/demo/app/icons/icon-192.png b/apps/demo/app/icons/icon-192.png index 007e9b98..5532656c 100644 Binary files a/apps/demo/app/icons/icon-192.png and b/apps/demo/app/icons/icon-192.png differ diff --git a/apps/demo/app/icons/icon-512.png b/apps/demo/app/icons/icon-512.png index 2ab95307..3820b8d6 100644 Binary files a/apps/demo/app/icons/icon-512.png and b/apps/demo/app/icons/icon-512.png differ diff --git a/apps/demo/app/icons/icon-maskable-512.png b/apps/demo/app/icons/icon-maskable-512.png index 43e74cf2..0b76e90b 100644 Binary files a/apps/demo/app/icons/icon-maskable-512.png and b/apps/demo/app/icons/icon-maskable-512.png differ diff --git a/apps/demo/app/screenshots/narrow-home.png b/apps/demo/app/screenshots/narrow-home.png index 90dee054..ff78a235 100644 Binary files a/apps/demo/app/screenshots/narrow-home.png and b/apps/demo/app/screenshots/narrow-home.png differ diff --git a/apps/demo/app/screenshots/narrow-quiz.png b/apps/demo/app/screenshots/narrow-quiz.png index 2aaa67bc..b19b9bfa 100644 Binary files a/apps/demo/app/screenshots/narrow-quiz.png and b/apps/demo/app/screenshots/narrow-quiz.png differ diff --git a/apps/demo/demo/favicon.svg b/apps/demo/demo/favicon.svg index f7d947b2..fae4d246 100644 --- a/apps/demo/demo/favicon.svg +++ b/apps/demo/demo/favicon.svg @@ -1,4 +1,20 @@ - - - H5P + + + + + + + + + + + + + + + + + + + diff --git a/apps/demo/demo/og-image.png b/apps/demo/demo/og-image.png index 019dfcc1..d805db1a 100644 Binary files a/apps/demo/demo/og-image.png and b/apps/demo/demo/og-image.png differ diff --git a/apps/demo/scripts/build-app-icons.mjs b/apps/demo/scripts/build-app-icons.mjs index 3fd488d6..25c80359 100644 --- a/apps/demo/scripts/build-app-icons.mjs +++ b/apps/demo/scripts/build-app-icons.mjs @@ -1,39 +1,38 @@ -import { mkdir, writeFile } from 'node:fs/promises' +import { mkdir, readFile, writeFile } from 'node:fs/promises' import { resolve } from 'node:path' import { chromium } from 'playwright' /** - * Renders the installable app's icons into `app/icons/`: the site's "H5P" mark at 192 and 512, - * and a maskable 512 whose mark sits inside the safe zone, the centre 80%, since a launcher may - * crop it to a circle, and a 180 for iOS, which ignores the manifest's icons for the home screen - * and draws a screenshot of the page without one. Rasterized in Chromium for the same reason as the social card — no image - * tooling in the repository. The output is committed; run this when the mark changes. + * Renders the installable app's icons into `app/icons/` from the site's logo, `demo/favicon.svg`, + * which the tab and the bar's mark show too: the logo at 192 and 512 on a transparent ground; a + * maskable 512, opaque, whose logo sits inside the safe zone, the circle in the centre 80%, since a + * launcher may crop it to one; and a 180 for iOS, which ignores the manifest's icons for the home + * screen and draws a screenshot of the page without one. Rasterized in Chromium for the same reason + * as the social card — no image tooling in the repository. The output is committed; run this when + * the logo changes. */ const rootDir = resolve(import.meta.dirname, '..') const outDir = resolve(rootDir, 'app', 'icons') +const logo = await readFile(resolve(rootDir, 'demo', 'favicon.svg'), 'utf8') -/** `inset` is the share of the canvas the tile leaves empty on each side. */ -const page = (size, { inset, radius }) => ` +/** `inset` is the share of the canvas left empty around the logo's square on each side; `ground` the colour under it. */ +const page = (size, { inset, ground }) => `
H5P
` + html, body { margin: 0; width: ${size}px; height: ${size}px; background: ${ground ?? 'transparent'}; } + svg { position: absolute; left: ${inset * size}px; top: ${inset * size}px; width: ${(1 - 2 * inset) * size}px; height: ${(1 - 2 * inset) * size}px; } +${logo}` const icons = [ - { name: 'icon-192.png', size: 192, inset: 0, radius: 0.22 }, - { name: 'icon-512.png', size: 512, inset: 0, radius: 0.22 }, - // Full bleed: the launcher supplies the shape. The mark stays within the centre 80%. - { name: 'icon-maskable-512.png', size: 512, inset: 0.1, radius: 0 }, + // The logo as drawn, with the margin it has. + { name: 'icon-192.png', size: 192, inset: 0 }, + { name: 'icon-512.png', size: 512, inset: 0 }, + // Full bleed: the launcher supplies the shape. At 70% of the canvas the logo's farthest point + // from the centre stays inside the safe zone's circle. + { name: 'icon-maskable-512.png', size: 512, inset: 0.15, ground: '#ffffff' }, // `apple-touch-icon`: opaque and square, since iOS rounds the corners itself and draws any // transparent pixel black. - { name: 'apple-touch-icon.png', size: 180, inset: 0.08, radius: 0 } + { name: 'apple-touch-icon.png', size: 180, inset: 0.1, ground: '#ffffff' } ] await mkdir(outDir, { recursive: true }) @@ -41,7 +40,7 @@ const browser = await chromium.launch() for (const icon of icons) { const tab = await browser.newPage({ viewport: { width: icon.size, height: icon.size }, deviceScaleFactor: 1 }) await tab.setContent(page(icon.size, icon)) - const png = await tab.screenshot({ type: 'png', omitBackground: icon.inset === 0 }) + const png = await tab.screenshot({ type: 'png', omitBackground: !icon.ground }) await writeFile(resolve(outDir, icon.name), png) console.log(`[app-icons] ${icon.name} ${(png.length / 1024).toFixed(1)} kB`) await tab.close() diff --git a/apps/demo/scripts/build-og-image.mjs b/apps/demo/scripts/build-og-image.mjs index a0eb18f1..107c332f 100644 --- a/apps/demo/scripts/build-og-image.mjs +++ b/apps/demo/scripts/build-og-image.mjs @@ -1,15 +1,16 @@ -import { writeFile } from 'node:fs/promises' +import { readFile, writeFile } from 'node:fs/promises' import { resolve } from 'node:path' import { chromium } from 'playwright' /** * Renders the social card, `demo/og-image.png`, 1200 by 630, from a small HTML page in Chromium. * Link previews want a raster image and the repository has no image tooling, so the browser the - * tests already need does the rasterizing. The output is committed; run this when the card's - * text or the brand colour changes. + * tests already need does the rasterizing. The mark beside the name is the site's logo, + * `demo/favicon.svg`. The output is committed; run this when the card's text or the logo changes. */ const rootDir = resolve(import.meta.dirname, '..') +const logo = await readFile(resolve(rootDir, 'demo', 'favicon.svg'), 'utf8') const html = ` @@ -26,10 +27,7 @@ const html = ` background: linear-gradient(135deg, #f6f8fa 0%, #ffffff 55%, #eef3ff 100%); } .brand { display: flex; align-items: center; gap: 20px; font-size: 34px; font-weight: 700; } - .mark { - width: 64px; height: 64px; border-radius: 16px; background: #2f6df6; color: #fff; - display: grid; place-items: center; font: 700 22px / 1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: -0.02em; - } + .brand svg { display: block; width: 64px; height: 64px; } h1 { margin: 0; font-size: 66px; line-height: 1.08; letter-spacing: -1.5px; max-width: 1000px; } p { margin: 26px 0 0; font-size: 30px; line-height: 1.4; color: #5b6370; max-width: 980px; } code { font-family: ui-monospace, Menlo, monospace; background: #eef1f5; padding: 2px 12px; border-radius: 8px; color: #15171c; } @@ -37,7 +35,7 @@ const html = ` -
H5P
h5p-offline-player
+
${logo}h5p-offline-player

Self-hosted H5P.
No H5P server, no unpacking.

A web component that reads a .h5p in place and serves it to the H5P runtime with a Service Worker.

diff --git a/packages/verify/lib/preview.mjs b/packages/verify/lib/preview.mjs index 5f2a176e..ac58b792 100644 --- a/packages/verify/lib/preview.mjs +++ b/packages/verify/lib/preview.mjs @@ -4,7 +4,7 @@ import { readFile, stat } from 'node:fs/promises' import { basename, join } from 'node:path' import { pipeline } from 'node:stream/promises' import { fileURLToPath } from 'node:url' -import { librarySources, packageFile, playerDist, serve } from './verify.mjs' +import { librarySources, packageFile, playerDist, serve } from './serve.mjs' /** @import { IncomingMessage, ServerResponse } from 'node:http' */ @@ -39,6 +39,8 @@ const HEARTBEAT_MS = 15_000 * @property {boolean} [untrusted] play it as a site that did not make it plays it * @property {boolean} [refreshLibraries] with the pack, play its newer versions of the libraries the * package carries; default true + * @property {{ dist: string, runtime: string }} [roots] the player's `dist/` and the runtime's, for a host + * that ships them itself, as the VS Code extension does; the installed packages' otherwise * @property {number} [port] the port to take; default 4645, and any free one when that is taken * @property {number} [openWait] ms to wait for a tab before stopping; default ten minutes * @property {number} [closeGrace] ms the preview outlives its last tab, so that a reload does not end @@ -86,7 +88,7 @@ export async function previewPackage(options) { }) const server = await serve( - await playerDist(), + options.roots ?? (await playerDist()), sources, async (path, request, response) => { if (path === '/') { @@ -143,12 +145,13 @@ export async function previewPackage(options) { * The package as a static host with `Range` serves it: `206` with the bytes asked for, `200` whole * otherwise, streamed from disk. Its validator is the file's size and time, so the package written * again at the same path is a new package to the element rather than its old caches. + * @internal * @param {string} file * @param {IncomingMessage} request * @param {ServerResponse} response - * @param {PreviewOptions['onArchiveRequest']} report + * @param {PreviewOptions['onArchiveRequest']} [report] */ -async function sendArchive(file, request, response, report) { +export async function sendArchive(file, request, response, report) { const { size, mtimeMs } = await stat(file) const headers = { 'Content-Type': 'application/zip', diff --git a/packages/verify/lib/serve.mjs b/packages/verify/lib/serve.mjs new file mode 100644 index 00000000..14f1d1fa --- /dev/null +++ b/packages/verify/lib/serve.mjs @@ -0,0 +1,196 @@ +import { createServer } from 'node:http' +import { createRequire } from 'node:module' +import { existsSync, statSync } from 'node:fs' +import { readFile, stat } from 'node:fs/promises' +import { dirname, extname, join, normalize, resolve } from 'node:path' + +/** @import { IncomingMessage, ServerResponse } from 'node:http' */ + +/** + * What the check and the preview share: the package on disk, the library sources, and the server + * on localhost for the player, the runtime and the pack. None of it loads Playwright, which only + * the check needs, so that the preview starts without it and a host that bundles the preview + * server — the VS Code extension, packages/vscode — carries none of it. + */ + +const require = createRequire(import.meta.url) + +/** @type {Record} */ +const MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json', + '.woff2': 'font/woff2', + '.woff': 'font/woff', + '.ttf': 'font/ttf', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.gif': 'image/gif', + '.txt': 'text/plain; charset=utf-8', + '.md': 'text/markdown; charset=utf-8' +} + +export class VerifyError extends Error {} + +/** + * The package's absolute path and size. A missing file, a folder, or a file that cannot be read + * says which, before anything starts. + * @internal + * @param {string} file + * @returns {Promise<{ path: string, size: number }>} + */ +export async function packageFile(file) { + const path = resolve(file) + let found + try { + found = await stat(path) + } catch (error) { + // Only a missing file is "no such file"; a file that cannot be read says why. + const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined + throw new VerifyError(code === 'ENOENT' ? `No such file: ${path}` : `Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`) + } + if (!found.isFile()) throw new VerifyError(`Not a file: ${path}`) + return { path, size: found.size } +} + +/** Where the verifier serves a copy of the pack named on disk, which the element's `pack-base` names. */ +const PACK_ROUTE = '/__pack/' + +/** + * `libraries` as the element reads it, with each bundle on disk given a route on the verifier's + * own server, and a folder on disk — a copy of the pack's `parts/` — served as the pack, which + * `packBase` then names: `pack` and URLs pass as they are. A path that names nothing is an error + * before anything starts. + * @internal + * @param {string | undefined} value + */ +export function librarySources(value) { + /** @type {Map} */ + const files = new Map() + /** @type {string | null} */ + let packDir = null + if (!value) return { attribute: null, files, packDir, packBase: null } + const tokens = value.split(/\s+/).filter(Boolean).map((token) => { + if (token === 'pack' || /^https?:\/\//i.test(token)) return token + const path = resolve(token) + if (!existsSync(path)) throw new VerifyError(`No such library bundle: ${path}`) + if (statSync(path).isDirectory()) { + if (!existsSync(join(path, 'index.json'))) throw new VerifyError(`${path} is a folder, and not a copy of the library pack: it has no index.json`) + if (packDir && packDir !== path) throw new VerifyError(`--libraries names two copies of the library pack: ${packDir} and ${path}`) + packDir = path + return 'pack' + } + const route = `/__libraries/${files.size}.h5p` + files.set(route, path) + return route + }) + return { attribute: [...new Set(tokens)].join(' '), files, packDir, packBase: packDir ? PACK_ROUTE : null } +} + +/** + * The player's `dist/` and the runtime's, from the installed packages; the workspace needs both + * built first. The runtime is a package of its own (`@missing-elements/h5p-runtime`, GPL) and is + * served at `/frame-assets/`, which is where the element looks beside its own script. + * @internal + */ +export async function playerDist() { + const element = require.resolve('@missing-elements/h5p-offline-player') + const dist = dirname(element) + if (!existsSync(join(dist, 'h5p-sw.js'))) { + throw new VerifyError(`The player is not built at ${dist} — run \`pnpm build\` in the workspace, or reinstall the package`) + } + const runtime = join(dirname(require.resolve('@missing-elements/h5p-runtime/package.json')), 'dist') + if (!existsSync(join(runtime, 'h5p.css')) || !existsSync(join(runtime, 'frame-boot.js'))) { + throw new VerifyError(`The H5P runtime is not built at ${runtime} — run \`pnpm build\` in the workspace, or reinstall @missing-elements/h5p-runtime`) + } + return { dist, runtime } +} + +/** + * A server on localhost for the player, the runtime and any library bundle named on disk. `own` + * answers first, for the paths its caller adds — the check's page; a preview's page, package and + * presence — and says whether it did. + * @internal + * @param {{ dist: string, runtime: string }} roots + * @param {{ files: Map, packDir: string | null }} sources bundles on disk by route, and a + * copy of the pack's `parts/`, served under `PACK_ROUTE` + * @param {(path: string, request: IncomingMessage, response: ServerResponse) => boolean | Promise} own + * @param {number | number[]} [port] the port to take, or the ports to try in order; any free one when + * they are taken, or with 0 + * @returns {Promise<{ url: string, close: () => void }>} + */ +export function serve({ dist, runtime }, { files: bundles, packDir }, own, port = 0) { + const ASSETS = '/frame-assets/' + const server = createServer(async (request, response) => { + try { + const path = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname) + if (await own(path, request, response)) return + /** + * @param {string} root + * @param {string} rest + */ + const safe = (root, rest) => join(root, normalize(rest).replace(/^(\.\.[/\\])+/, '')) + const bundle = bundles.get(path) + const inPack = packDir !== null && path.startsWith(PACK_ROUTE) + const target = + bundle ?? (inPack ? safe(packDir, path.slice(PACK_ROUTE.length)) : path.startsWith(ASSETS) ? safe(runtime, path.slice(ASSETS.length)) : safe(dist, path)) + if (!bundle && !target.startsWith(dist) && !target.startsWith(runtime) && !(inPack && target.startsWith(packDir))) { + response.writeHead(403).end() + return + } + await sendFile(target, response) + } catch (error) { + // A path that does not decode, or a file that went away mid-answer: the server goes on. + if (!response.headersSent) response.writeHead(error instanceof URIError ? 400 : 500).end() + else response.destroy() + } + }) + // The ports asked for, in order, and then any free one. + const ports = [...[port].flat().filter((candidate) => candidate !== 0), 0] + let attempt = 0 + return new Promise((resolveServer, rejectServer) => { + server.on('error', (error) => { + // A port asked for is taken, by another preview or another program: the next will do. + if (/** @type {NodeJS.ErrnoException} */ (error).code === 'EADDRINUSE' && attempt < ports.length - 1) { + attempt += 1 + server.listen(ports[attempt], '127.0.0.1') + } else rejectServer(error) + }) + server.once('listening', () => { + const { port: bound } = /** @type {import('node:net').AddressInfo} */ (server.address()) + resolveServer({ + url: `http://127.0.0.1:${bound}`, + // A connection left open — a browser's keep-alive, a preview tab's presence — would hold it. + close: () => { + server.closeAllConnections() + server.close() + } + }) + }) + server.listen(ports[0], '127.0.0.1') + }) +} + +/** + * A file whole, with its type and no caching, or a 404. + * @internal + * @param {string} target + * @param {ServerResponse} response + */ +export async function sendFile(target, response) { + let body + try { + body = await readFile(target) + } catch { + response.writeHead(404, { 'Content-Type': 'text/plain' }).end('not found') + return + } + response.writeHead(200, { + 'Content-Type': MIME[extname(target)] ?? 'application/octet-stream', + 'Content-Length': body.length, + 'Cache-Control': 'no-store' + }) + response.end(body) +} diff --git a/packages/verify/lib/verify.mjs b/packages/verify/lib/verify.mjs index 784cdc88..ffdc61ef 100644 --- a/packages/verify/lib/verify.mjs +++ b/packages/verify/lib/verify.mjs @@ -1,13 +1,13 @@ -import { createServer } from 'node:http' import { createRequire } from 'node:module' -import { existsSync, statSync } from 'node:fs' -import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' -import { basename, dirname, extname, join, normalize, resolve } from 'node:path' +import { mkdir, writeFile } from 'node:fs/promises' +import { basename, join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium, errors as playwrightErrors } from 'playwright-core' +import { VerifyError, librarySources, packageFile, playerDist, sendFile, serve } from './serve.mjs' + +export { VerifyError } /** @import { H5PPlayerElement, PlayerErrorDetail, PlayerState, RefreshedLibrary } from '@missing-elements/h5p-offline-player' */ -/** @import { IncomingMessage, ServerResponse } from 'node:http' */ /** * Plays a package the way a learner would — the real element, the real Service Worker, a real @@ -34,22 +34,6 @@ const CHECK_NOTES = ": the content was checked against its libraries /** The header the Service Worker wants before it hands an untrusted package's `content.json` over as written. */ const CONTENT_CHECK_HEADER = 'X-H5P-Content-Check' -/** @type {Record} */ -const MIME = { - '.html': 'text/html; charset=utf-8', - '.js': 'text/javascript; charset=utf-8', - '.mjs': 'text/javascript; charset=utf-8', - '.css': 'text/css; charset=utf-8', - '.json': 'application/json', - '.woff2': 'font/woff2', - '.woff': 'font/woff', - '.ttf': 'font/ttf', - '.svg': 'image/svg+xml', - '.png': 'image/png', - '.gif': 'image/gif', - '.txt': 'text/plain; charset=utf-8', - '.md': 'text/markdown; charset=utf-8' -} /** * @typedef {object} VerifyOptions @@ -350,63 +334,6 @@ export async function verifyPackage(options) { } } -export class VerifyError extends Error {} - -/** - * The package's absolute path and size. A missing file, a folder, or a file that cannot be read - * says which, before anything starts. - * @internal - * @param {string} file - * @returns {Promise<{ path: string, size: number }>} - */ -export async function packageFile(file) { - const path = resolve(file) - let found - try { - found = await stat(path) - } catch (error) { - // Only a missing file is "no such file"; a file that cannot be read says why. - const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined - throw new VerifyError(code === 'ENOENT' ? `No such file: ${path}` : `Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`) - } - if (!found.isFile()) throw new VerifyError(`Not a file: ${path}`) - return { path, size: found.size } -} - -/** Where the verifier serves a copy of the pack named on disk, which the element's `pack-base` names. */ -const PACK_ROUTE = '/__pack/' - -/** - * `libraries` as the element reads it, with each bundle on disk given a route on the verifier's - * own server, and a folder on disk — a copy of the pack's `parts/` — served as the pack, which - * `packBase` then names: `pack` and URLs pass as they are. A path that names nothing is an error - * before anything starts. - * @internal - * @param {string | undefined} value - */ -export function librarySources(value) { - /** @type {Map} */ - const files = new Map() - /** @type {string | null} */ - let packDir = null - if (!value) return { attribute: null, files, packDir, packBase: null } - const tokens = value.split(/\s+/).filter(Boolean).map((token) => { - if (token === 'pack' || /^https?:\/\//i.test(token)) return token - const path = resolve(token) - if (!existsSync(path)) throw new VerifyError(`No such library bundle: ${path}`) - if (statSync(path).isDirectory()) { - if (!existsSync(join(path, 'index.json'))) throw new VerifyError(`${path} is a folder, and not a copy of the library pack: it has no index.json`) - if (packDir && packDir !== path) throw new VerifyError(`--libraries names two copies of the library pack: ${packDir} and ${path}`) - packDir = path - return 'pack' - } - const route = `/__libraries/${files.size}.h5p` - files.set(route, path) - return route - }) - return { attribute: [...new Set(tokens)].join(' '), files, packDir, packBase: packDir ? PACK_ROUTE : null } -} - /** * What the content as played lost against the package's own `content.json`, field by field, by * JSON path: markup removed from a text (tags, attributes and style properties by name), fields @@ -563,107 +490,6 @@ function dedupe(messages) { return [...counts].map(([message, count]) => (count > 1 ? `${message} (×${count})` : message)) } -/** - * The player's `dist/` and the runtime's, from the installed packages; the workspace needs both - * built first. The runtime is a package of its own (`@missing-elements/h5p-runtime`, GPL) and is - * served at `/frame-assets/`, which is where the element looks beside its own script. - * @internal - */ -export async function playerDist() { - const element = require.resolve('@missing-elements/h5p-offline-player') - const dist = dirname(element) - if (!existsSync(join(dist, 'h5p-sw.js'))) { - throw new VerifyError(`The player is not built at ${dist} — run \`pnpm build\` in the workspace, or reinstall the package`) - } - const runtime = join(dirname(require.resolve('@missing-elements/h5p-runtime/package.json')), 'dist') - if (!existsSync(join(runtime, 'h5p.css')) || !existsSync(join(runtime, 'frame-boot.js'))) { - throw new VerifyError(`The H5P runtime is not built at ${runtime} — run \`pnpm build\` in the workspace, or reinstall @missing-elements/h5p-runtime`) - } - return { dist, runtime } -} - -/** - * A server on localhost for the player, the runtime and any library bundle named on disk. `own` - * answers first, for the paths its caller adds — the check's page; a preview's page, package and - * presence — and says whether it did. - * @internal - * @param {{ dist: string, runtime: string }} roots - * @param {{ files: Map, packDir: string | null }} sources bundles on disk by route, and a - * copy of the pack's `parts/`, served under `PACK_ROUTE` - * @param {(path: string, request: IncomingMessage, response: ServerResponse) => boolean | Promise} own - * @param {number} [port] the port to take; any free one when it is taken, or with 0 - * @returns {Promise<{ url: string, close: () => void }>} - */ -export function serve({ dist, runtime }, { files: bundles, packDir }, own, port = 0) { - const ASSETS = '/frame-assets/' - const server = createServer(async (request, response) => { - try { - const path = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname) - if (await own(path, request, response)) return - /** - * @param {string} root - * @param {string} rest - */ - const safe = (root, rest) => join(root, normalize(rest).replace(/^(\.\.[/\\])+/, '')) - const bundle = bundles.get(path) - const inPack = packDir !== null && path.startsWith(PACK_ROUTE) - const target = - bundle ?? (inPack ? safe(packDir, path.slice(PACK_ROUTE.length)) : path.startsWith(ASSETS) ? safe(runtime, path.slice(ASSETS.length)) : safe(dist, path)) - if (!bundle && !target.startsWith(dist) && !target.startsWith(runtime) && !(inPack && target.startsWith(packDir))) { - response.writeHead(403).end() - return - } - await sendFile(target, response) - } catch (error) { - // A path that does not decode, or a file that went away mid-answer: the server goes on. - if (!response.headersSent) response.writeHead(error instanceof URIError ? 400 : 500).end() - else response.destroy() - } - }) - return new Promise((resolveServer, rejectServer) => { - server.on('error', (error) => { - // The port asked for is taken, by another preview or another program: any free one will do. - if (/** @type {NodeJS.ErrnoException} */ (error).code === 'EADDRINUSE' && port !== 0) { - port = 0 - server.listen(0, '127.0.0.1') - } else rejectServer(error) - }) - server.once('listening', () => { - const { port: bound } = /** @type {import('node:net').AddressInfo} */ (server.address()) - resolveServer({ - url: `http://127.0.0.1:${bound}`, - // A connection left open — a browser's keep-alive, a preview tab's presence — would hold it. - close: () => { - server.closeAllConnections() - server.close() - } - }) - }) - server.listen(port, '127.0.0.1') - }) -} - -/** - * A file whole, with its type and no caching, or a 404. - * @param {string} target - * @param {ServerResponse} response - */ -async function sendFile(target, response) { - let body - try { - body = await readFile(target) - } catch { - response.writeHead(404, { 'Content-Type': 'text/plain' }).end('not found') - return - } - response.writeHead(200, { - 'Content-Type': MIME[extname(target)] ?? 'application/octet-stream', - 'Content-Length': body.length, - 'Cache-Control': 'no-store' - }) - response.end(body) -} - /** * A Chromium: the one named, else Chrome or Edge installed on the machine, else Playwright's * own. Chrome and Edge first because they are usually there and cost no download. diff --git a/packages/vscode/.vscodeignore b/packages/vscode/.vscodeignore new file mode 100644 index 00000000..b667788f --- /dev/null +++ b/packages/vscode/.vscodeignore @@ -0,0 +1,11 @@ +# The .vsix carries the bundle, the files the server serves, and what the Marketplace shows. The +# sources are bundled into dist/, and no node_modules is shipped (vsce package --no-dependencies). +** +!dist/** +!assets/** +!package.json +!README.md +!CHANGELOG.md +!LICENSE +!NOTICE.txt +!icon.png diff --git a/packages/vscode/CHANGELOG.md b/packages/vscode/CHANGELOG.md new file mode 100644 index 00000000..c219daac --- /dev/null +++ b/packages/vscode/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## 0.1.0 + +The first release. A `.h5p` opens in an editor that plays it with the library pack carried +inside, with Untrusted and Newest libraries switches, Restricted Mode playing every package +untrusted, Reload, Open in Browser, and a new play when the file changes. diff --git a/packages/vscode/README.md b/packages/vscode/README.md new file mode 100644 index 00000000..65179c18 --- /dev/null +++ b/packages/vscode/README.md @@ -0,0 +1,76 @@ +# H5P Preview by Missing Elements + +Open a `.h5p` file in VS Code and it plays, in the same player a website runs it with. There is no +H5P server and no account. It works offline, and the package never leaves your computer. + +## What it does + +- **Click a `.h5p` and it plays** in an editor tab: quizzes, interactive videos, presentations, + every content type the H5P hub serves. Video streams; a large package starts at once. +- **Exports without their libraries play too.** Packages from h5p.com and h5p.org often carry only + their content. The extension carries the libraries of every hub content type and supplies what a + package lacks, with no network. +- **It plays again when the file changes.** Rebuild a package, or let an agent write it again, and + the tab shows the new version. +- **Open in Browser** plays it in your default browser, served from this computer until you close + the tab. + +## Packages you did not make + +A package carries JavaScript. By default the preview runs it, as it plays your own work. + +- **Untrusted**, the switch above the content, plays a package as a site plays one it did not + make. None of its own code runs, its libraries come only from those the extension carries, and + its content is checked against those libraries' semantics, as the H5P plugins for Moodle, + WordPress and Drupal check it. +- **In Restricted Mode** every package plays untrusted. Trust the workspace to play packages with + their own code. +- **Newest libraries**, the other switch, plays the extension's newer version of a library a package + carries, as a site with up-to-date libraries would. Turn it off to see the package exactly as + exported. + +## Settings + +| Setting | Default | | +|---|---|---| +| `h5pPreview.untrusted` | `false` | Play every package untrusted. | +| `h5pPreview.newestLibraries` | `true` | Play the newer versions of the libraries a package carries. | + +The switches above each preview override them for that tab. + +## Commands + +- **H5P Preview: Reload** plays the package again from the start. Also in the editor's title bar. +- **H5P Preview: Open in Browser** plays it in your browser. Also in the title bar, and in the + Explorer's menu on a `.h5p`. + +## How it works + +The editor frames a page from a small server the extension runs on `127.0.0.1`, on the first free +port from 4646. It serves the package, the player, the H5P runtime and the libraries, and nothing +else. The player reads the package where it is: the libraries in a few reads, media in the ranges +the content asks for. Nothing is unpacked into your folders. + +In a remote or virtual workspace, the extension runs on this computer and copies the file to a +temporary folder here before it plays. + +## Requirements + +VS Code 1.90 or later, on the desktop. VS Code for the Web cannot run the server. + +## Related + +- [h5p-offline-player](https://github.com/missing-elements/h5p-offline-player): the player, a web + component that plays H5P on any website you host, with no H5P server. +- [h5p-verify](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/verify): + checks from the command line that a package plays; `--preview` opens it in your browser. +- [h5p-normalize](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/normalize): + rewrites a package so that its video streams. + +## Licence + +MIT. The extension carries the H5P core runtime (GPL-3.0) and the hub's libraries, each under its +own licence; `NOTICE.txt` lists them. + +H5P is a trademark of H5P Group. This extension is made by Missing Elements and is not affiliated +with or endorsed by H5P Group. diff --git a/packages/vscode/icon.png b/packages/vscode/icon.png new file mode 100644 index 00000000..3213bc44 Binary files /dev/null and b/packages/vscode/icon.png differ diff --git a/packages/vscode/package.json b/packages/vscode/package.json new file mode 100644 index 00000000..a3b549b9 --- /dev/null +++ b/packages/vscode/package.json @@ -0,0 +1,142 @@ +{ + "name": "h5p-preview", + "displayName": "H5P Preview by Missing Elements", + "description": "Open .h5p files in VS Code and play them in the real player: no H5P server, offline, and nothing leaves your computer.", + "version": "0.1.0", + "publisher": "missing-elements", + "private": true, + "license": "MIT", + "icon": "icon.png", + "repository": { + "type": "git", + "url": "https://github.com/missing-elements/h5p-offline-player.git", + "directory": "packages/vscode" + }, + "homepage": "https://github.com/missing-elements/h5p-offline-player/tree/main/packages/vscode#readme", + "bugs": { + "url": "https://github.com/missing-elements/h5p-offline-player/issues" + }, + "engines": { + "vscode": "^1.90.0" + }, + "categories": [ + "Visualization", + "Education" + ], + "keywords": [ + "h5p", + "h5p player", + "interactive content", + "interactive video", + "quiz", + "elearning", + "e-learning", + "preview" + ], + "extensionKind": [ + "ui" + ], + "capabilities": { + "untrustedWorkspaces": { + "supported": "limited", + "description": "In Restricted Mode every package plays untrusted: none of its own code runs, its libraries come from the library pack the extension carries, and its content is checked against their semantics." + }, + "virtualWorkspaces": true + }, + "main": "./dist/extension.cjs", + "contributes": { + "customEditors": [ + { + "viewType": "missingElements.h5pPreview", + "displayName": "H5P Preview", + "selector": [ + { + "filenamePattern": "*.h5p" + } + ], + "priority": "default" + } + ], + "commands": [ + { + "command": "h5pPreview.reload", + "title": "Reload", + "category": "H5P Preview", + "icon": "$(refresh)" + }, + { + "command": "h5pPreview.openInBrowser", + "title": "Open in Browser", + "category": "H5P Preview", + "icon": "$(link-external)" + } + ], + "menus": { + "editor/title": [ + { + "command": "h5pPreview.reload", + "when": "activeCustomEditorId == missingElements.h5pPreview", + "group": "navigation@1" + }, + { + "command": "h5pPreview.openInBrowser", + "when": "activeCustomEditorId == missingElements.h5pPreview", + "group": "navigation@2" + } + ], + "explorer/context": [ + { + "command": "h5pPreview.openInBrowser", + "when": "resourceExtname == .h5p", + "group": "navigation@9" + } + ], + "commandPalette": [ + { + "command": "h5pPreview.reload", + "when": "activeCustomEditorId == missingElements.h5pPreview" + }, + { + "command": "h5pPreview.openInBrowser", + "when": "activeCustomEditorId == missingElements.h5pPreview" + } + ] + }, + "configuration": { + "title": "H5P Preview", + "properties": { + "h5pPreview.untrusted": { + "type": "boolean", + "default": false, + "markdownDescription": "Play packages `untrusted`, as a site plays packages it did not make: none of their own code runs, their libraries come only from the library pack the extension carries, and their content is checked against the libraries' semantics. In Restricted Mode every package plays this way." + }, + "h5pPreview.newestLibraries": { + "type": "boolean", + "default": true, + "markdownDescription": "Play the library pack's newer version of a library a package carries, as a site with the pack plays it. Off: each package plays with its own libraries." + } + } + } + }, + "scripts": { + "build": "node scripts/build.mjs", + "icon": "node scripts/icon.mjs", + "package": "node scripts/build.mjs && node scripts/package.mjs", + "test": "pnpm --filter @missing-elements/h5p-offline-player build && vitest run", + "test:vscode": "node scripts/build.mjs && node tests/vscode/run.mjs", + "typecheck": "tsc -p tsconfig.json" + }, + "devDependencies": { + "@missing-elements/h5p-libraries": "workspace:^", + "@missing-elements/h5p-offline-player": "workspace:^", + "@missing-elements/h5p-runtime": "workspace:^", + "@types/node": "^26.6.5", + "@types/vscode": "1.90.0", + "@vscode/test-electron": "^3.1.0", + "@vscode/vsce": "^4.0.0", + "esbuild": "^0.28.2", + "playwright-core": "^1.64.1", + "typescript": "^7.0.2", + "vitest": "^5.0.5" + } +} diff --git a/packages/vscode/scripts/build.mjs b/packages/vscode/scripts/build.mjs new file mode 100644 index 00000000..4fe6c7c2 --- /dev/null +++ b/packages/vscode/scripts/build.mjs @@ -0,0 +1,124 @@ +import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { createRequire } from 'node:module' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { build } from 'esbuild' + +/** + * Builds the extension: `dist/extension.cjs`, one CommonJS file with the verifier's preview server + * in it, and `assets/` — the player's files, the runtime and the library pack's parts, from the + * installed packages as the embed builder takes them, so that the versions are this checkout's. + * `vsce package --no-dependencies` then ships those two folders and no node_modules. + */ + +const root = fileURLToPath(new URL('..', import.meta.url)) +const require = createRequire(import.meta.url) + +const player = dirname(require.resolve('@missing-elements/h5p-offline-player')) +const runtime = join(dirname(require.resolve('@missing-elements/h5p-runtime/package.json')), 'dist') +const pack = dirname(require.resolve('@missing-elements/h5p-libraries/parts/index.json')) +const licences = require.resolve('@missing-elements/h5p-libraries/libraries.txt') +const verify = join(root, '..', 'verify', 'lib') + +/** The player's files, by the names the element looks for beside itself. */ +const PLAYER_FILES = ['h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js'] + +for (const [what, file] of [ + ['the player', join(player, 'h5p-sw.js')], + ['the runtime', join(runtime, 'frame-boot.js')] +]) { + if (!existsSync(file)) { + console.error(`${what} is not built: ${file} is missing. Run \`pnpm build\` at the workspace root first.`) + process.exit(1) + } +} + +/** + * The preview must not load the check: Playwright is the check's, and the extension carries no + * node_modules to find it in. + * @type {import('esbuild').Plugin} + */ +const noPlaywright = { + name: 'no-playwright', + setup(context) { + context.onResolve({ filter: /^playwright-core$/ }, (args) => ({ + errors: [{ text: `${args.importer} imports playwright-core, which only the check needs` }] + })) + } +} + +await rm(join(root, 'dist'), { recursive: true, force: true }) +await rm(join(root, 'assets'), { recursive: true, force: true }) + +await build({ + entryPoints: [join(root, 'src', 'extension.mjs')], + outfile: join(root, 'dist', 'extension.cjs'), + bundle: true, + platform: 'node', + format: 'cjs', + // VS Code 1.90's extension host runs Node 18. + target: 'node18', + external: ['vscode'], + // The verifier's modules find their files beside themselves by `import.meta.url`, which a + // CommonJS bundle has not got: it is the bundle's own address, and its files go beside it. + define: { 'import.meta.url': 'importMetaUrl' }, + banner: { js: "const importMetaUrl = require('node:url').pathToFileURL(__filename).href;" }, + plugins: [noPlaywright], + legalComments: 'inline', + logLevel: 'warning' +}) +// Open in Browser runs the command's preview, which reads its page beside its module. +await cp(join(verify, 'preview.html'), join(root, 'dist', 'preview.html')) + +await mkdir(join(root, 'assets', 'player'), { recursive: true }) +for (const name of PLAYER_FILES) await cp(join(player, name), join(root, 'assets', 'player', name)) +await cp(runtime, join(root, 'assets', 'runtime'), { recursive: true }) +await cp(pack, join(root, 'assets', 'libraries'), { recursive: true }) +await cp(licences, join(root, 'assets', 'libraries.txt')) + +/** @param {string} name */ +const versionOf = async (name) => JSON.parse(await readFile(require.resolve(`${name}/package.json`), 'utf8')).version +const versions = { + // The player exports no package.json; its dist/ says its version, as the embed builder reads it. + player: (await readFile(join(player, 'VERSION'), 'utf8')).trim(), + runtime: await versionOf('@missing-elements/h5p-runtime'), + libraries: await versionOf('@missing-elements/h5p-libraries') +} +await writeFile( + join(root, 'NOTICE.txt'), + `H5P Preview by Missing Elements carries other people's work beside its own. + + dist/extension.cjs the extension, with the preview server of @missing-elements/h5p-verify + bundled: MIT. + assets/player/ @missing-elements/h5p-offline-player ${versions.player}: MIT. The two workers + also carry zip.js, BSD-3-Clause, its licence in each file's header. + assets/runtime/ @missing-elements/h5p-runtime ${versions.runtime}, the H5P core runtime: + GPL-3.0-only. Its LICENSE.txt and NOTICE.txt say what it is and where + its source is. + assets/libraries/ @missing-elements/h5p-libraries ${versions.libraries}, the H5P hub's libraries, + one archive per library, each under its own licence, listed in + assets/libraries.txt. The player reads only the ones a package needs. + +H5P is a trademark of H5P Group. This extension is made by Missing Elements and is not +affiliated with or endorsed by H5P Group. + +https://github.com/missing-elements/h5p-offline-player/tree/main/packages/vscode +` +) + +/** @param {string} path */ +async function size(path) { + const info = await stat(path) + if (!info.isDirectory()) return info.size + let total = 0 + for (const entry of await readdir(path)) total += await size(join(path, entry)) + return total +} +const megabytes = (/** @type {number} */ bytes) => `${(bytes / 1048576).toFixed(1)} MB` +console.log(`built dist/ (${megabytes(await size(join(root, 'dist')))}) and assets/ (${megabytes(await size(join(root, 'assets')))})`) +// Read so that a broken bundle fails here rather than in VS Code. +if (!(await readFile(join(root, 'dist', 'extension.cjs'), 'utf8')).includes('missingElements.h5pPreview')) { + console.error('dist/extension.cjs does not register the editor') + process.exit(1) +} diff --git a/packages/vscode/scripts/icon.mjs b/packages/vscode/scripts/icon.mjs new file mode 100644 index 00000000..81e4590f --- /dev/null +++ b/packages/vscode/scripts/icon.mjs @@ -0,0 +1,29 @@ +import { readFile, writeFile } from 'node:fs/promises' +import { chromium } from 'playwright-core' + +/** + * Renders `icon.png`, the extension's icon on the Marketplace, on Open VSX and in VS Code, from the + * project's logo, the demo site's `demo/favicon.svg`: one file for the site, the app and the + * extension, so that none of them drifts. 256 px square on a transparent ground: the Marketplace + * takes 128 at the least and 256 to draw it sharp on a high-density screen. Rasterized in Chromium, + * as the demo's icons are, since the repository has no image tooling. The output is committed; run + * this when the logo changes. + */ + +const SIZE = 256 + +const svg = await readFile(new URL('../../../apps/demo/demo/favicon.svg', import.meta.url), 'utf8') +const browser = await chromium.launch() +try { + const tab = await browser.newPage({ viewport: { width: SIZE, height: SIZE }, deviceScaleFactor: 1 }) + await tab.setContent(` +${svg}`) + const png = await tab.screenshot({ type: 'png', omitBackground: true }) + await writeFile(new URL('../icon.png', import.meta.url), png) + console.log(`icon.png: ${SIZE} px, ${(png.length / 1024).toFixed(1)} kB`) +} finally { + await browser.close() +} diff --git a/packages/vscode/scripts/package.mjs b/packages/vscode/scripts/package.mjs new file mode 100644 index 00000000..261348b4 --- /dev/null +++ b/packages/vscode/scripts/package.mjs @@ -0,0 +1,39 @@ +import { spawnSync } from 'node:child_process' +import { cp, readFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * Writes `h5p-preview-.vsix` from what `scripts/build.mjs` built: the file the owner + * publishes to the Visual Studio Marketplace and to Open VSX. vsce takes no node_modules + * (`--no-dependencies`; everything is in `dist/` and `assets/`), and its README's relative links + * resolve to this folder of the repository, which its default base, the repository's root, would not. + */ + +const root = fileURLToPath(new URL('..', import.meta.url)) +const require = createRequire(import.meta.url) +const vsce = join(dirname(require.resolve('@vscode/vsce/package.json')), 'vsce') +const { name, version } = JSON.parse(await readFile(join(root, 'package.json'), 'utf8')) +const out = `${name}-${version}.vsix` +const folder = 'https://github.com/missing-elements/h5p-offline-player' + +// As the other packages' prepack does: the repository's licence, in the package. +await cp(join(root, '..', '..', 'LICENSE'), join(root, 'LICENSE')) + +const result = spawnSync( + process.execPath, + [ + vsce, + 'package', + '--no-dependencies', + '--out', + out, + '--baseContentUrl', + `${folder}/blob/HEAD/packages/vscode/`, + '--baseImagesUrl', + `${folder}/raw/HEAD/packages/vscode/` + ], + { cwd: root, stdio: 'inherit' } +) +process.exit(result.status ?? 1) diff --git a/packages/vscode/src/extension.mjs b/packages/vscode/src/extension.mjs new file mode 100644 index 00000000..ffa5ccea --- /dev/null +++ b/packages/vscode/src/extension.mjs @@ -0,0 +1,31 @@ +import * as vscode from 'vscode' +import { Previews, VIEW_TYPE } from './previews.mjs' + +/** + * H5P Preview by Missing Elements: a `.h5p` opens in a read-only editor that plays it in the real + * player, served from this computer. See AGENTS.md, *The VS Code extension*. + * @param {vscode.ExtensionContext} context + */ +export function activate(context) { + const previews = new Previews(context) + context.subscriptions.push( + previews, + // Kept while hidden: a quiz half answered, a video half watched, stays as it was. + vscode.window.registerCustomEditorProvider(VIEW_TYPE, previews, { + webviewOptions: { retainContextWhenHidden: true }, + supportsMultipleEditorsPerDocument: true + }), + vscode.commands.registerCommand('h5pPreview.reload', () => previews.reload()), + vscode.commands.registerCommand('h5pPreview.openInBrowser', (/** @type {unknown} */ uri) => + previews.openInBrowser(uri instanceof vscode.Uri ? uri : undefined) + ), + vscode.workspace.onDidGrantWorkspaceTrust(() => previews.applySettings()), + vscode.workspace.onDidChangeConfiguration((event) => { + if (event.affectsConfiguration('h5pPreview')) previews.applySettings() + }) + ) + // What the integration tests read: each preview's state as its page reports it. + return { onDidChangeState: previews.onDidChangeState } +} + +export function deactivate() {} diff --git a/packages/vscode/src/page.mjs b/packages/vscode/src/page.mjs new file mode 100644 index 00000000..bcba8794 --- /dev/null +++ b/packages/vscode/src/page.mjs @@ -0,0 +1,88 @@ +/** + * The page a preview's webview frames: the element, set as the preview's mode says, telling the + * webview what it reached. It is told to the webview and nothing else — the first of the page's + * ancestor origins — and the webview takes it only from this page's origin. + * @param {object} settings + * @param {string} settings.name the file's name + * @param {string} settings.src the package's address on the server, a path + * @param {string | null} settings.packBase where the server serves the library pack + * @param {boolean} settings.untrusted + * @param {boolean} settings.newest with the pack's newer libraries + * @param {string | null} settings.lang for a package that names no language + */ +export function viewPage(settings) { + // `<` as an escape, so that no file name can end the script block it is written into. + const json = JSON.stringify(settings).replaceAll('<', '\\u003c') + return ` + + + + + Preview + + + + + + + + + +` +} diff --git a/packages/vscode/src/previews.mjs b/packages/vscode/src/previews.mjs new file mode 100644 index 00000000..407e0131 --- /dev/null +++ b/packages/vscode/src/previews.mjs @@ -0,0 +1,261 @@ +import { randomBytes } from 'node:crypto' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import * as vscode from 'vscode' +import { previewPackage } from '../../verify/lib/preview.mjs' +import { startServer } from './server.mjs' +import { webviewHtml } from './webview.mjs' + +/** @import { PreviewServer } from './server.mjs' */ + +/** The custom editor's view type, as `contributes.customEditors` names it. */ +export const VIEW_TYPE = 'missingElements.h5pPreview' + +/** How long a file has to stay unchanged before its previews play it again. */ +const SETTLE_MS = 500 + +/** + * What a preview reports: the page's message — `state`, `ready` or `error` — and the package's URI. + * @typedef {{ uri: vscode.Uri, type: string, [key: string]: unknown }} PreviewState + */ + +/** + * One editor showing a package. + * @typedef {object} Preview + * @property {H5PDocument} document + * @property {vscode.WebviewPanel} panel + * @property {string | null} id the package's id on the server, once it is served + * @property {{ untrusted: boolean, newest: boolean }} mode as the editor's switches stand + */ + +/** + * The mode a preview starts in: the settings, except that Restricted Mode plays everything + * untrusted. + */ +function defaults() { + const settings = vscode.workspace.getConfiguration('h5pPreview') + const restricted = !vscode.workspace.isTrusted + return { + restricted, + untrusted: restricted || settings.get('untrusted', false), + newest: settings.get('newestLibraries', true) + } +} + +/** + * A copy on this computer of a package that is not, from a remote or virtual workspace: the + * server runs here, beside the webview, and reads from disk. + * @param {vscode.Uri} uri + */ +async function localCopy(uri) { + const folder = await mkdtemp(join(tmpdir(), 'h5p-preview-')) + const file = join(folder, basename(uri.path)) + await writeFile(file, await vscode.workspace.fs.readFile(uri)) + return { folder, file } +} + +/** + * A `.h5p` open in one or more previews, and where the server reads it from. + * @implements {vscode.CustomDocument} + */ +class H5PDocument { + /** + * @param {vscode.Uri} uri + * @param {string} file + * @param {string | null} folder the temporary folder of a copy, removed with the document + */ + constructor(uri, file, folder) { + this.uri = uri + this.file = file + this.folder = folder + this.name = basename(uri.path) + /** @type {vscode.Disposable[]} */ + this.disposables = [] + } + + dispose() { + for (const disposable of this.disposables) disposable.dispose() + if (this.folder) rm(this.folder, { recursive: true, force: true }).catch(() => {}) + } +} + +/** + * The previews of a window and the one server they share: started with the first, stopped with + * the last. + * @implements {vscode.CustomReadonlyEditorProvider} + */ +export class Previews { + /** @param {vscode.ExtensionContext} context */ + constructor(context) { + const assets = context.asAbsolutePath('assets') + this.roots = { dist: join(assets, 'player'), runtime: join(assets, 'runtime') } + this.packDir = join(assets, 'libraries') + /** @type {Promise | null} */ + this.server = null + /** @type {Set} */ + this.previews = new Set() + /** @type {Preview | null} */ + this.active = null + /** Open in Browser's previews, by the function that ends each. @type {Set<() => void>} */ + this.browsers = new Set() + /** @type {vscode.EventEmitter} */ + this.states = new vscode.EventEmitter() + this.onDidChangeState = this.states.event + } + + /** @param {vscode.Uri} uri */ + async openCustomDocument(uri) { + const copy = uri.scheme === 'file' ? null : await localCopy(uri) + const document = new H5PDocument(uri, copy ? copy.file : uri.fsPath, copy ? copy.folder : null) + // A package written again — by hand, by a build, by an agent — plays again once it has settled. + // The folder is watched and the name compared: a name as the pattern is a glob, and brackets or + // braces in it, `quiz [v2].h5p`, would match other names and never its own. + const watcher = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(vscode.Uri.joinPath(uri, '..'), '*')) + /** @type {ReturnType | undefined} */ + let timer + /** @param {vscode.Uri} changedUri */ + const changed = (changedUri) => { + if (basename(changedUri.path) !== document.name) return + clearTimeout(timer) + timer = setTimeout(async () => { + // A copy is made again first, the file read whole before the copy is touched: a read that + // fails leaves the copy as it was, and its previews go on playing it. + if (document.folder) { + try { + await writeFile(document.file, await vscode.workspace.fs.readFile(uri)) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + vscode.window.showWarningMessage(`H5P Preview could not read ${document.name} again, and goes on playing the copy it has: ${reason}`) + return + } + } + for (const preview of this.previews) { + if (preview.document === document) preview.panel.webview.postMessage({ type: 'reload' }) + } + }, SETTLE_MS) + } + document.disposables.push(watcher, watcher.onDidChange(changed), watcher.onDidCreate(changed), { dispose: () => clearTimeout(timer) }) + return document + } + + /** + * @param {H5PDocument} document + * @param {vscode.WebviewPanel} panel + */ + async resolveCustomEditor(document, panel) { + const { restricted, untrusted, newest } = defaults() + /** @type {Preview} */ + const preview = { document, panel, id: null, mode: { untrusted, newest } } + // Counted before the server is waited for, so that no other preview's closing stops it meanwhile. + this.previews.add(preview) + this.active = preview + let closed = false + panel.onDidDispose(() => { + closed = true + this.previews.delete(preview) + if (this.active === preview) this.active = null + if (preview.id) this.server?.then((server) => preview.id && server.remove(preview.id)) + if (this.previews.size === 0) this.stopServer() + }) + panel.onDidChangeViewState(() => { + if (panel.active) this.active = preview + }) + panel.webview.onDidReceiveMessage((message) => { + if (!message || typeof message !== 'object') return + // What the page reported, which the webview relays: a state, `ready` or an error. Never a mode, + // whatever its type says: a package's own code can post as the page. + if (message.source === 'h5p-preview') this.states.fire({ ...message, uri: document.uri }) + // The webview's own: its switches as they stand. + else if (message.type === 'mode') preview.mode = { untrusted: Boolean(message.untrusted), newest: Boolean(message.newest) } + }) + + let server + try { + server = await this.serverReady() + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + vscode.window.showErrorMessage(`H5P Preview could not start its server: ${reason}`) + return + } + if (closed) return + preview.id = server.add(document.file, document.name, document.uri.toString()) + panel.webview.options = { enableScripts: true, localResourceRoots: [] } + panel.webview.html = webviewHtml({ + nonce: randomBytes(16).toString('base64'), + config: { origin: server.url, id: preview.id, name: document.name, untrusted, newest, restricted, lang: vscode.env.language } + }) + } + + /** The server, started if no preview has it running. A failed start is not kept: the next preview tries again. */ + serverReady() { + if (!this.server) { + const starting = startServer({ roots: this.roots, packDir: this.packDir, restricted: () => !vscode.workspace.isTrusted }) + this.server = starting + starting.catch(() => { + if (this.server === starting) this.server = null + }) + } + return this.server + } + + stopServer() { + const server = this.server + this.server = null + server?.then((running) => running.close(), () => {}) + } + + /** Plays the active preview's package again. */ + reload() { + this.active?.panel.webview.postMessage({ type: 'reload' }) + } + + /** + * The package in the default browser, by the command's own preview: as the editor plays it, + * or as the settings say for a package no editor shows. It ends when its last tab has closed. + * @param {vscode.Uri} [uri] from the explorer; the active preview's package otherwise + */ + async openInBrowser(uri) { + const target = uri ?? this.active?.document.uri + if (!target) return + const shown = [...this.previews].find((preview) => preview.document.uri.toString() === target.toString()) + const { restricted, untrusted, newest } = defaults() + const mode = shown ? shown.mode : { untrusted, newest } + // Its own copy, which outlives the editor that may have one. + const copy = target.scheme === 'file' ? null : await localCopy(target) + const removeCopy = () => copy && rm(copy.folder, { recursive: true, force: true }).catch(() => {}) + try { + const preview = await previewPackage({ + file: copy ? copy.file : target.fsPath, + roots: this.roots, + libraries: this.packDir, + untrusted: restricted || mode.untrusted, + refreshLibraries: mode.newest + }) + this.browsers.add(preview.close) + preview.closed.then(() => { + this.browsers.delete(preview.close) + removeCopy() + }) + await vscode.env.openExternal(vscode.Uri.parse(`${preview.url}/`)) + } catch (error) { + removeCopy() + vscode.window.showErrorMessage(`H5P Preview could not open the package in the browser: ${error instanceof Error ? error.message : String(error)}`) + } + } + + /** The settings, or the workspace's trust, changed: every preview plays as they now say. */ + applySettings() { + const { restricted, untrusted, newest } = defaults() + for (const preview of this.previews) { + preview.mode = { untrusted, newest } + preview.panel.webview.postMessage({ type: 'settings', restricted, untrusted, newest }) + } + } + + dispose() { + this.stopServer() + for (const close of this.browsers) close() + this.states.dispose() + } +} diff --git a/packages/vscode/src/server.mjs b/packages/vscode/src/server.mjs new file mode 100644 index 00000000..8ef50079 --- /dev/null +++ b/packages/vscode/src/server.mjs @@ -0,0 +1,125 @@ +import { createHash } from 'node:crypto' +import { sendArchive } from '../../verify/lib/preview.mjs' +import { librarySources, serve } from '../../verify/lib/serve.mjs' +import { viewPage } from './page.mjs' + +/** + * The window's preview server: the player, the runtime and the library pack the extension + * carries, a page for each package open in a preview, and the package itself as a static host with + * `Range` serves it. It is the verifier's server (`serve`, `sendArchive`), from this checkout and + * bundled, because a webview's own origin cannot register a Service Worker — the spec takes + * `http` and `https` script URLs only — while a page it frames from 127.0.0.1 can. + */ + +/** + * The ports the server tries, in order, before any free one. Each is an origin, and VS Code keeps + * the player's worker and caches for each origin it has framed, so the address has to be the same + * from one session to the next: the first window takes 4646, a second the next free one, and so + * on, where any free port would be a new origin each time a window's server starts. Not the + * command's 4645, which Open in Browser's preview takes. + */ +export const PORTS = Array.from({ length: 10 }, (_, index) => 4646 + index) + +/** A package's id on the server, its page `/view/` and its archive `/__package//`. */ +const ID = /^[0-9a-f]{16}$/ + +/** + * The id a package is served under: a hash of its URI, so that the same file has the same address + * — and the element its caches — from one session to the next, and a changed file is a new + * package to it by its validator, the file's size and time. + * @param {string} key the package's URI + */ +export function packageId(key) { + return createHash('sha256').update(key).digest('hex').slice(0, 16) +} + +/** + * A language tag as the element takes it, for a package that names none; anything else is none. + * @param {string | null | undefined} value + */ +export function languageTag(value) { + return value && /^[a-z]{2,3}(?:-[a-z0-9]{1,8})*$/i.test(value) ? value : null +} + +/** + * @typedef {object} PreviewServer + * @property {string} url `http://127.0.0.1:`, no trailing slash + * @property {(file: string, name: string, key: string) => string} add serves `file` under the id of `key` + * and returns the id; the same key again counts one more preview of it + * @property {(id: string) => void} remove one preview fewer; the package stops being served with its last + * @property {() => void} close + */ + +/** + * @param {object} options + * @param {{ dist: string, runtime: string }} options.roots the player's files and the runtime's + * @param {string} options.packDir the library pack's parts, served as the pack + * @param {number | number[]} [options.port] the port, or the ports in order, before any free one; + * 0 for any free one at once + * @param {() => boolean} [options.restricted] whether the workspace is in Restricted Mode, asked at + * each page: while it is, every page plays untrusted, whatever its address says + * @returns {Promise} + */ +export async function startServer({ roots, packDir, port = PORTS, restricted = () => false }) { + const sources = librarySources(packDir) + /** @type {Map} */ + const packages = new Map() + + const server = await serve( + roots, + sources, + async (path, request, response) => { + const view = /^\/view\/([^/]+)$/.exec(path) + if (view) { + const entry = ID.test(view[1]) ? packages.get(view[1]) : undefined + if (!entry) { + response.writeHead(404, { 'Content-Type': 'text/plain' }).end('not found') + return true + } + const query = new URL(request.url ?? '/', 'http://localhost').searchParams + const page = viewPage({ + name: entry.name, + src: `/__package/${view[1]}/${encodeURIComponent(entry.name)}`, + packBase: sources.packBase, + // Restricted Mode is the server's to keep, not the address's: an untrusted package's + // content keeps its links, and one to its own page without the flag, clicked, would + // otherwise play it trusted. The tab's switch in a trusted workspace is the address's. + untrusted: restricted() || query.get('untrusted') === '1', + newest: query.get('newest') !== '0', + lang: languageTag(query.get('lang')) + }) + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }).end(page) + return true + } + const archive = /^\/__package\/([^/]+)\/([^/]+)$/.exec(path) + if (archive) { + const entry = ID.test(archive[1]) ? packages.get(archive[1]) : undefined + if (!entry || entry.name !== archive[2]) { + response.writeHead(404, { 'Content-Type': 'text/plain' }).end('not found') + return true + } + await sendArchive(entry.file, request, response) + return true + } + return false + }, + port + ) + + return { + url: server.url, + add(file, name, key) { + const id = packageId(key) + const entry = packages.get(id) + // A file copied again for a remote workspace has a new path under the same key. + if (entry) Object.assign(entry, { file, name, previews: entry.previews + 1 }) + else packages.set(id, { file, name, previews: 1 }) + return id + }, + remove(id) { + const entry = packages.get(id) + if (entry && --entry.previews === 0) packages.delete(id) + }, + close: server.close + } +} diff --git a/packages/vscode/src/webview.mjs b/packages/vscode/src/webview.mjs new file mode 100644 index 00000000..bd7c6c2b --- /dev/null +++ b/packages/vscode/src/webview.mjs @@ -0,0 +1,191 @@ +/** + * What a preview's webview is told when it is made. + * @typedef {object} WebviewConfig + * @property {string} origin the preview server's origin, which the frame loads from + * @property {string} id the package's id on the server + * @property {string} name the file's name + * @property {boolean} untrusted the mode a new preview starts in + * @property {boolean} newest with the pack's newer libraries + * @property {boolean} restricted the workspace is in Restricted Mode: untrusted, and no switching + * @property {string | null} lang VS Code's language, for a package that names none + */ + +/** + * The webview of a preview: a bar with what the package reached and the two switches, and the + * frame that plays it. Everything inline, under a nonce; the frame may load from the server's + * origin alone. + * + * Messages are taken from two places only. The frame's, by its window and the server's origin: + * what the element reached — a state, `ready`, an error — which goes on to the extension, and + * nothing else. The extension's, by the webview's own origin: reload, a change of trust or of the + * settings. A package's own code runs in a frame below the page, on the server's origin. What it + * posts itself is from neither place; played trusted, though, it shares the page's origin and can + * post as the page, so the most it can do is misreport its own state. + * @param {object} options + * @param {string} options.nonce + * @param {WebviewConfig} options.config + */ +export function webviewHtml({ nonce, config }) { + const json = JSON.stringify(config).replaceAll('<', '\\u003c') + return ` + + + + + + + + +
+ Opening… + + + + +
+ + + + + +` +} diff --git a/packages/vscode/tests/html.test.ts b/packages/vscode/tests/html.test.ts new file mode 100644 index 00000000..0189f67f --- /dev/null +++ b/packages/vscode/tests/html.test.ts @@ -0,0 +1,235 @@ +import { runInNewContext } from 'node:vm' +import { describe, expect, it } from 'vitest' +import { viewPage } from '../src/page.mjs' +import { webviewHtml } from '../src/webview.mjs' + +const config = { + origin: 'http://127.0.0.1:4646', + id: '0123456789abcdef', + name: 'quiz.h5p', + untrusted: false, + newest: true, + restricted: false, + lang: 'en' +} + +const WEBVIEW_ORIGIN = 'vscode-webview://webview' + +/** The inline script of `html` whose opening tag's attributes `attributes` matches. */ +function inlineScript(html: string, attributes: RegExp) { + // An end tag ends at its own `>`: `` and `` end a script as `` does. + for (const [, opening, body] of html.matchAll(/]*)>([\s\S]*?)<\/script\b[^>]*>/gi)) { + if (attributes.test(opening)) return body + } + throw new Error(`no script with attributes ${attributes}`) +} + +type Listener = (event: unknown) => void + +/** + * An element as the two scripts use one, and as `` is before its module has defined it: + * attributes and listeners, and no accessors of its own. + */ +class StandIn { + attributes = new Map() + listeners = new Map() + children: unknown[] = [] + className = '' + title = '' + textContent = '' + checked = false + disabled = false + src = '' + contentWindow = {} + setAttribute(name: string, value: string) { + this.attributes.set(name, String(value)) + } + hasAttribute(name: string) { + return this.attributes.has(name) + } + addEventListener(type: string, listener: Listener) { + this.listeners.set(type, listener) + } + replaceChildren(...nodes: unknown[]) { + this.children = nodes + } + append(...nodes: unknown[]) { + this.children.push(...nodes) + } +} + +/** The webview's script, run against stand-ins: what it posts to the extension, and a way to message it. */ +function runWebview(state?: object) { + const html = webviewHtml({ nonce: 'n0nce', config }) + const json = /quiz') + const json = /.h5p' + const file = join(folder, 'quiz.h5p') + await copyFile(quiz, file) + const id = server.add(file, name, 'file:///odd') + const page = await (await fetch(`${server.url}/view/${id}`)).text() + expect(page).not.toContain('