winzik/docker/web-dev/live.js
David Nurdin 23966a2d07 Web sites: reliable live reload between the browser and the IDE
The reload container (docker/web-dev/live.js, browser-sync) now publishes the site's port itself, so the page's socket can connect
(the old proxy ws option moved it to an unpublished port: the tab never followed). The IDE tells it each saved file (POST /__jumphp/notify),
so it works without file events (Docker Desktop also polls); CSS is injected without a reload, anything else reloads once.
Status bar item Live: N (browser tabs connected), open the site at the live-reload address, turn it off ('live': 'off' in web.json).
bin/jumphp web:live, LiveReload (IDE) + tests, end-to-end test with headless Chrome on a Symfony site, docs, 14 languages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 10:31:20 +01:00

143 lines
6.3 KiB
JavaScript

// The live-reload server of a JumPHP web site (tools/web.sh copies it to .jumphp/live.js and runs it in the "reload" service):
// browser-sync as a proxy in front of the site (it injects its client into every page) + what makes it reliable:
// - the files are watched (inotify, or polling when JUMPHP_LIVE_POLL=1: Docker Desktop's bind mounts send no events),
// - the IDE says each save itself: POST /__jumphp/notify {"files": ["templates/base.html.twig"]} (no event needed),
// - GET /__jumphp/status -> {"ok": true, "clients": <browser tabs connected>, "reloads": N, ...}.
// A CSS change is injected without a reload (scroll and state kept); anything else reloads the page.
const fs = require('fs');
const path = require('path');
const browserSync = require('browser-sync').create();
const ROOT = '/app';
const TARGET = process.env.JUMPHP_LIVE_TARGET || 'http://app:8080';
const LIVE_PORT = parseInt(process.env.JUMPHP_LIVE_PORT || '3000', 10); // the port the browser opens (the same inside and outside the container: the page's socket connects there)
const POLL = process.env.JUMPHP_LIVE_POLL === '1';
const IGNORED_DIRS = new Set(['vendor', 'node_modules', 'var', '.git', '.jumphp', 'cache', 'uploads']);
const CSS = /\.css$/i;
const PRECSS = /\.(scss|sass|less|styl)$/i;
const WATCHED = /\.(php|twig|html|css|js|mjs|tpl|ya?ml|json|svg|env|xlf|po|ini|neon)$|(^|\/)\.env(\.[\w.-]+)?$/i;
const state = { reloads: 0, injects: 0, last: null, lastFiles: [] };
const seen = new Map(); // file -> mtime already reloaded (the watcher and the IDE's notice say the same save)
let pending = new Set();
let timer = null;
function mtime(file) {
try { return fs.statSync(path.join(ROOT, file)).mtimeMs; } catch (e) { return -1; }
}
function rel(file) {
return String(file).replace(/\\/g, '/').replace(/^\/app\//, '').replace(/^\/+/, '');
}
function ignored(file) {
return rel(file).split('/').some((p) => IGNORED_DIRS.has(p)) || /composer\.lock$|package-lock\.json$/.test(file);
}
function schedule(file, notified) {
file = rel(file);
if (!file || ignored(file)) return;
if (PRECSS.test(file)) { scanCss(); return; } // the compiler (sass --watch) writes the .css: found by the scan
const m = mtime(file);
// the watcher and the IDE's notice tell the same save: reloaded once
if (m !== -1 && seen.get(file) === m && !pending.has(file)) return;
seen.set(file, m);
pending.add(file);
clearTimeout(timer);
timer = setTimeout(flush, 120);
}
function flush() {
const files = [...pending];
pending = new Set();
const css = files.length > 0 && files.every((f) => CSS.test(f));
state.last = Date.now();
state.lastFiles = files.slice(0, 20);
if (css) {
state.injects++;
browserSync.reload(files.map((f) => path.basename(f))); // injected: no page reload
} else {
state.reloads++;
browserSync.reload();
}
console.log(`[live] ${css ? 'css injected' : 'reload'}: ${files.join(', ')}`);
}
// after a .scss save: the compiled .css files that change in the next seconds are injected
let scanning = false;
function scanCss() {
if (scanning) return;
scanning = true;
const before = new Map();
walk(ROOT, (f, m) => before.set(f, m));
let n = 0;
const iv = setInterval(() => {
walk(ROOT, (f, m) => { if (before.get(f) !== m) { before.set(f, m); schedule(f, true); } });
if (++n >= 16) { clearInterval(iv); scanning = false; }
}, 500);
}
function walk(dir, cb, depth = 0) {
if (depth > 8) return;
let entries = [];
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { return; }
for (const e of entries) {
const full = path.join(dir, e.name);
if (e.isDirectory()) { if (!IGNORED_DIRS.has(e.name)) walk(full, cb, depth + 1); }
else if (CSS.test(e.name)) { try { cb(path.relative(ROOT, full), fs.statSync(full).mtimeMs); } catch (x) { /* gone */ } }
}
}
function clients() {
try {
// browserSync.sockets is socket.io's main namespace; the pages connect to browser-sync's own ("/browser-sync")
const ns = browserSync.sockets.server.of('/browser-sync');
if (ns && ns.sockets && typeof ns.sockets.size === 'number') return ns.sockets.size;
} catch (e) { /* unknown */ }
return -1;
}
function json(res, code, body) {
res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(body));
}
const api = {
route: '/__jumphp',
handle(req, res) {
const url = (req.url || '').split('?')[0];
if (req.method === 'GET' && (url === '/status' || url === '/' || url === '')) {
return json(res, 200, { ok: true, clients: clients(), reloads: state.reloads, injects: state.injects, last: state.last, files: state.lastFiles, poll: POLL });
}
if (req.method === 'POST' && url === '/notify') {
// a web page cannot make the IDE's notice (browsers always send Origin on a cross-origin POST)
if (req.headers.origin) return json(res, 403, { ok: false, error: 'origin' });
let body = '';
req.on('data', (c) => { body += c; if (body.length > 100000) req.destroy(); });
req.on('end', () => {
let files = [];
try { files = (JSON.parse(body || '{}').files || []).map(String); } catch (e) { /* none */ }
files.forEach((f) => schedule(f, true));
json(res, 200, { ok: true, files: files.length, clients: clients() });
});
return;
}
json(res, 404, { ok: false });
},
};
browserSync.init({
// no `ws: true`: it moves browser-sync's socket to port 3001, which nothing publishes (the page could never connect); without it
// the socket shares the site port, the one the browser opens
proxy: { target: TARGET, proxyOptions: { changeOrigin: false } },
port: LIVE_PORT, open: false, ui: false, notify: false, ghostMode: false, logLevel: 'silent',
middleware: [api],
files: [{
match: [ROOT + '/**/*'],
fn: (event, file) => { if (['add', 'change', 'unlink'].includes(event) && WATCHED.test(file)) schedule(file, false); },
options: {
ignoreInitial: true, usePolling: POLL, interval: 400,
ignored: [/(^|[\/\\])(vendor|node_modules|var|\.git|\.jumphp|cache|uploads)([\/\\]|$)/, /composer\.lock$|package-lock\.json$/],
},
}],
}, (err) => { if (err) { console.error(err); process.exit(1); } console.log('[live] ready on :' + LIVE_PORT + ' (' + (POLL ? 'polling' : 'inotify') + ')'); });