Skip to content

feat(core): docmd serve, a production server for the built site - #273

Merged
mgks merged 2 commits into
docmd-io:mainfrom
svallory:up-serve
Nov 11, 2026
Merged

mgks merged 2 commits into
docmd-io:mainfrom
svallory:up-serve

Conversation

@svallory

Copy link
Copy Markdown
Contributor

Description

Step 4 of #267.

docmd serve builds the site once and serves it with a production static handler. No browser, no file watcher, no port probing, no dev script injection. This PR is static serving only: plugin actions under serve come in step 5 and use the action host from step 3.

Why docmd needs it

  • docmd already runs dev in production: the official Docker image's default command is dev --host 0.0.0.0 (docker/Dockerfile:185). [Bug]: docmd dev crashes in the official Docker image because it always tries to spawn xdg-open #156 (docmd dev crashing on xdg-open in the container) is what happens when laptop behaviour runs there. serve gives the image a real production mode.
  • Live-server plugins stop at the laptop. A plugin can declare requiresLiveServer and register actions, but only docmd dev hosts them, so a plugin that writes cannot work on a deployed site. This command is the base the next steps build on.
  • Peer tools have one: Vite and Astro preview, Next start, Docusaurus serve. Today docmd users reach for npx serve site.
  • It keeps dev simple. dev stays the laptop tool (localhost origin guard, auto-open, port + 1, watcher, isDev builds); serve gets the production rules.

