Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .DS_Store
Binary file not shown.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,5 @@ dist
.yarn/install-state.gz
.pnp.*
package-lock.json

.DS_Store
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ npm install .

```

## Development/contributing

Run `npm run dev` to start a development server at `http://localhost:8000/`. It will rebuild and reload the preview webpages when changes are made to `template.html`.

## Usage

```
Expand Down
129 changes: 129 additions & 0 deletions dev.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import * as fs from "node:fs";
import * as http from "node:http";
import * as path from "node:path";
import { Readable } from 'node:stream';
import { spawn } from 'node:child_process';

const PORT = 8000;

const MIME_TYPES = {
default: "application/octet-stream",
html: "text/html; charset=UTF-8",
js: "text/javascript",
css: "text/css",
png: "image/png",
jpg: "image/jpeg",
gif: "image/gif",
ico: "image/x-icon",
svg: "image/svg+xml",
};

const toBool = [() => true, () => false];

const STATIC_PATH = path.join(process.cwd(), "./test_data");

const PAGES = []

try {
const dir = await fs.opendirSync(STATIC_PATH);
for await (const dirent of dir)
if (fs.existsSync(path.join(STATIC_PATH, dirent.name, "ro-crate-preview.html"))) {
PAGES.push({
name: dirent.name,
link: path.join(dirent.name, "ro-crate-preview.html")
})
}
} catch (err) {
console.error(err);
}

function indexPage() {
let contents = `
<!DOCTYPE html>
<style>
ul {
list-style-type: none;
margin: auto;
font-size: 1.5rem;
}
</style>
<p>RO Crate HTML Lite development server</p>
<ul>
`
contents += "<ul>"
for (let page of PAGES) {
contents += `<li><a href="${page.link}">${page.name}</a></li>`
}
contents += "</ul></html>"

return {
found: true,
ext: "html",
stream: Readable.from(contents),
}
}

const prepareFile = async (url) => {
if (url === "/") {
return indexPage()
}
if (url.startsWith("/script")) {
filePath = path.join(process.cwd(), url.slice(7))
const stream = fs.createReadStream(filePath);
const { mtimeMs } = fs.statSync(filePath);
return { found: true, ext: "js", mtime: mtimeMs, stream }
}
const paths = [STATIC_PATH, url];
if (url.endsWith("/")) paths.push("../index.html");
var filePath = path.join(...paths);
const pathTraversal = !filePath.startsWith(STATIC_PATH);
const exists = await fs.promises.access(filePath).then(...toBool);
const found = !pathTraversal && exists;
if (found) {
const ext = path.extname(filePath).substring(1).toLowerCase();
const stream = fs.createReadStream(filePath);
const { mtimeMs } = fs.statSync(filePath);
return { found, ext, mtime: mtimeMs, stream };
} else {
return { found: false }
}
};

http
.createServer(async (req, res) => {
const file = await prepareFile(req.url);
const statusCode = file.found ? 200 : 404;
const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
if (file.found) {
res.writeHead(statusCode, {
"Content-Type": mimeType,
"ETag": file.mtime || null,
});
file.stream.pipe(res);
} else {
res.writeHead(statusCode, { "Content-Type": mimeType });
Readable.from("404 not found").pipe(res);
if (req.method !== "HEAD") {
console.log(`Error: ${req.method} ${req.url} ${statusCode}`);
}
}
})
.listen(PORT);

console.log(`Server running at http://localhost:${PORT}/\n`);

const reloadPreview = (fullPath, filename) => {
const proc = spawn("node",
[
"index.js",
fullPath.slice(0, -filename.length)
]
)
proc.on('close', () => console.log(`recreated ${fullPath.slice(STATIC_PATH.length)}`))
}

fs.watch(path.join(process.cwd(), "template.html"), async (_eventType, _filename) => {
for await (const page of PAGES) {
reloadPreview(path.join(STATIC_PATH, page.name, "ro-crate-metadata.json"), "ro-crate-metadata.json")
}
})
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"main": "index.js",
"scripts": {
"test": "mocha test/test-bounding-box.js",
"visualize": "node test/test-bounding-box.js"
"visualize": "node test/test-bounding-box.js",
"dev": "node --no-warnings dev.js"
},
"author": "Peter Sefton",
"license": "GPL-3.0",
Expand Down
93 changes: 93 additions & 0 deletions simple-live-reload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*Copyright 2025 Lean Rada.
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 therights 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.*/
if (
location.hostname === "localhost" ||
location.hostname === "127.0.0.1" ||
location.hostname === "[::1]"
) {
const interval = Number(document.currentScript?.dataset.interval || 1000);
const debug = document.currentScript?.hasAttribute("data-debug") || false;

let watching = new Set();
watch(location.href);

new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
watch(entry.name);
}
}).observe({ type: "resource", buffered: true });

function watch(urlString) {
if (!urlString) return;
const url = new URL(urlString);
if (url.origin !== location.origin) return;

if (watching.has(url.href)) return;
watching.add(url.href);

if (debug) {
console.log("[simple-live-reload] watching", url.href);
}

let focused = false;
let etag, lastModified, contentLength;
let request = { method: "head", cache: "no-store" };

async function check() {
try {
if (document.hidden) return;
if (focused) return;
} finally {
focused = document.hasFocus();
}

const res = await fetch(url, request);
if (res.status === 405 || res.status === 501) {
request.method = "get";
request.headers = {
Range: "bytes=0-0",
};
return check();
}

const newETag = res.headers.get("ETag");
const newLastModified = res.headers.get("Last-Modified");
const newContentLength = res.headers.get("Content-Length");

if (
(etag && etag !== newETag) ||
(lastModified && lastModified !== newLastModified) ||
(contentLength && contentLength !== newContentLength)
) {
if (debug) {
console.log("[simple-live-reload] change detected in", url.href);
}
try {
location.reload();
} catch (e) {
location = location;
}
}

etag = newETag;
lastModified = newLastModified;
contentLength = newContentLength;
}

check();
setInterval(check, interval);
document.addEventListener(
"visibilitychange",
() => !document.hidden && check()
);
}
}
6 changes: 5 additions & 1 deletion template.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
<!-- Prevent some browsers from requesting favicon -->
<link rel="icon" href="data:;base64,=">
<style>
body{
font-family: Arial, Helvetica, sans-serif;
Expand Down Expand Up @@ -418,7 +420,9 @@
input.parentNode.getElementsByClassName("count")[0].innerText = `${found - 1} / ${count - 1}`;
}


if (window.location.hostname === "localhost") {
import("/script/simple-live-reload.js");
}
</script>


Expand Down
6 changes: 5 additions & 1 deletion test_data/WO_SubCollections/ro-crate-preview.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<!-- Prevent some browsers from requesting favicon -->
<link rel="icon" href="data:;base64,=">
<style>
body{
font-family: Arial, Helvetica, sans-serif;
Expand Down Expand Up @@ -418,7 +420,9 @@
input.parentNode.getElementsByClassName("count")[0].innerText = `${found - 1} / ${count - 1}`;
}


if (window.location.hostname === "localhost") {
import("/script/simple-live-reload.js");
}
</script>


Expand Down
Loading