# Http-ws: complete application

> Documentation for Redweb 0.13.0. Install that exact version when following these examples.

## HTTP and WebSockets on one listener

One Node server answers ordinary HTTP requests and upgrades `/chat` connections to WebSockets. HTTP paths select Express services; a socket URL selects a route and each message's `type` selects a handler. No socket decorators or secondary `message.action` dispatcher are needed.

After starting the application, request `http://127.0.0.1:8181/health` to receive `{"ok":true}`. Connect a WebSocket to `ws://127.0.0.1:8181/chat` and send `{"type":"hello"}` to receive `{"type":"hello","message":"Hello from the server!"}`. This is a raw JSON socket example, not a chatroom UI or the versioned socket-contract protocol. Use the chat or socket starter for those applications.

The HTTP builder does not bind a port. The socket service explicitly takes responsibility for listening and closing the supplied server with `listen: true` and `closeServerOnShutdown: true`. Call the returned application's `shutdown()`; it processes route failures and still closes its HTTP/TCP peers. Do not separately close the HTTP builder. Importing this module creates no listener; the standalone entrypoint uses the same bounded `runApp` helper as the other starters.

`/health` reports liveness, not readiness or completed application work. Loopback binding is intentional. Before exposing the service, choose your deployment bind address, configure HTTPS/WSS, trusted origins, authentication, authorization, payload/connection limits, and any persistence you need. Shared listeners do not automatically provide these policies. Shutdown may force connections closed; it does not guarantee message delivery or durable work.

`npm test` runs real HTTP and WebSocket requests on ephemeral ports, checks strict socket routing and multiple clients, verifies idempotent cleanup with an incomplete HTTP peer, and proves a failing route cleanup still closes the listener. It also runs the shared process-lifecycle suite. No mocks are used. The package verification gate repeats the tests against the compiled application with `src/` unavailable.


## Setup and acceptance

```sh
npx --yes redweb@0.13.0 init my-http-ws --template http-ws
cd my-http-ws
npm install --save-exact redweb@0.13.0
npm test
npm run dev
```


Requirements: Node.js 18 or newer and npm for the realtime, chat, site, socket and http-ws templates; the dashboard template requires Node.js 22.13+ for native SQLite. Use a currently supported Node.js release in production.

For an unreleased checkout or tarball, first run `npm install --save-exact TARBALL`, replacing `TARBALL` with the absolute path to the same tested Redweb tarball used to generate this app (quote paths containing spaces). This installs the matching package and its published client dependency. Do not substitute an older registry release or `latest`. Published Redweb releases can use the installation command below directly.

```sh
npm install
npm test
npm run dev
```

HTTP starters open at http://localhost:8181; the authenticated dashboard uses http://127.0.0.1:8181/login and requires account provisioning described below. Set the `PORT` environment variable to change the listener.
`npm test` builds and runs real HTTP/WebSocket integration tests on an ephemeral loopback port. No mocks or external service are needed.
`npm run test:coverage` runs the same tests with application coverage mapped back to TypeScript. Reports are written to the ignored `coverage/` directory; this is separate from Redweb library coverage. TypeScript-generated decorator accessors can appear in function counts even when the framework does not call them. The report exposes remaining gaps; it does not certify complete application coverage. Source maps are generated during the build for diagnostics and coverage, but no coverage collector is loaded by `npm start`.

## Development and production

Edit `src/app.tsx`. `npm run dev` watches TypeScript, TSX, CSS, HTML, and the root TypeScript configuration,
then rebuilds and restarts the server. A type error stops startup until you fix it. On direct localhost access,
HTML pages refresh automatically when a new server revision is ready. If edits were detected, a keyboard-accessible
notice keeps the old document until you choose **Reload and discard drafts**. This is a conservative edit guard,
not autosave or browser hot-module replacement: restarts reset in-memory state and old socket sessions.
The generated development command sets `REDWEB_DEV_REFRESH=1`; `development: { refresh: false }` overrides it.
The refresh feature is refused under `NODE_ENV=production`, applies only to served HTML (not raw sockets or static exports),
and creates no local/session-storage copy of form contents. Use direct `localhost`, `127.x.x.x`, or `[::1]` access;
custom hostnames, tunnels and proxy-forwarded origins are not supported by this development helper.
`npm run build` checks types and copies CSS/HTML beside the compiled classes in `dist/`.
Run `npm start` to serve the compiled app. For deployment, build first, ship `dist/`, `package.json`, and the lockfile,
then install runtime dependencies with `npm ci --omit=dev`. The application does not require TypeScript or `src/` at runtime.

The standalone entrypoint calls the shared `runApp(createApp)` helper. Importing either module starts no listener and installs no process handlers. On SIGINT/SIGTERM, a listener error, or native listener closure, the helper calls application shutdown once. Repeated signals do not bypass cleanup. The five-second outer deadline covers the whole application, including database/worker cleanup after HTTP closes; customize it with the helper's second argument if necessary. Cleanup must resolve only after resources are released. A failed cleanup sets a failure exit status and retains a deadline for any surviving handles; the helper never resets an existing failure status. If cleanup does not finish in time, the entrypoint terminates the process with a failure status. This cannot preempt synchronous code blocking Node's event loop and does not make in-memory state durable. Factory functions remain responsible for releasing partially constructed resources before throwing.

The shipped lifecycle tests exercise actual processes, HTTP/TCP/WebSocket peers and timers. Linux uses actual OS signals; Windows tests explicitly emit signal events inside the process because killing a Windows child does not exercise graceful POSIX signal delivery. This is not a claim that Windows console/service managers forward the same signals. Deploy with a supervisor that forwards the supported termination signal and allows longer than the configured cleanup deadline.

For public deployment, configure HTTPS/WSS at your Node server or reverse proxy, authentication, trusted origins,
and application-specific rate limits. These starters are demonstrations, not a hosted identity or database service.
Never commit secrets; `.env` is ignored but is not loaded automatically.

`npx --no-install redweb doctor --json` reports configuration problems without changing your files.


## Exact generated files

These files come from the initializer itself. The tests below run real listeners; they are not illustrative pseudocode. The generated manifest uses the package metadata version; the installation step above pins the matching artifact or release.

### package.json

```json
{
  "name": "redweb-app",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "build": "tsc && node scripts/copy-assets.cjs",
    "start": "node dist/app.js",
    "dev": "nodemon",
    "test": "npm run build && node --test test/app.test.cjs test/run-app.test.cjs",
    "test:coverage": "npm run build && c8 --all --src=dist --include=dist/** --reporter=text --reporter=json node --test test/app.test.cjs test/run-app.test.cjs"
  },
  "dependencies": {
    "redweb": "^0.13.0"
  },
  "devDependencies": {
    "typescript": "^5.9.3",
    "nodemon": "^3.1.11",
    "ws": "^8.21.3",
    "c8": "^10.1.3"
  },
  "nodemonConfig": {
    "env": {
      "REDWEB_DEV_REFRESH": "1"
    },
    "watch": [
      "src",
      "tsconfig.json"
    ],
    "ext": "ts,tsx,css,html,json",
    "exec": "npm run build && npm start || exit 1",
    "delay": 200
  }
}
```

### tsconfig.json

```json
{
  "extends": "redweb/tsconfig.json",
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "dist",
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ]
}
```

### src/app.tsx

```tsx
import { BaseHandler, HttpServer, METHODS, SocketRoute, SocketServer, type RedWebSocket, type SocketServerOptions } from 'redweb';
import { runApp } from './run-app';

export class Hello extends BaseHandler {
    constructor() { super('hello'); }

    onMessage(socket: RedWebSocket) {
        socket.sendJson({ type: 'hello', message: 'Hello from the server!' });
    }
}

export class ChatRoute extends SocketRoute {
    constructor() {
        super({ path: '/chat', handlers: [Hello], allowDuplicateConnections: true });
    }
}

export function createApp(options: Pick<SocketServerOptions, 'port' | 'bind' | 'logger'> = {}) {
    const http = new HttpServer({
        listen: false,
        publicPaths: [],
        services: [{ serviceName: '/health', method: METHODS.GET, function: (_req, res) => res.json({ ok: true }) }],
    });

    return new SocketServer({
        port: options.port ?? Number(process.env.PORT ?? 8181),
        bind: options.bind ?? '127.0.0.1',
        logger: options.logger,
        server: http.server,
        routes: [ChatRoute],
        listen: true,
        closeServerOnShutdown: true, // One owner closes routes and the shared HTTP listener.
    });
}

if (require.main === module) runApp(createApp);
```

### src/run-app.ts

```ts
import type { Server } from 'node:http';

interface Application { server: Server; shutdown(): Promise<void>; }

/** Entry-point policy only: importing a recipe never installs process handlers. */
export function runApp<T extends Application>(createApp: () => T, shutdownTimeoutMs = 5000): T | undefined {
    if (!Number.isInteger(shutdownTimeoutMs) || shutdownTimeoutMs < 1 || shutdownTimeoutMs > 2147483647) {
        throw new RangeError('Application shutdown timeout must be a positive timer-safe integer.');
    }
    const fail = (message: string) => {
        console.error(message);
        if (Number(process.exitCode ?? 0) === 0) process.exitCode = 1;
    };
    let app: T;
    try { app = createApp(); }
    catch { fail('Application startup failed.'); return undefined; }

    let closing: Promise<void> | undefined;
    const stop = () => {
        if (!closing) {
            let failed = false;
            const deadline = setTimeout(() => {
                fail('Application cleanup exceeded its deadline; terminating the process.');
                process.exit();
            }, shutdownTimeoutMs);
            closing = Promise.resolve().then(() => app.shutdown()).catch(() => {
                failed = true;
                fail('Application cleanup failed.');
            }).finally(() => {
                // Failed cleanup may leave live handles. Permit natural exit if none
                // remain, but still force a bounded exit when resources were leaked.
                if (failed) { deadline.unref(); return; }
                clearTimeout(deadline);
                process.off('SIGINT', stop);
                process.off('SIGTERM', stop);
                app.server.off('error', onError);
                app.server.off('close', stop);
            });
        }
        return closing;
    };
    const onError = () => { fail('Application listener failed.'); void stop(); };
    // Persistent handlers keep repeated signals from bypassing active cleanup.
    process.on('SIGINT', stop);
    process.on('SIGTERM', stop);
    app.server.on('error', onError);
    // Native close can precede database/worker cleanup: it starts, never ends, shutdown.
    app.server.once('close', stop);
    return app;
}
```

### src/app.css

```css
:root { color-scheme: dark; font-family: system-ui, sans-serif; background: #08090d; color: #fff; }
body { margin: 0; }
.home { width: min(42rem, calc(100% - 2rem)); margin: 18vh auto 0; }
h1 { font-size: clamp(2rem, 6vw, 4rem); line-height: 1.1; }
p { color: #bfc1ca; line-height: 1.6; }
button { padding: .8rem 1.2rem; background: #ff5064; color: #08090d; border: 0; border-radius: .5rem; cursor: pointer; font: inherit; }
button:focus-visible, a:focus-visible { outline: 3px solid #fff; outline-offset: 4px; }
nav { padding: 1rem; } a { color: #ff8795; }
```

### scripts/copy-assets.cjs

```js
const fs = require('node:fs');
const path = require('node:path');

// Keep runtime assets beside the compiled classes. Production needs only dist/ and dependencies.
fs.cpSync('src', 'dist', {
    recursive: true,
    filter: file => fs.statSync(file).isDirectory() || ['.css', '.html'].includes(path.extname(file)),
});
```

### test/network.cjs

```js
const assert = require('node:assert/strict');
const { once } = require('node:events');
const WebSocket = require('ws');
const { createApp } = require('../dist/app.js');

async function listen(t) {
    const app = createApp({ port: 0, bind: '127.0.0.1', logger: null });
    t.after(() => app.shutdown());
    if (!app.server.listening) await once(app.server, 'listening');
    return `http://127.0.0.1:${app.server.address().port}`;
}

async function connect(t, url, origin, headers = {}) {
    const socket = new WebSocket(url, { headers: { ...headers, Origin: origin } });
    const messages = [];
    socket.on('message', raw => messages.push(JSON.parse(raw.toString())));
    t.after(async () => {
        if (socket.readyState === WebSocket.CLOSED) return;
        const closed = once(socket, 'close');
        // Cleanup must not depend on a peer completing the closing handshake.
        // Tests of graceful disconnect explicitly close and await their sockets.
        socket.terminate();
        await closed;
    });
    await once(socket, 'open');
    return {
        socket,
        send: message => socket.send(JSON.stringify(message)),
        async receive(predicate) {
            const deadline = Date.now() + 3000;
            while (Date.now() < deadline) {
                const index = messages.findIndex(predicate);
                if (index !== -1) return messages.splice(index, 1)[0];
                await new Promise(resolve => setTimeout(resolve, 10));
            }
            assert.fail(`Timed out waiting for a socket message; received ${JSON.stringify(messages)}`);
        },
    };
}

async function live(t, origin, headers = {}) {
    const response = await fetch(origin, { headers });
    assert.equal(response.status, 200);
    const document = await response.text();
    const config = JSON.parse(document.match(/id="__redweb_page">([^<]+)</)[1]);
    const connection = await connect(t, `${origin.replace('http:', 'ws:')}${config.socketPath}?pageId=${config.pageId}&redwebVersion=${encodeURIComponent(config.version)}`, origin, headers);
    return {
        ...connection,
        document, config,
        patch: predicate => connection.receive(message => message.type === 'redweb:patch' && message.payload.patches.some(predicate)),
        action: (name, args = [], component) => connection.send({
            v: config.version, type: 'redweb:html', payload: { kind: 'action', name, args, component },
        }),
        state: (name, value, component) => connection.receive(message => message.type === 'redweb:state' &&
            message.payload.name === name && message.payload.component === component && value(message.payload.value)),
    };
}

module.exports = { listen, connect, live };
```

### test/app.test.cjs

```js
const test = require('node:test');
const assert = require('node:assert/strict');
const net = require('node:net');
const { once } = require('node:events');
const WebSocket = require('ws');
const { SocketRoute } = require('redweb');
const { createApp, Hello } = require('../dist/app.js');
const { listen, connect } = require('./network.cjs');

test('an absent PORT binds the documented default or reports that exact port occupied', { timeout: 10000 }, async () => {
    const { spawnSync } = require('node:child_process');
    const env = { ...process.env };
    delete env.PORT;
    const result = spawnSync(process.execPath, ['-e', `
        const assert = require('node:assert/strict');
        const { once } = require('node:events');
        const WebSocket = require('ws');
        const { createApp } = require('./dist/app.js');
        (async () => {
            const app = createApp();
            let socket;
            try {
                try { if (!app.server.listening) await once(app.server, 'listening'); }
                catch (error) {
                    assert.equal(error.code, 'EADDRINUSE');
                    assert.equal(error.port, 8181);
                    return; // Never send test traffic to a listener this test does not own.
                }
                assert.equal(app.server.address().port, 8181);
                const response = await fetch('http://127.0.0.1:8181/health', { signal: AbortSignal.timeout(3000) });
                assert.deepEqual(await response.json(), { ok: true });
                socket = new WebSocket('ws://127.0.0.1:8181/chat', { handshakeTimeout: 3000 });
                await once(socket, 'open');
                const reply = once(socket, 'message');
                socket.send(JSON.stringify({ type: 'hello' }));
                assert.equal(JSON.parse((await reply)[0].toString()).type, 'hello');
            } finally { socket?.terminate(); await app.shutdown(); }
        })().catch(error => { console.error(error); process.exitCode = 1; });
    `], { env, encoding: 'utf8', timeout: 7000, windowsHide: true });
    assert.equal(result.error, undefined);
    assert.equal(result.status, 0, result.stdout + result.stderr);
});

test('HTTP and separate message handlers share one port, with strict socket paths', { timeout: 10000 }, async t => {
    const origin = await listen(t);
    const response = await fetch(`${origin}/health`, { signal: AbortSignal.timeout(3000) });
    assert.equal(response.status, 200);
    assert.deepEqual(await response.json(), { ok: true });
    assert.equal((await fetch(`${origin}/missing`, { signal: AbortSignal.timeout(3000) })).status, 404);
    for (let index = 0; index < 2; index++) {
        const client = await connect(t, `${origin.replace('http:', 'ws:')}/chat`, origin);
        client.send({ type: 'hello' });
        assert.deepEqual(await client.receive(message => message.type === 'hello'),
            { type: 'hello', message: 'Hello from the server!' });
    }
    const unknown = new WebSocket(`${origin.replace('http:', 'ws:')}/missing`, { handshakeTimeout: 3000 });
    t.after(() => unknown.terminate());
    await once(unknown, 'error');
});

for (const failingRoute of [false, true]) {
    test(`shutdown closes incomplete HTTP peers${failingRoute ? ' despite a route failure' : ' idempotently'}`, { timeout: 10000 }, async t => {
        const app = createApp({ port: 0, logger: null });
        t.after(() => app.shutdown().catch(() => {}));
        if (!app.server.listening) await once(app.server, 'listening');
        assert.equal(app.closeServerOnShutdown, true);
        const failure = new Error('Application cleanup failed');
        if (failingRoute) {
            class FailingRoute extends SocketRoute {
                constructor() { super({ path: '/fails', handlers: [Hello] }); }
                async shutdown() { await super.shutdown(); throw failure; }
            }
            app.addRoute(FailingRoute);
        }
        const accepted = once(app.server, 'connection');
        const peer = net.connect(app.server.address().port, '127.0.0.1');
        t.after(() => peer.destroy());
        peer.on('error', () => {});
        await once(peer, 'connect');
        const [serverPeer] = await accepted;
        peer.write('POST /health HTTP/1.1\r\nHost: localhost\r\nContent-Length: 100\r\n\r\nx');
        const closed = once(serverPeer, 'close');
        const shutdown = app.shutdown();
        assert.equal(app.shutdown(), shutdown);
        if (failingRoute) await assert.rejects(shutdown, error => error.errors.length === 1 && error.errors[0] === failure);
        else await shutdown;
        await closed;
        assert.equal(serverPeer.destroyed, true);
        assert.equal(app.server.listening, false);
        assert.equal(app.server.listenerCount('upgrade'), 0);
    });
}
```

### test/run-app.test.cjs

```js
const assert = require('node:assert/strict');
const { test } = require('node:test');
const { spawn } = require('node:child_process');

// Each case uses its own Node process, real HTTP/TCP/WS resources and real timers.
// Windows cannot deliver POSIX signals through child.kill, so only that platform
// explicitly emits the signal event inside the child. Linux uses real OS signals.
const fixture = String.raw`
const assert = require('node:assert/strict');
const http = require('node:http');
const net = require('node:net');
const { once } = require('node:events');
const WebSocket = require('ws');
const mode = process.argv[1];
const signals = ['SIGINT', 'SIGTERM'];
const initial = signals.map(signal => process.listenerCount(signal));
const { runApp } = require('./dist/run-app.js');
assert.deepEqual(signals.map(signal => process.listenerCount(signal)), initial);
require('./dist/app.js');
assert.deepEqual(signals.map(signal => process.listenerCount(signal)), initial);
let cleanups = 0;
process.once('beforeExit', () => console.log(JSON.stringify({ cleanups, signals: signals.map(signal => process.listenerCount(signal)), initial })));
const signal = name => process.platform === 'win32' ? process.emit(name) : process.kill(process.pid, name);
if (mode === 'invalid') {
    for (const value of [0, -1, NaN, Infinity, 1.5, 2147483648]) assert.throws(() => runApp(() => { throw Error('must not execute'); }, value), RangeError);
} else if (mode === 'factory') {
    assert.equal(runApp(() => { throw Error('private startup detail'); }), undefined);
} else {
    if (mode === 'preserve') process.exitCode = '7';
    const server = http.createServer((_request, response) => response.end('ready'));
    const wss = new WebSocket.Server({ server });
    wss.on('error', () => {}); // The HTTP listener error is owned by runApp.
    const peers = new Set();
    server.on('connection', peer => { peers.add(peer); peer.on('close', () => peers.delete(peer)); });
    const close = async () => {
        for (const peer of peers) peer.destroy();
        for (const peer of wss.clients) peer.terminate();
        await new Promise(resolve => wss.close(resolve));
        await new Promise(resolve => server.close(resolve));
    };
    const app = runApp(() => ({ server, shutdown() {
        cleanups++;
        console.log('cleanup-started');
        if (mode === 'throw') { void close(); throw Error('private cleanup detail'); }
        if (mode === 'reject-open') return Promise.reject(Error('private cleanup detail'));
        return close().then(async () => {
            if (mode === 'hung') return new Promise(() => {});
            if (mode === 'reject') throw Error('private cleanup detail');
            if (mode === 'repeat') {
                signal('SIGINT'); signal('SIGTERM');
                server.emit('error', Error('private listener detail'));
            }
            await new Promise(resolve => setTimeout(resolve, 20));
        });
    } }), 200);
    assert.equal(app.server, server);
    (async () => {
        if (mode === 'occupied') {
            const other = http.createServer();
            await new Promise(resolve => other.listen(0, '127.0.0.1', resolve));
            server.once('error', () => other.close());
            server.listen(other.address().port, '127.0.0.1');
            return;
        }
        await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
        const port = server.address().port;
        const response = await fetch('http://127.0.0.1:' + port);
        assert.equal(await response.text(), 'ready');
        const peer = net.connect(port, '127.0.0.1');
        peer.on('error', () => {});
        await once(peer, 'connect');
        peer.write('GET / HTTP/1.1\r\nHost: localhost\r\n');
        const socket = new WebSocket('ws://127.0.0.1:' + port);
        socket.on('error', () => {});
        await once(socket, 'open');
        if (mode === 'native-close') {
            for (const connection of peers) connection.destroy();
            server.close();
            return;
        }
        // A partial HTTP peer otherwise prevents native close; application cleanup
        // begins via the signal and the later native close must not end its timer.
        signal(mode === 'interrupt' ? 'SIGINT' : 'SIGTERM');
    })().catch(error => { console.error(error); process.exit(99); });
}
`;

function execute(mode, t, args = ['-e', fixture, mode], env = process.env) {
    return new Promise((resolve, reject) => {
        const child = spawn(process.execPath, args, { cwd: process.cwd(), env, windowsHide: true });
        let stdout = '', stderr = '';
        let timedOut = false, finished = false;
        const closed = new Promise(resolve => child.once('close', () => { finished = true; resolve(); }));
        const deadline = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, 5000);
        t.after(async () => {
            clearTimeout(deadline);
            if (!finished) { child.kill('SIGKILL'); await closed; }
        });
        child.stdout.on('data', data => { stdout += data; });
        child.stderr.on('data', data => { stderr += data; });
        child.once('error', reject);
        child.once('close', (code, signal) => {
            clearTimeout(deadline);
            if (timedOut) reject(new Error(`Lifecycle child timed out: ${mode}\n${stdout}\n${stderr}`));
            else resolve({ code, signal, stdout, stderr });
        });
    });
}

test('the actual application entrypoint exits cleanly when its port is occupied', { timeout: 7000 }, async t => {
    const net = require('node:net');
    const { once } = require('node:events');
    const fs = require('node:fs');
    const path = require('node:path');
    const directory = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'redweb-entrypoint-'));
    const occupied = net.createServer(socket => socket.destroy());
    const loopback = net.createServer(socket => socket.destroy());
    let failure;
    try {
        occupied.listen(0, '0.0.0.0');
        await once(occupied, 'listening');
        // Windows permits distinct wildcard/loopback binds on the same port.
        // Hold both addresses; Unix may already reject the second bind.
        loopback.listen(occupied.address().port, '127.0.0.1');
        try { await once(loopback, 'listening'); }
        catch (error) { assert.equal(error.code, 'EADDRINUSE'); }
        const env = { ...process.env, PORT: String(occupied.address().port), NODE_ENV: 'test', DASHBOARD_DATABASE: path.join(directory, 'test.sqlite') };
        delete env.DASHBOARD_ORIGIN;
        const result = await execute('actual-entrypoint', t, ['dist/app.js'], env);
        assert.equal(result.code, 1, `${result.stdout}\n${result.stderr}`);
        assert.equal(result.signal, null);
        assert.match(result.stderr, /Application listener failed/);
    } catch (error) { failure = error; }
    const cleanup = await Promise.allSettled([
        ...[occupied, loopback].map(server => new Promise((resolve, reject) => server.close(error =>
            error && error.code !== 'ERR_SERVER_NOT_RUNNING' ? reject(error) : resolve()))),
        fs.promises.rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),
    ]);
    const failures = [...(failure ? [failure] : []), ...cleanup.filter(result => result.status === 'rejected').map(result => result.reason)];
    if (failures.length) throw new AggregateError(failures, 'Entrypoint verification or cleanup failed');
});

for (const mode of ['normal', 'interrupt', 'native-close', 'invalid', 'factory', 'throw', 'reject', 'reject-open', 'hung', 'occupied', 'repeat', 'preserve']) {
    test(`entrypoint cleanup: ${mode}`, { timeout: 7000 }, async t => {
        const result = await execute(mode, t);
        const expected = ['normal', 'interrupt', 'native-close', 'invalid'].includes(mode) ? 0 : mode === 'preserve' ? 7 : 1;
        assert.equal(result.code, expected, `${result.stdout}\n${result.stderr}`);
        assert.equal(result.signal, null);
        assert.doesNotMatch(result.stderr, /private .* detail/);
        const noApp = ['invalid', 'factory'].includes(mode);
        assert.equal((result.stdout.match(/cleanup-started/g) || []).length, noApp ? 0 : 1);
        if (['hung', 'reject-open'].includes(mode)) assert.match(result.stderr, /exceeded its deadline/);
        if (['normal', 'interrupt', 'native-close', 'invalid', 'factory', 'preserve'].includes(mode)) {
            const snapshot = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));
            assert.deepEqual(snapshot.signals, snapshot.initial);
        }
    });
}
```

### README.md

````md
# Your Redweb application

Requirements: Node.js 18 or newer and npm for the realtime, chat, site, socket and http-ws templates; the dashboard template requires Node.js 22.13+ for native SQLite. Use a currently supported Node.js release in production.

For an unreleased checkout or tarball, first run `npm install --save-exact TARBALL`, replacing `TARBALL` with the absolute path to the same tested Redweb tarball used to generate this app (quote paths containing spaces). This installs the matching package and its published client dependency. Do not substitute an older registry release or `latest`. Published Redweb releases can use the installation command below directly.

```sh
npm install
npm test
npm run dev
```

HTTP starters open at http://localhost:8181; the authenticated dashboard uses http://127.0.0.1:8181/login and requires account provisioning described below. Set the `PORT` environment variable to change the listener.
`npm test` builds and runs real HTTP/WebSocket integration tests on an ephemeral loopback port. No mocks or external service are needed.
`npm run test:coverage` runs the same tests with application coverage mapped back to TypeScript. Reports are written to the ignored `coverage/` directory; this is separate from Redweb library coverage. TypeScript-generated decorator accessors can appear in function counts even when the framework does not call them. The report exposes remaining gaps; it does not certify complete application coverage. Source maps are generated during the build for diagnostics and coverage, but no coverage collector is loaded by `npm start`.

## Development and production

Edit `src/app.tsx`. `npm run dev` watches TypeScript, TSX, CSS, HTML, and the root TypeScript configuration,
then rebuilds and restarts the server. A type error stops startup until you fix it. On direct localhost access,
HTML pages refresh automatically when a new server revision is ready. If edits were detected, a keyboard-accessible
notice keeps the old document until you choose **Reload and discard drafts**. This is a conservative edit guard,
not autosave or browser hot-module replacement: restarts reset in-memory state and old socket sessions.
The generated development command sets `REDWEB_DEV_REFRESH=1`; `development: { refresh: false }` overrides it.
The refresh feature is refused under `NODE_ENV=production`, applies only to served HTML (not raw sockets or static exports),
and creates no local/session-storage copy of form contents. Use direct `localhost`, `127.x.x.x`, or `[::1]` access;
custom hostnames, tunnels and proxy-forwarded origins are not supported by this development helper.
`npm run build` checks types and copies CSS/HTML beside the compiled classes in `dist/`.
Run `npm start` to serve the compiled app. For deployment, build first, ship `dist/`, `package.json`, and the lockfile,
then install runtime dependencies with `npm ci --omit=dev`. The application does not require TypeScript or `src/` at runtime.

The standalone entrypoint calls the shared `runApp(createApp)` helper. Importing either module starts no listener and installs no process handlers. On SIGINT/SIGTERM, a listener error, or native listener closure, the helper calls application shutdown once. Repeated signals do not bypass cleanup. The five-second outer deadline covers the whole application, including database/worker cleanup after HTTP closes; customize it with the helper's second argument if necessary. Cleanup must resolve only after resources are released. A failed cleanup sets a failure exit status and retains a deadline for any surviving handles; the helper never resets an existing failure status. If cleanup does not finish in time, the entrypoint terminates the process with a failure status. This cannot preempt synchronous code blocking Node's event loop and does not make in-memory state durable. Factory functions remain responsible for releasing partially constructed resources before throwing.

The shipped lifecycle tests exercise actual processes, HTTP/TCP/WebSocket peers and timers. Linux uses actual OS signals; Windows tests explicitly emit signal events inside the process because killing a Windows child does not exercise graceful POSIX signal delivery. This is not a claim that Windows console/service managers forward the same signals. Deploy with a supervisor that forwards the supported termination signal and allows longer than the configured cleanup deadline.

For public deployment, configure HTTPS/WSS at your Node server or reverse proxy, authentication, trusted origins,
and application-specific rate limits. These starters are demonstrations, not a hosted identity or database service.
Never commit secrets; `.env` is ignored but is not loaded automatically.

`npx --no-install redweb doctor --json` reports configuration problems without changing your files.

## HTTP and WebSockets on one listener

One Node server answers ordinary HTTP requests and upgrades `/chat` connections to WebSockets. HTTP paths select Express services; a socket URL selects a route and each message's `type` selects a handler. No socket decorators or secondary `message.action` dispatcher are needed.

After starting the application, request `http://127.0.0.1:8181/health` to receive `{"ok":true}`. Connect a WebSocket to `ws://127.0.0.1:8181/chat` and send `{"type":"hello"}` to receive `{"type":"hello","message":"Hello from the server!"}`. This is a raw JSON socket example, not a chatroom UI or the versioned socket-contract protocol. Use the chat or socket starter for those applications.

The HTTP builder does not bind a port. The socket service explicitly takes responsibility for listening and closing the supplied server with `listen: true` and `closeServerOnShutdown: true`. Call the returned application's `shutdown()`; it processes route failures and still closes its HTTP/TCP peers. Do not separately close the HTTP builder. Importing this module creates no listener; the standalone entrypoint uses the same bounded `runApp` helper as the other starters.

`/health` reports liveness, not readiness or completed application work. Loopback binding is intentional. Before exposing the service, choose your deployment bind address, configure HTTPS/WSS, trusted origins, authentication, authorization, payload/connection limits, and any persistence you need. Shared listeners do not automatically provide these policies. Shutdown may force connections closed; it does not guarantee message delivery or durable work.

`npm test` runs real HTTP and WebSocket requests on ephemeral ports, checks strict socket routing and multiple clients, verifies idempotent cleanup with an incomplete HTTP peer, and proves a failing route cleanup still closes the listener. It also runs the shared process-lifecycle suite. No mocks are used. The package verification gate repeats the tests against the compiled application with `src/` unavailable.
````

### .gitignore

```text
node_modules/
dist/
coverage/
.env
data/
*.sqlite
*.sqlite-wal
*.sqlite-shm
```