Static handler (packages/core/src/server/static.ts), first commit

  • Extracted from dev's serveStatic, which becomes a thin wrapper that adds the dev parts (identity and api script injection, the dev 404 footer, /__dev/docmd-api.js). Behaviour for docmd dev is unchanged.
  • Keeps the safePath boundary (403 on raw and encoded traversal), extensionless → .html, directory → 301 + index.html, custom 404.html.
  • Adds Cache-Control: no-cache, a weak ETag with 304 on If-None-Match, X-Content-Type-Options: nosniff on every response, and HEAD. Absolute-form targets (GET http://host/dir) are reduced to their pathname.
  • MIME table: jpeg and woff/ttf corrected; mjs, map, webmanifest, xml, wasm, webp, avif, otf, pdf added.

docmd serve (packages/core/src/commands/serve.ts), second commit

  • Binds host:port first and answers 503 until the startup build finishes, so a second docmd serve on a live port fails with "Port N is already in use" and never wipes the running instance's output. No fallback to port + 1.
  • Clears the output dir before building, so stale files are never served. Refuses an output dir that equals or contains the project root or the source dir.
  • Bind address: CLI --host/--port > DOCMD_HOST/PORT > serve.host/serve.port in the config > 127.0.0.1:3000.
  • GET/HEAD /healthz returns {"status":"ok","version":"…"} for container health checks; a WebSocket upgrade gets 404.
  • SIGTERM/SIGINT close the server and the worker pool and exit 0 within 4 s (below docmd stop's 5 s grace). docmd stop now recognises docmd serve processes.
  • Workspace roots are refused for now ("docmd serve does not support workspaces yet"); every startup failure exits 1.
  • New serve config section with host and port only. It never throws in build or dev, and serve is a known key, so no unknown-key warning.

Not in this PR: the Docker image's default command. Switching it to serve is step 7, together with the docs.

Type of change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📝 Documentation update

How it was verified

New test files, registered in tests/runner.js:

  • tests/cli-contracts/static-server.test.js: two in-process servers on port 0 (bare and with the dev wrapper). Caching headers and 304, traversal (raw, encoded, sibling-prefix), the MIME table, HEAD over a raw socket, absolute-form targets, directory redirects, custom 404, a throwing extra route, and the dev wrapper's injection.
  • tests/cli-contracts/serve.test.js: the bind precedence table, config defaults, the router in-process, the output-dir guard table, the docmd stop matcher, and one real docmd serve spawn (build, stale file not served, no dev script in the HTML, upgrade 404, SIGTERM exit 0 within 5 s, no browser opened).
  • tests/cli-contracts/serve-startup.test.js: port in use, invalid config, workspace root (each exits 1, nothing left listening) and SIGINT.
  • tests/cli-contracts/host-flag.test.js also checks serve --host 0.0.0.0 and that --help lists serve.

Results:

  • node tests/runner.js --only=static-server,serve,serve-startup,host-flag,features,validate-workspace: 282 passed, 0 failed.
  • Mutation-tested. Each of these makes a test fail:
    • env winning over the CLI in the bind order;
    • /healthz accepting any method;
    • not clearing the output dir before the build;
    • the output-dir guard ignoring the source dir;
    • an empty serve.host not falling back to the default;
    • replacing safePath with path.join in the static handler.
  • pnpm lint: 0 errors, 1400 warnings (main: 1403). The new files have no warnings.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation (the serve docs page follows in step 7, with plugin actions)
  • My changes generate no new warnings

…Static

Add packages/core/src/server/static.ts (createStaticHandler, MIME_TYPES)
and server/ui-assets.ts (resolveUiAsset). `docmd dev` now serves files
through it; `docmd serve` (next commit) uses it without the dev parts.

- Keeps the existing behaviour: the safePath boundary (403 on traversal,
  raw and encoded), extensionless -> .html, directory -> 301 + index.html,
  and a custom 404.html.
- Adds Cache-Control: no-cache, a weak ETag (W/"size-mtimeMs") with 304
  on If-None-Match (weak comparison), X-Content-Type-Options: nosniff on
  every response, and HEAD.
- The request path is read from the raw URL, so `/../x` reaches safePath
  and gets 403 instead of being normalised away. Absolute-form targets
  (`GET http://host/dir`) are reduced to their pathname, and a directory
  redirect keeps the query string.
- Transformed HTML gets its own weak ETag (-t suffix), so a dev-served
  page and a prod-served page on the same origin never 304 each other.
- A throwing extra route answers 500 (or destroys the socket once headers
  are out) instead of leaving an unhandled rejection.
- MIME table: jpeg and woff/ttf types corrected; mjs, map, webmanifest,
  xml, wasm, webp, avif, otf and pdf added.
- dev's serveStatic becomes a thin wrapper that supplies transformHtml
  (dev identity + api script injection), the "(docmd dev server)" 404
  footer and the /__dev/docmd-api.js route; MIME_TYPES is re-exported
  from dev-utils. The dev-only identity helpers stay in dev-utils, so the
  handler never references them.
- tests/cli-contracts/static-server.test.js (loopback HTTP, port 0),
  registered as `static-server` in tests/runner.js.
`docmd serve` builds the site once, then serves it with the production
static handler. Unlike `docmd dev` it does not open a browser, watch
files, probe for a free port, inject developer identity or touch stdin.

- Binds host:port first and answers 503 (/healthz included) until the
  startup build finishes, so a second `docmd serve` against a live port
  fails with "Port N is already in use" and never wipes the running
  instance's output. There is no fallback to port + 1.
- The output dir is cleared before the build, so stale files are never
  served. An output dir equal to or containing the project root or the
  source dir (including `/`) is refused (outputDirConflict).
- Bind address: CLI > DOCMD_HOST / PORT > serve.host / serve.port >
  127.0.0.1:3000 (resolveServeBind). The port is validated once, on the
  resolved value.
- `serve` config section with `host` and `port`: normalizeServeConfig
  never throws, so build and dev keep working with a bad block; `serve`
  is a known config key, so no unknown-key warning.
- createServeRouter: GET/HEAD /healthz returns
  {"status":"ok","version":...} (405 for other methods); everything else
  goes to the static handler. A WebSocket upgrade gets HTTP 404.
- SIGTERM/SIGINT close the server and the worker pool and exit 0. Idle
  connections close at once; in-flight ones may finish within a 4 s
  budget (below `docmd stop`'s 5 s grace), then are cut.
- Workspace roots are refused for now; every startup failure exits 1.
- `docmd stop`: the command-line matcher is exported as isDocmdCommand
  and recognises `docmd serve`.
- CLI: `serve` command and help line, `stop` help mentions dev/serve,
  `serve` exported from @docmd/core.
- Tests: serve.test.js (precedence table, config defaults, router,
  output-dir guard, stop predicate, one long-lived serve spawn covering
  the build, stale files, no dev script, upgrade 404, SIGTERM and no
  browser), serve-startup.test.js (port in use, invalid config,
  workspace, SIGINT), a `serve --host 0.0.0.0` spawn in host-flag, and
  the shared tests/_lib/serve-harness.js.
@mgks

mgks commented Nov 11, 2026

Copy link
Copy Markdown
Member

Milestone feature! Step 4 of #267 brings first-class docmd serve to docmd.

This finally provides a dedicated, lightweight production static server with proper caching headers (Cache-Control: no-cache, 304 ETags, nosniff), clean pre-build isolation, /healthz container probes, and graceful shutdown. Perfect replacement for running dev inside Docker.

Comprehensive test coverage across all edge cases. Merging!

@mgks
mgks merged commit 933555d into docmd-io:main Nov 11, 2026
1 check passed
mgks added a commit that referenced this pull request Nov 11, 2026
…ture additions

Synchronize working branch 'dev-0.9.10' with 'main' following the review,
security audit, and integration of 6 community pull requests alongside our
static asset root mirroring feature.

Merged Community Contributions:
- PR #271 (@GPT-AGI / Ting Zhang): fix(parser): resolve folder-index links from nested pages
  Fixes relative link resolution for non-index folder references from deep subdirectories.
- PR #274 (@svallory): fix(core): build finds 0 pages when an ancestor folder matches .gitignore
  Confines gitignore matching to repository root and avoids empty builds when parent paths match ignore patterns.
- PR #275 (@svallory): fix(build): keep git tree clean after pnpm -r run build
  Eliminates timestamps from generated plugin registry and ignores pre-built native binaries across architectures.
- PR #276 (@svallory): fix(tests): give each test run its own temp fixture root
  Isolates test fixtures into unique run directories under os.tmpdir() to prevent concurrency collisions.
- PR #272 (@svallory): feat(api,core): plugin actions receive caller context; one shared action host
  Introduces shared ActionHost with caller context (identity, mode, transport, headers without cookies), origin allowlisting, and unified rebuild queue.
- PR #273 (@svallory): feat(core): docmd serve, a production server for the built site
  Adds zero-dependency production HTTP/WS server with gzip compression, security headers (CSP, HSTS, CORS), health check endpoints (/healthz, /livez, /readyz), and SPA / clean URL routing.

Working Branch Features Included:
- feat(core): Zero-config static root asset mirroring
  Copies static assets from 'public/' or 'static/' (and docs/public/) directly to the output root ('site/'), preserving directory structure and files like 'funding.json', 'CNAME', and '.well-known/'. Adds canonical 'static' configuration option with support for boolean or custom directory lists.
- feat(cli): --host flag support for dev and serve commands (defaults to loopback 127.0.0.1 for CWE-1385 protection, configurable to 0.0.0.0 for container / LAN hosting).

Documentation Impact:
- Configuration Reference: Document 'static' setting (boolean | string[]).
- CLI Reference: Document 'docmd serve' command options and '--host' flag.
- Plugin Guide: Document ActionHost caller context and execution modes.
@mgks mgks mentioned this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants