Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
886d48f
chore(release): merge main into staging [skip ci]
github-actions[bot] Nov 13, 2026
a13b824
fix(cli): on WSL, wait for a Windows opener's exit code, keep paths P…
hyamero Nov 14, 2026
e68e3e7
refactor(layout): share one coordinate rounding helper with core
hyamero Nov 13, 2026
7003475
fix(cli): keep serve running when a request path is not a valid URL
hyamero Nov 13, 2026
7d3904d
fix(cli): accept the port-less Host header that clients send when ser…
hyamero Nov 13, 2026
5d6e2b0
fix(viewer): keep the export menu open when an item is pressed in Safari
hyamero Nov 13, 2026
34f8215
fix(viewer): forget a pan's target when another camera move cuts it s…
hyamero Nov 13, 2026
458a7f6
fix(cli): pick up saves made during serve's first layout, and rebuild…
hyamero Nov 13, 2026
330a410
fix(cli): stop warning of a slow layout for workflow, lifecycle and s…
hyamero Nov 13, 2026
27be047
fix(cli): have serve say when a large diagram is being laid out
hyamero Nov 13, 2026
db0ba3b
perf(layout): skip routes nowhere near a label when placing it
hyamero Nov 13, 2026
f1899f5
fix(cli): skip serve rebuilds when the watched file's content has not…
hyamero Nov 13, 2026
c0d5e37
fix(viewer): centre a search result that was off screen instead of pa…
hyamero Nov 13, 2026
296271b
fix(layout): keep a repeated unanswered call in the activation bar it…
hyamero Nov 13, 2026
4a639f3
fix(viewer): keep a route to what lies between its ends, not loops ba…
hyamero Nov 13, 2026
4885152
fix(layout): end a sequence message on the bar it meets left of a nes…
hyamero Nov 13, 2026
fc61ac4
fix(cli): report serve's port and folder failures as plain errors, no…
hyamero Nov 13, 2026
5417160
fix(viewer): refit the presentation once full screen has resized the …
hyamero Nov 13, 2026
9fcf8e1
docs(site): reserve the walkthrough's runway in CSS so a hash or a re…
hyamero Nov 13, 2026
09684ec
fix(layout): size an empty group's frame to hold its title
hyamero Nov 13, 2026
ddac338
fix(cli): reject an empty or non-numeric --port instead of serving on…
hyamero Nov 13, 2026
d540987
fix(cli): refuse to overwrite the input when -o names it in a differe…
hyamero Nov 13, 2026
0d58890
fix(viewer): leave ⌘/Ctrl/Alt key combinations on the canvas to the b…
hyamero Nov 13, 2026
fdddbf7
fix(layout): keep edge labels off a group title wider than 160px
hyamero Nov 13, 2026
4a7f218
fix(core): budget a row label against its value as rendered, so padde…
hyamero Nov 13, 2026
e107004
fix(viewer): show a card's link in the inspector when the card has no…
hyamero Nov 13, 2026
98ec4d4
docs(site): leave what is already on screen alone when the reveals ta…
hyamero Nov 13, 2026
22af1d3
docs(site): light the edge when its JSON lines are pointed at in a li…
hyamero Nov 13, 2026
31ee23f
docs(site): fetch the search index again after a failed load
hyamero Nov 13, 2026
1c406f5
docs(site): start the embedded viewer's flow only once it is on screen
hyamero Nov 13, 2026
ef4a068
docs(site): keep the gallery's kind filter in step with the address
hyamero Nov 13, 2026
9eb25a1
docs(site): place the docs sheet's section bar when the sheet opens
hyamero Nov 13, 2026
1cf62a9
docs(site): describe Play in the try bar only while it runs over the …
hyamero Nov 13, 2026
6f5678a
docs(site): drop the embedded viewer's header icon on a phone, where …
hyamero Nov 13, 2026
ed5e880
fix(layout): keep a corner that ELK returns as two points in one place
hyamero Nov 13, 2026
2a3238f
fix(schema): suggest an evidence note, not a card row, for a self-loo…
hyamero Nov 13, 2026
f1f1cff
fix(schema): offer to phase the source of a phase-order edge only whe…
hyamero Nov 13, 2026
8a171d3
refactor(schema): read a phase-order edge's phase from phaseViolation…
hyamero Nov 13, 2026
e4e7824
perf(layout): skip a label retry that repeats the first layout, and c…
hyamero Nov 13, 2026
10a651b
fix(viewer): track the edges in flight per diagram, not once for the …
hyamero Nov 13, 2026
1efa898
fix(schema): give an out-of-range number a numeric fix instead of a t…
hyamero Nov 13, 2026
78a05d8
fix(schema): stop suggesting a move for unknown keys named like Objec…
hyamero Nov 13, 2026
7a51745
fix(schema): warn about an empty card footer, which draws a blank band
hyamero Nov 13, 2026
f0252d4
test(cli): resolve the built CLI with fileURLToPath so smoke and e2e …
hyamero Nov 13, 2026
ed542bc
test(cli): cover serve skipping a rebuild when a save changes nothing
hyamero Nov 13, 2026
052fec3
refactor(viewer): look up a viewer's cards and dot grid within that v…
hyamero Nov 13, 2026
ddc8b0f
docs(layout): say why a large diagram wraps without the width gate
hyamero Nov 13, 2026
bba2bf2
docs(site): keep the docs search's keys after a press on its panel, a…
hyamero Nov 13, 2026
a2c86cb
docs(site): fit the embedded viewer's still to the stage's 936px, its…
hyamero Nov 13, 2026
c64c5a4
docs(site): drop a phone gap rule that restates the embedded viewer's…
hyamero Nov 13, 2026
c2c2d4d
docs(site): write "An architecture diagram" in the example pages' des…
hyamero Nov 13, 2026
8c9923b
docs(site): list a schema field once in the search when folded card p…
hyamero Nov 13, 2026
48b22cd
docs(site): name the package, the repo and the schema URL in one module
hyamero Nov 13, 2026
a4b103c
docs(site): light the innermost group when linked figure frames nest
hyamero Nov 13, 2026
30c6f77
docs(site): count the gallery's kinds with the filter's own match
hyamero Nov 13, 2026
5eb8ebb
docs(site): take the landing's and the quick start's request from the…
hyamero Nov 13, 2026
7227d9c
docs(site): remove the unused Still, Note, three icons and their CSS
hyamero Nov 13, 2026
31b8cef
docs(site): fit stills and live scenes to their box with one hook
hyamero Nov 13, 2026
75ee6d7
docs(site): let git diff's own failure cover a commit missing from th…
hyamero Nov 13, 2026
30a0a59
perf(viewer): build flow geometry once per scene, and the flow only w…
hyamero Nov 13, 2026
0f9fd65
fix(layout): keep lane routes off cards and off the port runs that fa…
hyamero Nov 14, 2026
68d3519
docs(site): arrive at a #hash at once, so a glide can't be cut short …
hyamero Nov 14, 2026
b22e4b1
fix(layout): keep edge labels inside the diagram's bounds
hyamero Nov 14, 2026
f7e07d1
fix(layout): size stage bands round group frames, clear of the stage …
hyamero Nov 14, 2026
9dd88e6
fix(layout): keep lane routes off the lanes' edges
hyamero Nov 14, 2026
d096c73
docs(site): test the search's schema fields without the generated dat…
hyamero Nov 14, 2026
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
6 changes: 3 additions & 3 deletions packages/cli/e2e/offline.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { expect, test } from '@playwright/test';
import { groupedPlatform } from '@stackmap/core/samples';

test('a delivered file renders from file:// with no network', async ({ page }) => {
const dir = mkdtempSync(join(tmpdir(), 'stackmap-e2e-'));
const input = join(dir, 'platform.json');
writeFileSync(input, JSON.stringify(groupedPlatform));
execFileSync('node', [new URL('../dist/cli.js', import.meta.url).pathname, 'deliver', input]);
execFileSync('node', [fileURLToPath(new URL('../dist/cli.js', import.meta.url)), 'deliver', input]);

const requests: string[] = [];
await page.route('**/*', (route) => {
Expand All @@ -29,6 +29,6 @@ test('a delivered file renders from file:// with no network', async ({ page }) =
});

test('the bare template says no diagram is embedded', async ({ page }) => {
await page.goto(pathToFileURL(new URL('../dist/viewer.html', import.meta.url).pathname).href);
await page.goto(new URL('../dist/viewer.html', import.meta.url).href);
await expect(page.getByRole('status')).toHaveText(/No diagram embedded/);
});
3 changes: 2 additions & 1 deletion packages/cli/e2e/serve.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect, test } from '@playwright/test';
import { commerceApi } from '@stackmap/core/samples';

Expand All @@ -15,7 +16,7 @@ async function start(initial: unknown, port = '0') {
file = join(mkdtempSync(join(tmpdir(), 'stackmap-live-')), 'd.json');
write(initial);
}
proc = spawn('node', [new URL('../dist/cli.js', import.meta.url).pathname, 'serve', file, '--port', port]);
proc = spawn('node', [fileURLToPath(new URL('../dist/cli.js', import.meta.url)), 'serve', file, '--port', port]);
url = await new Promise<string>((resolve, reject) => {
proc.stdout!.on('data', (b: Buffer) => {
const m = /serving (http:\/\/127\.0\.0\.1:\d+)/.exec(b.toString());
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/scripts/smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import { createHash } from 'node:crypto';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { GALLERY } from '../../core/src/samples/gallery.ts';
import { commerceApi, groupedPlatform } from '../../core/src/samples/index.ts';

const cli = new URL('../dist/cli.js', import.meta.url).pathname;
// Not `.pathname`: it keeps percent-escapes, so a checkout path with a space would not resolve.
const cli = fileURLToPath(new URL('../dist/cli.js', import.meta.url));
const dir = mkdtempSync(join(tmpdir(), 'stackmap-smoke-'));
const run = (...args) => execFileSync('node', [cli, ...args], { encoding: 'utf8' });
const check = (ok, msg) => {
Expand Down
11 changes: 5 additions & 6 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readFileSync } from 'node:fs';
import { parseArgs } from 'node:util';
import { deliverCommand, validateCommand, type CommandResult } from './commands';
import { deliverCommand, failure, validateCommand, type CommandResult } from './commands';
import { openInBrowser } from './open';
import { serve } from './serve';
import { styleFor } from './style';
Expand Down Expand Up @@ -81,18 +81,17 @@ async function run(argv: string[]): Promise<CommandResult> {
return signed(command, await deliverCommand(file, { template, out: values.out, style, open, progress }));
}

const port = values.port === undefined ? 4400 : Number(values.port);
if (!Number.isInteger(port) || port < 0 || port > 65535) return usage(`--port must be 0-65535, got "${values.port}"`);
// Digits only: Number('') and Number(' ') are 0, which would silently mean "any free port".
const port = values.port === undefined ? 4400 : /^\d+$/.test(values.port) ? Number(values.port) : NaN;
if (!(port >= 0 && port <= 65535)) return usage(`--port must be 0-65535, got "${values.port}"`);
const server = await serve(file, { template, port, log: (line) => process.stderr.write(`${line}\n`) });
process.stdout.write(sign(command, `serving ${style.path(server.url)} · watching ${file} · Ctrl-C to stop\n`));
await new Promise<void>((resolve) => process.once('SIGINT', resolve));
await server.close();
return { code: 0, stdout: '', stderr: '' };
}

const result = await run(process.argv.slice(2)).catch(
(e: unknown): CommandResult => ({ code: 2, stdout: '', stderr: `stackmap: internal error: ${(e as Error).message}\n` }),
);
const result = await run(process.argv.slice(2)).catch(failure);
process.stdout.write(result.stdout);
process.stderr.write(result.stderr);
process.exitCode = result.code;
11 changes: 7 additions & 4 deletions packages/cli/src/commands.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { extname, resolve } from 'node:path';
import { isLaneKind } from '@stackmap/core';
import { isLarge, layoutDiagram } from '@stackmap/layout';
import { validateDiagram, type Diagnostic, type ValidationResult } from '@stackmap/schema';
import { embedDiagram } from './embed';
Expand Down Expand Up @@ -36,15 +37,16 @@ export function validateFile(path: string): ValidationResult {
}

// Exit 1 means "the diagram has errors" to the agent loop, so every other failure must be exit 2.
const failure = (e: unknown): CommandResult => ({
export const failure = (e: unknown): CommandResult => ({
code: 2,
stdout: '',
stderr: `stackmap: ${e instanceof CliError ? '' : 'internal error: '}${(e as Error).message}\n`,
});

const real = (p: string) => {
try {
return realpathSync(p);
// .native also resolves the name to its case on disk: on macOS and Windows `D.JSON` can be `d.json`.
return realpathSync.native(p);
} catch {
return resolve(p);
}
Expand All @@ -70,9 +72,10 @@ export async function buildHtml(
): Promise<ValidationResult & { html?: string }> {
const result = validateFile(path);
if (!result.ok || !result.diagram) return result;
const { nodes, edges } = result.diagram;
const { kind, nodes, edges } = result.diagram;
// The result only prints once the layout is done; without this a big diagram looks hung for minutes.
if (progress && isLarge(result.diagram))
// Lane and sequence kinds have their own layouts, which take a second at their largest.
if (progress && !isLaneKind(kind) && kind !== 'sequence' && isLarge(result.diagram))
progress(`laying out ${nodes.length} nodes and ${edges.length} connections; a diagram this size can take a while`);
return { ...result, html: embedDiagram(template, await layoutDiagram(result.diagram)) };
}
Expand Down
64 changes: 43 additions & 21 deletions packages/cli/src/open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,27 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

/**
* One way to open a file. `orAt` is where `cmd` lives when it isn't on the PATH. `startFile` is a file for
* PowerShell to start (WSL): its Windows path goes on the end of `args`, as an encoded command.
* One way to open a file. `orAt` finds `cmd` when it isn't on the PATH. `startFile` is a file for PowerShell to
* start (WSL): its Windows path goes on the end of `args`, as an encoded command. `wait` is how long, in ms, the
* opener gets to exit before it counts as having handed the file off.
*/
export type Opener = { cmd: string; args: string[]; orAt?: string; startFile?: string };
export type Opener = { cmd: string; args: string[]; orAt?: () => string; startFile?: string; wait?: number };

// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`; this is the default mount.
const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
const NOT_FOUND = 'not found';
// xdg-open can turn into the browser itself and never exit, so a short wait has to count as a hand-off.
const HANDED_OFF = 3000;
// A Windows program started through WSL interop can take longer than that to load, and its exit code is the only
// sign that nothing opened.
const WINDOWS_START = 15000;

// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`, and `automount.root` moves /mnt.
function powershell(): string {
try {
return wslpath('-u', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe');
} catch {
return '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
}
}

/** Whether this Linux is WSL, where a stock distro has no xdg-open but Windows has a browser. */
export function isWsl(env: NodeJS.ProcessEnv = process.env): boolean {
Expand Down Expand Up @@ -38,22 +51,26 @@ export function browserCommands(
if (!wsl) return [{ cmd: 'xdg-open', args: [file] }];
// The browser is on the Windows side. xdg-open comes last: with no Linux browser it can exit 0 having opened
// nothing, which would end the chain. PowerShell, unlike explorer.exe, exits non-zero when it couldn't start the file.
return [
{ cmd: 'wslview', args: [file] },
{ cmd: 'powershell.exe', orAt: POWERSHELL, args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'], startFile: file },
{ cmd: 'xdg-open', args: [file] },
];
const start: Opener = {
cmd: 'powershell.exe',
orAt: powershell,
args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'],
startFile: file,
wait: WINDOWS_START,
};
// wslview hands the path to PowerShell with quoting of its own, so it only gets paths PowerShell reads literally.
const viaWslview: Opener[] = /[$`'"‘’‚‛“”„]/.test(file) ? [] : [{ cmd: 'wslview', args: [file], wait: WINDOWS_START }];
return [...viaWslview, start, { cmd: 'xdg-open', args: [file] }];
}

/** The PowerShell command that opens `windowsPath` with its default app. */
export function startCommand(windowsPath: string): string {
// PowerShell ends a single-quoted string on the curly quotes too; a doubled one is the only escape.
return `Start-Process -FilePath '${windowsPath.replace(/['‘’‚‛]/g, '$&$&')}'`;
}

function wslpath(file: string): string {
function wslpath(to: '-w' | '-u', path: string): string {
// stderr is dropped so that wslpath's own message doesn't land ahead of the warning.
return execFileSync('wslpath', ['-w', file], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
return execFileSync('wslpath', [to, path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
}

/**
Expand All @@ -65,8 +82,10 @@ export async function openInBrowser(file: string): Promise<string | null> {
return 'refused' in commands ? commands.refused : openWith(commands);
}

/** Tries each opener until one hands the file off; resolves null then, or why every one of them failed. */
export async function openWith(openers: Opener[], windowsPath: (file: string) => string = wslpath): Promise<string | null> {
export async function openWith(
openers: Opener[],
windowsPath: (file: string) => string = (file) => wslpath('-w', file),
): Promise<string | null> {
const failures: string[] = [];
for (const opener of openers) {
const why = await run(opener, windowsPath);
Expand All @@ -76,24 +95,27 @@ export async function openWith(openers: Opener[], windowsPath: (file: string) =>
return failures.join('; ');
}

async function run({ cmd, args, orAt, startFile }: Opener, windowsPath: (file: string) => string): Promise<string | null> {
async function run(
{ cmd, args, orAt, startFile, wait = HANDED_OFF }: Opener,
windowsPath: (file: string) => string,
): Promise<string | null> {
if (startFile !== undefined) {
try {
args = [...args, Buffer.from(startCommand(windowsPath(resolve(startFile))), 'utf16le').toString('base64')];
} catch (e) {
return (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'wslpath not found' : "wslpath couldn't convert the path";
}
}
let why = await launch(cmd, args);
if (why === NOT_FOUND && orAt) why = await launch(orAt, args);
let why = await launch(cmd, args, wait);
if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait);
return why === null ? null : `${cmd} ${why}`;
}

/** Resolves null once the command exits cleanly or is still running after a moment, else what went wrong. */
function launch(cmd: string, args: string[]): Promise<string | null> {
/** Resolves null once the command exits cleanly or is still running after `wait` ms, else what went wrong. */
function launch(cmd: string, args: string[], wait: number): Promise<string | null> {
return new Promise((done) => {
const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' });
const timer = setTimeout(() => done(null), 3000);
const timer = setTimeout(() => done(null), wait);
const finish = (why: string | null) => {
clearTimeout(timer);
done(why);
Expand Down
81 changes: 59 additions & 22 deletions packages/cli/src/serve.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto';
import { watch, type FSWatcher } from 'node:fs';
import { readFileSync, watch, type FSWatcher } from 'node:fs';
import { createServer, type ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';
import { basename, dirname } from 'node:path';
Expand Down Expand Up @@ -41,6 +41,13 @@ const diagnostic = (code: string, message: string, fix: string, path: string): D
allowedFixes: [fix],
});

/** DNS rebinding: a foreign page resolving its own name to 127.0.0.1 would send its own Host. */
export function isLocalHost(host: string | undefined, port: number): boolean {
// Clients leave the port out of Host when it is http's default.
const suffixes = port === 80 ? [':80', ''] : [`:${port}`];
return suffixes.some((s) => host === `127.0.0.1${s}` || host === `localhost${s}`);
}

function listen(server: ReturnType<typeof createServer>, port: number): Promise<number> {
return new Promise((resolve, reject) => {
const tryPort = (p: number, left: number) => {
Expand Down Expand Up @@ -93,9 +100,19 @@ export async function serve(path: string, { template, port = 4400, log = () => {
};

let built = false;
// What the last build read: the watcher also reports saves that change nothing, and a write from just before it started.
let source = '';
const fingerprint = () => {
try {
return createHash('sha256').update(readFileSync(path)).digest('hex');
} catch {
return '';
}
};
const rebuild = async () => {
source = fingerprint();
try {
const result = await buildHtml(path, template);
const result = await buildHtml(path, template, log);
publish({ ok: result.ok, diagnostics: result.diagnostics }, result.html);
} catch (e) {
const unreadable = e instanceof CliError;
Expand All @@ -110,21 +127,54 @@ export async function serve(path: string, { template, port = 4400, log = () => {
}
};

await rebuild();
// One rebuild waits behind the running one however many saves arrive: only the latest content matters.
let queued = false;
let running = Promise.resolve();
const schedule = () => {
if (queued) return;
queued = true;
running = running
.then(() => {
queued = false;
if (fingerprint() !== source) return rebuild();
})
.catch((e: unknown) => log(`✗ rebuild failed: ${(e as Error).message}`));
};

// Editors save by writing a temp file and renaming it over the original, so watch the directory.
// Watching starts before the first build, so a save during that layout is not lost.
let timer: NodeJS.Timeout | undefined;
let watcher: FSWatcher;
try {
watcher = watch(dirname(path), (_event, name) => {
if (name !== null && name !== basename(path)) return;
clearTimeout(timer);
timer = setTimeout(schedule, DEBOUNCE_MS);
});
} catch (e) {
throw new CliError(`cannot watch ${dirname(path)}: ${(e as NodeJS.ErrnoException).code ?? (e as Error).message}`);
}
// e.g. the directory was deleted (EPERM on Windows): report it instead of crashing the server.
watcher.on('error', (e) =>
publish({ ok: false, diagnostics: [diagnostic('io/watch-failed', `stopped watching: ${e.message}`, 'restart stackmap serve', path)] }),
);

running = rebuild();
await running;

let bound = 0;
const server = createServer((req, res) => {
// DNS rebinding: a foreign page resolving its own name to 127.0.0.1 would send its own Host.
if (req.headers.host !== `127.0.0.1:${bound}` && req.headers.host !== `localhost:${bound}`) {
if (!isLocalHost(req.headers.host, bound)) {
res.writeHead(403, { 'content-type': 'text/plain' });
return void res.end('forbidden host');
}
const url = new URL(req.url ?? '/', 'http://localhost');
// Not `new URL`: it throws on a path like `//`, and any page in the user's browser can send one.
const pathname = (req.url ?? '/').split('?', 1)[0];
const read = req.method === 'GET' || req.method === 'HEAD';
if (read && url.pathname === '/') {
if (read && pathname === '/') {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
res.end(req.method === 'HEAD' ? undefined : page);
} else if (req.method === 'GET' && url.pathname === '/events') {
} else if (req.method === 'GET' && pathname === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
res.write('retry: 1000\n\n');
send(res, 'diagnostics', JSON.stringify(state));
Expand All @@ -136,23 +186,10 @@ export async function serve(path: string, { template, port = 4400, log = () => {
}
});

// Editors save by writing a temp file and renaming it over the original, so watch the directory.
let timer: NodeJS.Timeout | undefined;
let running = Promise.resolve();
const watcher: FSWatcher = watch(dirname(path), (_event, name) => {
if (name !== null && name !== basename(path)) return;
clearTimeout(timer);
timer = setTimeout(() => {
running = running.then(rebuild).catch((e: unknown) => log(`✗ rebuild failed: ${(e as Error).message}`));
}, DEBOUNCE_MS);
});
// e.g. the directory was deleted (EPERM on Windows): report it instead of crashing the server.
watcher.on('error', (e) =>
publish({ ok: false, diagnostics: [diagnostic('io/watch-failed', `stopped watching: ${e.message}`, 'restart stackmap serve', path)] }),
);
const keepAlive = setInterval(() => clients.forEach((res) => res.write(': ping\n\n')), 15_000);

bound = await listen(server, port).catch((e) => {
clearTimeout(timer);
watcher.close();
clearInterval(keepAlive);
throw e;
Expand Down
Loading
Loading