{"vulnerability": "cve-2024-51999", "sightings": [{"uuid": "0e7a2dbd-7005-4629-81ae-2e3bf1db1ece", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2024-51999", "type": "seen", "source": "https://bsky.app/profile/ulisesgascon.com/post/3m6wufigsy22l", "content": "", "creation_timestamp": "2025-12-01T16:37:07.673979Z"}, {"uuid": "e49efdfd-bbe3-4e55-abc1-af4d7f365e6a", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2024-51999", "type": "seen", "source": "https://bsky.app/profile/ulisesgascon.com/post/3m6wuhn4oz22l", "content": "", "creation_timestamp": "2025-12-01T16:38:20.125005Z"}, {"uuid": "9c415b4d-1151-44b6-838d-fb757582739e", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2024-51999", "type": "seen", "source": "https://bsky.app/profile/azu.bsky.social/post/3m6yrhzgjv42k", "content": "", "creation_timestamp": "2025-12-02T10:50:09.149106Z"}, {"uuid": "5ea8262b-8669-4d09-9682-b790cef8d23c", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2024-51999", "type": "seen", "source": "https://gist.github.com/Adcbda/3e82259b6deb6a426fbb5c89ed5ded87", "content": "\n\n\n\n\nexpress \u2014 Wiki\n\n\n\n\n*{margin:0;padding:0;box-sizing:border-box}\n:root{\n  --bg:#ffffff;--sidebar-bg:#f8f9fb;--border:#e5e7eb;\n  --text:#1e293b;--text-muted:#64748b;--primary:#2563eb;\n  --primary-soft:#eff6ff;--hover:#f1f5f9;--code-bg:#f1f5f9;\n  --radius:8px;--shadow:0 1px 3px rgba(0,0,0,.08);\n}\nbody{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;\n  line-height:1.65;color:var(--text);background:var(--bg)}\n\n.layout{display:flex;min-height:100vh}\n.sidebar{width:280px;background:var(--sidebar-bg);border-right:1px solid var(--border);\n  position:fixed;top:0;left:0;bottom:0;overflow-y:auto;padding:24px 16px;\n  display:flex;flex-direction:column;z-index:10}\n.content{margin-left:280px;flex:1;padding:48px 64px;max-width:960px}\n\n.sidebar-header{margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid var(--border)}\n.sidebar-title{font-size:16px;font-weight:700;color:var(--text);display:flex;align-items:center;gap:8px}\n.sidebar-title svg{flex-shrink:0}\n.sidebar-meta{font-size:11px;color:var(--text-muted);margin-top:6px}\n.nav-section{margin-bottom:2px}\n.nav-item{display:block;padding:7px 12px;border-radius:var(--radius);cursor:pointer;\n  font-size:13px;color:var(--text);text-decoration:none;transition:all .15s;\n  white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.nav-item:hover{background:var(--hover)}\n.nav-item.active{background:var(--primary-soft);color:var(--primary);font-weight:600}\n.nav-item.overview{font-weight:600;margin-bottom:4px}\n.nav-children{padding-left:14px;border-left:1px solid var(--border);margin-left:12px}\n.nav-group-label{font-size:11px;font-weight:600;color:var(--text-muted);\n  text-transform:uppercase;letter-spacing:.5px;padding:12px 12px 4px;user-select:none}\n.sidebar-footer{margin-top:auto;padding-top:16px;border-top:1px solid var(--border);\n  font-size:11px;color:var(--text-muted);text-align:center}\n\n.content h1{font-size:28px;font-weight:700;margin-bottom:8px;line-height:1.3}\n.content h2{font-size:22px;font-weight:600;margin:32px 0 12px;padding-bottom:6px;border-bottom:1px solid var(--border)}\n.content h3{font-size:17px;font-weight:600;margin:24px 0 8px}\n.content h4{font-size:15px;font-weight:600;margin:20px 0 6px}\n.content p{margin:12px 0}\n.content ul,.content ol{margin:12px 0 12px 24px}\n.content li{margin:4px 0}\n.content a{color:var(--primary);text-decoration:none}\n.content a:hover{text-decoration:underline}\n.content blockquote{border-left:3px solid var(--primary);padding:8px 16px;margin:16px 0;\n  background:var(--primary-soft);border-radius:0 var(--radius) var(--radius) 0;\n  color:var(--text-muted);font-size:14px}\n.content code{font-family:'SF Mono',Consolas,'Courier New',monospace;font-size:13px;\n  background:var(--code-bg);padding:2px 6px;border-radius:4px}\n.content pre{background:#1e293b;color:#e2e8f0;border-radius:var(--radius);padding:16px;\n  overflow-x:auto;margin:16px 0}\n.content pre code{background:none;padding:0;font-size:13px;line-height:1.6;color:inherit}\n.content table{border-collapse:collapse;width:100%;margin:16px 0}\n.content th,.content td{border:1px solid var(--border);padding:8px 12px;text-align:left;font-size:14px}\n.content th{background:var(--sidebar-bg);font-weight:600}\n.content img{max-width:100%;border-radius:var(--radius)}\n.content hr{border:none;border-top:1px solid var(--border);margin:32px 0}\n.content .mermaid{margin:20px 0;text-align:center}\n\n.menu-toggle{display:none;position:fixed;top:12px;left:12px;z-index:20;\n  background:var(--bg);border:1px solid var(--border);border-radius:var(--radius);\n  padding:8px 12px;cursor:pointer;font-size:18px;box-shadow:var(--shadow)}\n@media(max-width:768px){\n  .sidebar{transform:translateX(-100%);transition:transform .2s}\n  .sidebar.open{transform:translateX(0);box-shadow:2px 0 12px rgba(0,0,0,.1)}\n  .content{margin-left:0;padding:24px 20px;padding-top:56px}\n  .menu-toggle{display:block}\n}\n.empty-state{text-align:center;padding:80px 20px;color:var(--text-muted)}\n.empty-state h2{font-size:20px;margin-bottom:8px;border:none}\n\n\n\n\n&#9776;\n\n\n\n\n\n\n\n\n\nexpress\n\n\n\n\n\n\n\nGenerated by GitNexus\n\n\n\n\n\nLoading\u2026\n\n\n\nvar PAGES = {\"authentication-sessions\":\"# Authentication &amp; Sessions\\n\\n# Authentication &amp; Sessions Module\\n\\nThis module provides example implementations for authentication and session management in Express applications. It demonstrates multiple approaches: password-based authentication with sessions, cookie-based sessions, and Redis-backed session storage.\\n\\n## Architecture Overview\\n\\n```mermaid\\ngraph TD\\n    A[Client Request] --&gt; B{Session Exists?}\\n    B --&gt;|No| C[Create Session]\\n    B --&gt;|Yes| D[Load Session Data]\\n    C --&gt; E[Route Handler]\\n    D --&gt; E\\n    E --&gt; F{Protected Route?}\\n    F --&gt;|Yes| G[restrict Middleware]\\n    G --&gt; H{Authenticated?}\\n    H --&gt;|No| I[Redirect to Login]\\n    H --&gt;|Yes| J[Process Request]\\n    F --&gt;|No| J\\n```\\n\\n## Core Components\\n\\n### Authentication Example (`examples/auth/`)\\n\\nA complete username/password authentication system with session persistence.\\n\\n#### Key Functions\\n\\n**`authenticate(name, pass, fn)`**\\n\\nValidates user credentials against the in-memory user store.\\n\\n- **Parameters:**\\n  - `name` - Username to authenticate\\n  - `pass` - Plaintext password\\n  - `fn` - Callback `(err, user)` where `user` is `null` on failure\\n- **Behavior:** Retrieves the user by name, then hashes the submitted password with the stored salt. Compares the result against the stored hash.\\n\\n**`restrict(req, res, next)`**\\n\\nMiddleware that protects routes from unauthenticated access.\\n\\n- Sets `req.session.error` and redirects to `/login` if no `req.session.user` exists\\n- Calls `next()` when authentication is present\\n\\n#### Authentication Flow\\n\\n1. **POST /login** receives credentials via `req.body.username` and `req.body.password`\\n2. `authenticate()` verifies credentials using PBKDF2 password hashing\\n3. On success, `req.session.regenerate()` creates a new session (prevents session fixation)\\n4. User object stored in `req.session.user`\\n5. Subsequent requests check `req.session.user` via `restrict` middleware\\n\\n#### Session Configuration\\n\\n```javascript\\napp.use(session({\\n  resave: false,           // Skip saving unmodified sessions\\n  saveUninitialized: false, // Don't create session until data stored\\n  secret: 'shhhh, very secret'\\n}));\\n```\\n\\n#### Password Hashing\\n\\nUses `pbkdf2-password` for secure password storage. When a user is created, a salt is generated and the password is hashed:\\n\\n```javascript\\nhash({ password: 'foobar' }, function (err, pass, salt, hash) {\\n  users.tj.salt = salt;\\n  users.tj.hash = hash;\\n});\\n```\\n\\nDuring authentication, the same salt is applied to the submitted password:\\n\\n```javascript\\nhash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {\\n  if (hash === user.hash) return fn(null, user);\\n  fn(null, null);\\n});\\n```\\n\\n#### Flash Messages\\n\\nThe session-persisted message middleware extracts `error` and `success` from the session and makes them available in `res.locals.message` for template rendering:\\n\\n```javascript\\napp.use(function(req, res, next){\\n  var err = req.session.error;\\n  var msg = req.session.success;\\n  delete req.session.error;\\n  delete req.session.success;\\n  res.locals.message = '';\\n  if (err) res.locals.message = '\n' + err + '&lt;\\/p&gt;';\\n  if (msg) res.locals.message = '\n' + msg + '&lt;\\/p&gt;';\\n  next();\\n});\\n```\\n\\n---\\n\\n### Cookie Sessions (`examples/cookie-sessions/`)\\n\\nLightweight session storage using client-side cookies via `cookie-session`.\\n\\n```javascript\\napp.use(cookieSession({ secret: 'manny is cool' }));\\n\\napp.get('/', function (req, res) {\\n  req.session.count = (req.session.count || 0) + 1;\\n  res.send('viewed ' + req.session.count + ' times\\\\n');\\n});\\n```\\n\\n**Use case:** Small session data that doesn't require server-side storage. Session data is encrypted and stored in the client cookie.\\n\\n---\\n\\n### Cookie Parser (`examples/cookies/`)\\n\\nDemonstrates reading and writing cookies with `cookie-parser`.\\n\\n**Key operations:**\\n\\n- `req.cookies` - Parsed unsigned cookies\\n- `req.signedCookies` - Parsed signed cookies\\n- `res.cookie(name, value, options)` - Set a cookie\\n- `res.clearCookie(name)` - Remove a cookie\\n\\n**Remember-me example:**\\n\\n```javascript\\n// Set cookie with expiration\\nres.cookie('remember', 1, { maxAge: 60000 });\\n\\n// Check for cookie\\nif (req.cookies.remember) {\\n  // User is remembered\\n}\\n\\n// Clear cookie\\nres.clearCookie('remember');\\n```\\n\\n---\\n\\n### Redis-Backed Sessions (`examples/session/redis.js`)\\n\\nProduction-ready session storage using Redis via `connect-redis`.\\n\\n```javascript\\nvar RedisStore = require('connect-redis')(session);\\n\\napp.use(session({\\n  resave: false,\\n  saveUninitialized: false,\\n  secret: 'keyboard cat',\\n  store: new RedisStore\\n}));\\n```\\n\\n**Benefits:**\\n- Sessions persist across server restarts\\n- Shared session storage for multiple server instances\\n- Automatic session expiration via Redis TTL\\n\\n**Prerequisites:**\\n- Redis server running (`redis-server`)\\n- `npm install redis connect-redis`\\n\\n---\\n\\n### Online User Tracking (`examples/online/`)\\n\\nTracks active users using Redis and the `online` package.\\n\\n```javascript\\nvar online = require('online');\\nvar redis = require('redis');\\nvar db = redis.createClient();\\nonline = online(db);\\n\\n// Track each request\\napp.use(function(req, res, next){\\n  online.add(req.headers['user-agent']);\\n  next();\\n});\\n\\n// Query recent users\\napp.get('/', function(req, res, next){\\n  online.last(5, function(err, ids){\\n    // ids = array of recent user identifiers\\n  });\\n});\\n```\\n\\n---\\n\\n## Routes Reference\\n\\n### Authentication Example Routes\\n\\n| Route | Method | Handler | Description |\\n|-------|--------|---------|-------------|\\n| `/` | GET | redirects to `/login` | Root redirect |\\n| `/login` | GET | renders login view | Display login form |\\n| `/login` | POST | authenticate, session regenerate | Process credentials |\\n| `/logout` | GET | `req.session.destroy()` | End session |\\n| `/restricted` | GET | `restrict` middleware, send response | Protected content |\\n\\n### Session Example Routes\\n\\n| Route | Method | Handler | Description |\\n|-------|--------|---------|-------------|\\n| `/` | GET | increment `req.session.views` | View counter |\\n\\n---\\n\\n## Security Considerations\\n\\n### Session Fixation Prevention\\n\\nThe authentication example regenerates the session ID on successful login:\\n\\n```javascript\\nreq.session.regenerate(function(){\\n  req.session.user = user;\\n  // ...\\n});\\n```\\n\\nThis prevents attackers from using a known session ID to hijack authenticated sessions.\\n\\n### Password Storage\\n\\n- Passwords are never stored in plaintext\\n- PBKDF2 derives a key from the password with a unique salt per user\\n- The salt and hash are stored; the plaintext password is discarded\\n\\n### Session Configuration\\n\\n- `resave: false` - Avoids unnecessary session store writes\\n- `saveUninitialized: false` - Prevents creating empty session records for unauthenticated users\\n\\n### Production Requirements\\n\\nBefore deploying to production:\\n\\n1. Replace hardcoded secrets with environment variables\\n2. Use HTTPS to protect cookies in transit\\n3. Set `secure: true` and `httpOnly: true` cookie options\\n4. Use Redis or another persistent store for sessions\\n5. Implement proper user database (replace placeholder `users` object)\\n\\n---\\n\\n## Dependencies\\n\\n| Package | Purpose |\\n|---------|---------|\\n| `express-session` | Server-side session management |\\n| `cookie-session` | Client-side cookie-based sessions |\\n| `cookie-parser` | Parse cookies from request headers |\\n| `pbkdf2-password` | Password hashing with PBKDF2 |\\n| `connect-redis` | Redis session store adapter |\\n| `redis` | Redis client |\\n| `online` | Online user tracking with Redis |\",\"basic-usage\":\"# Basic Usage\\n\\n# Basic Usage Examples\\n\\nThis module contains example applications demonstrating core Express.js patterns. Each example is self-contained and runnable, progressing from minimal setup to more realistic use cases.\\n\\n## Examples Overview\\n\\n| Example | Purpose | Dependencies |\\n|---------|---------|--------------|\\n| `hello-world` | Minimal Express server | None |\\n| `search` | Redis-backed search API | redis |\\n\\n---\\n\\n## Hello World\\n\\n**Location:** `examples/hello-world/index.js`\\n\\nThe simplest Express application. Creates a server that responds to GET requests on the root path.\\n\\n### Code Structure\\n\\n```javascript\\nvar express = require('../../');\\nvar app = module.exports = express();\\n\\napp.get('/', function(req, res){\\n  res.send('Hello World');\\n});\\n\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\n### Key Patterns\\n\\n**Exportable App Pattern:** The `app` is assigned to `module.exports`, allowing the application to be imported by tests or other modules without starting the server:\\n\\n```javascript\\nvar app = module.exports = express()\\n```\\n\\n**Conditional Server Start:** The `!module.parent` check ensures the server only starts when the file is run directly, not when imported:\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n}\\n```\\n\\n### Running\\n\\n```bash\\nnode examples/hello-world/index.js\\n# Visit http://localhost:3000\\n```\\n\\n---\\n\\n## Search Example\\n\\n**Location:** `examples/search/index.js`\\n\\nA more complete application demonstrating static file serving, Redis integration, and dynamic routing.\\n\\n### Architecture\\n\\n```mermaid\\nflowchart LR\\n    A[Client Browser] --&gt; B[Express Server]\\n    B --&gt; C[Redis Database]\\n    B --&gt; D[Static Files]\\n    A --&gt;|AJAX /search/:query| B\\n    B --&gt;|sMembers| C\\n    C --&gt;|results| B\\n    B --&gt;|JSON response| A\\n```\\n\\n### Components\\n\\n#### Redis Initialization\\n\\nThe `initializeRedis()` function handles async database setup:\\n\\n```javascript\\nasync function initializeRedis() {\\n  await db.connect();\\n  await db.sAdd('ferret', 'tobi');\\n  await db.sAdd('ferret', 'loki');\\n  await db.sAdd('ferret', 'jane');\\n  await db.sAdd('cat', 'manny');\\n  await db.sAdd('cat', 'luna');\\n}\\n```\\n\\nPopulates Redis sets with sample data for demonstration.\\n\\n#### Static File Serving\\n\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\n\\nServes files from `public/` directory. Note: This middleware is placed before route definitions, allowing explicit routes to override static files when needed.\\n\\n#### Search Endpoint\\n\\n```javascript\\napp.get('/search/{:query}', function (req, res, next) {\\n  var query = req.params.query || '';\\n  db.sMembers(query)\\n    .then((vals) =&gt; res.send(vals))\\n    .catch((err) =&gt; {\\n      console.error(`Redis error for query \\\"${query}\\\":`, err);\\n      next(err);\\n    });\\n});\\n```\\n\\n**Route Pattern:** `/search/{:query}` captures the search term as a route parameter.\\n\\n**Error Handling:** Redis errors are passed to Express error middleware via `next(err)`.\\n\\n#### Explicit File Route\\n\\n```javascript\\napp.get('/client.js', function(req, res){\\n  res.sendFile(path.join(__dirname, 'client.js'));\\n});\\n```\\n\\nDemonstrates `sendFile()` for serving individual files with full path resolution. This pattern is useful when you need to serve specific files outside the static directory or with additional logic.\\n\\n### Client-Side Integration\\n\\n**Location:** `examples/search/public/client.js`\\n\\nImplements live search using XMLHttpRequest:\\n\\n```javascript\\nvar search = document.querySelector('[type=search]');\\nsearch.addEventListener('keyup', function(){\\n  var xhr = new XMLHttpRequest;\\n  xhr.open('GET', '/search/' + search.value, true);\\n  xhr.onreadystatechange = function(){\\n    if (xhr.readyState === 4) {\\n      code.textContent = xhr.responseText;\\n    }\\n  };\\n  xhr.send();\\n}, false);\\n```\\n\\nTriggers a search request on each keystroke and displays results in a `\n` element.\\n\\n### Running\\n\\n```bash\\n# Prerequisites\\nnpm install redis\\nredis-server\\n\\n# Start the application\\nnode examples/search/index.js\\n# Visit http://localhost:3000\\n```\\n\\n---\\n\\n## Common Patterns Demonstrated\\n\\n### Response Methods\\n\\n| Method | Example | Use Case |\\n|--------|---------|----------|\\n| `res.send()` | `res.send('Hello World')` | Text or JSON responses |\\n| `res.sendFile()` | `res.sendFile(path.join(...))` | Serving individual files |\\n\\n### Middleware Order\\n\\nThe search example demonstrates middleware ordering importance:\\n\\n1. `express.static()` \u2014 serves public assets first\\n2. Route handlers \u2014 explicit routes can intercept or add logic\\n3. Error handling \u2014 `next(err)` propagates to error middleware\\n\\n### Module Export Pattern\\n\\nBoth examples use the exportable app pattern for testability:\\n\\n```javascript\\n// In test file\\nvar app = require('../examples/hello-world');\\n// App is available without starting server\\n```\",\"core-framework\":\"# Core Framework\\n\\n# Express Core Framework\\n\\nThe Express Core Framework provides the foundational building blocks for creating web applications and APIs. It implements the application factory, request/response prototypes, middleware system, routing infrastructure, and view rendering.\\n\\n## Architecture Overview\\n\\n```mermaid\\ngraph TD\\n    A[createApplication] --&gt; B[app function]\\n    B --&gt; C[EventEmitter.prototype]\\n    B --&gt; D[application prototype]\\n    D --&gt; E[router - lazy init]\\n    B --&gt; F[request prototype]\\n    B --&gt; G[response prototype]\\n    F --&gt; H[http.IncomingMessage]\\n    G --&gt; I[http.ServerResponse]\\n    D --&gt; J[View class]\\n    D --&gt; K[utils]\\n```\\n\\n## Application Factory\\n\\nThe `createApplication()` function in `lib/express.js` is the main entry point that constructs an Express application:\\n\\n```javascript\\nfunction createApplication() {\\n  var app = function(req, res, next) {\\n    app.handle(req, res, next);\\n  };\\n\\n  mixin(app, EventEmitter.prototype, false);\\n  mixin(app, proto, false);\\n\\n  app.request = Object.create(req, {\\n    app: { configurable: true, enumerable: true, writable: true, value: app }\\n  });\\n\\n  app.response = Object.create(res, {\\n    app: { configurable: true, enumerable: true, writable: true, value: app }\\n  });\\n\\n  app.init();\\n  return app;\\n}\\n```\\n\\nThe returned `app` is both a callable function (for use with `http.createServer`) and an object with methods for configuration, routing, and middleware registration.\\n\\n## Application Prototype (`lib/application.js`)\\n\\n### Initialization\\n\\n**`app.init()`** \u2014 Sets up the application's internal state:\\n- Creates empty `cache`, `engines`, and `settings` objects\\n- Calls `defaultConfiguration()` to apply default settings\\n- Lazily initializes the router via a getter\\n\\n**`app.defaultConfiguration()`** \u2014 Applies default settings:\\n\\n| Setting | Default Value |\\n|---------|---------------|\\n| `x-powered-by` | `true` |\\n| `etag` | `'weak'` |\\n| `env` | `process.env.NODE_ENV \\\\|\\\\| 'development'` |\\n| `query parser` | `'simple'` |\\n| `subdomain offset` | `2` |\\n| `trust proxy` | `false` |\\n| `view` | `View` class |\\n| `views` | `'views'` (resolved path) |\\n| `jsonp callback name` | `'callback'` |\\n\\nIn production mode, `view cache` is automatically enabled.\\n\\n### Request Handling\\n\\n**`app.handle(req, res, callback)`** \u2014 The core request dispatcher:\\n\\n1. Creates a final handler for uncaught errors\\n2. Sets `X-Powered-By: Express` header if enabled\\n3. Establishes circular `req.res` and `res.req` references\\n4. Sets prototypes on `req` and `res` to extend them with Express methods\\n5. Initializes `res.locals` if not present\\n6. Delegates to `this.router.handle()`\\n\\n### Middleware &amp; Routing\\n\\n**`app.use(fn)`** \u2014 Registers middleware on the application router:\\n\\n```javascript\\n// Mount middleware at root\\napp.use(express.json());\\n\\n// Mount middleware at path\\napp.use('/api', authMiddleware);\\n\\n// Mount sub-application\\napp.use('/admin', adminApp);\\n```\\n\\nWhen mounting a sub-application:\\n- The sub-app's `mountpath` and `parent` properties are set\\n- A wrapper function restores request/response prototypes after the sub-app handles\\n- The `'mount'` event is emitted on the sub-app\\n\\n**`app.route(path)`** \u2014 Creates a new `Route` instance for the given path. Routes are isolated middleware stacks for specific paths.\\n\\n**`app.param(name, fn)`** \u2014 Registers parameter middleware. The `name` can be a string or array of strings.\\n\\n**HTTP Method Methods** \u2014 `app.get()`, `app.post()`, `app.put()`, `app.delete()`, etc.:\\n- `app.get(setting)` with one argument retrieves a setting value\\n- `app.get(path, ...handlers)` with multiple arguments creates a route\\n\\n**`app.all(path, ...handlers)`** \u2014 Registers handlers for all HTTP methods on the given path.\\n\\n### Settings Management\\n\\n**`app.set(setting, val)`** \u2014 Sets or retrieves settings:\\n\\n```javascript\\napp.set('title', 'My App');  // Set\\napp.set('title');            // Get \u2192 'My App'\\n```\\n\\nSpecial settings trigger compiled functions:\\n\\n| Setting | Compiled Function |\\n|---------|-------------------|\\n| `etag` | `etag fn` (via `compileETag`) |\\n| `query parser` | `query parser fn` (via `compileQueryParser`) |\\n| `trust proxy` | `trust proxy fn` (via `compileTrust`) |\\n\\n**`app.enable(setting)`** / **`app.disable(setting)`** \u2014 Set to `true` or `false`.\\n\\n**`app.enabled(setting)`** / **`app.disabled(setting)`** \u2014 Check boolean state.\\n\\n### View Rendering\\n\\n**`app.render(name, options, callback)`** \u2014 Renders a view template:\\n\\n1. Merges options with `app.locals` and `opts._locals`\\n2. Checks cache if `view cache` is enabled\\n3. Creates a new `View` instance if not cached\\n4. Calls `view.render()` with the merged options\\n\\n### Server\\n\\n**`app.listen(...)`** \u2014 Creates and starts an HTTP server:\\n\\n```javascript\\napp.listen(3000);\\napp.listen(3000, '127.0.0.1');\\napp.listen(3000, () =&gt; console.log('Server started'));\\n```\\n\\n## Request Prototype (`lib/request.js`)\\n\\nExtends `http.IncomingMessage` with properties and methods for handling incoming requests.\\n\\n### Header Access\\n\\n**`req.get(name)`** / **`req.header(name)`** \u2014 Retrieves request headers (case-insensitive). Special-cases `Referer`/`Referrer`.\\n\\n### Content Negotiation\\n\\n| Method | Description |\\n|--------|-------------|\\n| `req.accepts(types)` | Best matching MIME type from Accept header |\\n| `req.acceptsEncodings(...encodings)` | Accepted encodings |\\n| `req.acceptsCharsets(...charsets)` | Accepted charsets |\\n| `req.acceptsLanguages(...languages)` | Accepted languages |\\n\\n### Request Properties\\n\\nAll properties are defined via getters for lazy evaluation:\\n\\n| Property | Description |\\n|----------|-------------|\\n| `req.query` | Parsed query string object |\\n| `req.protocol` | `'http'` or `'https'` |\\n| `req.secure` | `true` if HTTPS |\\n| `req.ip` | Client IP address (respects trust proxy) |\\n| `req.ips` | Array of IPs from X-Forwarded-For |\\n| `req.subdomains` | Array of subdomain parts |\\n| `req.path` | URL pathname |\\n| `req.host` | Host header (respects X-Forwarded-Host) |\\n| `req.hostname` | Host without port |\\n| `req.fresh` | `true` if cache is fresh (ETag/Last-Modified) |\\n| `req.stale` | Opposite of `fresh` |\\n| `req.xhr` | `true` if XMLHttpRequest |\\n\\n### Other Methods\\n\\n**`req.range(size, options)`** \u2014 Parses the `Range` header. Returns `undefined` if no range, `-1` if unsatisfiable, `-2` if invalid, or an array of range objects.\\n\\n**`req.is(types)`** \u2014 Checks if the request Content-Type matches the given types.\\n\\n## Response Prototype (`lib/response.js`)\\n\\nExtends `http.ServerResponse` with methods for sending responses.\\n\\n### Status &amp; Headers\\n\\n**`res.status(code)`** \u2014 Sets HTTP status code. Validates integer range 100-999.\\n\\n**`res.set(field, val)`** / **`res.header(field, val)`** \u2014 Sets response headers. Accepts object or key-value pairs.\\n\\n**`res.get(field)`** \u2014 Retrieves a response header.\\n\\n**`res.append(field, val)`** \u2014 Appends to an existing header.\\n\\n**`res.vary(field)`** \u2014 Adds to the `Vary` header.\\n\\n**`res.links(links)`** \u2014 Sets `Link` header from an object.\\n\\n### Sending Responses\\n\\n**`res.send(body)`** \u2014 Universal response sender:\\n- Strings: sent as HTML with UTF-8 charset\\n- Objects/Arrays: converted to JSON\\n- Buffers: sent as binary\\n- Numbers/Booleans: converted to JSON\\n- Automatically sets `Content-Length` and `ETag`\\n- Handles 204, 205, 304 status codes specially\\n\\n**`res.json(obj)`** \u2014 Sends JSON response with `Content-Type: application/json`.\\n\\n**`res.jsonp(obj)`** \u2014 Sends JSONP response. Uses the query parameter specified by `jsonp callback name` setting.\\n\\n**`res.sendStatus(statusCode)`** \u2014 Sends status code with its standard message.\\n\\n### Files &amp; Downloads\\n\\n**`res.sendFile(path, options, callback)`** \u2014 Streams a file:\\n- Options: `maxAge`, `root`, `headers`, `dotfiles`\\n- Requires absolute path or `root` option\\n- Uses the `send` module internally\\n\\n**`res.download(path, filename, options, callback)`** \u2014 Sends file as attachment with `Content-Disposition` header.\\n\\n**`res.attachment(filename)`** \u2014 Sets `Content-Disposition: attachment` header.\\n\\n### Content Type\\n\\n**`res.type(type)`** / **`res.contentType(type)`** \u2014 Sets Content-Type. Accepts extensions or full MIME types.\\n\\n**`res.format(obj)`** \u2014 Content negotiation based on Accept header:\\n\\n```javascript\\nres.format({\\n  'text/plain': () =&gt; res.send('text'),\\n  'text/html': () =&gt; res.send('\nhtml&lt;\\/p&gt;'),\\n  'application/json': () =&gt; res.json({ data: 'json' }),\\n  default: () =&gt; res.status(406).send('Not Acceptable')\\n});\\n```\\n\\n### Cookies\\n\\n**`res.cookie(name, value, options)`** \u2014 Sets a cookie:\\n- `maxAge`: milliseconds until expiry\\n- `signed`: sign with `req.secret`\\n- `path`: defaults to `/`\\n- Other options: `expires`, `httpOnly`, `secure`, `sameSite`, etc.\\n\\n**`res.clearCookie(name, options)`** \u2014 Clears a cookie by setting expiry to the past.\\n\\n### Redirects\\n\\n**`res.location(url)`** \u2014 Sets `Location` header. Handles `'back'` for referrer.\\n\\n**`res.redirect(url)`** / **`res.redirect(status, url)`** \u2014 Performs HTTP redirect (default 302). Responds with appropriate body based on Accept header.\\n\\n### Rendering\\n\\n**`res.render(view, options, callback)`** \u2014 Renders a view template:\\n1. Merges `res.locals` into options\\n2. Calls `app.render()` with the view name\\n3. Default callback sends the rendered HTML\\n\\n## View Class (`lib/view.js`)\\n\\nHandles template lookup and rendering.\\n\\n### Constructor\\n\\n```javascript\\nnew View(name, {\\n  defaultEngine: 'ejs',\\n  root: './views',\\n  engines: { '.ejs': ejs.__express }\\n});\\n```\\n\\n- Resolves the file extension from the name or default engine\\n- Loads the template engine if not already cached\\n- Looks up the view file\\n\\n### Methods\\n\\n**`view.lookup(name)`** \u2014 Searches for the view file in configured root directories.\\n\\n**`view.resolve(dir, file)`** \u2014 Resolves a file within a directory, checking:\\n1. `.`\\n2. `/index.`\\n\\n**`view.render(options, callback)`** \u2014 Renders the view using the loaded engine. Ensures the callback is always invoked asynchronously via `process.nextTick()`.\\n\\n## Utilities (`lib/utils.js`)\\n\\nInternal helper functions used throughout the framework:\\n\\n| Function | Purpose |\\n|----------|---------|\\n| `methods` | Array of lowercase HTTP methods from Node.js |\\n| `etag(body, encoding)` | Generate strong ETag |\\n| `wetag(body, encoding)` | Generate weak ETag |\\n| `compileETag(val)` | Convert setting to ETag function |\\n| `compileQueryParser(val)` | Convert setting to query parser function |\\n| `compileTrust(val)` | Convert setting to trust proxy function |\\n| `normalizeType(type)` | Normalize MIME type with params |\\n| `normalizeTypes(types)` | Normalize array of types |\\n| `setCharset(type, charset)` | Add charset to Content-Type |\\n\\n## Sub-Application Mounting\\n\\nWhen mounting an Express app within another app:\\n\\n```javascript\\nvar admin = express();\\nadmin.locals.title = 'Admin';\\n\\napp.use('/admin', admin);\\n```\\n\\nThe sub-app:\\n- Receives `mountpath` set to `/admin`\\n- Receives `parent` reference to the main app\\n- Emits `'mount'` event\\n- Inherits `request`, `response`, `engines`, and `settings` prototypes from parent\\n- Inherits `trust proxy` setting if not explicitly set\\n\\n## Error Handling\\n\\nThe `finalhandler` module is used as the default error handler when no callback is provided to `app.handle()`. Errors are logged via `logerror()` in non-test environments.\\n\\n## Exports\\n\\nThe main `express` module exports:\\n\\n```javascript\\nexpress()              // createApplication factory\\nexpress.application    // application prototype\\nexpress.request        // request prototype\\nexpress.response       // response prototype\\nexpress.Route          // Route class from router\\nexpress.Router         // Router class\\nexpress.json()         // JSON body parser\\nexpress.raw()          // Raw body parser\\nexpress.text()         // Text body parser\\nexpress.urlencoded()   // URL-encoded body parser\\nexpress.static()       // Static file server\\n```\",\"error-handling\":\"# Error Handling\\n\\n# Error Handling Module\\n\\nThis module demonstrates Express.js error handling patterns through two example applications: a comprehensive error pages example with content negotiation, and a minimal error handling example.\\n\\n## Overview\\n\\nExpress distinguishes between two types of middleware:\\n- **Regular middleware**: signature `(req, res, next)` \u2014 handles normal request flow\\n- **Error-handling middleware**: signature `(err, req, res, next)` \u2014 catches errors passed through `next(err)` or thrown synchronously\\n\\nError-handling middleware must be registered **after** all routes and regular middleware to receive errors.\\n\\n## Architecture\\n\\n```mermaid\\nflowchart TD\\n    A[Request] --&gt; B{Route Handler}\\n    B --&gt;|Success| C[Response]\\n    B --&gt;|throw Error| D[Error Middleware]\\n    B --&gt;|next err| D\\n    B --&gt;|next without response| E[404 Handler]\\n    D --&gt; F[Error Response]\\n    E --&gt; G[404 Response]\\n```\\n\\n## Examples\\n\\n### Error Pages Example (`examples/error-pages/`)\\n\\nA full-featured error handling demonstration with custom views and content negotiation.\\n\\n#### Configuration\\n\\n```javascript\\napp.set('views', path.join(__dirname, 'views'));\\napp.set('view engine', 'ejs');\\napp.enable('verbose errors');\\n\\n// Disable verbose errors in production\\nif (app.settings.env === 'production') app.disable('verbose errors')\\n```\\n\\nThe `verbose errors` setting controls whether stack traces are displayed in error pages. This is exposed to templates via `settings['verbose errors']`.\\n\\n#### Triggering Errors\\n\\n| Route | Method | Behavior |\\n|-------|--------|----------|\\n| `GET /404` | `next()` | No response sent, falls through to 404 handler |\\n| `GET /403` | `next(err)` | Passes a 403 error to error middleware |\\n| `GET /500` | `next(new Error(...))` | Triggers a generic 500 error |\\n\\n```javascript\\napp.get('/403', function(req, res, next){\\n  var err = new Error('not allowed!');\\n  err.status = 403;\\n  next(err);\\n});\\n```\\n\\n#### 404 Handler\\n\\nPlaced after all routes. If no route matched or no middleware responded, this handler creates a 404 response:\\n\\n```javascript\\napp.use(function(req, res, next){\\n  res.status(404);\\n  res.format({\\n    html: function () {\\n      res.render('404', { url: req.url })\\n    },\\n    json: function () {\\n      res.json({ error: 'Not found' })\\n    },\\n    default: function () {\\n      res.type('txt').send('Not found')\\n    }\\n  })\\n});\\n```\\n\\nThe `res.format()` method performs content negotiation based on the `Accept` header.\\n\\n#### Error Middleware\\n\\n```javascript\\napp.use(function(err, req, res, next){\\n  res.status(err.status || 500);\\n  res.render('500', { error: err });\\n});\\n```\\n\\nUses `err.status` if available, otherwise defaults to 500 (Internal Server Error).\\n\\n#### Views\\n\\n**500.ejs** \u2014 Conditionally displays stack traces:\\n\\n```ejs\\n\nError: &lt;%= error.message %&gt;&lt;\\/h2&gt;\\n&lt;% if (settings['verbose errors']) { %&gt;\\n  \n&lt;%= error.stack %&gt;&lt;\\/pre&gt;\\n&lt;% } else { %&gt;\\n  \nAn error occurred!&lt;\\/p&gt;\\n&lt;% } %&gt;\\n```\\n\\n### Minimal Error Example (`examples/error/`)\\n\\nDemonstrates two ways errors reach error-handling middleware:\\n\\n#### Synchronous Throw\\n\\n```javascript\\napp.get('/', function () {\\n  throw new Error('something broke!');\\n});\\n```\\n\\nThrown errors are automatically caught by Express and passed to error middleware.\\n\\n#### Async with next(err)\\n\\n```javascript\\napp.get('/next', function(req, res, next){\\n  process.nextTick(function(){\\n    next(new Error('oh no!'));\\n  });\\n});\\n```\\n\\nFor async operations, pass errors to `next()`. Throwing inside async callbacks won't be caught by Express.\\n\\n#### Error Handler\\n\\n```javascript\\nfunction error(err, req, res, next) {\\n  if (!test) console.error(err.stack);\\n  res.status(500);\\n  res.send('Internal Server Error');\\n}\\n\\napp.use(error);\\n```\\n\\n## Key Concepts\\n\\n### Middleware Arity\\n\\nExpress uses function arity (argument count) to identify error-handling middleware:\\n\\n| Arity | Type | Signature |\\n|-------|------|-----------|\\n| 3 | Regular | `(req, res, next)` |\\n| 4 | Error | `(err, req, res, next)` |\\n\\n### Error Propagation\\n\\n1. **Synchronous throws**: Caught automatically by Express\\n2. **`next(err)`**: Passes error to next error-handling middleware\\n3. **`next()`**: Continues to next regular middleware (no error)\\n4. **No response + no next()**: Falls through to subsequent middleware\\n\\n### Middleware Order\\n\\nError handlers must be registered **after** routes:\\n\\n```javascript\\n// \u2713 Correct\\napp.get('/', routeHandler);\\napp.use(errorHandler);\\n\\n// \u2717 Wrong - handler never receives errors\\napp.use(errorHandler);\\napp.get('/', routeHandler);\\n```\\n\\n### Production vs Development\\n\\n| Environment | Verbose Errors | Stack Traces |\\n|--------------|----------------|--------------|\\n| Development | Enabled | Shown |\\n| Production | Disabled | Hidden |\\n\\n## Testing Error Responses\\n\\n```bash\\n# 404 with different Accept headers\\ncurl http://localhost:3000/notfound\\ncurl http://localhost:3000/notfound -H \\\"Accept: application/json\\\"\\ncurl http://localhost:3000/notfound -H \\\"Accept: text/plain\\\"\\n```\",\"other-acceptance\":\"# Other \u2014 acceptance\\n\\n# Acceptance Tests Module\\n\\nThe `test/acceptance/` directory contains integration tests for Express example applications. Each test file validates the end-to-end behavior of a corresponding example in the `examples/` directory using HTTP requests via `supertest`.\\n\\n## Purpose\\n\\nThese tests serve as:\\n- **Integration verification** \u2014 Confirm example apps work correctly as complete systems\\n- **Documentation by example** \u2014 Demonstrate expected HTTP behavior for each feature\\n- **Regression protection** \u2014 Catch breaking changes in example applications\\n\\n## Architecture\\n\\n```\\ntest/acceptance/\\n\u251c\u2500\u2500 auth.js              \u2192 examples/auth\\n\u251c\u2500\u2500 content-negotiation.js \u2192 examples/content-negotiation\\n\u251c\u2500\u2500 cookie-sessions.js   \u2192 examples/cookie-sessions\\n\u251c\u2500\u2500 cookies.js           \u2192 examples/cookies\\n\u251c\u2500\u2500 downloads.js         \u2192 examples/downloads\\n\u251c\u2500\u2500 ejs.js               \u2192 examples/ejs\\n\u251c\u2500\u2500 error.js             \u2192 examples/error\\n\u251c\u2500\u2500 error-pages.js       \u2192 examples/error-pages\\n\u251c\u2500\u2500 hello-world.js       \u2192 examples/hello-world\\n\u251c\u2500\u2500 markdown.js          \u2192 examples/markdown\\n\u251c\u2500\u2500 multi-router.js      \u2192 examples/multi-router\\n\u251c\u2500\u2500 mvc.js               \u2192 examples/mvc\\n\u251c\u2500\u2500 params.js            \u2192 examples/params\\n\u251c\u2500\u2500 resource.js          \u2192 examples/resource\\n\u251c\u2500\u2500 route-map.js         \u2192 examples/route-map\\n\u251c\u2500\u2500 route-separation.js  \u2192 examples/route-separation\\n\u251c\u2500\u2500 vhost.js             \u2192 examples/vhost\\n\u2514\u2500\u2500 web-service.js       \u2192 examples/web-service\\n```\\n\\n## Test Structure\\n\\nAll tests follow a consistent pattern using Mocha and supertest:\\n\\n```javascript\\nvar request = require('supertest');\\nvar app = require('../../examples/example-name');\\n\\ndescribe('example-name', function(){\\n  describe('GET /path', function(){\\n    it('should respond with expected behavior', function(done){\\n      request(app)\\n        .get('/path')\\n        .expect(200, done);\\n    });\\n  });\\n});\\n```\\n\\n## Key Test Categories\\n\\n### Authentication &amp; Sessions\\n\\n**auth.js** \u2014 Tests login/logout flow, session persistence, and route protection:\\n- Redirects unauthenticated users to `/login`\\n- Validates credentials (username: `tj`, password: `foobar`)\\n- Sets session cookies on successful login\\n- Restricts `/restricted` to authenticated users\\n\\n**cookie-sessions.js** \u2014 Tests cookie-based session state:\\n- Tracks view counts across requests\\n- Persists session data via cookies\\n\\n**cookies.js** \u2014 Tests cookie handling:\\n- Setting and clearing cookies\\n- \\\"Remember me\\\" functionality\\n\\n### Content Handling\\n\\n**content-negotiation.js** \u2014 Tests response format negotiation:\\n- `Accept: text/html` \u2192 HTML list\\n- `Accept: text/plain` \u2192 Plain text list\\n- `Accept: application/json` \u2192 JSON array\\n\\n**downloads.js** \u2014 Tests file download behavior:\\n- Sets `Content-Disposition: attachment` headers\\n- Blocks path traversal attacks (`/files/../index.js` returns 403)\\n- Returns 404 for missing files\\n\\n**ejs.js** \u2014 Tests EJS template rendering with proper HTML escaping\\n\\n**markdown.js** \u2014 Tests markdown-to-HTML conversion\\n\\n### Routing Patterns\\n\\n**multi-router.js** \u2014 Tests multiple Express routers:\\n- Root routes (`/`)\\n- Versioned API routes (`/api/v1/`, `/api/v2/`)\\n\\n**route-map.js** \u2014 Tests route mapping with HTTP method verbs\\n\\n**route-separation.js** \u2014 Tests modular route organization:\\n- User routes (`/users`, `/user/:id`)\\n- Pet routes (`/pet/:id`)\\n- Post routes (`/posts`)\\n\\n**params.js** \u2014 Tests route parameter preconditions:\\n- User lookup by ID\\n- Range parsing (`/users/0-2`)\\n- Error handling for invalid params\\n\\n### Error Handling\\n\\n**error.js** \u2014 Tests error middleware:\\n- Synchronous errors return 500\\n- Missing routes return 404\\n\\n**error-pages.js** \u2014 Tests custom error pages with content negotiation:\\n- HTML, JSON, and plain text error responses\\n- Status codes: 403, 404, 500\\n\\n### API Patterns\\n\\n**web-service.js** \u2014 Tests REST API with API key authentication:\\n- Missing API key \u2192 400 Bad Request\\n- Invalid API key \u2192 401 Unauthorized\\n- Valid API key (`foo` or `bar`) \u2192 JSON response\\n\\n**resource.js** \u2014 Tests resource-based routing:\\n- CRUD operations on `/users`\\n- Range queries (`/users/1..3`)\\n- JSON format suffix (`.json`)\\n\\n### Virtual Hosting\\n\\n**vhost.js** \u2014 Tests virtual host routing:\\n- `example.com` \u2192 main app\\n- `foo.example.com` \u2192 redirects to `/foo`\\n- `bar.example.com` \u2192 redirects to `/bar`\\n\\n### MVC Pattern\\n\\n**mvc.js** \u2014 Tests full MVC implementation:\\n- User CRUD operations\\n- Pet management per user\\n- Edit forms and updates\\n\\n## Helper Functions\\n\\n### getCookie (auth.js)\\n\\nExtracts session cookie from response headers:\\n\\n```javascript\\nfunction getCookie(res) {\\n  return res.headers['set-cookie'][0].split(';')[0];\\n}\\n```\\n\\n### getCookies (cookie-sessions.js)\\n\\nExtracts all cookies for multi-cookie responses:\\n\\n```javascript\\nfunction getCookies(res) {\\n  return res.headers['set-cookie'].map(function (val) {\\n    return val.split(';')[0]\\n  }).join('; ');\\n}\\n```\\n\\n## External Dependencies\\n\\n- **supertest** \u2014 HTTP assertion library for testing Express apps\\n- **test/support/utils.js** \u2014 Shared test utilities:\\n  - `shouldNotHaveHeader(headerName)` \u2014 Asserts response lacks a specific header\\n\\n## Running Tests\\n\\n```bash\\n# Run all acceptance tests\\nnpm test -- --grep \\\"acceptance\\\"\\n\\n# Run specific example test\\nnpm test -- test/acceptance/auth.js\\n```\\n\\n## Adding New Acceptance Tests\\n\\n1. Create `test/acceptance/your-feature.js`\\n2. Import the example app: `var app = require('../../examples/your-feature')`\\n3. Structure tests by HTTP method and route\\n4. Test both success and error scenarios\\n5. Verify status codes, response bodies, and headers\",\"other-examples\":\"# Other \u2014 examples\\n\\n# Express Examples\\n\\nThe `examples/` directory contains reference applications demonstrating Express.js features and common patterns. Each subdirectory is a self-contained, runnable application focused on a specific concept.\\n\\n## Overview\\n\\nThese examples serve as practical guides for implementing common web application features with Express. They range from basic request handling to advanced patterns like MVC architecture and virtual hosting.\\n\\n## Example Categories\\n\\n### Core Concepts\\n\\n| Example | Description |\\n|---------|-------------|\\n| `hello-world` | Minimal Express server with a single request handler |\\n| `static-files` | Serving static assets (CSS, JS, images) |\\n| `error` | Error handling middleware implementation |\\n| `error-pages` | Custom error page rendering |\\n\\n### Routing Patterns\\n\\n| Example | Description |\\n|---------|-------------|\\n| `params` | Route parameter extraction and validation |\\n| `route-middleware` | Middleware specific to routes |\\n| `route-separation` | Organizing routes by resource |\\n| `route-map` | Route definitions using configuration maps |\\n| `multi-router` | Multiple Express routers for modular routing |\\n| `resource` | RESTful resource handling with multiple HTTP methods |\\n\\n### Sessions and Authentication\\n\\n| Example | Description |\\n|---------|-------------|\\n| `auth` | Login and password authentication flow |\\n| `session` | Server-side session management |\\n| `cookie-sessions` | Client-side session storage via cookies |\\n| `cookies` | Reading and writing HTTP cookies |\\n| `online` | Real-time user activity tracking with Redis |\\n\\n### Views and Templating\\n\\n| Example | Description |\\n|---------|-------------|\\n| `ejs` | Embedded JavaScript templates |\\n| `markdown` | Markdown as a template engine |\\n| `view-constructor` | Dynamic view rendering |\\n| `view-locals` | Passing data through `res.locals` |\\n\\n### HTTP Features\\n\\n| Example | Description |\\n|---------|-------------|\\n| `content-negotiation` | Responding based on `Accept` headers |\\n| `downloads` | File transfer to clients |\\n| `search` | Search API implementation |\\n| `web-service` | RESTful API service |\\n| `vhost` | Virtual hosting for multiple domains |\\n\\n### Architecture Patterns\\n\\n| Example | Description |\\n|---------|-------------|\\n| `mvc` | Model-View-Controller structure |\\n| `online` | Integration with external services (Redis) |\\n\\n## Running an Example\\n\\nEach example is a standalone Node.js application:\\n\\n```bash\\ncd examples/hello-world\\nnpm install\\nnode app.js\\n```\\n\\nMost examples follow this pattern, though some (like `online`) require additional setup such as a running Redis instance.\\n\\n## Directory Structure\\n\\nEach example typically contains:\\n\\n```\\nexample-name/\\n\u251c\u2500\u2500 app.js          # Main application entry point\\n\u251c\u2500\u2500 package.json    # Dependencies and scripts\\n\u251c\u2500\u2500 routes/         # Route handlers (in larger examples)\\n\u251c\u2500\u2500 views/          # Template files (when applicable)\\n\u2514\u2500\u2500 public/         # Static assets (when applicable)\\n```\\n\\n## Learning Path\\n\\nRecommended order for newcomers:\\n\\n1. `hello-world` \u2014 Understand basic server setup\\n2. `static-files` \u2014 Learn to serve assets\\n3. `route-middleware` \u2014 Grasp middleware chains\\n4. `params` \u2014 Work with dynamic routes\\n5. `error` \u2014 Implement error handling\\n6. `session` \u2014 Add state management\\n7. `auth` \u2014 Secure your application\\n8. `mvc` \u2014 Structure larger applications\",\"other-history-md\":\"# Other \u2014 History.md\\n\\n# History.md - Express.js Changelog\\n\\n## Overview\\n\\n`History.md` is the canonical changelog for Express.js, documenting the complete evolution of the framework from early 0.x releases through the current 5.x series. It serves as the primary historical record of all changes, including new features, bug fixes, breaking changes, deprecations, security updates, and dependency updates.\\n\\n## Purpose\\n\\nThis file provides:\\n\\n- **Release history**: Chronological record of all published versions with release dates\\n- **Migration guidance**: Breaking changes and deprecation notices to help developers upgrade\\n- **Feature documentation**: New capabilities added in each release\\n- **Security tracking**: CVE references and security advisory links\\n- **Dependency evolution**: External package version changes and their impact\\n\\n## Structure\\n\\nThe changelog follows a reverse-chronological format with these conventions:\\n\\n### Version Headers\\n\\n```\\n5.2.1 / 2025-12-01\\n===================\\n```\\n\\nEach version entry includes:\\n- Version number (semver format)\\n- Release date in `YYYY-MM-DD` format\\n\\n### Change Categories\\n\\nChanges are organized by type using emoji prefixes:\\n\\n| Category | Prefix | Description |\\n|----------|--------|-------------|\\n| Improvements | \ud83d\ude80 | Enhancements and refinements |\\n| Performance | \u26a1 | Optimizations and speed improvements |\\n| Breaking | `breaking:` | Changes requiring code modification |\\n| Remove | `remove:` | Deprecated features removed |\\n| Change | `change:` | Modified behavior |\\n| Add | `add:` | New features |\\n| Fix | `fix:` | Bug corrections |\\n| Deps | `deps:` | Dependency updates |\\n| Deprecate | `deprecate` | Features scheduled for removal |\\n| Perf | `perf:` | Performance improvements |\\n| Security | Security fix | CVE and security advisory references |\\n\\n### Pull Request References\\n\\nChanges link to their source:\\n\\n```\\n- by [@username](https://github.com/username) in [#1234](https://github.com/expressjs/express/pull/1234)\\n```\\n\\n### Code Examples\\n\\nSignificant changes include usage examples:\\n\\n```js\\napp.render('index', null, callback); // now works as expected\\n```\\n\\n## Key Version Milestones\\n\\n### Express 5.x (Current)\\n\\nThe 5.x series represents a major evolution with significant breaking changes:\\n\\n**5.0.0 (2024-09-10)** - Major release highlights:\\n- `res.status()` now validates integer status codes (99 &lt; code &lt; 1000)\\n- Removed `res.redirect('back')` magic string support\\n- `res.clearCookie` ignores user-provided `maxAge` and `expires`\\n- Removed `path-is-absolute` dependency (use `path.isAbsolute`)\\n- Multiple dependency updates to modern versions\\n\\n**5.1.0 (2025-03-31)** - Feature additions:\\n- `Uint8Array` support in `res.send()`\\n- ETag option in `res.sendFile()`\\n- Multiple links with same rel in `res.links()`\\n- Removed legacy dependencies: `setprototypeof`, `safe-buffer`, `utils-merge`, `methods`, `depd`\\n\\n**Unreleased** - Upcoming improvements:\\n- Enhanced HTML structure in `res.redirect()` responses\\n- `app.render()` now handles `null` options correctly\\n- Performance: reduced duplicate Content-Type processing in `res.send()`\\n\\n### Express 4.x (Stable Legacy)\\n\\nThe 4.x series remains widely used with active maintenance:\\n\\n**4.20.0 (2024-09-10)** - Security and dependency updates:\\n- Removed link renderization in `res.redirect` HTML responses\\n- `body-parser` depth option (default: 32, previously Infinity)\\n- `path-to-regexp@0.1.10` with named matching groups support\\n\\n**4.19.x (2024-03)** - Security fixes:\\n- Open redirect allow list bypass prevention\\n- Non-string encoding handling in `res.location`\\n\\n**4.18.x (2022)** - Feature additions:\\n- `res.download` \\\"root\\\" option\\n- `res.status` deprecation for non-integer arguments\\n- Proper 205 response handling\\n\\n### Express 3.x (Deprecated)\\n\\nHistorical reference for legacy applications. Key transitions from 3.x to 4.x:\\n\\n- Removed bundled middleware (except `static`)\\n- `app.router` removed\\n- `req.params` changed from array to object\\n- `res.locals` changed from function to plain object\\n\\n## Breaking Changes Reference\\n\\n### Response Method Signatures\\n\\nSeveral response method signatures changed across versions:\\n\\n| Version | Old Signature | New Signature |\\n|---------|---------------|---------------|\\n| 5.0.0-alpha.6 | `res.redirect(url, status)` | `res.redirect(status, url)` |\\n| 5.0.0-alpha.6 | `res.send(status, body)` | `res.status(status).send(body)` |\\n| 5.0.0-alpha.3 | `res.json(status, obj)` | `res.status(status).json(obj)` |\\n| 5.0.0-alpha.3 | `res.jsonp(status, obj)` | `res.status(status).jsonp(obj)` |\\n\\n### Removed Features\\n\\n| Feature | Removed In | Replacement |\\n|---------|------------|-------------|\\n| `app.del()` | 5.0.0-alpha.1 | `app.delete()` |\\n| `req.param()` | 5.0.0-alpha.2 | `req.params`, `req.body`, `req.query` |\\n| `res.sendfile` | 5.0.0-beta.1 | `res.sendFile` |\\n| `res.redirect('back')` | 5.0.0 | `req.get('Referrer') || '/'` |\\n| `express.query` | 5.0.0-alpha.1 | Use body-parser middleware |\\n\\n## Security Advisories\\n\\nThe changelog documents security vulnerabilities with full references:\\n\\n| CVE | Version Fixed | Description |\\n|-----|---------------|-------------|\\n| CVE-2024-47764 | 5.0.1 | Cookie semver vulnerability |\\n| CVE-2024-51999 | 5.2.0 (reverted in 5.2.1) | Extended query parser (rejected CVE) |\\n| GHSA-pj86-cfqh-vqx6 | 5.2.0 | Related to CVE-2024-51999 |\\n\\n## Dependency Evolution\\n\\n### Core Dependencies (5.x)\\n\\n```\\nbody-parser@^2.2.1\\nrouter@^2.2.0\\ndebug@^4.4.0\\nqs@^6.14.0\\ncontent-type@^1.0.5\\nfinalhandler@^2.1.0\\n```\\n\\n### Removed Dependencies (5.1.0)\\n\\nSeveral legacy compatibility packages were removed:\\n- `setprototypeof` - now uses native `Object.setPrototypeOf`\\n- `safe-buffer` - uses native `Buffer` API\\n- `utils-merge` - replaced with native spread/assign\\n- `methods` - internalized\\n- `depd` - deprecation handling simplified\\n\\n## Usage for Developers\\n\\n### When Upgrading\\n\\n1. **Identify target version** - Locate the version header for your upgrade target\\n2. **Review breaking changes** - Check `breaking:` and `remove:` entries\\n3. **Note deprecations** - Plan for `deprecate` items in future releases\\n4. **Check dependencies** - Verify compatible dependency versions\\n5. **Test security fixes** - Ensure security-related changes don't affect behavior\\n\\n### Version Range Navigation\\n\\nFor upgrading across multiple versions, read entries between your current and target versions. Each entry is self-contained with sufficient context for understanding the change impact.\\n\\n### Pull Request Investigation\\n\\nEach change links to its originating PR. For detailed implementation details, discussion context, or related issues, follow the PR links provided.\",\"other-package-json\":\"# Other \u2014 package.json\\n\\n# package.json\\n\\nExpress.js package manifest defining project metadata, dependencies, and development workflows.\\n\\n## Overview\\n\\nThis is the npm package configuration for Express 5.2.1. It declares the framework's public API surface, runtime requirements, and development toolchain.\\n\\n## Runtime Requirements\\n\\n```json\\n\\\"engines\\\": {\\n  \\\"node\\\": \\\"&gt;= 18\\\"\\n}\\n```\\n\\nExpress 5.x requires Node.js 18 or later. This aligns with the framework's use of modern JavaScript features and the updated dependency versions.\\n\\n## Published Files\\n\\n```json\\n\\\"files\\\": [\\n  \\\"LICENSE\\\",\\n  \\\"Readme.md\\\",\\n  \\\"index.js\\\",\\n  \\\"lib/\\\"\\n]\\n```\\n\\nWhen published to npm, only these files are included. The `lib/` directory contains the core framework implementation, while `index.js` serves as the main entry point.\\n\\n## Production Dependencies\\n\\n| Package | Version | Purpose |\\n|---------|---------|---------|\\n| `accepts` | ^2.0.0 | Content negotiation for Accept headers |\\n| `body-parser` | ^2.2.1 | Request body parsing middleware |\\n| `content-disposition` | ^1.0.0 | Content-Disposition header generation |\\n| `content-type` | ^1.0.5 | Content-Type header parsing |\\n| `cookie` | ^0.7.1 | Cookie parsing and serialization |\\n| `cookie-signature` | ^1.2.1 | Cookie signing for tamper detection |\\n| `debug` | ^4.4.0 | Debugging output with namespace support |\\n| `depd` | ^2.0.0 | Deprecation warnings |\\n| `encodeurl` | ^2.0.0 | URL encoding utilities |\\n| `escape-html` | ^1.0.3 | HTML entity escaping for XSS prevention |\\n| `etag` | ^1.8.1 | ETag header generation for caching |\\n| `finalhandler` | ^2.1.0 | Final request handler for cleanup |\\n| `fresh` | ^2.0.0 | HTTP cache freshness validation |\\n| `http-errors` | ^2.0.0 | HTTP error object creation |\\n| `merge-descriptors` | ^2.0.0 | Property descriptor merging |\\n| `mime-types` | ^3.0.0 | MIME type lookup and resolution |\\n| `on-finished` | ^2.4.1 | Callback attachment for request/response completion |\\n| `once` | ^1.4.0 | Single-execution function wrapper |\\n| `parseurl` | ^1.3.3 | URL parsing with caching |\\n| `proxy-addr` | ^2.0.7 | Proxy address resolution for X-Forwarded-For |\\n| `qs` | ^6.14.2 | Query string parsing with nesting support |\\n| `range-parser` | ^1.2.1 | Range header parsing for file downloads |\\n| `router` | ^2.2.0 | Core routing implementation |\\n| `send` | ^1.1.0 | Static file serving with caching |\\n| `serve-static` | ^2.2.0 | Static file serving middleware |\\n| `statuses` | ^2.0.1 | HTTP status code mappings |\\n| `type-is` | ^2.0.1 | Request content-type checking |\\n| `vary` | ^1.1.2 | Vary header manipulation for caching |\\n\\n### Key Dependency Groups\\n\\n**Request Processing**: `body-parser`, `qs`, `type-is`, `content-type`\\n\\n**Response Handling**: `send`, `serve-static`, `content-disposition`, `etag`, `fresh`\\n\\n**Routing**: `router`, `parseurl`\\n\\n**Security**: `cookie-signature`, `escape-html`, `proxy-addr`, `http-errors`\\n\\n**HTTP Utilities**: `accepts`, `vary`, `statuses`, `range-parser`\\n\\n## Development Dependencies\\n\\n| Package | Version | Purpose |\\n|---------|---------|---------|\\n| `mocha` | ^10.7.3 | Test framework |\\n| `supertest` | ^6.3.0 | HTTP assertion testing |\\n| `nyc` | ^17.1.0 | Code coverage instrumentation |\\n| `eslint` | 8.47.0 | Code linting |\\n| `marked` | ^15.0.3 | Markdown processing for docs |\\n\\n### Session and Auth Testing\\n\\n| Package | Version | Purpose |\\n|---------|---------|---------|\\n| `express-session` | ^1.18.1 | Session middleware testing |\\n| `connect-redis` | ^8.0.1 | Redis session store testing |\\n| `cookie-parser` | 1.4.7 | Cookie parsing middleware testing |\\n| `cookie-session` | 2.1.1 | Cookie-based session testing |\\n| `pbkdf2-password` | 1.2.1 | Password hashing for auth examples |\\n\\n### Template Engine Testing\\n\\n| Package | Version | Purpose |\\n|---------|---------|---------|\\n| `ejs` | ^3.1.10 | Embedded JavaScript templates |\\n| `hbs` | 4.2.0 | Handlebars templates |\\n\\n### Middleware Testing\\n\\n| Package | Version | Purpose |\\n|---------|---------|---------|\\n| `morgan` | 1.10.1 | HTTP request logger |\\n| `method-override` | 3.0.0 | HTTP method override support |\\n| `vhost` | ~3.0.2 | Virtual host routing |\\n\\n## NPM Scripts\\n\\n### Linting\\n\\n```bash\\nnpm run lint        # Check code style\\nnpm run lint:fix    # Auto-fix style issues\\n```\\n\\nUses ESLint 8.47.0 for code quality enforcement.\\n\\n### Testing\\n\\n```bash\\nnpm test            # Run full test suite with spec reporter\\nnpm run test-tap    # Run tests with TAP output for CI parsing\\nnpm run test-cov    # Run tests with HTML coverage report\\nnpm run test-ci     # Run tests with lcov output for CI services\\n```\\n\\n**Test Configuration**:\\n- Test files: `test/` and `test/acceptance/`\\n- Environment setup: `test/support/env`\\n- Leak detection enabled (`--check-leaks`)\\n\\n**Coverage Exclusions**: `examples/`, `test/`, `benchmarks/`\\n\\n## Version Information\\n\\n- **Current Version**: 5.2.1\\n- **License**: MIT\\n- **Author**: TJ Holowaychuk\\n- **Repository**: expressjs/express\\n\\n## Funding\\n\\nThe project accepts funding through Open Collective:\\n\\n```json\\n\\\"funding\\\": {\\n  \\\"type\\\": \\\"opencollective\\\",\\n  \\\"url\\\": \\\"https://opencollective.com/express\\\"\\n}\\n```\",\"other-readme-md\":\"# Other \u2014 Readme.md\\n\\n# Express.js README\\n\\n## Overview\\n\\nThe `Readme.md` file serves as the primary entry point for developers discovering and adopting Express.js. It provides essential information for installation, quick start, and contribution to the project.\\n\\n## Purpose\\n\\nThis documentation file fulfills several key functions:\\n\\n1. **Project Introduction** \u2014 Establishes Express.js as a fast, unopinionated, minimalist web framework for Node.js\\n2. **Installation Guidance** \u2014 Provides step-by-step setup instructions\\n3. **Feature Overview** \u2014 Summarizes core capabilities\\n4. **Community Resources** \u2014 Links to documentation, discussions, and governance\\n5. **Contribution Guidelines** \u2014 Directs contributors to proper channels and procedures\\n\\n## Key Sections\\n\\n### Requirements\\n\\nThe README specifies the minimum Node.js version requirement:\\n\\n```\\nNode.js 18 or higher is required\\n```\\n\\nThis is critical information for developers before installation.\\n\\n### Installation\\n\\nStandard npm installation:\\n\\n```bash\\nnpm install express\\n```\\n\\nFor new projects, developers should initialize with `npm init` first.\\n\\n### Quick Start Options\\n\\nTwo paths are documented:\\n\\n| Approach | Use Case |\\n|----------|----------|\\n| Manual setup | Simple applications, learning |\\n| `express-generator` | Full application scaffolding |\\n\\n**Generator-based setup:**\\n\\n```bash\\nnpm install -g express-generator@4\\nexpress /tmp/foo &amp;&amp; cd /tmp/foo\\nnpm install\\nnpm start\\n```\\n\\n### Core Features\\n\\nThe README highlights these capabilities:\\n\\n- **Robust routing** \u2014 URL pattern matching and HTTP method handling\\n- **High performance** \u2014 Optimized for speed\\n- **Test coverage** \u2014 Comprehensive test suite\\n- **HTTP helpers** \u2014 Built-in utilities for redirection, caching, etc.\\n- **View system** \u2014 Support for 14+ template engines via `@ladjs/consolidate`\\n- **Content negotiation** \u2014 Automatic response format handling\\n- **Application generator** \u2014 CLI tool for rapid scaffolding\\n\\n### Philosophy\\n\\nExpress.js is intentionally unopinionated:\\n\\n&gt; Express does not force you to use any specific ORM or template engine.\\n\\nThis design principle means developers can:\\n- Choose their own database layer\\n- Select any template engine\\n- Structure applications as needed\\n\\n### Contributing\\n\\nThe README directs contributors to:\\n\\n1. **[Contributing Guide]** \u2014 Technical details on contributing\\n2. **Security Issues** \u2014 Security policy for vulnerability reporting\\n3. **Running Tests** \u2014 Test suite execution via `npm test`\\n\\n### Project Governance\\n\\nTeam structure is documented:\\n\\n- **Technical Committee (TC)** \u2014 8 active members with decision-making authority\\n- **TC Emeriti** \u2014 Former TC members\\n- **Triagers** \u2014 11 active members handling issue triage\\n- **Emeritus Triagers** \u2014 Former triage team members\\n\\nGovernance details: [GOVERNANCE.md](https://github.com/expressjs/discussions/blob/HEAD/docs/GOVERNANCE.md)\\n\\n## Important Links\\n\\n| Resource | URL |\\n|----------|-----|\\n| Official Documentation | https://expressjs.com/ |\\n| GitHub Organization | https://github.com/expressjs |\\n| GitHub Discussions | https://github.com/expressjs/discussions |\\n| Migration Guide to v5 | https://expressjs.com/en/guide/migrating-5 |\\n| Security Policy | https://github.com/expressjs/express/security/policy |\\n\\n## Badge Status Indicators\\n\\nThe README displays real-time project health indicators:\\n\\n- **NPM Version** \u2014 Current published version\\n- **NPM Downloads** \u2014 Download statistics\\n- **CI Status** \u2014 GitHub Actions build status\\n- **Test Coverage** \u2014 Coveralls coverage percentage\\n- **OpenSSF Scorecard** \u2014 Security assessment score\\n\\n## License\\n\\nMIT License \u2014 see [LICENSE](LICENSE) file for full text.\\n\\n## Related Files\\n\\n- `CONTRIBUTING.md` \u2014 Detailed contribution guidelines\\n- `CODE_OF_CONDUCT.md` \u2014 Community standards\\n- `GOVERNANCE.md` \u2014 Project governance structure\\n- `Security Policy` \u2014 Vulnerability reporting procedures\\n\\n---\\n\\n*Note: This README is the primary onboarding document. For API documentation, refer to the [official Express.js documentation site](https://expressjs.com/).*\",\"other-support\":\"# Other \u2014 support\\n\\n# Test Support Module\\n\\nThe `test/support` directory provides shared utilities for the Express test suite, including environment configuration, template rendering, and supertest assertion helpers.\\n\\n## Overview\\n\\n```\\ntest/support/\\n\u251c\u2500\u2500 env.js      # Test environment configuration\\n\u251c\u2500\u2500 tmpl.js     # Simple template renderer\\n\u2514\u2500\u2500 utils.js    # Supertest assertion helpers\\n```\\n\\n## Environment Configuration (`env.js`)\\n\\nSets required environment variables before tests execute:\\n\\n```javascript\\nprocess.env.NODE_ENV = 'test';\\nprocess.env.NO_DEPRECATION = 'body-parser,express';\\n```\\n\\n- **NODE_ENV**: Ensures Express runs in test mode\\n- **NO_DEPRECATION**: Suppresses deprecation warnings from body-parser and express to keep test output clean\\n\\nThis file should be imported at the top of test files that need these settings.\\n\\n## Template Renderer (`tmpl.js`)\\n\\nA minimal template engine for test fixtures that performs variable substitution.\\n\\n### Usage\\n\\n```javascript\\nconst renderFile = require('./support/tmpl');\\n\\nrenderFile('/path/to/template.html', { name: 'Express' }, (err, result) =&gt; {\\n  // result contains the rendered template\\n});\\n```\\n\\n### Variable Syntax\\n\\nVariables use `$` prefix notation and support dot notation for nested objects:\\n\\n```\\nHello, $user.name!\\nEmail: $user.email\\n```\\n\\n### How It Works\\n\\n1. Reads the template file asynchronously\\n2. Replaces all `$variable.path` patterns with corresponding values from the options object\\n3. Returns the rendered string via callback\\n\\nThe `generateVariableLookup` function traverses nested objects using the dot-separated path:\\n\\n```javascript\\n// $user.profile.name resolves to options.user.profile.name\\n```\\n\\n## Assertion Helpers (`utils.js`)\\n\\nFactory functions that create supertest assertion callbacks. Each function returns a function that receives a supertest response object.\\n\\n### `shouldHaveBody(buf)`\\n\\nAsserts the response body matches the expected buffer (hex comparison).\\n\\n```javascript\\nconst expected = Buffer.from('Hello World');\\nrequest(app)\\n  .get('/')\\n  .expect(shouldHaveBody(expected));\\n```\\n\\nHandles both buffer and text responses internally by converting to Buffer for comparison.\\n\\n### `shouldHaveHeader(header)`\\n\\nAsserts the response includes a specific header (case-insensitive).\\n\\n```javascript\\nrequest(app)\\n  .get('/')\\n  .expect(shouldHaveHeader('Content-Type'));\\n```\\n\\n### `shouldNotHaveBody()`\\n\\nAsserts the response has no body (empty or undefined text).\\n\\n```javascript\\nrequest(app)\\n  .get('/empty')\\n  .expect(shouldNotHaveBody());\\n```\\n\\n### `shouldNotHaveHeader(header)`\\n\\nAsserts the response does not include a specific header.\\n\\n```javascript\\nrequest(app)\\n  .get('/')\\n  .expect(shouldNotHaveHeader('X-Custom-Header'));\\n```\\n\\n### `shouldSkipQuery(versionString)`\\n\\nDetermines whether to skip HTTP QUERY method tests based on Node.js version.\\n\\n```javascript\\nconst nodeVersion = process.version; // e.g., 'v20.10.0'\\nif (shouldSkipQuery(nodeVersion)) {\\n  // Skip QUERY tests\\n}\\n```\\n\\nHTTP QUERY support was added in Node.js 22. This helper ensures tests don't fail on older Node versions.\\n\\n## Usage Across Test Suite\\n\\nThe assertion helpers are used throughout the Express test files:\\n\\n| Helper | Used In |\\n|--------|---------|\\n| `shouldHaveBody` | `res.send.js`, `res.sendFile.js`, `res.download.js`, `express.static.js` |\\n| `shouldNotHaveBody` | `res.send.js`, `res.redirect.js`, `express.static.js` |\\n| `shouldHaveHeader` | `res.sendFile.js`, `express.static.js` |\\n| `shouldNotHaveHeader` | `res.jsonp.js`, `res.download.js`, `res.vary.js`, `res.send.js`, `res.redirect.js`, `res.sendFile.js`, `cookies.js`, `express.static.js` |\\n\\n## Adding New Assertions\\n\\nWhen adding new helpers, follow the existing pattern:\\n\\n```javascript\\nfunction shouldHaveCustomProperty(prop) {\\n  return function (res) {\\n    assert.ok(prop in res.body, 'should have property ' + prop);\\n  };\\n}\\n\\nexports.shouldHaveCustomProperty = shouldHaveCustomProperty;\\n```\\n\\nAll assertion helpers:\\n1. Return a function that accepts a supertest response object\\n2. Use Node's built-in `assert` module\\n3. Include descriptive error messages\",\"overview\":\"# express \u2014 Wiki\\n\\n# Express\\n\\n**Fast, unopinionated, minimalist web framework for Node.js**\\n\\nExpress provides a thin layer of fundamental web application features without obscuring Node.js features you already know. It's designed to build web applications and APIs with minimal overhead, giving you the flexibility to structure your project however you see fit.\\n\\n## Architecture at a Glance\\n\\nExpress is built around a small, focused core that handles HTTP request/response processing, middleware orchestration, and routing. Everything else\u2014template rendering, static file serving, session management\u2014is either built on top of this core or provided through extensions.\\n\\n```mermaid\\ngraph TD\\n    A[HTTP Request] --&gt; B[Express App]\\n    B --&gt; C[Middleware Stack]\\n    C --&gt; D[Router]\\n    D --&gt; E[Route Handlers]\\n    E --&gt; F[Response]\\n    \\n    B --&gt; G[Request Prototype]\\n    B --&gt; H[Response Prototype]\\n    \\n    I[Views &amp; Templates] --&gt; E\\n    J[Static Files] --&gt; C\\n    K[Error Handling] --&gt; C\\n```\\n\\n## Core Concepts\\n\\nThe **[Core Framework](core-framework.md)** is the heart of Express. It creates the application instance, extends Node's `http.IncomingMessage` and `http.ServerResponse` with useful properties and methods, and implements the middleware system that makes Express so flexible. When you call `express()`, you're getting an application object that inherits from EventEmitter and manages a stack of middleware functions.\\n\\nRouting is handled lazily\u2014the router isn't initialized until the first route is defined, keeping the minimal footprint Express is known for.\\n\\n## Learning by Example\\n\\nThe repository includes a rich set of examples organized by feature area:\\n\\n- **[Basic Usage](basic-usage.md)** \u2014 Start here. The `hello-world` example shows the minimal Express server in about 10 lines, while the `search` example demonstrates a more realistic application with Redis integration.\\n\\n- **[Routing Patterns](routing-patterns.md)** \u2014 Once you're comfortable with basics, explore patterns for organizing routes: multi-router setups for API versioning, parameter preprocessing, RESTful resource conventions, and declarative route mapping.\\n\\n- **[Views &amp; Templates](views-templates.md)** \u2014 Express supports any template engine that follows the `(path, options, callback)` signature. This module shows how to register engines, render views, and pass data to templates.\\n\\n- **[Static Files &amp; Downloads](static-files-downloads.md)** \u2014 Serving CSS, JavaScript, and images with `express.static()`, plus triggering file downloads with proper error handling.\\n\\n- **[Error Handling](error-handling.md)** \u2014 Understanding Express's error-handling middleware is crucial for production applications. Learn the difference between regular and error-handling middleware, and how to structure error responses.\\n\\n- **[Web Services &amp; APIs](web-services-apis.md)** \u2014 Building REST APIs? This covers content negotiation, API key validation, virtual hosting for multi-tenant applications, and proper error responses.\\n\\n- **[Authentication &amp; Sessions](authentication-sessions.md)** \u2014 Example implementations for password-based authentication, cookie sessions, and Redis-backed session storage.\\n\\n## Getting Started\\n\\n### Prerequisites\\n\\n- Node.js (see `.nvmrc` or `package.json` for supported versions)\\n- npm or yarn\\n\\n### Installation\\n\\n```bash\\ngit clone https://github.com/expressjs/express.git\\ncd express\\nnpm install\\n```\\n\\n### Running Tests\\n\\nExpress has a comprehensive test suite. Run tests with:\\n\\n```bash\\nnpm test           # Run all tests\\nnpm run test-ci    # CI mode\\nnpm run test-cov   # With coverage\\n```\\n\\nCode quality is enforced via linting:\\n\\n```bash\\nnpm run lint       # Check for issues\\nnpm run lint:fix   # Auto-fix issues\\n```\\n\\n## Philosophy\\n\\nExpress is intentionally unopinionated. It provides the essential tools\u2014routing, middleware, request/response helpers\u2014without prescribing how you should structure your application, which template engine to use, or how to handle authentication. This minimalism is why Express works equally well for a simple API, a full-featured web application, or as a foundation for other frameworks.\\n\\n## Contributing\\n\\nThis project follows a [Code of Conduct](https://github.com/expressjs/express/blob/master/Code-of Conduct.md). See the repository's contributing guidelines and security policy for details on submitting pull requests and reporting vulnerabilities.\",\"routing-patterns\":\"# Routing Patterns\\n\\n# Routing Patterns\\n\\nThis module demonstrates several patterns for organizing and structuring routes in Express applications. Each example showcases a different approach to handling common routing scenarios.\\n\\n## Overview\\n\\nThe examples in this module cover:\\n\\n| Pattern | Location | Purpose |\\n|---------|----------|---------|\\n| Multi-Router | `multi-router/` | API versioning with separate routers |\\n| Route Parameters | `params/` | Parameter preprocessing and validation |\\n| Resource Routing | `resource/` | RESTful resource conventions |\\n| Route Mapping | `route-map/` | Declarative route configuration |\\n| Route Middleware | `route-middleware/` | Authentication and authorization chains |\\n| Route Separation | `route-separation/` | Modular route organization |\\n\\n---\\n\\n## Multi-Router Pattern\\n\\nOrganize multiple API versions using separate `Router` instances mounted at different paths.\\n\\n### Structure\\n\\n```\\nmulti-router/\\n\u251c\u2500\u2500 index.js              # Main app, mounts routers\\n\u2514\u2500\u2500 controllers/\\n    \u251c\u2500\u2500 api_v1.js         # API v1 routes\\n    \u2514\u2500\u2500 api_v2.js         # API v2 routes\\n```\\n\\n### Implementation\\n\\n**Main application** (`index.js`):\\n```javascript\\nvar app = express();\\n\\napp.use('/api/v1', require('./controllers/api_v1'));\\napp.use('/api/v2', require('./controllers/api_v2'));\\n```\\n\\n**Router modules** (`controllers/api_v1.js`):\\n```javascript\\nvar apiv1 = express.Router();\\n\\napiv1.get('/', function(req, res) {\\n  res.send('Hello from APIv1 root route.');\\n});\\n\\napiv1.get('/users', function(req, res) {\\n  res.send('List of APIv1 users.');\\n});\\n\\nmodule.exports = apiv1;\\n```\\n\\n### Resulting Routes\\n\\n| Path | Handler |\\n|------|---------|\\n| `/api/v1/` | APIv1 root |\\n| `/api/v1/users` | APIv1 users list |\\n| `/api/v2/` | APIv2 root |\\n| `/api/v2/users` | APIv2 users list |\\n\\n---\\n\\n## Route Parameters Pattern\\n\\nUse `app.param()` to preprocess route parameters before reaching route handlers.\\n\\n### Parameter Callbacks\\n\\nThe `app.param()` method registers middleware that executes when a named parameter appears in any route:\\n\\n```javascript\\n// Convert :to and :from to integers\\napp.param(['to', 'from'], function(req, res, next, num, name){\\n  req.params[name] = parseInt(num, 10);\\n  if( isNaN(req.params[name]) ){\\n    next(createError(400, 'failed to parseInt '+num));\\n  } else {\\n    next();\\n  }\\n});\\n\\n// Load user by id\\napp.param('user', function(req, res, next, id){\\n  req.user = users[id];\\n  if (req.user) {\\n    next();\\n  } else {\\n    next(createError(404, 'failed to find user'));\\n  }\\n});\\n```\\n\\n### Parameter Callback Signature\\n\\n```javascript\\nfunction(req, res, next, value, name)\\n```\\n\\n| Argument | Description |\\n|----------|-------------|\\n| `req` | Request object |\\n| `res` | Response object |\\n| `next` | Callback to continue |\\n| `value` | The parameter value from URL |\\n| `name` | The parameter name |\\n\\n### Routes Using Parameters\\n\\n```javascript\\n// Uses :user param (triggers user loading)\\napp.get('/user/:user', function (req, res) {\\n  res.send('user ' + req.user.name);\\n});\\n\\n// Uses :from and :to params (triggers integer conversion)\\napp.get('/users/:from-:to', function (req, res) {\\n  var from = req.params.from;\\n  var to = req.params.to;\\n  var names = users.map(function(user){ return user.name; });\\n  res.send('users ' + names.slice(from, to + 1).join(', '));\\n});\\n```\\n\\n---\\n\\n## Resource Routing Pattern\\n\\nCreate a custom `app.resource()` method that maps HTTP verbs to controller actions following REST conventions.\\n\\n### Resource Method Implementation\\n\\n```javascript\\napp.resource = function(path, obj) {\\n  this.get(path, obj.index);\\n  this.get(path + '/:a..:b{.:format}', function(req, res){\\n    var a = parseInt(req.params.a, 10);\\n    var b = parseInt(req.params.b, 10);\\n    var format = req.params.format;\\n    obj.range(req, res, a, b, format);\\n  });\\n  this.get(path + '/:id', obj.show);\\n  this.delete(path + '/:id', function(req, res){\\n    var id = parseInt(req.params.id, 10);\\n    obj.destroy(req, res, id);\\n  });\\n};\\n```\\n\\n### Controller Structure\\n\\n```javascript\\nvar User = {\\n  index: function(req, res){\\n    res.send(users);\\n  },\\n  show: function(req, res){\\n    res.send(users[req.params.id] || { error: 'Cannot find user' });\\n  },\\n  destroy: function(req, res, id){\\n    var destroyed = id in users;\\n    delete users[id];\\n    res.send(destroyed ? 'destroyed' : 'Cannot find user');\\n  },\\n  range: function(req, res, a, b, format){\\n    var range = users.slice(a, b + 1);\\n    switch (format) {\\n      case 'json':\\n        res.send(range);\\n        break;\\n      case 'html':\\n      default:\\n        var html = '\n' + range.map(function(user){\\n          return '\n' + user.name + '&lt;\\/li&gt;';\\n        }).join('\\\\n') + '&lt;\\/ul&gt;';\\n        res.send(html);\\n        break;\\n    }\\n  }\\n};\\n```\\n\\n### Generated Routes\\n\\n| HTTP Method | Path | Action |\\n|-------------|------|--------|\\n| GET | `/users` | `index` |\\n| GET | `/users/:id` | `show` |\\n| GET | `/users/:a..:b` | `range` |\\n| GET | `/users/:a..:b.json` | `range` (JSON format) |\\n| DELETE | `/users/:id` | `destroy` |\\n\\n---\\n\\n## Route Mapping Pattern\\n\\nDefine routes declaratively using nested objects that map to handler functions.\\n\\n### Map Implementation\\n\\n```javascript\\napp.map = function(a, route){\\n  route = route || '';\\n  for (var key in a) {\\n    switch (typeof a[key]) {\\n      // { '/path': { ... }}\\n      case 'object':\\n        app.map(a[key], route + key);\\n        break;\\n      // get: function(){ ... }\\n      case 'function':\\n        if (verbose) console.log('%s %s', key, route);\\n        app[key](route, a[key]);\\n        break;\\n    }\\n  }\\n};\\n```\\n\\n### Declarative Route Definition\\n\\n```javascript\\napp.map({\\n  '/users': {\\n    get: users.list,\\n    delete: users.delete,\\n    '/:uid': {\\n      get: users.get,\\n      '/pets': {\\n        get: pets.list,\\n        '/:pid': {\\n          delete: pets.delete\\n        }\\n      }\\n    }\\n  }\\n});\\n```\\n\\n### Generated Routes\\n\\n| HTTP Method | Path | Handler |\\n|-------------|------|---------|\\n| GET | `/users` | `users.list` |\\n| DELETE | `/users` | `users.delete` |\\n| GET | `/users/:uid` | `users.get` |\\n| GET | `/users/:uid/pets` | `pets.list` |\\n| DELETE | `/users/:uid/pets/:pid` | `pets.delete` |\\n\\n---\\n\\n## Route Middleware Pattern\\n\\nChain middleware functions for authentication, authorization, and data loading.\\n\\n### Middleware Functions\\n\\n```javascript\\n// Load user from database\\nfunction loadUser(req, res, next) {\\n  var user = users[req.params.id];\\n  if (user) {\\n    req.user = user;\\n    next();\\n  } else {\\n    next(new Error('Failed to load user ' + req.params.id));\\n  }\\n}\\n\\n// Restrict to the authenticated user\\nfunction andRestrictToSelf(req, res, next) {\\n  if (req.authenticatedUser.id === req.user.id) {\\n    next();\\n  } else {\\n    next(new Error('Unauthorized'));\\n  }\\n}\\n\\n// Restrict to specific role (factory function)\\nfunction andRestrictTo(role) {\\n  return function(req, res, next) {\\n    if (req.authenticatedUser.role === role) {\\n      next();\\n    } else {\\n      next(new Error('Unauthorized'));\\n    }\\n  }\\n}\\n```\\n\\n### Middleware Chains in Routes\\n\\n```javascript\\n// Chain: load user \u2192 render\\napp.get('/user/:id', loadUser, function(req, res){\\n  res.send('Viewing user ' + req.user.name);\\n});\\n\\n// Chain: load user \u2192 check self \u2192 render\\napp.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){\\n  res.send('Editing user ' + req.user.name);\\n});\\n\\n// Chain: load user \u2192 check role \u2192 render\\napp.delete('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){\\n  res.send('Deleted user ' + req.user.name);\\n});\\n```\\n\\n### Request Flow\\n\\n```mermaid\\nflowchart LR\\n    A[Request] --&gt; B[Auth Middleware]\\n    B --&gt; C[loadUser]\\n    C --&gt; D{Authorization}\\n    D --&gt;|Authorized| E[Route Handler]\\n    D --&gt;|Denied| F[Error]\\n```\\n\\n---\\n\\n## Route Separation Pattern\\n\\nOrganize routes into separate modules by domain (users, posts, etc.) with shared configuration.\\n\\n### Directory Structure\\n\\n```\\nroute-separation/\\n\u251c\u2500\u2500 index.js          # Main app with route mounting\\n\u251c\u2500\u2500 site.js           # Site-level routes\\n\u251c\u2500\u2500 user.js           # User routes and handlers\\n\u251c\u2500\u2500 post.js           # Post routes and handlers\\n\u251c\u2500\u2500 public/\\n\u2502   \u2514\u2500\u2500 style.css     # Static assets\\n\u2514\u2500\u2500 views/\\n    \u251c\u2500\u2500 header.ejs\\n    \u251c\u2500\u2500 footer.ejs\\n    \u251c\u2500\u2500 index.ejs\\n    \u251c\u2500\u2500 posts/\\n    \u2502   \u2514\u2500\u2500 index.ejs\\n    \u2514\u2500\u2500 users/\\n        \u251c\u2500\u2500 index.ejs\\n        \u251c\u2500\u2500 view.ejs\\n        \u2514\u2500\u2500 edit.ejs\\n```\\n\\n### Main Application (`index.js`)\\n\\n```javascript\\nvar app = express();\\n\\n// Configuration\\napp.set('view engine', 'ejs');\\napp.set('views', path.join(__dirname, 'views'));\\n\\n// Middleware\\napp.use(methodOverride('_method'));\\napp.use(cookieParser());\\napp.use(express.urlencoded({ extended: true }));\\napp.use(express.static(path.join(__dirname, 'public')));\\n\\n// Routes organized by domain\\napp.get('/', site.index);\\napp.get('/users', user.list);\\napp.all('/user/:id{/:op}', user.load);\\napp.get('/user/:id', user.view);\\napp.get('/user/:id/view', user.view);\\napp.get('/user/:id/edit', user.edit);\\napp.put('/user/:id/edit', user.update);\\napp.get('/posts', post.list);\\n```\\n\\n### Module Exports Pattern (`user.js`)\\n\\n```javascript\\nvar users = [\\n  { name: 'TJ', email: 'tj@vision-media.ca' },\\n  { name: 'Tobi', email: 'tobi@vision-media.ca' }\\n];\\n\\nexports.list = function(req, res){\\n  res.render('users', { title: 'Users', users: users });\\n};\\n\\nexports.load = function(req, res, next){\\n  var id = req.params.id;\\n  req.user = users[id];\\n  if (req.user) {\\n    next();\\n  } else {\\n    var err = new Error('cannot find user ' + id);\\n    err.status = 404;\\n    next(err);\\n  }\\n};\\n\\nexports.view = function(req, res){\\n  res.render('users/view', {\\n    title: 'Viewing user ' + req.user.name,\\n    user: req.user\\n  });\\n};\\n```\\n\\n### Shared Middleware with `app.all()`\\n\\nThe `app.all('/user/:id{/:op}', user.load)` pattern runs `user.load` for all HTTP methods matching the path, enabling shared data loading across multiple routes.\\n\\n---\\n\\n## Pattern Selection Guide\\n\\n| Scenario | Recommended Pattern |\\n|----------|---------------------|\\n| API versioning | Multi-Router |\\n| Parameter validation | Route Parameters |\\n| RESTful resources | Resource Routing |\\n| Configuration-heavy apps | Route Mapping |\\n| Auth/permission chains | Route Middleware |\\n| Large applications | Route Separation |\\n\\n## Common Patterns Across Examples\\n\\n### Error Handling in Middleware\\n\\n```javascript\\n// Pass errors to Express error handler\\nif (condition) {\\n  next();\\n} else {\\n  next(new Error('Description'));\\n  // or with status\\n  var err = new Error('Not found');\\n  err.status = 404;\\n  next(err);\\n}\\n```\\n\\n### Optional Route Segments\\n\\n```javascript\\n// Optional :op parameter\\napp.all('/user/:id{/:op}', user.load);\\n```\\n\\n### Range Parameters\\n\\n```javascript\\n// Custom range syntax\\napp.get('/users/:from-:to', handler);\\napp.get('/users/:a..:b{.:format}', handler);\\n```\",\"static-files-downloads\":\"# Static Files &amp; Downloads\\n\\n# Static Files &amp; Downloads Module\\n\\nThis module provides example implementations demonstrating two approaches to file handling in Express: serving static assets and triggering file downloads.\\n\\n## Overview\\n\\nThe module consists of two independent example applications:\\n\\n| Application | Purpose | Key Method |\\n|-------------|---------|------------|\\n| `static-files` | Serve static assets (CSS, JS, images) | `express.static()` |\\n| `downloads` | Trigger file downloads with error handling | `res.download()` |\\n\\n---\\n\\n## Static Files Server\\n\\n**Location:** `examples/static-files/index.js`\\n\\n### How It Works\\n\\nThe static files server demonstrates three patterns for serving static assets using Express's built-in middleware.\\n\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\n\\nThis middleware intercepts requests and checks if a file matching `req.path` exists in the specified directory. If found, it streams the file as the response.\\n\\n### Serving Patterns\\n\\n**1. Basic Static Serving**\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\nServes files directly from `./public`. A request for `/js/app.js` resolves to `./public/js/app.js`.\\n\\n**2. Mounted Path Prefix**\\n```javascript\\napp.use('/static', express.static(path.join(__dirname, 'public')));\\n```\\nAdds a URL prefix. A request for `/static/js/app.js` serves `./public/js/app.js` \u2014 the `/static` prefix is stripped before resolving.\\n\\n**3. Multiple Directories**\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public', 'css')));\\n```\\nServes files from a nested directory at the root path. A request for `/style.css` serves `./public/css/style.css`.\\n\\n### File Structure\\n\\n```\\nstatic-files/\\n\u251c\u2500\u2500 index.js\\n\u2514\u2500\u2500 public/\\n    \u251c\u2500\u2500 hello.txt\\n    \u251c\u2500\u2500 css/\\n    \u2502   \u2514\u2500\u2500 style.css\\n    \u2514\u2500\u2500 js/\\n        \u2514\u2500\u2500 app.js\\n```\\n\\n### Endpoints\\n\\n| URL | File Served |\\n|-----|-------------|\\n| `GET /hello.txt` | `public/hello.txt` |\\n| `GET /js/app.js` | `public/js/app.js` |\\n| `GET /css/style.css` | `public/css/style.css` |\\n| `GET /static/hello.txt` | `public/hello.txt` (via mounted path) |\\n\\n---\\n\\n## File Downloads Server\\n\\n**Location:** `examples/downloads/index.js`\\n\\n### How It Works\\n\\nThe downloads server uses `res.download()` to prompt browsers to save files rather than display them.\\n\\n```javascript\\napp.get('/files/*file', function (req, res, next) {\\n  res.download(req.params.file.join('/'), { root: FILES_DIR }, function (err) {\\n    if (!err) return;\\n    if (err.status !== 404) return next(err);\\n    res.statusCode = 404;\\n    res.send('Cant find that file, sorry!');\\n  });\\n});\\n```\\n\\n### Route Pattern Breakdown\\n\\nThe route `/files/*file` uses a wildcard parameter:\\n- `*file` captures all path segments after `/files/`\\n- `req.params.file` is an array of path segments\\n- `req.params.file.join('/')` reconstructs the file path\\n\\n**Example:** Request to `/files/notes/groceries.txt` produces:\\n- `req.params.file = ['notes', 'groceries.txt']`\\n- Resolved path: `FILES_DIR/notes/groceries.txt`\\n\\n### Error Handling\\n\\nThe callback to `res.download()` handles three scenarios:\\n\\n| Condition | Behavior |\\n|-----------|----------|\\n| No error | File sent successfully, return early |\\n| Non-404 error | Pass to `next(err)` for Express error handling |\\n| 404 error | Send custom \\\"file not found\\\" message |\\n\\n### File Structure\\n\\n```\\ndownloads/\\n\u251c\u2500\u2500 index.js\\n\u2514\u2500\u2500 files/\\n    \u251c\u2500\u2500 amazing.txt\\n    \u251c\u2500\u2500 CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\\n    \u2514\u2500\u2500 notes/\\n        \u2514\u2500\u2500 groceries.txt\\n```\\n\\n### Endpoints\\n\\n| URL | Result |\\n|-----|--------|\\n| `GET /` | HTML page with download links |\\n| `GET /files/amazing.txt` | Downloads `files/amazing.txt` |\\n| `GET /files/notes/groceries.txt` | Downloads `files/notes/groceries.txt` |\\n| `GET /files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt` | Downloads file with Unicode filename |\\n| `GET /files/missing.txt` | Custom 404 response |\\n\\n---\\n\\n## Key Differences\\n\\n```mermaid\\nflowchart LR\\n    subgraph Static[\\\"express.static()\\\"]\\n        A[Request] --&gt; B{File exists?}\\n        B --&gt;|Yes| C[Stream file]\\n        B --&gt;|No| D[Next middleware]\\n    end\\n    \\n    subgraph Download[\\\"res.download()\\\"]\\n        E[Request] --&gt; F{File exists?}\\n        F --&gt;|Yes| G[Set headerstrigger download]\\n        F --&gt;|No| H[Custom error handling]\\n    end\\n```\\n\\n| Aspect | `express.static()` | `res.download()` |\\n|--------|-------------------|------------------|\\n| Use case | Assets (CSS, JS, images) | User downloads |\\n| Browser behavior | Display inline | Save dialog |\\n| Content-Disposition | Not set | `attachment` |\\n| Error handling | Automatic 404 | Manual via callback |\\n| Scope | Middleware (all routes) | Route handler (specific paths) |\\n\\n---\\n\\n## Running the Examples\\n\\n**Static Files:**\\n```bash\\nnode examples/static-files/index.js\\n# Listening on port 3000\\n# Test: GET /hello.txt, GET /js/app.js, GET /css/style.css\\n```\\n\\n**Downloads:**\\n```bash\\nnode examples/downloads/index.js\\n# Express started on port 3000\\n# Navigate to http://localhost:3000 for download links\\n```\\n\\n---\\n\\n## Security Considerations\\n\\nThe downloads example uses `{ root: FILES_DIR }` to prevent directory traversal attacks. Without this option, a malicious path like `/files/../../../etc/passwd` could access files outside the intended directory.\\n\\nWith `root` specified, Express resolves paths relative to `FILES_DIR` and rejects attempts to escape it.\",\"views-templates\":\"# Views &amp; Templates\\n\\n# Views &amp; Templates\\n\\nExpress provides a flexible view system that supports multiple template engines, custom view resolution, and various patterns for passing data to templates. This module demonstrates the core concepts through practical examples.\\n\\n## Core Concepts\\n\\n### Template Engine Registration\\n\\nExpress uses a callback-based system for template engines. Register an engine using `app.engine(ext, callback)`:\\n\\n```javascript\\n// Register EJS to handle .html files\\napp.engine('.html', require('ejs').__express);\\n\\n// Custom markdown engine\\napp.engine('md', function(path, options, fn){\\n  fs.readFile(path, 'utf8', function(err, str){\\n    if (err) return fn(err);\\n    var html = marked.parse(str).replace(/\\\\{([^}]+)\\\\}/g, function(_, name){\\n      return escapeHtml(options[name] || '');\\n    });\\n    fn(null, html);\\n  });\\n});\\n```\\n\\nThe engine callback receives:\\n- `path` - the absolute path to the template file\\n- `options` - data locals passed to the view\\n- `fn` - callback `(err, renderedString)`\\n\\n### View Configuration Settings\\n\\n```javascript\\n// Set views directory (default: process.cwd() + '/views')\\napp.set('views', path.join(__dirname, 'views'));\\n\\n// Set default engine extension (avoids specifying extension in res.render)\\napp.set('view engine', 'html');\\n\\n// Register custom View constructor (advanced)\\napp.set('view', GithubView);\\n```\\n\\n### Rendering Views\\n\\n```javascript\\n// Basic render\\nres.render('users');\\n\\n// With locals\\nres.render('users', { \\n  users: users, \\n  title: \\\"User List\\\" \\n});\\n\\n// With callback for custom handling\\nres.render('template', { title: 'Page' }, function(err, html) {\\n  if (err) return next(err);\\n  // Process html before sending\\n});\\n```\\n\\n## View Resolution Flow\\n\\n```mermaid\\nflowchart TD\\n    A[res.render 'template'] --&gt; B{View engine set?}\\n    B --&gt;|Yes| C[Use default engine]\\n    B --&gt;|No| D{Extension in name?}\\n    D --&gt;|Yes| E[Lookup engine by extension]\\n    D --&gt;|No| F[Throw error]\\n    C --&gt; G[Resolve path in views directory]\\n    E --&gt; G\\n    G --&gt; H[Read template file]\\n    H --&gt; I[Compile with engine]\\n    I --&gt; J[Merge app.locals + res.locals + passed locals]\\n    J --&gt; K[Return rendered HTML]\\n```\\n\\n## Passing Data to Views\\n\\n### Approach 1: Direct Locals in res.render()\\n\\n```javascript\\napp.get('/', function(req, res, next){\\n  User.count(function(err, count){\\n    if (err) return next(err);\\n    User.all(function(err, users){\\n      if (err) return next(err);\\n      res.render('index', {\\n        title: 'Users',\\n        count: count,\\n        users: users.filter(ferrets)\\n      });\\n    });\\n  });\\n});\\n```\\n\\n### Approach 2: Middleware with req Properties\\n\\n```javascript\\nfunction count(req, res, next) {\\n  User.count(function(err, count){\\n    if (err) return next(err);\\n    req.count = count;\\n    next();\\n  });\\n}\\n\\nfunction users(req, res, next) {\\n  User.all(function(err, users){\\n    if (err) return next(err);\\n    req.users = users;\\n    next();\\n  });\\n}\\n\\napp.get('/middleware', count, users, function (req, res) {\\n  res.render('index', {\\n    title: 'Users',\\n    count: req.count,\\n    users: req.users.filter(ferrets)\\n  });\\n});\\n```\\n\\n### Approach 3: Middleware with res.locals\\n\\n`res.locals` is automatically merged into the view context:\\n\\n```javascript\\nfunction count(req, res, next) {\\n  User.count(function(err, count){\\n    if (err) return next(err);\\n    res.locals.count = count;\\n    next();\\n  });\\n}\\n\\nfunction users(req, res, next) {\\n  User.all(function(err, users){\\n    if (err) return next(err);\\n    res.locals.users = users.filter(ferrets);\\n    next();\\n  });\\n}\\n\\napp.get('/middleware-locals', count, users, function (req, res) {\\n  // Only need to pass title - count and users already in res.locals\\n  res.render('index', { title: 'Users' });\\n});\\n```\\n\\n### Global Locals via Middleware\\n\\n```javascript\\n// Make data available to all views\\napp.use(function(req, res, next){\\n  res.locals.user = req.user;\\n  res.locals.sess = req.session;\\n  next();\\n});\\n\\n// Or scoped to specific paths\\napp.use('/api', function(req, res, next){\\n  res.locals.user = req.user;\\n  next();\\n});\\n```\\n\\n## Custom View Constructor\\n\\nFor advanced use cases like loading templates from a database or remote source, implement a custom View class:\\n\\n```javascript\\nfunction GithubView(name, options){\\n  this.name = name;\\n  options = options || {};\\n  this.engine = options.engines[path.extname(name)];\\n  // options.root is the app.set('views') setting\\n  this.path = '/' + options.root + '/master/' + name;\\n}\\n\\nGithubView.prototype.render = function(options, fn){\\n  var self = this;\\n  https.get({\\n    host: 'raw.githubusercontent.com',\\n    path: this.path\\n  }, function(res) {\\n    var buf = '';\\n    res.setEncoding('utf8');\\n    res.on('data', function(str){ buf += str });\\n    res.on('end', function(){\\n      self.engine(buf, options, fn);\\n    });\\n  });\\n};\\n\\n// Register the custom view\\napp.set('view', GithubView);\\napp.set('views', 'expressjs/express');\\n```\\n\\nThe View constructor receives:\\n- `name` - the template name passed to `res.render()`\\n- `options` - contains `engines` (map of registered engines) and `root` (views directory)\\n\\nThe `render(options, fn)` method must call `fn(err, html)` with the rendered output.\\n\\n## MVC Pattern with Per-Controller Views\\n\\nThe MVC example demonstrates organizing views by controller:\\n\\n```\\ncontrollers/\\n\u251c\u2500\u2500 user/\\n\u2502   \u251c\u2500\u2500 index.js      # Controller logic\\n\u2502   \u2514\u2500\u2500 views/\\n\u2502       \u251c\u2500\u2500 list.hbs\\n\u2502       \u251c\u2500\u2500 show.hbs\\n\u2502       \u2514\u2500\u2500 edit.hbs\\n\u251c\u2500\u2500 pet/\\n\u2502   \u251c\u2500\u2500 index.js\\n\u2502   \u2514\u2500\u2500 views/\\n\u2502       \u251c\u2500\u2500 show.ejs\\n\u2502       \u2514\u2500\u2500 edit.ejs\\n```\\n\\nEach controller configures its own view engine:\\n\\n```javascript\\n// controllers/user/index.js\\nexports.engine = 'hbs';  // Use Handlebars for this controller\\n\\n// In the boot loader:\\nif (obj.engine) app.set('view engine', obj.engine);\\napp.set('views', path.join(__dirname, '..', 'controllers', name, 'views'));\\n```\\n\\n### Route Generation from Controller Exports\\n\\nControllers export methods that map to conventional routes:\\n\\n| Export | Method | Generated Route |\\n|--------|--------|-----------------|\\n| `index` | GET | `/` |\\n| `list` | GET | `/:name+s` |\\n| `show` | GET | `/:name/:name_id` |\\n| `edit` | GET | `/:name/:name_id/edit` |\\n| `update` | PUT | `/:name/:name_id` |\\n| `create` | POST | `/:name` |\\n\\n```javascript\\n// controllers/pet/index.js\\nexports.before = function(req, res, next){\\n  var pet = db.pets[req.params.pet_id];\\n  if (!pet) return next('route');\\n  req.pet = pet;\\n  next();\\n};\\n\\nexports.show = function(req, res, next){\\n  res.render('show', { pet: req.pet });\\n};\\n```\\n\\nThe `before` middleware runs before the handler, useful for loading resources.\\n\\n## Template Examples\\n\\n### EJS with Partials\\n\\n```html\\n&lt;%- include('header.html') -%&gt;\\n\\n\nUsers&lt;\\/h1&gt;\\n\n\\n  &lt;% users.forEach(function(user){ %&gt;\\n    \n&lt;%= user.name %&gt; &lt;&lt;%= user.email %&gt;&gt;&lt;\\/li&gt;\\n  &lt;% }) %&gt;\\n&lt;\\/ul&gt;\\n\\n&lt;%- include('footer.html') -%&gt;\\n```\\n\\n### Handlebars Conditionals\\n\\n```html\\n{{#if user.pets.length}}\\n  \n\\n    {{#each user.pets}}\\n      \n{{name}}&lt;\\/a&gt;&lt;\\/li&gt;\\n    {{/each}}\\n  &lt;\\/ul&gt;\\n{{else}}\\n  \nNo pets!&lt;\\/p&gt;\\n{{/if}}\\n```\\n\\n### Markdown with Variable Substitution\\n\\n```markdown\\n# {title}\\n\\nJust an example view rendered with _markdown_.\\n```\\n\\nVariables are replaced via regex: `/\\\\{([^}]+)\\\\}/g`\\n\\n## Flash Messages Pattern\\n\\nStore messages in the session and expose to views via middleware:\\n\\n```javascript\\n// Custom response method\\napp.response.message = function(msg){\\n  var sess = this.req.session;\\n  sess.messages = sess.messages || [];\\n  sess.messages.push(msg);\\n  return this;\\n};\\n\\n// Expose to views\\napp.use(function(req, res, next){\\n  var msgs = req.session.messages || [];\\n  res.locals.messages = msgs;\\n  res.locals.hasMessages = !!msgs.length;\\n  next();\\n  req.session.messages = [];  // Clear after exposing\\n});\\n```\\n\\nIn the template:\\n\\n```html\\n{{#if hasMessages}}\\n  \n\\n    {{#each messages}}\\n      \n{{this}}&lt;\\/li&gt;\\n    {{/each}}\\n  &lt;\\/ul&gt;\\n{{/if}}\\n```\\n\\n## Error Views\\n\\n```javascript\\n// 500 error handler\\napp.use(function(err, req, res, next){\\n  console.error(err.stack);\\n  res.status(500).render('5xx');\\n});\\n\\n// 404 handler (must be last)\\napp.use(function(req, res, next){\\n  res.status(404).render('404', { url: req.originalUrl });\\n});\\n```\",\"web-services-apis\":\"# Web Services &amp; APIs\\n\\n# Web Services &amp; APIs Module\\n\\nThis module demonstrates production-ready patterns for building RESTful web services and APIs with Express.js, covering content negotiation, virtual hosting, API key validation, and error handling.\\n\\n## Overview\\n\\nThe module contains three interconnected examples that showcase different aspects of API development:\\n\\n| Example | Purpose |\\n|---------|---------|\\n| `content-negotiation` | Multi-format response handling (HTML, JSON, text) |\\n| `web-service` | REST API with authentication middleware and error handling |\\n| `vhost` | Virtual hosting for multi-tenant applications |\\n\\n## Content Negotiation\\n\\nThe content negotiation example demonstrates how to serve the same data in multiple formats based on the client's `Accept` header.\\n\\n### Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502                     Client Request                          \u2502\\n\u2502                  Accept: text/html                          \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                          \u2502\\n                          \u25bc\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502                    res.format()                             \u2502\\n\u2502         Inspects Accept header and routes                   \u2502\\n\u2502         to appropriate handler                              \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n           \u2502          \u2502             \u2502\\n     html()\u2502    text()\u2502       json()\u2502\\n           \u25bc          \u25bc             \u25bc\\n      HTML list   Plain text    JSON array\\n```\\n\\n### Two Implementation Patterns\\n\\n**Pattern 1: Inline Handlers** (`/` endpoint)\\n\\n```javascript\\napp.get('/', function(req, res){\\n  res.format({\\n    html: function(){ /* render HTML */ },\\n    text: function(){ /* render plain text */ },\\n    json: function(){ res.json(users); }\\n  });\\n});\\n```\\n\\n**Pattern 2: Declarative Middleware** (`/users` endpoint)\\n\\nThe `format()` helper function abstracts handler definitions into a separate module:\\n\\n```javascript\\nfunction format(path) {\\n  var obj = require(path);\\n  return function(req, res){\\n    res.format(obj);\\n  };\\n}\\n\\napp.get('/users', format('./users'));\\n```\\n\\nThe `users.js` module exports format handlers as separate functions:\\n\\n```javascript\\nexports.html = function(req, res){ /* ... */ };\\nexports.text = function(req, res){ /* ... */ };\\nexports.json = function(req, res){ res.json(users); };\\n```\\n\\n### Data Layer\\n\\nThe `db.js` module provides a simple in-memory data store:\\n\\n```javascript\\nvar users = [];\\nusers.push({ name: 'Tobi' });\\nusers.push({ name: 'Loki' });\\nusers.push({ name: 'Jane' });\\nmodule.exports = users;\\n```\\n\\n## Web Service API\\n\\nThe `web-service` example demonstrates a complete REST API with middleware-based authentication and structured error handling.\\n\\n### Request Flow\\n\\n```mermaid\\nflowchart TD\\n    A[Request] --&gt; B{API Key Present?}\\n    B --&gt;|No| C[400: api key required]\\n    B --&gt;|Yes| D{Valid Key?}\\n    D --&gt;|No| E[401: invalid api key]\\n    D --&gt;|Yes| F[Route Handler]\\n    F --&gt; G{Data Found?}\\n    G --&gt;|Yes| H[200: JSON Response]\\n    G --&gt;|No| I[404: Not Found]\\n    \\n    C --&gt; J[Error Handler]\\n    E --&gt; J\\n    I --&gt; K[404 Middleware]\\n```\\n\\n### API Key Validation Middleware\\n\\nThe middleware is mounted at `/api`, ensuring all API routes require authentication:\\n\\n```javascript\\napp.use('/api', function(req, res, next){\\n  var key = req.query['api-key'];\\n  \\n  if (!key) return next(error(400, 'api key required'));\\n  if (apiKeys.indexOf(key) === -1) return next(error(401, 'invalid api key'));\\n  \\n  req.key = key;  // Store for route access\\n  next();\\n});\\n```\\n\\n**Valid API Keys**: `foo`, `bar`, `baz`\\n\\n### Available Endpoints\\n\\n| Endpoint | Description | Example |\\n|----------|-------------|---------|\\n| `GET /api/users` | List all users | `/api/users/?api-key=foo` |\\n| `GET /api/repos` | List all repositories | `/api/repos/?api-key=foo` |\\n| `GET /api/user/:name/repos` | Get user's repositories | `/api/user/tobi/repos/?api-key=foo` |\\n\\n### Data Models\\n\\n```javascript\\n// Repositories\\nvar repos = [\\n  { name: 'express', url: 'https://github.com/expressjs/express' },\\n  { name: 'stylus', url: 'https://github.com/learnboost/stylus' },\\n  { name: 'cluster', url: 'https://github.com/learnboost/cluster' }\\n];\\n\\n// Users\\nvar users = [\\n  { name: 'tobi' },\\n  { name: 'loki' },\\n  { name: 'jane' }\\n];\\n\\n// User-Repository mapping\\nvar userRepos = {\\n  tobi: [repos[0], repos[1]],\\n  loki: [repos[1]],\\n  jane: [repos[2]]\\n};\\n```\\n\\n### Error Handling\\n\\n**Custom Error Factory**\\n\\n```javascript\\nfunction error(status, msg) {\\n  var err = new Error(msg);\\n  err.status = status;\\n  return err;\\n}\\n```\\n\\n**Error Handler Middleware** (4-arity function)\\n\\n```javascript\\napp.use(function(err, req, res, next){\\n  res.status(err.status || 500);\\n  res.send({ error: err.message });\\n});\\n```\\n\\n**404 Fallback Middleware**\\n\\n```javascript\\napp.use(function(req, res){\\n  res.status(404);\\n  res.send({ error: \\\"Sorry, can't find that\\\" });\\n});\\n```\\n\\n## Virtual Hosting\\n\\nThe `vhost` example demonstrates routing requests to different applications based on the hostname.\\n\\n### Host Configuration\\n\\nAdd to `/etc/hosts`:\\n```\\n127.0.0.1       foo.example.com\\n127.0.0.1       bar.example.com\\n127.0.0.1       example.com\\n```\\n\\n### Architecture\\n\\n```mermaid\\nflowchart LR\\n    A[Request] --&gt; B{vhost router}\\n    B --&gt;|*.example.com| C[Redirect App]\\n    B --&gt;|example.com| D[Main App]\\n    C --&gt; E[Redirect to /:subdomain]\\n    D --&gt; F[Serve main content]\\n```\\n\\n### Application Structure\\n\\n**Main Application** (`main`)\\n\\n```javascript\\nvar main = express();\\nmain.get('/', function(req, res){\\n  res.send('Hello from main app!');\\n});\\nmain.get('/:sub', function(req, res){\\n  res.send('requested ' + req.params.sub);\\n});\\n```\\n\\n**Redirect Application** (`redirect`)\\n\\n```javascript\\nvar redirect = express();\\nredirect.use(function(req, res){\\n  res.redirect('http://example.com:3000/' + req.vhost[0]);\\n});\\n```\\n\\n**Vhost Router** (`app`)\\n\\n```javascript\\nvar app = express();\\napp.use(vhost('*.example.com', redirect));\\napp.use(vhost('example.com', main));\\n```\\n\\n### Request Routing Examples\\n\\n| Request URL | Routed To | Response |\\n|-------------|-----------|----------|\\n| `http://example.com:3000/` | Main app | \\\"Hello from main app!\\\" |\\n| `http://example.com:3000/test` | Main app | \\\"requested test\\\" |\\n| `http://foo.example.com:3000/` | Redirect app | Redirect to `/foo` |\\n| `http://bar.example.com:3000/` | Redirect app | Redirect to `/bar` |\\n\\n## Running the Examples\\n\\nEach example runs independently on port 3000:\\n\\n```bash\\n# Content negotiation\\nnode examples/content-negotiation/index.js\\n\\n# Web service API\\nnode examples/web-service/index.js\\n\\n# Virtual hosting\\nnode examples/vhost/index.js\\n```\\n\\n## Key Patterns Summary\\n\\n1. **Content Negotiation**: Use `res.format()` to serve multiple content types from a single endpoint\\n2. **Middleware Authentication**: Mount validation middleware at a path prefix to protect all sub-routes\\n3. **Error Propagation**: Use `next(err)` with custom error objects and handle with 4-arity middleware\\n4. **Virtual Hosting**: Use `vhost()` middleware to route by hostname to different Express applications\"};\nvar TREE = [{\"name\":\"Core Framework\",\"slug\":\"core-framework\",\"files\":[\"index.js\",\"lib/application.js\",\"lib/express.js\",\"lib/request.js\",\"lib/response.js\",\"lib/utils.js\",\"lib/view.js\"]},{\"name\":\"Authentication &amp; Sessions\",\"slug\":\"authentication-sessions\",\"files\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\",\"examples/cookie-sessions/index.js\",\"examples/cookies/index.js\",\"examples/online/index.js\",\"examples/session/index.js\",\"examples/session/redis.js\"]},{\"name\":\"Routing Patterns\",\"slug\":\"routing-patterns\",\"files\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\",\"examples/params/index.js\",\"examples/resource/index.js\",\"examples/route-map/index.js\",\"examples/route-middleware/index.js\",\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"]},{\"name\":\"Views &amp; Templates\",\"slug\":\"views-templates\",\"files\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\",\"examples/markdown/index.js\",\"examples/markdown/views/index.md\",\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\",\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\",\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"]},{\"name\":\"Static Files &amp; Downloads\",\"slug\":\"static-files-downloads\",\"files\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\",\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"]},{\"name\":\"Error Handling\",\"slug\":\"error-handling\",\"files\":[\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\",\"examples/error/index.js\"]},{\"name\":\"Web Services &amp; APIs\",\"slug\":\"web-services-apis\",\"files\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\",\"examples/vhost/index.js\",\"examples/web-service/index.js\"]},{\"name\":\"Basic Usage\",\"slug\":\"basic-usage\",\"files\":[\"examples/hello-world/index.js\",\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"]},{\"name\":\"Other\",\"slug\":\"other\",\"files\":[],\"children\":[{\"name\":\"Other \u2014 History.md\",\"slug\":\"other-history-md\",\"files\":[\"History.md\"]},{\"name\":\"Other \u2014 Readme.md\",\"slug\":\"other-readme-md\",\"files\":[\"Readme.md\"]},{\"name\":\"Other \u2014 examples\",\"slug\":\"other-examples\",\"files\":[\"examples/README.md\"]},{\"name\":\"Other \u2014 package.json\",\"slug\":\"other-package-json\",\"files\":[\"package.json\"]},{\"name\":\"Other \u2014 test\",\"slug\":\"other-test\",\"files\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"]},{\"name\":\"Other \u2014 acceptance\",\"slug\":\"other-acceptance\",\"files\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"]},{\"name\":\"Other \u2014 support\",\"slug\":\"other-support\",\"files\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]}]}];\nvar META = {\"fromCommit\":\"f873ac23124ffcff8c040b4bd257b32c29828d53\",\"generatedAt\":\"2026-05-08T07:35:04.785Z\",\"model\":\"glm-5\",\"moduleFiles\":{\"Core Framework\":[\"index.js\",\"lib/application.js\",\"lib/express.js\",\"lib/request.js\",\"lib/response.js\",\"lib/utils.js\",\"lib/view.js\"],\"Authentication &amp; Sessions\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\",\"examples/cookie-sessions/index.js\",\"examples/cookies/index.js\",\"examples/online/index.js\",\"examples/session/index.js\",\"examples/session/redis.js\"],\"Routing Patterns\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\",\"examples/params/index.js\",\"examples/resource/index.js\",\"examples/route-map/index.js\",\"examples/route-middleware/index.js\",\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"],\"Views &amp; Templates\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\",\"examples/markdown/index.js\",\"examples/markdown/views/index.md\",\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\",\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\",\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"],\"Static Files &amp; Downloads\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\",\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"],\"Error Handling\":[\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\",\"examples/error/index.js\"],\"Web Services &amp; APIs\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\",\"examples/vhost/index.js\",\"examples/web-service/index.js\"],\"Basic Usage\":[\"examples/hello-world/index.js\",\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"],\"Other\":[\"History.md\",\"Readme.md\",\"examples/README.md\",\"package.json\",\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\",\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\",\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"],\"Other \u2014 History.md\":[\"History.md\"],\"Other \u2014 Readme.md\":[\"Readme.md\"],\"Other \u2014 examples\":[\"examples/README.md\"],\"Other \u2014 package.json\":[\"package.json\"],\"Other \u2014 test\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"],\"Other \u2014 acceptance\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"],\"Other \u2014 support\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]},\"moduleTree\":[{\"name\":\"Core Framework\",\"slug\":\"core-framework\",\"files\":[\"index.js\",\"lib/application.js\",\"lib/express.js\",\"lib/request.js\",\"lib/response.js\",\"lib/utils.js\",\"lib/view.js\"]},{\"name\":\"Authentication &amp; Sessions\",\"slug\":\"authentication-sessions\",\"files\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\",\"examples/cookie-sessions/index.js\",\"examples/cookies/index.js\",\"examples/online/index.js\",\"examples/session/index.js\",\"examples/session/redis.js\"]},{\"name\":\"Routing Patterns\",\"slug\":\"routing-patterns\",\"files\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\",\"examples/params/index.js\",\"examples/resource/index.js\",\"examples/route-map/index.js\",\"examples/route-middleware/index.js\",\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"]},{\"name\":\"Views &amp; Templates\",\"slug\":\"views-templates\",\"files\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\",\"examples/markdown/index.js\",\"examples/markdown/views/index.md\",\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\",\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\",\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"]},{\"name\":\"Static Files &amp; Downloads\",\"slug\":\"static-files-downloads\",\"files\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\",\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"]},{\"name\":\"Error Handling\",\"slug\":\"error-handling\",\"files\":[\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\",\"examples/error/index.js\"]},{\"name\":\"Web Services &amp; APIs\",\"slug\":\"web-services-apis\",\"files\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\",\"examples/vhost/index.js\",\"examples/web-service/index.js\"]},{\"name\":\"Basic Usage\",\"slug\":\"basic-usage\",\"files\":[\"examples/hello-world/index.js\",\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"]},{\"name\":\"Other\",\"slug\":\"other\",\"files\":[],\"children\":[{\"name\":\"Other \u2014 History.md\",\"slug\":\"other-history-md\",\"files\":[\"History.md\"]},{\"name\":\"Other \u2014 Readme.md\",\"slug\":\"other-readme-md\",\"files\":[\"Readme.md\"]},{\"name\":\"Other \u2014 examples\",\"slug\":\"other-examples\",\"files\":[\"examples/README.md\"]},{\"name\":\"Other \u2014 package.json\",\"slug\":\"other-package-json\",\"files\":[\"package.json\"]},{\"name\":\"Other \u2014 test\",\"slug\":\"other-test\",\"files\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"]},{\"name\":\"Other \u2014 acceptance\",\"slug\":\"other-acceptance\",\"files\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"]},{\"name\":\"Other \u2014 support\",\"slug\":\"other-support\",\"files\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]}]}]};\n\n(function() {\n  var activePage = 'overview';\n\n  document.addEventListener('DOMContentLoaded', function() {\n    mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' });\n    renderMeta();\n    renderNav();\n    document.getElementById('menu-toggle').addEventListener('click', function() {\n      document.getElementById('sidebar').classList.toggle('open');\n    });\n    if (location.hash &amp;&amp; location.hash.length &gt; 1) {\n      activePage = decodeURIComponent(location.hash.slice(1));\n    }\n    navigateTo(activePage);\n  });\n\n  function renderMeta() {\n    if (!META) return;\n    var el = document.getElementById('meta-info');\n    var parts = [];\n    if (META.generatedAt) {\n      parts.push(new Date(META.generatedAt).toLocaleDateString());\n    }\n    if (META.model) parts.push(META.model);\n    if (META.fromCommit) parts.push(META.fromCommit.slice(0, 8));\n    el.textContent = parts.join(' \\u00b7 ');\n  }\n\n  function renderNav() {\n    var container = document.getElementById('nav-tree');\n    var html = '\n';\n    html += 'Overview';\n    html += '';\n    if (TREE.length &gt; 0) {\n      html += '\nModules';\n      html += buildNavTree(TREE);\n    }\n    container.innerHTML = html;\n    container.addEventListener('click', function(e) {\n      var target = e.target;\n      while (target &amp;&amp; !target.dataset.page) { target = target.parentElement; }\n      if (target &amp;&amp; target.dataset.page) {\n        e.preventDefault();\n        navigateTo(target.dataset.page);\n      }\n    });\n  }\n\n  function buildNavTree(nodes) {\n    var html = '';\n    for (var i = 0; i &lt; nodes.length; i++) {\n      var node = nodes[i];\n      html += '\n';\n      html += '' + escH(node.name) + '';\n      if (node.children &amp;&amp; node.children.length &gt; 0) {\n        html += '\n' + buildNavTree(node.children) + '';\n      }\n      html += '';\n    }\n    return html;\n  }\n\n  function escH(s) {\n    var d = document.createElement('div');\n    d.textContent = s;\n    return d.innerHTML;\n  }\n\n  function navigateTo(page) {\n    activePage = page;\n    location.hash = encodeURIComponent(page);\n\n    var items = document.querySelectorAll('.nav-item');\n    for (var i = 0; i &lt; items.length; i++) {\n      if (items[i].dataset.page === page) {\n        items[i].classList.add('active');\n      } else {\n        items[i].classList.remove('active');\n      }\n    }\n\n    var contentEl = document.getElementById('content');\n    var md = PAGES[page];\n\n    if (!md) {\n      contentEl.innerHTML = '\n\nPage not found\n' + escH(page) + '.md does not exist.';\n      return;\n    }\n\n    contentEl.innerHTML = marked.parse(md);\n\n    // Rewrite .md links to hash navigation\n    var links = contentEl.querySelectorAll('a[href]');\n    for (var i = 0; i &lt; links.length; i++) {\n      var href = links[i].getAttribute('href');\n      if (href &amp;&amp; href.endsWith('.md') &amp;&amp; href.indexOf('://') === -1) {\n        var slug = href.replace(/\\.md$/, '');\n        links[i].setAttribute('href', '#' + encodeURIComponent(slug));\n        (function(s) {\n          links[i].addEventListener('click', function(e) {\n            e.preventDefault();\n            navigateTo(s);\n          });\n        })(slug);\n      }\n    }\n\n    // Convert mermaid code blocks into mermaid divs\n    var mermaidBlocks = contentEl.querySelectorAll('pre code.language-mermaid');\n    for (var i = 0; i &lt; mermaidBlocks.length; i++) {\n      var pre = mermaidBlocks[i].parentElement;\n      var div = document.createElement('div');\n      div.className = 'mermaid';\n      div.textContent = mermaidBlocks[i].textContent;\n      pre.parentNode.replaceChild(div, pre);\n    }\n    try { mermaid.run({ querySelector: '.mermaid' }); } catch(e) {}\n\n    window.scrollTo(0, 0);\n    document.getElementById('sidebar').classList.remove('open');\n  }\n})();\n\n\n\n", "creation_timestamp": "2026-05-08T07:36:05.000000Z"}, {"uuid": "d742d18d-5ee5-45f3-80c9-5c28b3d3d108", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2024-51999", "type": "seen", "source": "https://gist.github.com/Adcbda/1903b9267561971f4b148df4c6e3182f", "content": "\n\n\n\n\nexpress \u2014 Wiki\n\n\n\n\n*{margin:0;padding:0;box-sizing:border-box}\n:root{\n  --bg:#ffffff;--sidebar-bg:#f8f9fb;--border:#e5e7eb;\n  --text:#1e293b;--text-muted:#64748b;--primary:#2563eb;\n  --primary-soft:#eff6ff;--hover:#f1f5f9;--code-bg:#f1f5f9;\n  --radius:8px;--shadow:0 1px 3px rgba(0,0,0,.08);\n}\nbody{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;\n  line-height:1.65;color:var(--text);background:var(--bg)}\n\n.layout{display:flex;min-height:100vh}\n.sidebar{width:280px;background:var(--sidebar-bg);border-right:1px solid var(--border);\n  position:fixed;top:0;left:0;bottom:0;overflow-y:auto;padding:24px 16px;\n  display:flex;flex-direction:column;z-index:10}\n.content{margin-left:280px;flex:1;padding:48px 64px;max-width:960px}\n\n.sidebar-header{margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid var(--border)}\n.sidebar-title{font-size:16px;font-weight:700;color:var(--text);display:flex;align-items:center;gap:8px}\n.sidebar-title svg{flex-shrink:0}\n.sidebar-meta{font-size:11px;color:var(--text-muted);margin-top:6px}\n.nav-section{margin-bottom:2px}\n.nav-item{display:block;padding:7px 12px;border-radius:var(--radius);cursor:pointer;\n  font-size:13px;color:var(--text);text-decoration:none;transition:all .15s;\n  white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.nav-item:hover{background:var(--hover)}\n.nav-item.active{background:var(--primary-soft);color:var(--primary);font-weight:600}\n.nav-item.overview{font-weight:600;margin-bottom:4px}\n.nav-children{padding-left:14px;border-left:1px solid var(--border);margin-left:12px}\n.nav-group-label{font-size:11px;font-weight:600;color:var(--text-muted);\n  text-transform:uppercase;letter-spacing:.5px;padding:12px 12px 4px;user-select:none}\n.sidebar-footer{margin-top:auto;padding-top:16px;border-top:1px solid var(--border);\n  font-size:11px;color:var(--text-muted);text-align:center}\n\n.content h1{font-size:28px;font-weight:700;margin-bottom:8px;line-height:1.3}\n.content h2{font-size:22px;font-weight:600;margin:32px 0 12px;padding-bottom:6px;border-bottom:1px solid var(--border)}\n.content h3{font-size:17px;font-weight:600;margin:24px 0 8px}\n.content h4{font-size:15px;font-weight:600;margin:20px 0 6px}\n.content p{margin:12px 0}\n.content ul,.content ol{margin:12px 0 12px 24px}\n.content li{margin:4px 0}\n.content a{color:var(--primary);text-decoration:none}\n.content a:hover{text-decoration:underline}\n.content blockquote{border-left:3px solid var(--primary);padding:8px 16px;margin:16px 0;\n  background:var(--primary-soft);border-radius:0 var(--radius) var(--radius) 0;\n  color:var(--text-muted);font-size:14px}\n.content code{font-family:'SF Mono',Consolas,'Courier New',monospace;font-size:13px;\n  background:var(--code-bg);padding:2px 6px;border-radius:4px}\n.content pre{background:#1e293b;color:#e2e8f0;border-radius:var(--radius);padding:16px;\n  overflow-x:auto;margin:16px 0}\n.content pre code{background:none;padding:0;font-size:13px;line-height:1.6;color:inherit}\n.content table{border-collapse:collapse;width:100%;margin:16px 0}\n.content th,.content td{border:1px solid var(--border);padding:8px 12px;text-align:left;font-size:14px}\n.content th{background:var(--sidebar-bg);font-weight:600}\n.content img{max-width:100%;border-radius:var(--radius)}\n.content hr{border:none;border-top:1px solid var(--border);margin:32px 0}\n.content .mermaid{margin:20px 0;text-align:center}\n\n.menu-toggle{display:none;position:fixed;top:12px;left:12px;z-index:20;\n  background:var(--bg);border:1px solid var(--border);border-radius:var(--radius);\n  padding:8px 12px;cursor:pointer;font-size:18px;box-shadow:var(--shadow)}\n@media(max-width:768px){\n  .sidebar{transform:translateX(-100%);transition:transform .2s}\n  .sidebar.open{transform:translateX(0);box-shadow:2px 0 12px rgba(0,0,0,.1)}\n  .content{margin-left:0;padding:24px 20px;padding-top:56px}\n  .menu-toggle{display:block}\n}\n.empty-state{text-align:center;padding:80px 20px;color:var(--text-muted)}\n.empty-state h2{font-size:20px;margin-bottom:8px;border:none}\n\n\n\n\n&#9776;\n\n\n\n\n\n\n\n\n\nexpress\n\n\n\n\n\n\n\nGenerated by GitNexus\n\n\n\n\n\nLoading\u2026\n\n\n\nvar PAGES = {\"application-core\":\"# Application Core\\n\\n# Application Core Module\\n\\n## Overview\\nThe Application Core module provides the foundational factory, prototype, and request lifecycle logic for the Express framework. It exposes `createApplication()` as the primary entry point, constructs the callable `app` object, and defines the `application` prototype that handles configuration, middleware mounting, routing delegation, view rendering, and HTTP server creation.\\n\\n## Initialization &amp; Architecture\\nThe module is structured around a factory pattern combined with prototype mixing:\\n\\n- **Entry Point**: `index.js` re-exports `./lib/express`\\n- **Factory**: `lib/express.js` exports `createApplication()`, which returns a callable function `app(req, res, next)`\\n- **Prototype Mixing**: `merge-descriptors` is used to attach `EventEmitter.prototype` and the `application` prototype (`proto`) to the `app` function\\n- **Request/Response Prototypes**: `app.request` and `app.response` are created via `Object.create()` with an `app` property descriptor. These serve as the base prototypes for incoming Node.js `req` and `res` objects\\n- **Lazy Router**: The `app.router` property is defined via `Object.defineProperty` with a getter that instantiates a `Router` only on first access, configured with `caseSensitive` and `strict` settings\\n\\n## Core API Reference\\n\\n### Configuration &amp; Settings\\nSettings are stored in `this.settings` and managed through a unified API:\\n- `app.set(setting, val)` / `app.set(setting)`: Assigns or retrieves a setting. Triggers compilation for `etag`, `query parser`, and `trust proxy` via `compileETag`, `compileQueryParser`, and `compileTrust`\\n- `app.enable(setting)` / `app.disable(setting)`: Shorthand for `app.set(setting, true/false)`\\n- `app.enabled(setting)` / `app.disabled(setting)`: Boolean checks against stored settings\\n- `app.defaultConfiguration()`: Initializes defaults (`x-powered-by`, `etag: 'weak'`, `env`, `query parser: 'simple'`, `subdomain offset: 2`, `trust proxy: false`, `view cache` in production)\\n\\n### Routing &amp; Middleware\\nRouting methods delegate to the lazily initialized `Router` instance:\\n- `app.use([path], ...fn)`: Proxies to `router.use()`. Handles argument flattening via `Array.prototype.flat`. If `fn` is an Express app, it mounts it, sets `fn.mountpath` and `fn.parent`, and wraps execution to restore original `req`/`res` prototypes after the sub-app finishes\\n- `app.route(path)`: Returns a new `Route` instance for isolated middleware stacks\\n- `app.param(name, fn)`: Proxies to `router.param()`. Accepts arrays of parameter names\\n- `app.all(path, ...fn)`: Registers middleware/callbacks for all HTTP methods\\n- **HTTP Verbs**: Dynamically generated via `methods.forEach`. `app.get(path)` acts as a settings getter when called with a single argument; otherwise, it delegates to `route.get()`\\n\\n### Request Handling Pipeline\\n- `app.handle(req, res, callback)`: Core dispatch function. Sets up circular references (`req.res`, `res.req`), attaches `app.request`/`app.response` prototypes to incoming objects, initializes `res.locals`, and delegates to `this.router.handle(req, res, done)`\\n- If no callback is provided, `finalhandler` is used as the terminal error handler, configured with `this.get('env')` and `logerror`\\n\\n### View Rendering\\n- `app.render(name, options, callback)`: Resolves views using the `View` constructor. Merges `this.locals`, `opts._locals`, and `opts`. Supports view caching via `this.cache` when `view cache` is enabled\\n- `app.engine(ext, fn)`: Registers template engine callbacks keyed by file extension\\n- `tryRender(view, options, callback)`: Internal wrapper that catches synchronous rendering errors and passes them to the callback\\n\\n### Server Lifecycle\\n- `app.listen()`: Creates an `http.Server` with `this` as the request handler. Wraps the final callback argument with `once` to prevent duplicate error event emissions, then delegates to `server.listen()`\\n\\n## Request Execution Flow\\n```mermaid\\ngraph TD\\n  A[Incoming HTTP Request] --&gt; B[app(req, res, next)]\\n  B --&gt; C[app.handle]\\n  C --&gt; D[Set req/res prototypes &amp; locals]\\n  D --&gt; E[router.handle]\\n  E --&gt; F[Middleware/Route Execution]\\n  F --&gt; G[finalhandler / logerror]\\n```\\n\\n1. The callable `app` function receives the raw Node.js request\\n2. `app.handle()` initializes the pipeline, optionally attaching `finalhandler`\\n3. `X-Powered-By` header is set if enabled\\n4. `req` and `res` prototypes are swapped to `app.request` and `app.response`\\n5. `res.locals` is initialized if absent\\n6. Control passes to `this.router.handle()`, which executes the middleware stack\\n7. Unhandled errors or completed responses trigger `finalhandler`, which logs via `logerror` in non-test environments\\n\\n## Key Implementation Patterns\\n\\n### Prototype Restoration for Mounted Apps\\nWhen a sub-application is mounted via `app.use()`, the wrapper function captures `req.app` before execution. After the sub-app's `handle()` completes, it restores the original prototypes:\\n```javascript\\nObject.setPrototypeOf(req, orig.request)\\nObject.setPrototypeOf(res, orig.response)\\n```\\nThis ensures middleware chains outside the mounted app continue using the parent's prototype chain.\\n\\n### Lazy Router Instantiation\\nThe router is not created during `app.init()`. Instead, a getter defers instantiation until the first routing or middleware call:\\n```javascript\\nObject.defineProperty(this, 'router', {\\n  get: function getrouter() {\\n    if (router === null) {\\n      router = new Router({ ... });\\n    }\\n    return router;\\n  }\\n});\\n```\\nThis avoids overhead for applications that only use `app.set()` or `app.render()`.\\n\\n### Settings Compilation &amp; Inheritance\\nSpecial settings (`etag`, `query parser`, `trust proxy`) trigger immediate compilation into internal `fn` properties. The `trustProxyDefaultSymbol` tracks whether the default trust proxy state should be inherited from a parent app during `mount` events, maintaining backward compatibility with Express 4.x behavior.\\n\\n### Error Handling &amp; Logging\\n`logerror()` is bound to the app instance and invoked by `finalhandler` when errors bubble up. It suppresses output in `test` environments and logs `err.stack` or `err.toString()` otherwise.\",\"other-acceptance\":\"# Other \u2014 acceptance\\n\\n# Acceptance Test Module\\n\\n## Purpose\\nThe `test/acceptance/` directory contains end-to-end integration tests for the Express.js example applications. Each file validates the HTTP behavior, routing logic, middleware execution, and response formatting of a specific example. The suite ensures that examples function correctly as standalone applications before deployment or documentation publication.\\n\\n## Architecture &amp; Tooling\\n- **Test Runner**: Mocha (`describe`, `it`, `done`)\\n- **HTTP Simulation**: `supertest` (`request(app)`)\\n- **Assertion Pattern**: Chained `.expect()` calls for status codes, headers, response bodies (regex or exact strings), and redirects\\n- **Execution Model**: Tests import Express app instances directly from `../../examples/` and pass them to `supertest`. This bypasses the need for a live HTTP server, enabling fast, isolated test execution.\\n\\n```mermaid\\nflowchart LR\\n  A[Test File] --&gt;|require| B[Express App]\\n  A --&gt;|request| C[supertest]\\n  C --&gt;|HTTP Simulation| B\\n  B --&gt;|Response| C\\n  C --&gt;|expect| D[Assertions]\\n  A --&gt;|getCookie / getCookies| E[Cookie Helpers]\\n  A --&gt;|shouldNotHaveHeader| F[test/support/utils.js]\\n```\\n\\n## Execution Flow\\nEach test follows a consistent asynchronous pattern:\\n1. **App Initialization**: `var app = require('../../examples/')`\\n2. **Request Construction**: `request(app).('/path')`\\n3. **Payload/Headers**: `.type('urlencoded')`, `.send({})`, `.set('Header', 'value')`\\n4. **Validation**: `.expect(status, body, done)` or chained `.expect()` calls\\n5. **Stateful Follow-up**: Capture `Set-Cookie` headers, parse with helper functions, and attach to subsequent requests via `.set('Cookie', ...)`\\n\\nThe `send` method routes payloads through the test simulation layer, which interfaces with the underlying Express router to trigger middleware and route handlers.\\n\\n## Test Domains &amp; Coverage\\n| File | Feature Validated | Key Behaviors |\\n|------|-------------------|---------------|\\n| `auth.js` | Session-based authentication | Login redirects, credential validation, protected route access, session persistence |\\n| `cookie-sessions.js` | Cookie-backed sessions | View counters, `Set-Cookie` header generation, session state across requests |\\n| `cookies.js` | Manual cookie management | Cookie setting/clearing, conditional header emission, form-driven state |\\n| `content-negotiation.js` | `Accept` header routing | Default `text/html`, `text/plain`, and `application/json` response formatting |\\n| `downloads.js` | Static file serving | `Content-Disposition` headers, 404 for missing files, 403 for path traversal |\\n| `ejs.js` / `markdown.js` | Template rendering | HTML output generation, error handling on render failure |\\n| `error.js` / `error-pages.js` | Error handling | 404/500 status codes, format-aware error payloads (JSON/HTML/plain text) |\\n| `multi-router.js` / `route-map.js` / `route-separation.js` | Routing architecture | Nested routers, HTTP method mapping, modular route organization |\\n| `mvc.js` | CRUD &amp; MVC patterns | Resource creation, form submission (`PUT`/`POST`), redirects, 404/500 handling |\\n| `params.js` / `resource.js` | Parameter parsing &amp; REST | Range parsing (`1..3`), integer validation, resource deletion, JSON fallback |\\n| `vhost.js` | Virtual host routing | `Host` header matching, subdomain redirection |\\n| `web-service.js` | API security | API key validation (`400`/`401`), protected endpoints, JSON error responses |\\n| `hello-world.js` | Baseline routing | Simple GET response, default 404 handling |\\n\\n## State Management &amp; Helpers\\nStateful tests (authentication, sessions, cookies) rely on two internal helper functions:\\n- `getCookie(res)`: Extracts the first cookie from `res.headers['set-cookie'][0]` by splitting on `;`\\n- `getCookies(res)`: Maps all `set-cookie` headers, extracts the key-value pairs, and joins them with `; ` for multi-cookie requests\\n\\nBoth helpers are used to maintain session state across sequential HTTP requests within a single test case.\\n\\nExternal assertions are imported from `test/support/utils.js`:\\n- `utils.shouldNotHaveHeader('Header-Name')`: Validates that a specific header is absent from the response (e.g., ensuring `Set-Cookie` is not emitted when no session is created).\\n\\n## Integration Points\\n- **Test Support**: `test/support/utils.js` provides shared assertion utilities\\n- **Example Apps**: All tests target modules under `examples/`, importing the exported Express app instance\\n- **Request Simulation**: `supertest` intercepts Express's internal routing, allowing `.send()` to trigger middleware chains without network overhead\\n- **Async Control**: All tests use the Mocha `done` callback pattern to handle asynchronous HTTP simulation and assertion resolution\\n\\n## Adding New Tests\\n1. Create a new file in `test/acceptance/` matching the target example name\\n2. Import the app: `var app = require('../../examples/')`\\n3. Structure tests using `describe` for routes/features and `it` for individual assertions\\n4. Use `.expect()` for status codes, headers, and body content. Prefer regex for HTML and exact strings for JSON\\n5. For stateful flows, capture cookies via `getCookie(res)` or `getCookies(res)` and attach them to follow-up requests using `.set('Cookie', ...)`\\n6. Always pass `done` to the final `.expect()` call or return a promise to ensure proper async resolution\",\"other-auth\":\"# Other \u2014 auth\\n\\n# Other \u2014 auth\\n\\nThis Express.js example demonstrates session-based user authentication using `express-session` and `pbkdf2-password`. It provides a complete, self-contained flow for login, session lifecycle management, route protection, and logout, backed by an in-memory user store.\\n\\n## Architecture &amp; Request Flow\\n\\nThe application follows a standard Express middleware pipeline:\\n1. **Parsing &amp; Session Initialization**: `express.urlencoded()` parses form data, while `express-session` attaches a session object to `req`.\\n2. **Flash Message Handling**: A custom middleware extracts `req.session.error` and `req.session.success`, formats them into HTML, assigns them to `res.locals.message`, and immediately deletes them from the session.\\n3. **Routing &amp; Protection**: Public routes (`/`, `/login`) render views or redirect. Protected routes (`/restricted`) pass through the `restrict` guard.\\n4. **Authentication**: `POST /login` invokes `authenticate()`, which verifies credentials against a pre-hashed in-memory user object. Successful authentication triggers session regeneration and user storage.\\n\\n```mermaid\\nsequenceDiagram\\n    participant Client\\n    participant Express\\n    participant Session\\n    participant Auth\\n    Client-&gt;&gt;Express: POST /login\\n    Express-&gt;&gt;Session: Load/attach session\\n    Express-&gt;&gt;Auth: authenticate(username, password)\\n    Auth--&gt;&gt;Express: Callback(err, user)\\n    alt Valid Credentials\\n        Express-&gt;&gt;Session: regenerate()\\n        Express-&gt;&gt;Session: Store req.session.user\\n        Express--&gt;&gt;Client: Redirect to referrer\\n    else Invalid Credentials\\n        Express-&gt;&gt;Session: Set req.session.error\\n        Express--&gt;&gt;Client: Redirect to /login\\n    end\\n```\\n\\n## Key Components\\n\\n### Session &amp; Message Middleware\\n- **`express-session`**: Configured with `resave: false` and `saveUninitialized: false` to prevent unnecessary session writes. Uses a hardcoded secret (`'shhhh, very secret'`).\\n- **Message Middleware**: Intercepts session-stored flash messages before route handlers execute. Clears them immediately after assignment to `res.locals.message` to prevent duplicate rendering on subsequent requests.\\n\\n### Password Hashing &amp; Verification\\n- **Initialization**: On startup, `pbkdf2-password` hashes the password `'foobar'` for the user `tj`. The resulting `salt` and `hash` are stored in the `users` object.\\n- **`authenticate(name, pass, fn)`**: Retrieves the user by username. Re-hashes the provided password using the stored salt via `pbkdf2-password`. Compares the resulting hash against `user.hash`. Invokes the callback with `(err, user)` on match, or `(err, null)` on mismatch.\\n\\n### Route Protection (`restrict`)\\n- **`restrict(req, res, next)`**: Middleware that checks for `req.session.user`. If present, calls `next()`. If absent, sets `req.session.error = 'Access denied!'` and redirects to `/login`. Applied to `GET /restricted`.\\n\\n### Login &amp; Session Lifecycle\\n- **`POST /login`**: Validates `req.body`, calls `authenticate()`. On success, calls `req.session.regenerate()` to issue a new session ID (preventing fixation), stores the user object in `req.session.user`, sets a success message, and redirects. On failure, sets an error message and redirects to `/login`.\\n- **`GET /logout`**: Calls `req.session.destroy()` to invalidate the session server-side and redirects to `/`.\\n- **`GET /restricted`**: Uses `res.send()` to render a protected message with a logout link.\\n\\n## Views &amp; Templating\\n- **Engine**: EJS (`app.set('view engine', 'ejs')`)\\n- **Layout**: Composed of `head.ejs` (HTML boilerplate, CSS for `.error`/`.success` classes) and `foot.ejs`.\\n- **`login.ejs`**: Includes the layout partials, renders `&lt;%- message %&gt;` for flash notifications, and provides a POST form targeting `/login`.\\n\\n## Security Considerations\\n- **Session Fixation Prevention**: `req.session.regenerate()` is called immediately after successful authentication, ensuring the session ID changes post-login.\\n- **Password Storage**: PBKDF2 with per-user salt is used. Never store plaintext passwords.\\n- **In-Memory Store**: The `users` object is strictly for demonstration. Production systems should use a persistent database and a dedicated session store (e.g., Redis, `connect-pg-simple`).\\n- **Secret Management**: The session secret is hardcoded. Replace with `process.env.SESSION_SECRET` in production.\\n\\n## Running the Example\\n```bash\\nnode examples/auth/index.js\\n```\\nThe server starts on `http://localhost:3000`. Default credentials are `tj` / `foobar`. Access `/restricted` to trigger the authentication guard, or navigate directly to `/login`.\",\"other-content-negotiation\":\"# Other \u2014 content-negotiation\\n\\n# Other \u2014 content-negotiation\\n\\n## Overview\\nThis module demonstrates HTTP content negotiation in Express using the `res.format()` API. It provides two distinct patterns for serving the same underlying data (`users`) in multiple representations (`html`, `text`, `json`) based on the client's `Accept` header.\\n\\n## Architecture &amp; Components\\nThe module is structured across three files:\\n\\n| File | Purpose |\\n|------|---------|\\n| `db.js` | In-memory data store exporting an array of user objects (`{ name: string }`). |\\n| `index.js` | Express application entry point. Defines routes and implements a reusable `format()` middleware factory. |\\n| `users.js` | External format handler module exporting `html`, `text`, and `json` response functions. |\\n\\n## Content Negotiation Patterns\\n\\n### 1. Inline Format Handlers (`GET /`)\\nThe root route demonstrates direct, inline content negotiation. An object mapping MIME types to handler functions is passed directly to `res.format()`:\\n```javascript\\nres.format({\\n  html: function() { res.send('\n...&lt;\\/ul&gt;'); },\\n  text: function() { res.send(' - Tobi\\\\n...'); },\\n  json: function() { res.json(users); }\\n});\\n```\\nExpress automatically parses the `Accept` header, selects the highest-priority matching type, and executes the corresponding handler.\\n\\n### 2. Modular Format Handlers (`GET /users`)\\nThe `/users` route demonstrates a declarative, reusable approach using a custom middleware factory:\\n```javascript\\nfunction format(path) {\\n  var obj = require(path);\\n  return function(req, res) {\\n    res.format(obj);\\n  };\\n}\\n\\napp.get('/users', format('./users'));\\n```\\nThe `format(path)` function dynamically loads a module (e.g., `users.js`) that exports format-specific functions. This separates routing logic from response formatting, making it easier to maintain and test.\\n\\n## Execution Flow\\n```mermaid\\nsequenceDiagram\\n    participant Client\\n    participant Express\\n    participant Route\\n    participant FormatHandler\\n    Client-&gt;&gt;Express: GET /users (Accept: application/json)\\n    Express-&gt;&gt;Route: Match /users\\n    Route-&gt;&gt;FormatHandler: res.format({html, text, json})\\n    FormatHandler-&gt;&gt;Express: Select best match (json)\\n    Express-&gt;&gt;Client: 200 OK + JSON payload\\n```\\n\\n## Integration &amp; Testing\\n- **Test Coverage:** The negotiation logic is validated by `test/res.format.js`, which exercises handler selection and execution.\\n- **Cross-Module References:** The `format()` factory pattern is referenced in `examples/error-pages/index.js` as a reusable abstraction for declarative response formatting.\\n- **Response Delegation:** All format handlers ultimately delegate to `res.send()` or `res.json()`, ensuring consistent Express response lifecycle behavior.\\n\\n## Developer Notes\\n- **MIME Type Matching:** `res.format()` supports exact matches (`json`), type aliases (`html`), and wildcards. If no match is found, Express returns a `406 Not Acceptable` response.\\n- **Extensibility:** To add a new format (e.g., `xml`), simply export an `xml` function from `users.js` or add it to the inline object. No route changes are required.\\n- **Middleware Factory:** The `format(path)` helper relies on Node's synchronous `require()` cache. For dynamic or async format loading, replace `require()` with a custom loader or async middleware pattern.\\n- **Data Source:** `db.js` is intentionally minimal. In production, replace the static array with a database query or service call, ensuring the query executes before `res.format()` is invoked.\",\"other-cookie-sessions\":\"# Other \u2014 cookie-sessions\\n\\n# Other \u2014 cookie-sessions\\n\\n## Purpose\\nThis module is a self-contained Express.js example demonstrating stateless, client-side session management using the `cookie-session` middleware. It provides a minimal implementation for tracking per-user state (a page-view counter) without relying on external databases or server-side session stores.\\n\\n## Architecture &amp; Request Flow\\nThe application follows a standard Express middleware pipeline. Incoming HTTP requests pass through the `cookie-session` middleware before reaching route handlers. The middleware intercepts the request, parses the signed session cookie, and attaches a mutable `req.session` object. After the route handler executes, Express automatically serializes the updated session data back into a `Set-Cookie` header on the response.\\n\\n```mermaid\\nflowchart LR\\n    A[Client Request] --&gt; B[cookieSession Middleware]\\n    B --&gt; C{Parse &amp; Verify Cookie}\\n    C --&gt;|Valid| D[Attach req.session]\\n    C --&gt;|Missing/Invalid| D\\n    D --&gt; E[app.get('/') Handler]\\n    E --&gt; F[Increment req.session.count]\\n    F --&gt; G[res.send Response]\\n    G --&gt; H[Serialize &amp; Set-Cookie]\\n    H --&gt; I[Client Response]\\n```\\n\\n## Core Components\\n\\n| Component | Description |\\n|-----------|-------------|\\n| `express()` | Initializes the application instance. Exported via `module.exports` to allow external mounting or testing. |\\n| `app.use(cookieSession({ secret: 'manny is cool' }))` | Registers the session middleware. The `secret` option is required for HMAC signing to prevent client-side tampering. |\\n| `app.get('/', handler)` | Defines the root route. Reads and mutates `req.session.count` on each invocation. |\\n| `res.send()` | Finalizes the HTTP response. Triggers Express's internal response pipeline, which includes session cookie serialization. |\\n| `if (!module.parent)` | Standard Node.js guard that starts the HTTP server on port `3000` only when the file is executed directly. |\\n\\n## Session Mechanics\\nUnlike traditional server-side sessions, `cookie-session` stores the entire session payload in the client's browser cookie. Key behaviors demonstrated in this module:\\n\\n- **Initialization**: `req.session` is automatically created as an empty object if no valid cookie is present.\\n- **State Mutation**: `req.session.count = (req.session.count || 0) + 1` demonstrates safe read-modify-write semantics. The fallback `|| 0` handles first-time visitors.\\n- **Serialization**: On response, the middleware JSON-encodes the session object, signs it with the provided `secret`, and attaches it to the `Set-Cookie` header.\\n- **Constraints**: Session data is limited by browser cookie size restrictions (~4KB). Sensitive data should never be stored here, as it is client-accessible (though cryptographically signed).\\n\\n## Execution &amp; Startup\\nWhen run directly via `node index.js`, the module:\\n1. Exports the Express app instance.\\n2. Evaluates `!module.parent` as `true`.\\n3. Calls `app.listen(3000)` and logs `Express started on port 3000`.\\n4. Begins accepting HTTP requests on `http://localhost:3000`.\\n\\nEach subsequent `GET /` request increments the counter and returns a plain-text response: `viewed N times\\\\n`.\\n\\n## Integration Notes\\n- **Testing &amp; Mounting**: Because the app is assigned to `module.exports`, it can be required in test suites or mounted as a sub-app in larger Express routers without triggering the standalone server.\\n- **Outgoing Calls**: The primary external interaction is `res.send()`, which delegates to Express's response layer for header management, body formatting, and session cookie attachment.\\n- **Middleware Order**: `cookieSession` must be registered before any route that accesses `req.session`. Placing it after route definitions will result in `undefined` session objects.\\n- **Security Considerations**: The hardcoded `secret` is for demonstration only. Production deployments should use environment variables or secure key management for the `secret` option.\",\"other-cookies\":\"# Other \u2014 cookies\\n\\n# Other \u2014 cookies\\n\\n## Overview\\nThis module is an Express.js example demonstrating HTTP cookie management using the `cookie-parser` middleware. It implements a minimal \\\"remember me\\\" workflow to illustrate how to read, set, and clear cookies across request/response cycles, and how to integrate cookie parsing with body parsing middleware.\\n\\n## Middleware Stack\\nThe application configures three middleware functions in sequence. Order is critical for correct request processing:\\n\\n1. **`logger` (morgan)**: Logs incoming requests using the custom format `:method :url`. Automatically disabled when `process.env.NODE_ENV === 'test'`.\\n2. **`cookieParser('my secret here')`**: Parses the `Cookie` header from incoming requests. Populates `req.cookies` with unsigned cookies and `req.signedCookies` with verified signed cookies. The provided secret string is used to verify and sign cookies.\\n3. **`express.urlencoded()`**: Parses `application/x-www-form-urlencoded` payloads from POST requests, making form data available via `req.body`.\\n\\n## Route Handlers\\n\\n### `GET /`\\nChecks for the presence of `req.cookies.remember`:\\n- If truthy: Responds with a confirmation message and a link to `/forget`.\\n- If falsy/missing: Responds with an HTML form containing a `remember` checkbox.\\n\\n### `POST /`\\nProcesses form submissions:\\n- Evaluates `req.body.remember`.\\n- If present, sets a cookie using `res.cookie('remember', 1, { maxAge: 60000 })`. The `maxAge` is set to 60,000ms (1 minute).\\n- Redirects to the `Referrer` header or falls back to `/`.\\n\\n### `GET /forget`\\nClears the session state:\\n- Calls `res.clearCookie('remember')` to instruct the browser to delete the cookie.\\n- Redirects to the `Referrer` header or falls back to `/`.\\n\\n## Cookie Lifecycle &amp; API Usage\\nThe module demonstrates three core Express response methods for cookie management:\\n\\n| Method | Purpose | Usage in Module |\\n|--------|---------|-----------------|\\n| `res.cookie(name, value, options)` | Sets a `Set-Cookie` header | `res.cookie('remember', 1, { maxAge: minute })` |\\n| `res.clearCookie(name)` | Sets an expired `Set-Cookie` header | `res.clearCookie('remember')` |\\n| `req.cookies` | Parsed cookie object | `req.cookies.remember` |\\n\\nThe `cookie-parser` middleware automatically handles cookie decoding and signature verification. When a secret is provided, `cookie-parser` will populate `req.signedCookies` for any cookies prefixed with `s:` and verified against the secret. This example uses unsigned cookies for simplicity.\\n\\n## Request Flow\\n```mermaid\\nflowchart TD\\n    A[Client Request] --&gt; B{Method &amp; Path}\\n    B --&gt;|GET /| C[Check req.cookies.remember]\\n    B --&gt;|POST /| D[Parse req.body via urlencoded]\\n    B --&gt;|GET /forget| E[Clear cookie &amp; redirect]\\n    \\n    C --&gt;|Exists| F[Send 'Remembered' HTML]\\n    C --&gt;|Missing| G[Send Form HTML]\\n    \\n    D --&gt; H{req.body.remember?}\\n    H --&gt;|Yes| I[res.cookie maxAge: 60000]\\n    H --&gt;|No| J[Skip cookie set]\\n    I --&gt; K[Redirect to Referrer]\\n    J --&gt; K\\n    \\n    E --&gt; K\\n```\\n\\n## Running &amp; Testing\\n- **Start server**: `node index.js` (listens on port `3000` when executed directly)\\n- **Module export**: The app is exported via `module.exports = express()` for integration testing or mounting in larger applications.\\n- **Test environment**: Set `NODE_ENV=test` to suppress `morgan` logging during automated test runs.\\n\\n## Production Considerations\\nThis example is intentionally minimal. For production deployments, consider:\\n- **Security flags**: Add `httpOnly: true` and `secure: true` to `res.cookie` options to prevent XSS and enforce HTTPS.\\n- **Secret management**: Replace the hardcoded `'my secret here'` with an environment variable or secure vault.\\n- **CSRF protection**: Pair cookie-based state with CSRF tokens when handling POST requests.\\n- **SameSite attribute**: Set `sameSite: 'lax'` or `'strict'` to mitigate cross-site request forgery.\",\"other-downloads\":\"# Other \u2014 downloads\\n\\n# Other \u2014 Downloads Module\\n\\n## Overview\\nThis module is a standalone Express.js example demonstrating secure file downloads using `res.download()`. It serves files from a designated directory, handles nested paths via wildcard route parameters, and implements explicit error handling to distinguish between missing files and server-level failures.\\n\\n## Request Flow\\nThe module exposes two primary endpoints. The download route processes requests through Express's routing layer, resolves the target file path, and streams the file to the client or triggers an error callback.\\n\\n```mermaid\\nflowchart TD\\n    A[Client Request] --&gt; B{Route Match}\\n    B --&gt;|GET /| C[Render HTML Index]\\n    B --&gt;|GET /files/*| D[Parse req.params.file]\\n    D --&gt; E[res.download with root option]\\n    E --&gt; F{Callback Result}\\n    F --&gt;|Success| G[Stream File to Client]\\n    F --&gt;|Non-404 Error| H[next err]\\n    F --&gt;|404 Error| I[Custom 404 Response]\\n```\\n\\n## Core Implementation\\n\\n### Route Configuration\\nThe application defines two routes using `app.get()`:\\n- `GET /`: Returns a static HTML list containing direct links to test files, including nested paths and Unicode filenames.\\n- `GET /files/*file`: Captures any path following `/files/` using a wildcard parameter. The `*file` syntax instructs Express to populate `req.params.file` as an array of path segments.\\n\\n### File Download Handler\\nThe download logic relies on `res.download()` with a configuration object:\\n```javascript\\nres.download(req.params.file.join('/'), { root: FILES_DIR }, callback)\\n```\\n- **Path Resolution**: `req.params.file.join('/')` reconstructs the relative path from the array of captured segments (e.g., `['notes', 'groceries.txt']` becomes `'notes/groceries.txt'`).\\n- **Root Directory**: The `{ root: FILES_DIR }` option explicitly sets the base directory for file resolution. `FILES_DIR` is computed using `path.join(__dirname, 'files')` to ensure cross-platform compatibility.\\n- **Callback Execution**: The third argument is a completion callback invoked after the transfer finishes or fails.\\n\\n### Error Handling Strategy\\nThe callback implements a three-tier error resolution pattern:\\n1. **Success**: `if (!err) return;` \u2014 The file was successfully sent. No further action is required.\\n2. **Server/Non-404 Errors**: `if (err.status !== 404) return next(err);` \u2014 Passes permission errors, I/O failures, or malformed requests to Express's default error handler.\\n3. **Missing Files**: `res.statusCode = 404; res.send('Cant find that file, sorry!');` \u2014 Catches `ENOENT` or similar 404-status errors and returns a custom plain-text response.\\n\\n## Security &amp; Path Traversal Prevention\\nThe module mitigates directory traversal attacks by strictly binding file resolution to `FILES_DIR` via the `root` option in `res.download()`. Express automatically normalizes the requested path and rejects any attempts to escape the root directory using `../` sequences. This eliminates the need for manual path validation while maintaining secure file access.\\n\\n## Execution Context &amp; Dependencies\\n- **Dependencies**: `express` (core framework), `node:path` (path resolution)\\n- **Module Pattern**: Uses CommonJS `module.exports = express()` to allow the app to be required by test runners or other modules.\\n- **Standalone Execution**: The `if (!module.parent)` guard ensures the server only starts on port 3000 when executed directly via `node index.js`, preventing port conflicts when imported.\\n- **Call Graph**: The module contains no internal cross-file dependencies. All outgoing calls route directly to Express response methods (`res.send`, `res.download`) and the `next()` error propagation chain.\\n\\n## Running the Example\\n1. Ensure dependencies are installed: `npm install`\\n2. Start the server: `node examples/downloads/index.js`\\n3. Access the index page: `http://localhost:3000`\\n4. Test download behavior:\\n   - Valid file: `http://localhost:3000/files/amazing.txt`\\n   - Nested file: `http://localhost:3000/files/notes/groceries.txt`\\n   - Missing file: `http://localhost:3000/files/missing.txt` (triggers custom 404)\\n   - Unicode filename: `http://localhost:3000/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt`\",\"other-ejs\":\"# Other \u2014 ejs\\n\\n# Other \u2014 ejs\\n\\n## Overview\\nThis module demonstrates how to configure an Express.js application to use the EJS templating engine while maintaining `.html` file extensions for views. It covers custom view engine registration, layout composition via includes, static asset serving, and conditional server startup.\\n\\n## View Engine Configuration\\nThe core configuration maps the `.html` extension to EJS's internal rendering method:\\n\\n```javascript\\napp.engine('.html', require('ejs').__express);\\napp.set('view engine', 'html');\\n```\\n\\n- `app.engine('.html', require('ejs').__express)` registers EJS's `__express` function as the handler for `.html` files. This bypasses the default `.ejs` extension requirement.\\n- `app.set('view engine', 'html')` sets the default extension for `res.render()`, allowing calls like `res.render('users')` instead of `res.render('users.html')`.\\n- `app.set('views', path.join(__dirname, 'views'))` explicitly defines the template directory. While Express defaults to `./views`, this ensures predictable resolution regardless of the working directory.\\n\\n## Routing &amp; Data Flow\\nThe application defines a single route that renders a dynamic user list:\\n\\n```javascript\\napp.get('/', function(req, res){\\n  res.render('users', {\\n    users: users,\\n    title: \\\"EJS example\\\",\\n    header: \\\"Some users\\\"\\n  });\\n});\\n```\\n\\n- `res.render('users', ...)` triggers Express to locate `views/users.html`, compile it through the registered EJS engine, and inject the provided context object.\\n- The context passes an array of user objects (`{ name, email }`) and metadata (`title`, `header`) to the template.\\n\\n## Template Architecture\\nViews are split into reusable partials using EJS includes and interpolation syntax:\\n\\n| File | Purpose | Key EJS Patterns |\\n|------|---------|------------------|\\n| `views/header.html` | Document head &amp; opening body | `&lt;%= title %&gt;` (escaped interpolation) |\\n| `views/users.html` | Main content &amp; iteration | `&lt;%- include('header.html') -%&gt;`, `&lt;% users.forEach(...) %&gt;`, `&lt;%= user.name %&gt;` |\\n| `views/footer.html` | Closing tags | Static HTML closure |\\n\\n**Syntax Notes:**\\n- `&lt;%- include('...') -%&gt;` uses unescaped output (`&lt;%-`) to inject raw HTML partials without double-encoding. The trailing `-` trims surrounding whitespace.\\n- `&lt;%= ... %&gt;` safely escapes HTML entities, preventing XSS when rendering user-provided or dynamic strings.\\n- `&lt;% ... %&gt;` executes JavaScript logic (e.g., `forEach`) without outputting to the template.\\n\\n## Static Asset Serving\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\n- Mounts the `public/` directory at the root path (`/`).\\n- `views/header.html` references `/stylesheets/style.css`, which is resolved to `public/stylesheets/style.css` by the static middleware.\\n\\n## Module Execution &amp; Export Pattern\\n```javascript\\nvar app = module.exports = express();\\n\\n/* istanbul ignore next */\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n- `module.exports = express()` allows the file to be required as a module in tests or parent applications without triggering the server.\\n- The `!module.parent` guard ensures `app.listen(3000)` only executes when the file is run directly via `node index.js`.\\n- The `/* istanbul ignore next */` comment excludes the startup block from code coverage instrumentation.\\n\\n## Request Flow\\n```mermaid\\ngraph LR\\n  Client[Client Request] --&gt; Route[GET / Handler]\\n  Route --&gt; Render[res.render users]\\n  Render --&gt; EJS[EJS Engine]\\n  EJS --&gt; Header[header.html]\\n  EJS --&gt; Users[users.html]\\n  EJS --&gt; Footer[footer.html]\\n  EJS --&gt; Response[Compiled HTML]\\n```\",\"other-error-pages\":\"# Other \u2014 error-pages\\n\\n# Other \u2014 error-pages\\n\\n## Overview\\nThis module is an Express.js example application demonstrating production-ready error handling, content negotiation, and environment-aware configuration. It illustrates how to intentionally trigger HTTP errors, propagate them through the middleware stack, and render appropriate responses using Express's built-in error-handling patterns and EJS templating.\\n\\n## Request &amp; Error Flow\\nThe application follows a standard Express middleware pipeline. Successful requests are handled by route-specific callbacks. Unmatched routes or explicitly passed errors bypass standard middleware and fall through to dedicated error-handling layers.\\n\\n```mermaid\\nflowchart TD\\n    A[Incoming Request] --&gt; B{Route Match?}\\n    B --&gt;|Yes| C[Route Handler]\\n    B --&gt;|No| D[404 Catch-All Middleware]\\n    C --&gt;|next()| D\\n    C --&gt;|next(err)| E[500 Error Handler]\\n    D --&gt; F[res.format: HTML/JSON/TXT]\\n    E --&gt; G[Render 500.ejs]\\n    F --&gt; H[Response]\\n    G --&gt; H\\n```\\n\\n## Key Components\\n\\n### Configuration &amp; Environment\\nThe application configures view resolution and a custom application setting to control error verbosity:\\n- `app.set('views', path.join(__dirname, 'views'))` and `app.set('view engine', 'ejs')` establish the templating engine.\\n- `app.enable('verbose errors')` creates a custom setting accessible in templates via `settings['verbose errors']`.\\n- Production environments automatically disable verbose output: `if (app.settings.env === 'production') app.disable('verbose errors')`.\\n- Logging is conditionally applied: `silent || app.use(logger('dev'))` suppresses `morgan` output when `NODE_ENV=test`.\\n\\n### Route Handlers (Error Triggers)\\nRoutes are designed to demonstrate different error propagation techniques:\\n- `GET /` renders the landing page (`index.ejs`).\\n- `GET /404` calls `next()` without arguments. Since no subsequent middleware matches, the request falls through to the 404 catch-all.\\n- `GET /403` instantiates an `Error`, attaches `err.status = 403`, and passes it via `next(err)`. This immediately routes to error-handling middleware.\\n- `GET /500` passes a generic error via `next(new Error('keyboard cat!'))`, demonstrating default 500 fallback behavior.\\n\\n### Error-Handling Middleware\\nExpress distinguishes error-handling middleware by its **4-arity signature**: `(err, req, res, next)`.\\n\\n**404 Catch-All**\\n```javascript\\napp.use(function(req, res, next){\\n  res.status(404);\\n  res.format({ ... })\\n});\\n```\\nPlaced after all standard routes, this handler assumes any request reaching it is unmatched. It sets the HTTP status and delegates response formatting to `res.format()`.\\n\\n**500 Error Handler**\\n```javascript\\napp.use(function(err, req, res, next){\\n  res.status(err.status || 500);\\n  res.render('500', { error: err });\\n});\\n```\\nThis is the final middleware in the stack. It extracts the HTTP status from `err.status` (defaulting to `500`) and renders the error view. Calling `next()` or `next(err)` here would either continue to remaining non-error middleware or re-invoke error handlers, but the example terminates the response directly.\\n\\n### View Templates\\nEJS templates use partials for consistent layout and conditional rendering:\\n- `error_header.ejs` &amp; `footer.ejs`: Shared HTML shell.\\n- `404.ejs`: Displays the requested `url` passed from the middleware.\\n- `500.ejs`: Conditionally renders stack traces:\\n  ```ejs\\n  &lt;% if (settings['verbose errors']) { %&gt;\\n    \n&lt;%= error.stack %&gt;&lt;\\/pre&gt;\\n  &lt;% } else { %&gt;\\n    \nAn error occurred!&lt;\\/p&gt;\\n  &lt;% } %&gt;\\n  ```\\n\\n## Content Negotiation\\nThe 404 handler uses `res.format()` to serve different representations based on the `Accept` header:\\n- `html`: Renders `404.ejs` with the requested URL.\\n- `json`: Returns `{ error: 'Not found' }` via `res.json()`.\\n- `default`: Sets `Content-Type: text/plain` and sends `'Not found'` via `res.send()`.\\n\\nThis pattern allows the same endpoint to serve browser clients, API consumers, and CLI tools (e.g., `curl`) without duplicating routing logic.\\n\\n## Running &amp; Testing\\nStart the server:\\n```bash\\nnode examples/error-pages/index.js\\n```\\n\\nTest error responses:\\n```bash\\n# Trigger 404 (HTML)\\ncurl http://localhost:3000/notfound\\n\\n# Trigger 404 (JSON)\\ncurl http://localhost:3000/notfound -H \\\"Accept: application/json\\\"\\n\\n# Trigger 403\\ncurl http://localhost:3000/403\\n\\n# Trigger 500\\ncurl http://localhost:3000/500\\n```\\n\\nRun in production mode to verify verbose error suppression:\\n```bash\\nNODE_ENV=production node examples/error-pages/index.js\\n```\",\"other-error\":\"# Other \u2014 error\\n\\n# Other \u2014 Error Module\\n\\n## Overview\\nThis module demonstrates Express.js error handling patterns, focusing on synchronous error throwing, asynchronous error propagation, and the implementation of a centralized error-handling middleware. It serves as a reference implementation for routing exceptions to a dedicated handler while maintaining environment-aware logging.\\n\\n## Execution Flow &amp; Architecture\\nRequests enter the Express router and match defined route handlers. If an error occurs\u2014either synchronously via `throw` or asynchronously via `next(err)`\u2014Express bypasses standard middleware and routes the error to the first registered middleware with a 4-argument signature. The error handler logs the stack trace (conditionally), sets an HTTP 500 status, and terminates the response.\\n\\n```mermaid\\ngraph TD\\n  A[Incoming Request] --&gt; B{Route Match}\\n  B --&gt;|GET /| C[Sync: throw Error]\\n  B --&gt;|GET /next| D[Async: next Error]\\n  C --&gt; E[Express Error Router]\\n  D --&gt; E\\n  E --&gt; F[error Middleware]\\n  F --&gt; G[res.send 500]\\n```\\n\\n## Key Components\\n\\n### `error(err, req, res, next)`\\nThe core error-handling middleware. Express identifies this function as an error handler strictly by its 4-argument arity.\\n- **Error Logging**: Conditionally outputs `err.stack` to `console.error` when `app.get('env') !== 'test'`.\\n- **Response Handling**: Sets `res.status(500)` and calls `res.send('Internal Server Error')` to terminate the request cycle.\\n- **Signature Requirement**: Must maintain `(err, req, res, next)` exactly. Omitting or reordering parameters will cause Express to treat it as standard middleware, breaking error routing.\\n\\n### Route Handlers\\n- **`app.get('/')`**: Demonstrates synchronous error handling. Uses `throw new Error('something broke!')`. Express automatically catches the thrown exception and passes it down the middleware chain.\\n- **`app.get('/next')`**: Demonstrates asynchronous error handling. Wraps the error propagation in `process.nextTick()` to simulate non-blocking I/O (e.g., database queries or HTTP requests). Explicitly passes the error to `next(new Error('oh no!'))`.\\n\\n### Environment &amp; Configuration\\n- **Test Gating**: `var test = app.get('env') === 'test'` suppresses `morgan` logging and console error output during automated test runs.\\n- **Module Export**: `var app = module.exports = express()` allows the application to be required by test suites or mounted as a sub-app in larger Express architectures.\\n- **Standalone Execution**: The `if (!module.parent)` block starts the server on port 3000 only when the file is executed directly.\\n\\n## Middleware Ordering &amp; Integration\\nThe error handler is registered **after** all route definitions:\\n```javascript\\napp.get('/', ...);\\napp.get('/next', ...);\\napp.use(error); // Must be last\\n```\\nPlacing `app.use(error)` before route definitions will prevent it from receiving errors thrown or passed by those routes. Express evaluates middleware sequentially; error handlers are only invoked when an error is explicitly passed or thrown downstream.\\n\\n## Contributor Guidelines\\n- **Maintain 4-Arity**: Any new error-handling middleware must accept exactly four parameters. Use `(err, req, res, next)` even if `req` or `next` are unused.\\n- **Preserve Order**: Always register error-handling middleware at the end of the middleware stack.\\n- **Async Safety**: Never rely on `try/catch` for asynchronous operations. Always pass errors to `next(err)` to ensure they reach the error handler.\\n- **Environment Checks**: Keep logging and verbose error details gated behind `app.get('env') !== 'test'` to maintain clean CI/CD output.\\n- **Response Termination**: Ensure the error handler calls a response method (`res.send`, `res.json`, `res.end`) to prevent hanging requests.\",\"other-examples\":\"# Other \u2014 examples\\n\\n# Other \u2014 Examples Module\\n\\n## Overview\\nThe `examples/` directory contains a curated collection of standalone Express.js applications. Each subdirectory demonstrates a specific framework capability, common web development pattern, or integration technique. This module serves as a reference implementation, learning resource, and testing ground for developers working with Express.\\n\\n## Example Catalog\\nThe examples are organized by functional domain. Each entry corresponds to a self-contained directory within `examples/`.\\n\\n### Routing &amp; Middleware\\n- `hello-world` \u2014 Simple request handler\\n- `params` \u2014 Working with route parameters\\n- `route-middleware` \u2014 Working with route middleware\\n- `route-separation` \u2014 Organizing routes per each resource\\n- `multi-router` \u2014 Working with multiple Express routers\\n- `route-map` \u2014 Organizing routes using a map\\n- `resource` \u2014 Multiple HTTP operations on the same resource\\n\\n### Sessions, Cookies &amp; Authentication\\n- `auth` \u2014 Authentication with login and password\\n- `cookie-sessions` \u2014 Working with cookie-based sessions\\n- `cookies` \u2014 Working with cookies\\n- `session` \u2014 User sessions\\n- `online` \u2014 Tracking online user activity with `online` and `redis` packages\\n\\n### Views &amp; Templating\\n- `ejs` \u2014 Working with Embedded JavaScript templating (ejs)\\n- `markdown` \u2014 Markdown as template engine\\n- `view-constructor` \u2014 Rendering views dynamically\\n- `view-locals` \u2014 Saving data in request object between middleware calls\\n- `error-pages` \u2014 Creating error pages\\n\\n### HTTP, API &amp; Infrastructure\\n- `content-negotiation` \u2014 HTTP content negotiation\\n- `downloads` \u2014 Transferring files to client\\n- `static-files` \u2014 Serving static files\\n- `search` \u2014 Search API\\n- `web-service` \u2014 Simple API service\\n- `vhost` \u2014 Working with virtual hosts\\n\\n### Architecture &amp; Error Handling\\n- `mvc` \u2014 MVC-style controllers\\n- `error` \u2014 Working with error middleware\\n\\n## Execution Model &amp; Isolation\\nBased on the module's call graph analysis:\\n- **No Internal Calls:** Examples do not import or reference each other. Each directory is a completely isolated Express application.\\n- **No Shared Execution Flows:** There are no cross-module execution paths. Each example initializes its own `express()` instance, configures middleware, and starts an independent HTTP server.\\n- **Dependency Scope:** Dependencies are scoped locally to each example's `package.json`. Running one example does not affect the runtime state of another.\\n\\n## Getting Started\\nTo run any example locally:\\n1. Navigate to the target directory: `cd examples/`\\n2. Install dependencies: `npm install`\\n3. Start the server: `node app.js` (or `node index.js`, depending on the entry point defined in the example)\\n4. Access the application at `http://localhost:` (port configuration varies per example; check the source or console output)\\n\\n## Contribution Guidelines\\nWhen adding or modifying examples:\\n- **Maintain Isolation:** Do not introduce cross-directory imports or shared state. Each example must run independently.\\n- **Document Entry Points:** Ensure the primary server file is clearly named (`app.js` or `index.js`) and includes a startup log indicating the listening port.\\n- **Update Index:** Add new examples to this `README.md` with a concise, one-line description matching the existing format.\\n- **Keep Dependencies Minimal:** Only include packages strictly required to demonstrate the target concept. Avoid bundling unrelated utilities.\\n- **Follow Express Conventions:** Use standard middleware ordering, explicit error handling, and clear route definitions.\\n\\n## Key Patterns Demonstrated\\nThis module covers foundational and advanced Express patterns:\\n- **Middleware Chaining:** Demonstrated in `route-middleware`, `error`, and `view-locals`\\n- **Router Composition:** Illustrated in `multi-router`, `route-separation`, and `route-map`\\n- **State Management:** Covered via `cookies`, `cookie-sessions`, `session`, and `online`\\n- **Response Formatting:** Shown in `content-negotiation`, `downloads`, and `static-files`\\n- **View Engine Integration:** Implemented in `ejs`, `markdown`, and `view-constructor`\\n- **Architectural Layouts:** Structured in `mvc` and `resource`\",\"other-hello-world\":\"# Other \u2014 hello-world\\n\\n# Other \u2014 hello-world\\n\\n## Overview\\nThe `hello-world` module (`examples/hello-world/index.js`) is a minimal, self-contained Express.js application. It demonstrates foundational framework patterns including application initialization, route registration, response handling, and conditional server startup. The module is designed to function both as a standalone executable and as a reusable component for testing or integration.\\n\\n## Usage Patterns\\n\\n### Standalone Execution\\nRun directly via Node.js to start a local HTTP server:\\n```bash\\nnode examples/hello-world/index.js\\n```\\nThe server binds to port `3000` and responds to `GET /` with `Hello World`.\\n\\n### Module Import\\nImport the configured application instance without triggering the server listener:\\n```javascript\\nconst app = require('./examples/hello-world');\\n// Use `app` in test suites, middleware chains, or custom server wrappers\\n```\\n\\n## Architecture &amp; Key Components\\n\\n| Component | Purpose |\\n|-----------|---------|\\n| `express()` | Initializes the core Express application instance. |\\n| `app.get('/', handler)` | Registers a route handler for HTTP `GET` requests to the root path. |\\n| `res.send('Hello World')` | Terminates the request cycle by sending a plain-text response. |\\n| `module.exports = app` | Exposes the application instance for external consumption. |\\n| `if (!module.parent)` | Node.js module guard that detects direct execution vs. `require()`. |\\n| `app.listen(3000)` | Binds the HTTP server to port 3000 when executed directly. |\\n\\n## Execution Flow\\n\\n```mermaid\\nflowchart TD\\n    A[Module Load] --&gt; B[Initialize Express App]\\n    B --&gt; C[Register GET / Route]\\n    C --&gt; D{Run Directly?}\\n    D --&gt;|Yes| E[app.listen(3000)]\\n    D --&gt;|No| F[Export App Instance]\\n    E --&gt; G[Handle Incoming Requests]\\n    G --&gt; H[Invoke Route Handler]\\n    H --&gt; I[res.send Response]\\n```\\n\\n1. **Initialization**: The module loads, imports the Express framework from the parent directory, and instantiates the application.\\n2. **Route Registration**: A single `GET` route is attached to `/`. The handler receives `(req, res)` and immediately calls `res.send()`.\\n3. **Conditional Startup**: The `!module.parent` check determines execution context. If the file is the entry point, `app.listen(3000)` starts the server. If required elsewhere, the listener is skipped, allowing the exported `app` to be mounted or tested.\\n4. **Request Handling**: Incoming requests matching `GET /` trigger the registered callback, which writes the response and closes the connection.\\n\\n## Testing &amp; Coverage Notes\\n- **Coverage Exclusion**: The `/* istanbul ignore next */` directive explicitly excludes the standalone execution block from code coverage reports. This is intentional, as the block only runs during direct execution and is not part of the module's reusable API.\\n- **Test Compatibility**: Exporting `app` enables standard Express testing patterns. Tools like `supertest` can inject mock requests directly into the exported instance without opening a real network port.\\n- **Dependency Scope**: The module relies solely on the local Express build (`require('../../')`). It contains no internal middleware, error handlers, or additional routing layers, making it a clean baseline for example expansion or framework validation.\",\"other-history-md\":\"# Other \u2014 History.md\\n\\n# History.md \u2014 Express.js Release Changelog\\n\\n## Overview\\n`History.md` serves as the canonical release log and migration reference for the Express.js framework. It documents every public API change, dependency update, security patch, and behavioral adjustment across all major, minor, and patch versions. Developers use this file to:\\n- Plan version upgrades and identify breaking changes\\n- Understand the evolution of request/response contracts\\n- Track dependency lifecycles and security advisories\\n- Verify deprecation timelines and replacement APIs\\n\\n## Format &amp; Conventions\\nThe changelog follows a strict, machine-parseable structure optimized for rapid scanning and automated tooling:\\n\\n| Prefix | Meaning | Example |\\n|--------|---------|---------|\\n| `breaking:` | Incompatible API or behavioral changes requiring code updates | `res.status()` now validates integer range |\\n| `change:` | Modified behavior that remains backward-compatible | `req.query` converted from property to getter |\\n| `add:` | New features, methods, or configuration options | `res.sendStatus()`, `Uint8Array` support in `res.send()` |\\n| `remove:` | Deleted APIs, dependencies, or legacy behaviors | `app.del`, `req.param()`, `express.query` middleware |\\n| `deprecate:` | APIs scheduled for removal in future major versions | `res.redirect(url, status)` \u2192 `res.redirect(status, url)` |\\n| `fix:` | Bug corrections, edge-case handling, or spec compliance | `res.jsonp` handling of `undefined`, `qs` prototype pollution |\\n| `perf:` | Runtime optimizations or reduced overhead | Loop-based `acceptParams`, removed `Buffer` allocations |\\n| `deps:` | Third-party package version bumps or removals | `body-parser@^2.2.1`, removal of `safe-buffer` |\\n\\n## API Evolution &amp; Migration Reference\\n\\n### Response Object (`res.*`)\\nThe response API has shifted from flexible, overloaded signatures to strict, chainable, and type-safe patterns.\\n\\n| Legacy Pattern | Current Pattern | Notes |\\n|----------------|-----------------|-------|\\n| `res.send(body, status)` | `res.status(status).send(body)` | Removed in 5.0.0-alpha.6 |\\n| `res.json(obj, status)` | `res.status(status).json(obj)` | Deprecated in 4.7.0, removed in 5.0.0-alpha.3 |\\n| `res.redirect(url, status)` | `res.redirect(status, url)` | Deprecated in 4.6.0, removed in 5.0.0-alpha.6 |\\n| `res.redirect('back')` | `res.redirect(req.get('Referrer') || '/')` | Magic string removed in 5.0.0 |\\n| `res.sendfile()` | `res.sendFile()` | Deprecated in 4.8.0, requires absolute path or `root` option |\\n| `res.clearCookie(name, { maxAge, expires })` | `res.clearCookie(name)` | `maxAge`/`expires` ignored in v5; cookie is expired immediately |\\n\\n**Recent Behavioral Updates:**\\n- `res.status(code)` now throws `RangeError` for codes outside `100\u2013999` and `TypeError` for non-integers (5.0.0)\\n- `res.send()` natively supports `Uint8Array` payloads (5.1.0)\\n- `res.sendFile()` accepts an `etag` option for cache control (5.1.0)\\n- `res.links()` supports multiple headers with identical `rel` attributes (5.1.0)\\n- `res.redirect()` HTML responses now include proper ``, ``, and `` structure for browser compatibility (Unreleased)\\n\\n### Request &amp; Routing (`req.*`, `app.*`, `Router`)\\nRouting and request parsing have been decoupled from Connect and hardened against prototype pollution and ambiguous parameter resolution.\\n\\n- `req.param(name)` removed; use `req.params`, `req.body`, or `req.query` explicitly (5.0.0-alpha.2)\\n- `req.host` returns `hostname:port`; use `req.hostname` for hostname-only (4.5.0)\\n- `req.query` is now a getter instead of a plain property (5.0.0-alpha.1)\\n- `app.param(fn)` removed; use `app.param(name, fn)` without leading `:` (5.0.0-alpha.2)\\n- `app.set('query parser', parser)` controls parsing strategy:\\n  - `'simple'` (default in 5.0.0-beta.1): uses Node's `querystring`\\n  - `'extended'`: uses `qs` with depth/length limits\\n  - `false`: disables parsing\\n- `Router` now supports `next(\\\"router\\\")` to exit router scope early (4.15.0)\\n- `app.render('view', null, callback)` correctly handles `null` options, matching omitted/empty object behavior (Unreleased)\\n\\n### Application Configuration\\n- `app.set('etag', val)` supports `'weak'`, `'strong'`, `false`, `true`, or a custom generator function (4.4.0)\\n- `app.set('trust proxy', trust)` accepts hop counts, IP ranges, subnets, or `'loopback'` (4.3.0)\\n- `app.set('views', array)` enables sequential view directory lookup (4.10.0)\\n- `app.router` is no longer a configurable middleware; it is a reference to the base router instance (4.0.0)\\n\\n## Security &amp; Dependency Tracking\\nThe changelog explicitly tracks security patches, CVE resolutions, and dependency lifecycle changes.\\n\\n- **CVE Tracking:** Security fixes are linked to CVE records and GitHub Security Advisories (e.g., `CVE-2024-51999`, `CVE-2024-47764`)\\n- **Open Redirect Mitigation:** `res.redirect()` and `res.location()` now validate and encode URLs to prevent allow-list bypasses (4.19.0)\\n- **Query Parser Hardening:** `qs` depth defaults to `32` (previously `Infinity`) to prevent ReDoS and memory exhaustion (4.20.0)\\n- **Prototype Pollution Prevention:** `qs` and `app.set`/`app.get` ignore `Object.prototype` keys (4.17.3, 4.18.0)\\n- **Dependency Pruning:** Legacy polyfills and utilities (`setprototypeof`, `safe-buffer`, `utils-merge`, `methods`, `depd`, `path-is-absolute`) have been removed in favor of native Node.js APIs or modern replacements (5.1.0)\\n\\n## Developer Workflow &amp; Upgrade Strategy\\n\\n1. **Identify Target Version:** Locate the desired version header (e.g., `5.0.0 / 2024-09-10`)\\n2. **Scan for `breaking:` and `remove:` Entries:** These require immediate code changes before upgrading\\n3. **Check `deprecate:` Warnings:** Plan refactoring for the next major release\\n4. **Review `deps:` Updates:** Verify compatibility with your existing middleware stack, especially `body-parser`, `qs`, and `serve-static`\\n5. **Validate Security Patches:** Cross-reference CVE links with your threat model and compliance requirements\\n6. **Test with `app.render` and `res.send` Edge Cases:** Recent fixes address `null` options, `Uint8Array` handling, and Content-Type deduplication\\n\\nWhen contributing to Express, follow the established changelog format. Prefix entries with the appropriate category, link to PRs and issues, and include minimal code examples for breaking changes or new APIs.\",\"other-markdown\":\"# Other \u2014 markdown\\n\\n# Other \u2014 Markdown\\n\\n## Overview\\nThis module demonstrates how to register a custom view engine in Express.js to render Markdown (`.md`) files as HTML. It integrates the `marked` library for parsing and implements a lightweight, secure template interpolation system using `{variable}` syntax. The example serves as a reference for extending Express's view system without relying on third-party templating engines.\\n\\n## Architecture &amp; Request Flow\\nWhen a route calls `res.render()`, Express delegates rendering to the registered `.md` engine. The engine asynchronously reads the file, parses Markdown to HTML, interpolates variables, and returns the result via a callback.\\n\\n```mermaid\\nsequenceDiagram\\n  participant Client\\n  participant Express\\n  participant Engine\\n  participant FS\\n  Client-&gt;&gt;Express: GET /\\n  Express-&gt;&gt;Express: res.render('index', {title})\\n  Express-&gt;&gt;Engine: app.engine('md', path, options, fn)\\n  Engine-&gt;&gt;FS: fs.readFile(path, 'utf8')\\n  FS--&gt;&gt;Engine: raw markdown string\\n  Engine-&gt;&gt;Engine: marked.parse() + regex interpolation\\n  Engine--&gt;&gt;Express: fn(null, html)\\n  Express--&gt;&gt;Client: 200 OK (HTML)\\n```\\n\\n## Core Components\\n\\n### Custom View Engine Registration\\nThe engine is registered using `app.engine('md', callback)`. Express invokes this callback whenever a `.md` view is rendered.\\n\\n```javascript\\napp.engine('md', function(path, options, fn){\\n  fs.readFile(path, 'utf8', function(err, str){\\n    if (err) return fn(err);\\n    var html = marked.parse(str).replace(/\\\\{([^}]+)\\\\}/g, function(_, name){\\n      return escapeHtml(options[name] || '');\\n    });\\n    fn(null, html);\\n  });\\n});\\n```\\n\\n**Parameters:**\\n- `path`: Absolute file path to the `.md` template.\\n- `options`: Object containing variables passed from `res.render(view, locals)`.\\n- `fn`: Callback following the `(err, html)` signature expected by Express.\\n\\n**Processing Steps:**\\n1. Reads the template file asynchronously via `fs.readFile`.\\n2. Converts Markdown to HTML using `marked.parse()`.\\n3. Replaces `{placeholder}` patterns with corresponding values from `options`.\\n4. Escapes interpolated values using `escapeHtml` to prevent XSS.\\n5. Returns the final HTML string or propagates errors.\\n\\n### Template Interpolation\\nThe module uses a simple regex-based substitution pattern: `/\\\\{([^}]+)\\\\}/g`. Placeholders in the template are replaced with values from the `options` object. If a key is missing, it defaults to an empty string (`''`).\\n\\n**Example (`views/index.md`):**\\n```markdown\\n# {title}\\n\\nJust an example view rendered with _markdown_.\\n```\\nWhen rendered with `{ title: 'Markdown Example' }`, the output becomes:\\n```html\\n\nMarkdown Example&lt;\\/h1&gt;\\n\nJust an example view rendered with markdown&lt;\\/em&gt;.&lt;\\/p&gt;\\n```\\n\\n### Route Handlers\\n- `GET /`: Successfully renders `index.md` and passes `{ title: 'Markdown Example' }`.\\n- `GET /fail`: Intentionally attempts to render a non-existent `missing.md` file. This triggers the `fs.readFile` error path, demonstrating how errors are propagated to Express via `fn(err)`.\\n\\n## Configuration\\n```javascript\\napp.set('views', path.join(__dirname, 'views'));\\napp.set('view engine', 'md');\\n```\\n- `views`: Sets the directory where Express looks for template files.\\n- `view engine`: Registers `md` as the default extension. This allows `res.render('index')` to automatically resolve to `index.md`.\\n\\n## Error Handling\\nFile system errors (e.g., missing templates, permission issues) are caught in the `fs.readFile` callback and passed directly to `fn(err)`. Express intercepts this error and invokes its default error-handling middleware, typically resulting in a `500 Internal Server Error` response. The `/fail` route explicitly validates this behavior.\\n\\n## Execution &amp; Standalone Usage\\nThe module exports the configured Express application:\\n```javascript\\nvar app = module.exports = express();\\n```\\nIt includes a standard execution guard to allow standalone testing:\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\nRun directly with `node index.js` to start the server. Require it in another module to mount or test the routes.\\n\\n## Dependencies\\n| Package | Purpose |\\n|---------|---------|\\n| `express` | Web framework and view system |\\n| `marked` | Markdown-to-HTML parser |\\n| `escape-html` | HTML entity escaping for safe interpolation |\\n| `node:fs` | Asynchronous file reading |\\n| `node:path` | Cross-platform path resolution |\",\"other-multi-router\":\"# Other \u2014 multi-router\\n\\n# Other \u2014 multi-router\\n\\n## Overview\\nThe `multi-router` module demonstrates Express.js's modular routing architecture using `express.Router()`. It illustrates how to isolate route definitions into separate controller files and mount them at distinct base paths (`/api/v1` and `/api/v2`) within a single Express application. This pattern is standard for API versioning, feature isolation, and maintaining decoupled route hierarchies.\\n\\n## Architecture &amp; File Structure\\n```\\nexamples/multi-router/\\n\u251c\u2500\u2500 index.js                 # Main application entry point &amp; server bootstrap\\n\u2514\u2500\u2500 controllers/\\n    \u251c\u2500\u2500 api_v1.js            # Router instance for API v1 endpoints\\n    \u2514\u2500\u2500 api_v2.js            # Router instance for API v2 endpoints\\n```\\n\\n## Core Components\\n\\n### `controllers/api_v1.js` &amp; `controllers/api_v2.js`\\nBoth controller files follow an identical structural pattern:\\n1. Import Express: `var express = require('../../..');`\\n2. Instantiate an isolated router: `var apiv1 = express.Router();` (or `apiv2`)\\n3. Register route handlers using `router.get(path, callback)`\\n4. Export the router: `module.exports = apiv1;`\\n\\nEach router defines two endpoints:\\n- `GET /` \u2192 Responds with a version-specific root message\\n- `GET /users` \u2192 Responds with a version-specific user list message\\n\\nBoth handlers terminate the request-response cycle using `res.send()`.\\n\\n### `index.js`\\nThe application entry point orchestrates routing and server lifecycle:\\n- Creates the main Express app: `var app = module.exports = express();`\\n- Mounts versioned routers using `app.use(basePath, router)`:\\n  ```js\\n  app.use('/api/v1', require('./controllers/api_v1'));\\n  app.use('/api/v2', require('./controllers/api_v2'));\\n  ```\\n- Defines a fallback root route: `app.get('/', function(req, res) { ... })`\\n- Conditionally starts the HTTP server on port `3000` when executed directly:\\n  ```js\\n  if (!module.parent) {\\n    app.listen(3000);\\n    console.log('Express started on port 3000');\\n  }\\n  ```\\n\\n## Routing &amp; Mounting Behavior\\nExpress routers function as mini-applications. When mounted via `app.use()`, Express automatically prefixes all routes defined within the router with the specified base path. This allows controllers to define routes relative to their own context (`/`, `/users`) while remaining completely agnostic of their final public paths.\\n\\n```mermaid\\ngraph TD\\n  App[Express App index.js] --&gt;|/api/v1| V1[api_v1 Router]\\n  App --&gt;|/api/v2| V2[api_v2 Router]\\n  App --&gt;|/| Root[Root Handler]\\n  V1 --&gt;|GET /| V1Root[res.send APIv1 root]\\n  V1 --&gt;|GET /users| V1Users[res.send APIv1 users]\\n  V2 --&gt;|GET /| V2Root[res.send APIv2 root]\\n  V2 --&gt;|GET /users| V2Users[res.send APIv2 users]\\n```\\n\\n## Request Execution Flow\\n1. An incoming HTTP request reaches the Express app instance\\n2. Express evaluates mounted middleware/routers in registration order\\n3. If the request path begins with `/api/v1` or `/api/v2`, Express strips the prefix and delegates control to the corresponding router\\n4. The router matches the remaining path segment against its internal `router.get()` definitions\\n5. The matched handler executes and calls `res.send()` to finalize the response\\n6. Requests targeting `/` bypass both routers and trigger the root handler defined directly in `index.js`\\n\\n## Extension Guidelines\\n- **Adding API Versions:** Create a new controller file following the existing pattern, export the router, and mount it in `index.js` with `app.use('/api/vX', require('./controllers/api_vX'))`.\\n- **Version-Specific Middleware:** Attach middleware directly to the router instance before route definitions (e.g., `apiv1.use(express.json())`). This scopes the middleware exclusively to that version's endpoints.\\n- **Testing:** The exported `app` instance in `index.js` can be passed directly to testing utilities like `supertest`. Mock `req`/`res` objects or use integration tests to verify `res.send()` payloads.\\n- **Standalone Execution:** The `if (!module.parent)` guard ensures the server only starts when the file is run directly via `node index.js`, preventing port conflicts when the module is imported as a dependency.\",\"other-mvc\":\"# Other \u2014 mvc\\n\\n## Module Overview\\n\\nThe `mvc` module is a reference Express.js application demonstrating a convention-over-configuration approach to structuring Model-View-Controller (MVC) applications. It dynamically loads controllers from the `controllers/` directory, automatically generates RESTful routes based on exported method names, and supports per-controller view engine configuration. This module serves as an architectural blueprint for scaling Express apps without manual route registration.\\n\\n## Architecture &amp; Directory Structure\\n\\n```\\nexamples/mvc/\\n\u251c\u2500\u2500 index.js              # Main Express app, middleware, and bootstrapper entry\\n\u251c\u2500\u2500 lib/boot.js           # Dynamic controller loader and route generator\\n\u251c\u2500\u2500 db.js                 # In-memory mock database\\n\u251c\u2500\u2500 controllers/          # Modular controller directories\\n\u2502   \u251c\u2500\u2500 main/             # Root redirect controller\\n\u2502   \u251c\u2500\u2500 user/             # User CRUD (uses Handlebars)\\n\u2502   \u251c\u2500\u2500 pet/              # Pet CRUD (uses EJS)\\n\u2502   \u2514\u2500\u2500 user-pet/         # Nested resource creation\\n\u251c\u2500\u2500 views/                # Global error templates (404, 5xx)\\n\u2514\u2500\u2500 public/               # Static assets\\n```\\n\\n## Core Components\\n\\n### Application Entry (`index.js`)\\nInitializes the Express application and configures foundational middleware:\\n- Sets default view engine to `ejs` and global views directory.\\n- Extends `res` with `res.message(msg)` to store flash messages in `req.session.messages`.\\n- Configures `express-session`, `express.urlencoded({ extended: true })`, and `method-override('_method')`.\\n- Injects `messages` and `hasMessages` into `res.locals` for template rendering, then flushes the session array.\\n- Mounts controllers via `require('./lib/boot')(app, { verbose: !module.parent })`.\\n- Defines fallback 404 and 500 error handlers.\\n\\n### Controller Bootstrapper (`lib/boot.js`)\\nThe `boot` function scans `controllers/`, loads each directory as a module, and maps exported functions to Express routes. It respects reserved exports (`name`, `prefix`, `engine`, `before`) and applies the following routing convention:\\n\\n| Exported Method | HTTP Method | Generated URL Pattern          |\\n|-----------------|-------------|--------------------------------|\\n| `index`         | `GET`       | `/`                            |\\n| `list`          | `GET`       | `/s`                     |\\n| `show`          | `GET`       | `//:_id`           |\\n| `edit`          | `GET`       | `//:_id/edit`      |\\n| `update`        | `PUT`       | `//:_id`           |\\n| `create`        | `POST`      | `/`                      |\\n\\nIf a controller exports a `before` function, it is injected as middleware before the route handler. The generated routes are mounted on a sub-app and attached to the parent Express instance.\\n\\n### Controllers\\nEach controller is a Node.js module exporting route handlers and optional configuration:\\n- `main/index.js`: Exports `index` to redirect `/` to `/users`.\\n- `user/index.js`: Exports `list`, `show`, `edit`, `update`. Sets `exports.engine = 'hbs'`. Uses `exports.before` to asynchronously load `req.user` from `db.users` based on `req.params.user_id`. Calls `next('route')` if not found.\\n- `pet/index.js`: Exports `show`, `edit`, `update`. Sets `exports.engine = 'ejs'`. Uses `exports.before` to load `req.pet` from `db.pets` via `req.params.pet_id`.\\n- `user-pet/index.js`: Exports `create`. Sets `exports.name = 'pet'` and `exports.prefix = '/user/:user_id'` to create nested routes like `POST /user/:user_id/pet`.\\n\\n### Mock Database (`db.js`)\\nProvides `exports.pets` and `exports.users` arrays with pre-seeded data. Used by controllers to simulate database queries and mutations.\\n\\n## Key Features &amp; Patterns\\n\\n### Flash Messaging System\\nMessages are stored in the session via `res.message('Information updated!')`. A middleware in `index.js` exposes them to templates:\\n```javascript\\nres.locals.messages = req.session.messages || [];\\nres.locals.hasMessages = !!res.locals.messages.length;\\nreq.session.messages = []; // Flush after exposure\\n```\\nTemplates (e.g., `user/views/show.hbs`) conditionally render messages using `{{#if hasMessages}}`.\\n\\n### Per-Controller View Engines\\nWhile the app defaults to `ejs`, individual controllers can override this. The `user` controller sets `exports.engine = 'hbs'`, causing `boot.js` to call `app.set('view engine', 'hbs')` for that sub-app. Views are resolved from `controllers//views/`.\\n\\n### HTTP Method Override\\nHTML forms only support `GET` and `POST`. The app uses `method-override('_method')` to interpret `?_method=put` in form actions as `PUT` requests, enabling RESTful `update` operations.\\n\\n## Request Lifecycle &amp; Routing Flow\\n\\n```mermaid\\ngraph TD\\n  A[Incoming Request] --&gt; B[Middleware: session/body/method-override]\\n  B --&gt; C[boot.js Generated Routes]\\n  C --&gt; D{exports.before?}\\n  D --&gt;|Yes| E[Run before middleware]\\n  D --&gt;|No| F[Route Handler]\\n  E --&gt; F\\n  F --&gt; G[Render View / Redirect]\\n```\\n\\n## Extending the Module\\n\\nTo add a new resource:\\n1. Create a directory under `controllers/` (e.g., `controllers/article/`).\\n2. Create `index.js` exporting route handlers (`list`, `show`, `create`, etc.).\\n3. Optionally export `before` for pre-route logic, `engine` to change the template engine, or `prefix`/`name` to customize URL generation.\\n4. Add a `views/` subdirectory with templates matching the exported handler names (e.g., `list.ejs`, `show.ejs`).\\n5. Restart the app; `lib/boot.js` will automatically register the routes.\\n\\n## Notes for Contributors\\n- Route generation relies on exact function name matches. Custom handlers outside the convention will throw `unrecognized route: .`.\\n- The `before` middleware must call `next()` to proceed or `next('route')` to skip to the next matching route.\\n- Session secret is hardcoded for example purposes. Replace with environment variables in production.\\n- The mock `db.js` uses array indices as IDs. Real implementations should replace this with a proper ORM or database client.\",\"other-online\":\"# Other \u2014 online\\n\\n# Other \u2014 online\\n\\n## Overview\\nThis module demonstrates how to track and display recently active users in an Express application using the `online` package backed by Redis. It implements a fire-and-forget activity tracking middleware and provides a simple endpoint to query and render the most recent active identifiers.\\n\\n## Prerequisites\\n- Running Redis server (`redis-server`)\\n- npm packages: `express`, `online`, `redis`\\n- Node.js environment\\n\\n## Architecture &amp; Data Flow\\nThe module initializes a Redis client and binds it to the `online` package. An Express middleware intercepts every incoming request, extracts an identifier, and asynchronously records it in Redis. A separate route handler queries the last N active identifiers and renders them as HTML.\\n\\n```mermaid\\ngraph LR\\n  Client --&gt;|HTTP Request| Express\\n  Express --&gt;|Middleware| online.add\\n  online.add --&gt;|Async Write| Redis\\n  Express --&gt;|GET /| online.last\\n  online.last --&gt;|Sorted Set Query| Redis\\n  Redis --&gt;|Return IDs| Express\\n  Express --&gt;|res.send| Client\\n```\\n\\n## Key Components\\n\\n### Redis &amp; Online Initialization\\n```javascript\\nvar redis = require('redis');\\nvar db = redis.createClient();\\nonline = online(db);\\n```\\nThe `online` package is instantiated with a Redis client instance. This configuration enables the package to use Redis sorted sets for time-based activity tracking, allowing efficient retrieval of recently active keys.\\n\\n### Activity Tracking Middleware\\n```javascript\\napp.use(function(req, res, next){\\n  online.add(req.headers['user-agent']);\\n  next();\\n});\\n```\\nThis middleware executes on every request. It calls `online.add()` with the `User-Agent` header as the tracking identifier. The operation is fire-and-forget: it does not await Redis acknowledgment before calling `next()`, ensuring zero latency impact on the request pipeline.\\n\\n**Production Note:** Replace `req.headers['user-agent']` with a stable, unique identifier such as `req.user.id`, session ID, or device token.\\n\\n### Route Handler &amp; Response\\n```javascript\\napp.get('/', function(req, res, next){\\n  online.last(5, function(err, ids){\\n    if (err) return next(err);\\n    res.send('\nUsers online: ' + ids.length + '&lt;\\/p&gt;' + list(ids));\\n  });\\n});\\n```\\nThe `GET /` route queries the last 5 active identifiers using `online.last(5, callback)`. Errors are delegated to Express's error handling pipeline via `next(err)`. On success, the response payload is constructed and sent using `res.send()`.\\n\\n### Helper Function\\n```javascript\\nfunction list(ids) {\\n  return '\n' + ids.map(function(id){\\n    return '\n' + id + '&lt;\\/li&gt;';\\n  }).join('') + '&lt;\\/ul&gt;';\\n}\\n```\\nA synchronous utility that transforms an array of identifiers into an HTML unordered list. It is invoked internally by the route handler and contains no external dependencies.\\n\\n## Integration &amp; Extension Guidelines\\n\\n- **Identifier Strategy:** The example uses `User-Agent` for demonstration purposes. For accurate user tracking, integrate with your authentication layer and pass `req.user.id` or equivalent to `online.add()`.\\n- **Error Handling:** The route handler forwards Redis/query errors to Express's default error middleware. Implement custom logging or fallback behavior as required by your application's error policy.\\n- **Performance &amp; Scaling:** `online.add()` is non-blocking, but high-throughput applications should monitor Redis memory consumption. Configure appropriate Redis eviction policies or TTLs if tracking long-term activity. Multiple Express instances can safely share the same Redis backend without additional synchronization.\\n- **Module Boundaries:** This example operates as a standalone Express application. It has no incoming module dependencies and exposes no public API. Internal calls flow from `index.js` to the `list` helper, while outgoing calls delegate to Express's `res.send` for response delivery.\",\"other-package-json\":\"# Other \u2014 package.json\\n\\n# Module: `package.json`\\n\\n## Purpose &amp; Scope\\nThis manifest defines the project metadata, dependency graph, engine constraints, published file boundaries, and development lifecycle scripts for **Express.js v5.2.1**. As a declarative configuration file, it contains no executable logic or internal call graphs. It serves as the single source of truth for dependency resolution, package publishing, and contributor tooling.\\n\\n## Package Identity\\n- **Name:** `express`\\n- **Version:** `5.2.1`\\n- **License:** MIT\\n- **Repository:** `expressjs/express`\\n- **Funding:** OpenCollective (`https://opencollective.com/express`)\\n- **Keywords:** `express`, `framework`, `sinatra`, `web`, `http`, `rest`, `restful`, `router`, `app`, `api`\\n\\n## Runtime Dependency Architecture\\nExpress v5 delegates core HTTP, routing, and response handling to a modular set of upstream packages. Dependencies are pinned to caret (`^`) ranges to allow minor/patch updates while maintaining API compatibility.\\n\\n| Functional Area | Dependencies |\\n|----------------|--------------|\\n| **HTTP &amp; Request Parsing** | `body-parser`, `qs`, `type-is`, `accepts`, `content-type`, `content-disposition` |\\n| **Routing &amp; Middleware Pipeline** | `router`, `finalhandler`, `parseurl`, `merge-descriptors` |\\n| **Response &amp; Static Assets** | `send`, `serve-static`, `mime-types`, `etag`, `fresh`, `range-parser`, `vary` |\\n| **Error Handling &amp; Status Codes** | `http-errors`, `statuses` |\\n| **Cookies &amp; Security** | `cookie`, `cookie-signature`, `proxy-addr` |\\n| **Utilities &amp; Debugging** | `debug`, `depd`, `on-finished`, `once`, `encodeurl`, `escape-html` |\\n\\n## Development &amp; Testing Toolchain\\nThe `devDependencies` block configures the testing, linting, coverage, and integration fixture environment:\\n- **Test Runner &amp; Assertions:** `mocha`, `supertest`, `after`\\n- **Code Coverage:** `nyc`\\n- **Linting:** `eslint`\\n- **Template Engines (Test/Example Fixtures):** `ejs`, `hbs`\\n- **Session &amp; State Management (Integration Tests):** `express-session`, `cookie-parser`, `cookie-session`, `connect-redis`\\n- **HTTP Utilities &amp; Logging:** `morgan`, `method-override`, `vhost`\\n- **Documentation &amp; Auth Fixtures:** `marked`, `pbkdf2-password`\\n\\n## Engine &amp; Distribution Constraints\\n- **Node.js Requirement:** `&gt;= 18.0.0`\\n- **Published Files:** The `files` array restricts the npm package to:\\n  - `LICENSE`\\n  - `Readme.md`\\n  - `index.js` (Primary entry point)\\n  - `lib/` (Core framework source)\\n- All other directories (e.g., `test/`, `examples/`, `benchmarks/`, `devDependencies`) are excluded from the published tarball.\\n\\n## Lifecycle Scripts\\n| Command | Description |\\n|---------|-------------|\\n| `npm run lint` | Runs `eslint .` across the project |\\n| `npm run lint:fix` | Runs `eslint . --fix` to auto-correct lint violations |\\n| `npm test` | Executes `mocha` with `test/support/env` preloaded, `spec` reporter, and `--check-leaks` across `test/` and `test/acceptance/` |\\n| `npm run test-ci` | Runs tests with `nyc` coverage (lcovonly + text), excluding `examples`, `test`, and `benchmarks` |\\n| `npm run test-cov` | Generates HTML + text coverage reports via `nyc` |\\n| `npm run test-tap` | Runs tests with the `tap` reporter |\\n\\n## Integration Notes for Contributors\\n- **Entry Point:** `index.js` bootstraps the framework. All core logic resides in `lib/`.\\n- **Dependency Updates:** When upgrading runtime dependencies, verify compatibility with the `router` and `finalhandler` pipelines, as these form the backbone of Express v5's request lifecycle.\\n- **Testing Environment:** The `test/support/env` module (referenced in `npm test`) configures global test state. Always run `npm test` or `npm run test-cov` before submitting PRs to ensure leak checks and coverage thresholds pass.\\n- **No Execution Flow:** This file is purely declarative. It does not participate in runtime call graphs or execution flows. All framework behavior is implemented in `lib/` and orchestrated via `index.js`.\",\"other-params\":\"# Other \u2014 params\\n\\n# `examples/params/index.js` \u2014 Route Parameter Preprocessing\\n\\n## Overview\\nThis module demonstrates Express's `app.param()` middleware for intercepting, validating, and transforming route parameters before they reach the main route handler. It establishes a pattern for preprocessing request data, attaching resolved objects to the request context, and short-circuiting invalid requests with standardized HTTP errors.\\n\\n## Execution Flow &amp; Architecture\\nWhen a request matches a route containing `:user`, `:from`, or `:to`, Express automatically invokes the registered `app.param` middleware. These handlers execute sequentially before the route callback, allowing parameter normalization and data preloading.\\n\\n```mermaid\\ngraph LR\\n  A[Incoming Request] --&gt; B{Route Match}\\n  B --&gt;|:user| C[app.param('user')]\\n  B --&gt;|:from/:to| D[app.param(['to','from'])]\\n  C --&gt; E[Route Handler]\\n  D --&gt; E\\n  E --&gt; F[res.send]\\n```\\n\\nIf a param handler calls `next(err)`, Express skips the route handler and forwards the error to the default error middleware. Successful handlers call `next()` to proceed to the route callback, which then uses the preprocessed data via `req.params` or attached properties like `req.user`.\\n\\n## Parameter Middleware Handlers\\n\\n### Integer Conversion Handler\\n```javascript\\napp.param(['to', 'from'], function(req, res, next, num, name){ ... })\\n```\\n- **Triggered by:** `:from` and `:to` parameters in `/users/:from-:to`\\n- **Behavior:** \\n  - Parses the raw string parameter as a base-10 integer using `parseInt(num, 10)`\\n  - Assigns the converted value back to `req.params[name]`\\n  - Validates the result with `isNaN()`\\n  - Calls `next(createError(400, 'failed to parseInt '+num))` on failure\\n  - Calls `next()` on success\\n\\n### User Preloading Handler\\n```javascript\\napp.param('user', function(req, res, next, id){ ... })\\n```\\n- **Triggered by:** `:user` parameter in `/user/:user`\\n- **Behavior:**\\n  - Uses the parameter value as an array index to fetch from the `users` mock database\\n  - Attaches the resolved object to `req.user`\\n  - Calls `next(createError(404, 'failed to find user'))` if the index is out of bounds or undefined\\n  - Calls `next()` if the user exists\\n\\n## Route Definitions\\n\\n| Route | Handler | Data Source | Response |\\n|-------|---------|-------------|----------|\\n| `GET /` | Index | None | Instructional text |\\n| `GET /user/:user` | User Detail | `req.user` (preloaded) | `user ` |\\n| `GET /users/:from-:to` | User Range | `req.params.from`, `req.params.to` (parsed) | Comma-separated names from `users.slice(from, to + 1)` |\\n\\nThe `/users/:from-:to` route uses a literal hyphen in the path pattern. Express matches it as a single segment, splitting the captured values into `req.params.from` and `req.params.to` after the param middleware processes them.\\n\\n## Integration &amp; Usage\\n- **Export:** `module.exports = express()` allows the app to be mounted in larger Express applications via `app.use('/params', require('./examples/params'))`\\n- **Standalone Execution:** Runs on port `3000` when executed directly (`node index.js`), guarded by `if (!module.parent)`\\n- **Dependencies:** \\n  - `express` (core framework)\\n  - `http-errors` (standardized error object creation)\\n\\n## Developer Notes &amp; Extension Points\\n- **Callback Signature:** `app.param` handlers receive `(req, res, next, value, name)`. The `value` argument is the raw string from the URL, and `name` is the parameter key.\\n- **Error Propagation:** Errors passed to `next()` bypass route handlers. The `http-errors` package ensures consistent `status` and `message` properties for downstream error middleware.\\n- **Mock Data:** The `users` array is a placeholder. In production, replace the synchronous array lookup with an asynchronous database query, ensuring `next()` is called inside the query callback or `async/await` block.\\n- **Range Logic:** The route handler uses `slice(from, to + 1)` to create an inclusive upper bound. Adjust this logic if exclusive ranges are preferred.\\n- **Response Method:** All routes terminate with `res.send()`, which serializes the string payload and sets appropriate `Content-Type` headers before closing the connection.\",\"other-readme-md\":\"# Other \u2014 Readme.md\\n\\n# Other \u2014 Readme.md\\n\\n## Overview\\nThe `Readme.md` file serves as the primary entry point and public-facing documentation for the Express.js repository. It is a static Markdown artifact that defines the developer onboarding path, installation requirements, canonical usage patterns, and project governance structure. While it contains no executable runtime logic, it acts as the authoritative reference for interacting with the Express ecosystem, tooling, and contribution workflows.\\n\\n## Developer Onboarding &amp; Setup\\nThe module outlines a strict prerequisite and installation workflow:\\n- **Runtime Requirement:** Node.js 18 or higher.\\n- **Project Initialization:** Recommends `npm init` for new projects before dependency installation.\\n- **Installation Command:** `npm install express`\\n- **Quick Start CLI:** Utilizes the `express-generator` package (`npm install -g express-generator@4`) to scaffold applications via `express /tmp/foo &amp;&amp; cd /tmp/foo`, followed by `npm install` and `npm start`.\\n\\n## API Entry Point &amp; Usage Pattern\\nThe README establishes the canonical Express application bootstrap pattern:\\n```js\\nimport express from 'express'\\n\\nconst app = express()\\n\\napp.get('/', (req, res) =&gt; {\\n  res.send('Hello World')\\n})\\n\\napp.listen(3000, () =&gt; {\\n  console.log('Server is running on http://localhost:3000')\\n})\\n```\\nThis pattern demonstrates the core API surface:\\n- `express()` factory function for application initialization\\n- `app.get(path, handler)` for route definition\\n- `app.listen(port, callback)` for HTTP server binding\\n\\n## Ecosystem &amp; Tooling Integration\\nThe documentation maps Express to its surrounding toolchain and architectural philosophy:\\n- **Template Engines:** Supports 14+ engines via `@ladjs/consolidate`\\n- **HTTP Helpers:** Built-in support for redirection, caching, and content negotiation\\n- **Examples Directory:** Runnable demos located in `examples/` (e.g., `node examples/content-negotiation`)\\n- **Migration Path:** Directs developers to the v5 migration guide for version upgrades\\n- **External Resources:** Links to the official website, GitHub organization, and discussion forums\\n\\n## Contribution &amp; Governance\\nThe module formalizes the project's open-source workflow:\\n- **Testing:** `npm install` followed by `npm test` to execute the test suite\\n- **Security:** Directs vulnerability reports to the official Security Policies and Procedures\\n- **Governance Structure:** Lists active Technical Committee (TC) members, Triagers, and Emeritus contributors\\n- **Documentation Links:** References `GOVERNANCE.md`, `CODE_OF_CONDUCT.md`, and `CONTRIBUTING.md` for policy and workflow details\\n\\n## Execution Context &amp; Call Graph\\nAs a static documentation file, `Readme.md` does not participate in the runtime call graph or execution flow. It contains zero internal, outgoing, or incoming runtime calls. Its function is purely informational, serving as a reference map that points developers to:\\n- Package registry endpoints (`npm install`)\\n- CLI tooling (`express-generator`)\\n- Repository directories (`examples/`)\\n- External documentation and CI/CD status badges (Coveralls, GitHub Actions, OpenSSF Scorecard)\\n\\n## Developer Workflow Diagram\\nThe following diagram illustrates how developers interact with the repository through the guidance provided in this module:\\n\\n```mermaid\\ngraph TD\\n  A[Read Readme.md] --&gt; B{Primary Goal}\\n  B --&gt;|Install &amp; Run| C[npm install express]\\n  B --&gt;|Scaffold App| D[express-generator CLI]\\n  B --&gt;|Contribute| E[npm test &amp; PR]\\n  C --&gt; F[app.get / app.listen]\\n  D --&gt; G[Generated Project]\\n  E --&gt; H[CI/CD Validation]\\n```\",\"other-resource\":\"# Other \u2014 resource\\n\\n# Other \u2014 Resource Module\\n\\n## Overview\\nThe `examples/resource/index.js` module demonstrates a custom RESTful resource routing pattern for Express. It extends the Express application instance with an `app.resource()` method that automatically maps HTTP verbs and URL patterns to a controller object. The module includes an in-memory mock data store (`users`) and a sample controller (`User`) to illustrate how route handlers can delegate to controller methods, parse parameters, and format responses.\\n\\nThis module is intended as an educational example and is not a production-ready resource router. It relies on Express routing patterns compatible with older versions of `path-to-regexp` (e.g., `{.:format}` syntax).\\n\\n## Custom Router API: `app.resource(path, obj)`\\nThe module attaches a `resource` method directly to the Express app instance. When invoked, it registers four routes using `this.get()` and `this.delete()`:\\n\\n```javascript\\napp.resource = function(path, obj) {\\n  this.get(path, obj.index);\\n  this.get(path + '/:a..:b{.:format}', function(req, res){ ... });\\n  this.get(path + '/:id', obj.show);\\n  this.delete(path + '/:id', function(req, res){ ... });\\n};\\n```\\n\\n### Route Registration\\n| HTTP Method | Path Pattern                  | Handler / Controller Method |\\n|-------------|-------------------------------|-----------------------------|\\n| `GET`       | `/:path`                      | `obj.index(req, res)`       |\\n| `GET`       | `/:path/:a..:b{.:format}`     | Inline handler \u2192 `obj.range(req, res, a, b, format)` |\\n| `GET`       | `/:path/:id`                  | `obj.show(req, res)`        |\\n| `DELETE`    | `/:path/:id`                  | Inline handler \u2192 `obj.destroy(req, res, id)` |\\n\\n## Controller Contract\\nThe `obj` parameter passed to `app.resource()` must implement the following methods. The `User` object in this module serves as the reference implementation:\\n\\n| Method | Signature | Responsibility |\\n|--------|-----------|----------------|\\n| `index` | `(req, res)` | Returns the full collection. Calls `res.send(users)`. |\\n| `show` | `(req, res)` | Returns a single record by `req.params.id`. Handles missing records with `{ error: 'Cannot find user' }`. |\\n| `destroy` | `(req, res, id)` | Deletes a record by numeric `id`. Returns `'destroyed'` or `'Cannot find user'`. |\\n| `range` | `(req, res, a, b, format)` | Returns a slice of the collection from `a` to `b` (inclusive). Supports `json` and `html` formatting. |\\n\\n## Route Resolution &amp; Parameter Parsing\\nThe module uses inline route handlers to bridge Express request objects and the controller contract:\\n\\n- **Range Route (`/:a..:b{.:format}`)**: Parses `req.params.a` and `req.params.b` as base-10 integers using `parseInt(req.params.a, 10)`. Extracts the optional `format` parameter to determine response serialization.\\n- **Delete Route (`/:id`)**: Parses `req.params.id` as an integer before passing it to `obj.destroy()`.\\n- **Show Route (`/:id`)**: Passes `req.params.id` directly to `obj.show()`, which uses it as an array index.\\n\\nAll controller methods ultimately delegate to `res.send()` to terminate the request-response cycle.\\n\\n## Execution Flow\\nRequests flow through Express's routing layer into the registered handlers, which parse parameters and invoke the corresponding controller method. The controller processes the mock data and calls `res.send()`.\\n\\n```mermaid\\nflowchart TD\\n    A[Incoming Request] --&gt; B{Route Match}\\n    B --&gt;|GET /users| C[obj.index]\\n    B --&gt;|GET /users/:id| D[obj.show]\\n    B --&gt;|GET /users/:a..:b| E[Inline Handler]\\n    B --&gt;|DELETE /users/:id| F[Inline Handler]\\n    E --&gt; G[obj.range]\\n    F --&gt; H[obj.destroy]\\n    C --&gt; I[res.send]\\n    D --&gt; I\\n    G --&gt; I\\n    H --&gt; I\\n```\\n\\nThe call graph confirms that `index.js` delegates to `range` and `destroy`, while all controller methods (`index`, `show`, `range`, `destroy`) funnel into `res.send()`.\\n\\n## Usage Examples\\nThe module exposes a root route (`GET /`) that lists available endpoints. Example interactions:\\n\\n```bash\\n# List all users\\ncurl http://localhost:3000/users\\n\\n# Get user by index\\ncurl http://localhost:3000/users/1\\n\\n# Get range of users (indices 1 to 3)\\ncurl http://localhost:3000/users/1..3\\n\\n# Get range as JSON\\ncurl http://localhost:3000/users/1..3.json\\n\\n# Delete user by index\\ncurl -X DELETE http://localhost:3000/users/1\\n```\\n\\n## Integration &amp; Testing Notes\\n- **Direct Method Invocation**: The `destroy` and `range` methods are referenced externally by other modules (`examples/auth/index.js` and `test/req.range.js` respectively). This indicates they are sometimes imported or called directly for testing or cross-example integration.\\n- **Mock Data State**: The `users` array is module-scoped and mutable. `destroy` permanently removes entries using `delete users[id]`. Subsequent requests to the same index will return `undefined` or trigger the error path.\\n- **Path Syntax Compatibility**: The `/:a..:b{.:format}` pattern uses legacy Express routing syntax. Modern Express applications using `path-to-regexp` v1+ should replace `{.:format}` with `/:format?` or use explicit regex patterns.\\n- **Server Bootstrap**: The module conditionally starts the server on port `3000` when executed directly (`!module.parent`). It exports the `app` instance via `module.exports` for testing or mounting in larger applications.\",\"other-search\":\"# Other \u2014 search\\n\\n# Other \u2014 Search Module\\n\\n## Overview\\nThe **search** module is a lightweight Express.js example demonstrating real-time, client-driven search backed by Redis. It serves a static HTML interface where user keystrokes trigger asynchronous HTTP requests. The server uses the input string as a Redis key, retrieves all members of the corresponding set, and returns them to the browser for immediate display.\\n\\n## Architecture &amp; Data Flow\\nThe module follows a straightforward client-server pattern with Redis acting as an in-memory key-value store.\\n\\n```mermaid\\nsequenceDiagram\\n    participant Client as Browser (client.js)\\n    participant Server as Express (index.js)\\n    participant Redis as Redis DB\\n    Client-&gt;&gt;Server: GET /search/{:query}\\n    Server-&gt;&gt;Redis: SMEMBERS {query}\\n    Redis--&gt;&gt;Server: Array of members\\n    Server--&gt;&gt;Client: res.send(vals)\\n    Client-&gt;&gt;Client: Update \n with response\\n```\\n\\n## Key Components\\n\\n### Server (`examples/search/index.js`)\\nThe server manages Redis connectivity, data seeding, routing, and static asset delivery.\\n\\n#### Redis Initialization (`initializeRedis`)\\n- Establishes a connection to the local Redis instance via `redis.createClient()`.\\n- Seeds two sets using `db.sAdd()`:\\n  - `ferret` \u2192 `['tobi', 'loki', 'jane']`\\n  - `cat` \u2192 `['manny', 'luna']`\\n- Wrapped in an `async` function and executed before server startup. Catches connection/seeding errors and terminates the process with `process.exit(1)`.\\n\\n#### Route Handlers\\n- **`GET /search/{:query}`**: Extracts the search term from `req.params.query`. Calls `db.sMembers(query)` to fetch all members of the Redis set matching the exact key. Returns the resulting array via `res.send()`. Redis errors are caught and forwarded to Express's error middleware using `next(err)`.\\n- **`GET /client.js`**: Explicitly serves the frontend script using `res.sendFile(path.join(__dirname, 'client.js'))`. This prevents `express.static()` from exposing server-side files (e.g., `index.js` or template files) that reside in the same directory.\\n\\n#### Server Startup\\n- Uses an async IIFE to `await initializeRedis()` before conditionally calling `app.listen(3000)`.\\n- The `!module.parent` guard ensures the HTTP server only starts when the file is executed directly, not when imported as a dependency.\\n\\n### Client (`examples/search/public/`)\\n- **`index.html`**: Minimal UI containing a `` and a `\n` element for output. Loads `client.js` at the end of the body.\\n- **`client.js`**: Attaches a `keyup` event listener to the search input. On each keystroke, it instantiates an `XMLHttpRequest`, opens a `GET` request to `/search/{search.value}`, and updates the `\n` element's `textContent` when `readyState === 4`.\\n\\n## Setup &amp; Usage\\n1. **Prerequisites**: Install and start a local Redis server (`redis-server`).\\n2. **Dependencies**: Run `npm install redis` in the project root.\\n3. **Execution**: Run `node examples/search/index.js`.\\n4. **Access**: Navigate to `http://localhost:3000`. Typing `ferret` or `cat` into the search box will return the seeded members in real-time.\\n\\n## Implementation Notes\\n- **Route Syntax**: The source defines the route as `/search/{:query}`. Express will parse `:query` as a route parameter, but the literal `{` and `}` characters will be part of the URL path. Adjust to `/search/:query` if standard Express routing is preferred.\\n- **Data Model**: The example relies on exact Redis key matching via `SMEMBERS`. It does not support partial matches, wildcards, or fuzzy search.\\n- **Error Handling**: Search route errors are passed to `next(err)`, relying on Express's default error handler. Initialization failures halt the process to prevent serving an unseeded or disconnected state.\\n- **Static Serving**: `express.static()` is scoped to `public/`, but `/client.js` is explicitly routed to avoid directory traversal risks and unintended file exposure.\\n\\n## Extending the Module\\n- Replace `db.sMembers()` with `db.sScan()` or `db.keys()` to support pattern-based or paginated lookups.\\n- Add input debouncing in `client.js` to throttle `XMLHttpRequest` calls during rapid typing.\\n- Switch `res.send(vals)` to `res.json(vals)` for structured JSON responses.\\n- Externalize Redis connection configuration using environment variables instead of relying on default localhost settings.\",\"other-session\":\"# Other \u2014 session\\n\\n# Other \u2014 Session Module\\n\\n## Purpose\\nDemonstrates HTTP session management in Express using the `express-session` middleware. The module provides two standalone examples: a default in-memory session store and a Redis-backed persistent store. Both examples track per-user page views by attaching state to `req.session`.\\n\\n## Architecture &amp; Components\\nThe module consists of two independent entry points that share identical routing logic but differ in session storage configuration:\\n\\n| File | Storage Backend | Additional Dependencies |\\n|------|----------------|-------------------------|\\n| `examples/session/index.js` | Default `MemoryStore` (in-memory) | `express`, `express-session` |\\n| `examples/session/redis.js` | `connect-redis` (Redis-backed) | `express`, `express-session`, `connect-redis`, `morgan` |\\n\\nBoth files follow the same structural pattern:\\n1. Initialize an Express application via `express()`\\n2. Attach session middleware using `app.use(session({...}))`\\n3. Define a `GET /` route handler that reads/writes `req.session.views`\\n4. Start the HTTP server on port `3000`\\n\\n## Session Middleware Configuration\\nThe `express-session` middleware is configured with identical core options across both examples:\\n\\n```javascript\\napp.use(session({\\n  resave: false,              // Prevents saving unmodified sessions\\n  saveUninitialized: false,   // Defers session creation until data is stored\\n  secret: 'keyboard cat',     // Signs the session ID cookie\\n  store: new RedisStore       // (redis.js only) Overrides default MemoryStore\\n}));\\n```\\n\\n- `resave: false` avoids race conditions and unnecessary writes when session data hasn't changed.\\n- `saveUninitialized: false` complies with privacy regulations by not creating empty sessions for anonymous visitors.\\n- `secret` is used to cryptographically sign the session cookie. In production, this should be a strong, environment-specific value.\\n\\n## Store Implementations\\n### In-Memory Store (`index.js`)\\nRelies on `express-session`'s built-in `MemoryStore`. Suitable for development and testing. Session data is lost on process restart and does not scale across multiple Node.js instances.\\n\\n### Redis Store (`redis.js`)\\nIntegrates `connect-redis` by passing the `session` module to it, allowing the Redis store to inherit from `session.Store`:\\n```javascript\\nvar RedisStore = require('connect-redis')(session);\\n```\\nThe store instance is passed to the middleware via `store: new RedisStore`. This enables persistent, distributed session storage suitable for production environments.\\n\\n## Request Execution Flow\\nThe following diagram illustrates the request lifecycle for both examples:\\n\\n```mermaid\\ngraph LR\\n  A[HTTP Request] --&gt; B[session Middleware]\\n  B --&gt; C{req.session exists?}\\n  C --&gt;|Yes| D[Load session data]\\n  C --&gt;|No| E[Create new session]\\n  D --&gt; F[Route Handler GET /]\\n  E --&gt; F\\n  F --&gt; G[Increment req.session.views]\\n  G --&gt; H[res.send HTML Response]\\n```\\n\\n1. Incoming requests pass through the `session` middleware, which parses the session cookie and attaches a `req.session` object.\\n2. The `GET /` route handler checks `req.session.views`. If present, it increments the counter; otherwise, it initializes it to `1` and appends a first-visit message.\\n3. The handler responds using `res.send()`, which serializes the HTML string and ends the response.\\n4. The session middleware automatically persists modified session data before the response completes.\\n\\n## Running the Examples\\n### In-Memory Variant\\n```bash\\nnode examples/session/index.js\\n```\\nThe server starts on `http://localhost:3000`. The `if (!module.parent)` guard ensures the server only starts when the file is executed directly, not when required as a module.\\n\\n### Redis Variant\\nPrerequisites:\\n- Redis server running locally (`redis-server`)\\n- Dependencies installed: `npm install redis connect-redis morgan express-session`\\n\\n```bash\\nnode examples/session/redis.js\\n```\\nThe server starts on `http://localhost:3000` with `morgan` logging enabled in `dev` format. Session state persists across server restarts and is shared across Redis clients.\\n\\n## Integration Notes\\n- These files are standalone examples and do not export middleware or utilities for consumption by other modules.\\n- The `res.send()` calls route through Express's response pipeline. No custom routing or internal module calls are present.\\n- When adapting this pattern for production:\\n  - Replace `'keyboard cat'` with a cryptographically secure secret loaded from environment variables.\\n  - Configure `connect-redis` with connection options (host, port, password, TTL) as needed.\\n  - Consider adding session cookie options (`cookie: { secure: true, httpOnly: true, sameSite: 'strict' }`) for security compliance.\",\"other-static-files\":\"# Other \u2014 static-files\\n\\n# Other \u2014 static-files\\n\\n## Overview\\nThis module is an Express.js example demonstrating how to serve static assets using the built-in `express.static()` middleware. It illustrates three distinct routing patterns for mapping HTTP requests to filesystem directories, along with request logging via `morgan`.\\n\\n## Core Middleware &amp; Configuration\\n\\nThe module relies on `express.static(root)` to intercept incoming requests, check for matching files in the specified directory, and serve them with appropriate MIME types. If no file matches, the middleware calls `next()` to pass control down the stack.\\n\\n### Pattern 1: Direct Root Mapping\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\n- **Behavior**: Serves files from `./public` at the root URL path.\\n- **Example**: `GET /js/app.js` \u2192 resolves to `./public/js/app.js`\\n- **Use Case**: Simple applications where static assets share the same base path as API or view routes.\\n\\n### Pattern 2: Prefixed/Mounted Routing\\n```javascript\\napp.use('/static', express.static(path.join(__dirname, 'public')));\\n```\\n- **Behavior**: Mounts the static middleware at `/static`. Express automatically strips the mount path before resolving the file.\\n- **Example**: `GET /static/js/app.js` \u2192 strips `/static` \u2192 resolves to `./public/js/app.js`\\n- **Use Case**: Namespacing static assets to avoid collisions with dynamic routes or API endpoints.\\n\\n### Pattern 3: Multiple Static Directories\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public', 'css')));\\n```\\n- **Behavior**: Registers an additional static directory. Express evaluates middleware in registration order.\\n- **Example**: `GET /style.css` \u2192 resolves to `./public/css/style.css`\\n- **Use Case**: Serving assets from disparate directories without requiring URL prefixes, or overriding files in earlier directories with later ones.\\n\\n## Request Resolution Flow\\n\\nThe following diagram illustrates how incoming requests are evaluated against the registered middleware stack:\\n\\n```mermaid\\ngraph TD\\n    A[Incoming Request] --&gt; B{Logger: morgan}\\n    B --&gt; C{Static: ./public}\\n    C --&gt;|File Found| D[Serve File]\\n    C --&gt;|Not Found| E{Static: /static -&gt; ./public}\\n    E --&gt;|File Found| D\\n    E --&gt;|Not Found| F{Static: ./public/css}\\n    F --&gt;|File Found| D\\n    F --&gt;|Not Found| G[404 / Next Middleware]\\n```\\n\\n## Project Structure\\n```\\nexamples/static-files/\\n\u251c\u2500\u2500 index.js              # Express app entry point &amp; middleware configuration\\n\u2514\u2500\u2500 public/               # Root static directory\\n    \u251c\u2500\u2500 hello.txt         # Plain text asset\\n    \u251c\u2500\u2500 js/\\n    \u2502   \u2514\u2500\u2500 app.js        # JavaScript asset\\n    \u2514\u2500\u2500 css/\\n        \u2514\u2500\u2500 style.css     # Stylesheet asset\\n```\\n\\n## Running &amp; Testing\\n1. Start the server: `node index.js`\\n2. Verify endpoints:\\n   - `GET /hello.txt` \u2192 served by Pattern 1\\n   - `GET /js/app.js` \u2192 served by Pattern 1\\n   - `GET /static/js/app.js` \u2192 served by Pattern 2\\n   - `GET /css/style.css` \u2192 served by Pattern 1 (if `public/css` is traversed) or Pattern 3 (direct root mapping)\\n   - `GET /style.css` \u2192 served by Pattern 3\\n\\n## Implementation Notes\\n- **Path Resolution**: `path.join(__dirname, 'public')` ensures cross-platform compatibility. Avoid hardcoding forward/backward slashes.\\n- **Middleware Order**: Express evaluates `app.use()` calls sequentially. Place `express.static()` before route handlers if you want static files to take precedence, or after if you want dynamic routes to override them.\\n- **Caching &amp; Headers**: `express.static()` automatically sets `Cache-Control`, `ETag`, and `Last-Modified` headers. These can be customized via the optional `options` object (e.g., `maxAge`, `immutable`).\\n- **Security**: The middleware prevents directory traversal attacks by default. Requests containing `../` are safely rejected or normalized.\",\"other-support\":\"# Other \u2014 support\\n\\n# Other \u2014 Support Module\\n\\n## Overview\\nThe `test/support` module provides foundational utilities for the project's test suite. It handles environment bootstrapping, supplies a lightweight template engine for dynamic test fixtures, and exports assertion factories compatible with `supertest` for validating HTTP responses. This module is strictly internal to the testing infrastructure and is not intended for production use.\\n\\n## Environment Configuration (`env.js`)\\nBootstraps the Node.js process for test execution by setting environment variables before any application code loads:\\n- `NODE_ENV`: Forced to `'test'` to ensure test-specific behavior in dependencies.\\n- `NO_DEPRECATION`: Suppresses deprecation warnings from `body-parser` and `express` to keep test output clean.\\n\\n**Usage:** Require this file at the very beginning of your test runner or entry script:\\n```js\\nrequire('./test/support/env');\\n```\\n\\n## Template Engine (`tmpl.js`)\\nExports a minimal, synchronous-style template renderer designed for generating dynamic test fixtures.\\n\\n### `renderFile(fileName, options, callback)`\\nReads a file from disk and performs variable substitution before returning the result.\\n- **Parameters:**\\n  - `fileName` (string): Path to the template file.\\n  - `options` (object): Key-value map for variable resolution. Supports dot-notation paths (e.g., `$user.profile.name`).\\n  - `callback` (function): Node-style `(err, str)` callback.\\n- **Behavior:**\\n  - Uses `fs.readFile` with `utf8` encoding.\\n  - Matches variables via `/\\\\$([0-9a-zA-Z\\\\.]+)/g`.\\n  - Delegates path resolution to `generateVariableLookup(data)`, which traverses nested objects.\\n  - Catches substitution errors and attaches `err.name = 'RenderError'` before invoking the callback.\\n\\n## Assertion Utilities (`utils.js`)\\nExports factory functions that return assertion callbacks compatible with `supertest`'s `.expect()` chain. All assertions use `node:assert` and operate on the `res` object provided by `supertest`.\\n\\n### Body Assertions\\n- `shouldHaveBody(buf)`: Validates that the response body exactly matches the provided `Buffer`. Normalizes string responses to `Buffer` and compares hex representations for strict equality.\\n- `shouldNotHaveBody()`: Asserts that `res.text` is either an empty string or `undefined`.\\n\\n### Header Assertions\\n- `shouldHaveHeader(header)`: Asserts the presence of a header. Performs case-insensitive matching against `res.headers`.\\n- `shouldNotHaveHeader(header)`: Asserts the absence of a header using the same case-insensitive logic.\\n\\n### Version Gating\\n- `shouldSkipQuery(versionString)`: Returns `true` if the Node.js major version is `&lt; 22`. Used to conditionally skip HTTP `QUERY` method tests, as full upstream support was introduced in Node 22.\\n- `getMajorVersion(versionString)`: Internal helper that extracts the major version segment from a semver string.\\n\\n## Test Integration &amp; Call Flow\\nThe assertion utilities are designed to be passed directly into `supertest` chains. The module follows a factory pattern: each exported function returns a closure that captures the expected value and executes the assertion when invoked with a `supertest` response object.\\n\\n```mermaid\\ngraph TD\\n    A[Test File] --&gt;|import| B[utils.js]\\n    B --&gt;|exports| C[shouldHaveBody]\\n    B --&gt;|exports| D[shouldHaveHeader]\\n    B --&gt;|exports| E[shouldNotHaveBody]\\n    B --&gt;|exports| F[shouldNotHaveHeader]\\n    C --&gt;|passed to| G[supertest.expect]\\n    D --&gt;|passed to| G\\n    E --&gt;|passed to| G\\n    F --&gt;|passed to| G\\n    H[tmpl.js] --&gt;|renderFile| I[Test Fixtures]\\n    I --&gt;|used by| A\\n```\\n\\n**Typical Usage Pattern:**\\n```js\\nconst request = require('supertest');\\nconst { shouldHaveBody, shouldNotHaveHeader } = require('../support/utils');\\n\\nrequest(app)\\n  .get('/download')\\n  .expect(shouldHaveBody(Buffer.from('expected content')))\\n  .expect(shouldNotHaveHeader('x-custom-header'))\\n  .end(done);\\n```\\n\\n## Development Notes\\n- **Hex Comparison:** `shouldHaveBody` converts both expected and actual bodies to hex strings before comparison. This avoids encoding pitfalls and ensures byte-level accuracy.\\n- **Header Case-Insensitivity:** HTTP headers are normalized to lowercase in `res.headers`. The assertion helpers automatically call `.toLowerCase()` on the input header name to match this behavior.\\n- **Node Version Gating:** `shouldSkipQuery` is tied to Node 22 due to incomplete `HTTP QUERY` method support in earlier versions. Update the threshold only after verifying upstream Node.js and Express compatibility.\\n- **Error Handling in `tmpl.js`:** The renderer catches template substitution errors and explicitly names them `RenderError`. Test code should check for this error name when validating malformed template inputs.\",\"other-vhost\":\"# Other \u2014 vhost\\n\\n# Other \u2014 vhost Module\\n\\n## Purpose\\nThis module is an Express.js example demonstrating hostname-based routing using the `vhost` middleware. It illustrates how to mount multiple independent Express applications behind a single HTTP server and delegate incoming requests to the appropriate app based on the `Host` header.\\n\\n## Architecture\\nThe module instantiates three separate Express applications:\\n- `main`: Handles requests for the top-level domain (`example.com`)\\n- `redirect`: Handles wildcard subdomain requests (`*.example.com`)\\n- `app`: The root application that exports the server and mounts the `vhost` middleware\\n\\nThe `vhost` middleware acts as a conditional router. It inspects the `Host` header, matches it against registered patterns, and forwards the request to the corresponding mounted application.\\n\\n## Key Components\\n\\n### `main` Application\\nHandles direct requests to `example.com`. Defines two route handlers:\\n- `GET /`: Returns a static greeting via `res.send('Hello from main app!')`\\n- `GET /:sub`: Captures a path parameter and echoes it back\\n\\n### `redirect` Application\\nHandles all subdomain requests matching `*.example.com`. Contains a single catch-all middleware:\\n- Extracts the matched subdomain from `req.vhost[0]` (populated by the `vhost` middleware)\\n- Issues a 302 redirect to `http://example.com:3000/`\\n- Conditionally logs the `req.vhost` object when executed directly (`!module.parent`)\\n\\n### Root `app` &amp; Middleware Mounting\\nThe exported `app` instance registers two `vhost` middleware layers:\\n```javascript\\napp.use(vhost('*.example.com', redirect));\\napp.use(vhost('example.com', main));\\n```\\nOrder matters: Express evaluates middleware sequentially. The wildcard pattern is registered first, ensuring subdomains are intercepted before the exact domain match.\\n\\n## Request Routing Flow\\n```mermaid\\ngraph TD\\n    A[Incoming HTTP Request] --&gt; B{vhost Middleware}\\n    B --&gt;|Host: *.example.com| C[redirect App]\\n    B --&gt;|Host: example.com| D[main App]\\n    C --&gt; E[Extract req.vhost[0]]\\n    E --&gt; F[302 Redirect to /]\\n    D --&gt; G[Route: GET / or GET /:sub]\\n    G --&gt; H[res.send Response]\\n```\\n\\n1. Request arrives at the server with a `Host` header\\n2. `vhost` evaluates the hostname against registered patterns\\n3. If matched, `req.vhost` is populated as an array of regex capture groups\\n4. Control is passed to the mounted Express app (`redirect` or `main`)\\n5. The target app's route handlers or middleware execute and terminate the request via `res.send()` or `res.redirect()`\\n\\n## Local Configuration &amp; Execution\\nThe example requires local DNS resolution to simulate virtual hosts. Add the following to `/etc/hosts` (or `C:\\\\Windows\\\\System32\\\\drivers\\\\etc\\\\hosts`):\\n```\\n127.0.0.1       foo.example.com\\n127.0.0.1       bar.example.com\\n127.0.0.1       example.com\\n```\\n\\nRun the server directly:\\n```bash\\nnode examples/vhost/index.js\\n```\\nThe `!module.parent` guard ensures `morgan` logging and `app.listen(3000)` only execute when the file is run as the entry point, not when required as a module in tests or other scripts.\\n\\n## Integration Notes\\n- **`req.vhost` Structure**: The `vhost` middleware attaches an array to `req.vhost` containing matched capture groups. For `*.example.com`, `req.vhost[0]` holds the subdomain string (e.g., `\\\"foo\\\"`).\\n- **Middleware Order**: Swapping the `vhost` registration order will cause `example.com` requests to incorrectly match the wildcard pattern. Always register specific patterns after wildcards, or use exact matches first if precedence requires it.\\n- **Testing**: When importing this module in test suites, the `module.parent` check prevents port binding conflicts. Route handlers can be tested by passing mock `req`/`res` objects or using `supertest` against the exported `app`.\",\"other-view-constructor\":\"# Other \u2014 view-constructor\\n\\n# Other \u2014 view-constructor\\n\\n## Overview\\nThe `view-constructor` module demonstrates how to override Express's default view resolution and rendering pipeline by providing a custom view constructor. Instead of reading template files from the local filesystem, this implementation fetches Markdown templates directly from a GitHub repository over HTTPS, compiles them using a custom engine, and returns the rendered HTML.\\n\\n## Architecture &amp; Key Components\\n\\n### `GithubView` Constructor\\n```javascript\\nfunction GithubView(name, options)\\n```\\nRegistered via `app.set('view', GithubView)`, this constructor replaces Express's built-in `View` class. It receives the view name and an options object containing the registered template engines and the application's `views` directory setting.\\n\\n**Key Behavior:**\\n- Extracts the appropriate template engine using `options.engines[extname(name)]`.\\n- Constructs a remote file path: `/{root}/master/{name}`. The `root` value corresponds to `app.set('views', '...')`.\\n- Stores `name`, `engine`, and `path` as instance properties for use during rendering.\\n\\n### `GithubView.prototype.render`\\n```javascript\\nGithubView.prototype.render = function(options, fn)\\n```\\nThe core rendering method invoked by Express when `res.render()` is called. It handles asynchronous remote fetching and delegates compilation to the registered engine.\\n\\n**Execution Steps:**\\n1. Configures an HTTPS GET request to `raw.githubusercontent.com` using `this.path`.\\n2. Buffers the incoming response stream with `utf8` encoding.\\n3. On stream `end`, invokes `this.engine(buf, options, fn)`, passing the fetched Markdown, merged locals, and the Express callback.\\n4. Express receives the compiled HTML via `fn(null, html)` and sends the response.\\n\\n## Express Integration (`index.js`)\\n\\nThe application setup configures the custom view system and registers a Markdown processing engine:\\n\\n- **Custom Engine Registration:** `app.engine('md', ...)` registers a `.md` handler using `marked.parse`. The engine also performs basic string interpolation, replacing `{placeholder}` patterns with values from the `options` locals object.\\n- **View Configuration:** \\n  - `app.set('views', 'expressjs/express')` defines the GitHub repository path.\\n  - `app.set('view', GithubView)` swaps the default view constructor.\\n- **Route Definitions:** \\n  - `GET /` renders `examples/markdown/views/index.md` with `{ title: 'Example' }`.\\n  - `GET /Readme.md` renders the repository's root `Readme.md`.\\n\\n## Request Lifecycle\\n\\n```mermaid\\nsequenceDiagram\\n  participant Client\\n  participant Express\\n  participant GithubView\\n  participant GitHub API\\n  participant MDEngine\\n  Client-&gt;&gt;Express: GET /\\n  Express-&gt;&gt;GithubView: new GithubView(name, opts)\\n  Express-&gt;&gt;GithubView: render(locals, fn)\\n  GithubView-&gt;&gt;GitHub API: HTTPS GET /{root}/master/{name}\\n  GitHub API--&gt;&gt;GithubView: Markdown content\\n  GithubView-&gt;&gt;MDEngine: engine(content, locals, fn)\\n  MDEngine--&gt;&gt;Express: fn(null, html)\\n  Express--&gt;&gt;Client: 200 OK (HTML)\\n```\\n\\n## Implementation Notes &amp; Caveats\\n\\n- **Error Handling:** The `https.request` implementation lacks explicit `.on('error', fn)` handlers. Network failures or non-2xx responses will not trigger the Express error callback in this example.\\n- **Branch Hardcoding:** The path construction explicitly uses `/master/`. Modern repositories default to `main`, and branch names should ideally be configurable.\\n- **Caching:** Every request triggers a fresh network call. Production implementations should implement in-memory or HTTP-level caching to avoid rate limits and latency.\\n- **Template Interpolation:** The custom `.md` engine uses a simple regex replacement (`/\\\\{([^}]+)\\\\}/g`). This does not support nested objects, escaping, or complex logic. Consider a dedicated templating engine for production use.\\n- **Extensibility Pattern:** This module serves as a reference for implementing alternative view sources (e.g., databases, CDNs, or remote APIs) by conforming to Express's `(name, options) =&gt; { render(options, fn) }` interface.\",\"other-view-locals\":\"# Other \u2014 view-locals\\n\\n# `view-locals` Module\\n\\n## Purpose\\nThe `view-locals` module demonstrates three progressive patterns for fetching asynchronous data and passing it to Express views. It contrasts inline callback nesting with middleware-based approaches, highlighting how `req` and `res.locals` can be used to decouple data fetching from route handlers, improve readability, and enable reusable view context composition.\\n\\n## Core Components\\n\\n| File | Role |\\n|------|------|\\n| `index.js` | Express application entry point. Defines routes, middleware chains, and view configuration. |\\n| `user.js` | Faux data model. Exports the `User` constructor and static async-like methods `User.all(fn)` and `User.count(fn)`. |\\n| `views/index.ejs` | EJS template expecting `title` and `users` locals. Renders a list of filtered users. |\\n\\n### Faux Model (`user.js`)\\n- `User(name, age, species)`: Constructor for user records.\\n- `User.all(fn)`: Simulates a database read. Uses `process.nextTick` to defer execution and invoke `fn(null, users)` with the in-memory array.\\n- `User.count(fn)`: Simulates a count query. Invokes `fn(null, users.length)` asynchronously.\\n- Maintains a static `users` array pre-populated with five `User` instances (three ferrets, two cats).\\n\\n### View Template (`views/index.ejs`)\\nExpects two locals:\\n- `title`: String rendered in `` and `\n`.\\n- `users`: Array of user objects. Iterates via `users.forEach()` to display `name`, `age`, and `species`.\\n\\n## Data-Passing Patterns\\n\\nThe module implements three routes, each demonstrating a different strategy for assembling view data.\\n\\n### 1. Inline Callback Nesting (`GET /`)\\n```javascript\\napp.get('/', function(req, res, next){\\n  User.count(function(err, count){\\n    if (err) return next(err);\\n    User.all(function(err, users){\\n      if (err) return next(err);\\n      res.render('index', {\\n        title: 'Users',\\n        count: count,\\n        users: users.filter(ferrets)\\n      });\\n    })\\n  })\\n});\\n```\\n- **Behavior**: Fetches data sequentially in nested callbacks. Filters users inline using the `ferrets(user)` helper.\\n- **Trade-offs**: High coupling between data fetching and rendering. Deep nesting reduces readability. Error handling is explicit but repetitive.\\n\\n### 2. Request-Scoped Middleware (`GET /middleware`)\\n```javascript\\nfunction count(req, res, next) { /* attaches req.count */ }\\nfunction users(req, res, next) { /* attaches req.users */ }\\n\\napp.get('/middleware', count, users, function (req, res) {\\n  res.render('index', {\\n    title: 'Users',\\n    count: req.count,\\n    users: req.users.filter(ferrets)\\n  });\\n});\\n```\\n- **Behavior**: `count` and `users` middleware attach data to the `req` object. The final handler reads from `req`, applies filtering, and renders.\\n- **Trade-offs**: Eliminates callback nesting. Data remains available across the middleware chain. Filtering stays in the route handler, preserving flexibility.\\n\\n### 3. Response-Scoped Locals (`GET /middleware-locals`)\\n```javascript\\nfunction count2(req, res, next) { /* attaches res.locals.count */ }\\nfunction users2(req, res, next) { /* attaches res.locals.users (filtered) */ }\\n\\napp.get('/middleware-locals', count2, users2, function (req, res) {\\n  res.render('index', { title: 'Users' });\\n});\\n```\\n- **Behavior**: Middleware writes directly to `res.locals`. Express automatically merges `res.locals` into the view context, so `res.render()` only needs to pass `title`.\\n- **Trade-offs**: Cleanest route handler. Best for routes sharing identical view payloads. Filtering is moved to middleware, which may reduce flexibility if different routes require different subsets of the same data.\\n\\n## Middleware &amp; Locals Lifecycle\\n\\nExpress provides two primary attachment points for request-scoped data:\\n- `req.*`: Persists across middleware and route handlers. Ideal for raw data that may be transformed differently per route.\\n- `res.locals`: Automatically exposed to the view engine. Ideal for pre-formatted data, session state, or authentication context.\\n\\nThe module includes commented patterns for applying locals at different scopes:\\n```javascript\\n// Global: applies to all routes\\napp.use(function(req, res, next){\\n  res.locals.user = req.user;\\n  res.locals.sess = req.session;\\n  next();\\n});\\n\\n// Path-scoped: applies to /api/* routes\\napp.use('/api', function(req, res, next){ ... });\\napp.all('/api/*', function(req, res, next){ ... });\\n```\\n\\n## Execution Flow\\n\\nThe following diagram illustrates the middleware chain for the `/middleware-locals` route, which represents the most idiomatic Express pattern demonstrated:\\n\\n```mermaid\\nsequenceDiagram\\n    participant Client\\n    participant Express\\n    participant count2\\n    participant users2\\n    participant RouteHandler\\n    participant EJS\\n\\n    Client-&gt;&gt;Express: GET /middleware-locals\\n    Express-&gt;&gt;count2: Execute middleware\\n    count2-&gt;&gt;User.count: Fetch count (async)\\n    User.count--&gt;&gt;count2: Return count\\n    count2-&gt;&gt;Express: res.locals.count = count; next()\\n    Express-&gt;&gt;users2: Execute middleware\\n    users2-&gt;&gt;User.all: Fetch users (async)\\n    User.all--&gt;&gt;users2: Return users\\n    users2-&gt;&gt;Express: res.locals.users = filtered; next()\\n    Express-&gt;&gt;RouteHandler: Execute route\\n    RouteHandler-&gt;&gt;EJS: res.render('index', {title})\\n    EJS--&gt;&gt;Client: Rendered HTML\\n```\\n\\n## Integration &amp; Extension Guidelines\\n\\n1. **Replace Faux Model**: Swap `User.all` and `User.count` with real database queries (e.g., `mongoose`, `pg`, `sequelize`). Maintain the `fn(err, data)` callback signature or convert to `async/await` with `try/catch` and `next(err)`.\\n2. **Error Handling**: All middleware consistently uses `if (err) return next(err);`. Ensure downstream error-handling middleware is registered to catch and format these errors.\\n3. **Filtering Strategy**: \\n   - Use `req.*` middleware when routes need different transformations of the same dataset.\\n   - Use `res.locals` middleware when multiple routes render the same view with identical data shapes.\\n4. **View Context Merging**: Express merges `res.locals` with the object passed to `res.render()`. Route-level locals override `res.locals` if keys collide.\\n5. **Performance**: The example uses `process.nextTick` to simulate async I/O. In production, ensure database connections are pooled and queries are optimized to avoid blocking the event loop.\",\"other-web-service\":\"# Other \u2014 web-service\\n\\n# Other \u2014 web-service\\n\\n## Overview\\nA standalone Express.js example demonstrating foundational patterns for building JSON APIs. The module implements API key validation, route parameter extraction, custom error propagation, and centralized error/404 handling. It serves as a reference for middleware composition and request lifecycle management in Express.\\n\\n## Request Processing Flow\\nAll requests targeting the `/api` namespace pass through a validation gate before reaching route handlers. Successful validation attaches metadata to the request object. Route handlers return JSON responses via `res.send()`. Unhandled errors or unmatched routes cascade to dedicated fallback middleware.\\n\\n## Core Components\\n\\n### API Key Validation Middleware\\nMounted at `/api`, this middleware intercepts all prefixed requests:\\n```javascript\\napp.use('/api', function(req, res, next){ ... })\\n```\\n- Extracts `api-key` from `req.query`\\n- Returns `400` if the key is missing\\n- Returns `401` if the key is not found in the `apiKeys` array\\n- On success, attaches the validated key to `req.key` and calls `next()`\\n\\n### Route Handlers\\nThree `GET` endpoints expose the in-memory data:\\n- `GET /api/users` \u2192 Returns the `users` array\\n- `GET /api/repos` \u2192 Returns the `repos` array\\n- `GET /api/user/:name/repos` \u2192 Extracts `req.params.name`, looks up `userRepos[name]`, and returns the result. Calls `next()` if the user is not found, allowing the request to fall through to the 404 handler.\\n\\n### Error &amp; Fallback Handling\\nExpress distinguishes error-handling middleware by arity (4 parameters):\\n```javascript\\napp.use(function(err, req, res, next){ ... })\\n```\\n- Catches errors passed via `next(err)`\\n- Reads `err.status` (defaults to `500` if undefined)\\n- Responds with `{ error: err.message }`\\n\\nA final 2-parameter middleware acts as a catch-all 404 handler:\\n```javascript\\napp.use(function(req, res){ ... })\\n```\\n- Executes only if all preceding middleware and routes call `next()` without sending a response\\n- Returns `404` with `{ error: \\\"Sorry, can't find that\\\" }`\\n\\n### Error Factory\\nThe `error(status, msg)` helper creates standard `Error` instances augmented with a `.status` property. This pattern aligns with Connect/Express conventions, allowing downstream error handlers to inspect HTTP status codes directly on the error object.\\n\\n## Data Structures\\nThe module uses in-memory objects to simulate a database layer:\\n- `apiKeys`: Array of valid keys (`['foo', 'bar', 'baz']`)\\n- `users`: Array of user objects\\n- `repos`: Array of repository objects\\n- `userRepos`: Object mapping usernames to arrays of repository objects\\n\\n## Execution &amp; Module Export\\nThe application instance is exported for testing or composition:\\n```javascript\\nvar app = module.exports = express();\\n```\\nThe server only starts when executed directly:\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\nThis pattern allows the module to be `require()`d in test suites without binding to a port, while remaining runnable as a standalone script.\\n\\n## Middleware Pipeline\\n```mermaid\\ngraph TD\\n    A[Client Request] --&gt; B{Path starts with /api?}\\n    B --&gt;|No| C[404 Fallback]\\n    B --&gt;|Yes| D[API Key Validation]\\n    D --&gt;|Invalid/Missing| E[Error Handler]\\n    D --&gt;|Valid| F[Route Handler]\\n    F --&gt;|Match Found| G[res.send JSON]\\n    F --&gt;|No Match| C\\n    E --&gt; H[Return Error JSON]\\n    C --&gt; I[Return 404 JSON]\\n```\",\"overview\":\"# express \u2014 Wiki\\n\\n# Express\\n\\nWelcome to the Express documentation. Express is a fast, unopinionated, minimalist web framework for Node.js. It provides a robust set of features for building web and mobile applications while keeping the core lightweight, flexible, and easy to extend.\\n\\n## Quick Start\\n\\nInstall Express in your project directory:\\n```bash\\nnpm install express\\n```\\n\\nCreate a basic server:\\n```javascript\\nconst express = require('express');\\nconst app = express();\\nconst port = 3000;\\n\\napp.get('/', (req, res) =&gt; {\\n  res.send('Hello World!');\\n});\\n\\napp.listen(port, () =&gt; {\\n  console.log(`Server running at http://localhost:${port}`);\\n});\\n```\\n\\n## Architecture Overview\\n\\nExpress is built around a prototype-mixing architecture that extends Node.js's native HTTP primitives. When a request arrives, the framework instantiates a callable application object, attaches extended request and response prototypes, and passes control through a configurable middleware stack.\\n\\n```mermaid\\ngraph TD\\n    NodeHTTP[Node.js HTTP] --&gt; App[Application Core]\\n    App --&gt; Req[Request API]\\n    App --&gt; Res[Response API]\\n    App --&gt; View[View Rendering]\\n    App --&gt; Utils[Utilities]\\n    Req --&gt; Utils\\n    Res --&gt; Utils\\n    Res --&gt; View\\n```\\n\\nThe [Application Core](application-core.md) serves as the central factory and lifecycle manager. It initializes the `app` object, handles configuration, mounts middleware, delegates routing, and bootstraps the underlying HTTP server.\\n\\nIncoming requests and outgoing responses are enhanced by the [Request API](request-api.md) and [Response API](response-api.md) modules. These extend `http.IncomingMessage` and `http.ServerResponse` respectively, adding Express-specific methods for header management, content negotiation, proxy resolution, and chainable response handling.\\n\\nTemplate rendering is abstracted through the [View Rendering](view-rendering.md) module, which dynamically loads engines, resolves file paths, and executes templates asynchronously. It is invoked internally by `app.render()` and `res.render()`.\\n\\nSupporting all of these layers is the [Utilities](utilities.md) module, which provides internal helpers for HTTP method normalization, ETag generation, query parsing, proxy trust evaluation, and configuration compilation.\\n\\n## Development &amp; Testing\\n\\nThe repository includes a suite of npm scripts to streamline development and ensure code quality:\\n\\n- `npm run lint` / `npm run lint:fix` \u2014 Check and automatically fix code style issues\\n- `npm test` \u2014 Run the full test suite\\n- `npm run test-ci` \u2014 Run tests optimized for continuous integration environments\\n- `npm run test-cov` \u2014 Generate test coverage reports\\n- `npm run test-tap` \u2014 Run tests using the TAP reporter\\n\\nFor detailed contribution guidelines, security reporting procedures, and team information, please refer to the project's [Contributing](contributing.md) and [Code of Conduct](code-of-conduct.md) pages.\\n\\n## Next Steps\\n\\n- Dive into the [Application Core](application-core.md) to understand routing, middleware mounting, and server initialization.\\n- Explore the [Request API](request-api.md) and [Response API](response-api.md) to see how Express extends native HTTP objects.\\n- Review the [View Rendering](view-rendering.md) documentation for template engine integration.\\n- Check out the official [Express.js website](https://expressjs.com/) for guides, API references, and community resources.\",\"request-api\":\"# Request API\\n\\n# Request API Module (`lib/request.js`)\\n\\n## Overview\\nThe Request API module extends Node.js's native `http.IncomingMessage` prototype to provide Express-specific request handling capabilities. It exports a prototype object (`req`) that is mixed into every incoming HTTP request. The module adds methods and lazy-evaluated properties for header access, content negotiation, proxy resolution, URL parsing, and cache validation, while maintaining strict compatibility with the underlying Node.js HTTP implementation.\\n\\n## Architecture &amp; Prototype Extension\\nThe module creates its prototype via `Object.create(http.IncomingMessage.prototype)` and attaches all custom functionality directly to it. This design ensures that:\\n- Native `IncomingMessage` properties and methods remain fully accessible.\\n- Express-specific features are added without modifying Node.js core objects.\\n- Performance is optimized through lazy evaluation: expensive operations (query parsing, proxy resolution, header normalization) are deferred until the property is first accessed.\\n\\n```mermaid\\ngraph TD\\n  IncomingMessage[http.IncomingMessage] --&gt;|extends| req[req Prototype]\\n  req --&gt;|lazy evaluation| defineGetter[defineGetter]\\n  req --&gt;|content negotiation| accepts[accepts]\\n  req --&gt;|type checking| typeis[type-is]\\n  req --&gt;|proxy resolution| proxyaddr[proxy-addr]\\n  req --&gt;|cache validation| fresh[fresh]\\n  req --&gt;|URL parsing| parseurl[parseurl]\\n  req --&gt;|range parsing| rangeparser[range-parser]\\n  appConfig[Express App Settings] --&gt;|trust proxy, query parser, subdomain offset| req\\n```\\n\\n## API Reference\\n\\n### Header Access\\n| Method | Description |\\n|--------|-------------|\\n| `req.get(name)` / `req.header(name)` | Retrieves a request header by name. Case-insensitive. Special-cased to handle both `Referer` and `Referrer` interchangeably. Throws `TypeError` if `name` is missing or not a string. |\\n\\n### Content Negotiation\\nAll negotiation methods wrap the `accepts` library and return the best matching type, an array of matches, or `false` if none are acceptable.\\n\\n| Method | Description |\\n|--------|-------------|\\n| `req.accepts(...types)` | Checks `Accept` header. Accepts MIME types, extensions, or arrays. |\\n| `req.acceptsEncodings(...encodings)` | Checks `Accept-Encoding` header. |\\n| `req.acceptsCharsets(...charsets)` | Checks `Accept-Charset` header. Supports comma-delimited strings or multiple arguments. |\\n| `req.acceptsLanguages(...languages)` | Checks `Accept-Language` header. |\\n\\n### Content-Type Validation\\n| Method | Description |\\n|--------|-------------|\\n| `req.is(...types)` | Checks if the incoming `Content-Type` matches the given MIME type(s). Uses `type-is`. Supports flattened arguments or arrays. Returns the matched type string, `false`, or `null` if no `Content-Type` is present. |\\n\\n### URL &amp; Query Parsing\\n| Property/Method | Description |\\n|-----------------|-------------|\\n| `req.path` | Returns the URL pathname. Uses `parseurl` for efficient caching. |\\n| `req.query` | Parses the query string using the app's configured `query parser fn`. Returns an empty object if parsing is disabled. |\\n| `req.range(size, options)` | Parses the `Range` header. Returns `undefined` if missing, `-1` if unsatisfiable, `-2` if syntactically invalid, or an array of `{start, end}` objects. Supports `options.combine` to merge overlapping ranges. |\\n\\n### Proxy &amp; Network Resolution\\nAll network-related getters respect the `trust proxy` application setting. When enabled, they prioritize `X-Forwarded-*` headers over socket-level data.\\n\\n| Property | Description |\\n|----------|-------------|\\n| `req.protocol` | Returns `\\\"http\\\"` or `\\\"https\\\"`. Falls back to `X-Forwarded-Proto` if trusted. |\\n| `req.secure` | Boolean shorthand for `req.protocol === 'https'`. |\\n| `req.ip` | Returns the remote IP address. Uses `proxy-addr` to resolve trusted proxy chains. |\\n| `req.ips` | Returns an array of IP addresses from the client to the furthest trusted proxy, ordered closest to farthest. |\\n| `req.host` | Returns the `Host` header value. Falls back to `X-Forwarded-Host` if trusted. Handles comma-separated proxy lists safely. |\\n| `req.hostname` | Extracts the hostname from `req.host`, stripping port numbers and handling IPv6 literals (`[::1]`). |\\n| `req.subdomains` | Returns an array of subdomains. Splits `req.hostname` by `.` and slices based on the `subdomain offset` app setting. Returns `[]` for IP addresses. |\\n\\n### Cache &amp; Request State\\n| Property | Description |\\n|----------|-------------|\\n| `req.fresh` | Returns `true` if the request is cacheable (`GET`/`HEAD`) and the response's `ETag` or `Last-Modified` headers match the request's conditional headers. Uses the `fresh` library. |\\n| `req.stale` | Boolean inverse of `req.fresh`. |\\n| `req.xhr` | Returns `true` if `X-Requested-With` header equals `xmlhttprequest` (case-insensitive). |\\n\\n## Internal Mechanics\\n\\n### Lazy Evaluation via `defineGetter`\\nThe private `defineGetter(obj, name, getter)` function uses `Object.defineProperty` to attach properties with `configurable: true`, `enumerable: true`, and a custom `get` function. This pattern ensures:\\n- Zero overhead for unused properties.\\n- Consistent API surface across all request objects.\\n- Safe re-evaluation if underlying headers or app settings change mid-request (though typically headers are static per request).\\n\\n### Application Settings Integration\\nSeveral getters dynamically query the Express application instance (`this.app`) at access time:\\n- `this.app.get('trust proxy fn')`: Determines whether to trust `X-Forwarded-*` headers for `protocol`, `ip`, `ips`, `host`, and `hostname`.\\n- `this.app.get('query parser fn')`: Supplies the parsing function for `req.query`.\\n- `this.app.get('subdomain offset')`: Controls how many trailing domain parts are excluded from `req.subdomains`.\\n\\nThis design allows runtime configuration changes to affect request behavior without requiring prototype mutation or server restarts.\\n\\n## Integration Notes\\n- **Attachment:** The exported `req` prototype is typically assigned to `app.request` in Express's initialization phase and mixed into `http.IncomingMessage` instances during request creation.\\n- **Execution Flow:** The module itself contains no runtime execution logic. All methods and getters execute per-request when invoked or accessed. The only internal call graph edge is `req` \u2192 `defineGetter` during module initialization.\\n- **Error Handling:** `req.get()` explicitly validates input types. Other methods rely on underlying libraries (`accepts`, `type-is`, `range-parser`) to handle malformed headers gracefully, returning `false`, `undefined`, or numeric error codes as documented.\\n- **Extensibility:** Developers can safely add custom properties to `req` by extending the exported prototype before the server starts listening, or by using middleware that attaches properties to `req` at runtime.\",\"response-api\":\"# Response API\\n\\n# Response API (`lib/response.js`)\\n\\n## Overview\\nThe `Response` module extends Node.js's native `http.ServerResponse.prototype` to provide Express-specific response handling capabilities. It exposes a chainable API for setting status codes, managing headers, transmitting data (strings, JSON, buffers), streaming files, handling cookies, performing redirects, and rendering views. The module is instantiated once and attached to every incoming request's `res` object during the Express routing lifecycle.\\n\\n## Architecture &amp; Prototype Chain\\n```javascript\\nvar res = Object.create(http.ServerResponse.prototype)\\nmodule.exports = res\\n```\\nThe module uses prototypal inheritance to augment `http.ServerResponse`. All methods return `this` to enable method chaining. The prototype relies on several external utilities (`mime-types`, `content-disposition`, `send`, `vary`, `cookie`, `on-finished`) and reads runtime configuration from `this.app` and `this.req`.\\n\\n## Core Methods\\n\\n### Status &amp; Header Management\\n| Method | Description |\\n|--------|-------------|\\n| `res.status(code)` | Validates and sets `this.statusCode`. Throws `TypeError` for non-integers and `RangeError` for codes outside `100\u2013999`. |\\n| `res.set(field, val)` / `res.header()` | Sets headers. Automatically expands `Content-Type` via `mime.contentType()`. Accepts objects for bulk setting. |\\n| `res.get(field)` | Alias for `this.getHeader(field)`. |\\n| `res.append(field, val)` | Appends values to existing headers, handling array/string concatenation safely. |\\n| `res.vary(field)` | Adds `field` to the `Vary` header using the `vary` package. Ignores duplicates. |\\n| `res.links(links)` | Constructs and sets the `Link` header. Supports arrays for multiple links per relation. |\\n\\n### Data Transmission\\n| Method | Description |\\n|--------|-------------|\\n| `res.send(body)` | Core transmission method. Handles strings, buffers, booleans, numbers, and objects. Automatically sets `Content-Type`, calculates `Content-Length`, generates ETags (if configured), and strips payload headers for `204`, `205`, and `304` responses. |\\n| `res.json(obj)` | Serializes `obj` to JSON, sets `Content-Type: application/json`, and delegates to `res.send()`. |\\n| `res.jsonp(obj)` | Wraps JSON in a callback function. Extracts callback name from `req.query[app.get('jsonp callback name')]`. Includes Rosetta Flash mitigation (`/**/ typeof ...`) and escapes U+2028/U+2029. |\\n| `res.sendStatus(statusCode)` | Sets status and sends the standard HTTP status message (or numeric fallback) as `text/plain`. |\\n\\n### File Transfer &amp; Streaming\\n| Method | Description |\\n|--------|-------------|\\n| `res.sendFile(path, options, callback)` | Streams a file using the `send` module. Requires absolute paths or `options.root`. Wires app-level `etag` setting. Handles errors via `next()` or callback. |\\n| `res.download(path, filename, options, callback)` | Wrapper around `res.sendFile()` that automatically sets `Content-Disposition: attachment`. Supports flexible argument ordering for `filename`, `options`, and `callback`. |\\n\\n### Content Negotiation\\n| Method | Description |\\n|--------|-------------|\\n| `res.format(obj)` | Matches `req.accepts()` against object keys. Sets `Content-Type` and invokes the matched handler. Falls back to `obj.default` or throws a `406 Not Acceptable` error via `createError`. |\\n| `res.type(type)` / `res.contentType()` | Resolves MIME types via `mime.contentType()`. Falls back to `application/octet-stream` if unmapped. |\\n| `res.attachment(filename)` | Sets `Content-Disposition: attachment` and infers `Content-Type` from the file extension. |\\n\\n### Cookies &amp; Redirects\\n| Method | Description |\\n|--------|-------------|\\n| `res.cookie(name, value, options)` | Serializes cookies using the `cookie` package. Supports `maxAge` \u2192 `expires` conversion, signed cookies (`s:` prefix via `cookie-signature`), and JSON values (`j:` prefix). Requires `req.secret` for signed cookies. |\\n| `res.clearCookie(name, options)` | Expires a cookie by setting `expires: new Date(1)` and removing `maxAge`. |\\n| `res.location(url)` | Sets the `Location` header with URL encoding via `encodeurl`. |\\n| `res.redirect(url)` | Performs HTTP redirects (default `302`). Supports `res.redirect(status, url)`. Generates `text/plain` or `text/html` fallback bodies based on `Accept` headers. |\\n\\n### View Rendering\\n| Method | Description |\\n|--------|-------------|\\n| `res.render(view, options, callback)` | Delegates to `app.render()`. Merges `res.locals` into `opts._locals`. If no callback is provided, automatically sends the rendered string with `200 OK`. |\\n\\n## Internal Helpers &amp; Execution Flow\\n\\n### `sendfile(res, file, options, callback)`\\nManages the lifecycle of file streams created by `res.sendFile()` and `res.download()`. It attaches event listeners to the `send` stream and uses `on-finished` to monitor the response socket.\\n\\n```mermaid\\ngraph TD\\n  A[sendfile] --&gt; B[file.pipe res]\\n  A --&gt; C[on-finished]\\n  C --&gt; D{onfinish}\\n  D --&gt;|ECONNRESET| E[onaborted]\\n  D --&gt;|Other Error| F[onerror]\\n  D --&gt;|Success| G[callback]\\n  B --&gt; H[file events: directory, end, error, file, stream]\\n  H --&gt; D\\n```\\n\\nKey behaviors:\\n- Prevents duplicate callback execution via a `done` flag.\\n- Translates `EISDIR` to a directory error, allowing `res.sendFile()` to call `next()`.\\n- Aborts streaming if the response finishes before the file stream completes.\\n- Applies custom headers via the `headers` event if provided in `options`.\\n\\n### `stringify(value, replacer, spaces, escape)`\\nOptimized JSON serialization wrapper. When `escape` is `true` (controlled by `app.get('json escape')`), it replaces `&lt;`, `&gt;`, and `&amp;` with Unicode escapes (`\\\\u003c`, `\\\\u003e`, `\\\\u0026`) to mitigate HTML injection in JSON payloads.\\n\\n## Configuration Dependencies\\nMethods dynamically read application settings at runtime:\\n- `app.get('etag fn')` / `app.enabled('etag')`: Controls ETag generation in `res.send()` and `res.sendFile()`.\\n- `app.get('json escape')`, `app.get('json replacer')`, `app.get('json spaces')`: Configures `res.json()` and `res.jsonp()` serialization.\\n- `app.get('jsonp callback name')`: Defines the query parameter for JSONP callbacks.\\n- `this.req.secret`: Required when `options.signed` is passed to `res.cookie()`.\\n\\n## Security &amp; Edge Cases\\n- **Status Code Validation:** `res.status()` strictly enforces integer types and `100\u2013999` range.\\n- **Header Stripping:** `res.send()` automatically removes `Content-Type`, `Content-Length`, and `Transfer-Encoding` for `204` and `304` responses, and forces `Content-Length: 0` for `205`.\\n- **HEAD Requests:** `res.send()` and `res.redirect()` skip body transmission for `HEAD` methods, calling `this.end()` without arguments.\\n- **Freshness Check:** `res.send()` checks `req.fresh` and automatically downgrades to `304 Not Modified` when applicable.\\n- **Path Validation:** `res.sendFile()` throws if `path` is missing, non-string, or relative without a `root` option.\\n\\n## Contribution Guidelines\\n- All public methods must return `this` to maintain chainability.\\n- Header manipulation should use `mime.contentType()` for type resolution and `setCharset()` for charset normalization.\\n- When adding streaming capabilities, follow the `sendfile` pattern: use `on-finished` for socket lifecycle management and guard callbacks with a `done` flag to prevent double-invocation.\\n- Deprecations are handled via the `depd` module. Use `deprecate('message')` for legacy argument patterns.\\n- ETag generation is intentionally deferred to app configuration; do not hardcode hashing algorithms in this module.\",\"utilities\":\"# Utilities\\n\\n# Utilities Module (`lib/utils.js`)\\n\\n## Overview\\nThe `utils` module provides internal helper functions and configuration compilers used throughout the Express framework. It centralizes logic for HTTP method normalization, MIME type resolution, ETag generation, query string parsing, proxy trust evaluation, and `Content-Type` charset manipulation. All exports are marked `@api private` and are intended exclusively for internal framework consumption.\\n\\n## Configuration Compilation Pattern\\nExpress accepts flexible configuration values for several core features. This module standardizes those values into optimized, executable functions using three compiler utilities:\\n\\n- `compileETag(val)`: Maps ETag settings (`true`, `'weak'`, `'strong'`, `false`, or a custom function) to an ETag generator.\\n- `compileQueryParser(val)`: Maps query parser settings (`true`, `'simple'`, `'extended'`, `false`, or a custom function) to a query string parser.\\n- `compileTrust(val)`: Maps proxy trust settings (`true`, `false`, hop count, comma-separated IPs, or a custom function) to a trust evaluation function.\\n\\nEach compiler follows a consistent dispatch pattern:\\n1. If `val` is already a function, it is returned directly.\\n2. If `val` matches a known string/boolean/number, it is mapped to a predefined implementation.\\n3. Unrecognized values throw a `TypeError`.\\n\\n## Core Exports\\n\\n### HTTP &amp; Content Negotiation\\n- `methods`: Array of lowercased HTTP methods supported by Node.js (e.g., `['get', 'post', 'put', ...]`).\\n- `normalizeType(type)`: Resolves a MIME type shorthand (e.g., `\\\"html\\\"`) to a full type string (`\\\"text/html\\\"`). If the input already contains a `/`, it delegates to `acceptParams()` to extract quality and parameter data.\\n- `normalizeTypes(types)`: Maps `normalizeType` over an array of type strings.\\n- `setCharset(type, charset)`: Injects or replaces the `charset` parameter in a `Content-Type` string using the `content-type` library. Returns the original string if either argument is falsy.\\n\\n### ETag Generation\\n- `etag(body, [encoding])`: Generates a strong ETag for the provided string or `Buffer`.\\n- `wetag(body, [encoding])`: Generates a weak ETag for the provided string or `Buffer`.\\nBoth are instantiated via the internal `createETagGenerator()` factory, which ensures input is normalized to a `Buffer` before delegation to the `etag` package.\\n\\n### Query Parsing\\n- `compileQueryParser(val)`: (See Configuration Compilation Pattern)\\n- `parseExtendedQueryString(str)`: Internal wrapper around `qs.parse()` configured with `allowPrototypes: true` to safely handle complex query structures.\\n\\n### Proxy Trust\\n- `compileTrust(val)`: (See Configuration Compilation Pattern)\\nNormalizes string inputs into trimmed arrays and delegates to `proxy-addr.compile()` for IP/hop validation.\\n\\n## Internal Utilities\\n- `acceptParams(str)`: Parses HTTP `Accept` header parameters. Extracts the media type/value, quality factor (`q`), and additional parameters into an object `{ value, quality, params }`. Handles edge cases like missing semicolons or malformed splits by tracking index boundaries.\\n- `createETagGenerator(options)`: Factory function that returns a closure for generating ETags. Handles `Buffer` conversion and passes the `weak` option to the underlying `etag` library.\\n- `parseExtendedQueryString(str)`: Dedicated parser for the `'extended'` query mode, isolating `qs` configuration from the rest of the module.\\n\\n## Architecture &amp; Call Flow\\nThe module acts as a centralized utility hub. Configuration compilers route to either built-in Node.js modules, third-party packages, or internal helpers. Internal utilities are invoked by exports to maintain a clean public API surface.\\n\\n```mermaid\\ngraph TD\\n  A[compileETag] --&gt; B{val type?}\\n  B --&gt;|'weak'| C[wetag]\\n  B --&gt;|'strong'| D[etag]\\n  B --&gt;|function| E[return val]\\n  \\n  F[compileQueryParser] --&gt; G{val type?}\\n  G --&gt;|'simple'| H[querystring.parse]\\n  G --&gt;|'extended'| I[parseExtendedQueryString]\\n  \\n  J[normalizeType] --&gt; K{contains '/'?}\\n  K --&gt;|yes| L[acceptParams]\\n  K --&gt;|no| M[mime.lookup]\\n  \\n  C --&gt; N[createETagGenerator]\\n  D --&gt; N\\n```\\n\\n## Dependencies\\n| Package | Purpose |\\n|---|---|\\n| `node:http` | Provides `METHODS` array for HTTP method normalization |\\n| `content-type` | Parses and formats `Content-Type` headers for charset manipulation |\\n| `etag` | Generates strong/weak ETags from Buffers |\\n| `mime-types` | Resolves file extensions to MIME types |\\n| `proxy-addr` | Compiles and evaluates proxy trust functions |\\n| `qs` | Parses extended query strings with prototype safety |\\n| `node:querystring` | Provides simple query string parsing for `'simple'` mode |\\n| `node:buffer` | Ensures consistent `Buffer` handling for ETag generation |\\n\\n## Integration Notes\\n- This module is loaded during Express initialization and is referenced by `lib/application.js`, `lib/request.js`, and `lib/response.js`.\\n- Compiler functions (`compileETag`, `compileQueryParser`, `compileTrust`) are typically invoked during `app.set()` or `app.enable()` calls to transform user-provided settings into cached runtime functions, avoiding repeated type-checking on every request.\\n- `normalizeType` and `acceptParams` are heavily utilized in content negotiation logic to match `Accept` headers against supported response types.\\n- All functions are synchronous and designed for minimal allocation overhead. Modifying exported functions or internal helpers will directly impact framework behavior.\",\"view-rendering\":\"# View Rendering\\n\\n# View Rendering Module (`lib/view.js`)\\n\\n## Overview\\nThe `View` module encapsulates the lifecycle of a single template in Express. It is responsible for:\\n- Parsing view names and resolving file extensions\\n- Dynamically loading and caching template engines\\n- Resolving absolute file paths against configured view directories\\n- Executing the template engine with normalized asynchronous callbacks\\n\\nThis module is instantiated internally by `res.render()` and `app.render()`. It acts as a bridge between Express routing/response logic and third-party template engines (e.g., Pug, EJS, Handlebars).\\n\\n## Constructor &amp; Initialization\\n```javascript\\nfunction View(name, options)\\n```\\nThe constructor accepts a view `name` (string) and an `options` object containing:\\n- `defaultEngine`: The fallback engine name (e.g., `'pug'`)\\n- `engines`: A shared cache object for loaded engine functions\\n- `root`: Base directory or array of directories for view lookup\\n\\n### Initialization Flow\\n1. Extracts the file extension from `name` using `path.extname()`.\\n2. Validates that either an extension is provided or a `defaultEngine` is configured. Throws if neither exists.\\n3. If no extension is present, appends the `defaultEngine` (ensuring a leading `.`) to the filename.\\n4. Loads the template engine if not already cached in `opts.engines`.\\n5. Stores the resolved engine function in `this.engine`.\\n6. Resolves the absolute file path via `this.lookup(fileName)` and stores it in `this.path`.\\n\\n## Engine Loading &amp; Caching\\nExpress expects template engines to export a `__express` function conforming to the signature `(path, options, callback)`. The `View` module handles dynamic loading:\\n\\n```javascript\\nvar mod = this.ext.slice(1)\\nvar fn = require(mod).__express\\n```\\n- The leading `.` is stripped from the extension to form the module name (e.g., `.ejs` \u2192 `ejs`).\\n- The engine is required synchronously. If `__express` is missing or not a function, an error is thrown.\\n- Loaded engines are stored in the shared `opts.engines` cache, preventing redundant `require()` calls across multiple `View` instances.\\n\\n## Path Resolution Strategy\\nPath resolution is split between `lookup()` and `resolve()`, supporting multiple view directories and fallback patterns.\\n\\n### `View.prototype.lookup(name)`\\n- Normalizes `this.root` into an array to support multiple view directories.\\n- Iterates through each root, resolving an absolute path with `path.resolve()`.\\n- Delegates to `this.resolve(dir, file)` for each root until a valid file is found.\\n\\n### `View.prototype.resolve(dir, file)`\\nImplements a two-step resolution strategy:\\n1. **Exact Match**: Checks `/` using `tryStat()`.\\n2. **Index Fallback**: If the exact match fails, checks `//index.`.\\n\\nBoth checks use `fs.statSync()` wrapped in `tryStat()` to safely return `undefined` on missing files without throwing.\\n\\n## Rendering &amp; Callback Normalization\\n```javascript\\nView.prototype.render = function render(options, callback)\\n```\\nThe `render` method executes the loaded engine and guarantees asynchronous callback invocation, which is critical for Express middleware consistency.\\n\\n### Sync-to-Async Normalization\\nSome template engines execute synchronously. To prevent stack overflows and maintain predictable event-loop behavior, `render` uses a `sync` flag:\\n1. `sync` is initialized to `true`.\\n2. The engine is called: `this.engine(this.path, options, onRender)`.\\n3. If the engine calls `onRender` synchronously (`sync === true`), the callback arguments and context are copied, and execution is deferred to `process.nextTick()`.\\n4. If the engine calls `onRender` asynchronously (`sync === false`), the callback is invoked immediately.\\n5. `sync` is set to `false` after the engine call returns, ensuring only the first synchronous callback is deferred.\\n\\n## Integration with Express\\nThe `View` module does not operate in isolation. It relies on application-level configuration passed through the `options` object:\\n- `app.set('views', '/path/to/views')` \u2192 populates `options.root`\\n- `app.set('view engine', 'pug')` \u2192 populates `options.defaultEngine`\\n- `app.engines` \u2192 passed as `options.engines` for cross-request caching\\n\\nWhen `res.render(view, locals, callback)` is called, Express constructs a new `View` instance, merges `res.locals` with `locals`, and invokes `view.render()`.\\n\\n## Architecture Flow\\n```mermaid\\nsequenceDiagram\\n    participant App as Express App\\n    participant View as View Instance\\n    participant Engine as Template Engine\\n    participant FS as File System\\n\\n    App-&gt;&gt;View: new View(name, options)\\n    View-&gt;&gt;View: Load/cache engine via require(mod).__express\\n    View-&gt;&gt;View: lookup() &amp; resolve()\\n    View-&gt;&gt;FS: tryStat() (sync)\\n    FS--&gt;&gt;View: File path or undefined\\n    View--&gt;&gt;App: Initialized View with this.path &amp; this.engine\\n    App-&gt;&gt;View: render(options, callback)\\n    View-&gt;&gt;Engine: this.engine(path, options, onRender)\\n    alt Sync Engine\\n        Engine--&gt;&gt;View: onRender() (sync)\\n        View-&gt;&gt;View: process.nextTick(callback)\\n    else Async Engine\\n        Engine--&gt;&gt;View: onRender() (async)\\n        View-&gt;&gt;View: callback()\\n    end\\n    View--&gt;&gt;App: Rendered HTML / Error\\n```\\n\\n## Contributing Notes\\n- **Engine Compatibility**: Any new template engine must export a `__express` function matching `(path, options, callback)`. The callback signature is `(err, html)`.\\n- **Sync Safety**: Do not remove the `process.nextTick` normalization. Many engines run synchronously, and Express routing assumes async rendering to avoid blocking the event loop or causing unhandled sync errors in middleware chains.\\n- **Path Resolution**: The `tryStat` helper uses synchronous I/O intentionally. View resolution happens during request setup, and synchronous checks are acceptable here. Avoid introducing async `fs.stat` unless benchmarking proves a bottleneck.\\n- **Cache Management**: The `engines` cache is shared across the application. Clearing it requires modifying `app.engines` directly; the `View` module does not expose cache invalidation methods.\"};\nvar TREE = [{\"name\":\"Application Core\",\"slug\":\"application-core\",\"files\":[\"index.js\",\"lib/express.js\",\"lib/application.js\"]},{\"name\":\"Request API\",\"slug\":\"request-api\",\"files\":[\"lib/request.js\"]},{\"name\":\"Response API\",\"slug\":\"response-api\",\"files\":[\"lib/response.js\"]},{\"name\":\"View Rendering\",\"slug\":\"view-rendering\",\"files\":[\"lib/view.js\"]},{\"name\":\"Utilities\",\"slug\":\"utilities\",\"files\":[\"lib/utils.js\"]},{\"name\":\"Other\",\"slug\":\"other\",\"files\":[],\"children\":[{\"name\":\"Other \u2014 History.md\",\"slug\":\"other-history-md\",\"files\":[\"History.md\"]},{\"name\":\"Other \u2014 Readme.md\",\"slug\":\"other-readme-md\",\"files\":[\"Readme.md\"]},{\"name\":\"Other \u2014 examples\",\"slug\":\"other-examples\",\"files\":[\"examples/README.md\"]},{\"name\":\"Other \u2014 auth\",\"slug\":\"other-auth\",\"files\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\"]},{\"name\":\"Other \u2014 content-negotiation\",\"slug\":\"other-content-negotiation\",\"files\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\"]},{\"name\":\"Other \u2014 cookie-sessions\",\"slug\":\"other-cookie-sessions\",\"files\":[\"examples/cookie-sessions/index.js\"]},{\"name\":\"Other \u2014 cookies\",\"slug\":\"other-cookies\",\"files\":[\"examples/cookies/index.js\"]},{\"name\":\"Other \u2014 downloads\",\"slug\":\"other-downloads\",\"files\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\"]},{\"name\":\"Other \u2014 ejs\",\"slug\":\"other-ejs\",\"files\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\"]},{\"name\":\"Other \u2014 error-pages\",\"slug\":\"other-error-pages\",\"files\":[\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\"]},{\"name\":\"Other \u2014 error\",\"slug\":\"other-error\",\"files\":[\"examples/error/index.js\"]},{\"name\":\"Other \u2014 hello-world\",\"slug\":\"other-hello-world\",\"files\":[\"examples/hello-world/index.js\"]},{\"name\":\"Other \u2014 markdown\",\"slug\":\"other-markdown\",\"files\":[\"examples/markdown/index.js\",\"examples/markdown/views/index.md\"]},{\"name\":\"Other \u2014 multi-router\",\"slug\":\"other-multi-router\",\"files\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\"]},{\"name\":\"Other \u2014 mvc\",\"slug\":\"other-mvc\",\"files\":[\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\"]},{\"name\":\"Other \u2014 online\",\"slug\":\"other-online\",\"files\":[\"examples/online/index.js\"]},{\"name\":\"Other \u2014 params\",\"slug\":\"other-params\",\"files\":[\"examples/params/index.js\"]},{\"name\":\"Other \u2014 resource\",\"slug\":\"other-resource\",\"files\":[\"examples/resource/index.js\"]},{\"name\":\"Other \u2014 route-map\",\"slug\":\"other-route-map\",\"files\":[\"examples/route-map/index.js\"]},{\"name\":\"Other \u2014 route-middleware\",\"slug\":\"other-route-middleware\",\"files\":[\"examples/route-middleware/index.js\"]},{\"name\":\"Other \u2014 route-separation\",\"slug\":\"other-route-separation\",\"files\":[\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"]},{\"name\":\"Other \u2014 search\",\"slug\":\"other-search\",\"files\":[\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"]},{\"name\":\"Other \u2014 session\",\"slug\":\"other-session\",\"files\":[\"examples/session/index.js\",\"examples/session/redis.js\"]},{\"name\":\"Other \u2014 static-files\",\"slug\":\"other-static-files\",\"files\":[\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"]},{\"name\":\"Other \u2014 vhost\",\"slug\":\"other-vhost\",\"files\":[\"examples/vhost/index.js\"]},{\"name\":\"Other \u2014 view-constructor\",\"slug\":\"other-view-constructor\",\"files\":[\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\"]},{\"name\":\"Other \u2014 view-locals\",\"slug\":\"other-view-locals\",\"files\":[\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"]},{\"name\":\"Other \u2014 web-service\",\"slug\":\"other-web-service\",\"files\":[\"examples/web-service/index.js\"]},{\"name\":\"Other \u2014 package.json\",\"slug\":\"other-package-json\",\"files\":[\"package.json\"]},{\"name\":\"Other \u2014 test\",\"slug\":\"other-test\",\"files\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"]},{\"name\":\"Other \u2014 acceptance\",\"slug\":\"other-acceptance\",\"files\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"]},{\"name\":\"Other \u2014 support\",\"slug\":\"other-support\",\"files\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]}]}];\nvar META = {\"fromCommit\":\"f873ac23124ffcff8c040b4bd257b32c29828d53\",\"generatedAt\":\"2026-05-09T02:42:42.656Z\",\"model\":\"qwen3.6-plus\",\"moduleFiles\":{\"Application Core\":[\"index.js\",\"lib/express.js\",\"lib/application.js\"],\"Request API\":[\"lib/request.js\"],\"Response API\":[\"lib/response.js\"],\"View Rendering\":[\"lib/view.js\"],\"Utilities\":[\"lib/utils.js\"],\"Other\":[\"History.md\",\"Readme.md\",\"examples/README.md\",\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\",\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\",\"examples/cookie-sessions/index.js\",\"examples/cookies/index.js\",\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\",\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\",\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\",\"examples/error/index.js\",\"examples/hello-world/index.js\",\"examples/markdown/index.js\",\"examples/markdown/views/index.md\",\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\",\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\",\"examples/online/index.js\",\"examples/params/index.js\",\"examples/resource/index.js\",\"examples/route-map/index.js\",\"examples/route-middleware/index.js\",\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\",\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\",\"examples/session/index.js\",\"examples/session/redis.js\",\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\",\"examples/vhost/index.js\",\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\",\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\",\"examples/web-service/index.js\",\"package.json\",\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\",\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\",\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"],\"Other \u2014 History.md\":[\"History.md\"],\"Other \u2014 Readme.md\":[\"Readme.md\"],\"Other \u2014 examples\":[\"examples/README.md\"],\"Other \u2014 auth\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\"],\"Other \u2014 content-negotiation\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\"],\"Other \u2014 cookie-sessions\":[\"examples/cookie-sessions/index.js\"],\"Other \u2014 cookies\":[\"examples/cookies/index.js\"],\"Other \u2014 downloads\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\"],\"Other \u2014 ejs\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\"],\"Other \u2014 error-pages\":[\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\"],\"Other \u2014 error\":[\"examples/error/index.js\"],\"Other \u2014 hello-world\":[\"examples/hello-world/index.js\"],\"Other \u2014 markdown\":[\"examples/markdown/index.js\",\"examples/markdown/views/index.md\"],\"Other \u2014 multi-router\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\"],\"Other \u2014 mvc\":[\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\"],\"Other \u2014 online\":[\"examples/online/index.js\"],\"Other \u2014 params\":[\"examples/params/index.js\"],\"Other \u2014 resource\":[\"examples/resource/index.js\"],\"Other \u2014 route-map\":[\"examples/route-map/index.js\"],\"Other \u2014 route-middleware\":[\"examples/route-middleware/index.js\"],\"Other \u2014 route-separation\":[\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"],\"Other \u2014 search\":[\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"],\"Other \u2014 session\":[\"examples/session/index.js\",\"examples/session/redis.js\"],\"Other \u2014 static-files\":[\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"],\"Other \u2014 vhost\":[\"examples/vhost/index.js\"],\"Other \u2014 view-constructor\":[\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\"],\"Other \u2014 view-locals\":[\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"],\"Other \u2014 web-service\":[\"examples/web-service/index.js\"],\"Other \u2014 package.json\":[\"package.json\"],\"Other \u2014 test\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"],\"Other \u2014 acceptance\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"],\"Other \u2014 support\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]},\"moduleTree\":[{\"name\":\"Application Core\",\"slug\":\"application-core\",\"files\":[\"index.js\",\"lib/express.js\",\"lib/application.js\"]},{\"name\":\"Request API\",\"slug\":\"request-api\",\"files\":[\"lib/request.js\"]},{\"name\":\"Response API\",\"slug\":\"response-api\",\"files\":[\"lib/response.js\"]},{\"name\":\"View Rendering\",\"slug\":\"view-rendering\",\"files\":[\"lib/view.js\"]},{\"name\":\"Utilities\",\"slug\":\"utilities\",\"files\":[\"lib/utils.js\"]},{\"name\":\"Other\",\"slug\":\"other\",\"files\":[],\"children\":[{\"name\":\"Other \u2014 History.md\",\"slug\":\"other-history-md\",\"files\":[\"History.md\"]},{\"name\":\"Other \u2014 Readme.md\",\"slug\":\"other-readme-md\",\"files\":[\"Readme.md\"]},{\"name\":\"Other \u2014 examples\",\"slug\":\"other-examples\",\"files\":[\"examples/README.md\"]},{\"name\":\"Other \u2014 auth\",\"slug\":\"other-auth\",\"files\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\"]},{\"name\":\"Other \u2014 content-negotiation\",\"slug\":\"other-content-negotiation\",\"files\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\"]},{\"name\":\"Other \u2014 cookie-sessions\",\"slug\":\"other-cookie-sessions\",\"files\":[\"examples/cookie-sessions/index.js\"]},{\"name\":\"Other \u2014 cookies\",\"slug\":\"other-cookies\",\"files\":[\"examples/cookies/index.js\"]},{\"name\":\"Other \u2014 downloads\",\"slug\":\"other-downloads\",\"files\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\"]},{\"name\":\"Other \u2014 ejs\",\"slug\":\"other-ejs\",\"files\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\"]},{\"name\":\"Other \u2014 error-pages\",\"slug\":\"other-error-pages\",\"files\":[\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\"]},{\"name\":\"Other \u2014 error\",\"slug\":\"other-error\",\"files\":[\"examples/error/index.js\"]},{\"name\":\"Other \u2014 hello-world\",\"slug\":\"other-hello-world\",\"files\":[\"examples/hello-world/index.js\"]},{\"name\":\"Other \u2014 markdown\",\"slug\":\"other-markdown\",\"files\":[\"examples/markdown/index.js\",\"examples/markdown/views/index.md\"]},{\"name\":\"Other \u2014 multi-router\",\"slug\":\"other-multi-router\",\"files\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\"]},{\"name\":\"Other \u2014 mvc\",\"slug\":\"other-mvc\",\"files\":[\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\"]},{\"name\":\"Other \u2014 online\",\"slug\":\"other-online\",\"files\":[\"examples/online/index.js\"]},{\"name\":\"Other \u2014 params\",\"slug\":\"other-params\",\"files\":[\"examples/params/index.js\"]},{\"name\":\"Other \u2014 resource\",\"slug\":\"other-resource\",\"files\":[\"examples/resource/index.js\"]},{\"name\":\"Other \u2014 route-map\",\"slug\":\"other-route-map\",\"files\":[\"examples/route-map/index.js\"]},{\"name\":\"Other \u2014 route-middleware\",\"slug\":\"other-route-middleware\",\"files\":[\"examples/route-middleware/index.js\"]},{\"name\":\"Other \u2014 route-separation\",\"slug\":\"other-route-separation\",\"files\":[\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"]},{\"name\":\"Other \u2014 search\",\"slug\":\"other-search\",\"files\":[\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"]},{\"name\":\"Other \u2014 session\",\"slug\":\"other-session\",\"files\":[\"examples/session/index.js\",\"examples/session/redis.js\"]},{\"name\":\"Other \u2014 static-files\",\"slug\":\"other-static-files\",\"files\":[\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"]},{\"name\":\"Other \u2014 vhost\",\"slug\":\"other-vhost\",\"files\":[\"examples/vhost/index.js\"]},{\"name\":\"Other \u2014 view-constructor\",\"slug\":\"other-view-constructor\",\"files\":[\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\"]},{\"name\":\"Other \u2014 view-locals\",\"slug\":\"other-view-locals\",\"files\":[\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"]},{\"name\":\"Other \u2014 web-service\",\"slug\":\"other-web-service\",\"files\":[\"examples/web-service/index.js\"]},{\"name\":\"Other \u2014 package.json\",\"slug\":\"other-package-json\",\"files\":[\"package.json\"]},{\"name\":\"Other \u2014 test\",\"slug\":\"other-test\",\"files\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"]},{\"name\":\"Other \u2014 acceptance\",\"slug\":\"other-acceptance\",\"files\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"]},{\"name\":\"Other \u2014 support\",\"slug\":\"other-support\",\"files\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]}]}]};\n\n(function() {\n  var activePage = 'overview';\n\n  document.addEventListener('DOMContentLoaded', function() {\n    mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' });\n    renderMeta();\n    renderNav();\n    document.getElementById('menu-toggle').addEventListener('click', function() {\n      document.getElementById('sidebar').classList.toggle('open');\n    });\n    if (location.hash &amp;&amp; location.hash.length &gt; 1) {\n      activePage = decodeURIComponent(location.hash.slice(1));\n    }\n    navigateTo(activePage);\n  });\n\n  function renderMeta() {\n    if (!META) return;\n    var el = document.getElementById('meta-info');\n    var parts = [];\n    if (META.generatedAt) {\n      parts.push(new Date(META.generatedAt).toLocaleDateString());\n    }\n    if (META.model) parts.push(META.model);\n    if (META.fromCommit) parts.push(META.fromCommit.slice(0, 8));\n    el.textContent = parts.join(' \\u00b7 ');\n  }\n\n  function renderNav() {\n    var container = document.getElementById('nav-tree');\n    var html = '\n';\n    html += 'Overview';\n    html += '';\n    if (TREE.length &gt; 0) {\n      html += '\nModules';\n      html += buildNavTree(TREE);\n    }\n    container.innerHTML = html;\n    container.addEventListener('click', function(e) {\n      var target = e.target;\n      while (target &amp;&amp; !target.dataset.page) { target = target.parentElement; }\n      if (target &amp;&amp; target.dataset.page) {\n        e.preventDefault();\n        navigateTo(target.dataset.page);\n      }\n    });\n  }\n\n  function buildNavTree(nodes) {\n    var html = '';\n    for (var i = 0; i &lt; nodes.length; i++) {\n      var node = nodes[i];\n      html += '\n';\n      html += '' + escH(node.name) + '';\n      if (node.children &amp;&amp; node.children.length &gt; 0) {\n        html += '\n' + buildNavTree(node.children) + '';\n      }\n      html += '';\n    }\n    return html;\n  }\n\n  function escH(s) {\n    var d = document.createElement('div');\n    d.textContent = s;\n    return d.innerHTML;\n  }\n\n  function navigateTo(page) {\n    activePage = page;\n    location.hash = encodeURIComponent(page);\n\n    var items = document.querySelectorAll('.nav-item');\n    for (var i = 0; i &lt; items.length; i++) {\n      if (items[i].dataset.page === page) {\n        items[i].classList.add('active');\n      } else {\n        items[i].classList.remove('active');\n      }\n    }\n\n    var contentEl = document.getElementById('content');\n    var md = PAGES[page];\n\n    if (!md) {\n      contentEl.innerHTML = '\n\nPage not found\n' + escH(page) + '.md does not exist.';\n      return;\n    }\n\n    contentEl.innerHTML = marked.parse(md);\n\n    // Rewrite .md links to hash navigation\n    var links = contentEl.querySelectorAll('a[href]');\n    for (var i = 0; i &lt; links.length; i++) {\n      var href = links[i].getAttribute('href');\n      if (href &amp;&amp; href.endsWith('.md') &amp;&amp; href.indexOf('://') === -1) {\n        var slug = href.replace(/\\.md$/, '');\n        links[i].setAttribute('href', '#' + encodeURIComponent(slug));\n        (function(s) {\n          links[i].addEventListener('click', function(e) {\n            e.preventDefault();\n            navigateTo(s);\n          });\n        })(slug);\n      }\n    }\n\n    // Convert mermaid code blocks into mermaid divs\n    var mermaidBlocks = contentEl.querySelectorAll('pre code.language-mermaid');\n    for (var i = 0; i &lt; mermaidBlocks.length; i++) {\n      var pre = mermaidBlocks[i].parentElement;\n      var div = document.createElement('div');\n      div.className = 'mermaid';\n      div.textContent = mermaidBlocks[i].textContent;\n      pre.parentNode.replaceChild(div, pre);\n    }\n    try { mermaid.run({ querySelector: '.mermaid' }); } catch(e) {}\n\n    window.scrollTo(0, 0);\n    document.getElementById('sidebar').classList.remove('open');\n  }\n})();\n\n\n\n", "creation_timestamp": "2026-05-09T02:43:21.000000Z"}, {"uuid": "62d8d437-f1d2-437c-81a2-d18e0ca88f13", "vulnerability_lookup_origin": "1a89b78e-f703-45f3-bb86-59eb712668bd", "author": "9f56dd64-161d-43a6-b9c3-555944290a09", "vulnerability": "CVE-2024-51999", "type": "seen", "source": "https://gist.github.com/Adcbda/8715cb3a2a149d295bc127dde35f13d6", "content": "\n\n\n\n\nexpress \u2014 Wiki\n\n\n\n\n*{margin:0;padding:0;box-sizing:border-box}\n:root{\n  --bg:#ffffff;--sidebar-bg:#f8f9fb;--border:#e5e7eb;\n  --text:#1e293b;--text-muted:#64748b;--primary:#2563eb;\n  --primary-soft:#eff6ff;--hover:#f1f5f9;--code-bg:#f1f5f9;\n  --radius:8px;--shadow:0 1px 3px rgba(0,0,0,.08);\n}\nbody{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;\n  line-height:1.65;color:var(--text);background:var(--bg)}\n\n.layout{display:flex;min-height:100vh}\n.sidebar{width:280px;background:var(--sidebar-bg);border-right:1px solid var(--border);\n  position:fixed;top:0;left:0;bottom:0;overflow-y:auto;padding:24px 16px;\n  display:flex;flex-direction:column;z-index:10}\n.content{margin-left:280px;flex:1;padding:48px 64px;max-width:960px}\n\n.sidebar-header{margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid var(--border)}\n.sidebar-title{font-size:16px;font-weight:700;color:var(--text);display:flex;align-items:center;gap:8px}\n.sidebar-title svg{flex-shrink:0}\n.sidebar-meta{font-size:11px;color:var(--text-muted);margin-top:6px}\n.nav-section{margin-bottom:2px}\n.nav-item{display:block;padding:7px 12px;border-radius:var(--radius);cursor:pointer;\n  font-size:13px;color:var(--text);text-decoration:none;transition:all .15s;\n  white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.nav-item:hover{background:var(--hover)}\n.nav-item.active{background:var(--primary-soft);color:var(--primary);font-weight:600}\n.nav-item.overview{font-weight:600;margin-bottom:4px}\n.nav-children{padding-left:14px;border-left:1px solid var(--border);margin-left:12px}\n.nav-group-label{font-size:11px;font-weight:600;color:var(--text-muted);\n  text-transform:uppercase;letter-spacing:.5px;padding:12px 12px 4px;user-select:none}\n.sidebar-footer{margin-top:auto;padding-top:16px;border-top:1px solid var(--border);\n  font-size:11px;color:var(--text-muted);text-align:center}\n\n.content h1{font-size:28px;font-weight:700;margin-bottom:8px;line-height:1.3}\n.content h2{font-size:22px;font-weight:600;margin:32px 0 12px;padding-bottom:6px;border-bottom:1px solid var(--border)}\n.content h3{font-size:17px;font-weight:600;margin:24px 0 8px}\n.content h4{font-size:15px;font-weight:600;margin:20px 0 6px}\n.content p{margin:12px 0}\n.content ul,.content ol{margin:12px 0 12px 24px}\n.content li{margin:4px 0}\n.content a{color:var(--primary);text-decoration:none}\n.content a:hover{text-decoration:underline}\n.content blockquote{border-left:3px solid var(--primary);padding:8px 16px;margin:16px 0;\n  background:var(--primary-soft);border-radius:0 var(--radius) var(--radius) 0;\n  color:var(--text-muted);font-size:14px}\n.content code{font-family:'SF Mono',Consolas,'Courier New',monospace;font-size:13px;\n  background:var(--code-bg);padding:2px 6px;border-radius:4px}\n.content pre{background:#1e293b;color:#e2e8f0;border-radius:var(--radius);padding:16px;\n  overflow-x:auto;margin:16px 0}\n.content pre code{background:none;padding:0;font-size:13px;line-height:1.6;color:inherit}\n.content table{border-collapse:collapse;width:100%;margin:16px 0}\n.content th,.content td{border:1px solid var(--border);padding:8px 12px;text-align:left;font-size:14px}\n.content th{background:var(--sidebar-bg);font-weight:600}\n.content img{max-width:100%;border-radius:var(--radius)}\n.content hr{border:none;border-top:1px solid var(--border);margin:32px 0}\n.content .mermaid{margin:20px 0;text-align:center}\n\n.menu-toggle{display:none;position:fixed;top:12px;left:12px;z-index:20;\n  background:var(--bg);border:1px solid var(--border);border-radius:var(--radius);\n  padding:8px 12px;cursor:pointer;font-size:18px;box-shadow:var(--shadow)}\n@media(max-width:768px){\n  .sidebar{transform:translateX(-100%);transition:transform .2s}\n  .sidebar.open{transform:translateX(0);box-shadow:2px 0 12px rgba(0,0,0,.1)}\n  .content{margin-left:0;padding:24px 20px;padding-top:56px}\n  .menu-toggle{display:block}\n}\n.empty-state{text-align:center;padding:80px 20px;color:var(--text-muted)}\n.empty-state h2{font-size:20px;margin-bottom:8px;border:none}\n\n\n\n\n&#9776;\n\n\n\n\n\n\n\n\n\nexpress\n\n\n\n\n\n\n\nGenerated by GitNexus\n\n\n\n\n\nLoading\u2026\n\n\n\nvar PAGES = {\"application-configuration\":\"# Application Configuration\\n\\n# Application Configuration\\n\\nThe `package.json` file serves as the central manifest for the Express web framework, defining project metadata, runtime dependencies, development tooling, and npm scripts. This document describes how the configuration shapes the framework's architecture and developer workflow.\\n\\n## Project Identity\\n\\n| Field | Value | Purpose |\\n|-------|-------|---------|\\n| `name` | `express` | npm package identifier |\\n| `version` | `5.2.1` | Semantic versioning for API stability guarantees |\\n| `description` | \\\"Fast, unopinionated, minimalist web framework\\\" | Core design philosophy communicated to users |\\n| `engines.node` | `&gt;= 18` | Minimum Node.js runtime requirement |\\n\\nThe `keywords` array (`express`, `framework`, `sinatra`, `web`, `http`, `rest`, `restful`, `router`, `app`, `api`) indexes the package in npm search and signals the framework's positioning as a Sinatra-inspired, REST-capable HTTP router.\\n\\n## Dependency Architecture\\n\\nExpress 5.2.1 maintains a lean core through strategic delegation to specialized middleware packages. Dependencies fall into functional groups:\\n\\n### HTTP Protocol Handling\\n\\n| Package | Version | Role in Request/Response Cycle |\\n|---------|---------|-------------------------------|\\n| `accepts` | `^2.0.0` | Content negotiation (`req.accepts()`) |\\n| `content-type` | `^1.0.5` | MIME type parsing and validation |\\n| `encodeurl` | `^2.0.0` | RFC-compliant URL encoding |\\n| `escape-html` | `^1.0.3` | XSS prevention in error pages |\\n| `fresh` | `^2.0.0` | HTTP cache freshness checks |\\n| `parseurl` | `^1.3.3` | URL parsing with caching |\\n| `proxy-addr` | `^2.0.7` | X-Forwarded-For trust evaluation |\\n| `qs` | `^6.14.2` | Query string parsing (`extended` mode) |\\n| `range-parser` | `^1.2.1` | HTTP Range header parsing |\\n| `vary` | `^1.1.2` | Vary header management |\\n\\n### Request Body &amp; Cookies\\n\\n| Package | Version | Integration Point |\\n|---------|---------|-------------------|\\n| `body-parser` | `^2.2.1` | `express.json()`, `express.urlencoded()`, `express.raw()`, `express.text()` |\\n| `cookie` | `^0.7.1` | Cookie serialization (`res.cookie()`) |\\n| `cookie-signature` | `^1.2.1` | Signed cookie integrity (`cookieParser` secret) |\\n\\n### Response Generation\\n\\n| Package | Version | Usage |\\n|---------|---------|-------|\\n| `content-disposition` | `^1.0.0` | `res.attachment()`, `res.download()` |\\n| `etag` | `^1.8.1` | Entity tag generation for conditional requests |\\n| `send` | `^1.1.0` | `res.sendFile()`, static file serving foundation |\\n| `serve-static` | `^2.2.0` | `express.static()` middleware |\\n| `statuses` | `^2.0.1` | HTTP status code lookup and validation |\\n| `finalhandler` | `^2.1.0` | Terminal error handling when no middleware responds |\\n\\n### Routing &amp; Middleware Core\\n\\n| Package | Version | Responsibility |\\n|---------|---------|---------------|\\n| `router` | `^2.2.0` | Express 5's extracted routing engine; handles `app.get()`, `app.use()`, path matching, `Layer` execution, and `next()` propagation |\\n| `merge-descriptors` | `^2.0.0` | Property merging for `app.locals` inheritance and prototype extension |\\n| `on-finished` | `^2.4.1` | Response completion detection for cleanup (logging, resource release) |\\n| `once` | `^1.4.0` | Event handler deduplication in error paths |\\n\\n### Type Negotiation\\n\\n| Package | Version | Function |\\n|---------|---------|----------|\\n| `mime-types` | `^3.0.0` | Content-Type to file extension resolution |\\n| `type-is` | `^2.0.1` | `req.is()` for content-type validation |\\n\\n### Debugging &amp; Diagnostics\\n\\n| Package | Version | Integration |\\n|---------|---------|-------------|\\n| `debug` | `^4.4.0` | Namespaced logging (`express:application`, `express:router`, etc.) |\\n| `depd` | `^2.0.0` | Deprecated API warnings with stack traces |\\n| `http-errors` | `^2.0.0` | `createError()` factory for `next(err)` patterns |\\n\\n## npm Scripts: Developer Workflow\\n\\n```bash\\n# Code quality\\nnpm run lint          # eslint . \u2014 static analysis\\nnpm run lint:fix      # eslint . --fix \u2014 automated fixes\\n\\n# Testing\\nnpm test              # Full test suite with spec reporter\\nnpm run test-tap      # TAP-formatted output for CI parsing\\nnpm run test-cov      # HTML + text coverage reports\\nnpm run test-ci       # LCOV-only coverage for Codecov/Coveralls\\n```\\n\\nThe test command reveals the project structure:\\n\\n```bash\\nmocha --require test/support/env --reporter spec --check-leaks test/ test/acceptance/\\n```\\n\\n- `test/support/env` \u2014 environment bootstrap (likely sets `NODE_ENV=test`, configures `supertest` globals)\\n- `test/` \u2014 unit tests for internal modules\\n- `test/acceptance/` \u2014 integration tests validating end-to-end HTTP behavior\\n\\n## File Distribution\\n\\nThe `files` array controls the npm publish payload:\\n\\n```json\\n[\\\"LICENSE\\\", \\\"Readme.md\\\", \\\"index.js\\\", \\\"lib/\\\"]\\n```\\n\\nOnly the entry point (`index.js`) and `lib/` directory ship to consumers. Examples, benchmarks, and tests are excluded from the production package, reducing install size despite their presence in the repository.\\n\\n## DevDependencies: Ecosystem Compatibility Testing\\n\\nDevelopment dependencies validate Express integration with common middleware patterns without bloating the core:\\n\\n| Package | Test Purpose |\\n|---------|-------------|\\n| `express-session` / `connect-redis` | Session store abstraction |\\n| `cookie-parser` / `cookie-session` | Cookie middleware alternatives |\\n| `ejs` / `hbs` | Template engine integration (`res.render()`) |\\n| `method-override` | HTTP verb tunneling |\\n| `morgan` | HTTP request logging |\\n| `vhost` | Virtual host routing |\\n| `supertest` | HTTP assertion library for tests |\\n| `pbkdf2-password` | Authentication pattern examples |\\n\\nThese packages are not Express dependencies\u2014they are *test subjects* ensuring the framework's extension points remain compatible with the broader ecosystem.\\n\\n## Connection to Runtime Code\\n\\nThe `package.json` configuration directly shapes the implementation in `lib/`:\\n\\n- **`lib/application.js`**: Bootstraps `body-parser`, `serve-static`, and `router` exports via `require()` calls to packages listed in `dependencies`\\n- **`lib/response.js`**: Delegates to `send`, `content-disposition`, `etag`, `encodeurl`, `escape-html`, `statuses`, and `mime-types`\\n- **`lib/request.js`**: Uses `accepts`, `fresh`, `parseurl`, `proxy-addr`, `qs`, `range-parser`, `type-is`\\n- **`lib/express.js`**: Factory function returning `app` instances backed by the `router` package\\n\\nThe `engines` constraint (`&gt;= 18`) permits native use of:\\n- `Readable.fromWeb()` / `Writable.toWeb()` for stream interoperability\\n- `fetch` global (though Express uses `http` module directly)\\n- Native `structuredClone` where applicable\\n\\n## Funding &amp; Governance\\n\\nThe `funding` field points to Open Collective, sustaining maintenance of this dependency graph. The `contributors` list spans the framework's evolution from TJ Holowaychuk's original release through the current Express.js organization stewardship.\",\"authentication-example\":\"# Authentication Example\\n\\n# Authentication Example\\n\\nA complete Express.js application demonstrating session-based user authentication with password hashing. This example implements a minimal but production-pattern login system using PBKDF2 password hashing, server-side sessions, and flash-style messaging.\\n\\n## Purpose\\n\\nThis module serves as a reference implementation for:\\n\\n- Secure password storage using salted hashes (PBKDF2 via `pbkdf2-password`)\\n- Session-based authentication state management\\n- Session fixation protection through regeneration\\n- Flash message patterns for user feedback\\n- Route protection middleware\\n\\n## Architecture Overview\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   Client    \u2502\u2500\u2500\u2500\u2500\u25b6\u2502   Express   \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  Session    \u2502\\n\u2502  (Browser)  \u2502\u25c4\u2500\u2500\u2500\u2500\u2502   Server    \u2502\u25c4\u2500\u2500\u2500\u2500\u2502   Store     \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                           \u2502\\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                    \u2502  In-Memory  \u2502\\n                    \u2502  User \\\"DB\\\"  \u2502\\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## Key Components\\n\\n### Application Setup\\n\\nThe Express application is configured with EJS templating and three layers of middleware:\\n\\n| Middleware | Purpose |\\n|-----------|---------|\\n| `express.urlencoded()` | Parse POST form data |\\n| `express-session` | Server-side session management |\\n| Custom flash middleware | Extract and clear session messages into `res.locals` |\\n\\n```javascript\\napp.use(session({\\n  resave: false,           // Skip save if session unmodified\\n  saveUninitialized: false, // Don't create empty sessions\\n  secret: 'shhhh, very secret'\\n}));\\n```\\n\\n### User Database\\n\\nA plain object simulates persistent storage. On startup, the user `tj` is created with a PBKDF2 hash of password `foobar`:\\n\\n```javascript\\nvar users = {\\n  tj: { name: 'tj' }\\n};\\n\\n// Generate salt and hash asynchronously\\nhash({ password: 'foobar' }, function (err, pass, salt, hash) {\\n  users.tj.salt = salt;\\n  users.tj.hash = hash;\\n});\\n```\\n\\n### Authentication Flow\\n\\n```mermaid\\nsequenceDiagram\\n    participant C as Client\\n    participant S as Express Server\\n    participant D as User DB\\n\\n    C-&gt;&gt;S: POST /login (username, password)\\n    S-&gt;&gt;D: lookup users[name]\\n    alt User not found\\n        S--&gt;&gt;C: redirect /login (error)\\n    else User exists\\n        S-&gt;&gt;S: hash(password, storedSalt)\\n        alt Hash mismatch\\n            S--&gt;&gt;C: redirect /login (error)\\n        else Hash matches\\n            S-&gt;&gt;S: req.session.regenerate()\\n            S-&gt;&gt;S: store user in session\\n            S--&gt;&gt;C: redirect (success)\\n        end\\n    end\\n```\\n\\n### Core Functions\\n\\n#### `authenticate(name, pass, fn)`\\n\\nVerifies credentials against the stored hash. The callback signature is `fn(err, user)` where `user` is `null` on failure.\\n\\n```javascript\\nauthenticate(req.body.username, req.body.password, function(err, user) {\\n  if (user) {\\n    // successful login\\n  } else {\\n    // authentication failed\\n  }\\n});\\n```\\n\\n**Security note**: The function uses timing-safe comparison implicitly through `hash === user.hash`. In production, prefer `crypto.timingSafeEqual()`.\\n\\n#### `restrict(req, res, next)`\\n\\nRoute middleware that enforces authentication. Unauthenticated requests are redirected to `/login` with a flash error message.\\n\\n```javascript\\napp.get('/restricted', restrict, function(req, res) {\\n  // Only reached when req.session.user exists\\n});\\n```\\n\\n### Route Handlers\\n\\n| Route | Method | Middleware | Behavior |\\n|-------|--------|-----------|----------|\\n| `/` | GET | \u2014 | Redirect to `/login` |\\n| `/login` | GET | \u2014 | Render login form |\\n| `/login` | POST | \u2014 | Validate credentials, establish session |\\n| `/restricted` | GET | `restrict` | Protected content |\\n| `/logout` | GET | \u2014 | Destroy session, redirect home |\\n\\n### Session Security Patterns\\n\\n**Session regeneration on login** prevents fixation attacks:\\n\\n```javascript\\nreq.session.regenerate(function() {\\n  req.session.user = user;  // Store in new session ID\\n  // ...\\n});\\n```\\n\\n**Session destruction on logout** ensures complete cleanup:\\n\\n```javascript\\nreq.session.destroy(function(){\\n  res.redirect('/');\\n});\\n```\\n\\n### Flash Message Middleware\\n\\nA custom middleware bridges session-stored messages to template locals:\\n\\n```javascript\\napp.use(function(req, res, next){\\n  var err = req.session.error;\\n  var msg = req.session.success;\\n  delete req.session.error;    // Clear after reading\\n  delete req.session.success;\\n  // Expose to templates via res.locals\\n  res.locals.message = buildMessageHtml(err, msg);\\n  next();\\n});\\n```\\n\\nMessages are consumed once\u2014displayed on the next rendered page, then removed.\\n\\n## Views\\n\\nThe EJS templates use includes for consistent layout:\\n\\n- `head.ejs` \u2014 HTML boilerplate with base styling for `.error` (red) and `.success` (green) classes\\n- `login.ejs` \u2014 Form with `username`/`password` fields and `message` injection point\\n- `foot.ejs` \u2014 Closing tags\\n\\nThe login form submits to `/login` via POST with `application/x-www-form-urlencoded` encoding.\\n\\n## Running the Example\\n\\n```bash\\nnode examples/auth/index.js\\n```\\n\\nServer starts on port 3000 when executed directly (`!module.parent`). Default credentials: **tj** / **foobar**.\\n\\n## Integration Points\\n\\n| Dependency | Usage |\\n|-----------|-------|\\n| `express` | Core framework (loaded via `../..` relative path for in-repo examples) |\\n| `express-session` | Session middleware |\\n| `pbkdf2-password` | PBKDF2 hashing with automatic salt generation |\\n| `node:path` | Cross-platform path resolution for views directory |\\n\\nThe `module.exports = app` pattern allows the application to be imported for testing without starting the server.\",\"content-negotiation-example\":\"# Content Negotiation Example\\n\\n# Content Negotiation Example\\n\\nThis module demonstrates two patterns for handling HTTP content negotiation in Express: inline format handlers within route definitions, and a reusable middleware pattern that delegates to external formatter modules.\\n\\n## Module Purpose\\n\\nContent negotiation allows a single endpoint to serve the same data in different representations based on the client's `Accept` header. This example shows how `res.format()` selects the appropriate handler for `text/html`, `text/plain`, or `application/json` responses.\\n\\n## File Structure\\n\\n| File | Role |\\n|------|------|\\n| `db.js` | In-memory data store with three sample users |\\n| `index.js` | Express application with two route patterns |\\n| `users.js` | External format handlers for the middleware pattern |\\n\\n## Data Layer\\n\\n`db.js` exports a simple array of user objects:\\n\\n```javascript\\nvar users = [];\\nusers.push({ name: 'Tobi' });\\nusers.push({ name: 'Loki' });\\nusers.push({ name: 'Jane' });\\nmodule.exports = users;\\n```\\n\\nThis is imported by both `index.js` and `users.js`.\\n\\n## Pattern 1: Inline Format Handlers\\n\\nThe root route (`GET /`) defines format handlers directly in `res.format()`:\\n\\n```javascript\\napp.get('/', function(req, res){\\n  res.format({\\n    html: function(){\\n      res.send('\n' + users.map(function(user){\\n        return '\n' + user.name + '&lt;\\/li&gt;';\\n      }).join('') + '&lt;\\/ul&gt;');\\n    },\\n    text: function(){\\n      res.send(users.map(function(user){\\n        return ' - ' + user.name + '\\\\n';\\n      }).join(''));\\n    },\\n    json: function(){\\n      res.json(users);\\n    }\\n  });\\n});\\n```\\n\\nExpress inspects the `Accept` header and invokes the matching handler. Default priority follows Express's format ordering when the client accepts multiple types.\\n\\n## Pattern 2: Middleware Abstraction\\n\\nThe `/users` route demonstrates extracting format logic into a reusable `format()` middleware factory:\\n\\n```javascript\\nfunction format(path) {\\n  var obj = require(path);\\n  return function(req, res){\\n    res.format(obj);\\n  };\\n}\\n\\napp.get('/users', format('./users'));\\n```\\n\\nThe `format()` function:\\n1. Requires a module at the given `path`\\n2. Expects that module to export handlers keyed by format name (`html`, `text`, `json`)\\n3. Returns an Express middleware that calls `res.format()` with those handlers\\n\\n## External Format Module\\n\\n`users.js` exports the same three handlers as named properties, making the format logic testable and reusable across routes:\\n\\n```javascript\\nvar users = require('./db');\\n\\nexports.html = function(req, res){ /* ... */ };\\nexports.text = function(req, res){ /* ... */ };\\nexports.json = function(req, res){ /* ... */ };\\n```\\n\\nThis separation allows multiple routes to share format definitions without duplication.\\n\\n## Architecture\\n\\n```mermaid\\nflowchart LR\\n    A[Client Request] --&gt; B{Accept Header}\\n    B --&gt;|text/html| C[html handler]\\n    B --&gt;|text/plain| D[text handler]\\n    B --&gt;|application/json| E[json handler]\\n    \\n    C --&gt; F[res.send]\\n    D --&gt; F\\n    E --&gt; G[res.json]\\n    \\n    C &amp; D &amp; E --&gt; H[users array from db.js]\\n    \\n    style A fill:#f9f,stroke:#333\\n    style H fill:#bbf,stroke:#333\\n```\\n\\n## Server Bootstrap\\n\\nThe application starts only when run directly (not when required as a module):\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\nThis pattern enables the file to serve as both a standalone application and a testable module export.\\n\\n## Integration with Express\\n\\nThis example requires Express via a relative path (`../../`), indicating it lives within the Express repository's `examples/` directory. The `app` is exported as `module.exports`, allowing test files to mount or inspect it without starting the server.\",\"cookie-sessions-example\":\"# Cookie Sessions Example\\n\\n# Cookie Sessions Example\\n\\n## Overview\\n\\nThis module demonstrates a minimal Express application that uses signed cookie-based sessions to persist per-user state across requests. It increments and displays a view counter that survives browser refreshes without server-side session storage.\\n\\n## Architecture\\n\\n```mermaid\\nflowchart LR\\n    A[Client Request] --&gt; B[cookie-session middleware]\\n    B --&gt; C[Session data in signed cookie]\\n    C --&gt; D[Route handlerincrements count]\\n    D --&gt; E[Response withupdated cookie]\\n```\\n\\n## Dependencies\\n\\n| Module | Source | Purpose |\\n|--------|--------|---------|\\n| `cookie-session` | npm | Parses and signs session cookies; exposes `req.session` |\\n| `express` | `../../` (local) | Web framework |\\n\\n## Configuration\\n\\n### Session Middleware\\n\\n```javascript\\napp.use(cookieSession({ secret: 'manny is cool' }));\\n```\\n\\n| Option | Value | Behavior |\\n|--------|-------|----------|\\n| `secret` | `'manny is cool'` | Signs cookies to prevent tampering; **must be changed in production** |\\n\\nThe `cookie-session` middleware:\\n- Reads the session cookie from `req.headers.cookie`\\n- Verifies the signature using `secret`\\n- Populates `req.session` with the deserialized cookie payload (or `{}` if absent/malformed)\\n- Serializes and re-signs `req.session` to `Set-Cookie` on response end\\n\\n## Route Handler\\n\\n### `GET /`\\n\\n```javascript\\napp.get('/', function (req, res) {\\n  req.session.count = (req.session.count || 0) + 1\\n  res.send('viewed ' + req.session.count + ' times\\\\n')\\n})\\n```\\n\\n| Step | Action |\\n|------|--------|\\n| Read | Retrieves `req.session.count` (undefined on first visit) |\\n| Update | Increments counter, storing back to `req.session` |\\n| Persist | `cookie-session` automatically serializes to signed cookie |\\n| Respond | Returns plain text with current count |\\n\\n## Session Data Flow\\n\\n```\\nFirst Request          Subsequent Request\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500          \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\\n\\nNo cookie sent    \u2192    Cookie: session=eyJjb3VudCI6MX0=...\\n                     \u2193\\n                     Verify signature\\n                     \u2193\\nreq.session = {}     \u2192    req.session = { count: 1 }\\n     \u2193                         \u2193\\nreq.session.count = 1      req.session.count = 2\\n     \u2193                         \u2193\\nSet-Cookie: session=...    Set-Cookie: session=...\\n```\\n\\n## Security Considerations\\n\\n| Concern | Mitigation Required |\\n|---------|---------------------|\\n| Secret exposure | Replace hardcoded secret; use environment variable |\\n| Cookie size | Session data limited to ~4KB; large data needs server-side storage |\\n| No expiration set | Add `maxAge` or `expires` to limit window of compromise |\\n| No `httpOnly`/`secure` | Add for production to prevent XSS theft and ensure HTTPS-only transmission |\\n\\n## Running the Example\\n\\n```bash\\n# From repository root\\nnode examples/cookie-sessions/index.js\\n# Express started on port 3000\\n\\n# Test with curl\\ncurl -c cookies.txt -b cookies.txt http://localhost:3000/\\n# viewed 1 times\\ncurl -c cookies.txt -b cookies.txt http://localhost:3000/\\n# viewed 2 times\\n```\\n\\n## Integration with Express\\n\\nThis example uses the local Express build (`../../` relative to `examples/cookie-sessions/`) rather than a published npm version. The `module.parent` guard allows the file to be both:\\n\\n- **Required as module**: `var app = require('./examples/cookie-sessions')` (skips `listen()`)\\n- **Run directly**: `node examples/cookie-sessions/index.js` (starts server on port 3000)\\n\\n## Key API References\\n\\n- [`cookie-session`](https://github.com/expressjs/cookie-session): Middleware documentation\\n- [`res.send()`](../../lib/response.js): Response body method (called via `test/Router.js` in test environment per call graph)\",\"cookies-example\":\"# Cookies Example\\n\\n# Cookies Example\\n\\nAn Express.js application demonstrating cookie-based session persistence using signed cookies, form handling, and conditional response rendering.\\n\\n## Overview\\n\\nThis example implements a \\\"remember me\\\" feature that persists user preference across browser sessions via HTTP cookies. It showcases three core Express patterns: middleware composition for request processing, cookie signing for tamper detection, and form-based state transitions with POST-redirect-GET flow.\\n\\n## Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   HTTP Request  \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  cookie-parser  \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  urlencoded()   \u2502\\n\u2502                 \u2502     \u2502  (signed cookies)\u2502     \u2502  (form parsing) \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                                        \u2502\\n                              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                              \u25bc\\n                       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                       \u2502  Route Handler  \u2502\\n                       \u2502  (GET /, POST /,\u2502\\n                       \u2502   GET /forget)  \u2502\\n                       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                              \u2502\\n                              \u25bc\\n                       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                       \u2502  Cookie Set/    \u2502\\n                       \u2502  Clear + Redirect\u2502\\n                       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## Middleware Stack\\n\\nThe application configures middleware in a specific order, with each layer transforming the request object:\\n\\n| Order | Middleware | Purpose | Condition |\\n|-------|-----------|---------|-----------|\\n| 1 | `morgan` | Request logging | Skipped in `test` environment |\\n| 2 | `cookieParser('my secret here')` | Parse &amp; verify signed cookies | Always |\\n| 3 | `express.urlencoded()` | Parse form submissions | Always |\\n\\nThe cookie parser secret (`'my secret here'`) enables `req.signedCookies` verification. Cookies signed with this secret can be detected if tampered with by clients.\\n\\n## Routes\\n\\n### `GET /`\\n\\nRenders one of two states based on cookie presence:\\n\\n- **Cookie present (`req.cookies.remember`)**: Displays confirmation message with link to `/forget`\\n- **No cookie**: Renders checkbox form for opting into \\\"remember me\\\"\\n\\n```javascript\\n// Cookie check uses the unsigned cookies object\\nif (req.cookies.remember) {  // Note: not req.signedCookies\\n  // ...\\n}\\n```\\n\\n**Note**: The implementation checks `req.cookies` rather than `req.signedCookies`, meaning it does not verify the cookie signature on read. The cookie is still signed on write (via `res.cookie`).\\n\\n### `POST /`\\n\\nProcesses form submission from the root page:\\n\\n```javascript\\nvar minute = 60000;\\n\\nif (req.body &amp;&amp; req.body.remember) {\\n  res.cookie('remember', 1, { maxAge: minute })\\n}\\nres.redirect(req.get('Referrer') || '/');\\n```\\n\\nSets cookie with:\\n- **Name**: `remember`\\n- **Value**: `1`\\n- **maxAge**: 60,000ms (1 minute)\\n\\nThe redirect implements POST-redirect-GET pattern to prevent form resubmission on refresh.\\n\\n### `GET /forget`\\n\\nClears the `remember` cookie and redirects back:\\n\\n```javascript\\nres.clearCookie('remember');\\nres.redirect(req.get('Referrer') || '/');\\n```\\n\\nUses `Referrer` header to maintain navigation context; falls back to root path.\\n\\n## Cookie Lifecycle\\n\\n```mermaid\\nstateDiagram-v2\\n    [*] --&gt; Form: GET / (no cookie)\\n    Form --&gt; Remembered: POST / (checked)\\n    Remembered --&gt; Remembered: GET / (cookie valid)\\n    Remembered --&gt; Form: GET /forget\\n    Form --&gt; Form: POST / (unchecked)\\n```\\n\\n## Environment Handling\\n\\nThe module uses `process.env.NODE_ENV` to conditionally disable logging during test execution. This pattern allows test suites to run without console noise while preserving observability in development and production.\\n\\nThe `module.parent` check enables both direct execution and programmatic import:\\n\\n```javascript\\n// Direct: node examples/cookies/index.js\\n// \u2192 Server starts on port 3000\\n\\n// Programmatic: require('./examples/cookies')\\n// \u2192 Returns app instance without binding to port\\n```\\n\\n## Integration Points\\n\\n| External Module | Version Context | Role |\\n|-----------------|-----------------|------|\\n| `express` | `../../` (local) | Framework \u2014 provides `app`, routing, middleware |\\n| `morgan` | npm dependency | HTTP request logging |\\n| `cookie-parser` | npm dependency | Cookie parsing and signature verification |\\n\\nThe `../../` require path for Express indicates this example runs from within the Express repository itself, not against a published npm version.\\n\\n## Security Considerations\\n\\n- Cookie secret is hardcoded (`'my secret here'`) \u2014 production applications should use environment variables\\n- `maxAge` of 1 minute is intentionally short for demonstration; real \\\"remember me\\\" features typically use longer durations with additional safeguards\\n- The cookie value `1` is a simple flag; sensitive data should not be stored client-side even with signing\",\"core-framework\":\"# Core Framework\\n\\n# Core Framework\\n\\nThe Core Framework module is the heart of Express, responsible for application instantiation, request/response pipeline orchestration, and the HTTP server abstraction. It wires together routing, middleware, view rendering, and the enhanced request/response prototypes that define Express's programming model.\\n\\n## Module Structure\\n\\n| File | Responsibility |\\n|------|-------------|\\n| `lib/express.js` | Factory function and module exports |\\n| `lib/application.js` | App prototype: configuration, routing delegation, server lifecycle |\\n| `lib/request.js` | Enhanced `http.IncomingMessage` prototype |\\n| `lib/response.js` | Enhanced `http.ServerResponse` prototype |\\n| `lib/view.js` | Template engine resolution and rendering |\\n| `lib/utils.js` | Shared utilities: ETag generation, query parsing, trust proxy compilation |\\n\\n## Application Factory (`lib/express.js`)\\n\\n`createApplication()` produces a function object that acts as both a request handler and an application instance. It merges in `EventEmitter` behavior and the `app` prototype, then creates isolated request/response prototypes with a back-reference to the app.\\n\\n```javascript\\nvar app = function(req, res, next) {\\n  app.handle(req, res, next);\\n};\\n```\\n\\nThe factory exposes constructors and bundled middleware at the module level:\\n\\n```javascript\\nexports.json = bodyParser.json;\\nexports.static = require('serve-static');\\n// ... etc\\n```\\n\\n## Application Prototype (`lib/application.js`)\\n\\n### Initialization\\n\\n`app.init()` sets up the default configuration and lazily instantiates the router. The `router` property uses a getter so that `new Router()` is deferred until first access\u2014typically when `app.use()` or `app.handle()` is called.\\n\\n```javascript\\nObject.defineProperty(this, 'router', {\\n  get: function getrouter() {\\n    if (router === null) {\\n      router = new Router({\\n        caseSensitive: this.enabled('case sensitive routing'),\\n        strict: this.enabled('strict routing')\\n      });\\n    }\\n    return router;\\n  }\\n});\\n```\\n\\n### Configuration System\\n\\nSettings are stored in `app.settings`, a plain object that supports inheritance through prototype chaining when apps are mounted. `app.set()` triggers side effects for three special keys:\\n\\n| Setting | Compiled Function |\\n|---------|-----------------|\\n| `etag` | `compileETag(val)` \u2192 stored as `etag fn` |\\n| `query parser` | `compileQueryParser(val)` \u2192 stored as `query parser fn` |\\n| `trust proxy` | `compileTrust(val)` \u2192 stored as `trust proxy fn` |\\n\\nThe `trust proxy` setting includes backward-compatibility logic: a symbol `@@symbol:trust_proxy_default` tracks whether the value was explicitly set or inherited from a parent app.\\n\\n### Request Dispatch (`app.handle`)\\n\\nWhen a request arrives, `app.handle` performs setup before delegating to the router:\\n\\n1. Creates `finalhandler` fallback if no callback provided\\n2. Sets `X-Powered-By` header if enabled\\n3. Establishes `req.res` and `res.req` circular references\\n4. Swaps prototypes: `req.__proto__ = this.request`, `res.__proto__ = this.response`\\n5. Initializes `res.locals`\\n6. Calls `this.router.handle(req, res, done)`\\n\\n### Mounting Sub-Applications (`app.use`)\\n\\n`app.use` distinguishes between plain middleware and mounted Express apps. When an app is mounted:\\n\\n```javascript\\nfn.mountpath = path;\\nfn.parent = this;\\n\\nrouter.use(path, function mounted_app(req, res, next) {\\n  var orig = req.app;\\n  fn.handle(req, res, function (err) {\\n    Object.setPrototypeOf(req, orig.request);\\n    Object.setPrototypeOf(res, orig.response);\\n    next(err);\\n  });\\n});\\n\\nfn.emit('mount', this);\\n```\\n\\nThe prototype restoration ensures that after leaving the sub-app, `req` and `res` revert to the parent app's enhanced prototypes.\\n\\n### Route Registration\\n\\nHTTP methods are dynamically attached by iterating `utils.methods` (derived from `http.METHODS`). The `get` method is special-cased: one argument means `app.get(setting)` (retrieve config), two or more means `app.get(path, ...handlers)` (define route).\\n\\n```javascript\\napp.get = function (path) {\\n  if (arguments.length === 1) {\\n    return this.set(path);  // getter\\n  }\\n  var route = this.route(path);\\n  route.get.apply(route, slice.call(arguments, 1));\\n  return this;\\n};\\n```\\n\\n## Request Prototype (`lib/request.js`)\\n\\nBuilt on `http.IncomingMessage.prototype`, the request object adds Express-specific getters via `defineGetter`:\\n\\n| Property | Implementation |\\n|----------|---------------|\\n| `req.query` | Parsed via `query parser fn`, cached by `parseurl` |\\n| `req.protocol` | `https` if encrypted, else checks `X-Forwarded-Proto` |\\n| `req.secure` | `this.protocol === 'https'` |\\n| `req.ip` | `proxyaddr(this, trust)` \u2014 client IP through trusted proxies |\\n| `req.ips` | Array of proxy addresses (reversed, socket addr removed) |\\n| `req.subdomains` | Host parts before domain, controlled by `subdomain offset` |\\n| `req.path` | `url.parse(this.url).pathname` |\\n| `req.host` / `req.hostname` | Host header with `X-Forwarded-Host` proxy support |\\n| `req.fresh` / `req.stale` | Cache validation via `fresh` module |\\n| `req.xhr` | Checks `X-Requested-With: xmlhttprequest` |\\n\\nContent negotiation delegates to the `accepts` module:\\n\\n```javascript\\nreq.accepts = function() {\\n  var accept = accepts(this);\\n  return accept.types.apply(accept, arguments);\\n};\\n```\\n\\n## Response Prototype (`lib/response.js`)\\n\\nBuilt on `http.ServerResponse.prototype`, handling content generation, header manipulation, and stream-based file transfer.\\n\\n### Content Serialization (`res.send`)\\n\\n`res.send` performs type-based dispatch:\\n\\n```\\nstring  \u2192 HTML (unless Content-Type already set)\\nnumber  \u2192 pass to res.json (deprecated path, actually handled as object)\\nboolean \u2192 pass to res.json\\nobject  \u2192 pass to res.json\\nnull    \u2192 empty body\\nBuffer/ArrayBufferView \u2192 binary\\n```\\n\\nETag generation is conditional on `etag fn` being configured and no existing `ETag` header. For 204/304 responses, content headers are stripped.\\n\\n### JSON and JSONP\\n\\n`res.json` serializes with `JSON.stringify`, respecting `json replacer` and `json spaces` settings. `res.jsonp` additionally checks `req.query[app.get('jsonp callback name')]` for a callback function name, sanitizing it and wrapping the response in a function invocation with a `/**/` prefix to mitigate Rosetta Flash attacks.\\n\\n### File Transfer (`res.sendFile` / `res.download`)\\n\\n`res.sendFile` delegates to the `send` module, creating a readable stream piped to the response. The `sendfile` helper manages lifecycle events:\\n\\n```javascript\\nfunction sendfile(res, file, options, callback) {\\n  file.on('directory', ondirectory);\\n  file.on('error', onerror);\\n  file.on('end', onend);\\n  onFinished(res, onfinish);  // detects premature client disconnect\\n  file.pipe(res);\\n}\\n```\\n\\n`res.download` sets `Content-Disposition: attachment` before calling `res.sendFile`.\\n\\n### Cookies\\n\\n`res.cookie` serializes values with optional signing and JSON encoding:\\n\\n```javascript\\nvar val = typeof value === 'object'\\n  ? 'j:' + JSON.stringify(value)\\n  : String(value);\\n\\nif (signed) {\\n  val = 's:' + sign(val, secret);\\n}\\n```\\n\\n`res.clearCookie` forces expiration by setting `expires: new Date(1)`.\\n\\n## View System (`lib/view.js`)\\n\\n`View` resolves template paths and normalizes engine loading. Engine functions are cached in `app.engines` and must conform to `(path, options, callback)` signature.\\n\\nResolution order for `view.lookup('foo')`:\\n\\n1. `/foo.`\\n2. `/foo/index.`\\n\\nEngines are auto-required by extension if not pre-registered:\\n\\n```javascript\\nvar fn = require(mod).__express;\\nif (typeof fn !== 'function') {\\n  throw new Error('Module \\\"' + mod + '\\\" does not provide a view engine.');\\n}\\n```\\n\\nRendering forces async callbacks via `process.nextTick` if the engine calls back synchronously.\\n\\n## Utilities (`lib/utils.js`)\\n\\n| Export | Purpose |\\n|--------|---------|\\n| `methods` | Lowercased `http.METHODS` array |\\n| `compileETag(val)` | Converts `true/'weak'/'strong'/false/function` to ETag function |\\n| `compileQueryParser(val)` | Converts `true/'simple'/'extended'/false/function` to parser |\\n| `compileTrust(val)` | Converts boolean/number/string/array/function to proxy trust function |\\n| `normalizeType(type)` | Resolves extension to MIME type with parameters |\\n| `setCharset(type, charset)` | Injects charset into Content-Type via `content-type` module |\\n\\nETag generation uses `etag` module with pre-bound options:\\n\\n```javascript\\nfunction createETagGenerator(options) {\\n  return function generateETag(body, encoding) {\\n    var buf = !Buffer.isBuffer(body)\\n      ? Buffer.from(body, encoding)\\n      : body;\\n    return etag(buf, options);\\n  };\\n}\\n```\\n\\n## Architecture Diagram\\n\\n```mermaid\\nflowchart LR\\n    A[http.createServer] --&gt;|req, res| B(app.handle)\\n    B --&gt; C[Prototype Swap]\\n    C --&gt; D[router.handle]\\n    D --&gt; E[Middleware Stack]\\n    E --&gt; F[Route Handlers]\\n    E --&gt; G[Mounted Apps]\\n    G --&gt;|fn.handle| B\\n    \\n    subgraph \\\"Request Enhancement\\\"\\n    C --&gt; H[req: IncomingMessage + request.js]\\n    C --&gt; I[res: ServerResponse + response.js]\\n    end\\n    \\n    subgraph \\\"View System\\\"\\n    F --&gt; J[app.render]\\n    J --&gt; K[View.lookup]\\n    K --&gt; L[engine(path, opts, cb)]\\n    end\\n```\\n\\n## Key Integration Points\\n\\n- **Router**: `app.router` is a `Router` instance from the separate `router` package. All routing methods (`use`, `route`, `param`, VERB methods) proxy to it.\\n- **Body Parser / Serve-Static**: Re-exported from `express.js` as convenience properties; not internally used by core.\\n- **Finalhandler**: Provides default error response when no error-handling middleware catches an exception.\\n- **Merge-Descriptors**: Used once at app creation to mix `EventEmitter` and `app` prototype onto the function object.\",\"downloads-example\":\"# Downloads Example\\n\\n# Downloads Example\\n\\nAn Express application demonstrating secure file downloads with path traversal protection and custom error handling for missing files.\\n\\n## Overview\\n\\nThis example showcases `res.download()` with a virtual path prefix. Files are stored in a dedicated `files/` directory and served through a wildcard route that strips the `/files/` prefix before resolving paths on disk.\\n\\n## Route Structure\\n\\n| Route | Handler | Purpose |\\n|-------|---------|---------|\\n| `GET /` | Inline function | Serves an HTML index with download links |\\n| `GET /files/*file` | Inline function | Handles file downloads with error recovery |\\n\\n## File Resolution\\n\\nThe application uses `req.params.file` as an array of path segments captured by the wildcard `*file` parameter. These segments are joined with `/` to form the relative file path passed to `res.download()`.\\n\\n```javascript\\nres.download(req.params.file.join('/'), { root: FILES_DIR }, callback)\\n```\\n\\nThe `root` option constrains file access to `FILES_DIR`, preventing directory traversal attacks even if a request contains `../` segments.\\n\\n## Error Handling Strategy\\n\\nThe download callback implements a two-tier error response:\\n\\n```javascript\\nfunction (err) {\\n  if (!err) return;                    // Success \u2014 file transmitted\\n  if (err.status !== 404) return next(err);  // Server error \u2014 propagate to Express error handler\\n  res.statusCode = 404;                 // Not found \u2014 custom friendly response\\n  res.send('Cant find that file, sorry!');\\n}\\n```\\n\\nNon-404 errors (permission denied, disk I/O failures) are passed to `next(err)` for the default Express error middleware to handle.\\n\\n## Test Files\\n\\nThe `files/` directory contains sample content demonstrating various filename scenarios:\\n\\n| File | Purpose |\\n|------|---------|\\n| `amazing.txt` | Basic ASCII filename |\\n| `notes/groceries.txt` | Nested directory path |\\n| `CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt` | Unicode filename (URL-encoded in requests) |\\n| *(missing)* | `missing.txt` intentionally absent to trigger 404 handling |\\n\\n## Connection to Express Core\\n\\nThis example depends on Express's `res.download()` implementation, which internally delegates to `send()` (from the `send` module, referenced in `test/Router.js`). The `root` option leverages Express's path resolution and security checks before streaming the file response.\\n\\n## Running the Example\\n\\n```bash\\nnode examples/downloads/index.js\\n```\\n\\nThe server binds to port 3000 when executed directly (`!module.parent`), or exports the app instance for testing/embedding.\",\"ejs-templating-example\":\"# EJS Templating Example\\n\\n# EJS Templating Example\\n\\nThis example demonstrates how to configure Express to use the EJS (Embedded JavaScript) templating engine with HTML file extensions instead of the default `.ejs` extension. It renders a user list page using partial templates for modular view composition.\\n\\n## Purpose\\n\\nThe module serves as a reference implementation for:\\n\\n- Registering a template engine under a custom file extension\\n- Using EJS includes for reusable view partials (`header.html`, `footer.html`)\\n- Serving static assets alongside dynamic views\\n- Passing local variables from route handlers to templates\\n\\n## Application Setup\\n\\n### Engine Registration\\n\\n```javascript\\napp.engine('.html', require('ejs').__express);\\n```\\n\\nBy default, Express looks for engines that match file extensions. EJS exposes `__express` as its standard hook into Express's view system. This line registers EJS to handle `.html` files, allowing templates to use the more neutral `.html` extension rather than `.ejs`.\\n\\n### View Configuration\\n\\n```javascript\\napp.set('views', path.join(__dirname, 'views'));\\napp.set('view engine', 'html');\\n```\\n\\n| Setting | Purpose |\\n|---------|---------|\\n| `views` | Absolute path to the directory containing template files |\\n| `view engine` | Default extension to append when `res.render()` is called without one |\\n\\nWith `view engine` set to `html`, `res.render('users')` resolves to `views/users.html`.\\n\\n### Static Files\\n\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\n\\nServes the `public/` directory at the root URL path. The stylesheet at `public/stylesheets/style.css` becomes available at `/stylesheets/style.css`.\\n\\n## Route Handler\\n\\n```javascript\\napp.get('/', function(req, res){\\n  res.render('users', {\\n    users: users,\\n    title: \\\"EJS example\\\",\\n    header: \\\"Some users\\\"\\n  });\\n});\\n```\\n\\nThe single route renders `users.html` with three local variables:\\n\\n- `users` \u2014 array of user objects consumed by the `forEach` loop\\n- `title` \u2014 inserted into the `` element via `&lt;%= title %&gt;`\\n- `header` \u2014 passed but unused in the current template (available for future use)\\n\\n## Template Architecture\\n\\n### `users.html` (Main Template)\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502  &lt;%- include('header.html') -%&gt;     \u2502\\n\u2502                                     \u2502\\n\u2502  \nUsers&lt;\\/h1&gt;                     \u2502\\n\u2502  \n                    \u2502\\n\u2502    &lt;% users.forEach(...) %&gt;         \u2502\\n\u2502  &lt;\\/ul&gt;                              \u2502\\n\u2502                                     \u2502\\n\u2502  &lt;%- include('footer.html') -%&gt;     \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\nUses **unescaped include tags** (`&lt;%- ... -%&gt;`) to prevent EJS from double-escaping the HTML partials. The `-%&gt;` syntax trims trailing whitespace.\\n\\n### `header.html`\\n\\n- Outputs HTML5 doctype and `` structure\\n- References `&lt;%= title %&gt;` for dynamic page title\\n- Links to `/stylesheets/style.css` (served by `express.static`)\\n\\n### `footer.html`\\n\\nCloses the `` and `` tags opened in `header.html`.\\n\\n## EJS Tag Reference\\n\\n| Tag | Purpose | Example in Module |\\n|-----|---------|-------------------|\\n| `&lt;%= expr %&gt;` | Escaped output | `&lt;%= user.name %&gt;`, `&lt;%= title %&gt;` |\\n| `&lt;%- expr %&gt;` | Unescaped output | `&lt;%- include('header.html') -%&gt;` |\\n| `&lt;% code %&gt;` | Control flow (no output) | `&lt;% users.forEach(...) %&gt;` |\\n\\n## Request Flow\\n\\n```mermaid\\nflowchart LR\\n    A[GET /] --&gt; B[Route Handler]\\n    B --&gt; C[res.render('users')]\\n    C --&gt; D[Express View System]\\n    D --&gt; E[Load users.html]\\n    E --&gt; F[Include header.html]\\n    E --&gt; G[Include footer.html]\\n    F &amp; G --&gt; H[Render HTML Response]\\n    H --&gt; I[Send to Client]\\n```\\n\\n## File Structure\\n\\n```\\nexamples/ejs/\\n\u251c\u2500\u2500 index.js                    # Application entry point\\n\u251c\u2500\u2500 public/\\n\u2502   \u2514\u2500\u2500 stylesheets/\\n\u2502       \u2514\u2500\u2500 style.css           # Static stylesheet\\n\u2514\u2500\u2500 views/\\n    \u251c\u2500\u2500 header.html             # Opening HTML structure\\n    \u251c\u2500\u2500 footer.html             # Closing HTML structure\\n    \u2514\u2500\u2500 users.html              # Main template with user list\\n```\\n\\n## Running the Example\\n\\n```bash\\nnode examples/ejs/index.js\\n```\\n\\nThe server starts on port 3000 when executed directly (`!module.parent`). Access the application at `http://localhost:3000/`.\\n\\nThe `module.exports = app` pattern allows the application to be imported for testing without starting the server.\",\"error-handling-examples\":\"# Error Handling Examples\\n\\n# Error Handling Examples\\n\\nTwo reference implementations demonstrating Express error handling patterns: basic synchronous and asynchronous error capture, and content-negotiated custom error pages with environment-aware verbosity.\\n\\n---\\n\\n## `examples/error/` \u2014 Basic Error Handling\\n\\nA minimal Express application showing how errors propagate to error-handling middleware.\\n\\n### Key Pattern: Error-Handling Middleware Signature\\n\\nError-handling middleware in Express is distinguished by **arity of 4** \u2014 the `(err, req, res, next)` signature. Without the `err` parameter, Express treats it as regular middleware and it will not receive errors.\\n\\n```javascript\\nfunction error(err, req, res, next) {   // \u2190 4 parameters required\\n  if (!test) console.error(err.stack);\\n  res.status(500);\\n  res.send('Internal Server Error');\\n}\\n```\\n\\n### Error Propagation Mechanisms\\n\\n| Mechanism | Source | Trigger |\\n|-----------|--------|---------|\\n| `throw` | `app.get('/')` | Synchronous error in route handler |\\n| `next(err)` | `app.get('/next')` | Asynchronous error via callback |\\n\\nThe `/next` route demonstrates that `next(err)` works inside async operations (simulated with `process.nextTick()`). In production code, this pattern applies to database queries, HTTP requests, or any async I/O.\\n\\n```javascript\\napp.get('/next', function(req, res, next){\\n  process.nextTick(function(){\\n    next(new Error('oh no!'));   // passes error to error-handling middleware\\n  });\\n});\\n```\\n\\n### Critical Ordering Rule\\n\\nError-handling middleware **must be registered after routes**. The example places `app.use(error)` after all `app.get()` calls. If registered before routes, it would never receive errors from those routes.\\n\\n---\\n\\n## `examples/error-pages/` \u2014 Custom Error Pages with Content Negotiation\\n\\nA more sophisticated example showing status-specific error pages, format negotiation, and environment-conditional error detail.\\n\\n### Architecture Overview\\n\\n```mermaid\\ngraph TD\\n    A[Request] --&gt; B{Route matches?}\\n    B --&gt;|Yes| C[Route handler]\\n    B --&gt;|No| D[404 Handler]\\n    C --&gt;|next() without response| D\\n    C --&gt;|next(err)| E[Error Handler]\\n    C --&gt;|next(err with status)| E\\n    D --&gt;|res.format| F[HTML / JSON / Text]\\n    E --&gt;|res.render| G[500.ejs with conditional stack trace]\\n```\\n\\n### Environment-Aware Verbosity\\n\\nThe application uses Express's `settings` system to control error detail exposure:\\n\\n```javascript\\napp.enable('verbose errors');                    // default: on\\nif (app.settings.env === 'production') {\\n  app.disable('verbose errors');                 // production: off\\n}\\n```\\n\\nThis setting is consumed in `views/500.ejs`:\\n\\n```ejs\\n&lt;% if (settings['verbose errors']) { %&gt;\\n  \n&lt;%= error.stack %&gt;&lt;\\/pre&gt;\\n&lt;% } else { %&gt;\\n  \nAn error occurred!&lt;\\/p&gt;\\n&lt;% } %&gt;\\n```\\n\\n### Trigger Routes\\n\\n| Route | Behavior | Result |\\n|-------|----------|--------|\\n| `GET /` | Renders landing page | `200` with `index.ejs` |\\n| `GET /404` | Calls `next()` without responding | Falls through to 404 handler |\\n| `GET /403` | Creates error with `err.status = 403` | 403 error page |\\n| `GET /500` | Calls `next(new Error(...))` | 500 error page |\\n\\n### Content Negotiation for 404s\\n\\nThe 404 handler uses `res.format()` to respond differently based on `Accept` header:\\n\\n```javascript\\nres.format({\\n  html: function () {\\n    res.render('404', { url: req.url })\\n  },\\n  json: function () {\\n    res.json({ error: 'Not found' })\\n  },\\n  default: function () {\\n    res.type('txt').send('Not found')\\n  }\\n})\\n```\\n\\nThis produces:\\n- `curl http://localhost:3000/notfound` \u2192 HTML page\\n- `curl ... -H \\\"Accept: application/json\\\"` \u2192 `{\\\"error\\\":\\\"Not found\\\"}`\\n- `curl ... -H \\\"Accept: text/plain\\\"` \u2192 `Not found`\\n\\n### Error Handler with Status Preservation\\n\\nThe final error-handling middleware preserves HTTP status codes set on error objects:\\n\\n```javascript\\napp.use(function(err, req, res, next){\\n  res.status(err.status || 500);   // respects err.status, defaults to 500\\n  res.render('500', { error: err });\\n});\\n```\\n\\nThis allows the `/403` route to display a 403 page rather than a generic 500.\\n\\n---\\n\\n## View Templates\\n\\n### `error_header.ejs` / `footer.ejs`\\nShared wrapper providing HTML boilerplate. Included by `404.ejs` and `500.ejs`.\\n\\n### `404.ejs`\\n```ejs\\n&lt;%- include('error_header') -%&gt;\\n\nCannot find &lt;%= url %&gt;&lt;\\/h2&gt;\\n&lt;%- include('footer') -%&gt;\\n```\\n\\n### `500.ejs`\\nConditionally renders stack trace based on `settings['verbose errors']`. Receives the full `error` object from the error-handling middleware.\\n\\n---\\n\\n## Integration with Express Core\\n\\nBoth examples use `require('../../')` to load the local Express source (not npm-installed express), making them part of the Express test/development workflow. They serve as:\\n\\n- **Integration tests**: Verified by the test suite (note `/* istanbul ignore next */` guards on `app.listen()` blocks)\\n- **Documentation**: Working code demonstrating canonical patterns\\n- **Regression checks**: Ensure error propagation behavior remains stable across versions\\n\\nThe `error-pages` example connects to broader Express patterns through `res.format()` (shared with `examples/content-negotiation/`) and `res.json()` (core response method).\",\"hello-world-example\":\"# Hello World Example\\n\\n# Hello World Example\\n\\n## Overview\\n\\nThe Hello World example is the minimal Express application demonstrating the framework's core routing and response APIs. It initializes an Express instance, registers a single root route handler, and conditionally starts an HTTP server based on whether the module is executed directly or required by another module.\\n\\n## Module Structure\\n\\n```javascript\\nvar express = require('../../');\\nvar app = module.exports = express()\\n```\\n\\nThe module exports the Express `app` instance directly, making it available for testing or composition by other modules. The `module.parent` check enables dual-use: direct execution runs a server on port 3000, while `require()` simply returns the configured app without binding to a port.\\n\\n## Request Handling Flow\\n\\n```mermaid\\nflowchart LR\\n    A[HTTP GET /] --&gt; B[Express Router]\\n    B --&gt; C[Route Handler]\\n    C --&gt; D[\\\"res.send('Hello World')\\\"]\\n    D --&gt; E[HTTP Response]\\n```\\n\\n## Route Configuration\\n\\n| Property | Value |\\n|----------|-------|\\n| Method | `GET` |\\n| Path | `/` |\\n| Handler | Inline function |\\n| Response | Plain text `\\\"Hello World\\\"` |\\n\\nThe handler uses `res.send()`, which delegates through Express's response pipeline to finalize the HTTP response with automatic content-type detection (`text/html` for string payloads).\\n\\n## Server Lifecycle\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\n| Condition | Behavior |\\n|-----------|----------|\\n| `module.parent` is falsy | Module executed directly (`node index.js`); server binds to port 3000 |\\n| `module.parent` is truthy | Module required by another file; no server started, `app` exported for external control |\\n\\nThe `/* istanbul ignore next */` comment excludes this block from code coverage instrumentation, as the conditional branch requiring direct execution is not exercised during typical test suite runs where the module is imported.\\n\\n## Integration Points\\n\\n| Element | Connects To |\\n|---------|-------------|\\n| `require('../../')` | Resolves to the Express package entry point at `examples/../index.js` |\\n| `res.send()` | Invokes Express's response sending logic (referenced in test/Router.js call graph) |\\n| `module.exports` | Consumed by test suites or parent modules for app-level testing |\\n\\n## Usage Patterns\\n\\n**Direct execution:**\\n```bash\\nnode examples/hello-world/index.js\\n# Express started on port 3000\\n# Server responds with \\\"Hello World\\\" at http://localhost:3000/\\n```\\n\\n**Programmatic use:**\\n```javascript\\nvar app = require('./examples/hello-world');\\n// app is a configured Express instance, ready for .listen() or mounting\\n```\",\"markdown-example\":\"# Markdown Example\\n\\n# Markdown Example\\n\\nAn Express application demonstrating custom view engine integration for rendering Markdown templates with variable interpolation.\\n\\n## Overview\\n\\nThis module creates a minimal Express server that registers `.md` files as first-class view templates. It uses the `marked` library to parse Markdown into HTML and implements a lightweight token replacement system for dynamic content injection.\\n\\n## Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   HTTP Request  \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  Express Router \u2502\u2500\u2500\u2500\u2500\u25b6\u2502   res.render()  \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                                        \u2502\\n                              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                              \u25bc\\n                       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                       \u2502  Custom 'md'    \u2502\\n                       \u2502  View Engine    \u2502\\n                       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                              \u2502\\n              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n              \u25bc               \u25bc               \u25bc\\n         \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n         \u2502 fs.read \u2502\u2500\u2500\u2500\u25b6\u2502 marked.  \u2502\u2500\u2500\u2500\u25b6\u2502 {token}  \u2502\\n         \u2502  File   \u2502    \u2502  parse() \u2502    \u2502 replace  \u2502\\n         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## Custom View Engine\\n\\nThe core of this example is the `md` engine registered with `app.engine()`:\\n\\n```javascript\\napp.engine('md', function(path, options, fn){\\n  fs.readFile(path, 'utf8', function(err, str){\\n    if (err) return fn(err);\\n    var html = marked.parse(str).replace(/\\\\{([^}]+)\\\\}/g, function(_, name){\\n      return escapeHtml(options[name] || '');\\n    });\\n    fn(null, html);\\n  });\\n});\\n```\\n\\n| Step | Description |\\n|------|-------------|\\n| File Read | Asynchronously reads the template file as UTF-8 |\\n| Parse | Converts Markdown to HTML via `marked.parse()` |\\n| Interpolate | Replaces `{token}` patterns with escaped values from `options` |\\n| Callback | Returns rendered HTML or error via Express's `fn(err, html)` convention |\\n\\n### Variable Interpolation Syntax\\n\\nTemplates use curly-brace tokens that map to `options` properties passed to `res.render()`:\\n\\n```markdown\\n# {title}\\n```\\n\\nThe replacement applies `escapeHtml()` to prevent XSS attacks, falling back to empty string for undefined keys.\\n\\n## Application Configuration\\n\\n```javascript\\napp.set('views', path.join(__dirname, 'views'));   // Template lookup directory\\napp.set('view engine', 'md');                       // Default extension, omit .md in render calls\\n```\\n\\nSetting `view engine` to `md` allows `res.render('index')` instead of `res.render('index.md')`.\\n\\n## Routes\\n\\n| Route | Handler | Purpose |\\n|-------|---------|---------|\\n| `GET /` | `res.render('index', { title: 'Markdown Example' })` | Renders main example page |\\n| `GET /fail` | `res.render('missing', { title: 'Markdown Example' })` | Demonstrates error handling (missing template) |\\n\\n## Template Example\\n\\n**`views/index.md`**\\n```markdown\\n# {title}\\n\\nJust an example view rendered with _markdown_.\\n```\\n\\nRenders to:\\n```html\\n\nMarkdown Example&lt;\\/h1&gt;\\n\nJust an example view rendered with markdown&lt;\\/em&gt;.&lt;\\/p&gt;\\n```\\n\\n## Server Bootstrap\\n\\nThe module uses a conditional listen pattern for testability:\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\nWhen `module.parent` is defined (e.g., required by test files), the server does not bind to a port. The `app` instance is exported for external testing or mounting.\\n\\n## Dependencies\\n\\n| Module | Usage |\\n|--------|-------|\\n| `escape-html` | Sanitizes interpolated values |\\n| `express` | Web framework (relative path `../..`) |\\n| `marked` | Markdown-to-HTML parser |\\n| `node:fs` | Template file I/O |\\n| `node:path` | Cross-platform path resolution |\\n\\n## Key Integration Points\\n\\n- **Express view system**: The `app.engine()` and `app.set()` calls plug into Express's `View` class resolution logic\\n- **Error propagation**: Async errors from `fs.readFile` flow through the `fn(err)` callback to Express's default error handler\\n- **Module exports**: `module.exports = app` enables testing and composition with larger applications\",\"multi-router-example\":\"# Multi-Router Example\\n\\n# Multi-Router Example\\n\\nAn Express.js application demonstrating how to compose multiple `Router` instances with versioned API prefixes.\\n\\n## Purpose\\n\\nThis example shows the standard pattern for organizing route handlers into separate modules and mounting them at distinct URL paths. It implements two API versions (`v1` and `v2`) with identical endpoint structures, illustrating how Express applications scale from monolithic route files to modular, mountable routers.\\n\\n## Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   api_v1.js     \u2502     \u2502   api_v2.js     \u2502\\n\u2502  /api/v1/*      \u2502     \u2502  /api/v2/*      \u2502\\n\u2502  \u2022 GET /        \u2502     \u2502  \u2022 GET /        \u2502\\n\u2502  \u2022 GET /users   \u2502     \u2502  \u2022 GET /users   \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n         \u2502                       \u2502\\n         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                     \u25bc\\n            \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n            \u2502    index.js     \u2502\\n            \u2502  Mounts routers \u2502\u2500\u2500\u2500\u2500\u25ba Root handler: GET /\\n            \u2502  at path prefix \u2502\\n            \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## Entry Point: `index.js`\\n\\nThe main application file creates the Express instance, mounts the API routers, and defines a root-level fallback route.\\n\\n```javascript\\nvar app = module.exports = express();\\n\\napp.use('/api/v1', require('./controllers/api_v1'));\\napp.use('/api/v2', require('./controllers/api_v2'));\\n\\napp.get('/', function(req, res) {\\n  res.send('Hello from root route.')\\n});\\n```\\n\\n### Key behaviors\\n\\n| Aspect | Implementation |\\n|--------|---------------|\\n| **Router mounting** | `app.use(path, router)` attaches each API version at its URL prefix |\\n| **Module exports** | `module.exports = app` allows the application to be imported for testing without starting the server |\\n| **Conditional listen** | Server only starts if `!module.parent` \u2014 prevents port conflicts when the module is required by test suites |\\n\\n## API Version Routers\\n\\nBoth `api_v1.js` and `api_v2.js` follow an identical structure, creating isolated `Router` instances with their own route definitions.\\n\\n### `api_v1.js`\\n\\n```javascript\\nvar apiv1 = express.Router();\\n\\napiv1.get('/', function(req, res) {\\n  res.send('Hello from APIv1 root route.');\\n});\\n\\napiv1.get('/users', function(req, res) {\\n  res.send('List of APIv1 users.');\\n});\\n\\nmodule.exports = apiv1;\\n```\\n\\n### `api_v2.js`\\n\\n```javascript\\nvar apiv2 = express.Router();\\n\\napiv2.get('/', function(req, res) {\\n  res.send('Hello from APIv2 root route.');\\n});\\n\\napiv2.get('/users', function(req, res) {\\n  res.send('List of APIv2 users.');\\n});\\n\\nmodule.exports = apiv2;\\n```\\n\\n### Router isolation\\n\\nEach file creates its own `express.Router()` rather than mutating a shared instance. This ensures:\\n\\n- Routes remain namespaced to their version prefix\\n- Middleware applied to one router does not affect the other\\n- Controllers can be tested independently by requiring them directly\\n\\n## Request Routing Flow\\n\\nWhen a request arrives, Express matches the URL path against mounted routers in registration order:\\n\\n```\\nGET /api/v1/users\\n    \u2502\\n    \u25bc\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502  Does path start with /api/v1?      \u2502\u25c4\u2500\u2500 First mount point checked\\n\u2502  Yes \u2192 Strip prefix, pass to        \u2502\\n\u2502        api_v1 router                \u2502\\n\u2502        \u2514\u2500\u25ba Matches /users handler   \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\\nGET /api/v2/\\n    \u2502\\n    \u25bc\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502  Does path start with /api/v1?      \u2502\u25c4\u2500\u2500 No match, continue\\n\u2502  Does path start with /api/v2?      \u2502\u25c4\u2500\u2500 Match found\\n\u2502  Yes \u2192 Strip prefix, pass to        \u2502\\n\u2502        api_v2 router                \u2502\\n\u2502        \u2514\u2500\u25ba Matches / handler        \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## URL Map\\n\\n| Request | Handler | Response |\\n|---------|---------|----------|\\n| `GET /` | `index.js` | `\\\"Hello from root route.\\\"` |\\n| `GET /api/v1` | `api_v1.js` \u2192 `/` | `\\\"Hello from APIv1 root route.\\\"` |\\n| `GET /api/v1/users` | `api_v1.js` \u2192 `/users` | `\\\"List of APIv1 users.\\\"` |\\n| `GET /api/v2` | `api_v2.js` \u2192 `/` | `\\\"Hello from APIv2 root route.\\\"` |\\n| `GET /api/v2/users` | `api_v2.js` \u2192 `/users` | `\\\"List of APIv2 users.\\\"` |\\n\\n## Integration with Express\\n\\nThe example uses the local Express build (`require('../..')` / `require('../../..')`) rather than a npm-installed package. This pattern appears throughout the `examples/` directory and ensures examples run against the current working tree during development.\\n\\nThe `send` calls referenced in the call graph resolve to Express's `res.send` implementation (internally tested via `test/Router.js`), not a custom function within this module.\",\"mvc-example\":\"# MVC Example\\n\\n# MVC Example Module\\n\\nA complete Express.js application demonstrating a convention-based Model-View-Controller architecture with automatic route generation, nested resources, and per-controller view engine configuration.\\n\\n## Overview\\n\\nThis module implements a full-stack web application managing **Users** and their **Pets**. It showcases Express patterns including: programmatic route mounting via filesystem conventions, controller-level middleware (`before` hooks), method override for RESTful semantics, flash messaging through sessions, and mixed template engines (EJS and Handlebars) within the same application.\\n\\nThe application uses an in-memory faux database (`db.js`) with seeded data for three users and four pets.\\n\\n## Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   HTTP Request  \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  Express    \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  Sub-App Router \u2502\\n\u2502                 \u2502     \u2502   (index)   \u2502     \u2502  (boot.js)      \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                                   \u2502\\n                              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                              \u25bc                    \u25bc                    \u25bc\\n                         \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                         \u2502  main   \u2502        \u2502   user   \u2502         \u2502   pet    \u2502\\n                         \u2502 (index) \u2502        \u2502 (router) \u2502         \u2502 (router) \u2502\\n                         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518        \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                                   \u2502                    \u2502\\n                              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                    \u2502\\n                              \u25bc                                         \u25bc\\n                         \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                            \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                         \u2502user-pet  \u2502                            \u2502  Views   \u2502\\n                         \u2502(nested)  \u2502                            \u2502(ejs/hbs) \u2502\\n                         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                            \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## Entry Point: `index.js`\\n\\nThe main application file configures Express and delegates controller loading to `lib/boot.js`.\\n\\n### Key Configurations\\n\\n| Setting | Value | Purpose |\\n|---------|-------|---------|\\n| `view engine` | `ejs` | Default template engine |\\n| `views` | `./views` | Global error page templates (404, 5xx) |\\n\\n### Custom Response Method\\n\\n```javascript\\napp.response.message = function(msg){\\n  var sess = this.req.session;\\n  sess.messages = sess.messages || [];\\n  sess.messages.push(msg);\\n  return this;\\n};\\n```\\n\\nStores flash messages in the session. Consumed by the middleware below and exposed to views as `res.locals.messages` / `res.locals.hasMessages`.\\n\\n### Middleware Stack (in order)\\n\\n1. **`morgan`** \u2014 HTTP request logging (development only)\\n2. **`express.static`** \u2014 Serves `public/` directory\\n3. **`express-session`** \u2014 Session management with `resave: false`, `saveUninitialized: false`\\n4. **`express.urlencoded`** \u2014 Parses form bodies into `req.body`\\n5. **`methodOverride('_method')`** \u2014 Allows `POST` with `?_method=put` to act as `PUT`\\n6. **Flash message middleware** \u2014 Moves session messages to `res.locals`, then clears them\\n7. **Controller sub-apps** \u2014 Loaded via `require('./lib/boot')(app, options)`\\n8. **Error handler** \u2014 Renders `5xx.ejs` for uncaught errors\\n9. **404 handler** \u2014 Renders `404.ejs` when no route matches\\n\\n## Auto-Route Generation: `lib/boot.js`\\n\\nScans `controllers/` directories and mounts each as an isolated Express sub-app with convention-derived routes.\\n\\n### Convention Mapping\\n\\n| Export Name | HTTP Method | URL Pattern | Example (for `pet` controller) |\\n|-------------|-------------|-------------|-------------------------------|\\n| `index` | `GET` | `/` | `GET /` |\\n| `list` | `GET` | `/{name}s` | `GET /pets` |\\n| `show` | `GET` | `/{name}/:{name}_id` | `GET /pet/:pet_id` |\\n| `edit` | `GET` | `/{name}/:{name}_id/edit` | `GET /pet/:pet_id/edit` |\\n| `update` | `PUT` | `/{name}/:{name}_id` | `PUT /pet/:pet_id` |\\n| `create` | `POST` | `/{name}` | `POST /pet` |\\n\\n### Controller Metadata Exports\\n\\n| Export | Type | Purpose |\\n|--------|------|---------|\\n| `name` | `string` | Overrides directory name for URL generation |\\n| `prefix` | `string` | Prepends path to all routes (for nesting) |\\n| `engine` | `string` | Sets sub-app's view engine (e.g., `'hbs'`, `'ejs'`) |\\n| `before` | `function(req, res, next)` | Middleware run before matched routes |\\n\\nThe `before` export receives special treatment: when present, routes are registered as `app[method](url, obj.before, handler)` instead of `app[method](url, handler)`.\\n\\n### View Resolution\\n\\nEach sub-app gets its own `views` directory pointing to `controllers/{name}/views/`, enabling colocated templates.\\n\\n## Controllers\\n\\n### `main/index.js`\\n\\nSimple redirect controller. No database dependency.\\n\\n```javascript\\nexports.index = function(req, res){\\n  res.redirect('/users');\\n};\\n```\\n\\n**Route:** `GET /` \u2192 redirects to `/users`\\n\\n### `user/index.js`\\n\\nFull CRUD controller for users with async simulation in `before` hook.\\n\\n```javascript\\nexports.engine = 'hbs';           // Uses Handlebars templates\\nexports.before = function(req, res, next){\\n  var id = req.params.user_id;\\n  if (!id) return next();         // Skip for list route (no :user_id)\\n  process.nextTick(function(){    // Simulate async DB query\\n    req.user = db.users[id];\\n    if (!req.user) return next('route'); // Skip to next matching route\\n    next();\\n  });\\n};\\n```\\n\\n| Export | Route | Template |\\n|--------|-------|----------|\\n| `list` | `GET /users` | `list.hbs` |\\n| `show` | `GET /user/:user_id` | `show.hbs` |\\n| `edit` | `GET /user/:user_id/edit` | `edit.hbs` |\\n| `update` | `PUT /user/:user_id` | redirect to `show` |\\n\\nThe `show.hbs` template displays flash messages via `{{#if hasMessages}}` and lists the user's pets with links to individual pet pages.\\n\\n### `pet/index.js`\\n\\nPet controller using EJS (inherits default, but explicitly sets `engine: 'ejs'`).\\n\\n```javascript\\nexports.before = function(req, res, next){\\n  var pet = db.pets[req.params.pet_id];\\n  if (!pet) return next('route');  // 404-style skip\\n  req.pet = pet;\\n  next();\\n};\\n```\\n\\n| Export | Route | Template |\\n|--------|-------|----------|\\n| `show` | `GET /pet/:pet_id` | `show.ejs` |\\n| `edit` | `GET /pet/:pet_id/edit` | `edit.ejs` |\\n| `update` | `PUT /pet/:pet_id` | redirect to `show` |\\n\\nThe `edit.ejs` form uses `?_method=put` to trigger `PUT` via method override:\\n\\n```html\\n\n?_method=put\\\" method=\\\"post\\\"&gt;\\n```\\n\\n### `user-pet/index.js`\\n\\nNested resource controller creating pets through a user.\\n\\n```javascript\\nexports.name = 'pet';                    // Uses 'pet' in URL generation\\nexports.prefix = '/user/:user_id';       // All routes prefixed with user path\\n\\nexports.create = function(req, res, next){\\n  var id = req.params.user_id;\\n  var user = db.users[id];\\n  if (!user) return next('route');\\n  var pet = { name: req.body.pet.name };\\n  pet.id = db.pets.push(pet) - 1;        // Auto-increment ID via array length\\n  user.pets.push(pet);                    // Associate with user\\n  res.message('Added pet ' + req.body.pet.name);\\n  res.redirect('/user/' + id);\\n};\\n```\\n\\n**Generated route:** `POST /user/:user_id/pet`\\n\\nThis demonstrates how `name` and `prefix` combine: the `create` export normally generates `POST /pet`, but with `prefix: '/user/:user_id'` becomes `POST /user/:user_id/pet`.\\n\\n## Data Layer: `db.js`\\n\\nIn-memory arrays with bidirectional object references (pets exist in both `db.pets` and embedded in `user.pets`).\\n\\n```javascript\\n// Seeded data structure\\npets = [{ name: 'Tobi', id: 0 }, ...]   // 4 pets\\nusers = [\\n  { name: 'TJ', pets: [pets[0], pets[1], pets[2]], id: 0 },\\n  { name: 'Guillermo', pets: [pets[3]], id: 1 },\\n  { name: 'Nathan', pets: [], id: 2 }\\n]\\n```\\n\\n**Note:** No persistence. Restarting the server resets all data.\\n\\n## View Templates\\n\\n| Template | Engine | Purpose |\\n|----------|--------|---------|\\n| `controllers/user/views/list.hbs` | Handlebars | User directory |\\n| `controllers/user/views/show.hbs` | Handlebars | User profile with pets |\\n| `controllers/user/views/edit.hbs` | Handlebars | Edit user + add pet form |\\n| `controllers/pet/views/show.ejs` | EJS | Pet profile |\\n| `controllers/pet/views/edit.ejs` | EJS | Edit pet name |\\n| `views/404.ejs` | EJS | Global not found |\\n| `views/5xx.ejs` | EJS | Global server error |\\n\\nThe `edit.hbs` template contains **two forms**: one for updating the user (`PUT /user/:id`) and one for creating a pet (`POST /user/:id/pet`), demonstrating the nested resource pattern in the UI.\\n\\n## Request Flow Example\\n\\n```\\nGET /user/0/edit\\n  \u2502\\n  \u25bc\\nboot.js mounts user sub-app at root\\n  \u2502\\n  \u25bc\\nuser.before() \u2500\u2500process.nextTick()\u2500\u2500\u25b6 req.user = db.users[0]\\n  \u2502\\n  \u25bc\\nuser.edit() \u2500\u2500\u25b6 res.render('edit', { user: req.user })\\n  \u2502\\n  \u25bc\\nedit.hbs renders with {{user.name}}, forms for user update + pet creation\\n```\\n\\n```\\nPOST /user/0/pet (from \\\"Add Pet\\\" form in edit.hbs)\\n  \u2502\\n  \u25bc\\nmethodOverride sees no ?_method, stays POST\\n  \u2502\\n  \u25bc\\nboot.js routes to user-pet.create (prefix match: /user/:user_id/pet)\\n  \u2502\\n  \u25bc\\nuser-pet.create() \u2500\u2500\u25b6 creates pet, pushes to db.pets and user.pets\\n                      res.message('Added pet ...')\\n                      redirect /user/0\\n  \u2502\\n  \u25bc\\nGET /user/0\\n  \u2502\\n  \u25bc\\nuser.before() \u2500\u2500\u25b6 req.user = db.users[0] (now with new pet)\\n  \u2502\\n  \u25bc\\nuser.show() \u2500\u2500\u25b6 show.hbs renders with {{#each user.pets}}\\n                flash message appears via {{#if hasMessages}}\\n```\\n\\n## Extension Points\\n\\nTo add a new controller:\\n\\n1. Create directory under `controllers/{name}/`\\n2. Add `index.js` with route exports (`list`, `show`, `create`, etc.)\\n3. Optionally add `views/` subdirectory with templates matching the configured engine\\n4. Optionally export `name`, `prefix`, `engine`, or `before` for customization\\n\\nThe boot system automatically picks up the directory on next application start\u2014no route registration changes needed in `index.js`.\",\"online-example\":\"# Online Example\\n\\n# Online Example\\n\\nAn Express application demonstrating real-time user activity tracking using Redis-backed presence detection. This example shows how to integrate the `online` module with Express middleware to track active users and display recently seen visitors.\\n\\n## Purpose\\n\\nThis module serves as a runnable example that demonstrates:\\n\\n- Integrating Express with Redis for stateful session tracking\\n- Using middleware for fire-and-forget activity logging\\n- Querying time-bucketed presence data with the `online` module\\n- Rendering dynamic HTML from stored identifiers\\n\\n## Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     middleware      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   Client    \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba \u2502 Express \u2502 \u2500\u2500\u25ba \u2502   online    \u2502\\n\u2502   Request   \u2502   (UA string)       \u2502  (app)  \u2502     \u2502  (Redis)    \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                         \u2502\\n                                         \u25bc\\n                                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                                    \u2502   GET   \u2502\\n                                    \u2502    /    \u2502 \u25c4\u2500\u2500 Query last 5\\n                                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     active users\\n```\\n\\n## Dependencies\\n\\n| Module | Purpose |\\n|--------|---------|\\n| `express` | Web framework (loaded from parent directory via `../..`) |\\n| `online` | Presence tracking library with Redis backend |\\n| `redis` | Redis client for Node.js |\\n\\n## Components\\n\\n### Redis Client Setup\\n\\n```javascript\\nvar db = redis.createClient();\\nonline = online(db);\\n```\\n\\nCreates a Redis connection and initializes the `online` instance with that connection. The `online` module uses Redis sorted sets or similar structures to maintain time-bucketed presence data.\\n\\n### Activity Tracking Middleware\\n\\n```javascript\\napp.use(function(req, res, next){\\n  online.add(req.headers['user-agent']);\\n  next();\\n});\\n```\\n\\nFire-and-forget middleware that records each request's `User-Agent` header as an activity identifier. In production applications, this would typically use `req.user.id` or a session identifier instead.\\n\\n**Important characteristics:**\\n- Calls `next()` immediately without waiting for Redis operation\\n- Does not block request processing\\n- Uses `user-agent` string for demonstration purposes only (not unique per user in practice)\\n\\n### List Helper\\n\\n```javascript\\nfunction list(ids) {\\n  return '\n' + ids.map(function(id){\\n    return '\n' + id + '&lt;\\/li&gt;';\\n  }).join('') + '&lt;\\/ul&gt;';\\n}\\n```\\n\\nTransforms an array of identifiers into an HTML unordered list. Pure function with no side effects.\\n\\n### Route Handler\\n\\n```javascript\\napp.get('/', function(req, res, next){\\n  online.last(5, function(err, ids){\\n    if (err) return next(err);\\n    res.send('\nUsers online: ' + ids.length + '&lt;\\/p&gt;' + list(ids));\\n  });\\n});\\n```\\n\\nQueries the `online` module for the 5 most recently active identifiers and renders a count with the full list.\\n\\n## API Surface\\n\\n| Method | Description |\\n|--------|-------------|\\n| `online.add(id)` | Records activity for a given identifier (fire-and-forget) |\\n| `online.last(n, callback)` | Retrieves `n` most recently active identifiers |\\n\\n## Execution Flow\\n\\n```mermaid\\nsequenceDiagram\\n    participant C as Client\\n    participant E as Express\\n    participant M as Middleware\\n    participant O as online/Redis\\n    participant R as Route /\\n\\n    C-&gt;&gt;E: GET /\\n    E-&gt;&gt;M: app.use middleware\\n    M-&gt;&gt;O: online.add(ua-string)\\n    M--&gt;&gt;E: next() (immediate)\\n    E-&gt;&gt;R: match GET /\\n    R-&gt;&gt;O: online.last(5, cb)\\n    O--&gt;&gt;R: ids array\\n    R-&gt;&gt;E: res.send(html)\\n    E--&gt;&gt;C: HTML response\\n```\\n\\n## Running the Example\\n\\nPrerequisites and startup:\\n\\n```bash\\n# Install Redis: https://redis.io/\\nnpm install redis online\\nredis-server\\n\\n# From project root\\nnode examples/online/index.js\\n# Express started on port 3000\\n```\\n\\n## Connection to Codebase\\n\\nThis module is located in `examples/online/` and depends on the parent directory's Express installation via `require('../..')`. It is not imported by any other module in the codebase (no incoming calls). The `send` reference in call graph data indicates Express's `res.send` method usage.\\n\\n## Notes for Contributors\\n\\n- The `user-agent` tracking is illustrative; real applications should use authenticated user identifiers\\n- Error handling follows Express convention: `if (err) return next(err)`\\n- The `/* istanbul ignore next */` comment excludes the listen block from test coverage\\n- Module uses `var` consistently (pre-ES6 style matching the codebase's era)\",\"other-acceptance\":\"# Other \u2014 acceptance\\n\\n# Acceptance Test Suite\\n\\nEnd-to-end HTTP acceptance tests for Express.js example applications. This suite validates complete request/response cycles using Supertest to ensure each example behaves correctly as a deployed web service.\\n\\n## Purpose\\n\\nThese tests serve as integration verification for the `examples/` directory. Each test file corresponds to a specific example application, exercising its routes, middleware, and edge cases through actual HTTP requests against a running app instance. Unlike unit tests, these validate the full stack including routing, middleware execution, response rendering, and header handling.\\n\\n## Test Structure\\n\\nAll tests follow a consistent pattern:\\n\\n```javascript\\nvar app = require('../../examples/')\\nvar request = require('supertest')\\n\\ndescribe('', function () {\\n  describe(' ', function () {\\n    it('', function (done) {\\n      request(app)\\n        .()\\n        .\\n        .end(done)\\n    })\\n  })\\n})\\n```\\n\\nThe `app` export from each example is a configured Express application instance that Supertest binds to an ephemeral port for the duration of the test.\\n\\n## Example Coverage\\n\\n| Test File | Example App | Key Behaviors Tested |\\n|-----------|-------------|----------------------|\\n| `auth.js` | `examples/auth` | Session-based authentication, login/logout flow, protected routes |\\n| `content-negotiation.js` | `examples/content-negotiation` | `Accept` header parsing, format switching (HTML/Plain/JSON) |\\n| `cookie-sessions.js` | `examples/cookie-sessions` | Client-side session cookie incrementing view counter |\\n| `cookies.js` | `examples/cookies` | Cookie setting, reading, and clearing via form submission |\\n| `downloads.js` | `examples/downloads` | File serving with `Content-Disposition`, path traversal protection |\\n| `ejs.js` | `examples/ejs` | EJS template rendering with HTML escaping |\\n| `error-pages.js` | `examples/error-pages` | Error response formatting by content type |\\n| `error.js` | `examples/error` | Synchronous and asynchronous error handling |\\n| `hello-world.js` | `examples/hello-world` | Basic response, 404 handling |\\n| `markdown.js` | `examples/markdown` | Markdown-to-HTML rendering, error propagation |\\n| `multi-router.js` | `examples/multi-router` | Mounting sub-routers at versioned paths |\\n| `mvc.js` | `examples/mvc` | Full CRUD: redirect, read, update, nested resource creation |\\n| `params.js` | `examples/params` | Route parameter parsing, custom parameter validation |\\n| `resource.js` | `examples/resource` | RESTful resource routing, range queries, format suffixes |\\n| `route-map.js` | `examples/route-map` | Declarative route mapping, nested resource paths |\\n| `route-separation.js` | `examples/route-separation` | Route-handler separation pattern, method override |\\n| `vhost.js` | `examples/vhost` | Virtual host routing by `Host` header |\\n| `web-service.js` | `examples/web-service` | API key authentication, JSON API responses, 404 handling |\\n\\n## Common Testing Patterns\\n\\n### Cookie-Based Session Testing\\n\\nTests that verify authenticated flows extract and replay cookies across requests:\\n\\n```javascript\\n// auth.js \u2014 single cookie extraction\\nfunction getCookie(res) {\\n  return res.headers['set-cookie'][0].split(';')[0];\\n}\\n\\n// Usage: login, capture cookie, access protected route\\nrequest(app)\\n  .post('/login')\\n  .send('username=tj&amp;password=foobar')\\n  .expect(302, function(err, res){\\n    request(app)\\n      .get('/restricted')\\n      .set('Cookie', getCookie(res))  // Replay session\\n      .expect(200, done)\\n  })\\n```\\n\\n```javascript\\n// cookie-sessions.js \u2014 multiple cookie joining\\nfunction getCookies(res) {\\n  return res.headers['set-cookie'].map(function (val) {\\n    return val.split(';')[0]\\n  }).join('; ');\\n}\\n```\\n\\n### Negative Header Assertions\\n\\nThe `cookies.js` test imports `shouldNotHaveHeader` from `../support/utils` to verify headers are *absent*:\\n\\n```javascript\\nvar utils = require('../support/utils');\\n\\n// Ensure no Set-Cookie header when form submitted without remember checkbox\\n.expect(utils.shouldNotHaveHeader('Set-Cookie'))\\n```\\n\\n### Multi-Step Flow Verification\\n\\nSeveral tests chain requests to verify state changes persist:\\n\\n```javascript\\n// mvc.js \u2014 PUT then GET to confirm update\\nrequest(app)\\n  .put('/user/1')\\n  .send({ user: { name: 'Tobo' }})\\n  .expect(302, function (err, res) {\\n    request(app)\\n      .get('/user/1/edit')\\n      .expect(200, /Tobo/, done)  // Verify rendered with new name\\n  })\\n```\\n\\n### Content Negotiation Testing\\n\\nThe `error-pages.js` test demonstrates running identical routes with different `Accept` headers to verify format-specific responses:\\n\\n```javascript\\ndescribe('Accept: text/html', function(){ /* ... */ })\\ndescribe('Accept: application/json', function(){ /* ... */ })\\ndescribe('Accept: text/plain', function(){ /* ... */ })\\n```\\n\\n## Shared Utilities\\n\\n| Utility | Location | Purpose |\\n|---------|----------|---------|\\n| `getCookie(res)` | `auth.js` (local) | Extract first cookie value from response |\\n| `getCookies(res)` | `cookie-sessions.js` (local) | Join all cookie values for session replay |\\n| `shouldNotHaveHeader(name)` | `../support/utils` | Assertion helper for absent headers |\\n\\n## Integration with Test Framework\\n\\nThese tests rely on the project's Mocha configuration and Supertest's `.expect()` chaining. The `done` callback signals async completion. Nested `describe` blocks organize tests by route and condition, producing readable output:\\n\\n```\\n  auth\\n    GET /\\n      \u2713 should redirect to /login\\n    GET /login\\n      \u2713 should render login form\\n      \u2713 should display login error for bad user\\n      ...\\n```\\n\\n## Adding New Acceptance Tests\\n\\nWhen contributing a new example to `examples/`, add a corresponding test file here:\\n\\n1. Require the example app: `var app = require('../../examples/')`\\n2. Import `supertest`: `var request = require('supertest')`\\n3. Structure with `describe` blocks matching URL hierarchy\\n4. Use `.expect(status)` for status codes, `.expect(body)` for response content\\n5. For cookie flows, copy `getCookie` pattern from `auth.js`\\n6. For header absence checks, import `shouldNotHaveHeader` from `../support/utils`\\n\\nEnsure tests cover: happy path, expected errors, and any stateful interactions (cookies, sessions, updates).\",\"other-examples\":\"# Other \u2014 examples\\n\\n# Express Examples\\n\\nThe `examples/` directory contains a curated collection of runnable Express.js applications demonstrating idiomatic patterns, common use cases, and integration techniques. These serve as both learning materials for developers new to Express and as canonical references for implementing specific features.\\n\\n## Purpose\\n\\nThe examples fulfill three roles:\\n\\n1. **Learning path** \u2014 Progressive complexity from basic \\\"hello-world\\\" to multi-layered applications (MVC, web services)\\n2. **Pattern reference** \u2014 Demonstrating Express-specific concepts: middleware composition, routing strategies, view rendering, error handling\\n3. **Integration guide** \u2014 Showing how Express connects with external packages (Redis, EJS, session stores, virtual hosts)\\n\\nEach example is self-contained with its own `package.json` and can be run independently.\\n\\n## Example Categories\\n\\n### Foundational Patterns\\n\\n| Example | Focus Area | Key Express Concepts |\\n|---------|-----------|-------------------|\\n| `hello-world` | Basic HTTP server | `app.get()`, `app.listen()` |\\n| `static-files` | Asset serving | `express.static()` middleware |\\n| `error` | Error handling | Error-handling middleware signature `(err, req, res, next)` |\\n| `error-pages` | Custom error responses | Status-code based rendering |\\n\\n### Routing Architecture\\n\\n| Example | Focus Area | Key Express Concepts |\\n|---------|-----------|-------------------|\\n| `route-separation` | Resource-based organization | Modular route files per domain entity |\\n| `route-map` | Declarative route definitions | Programmatic route registration from data structures |\\n| `multi-router` | Router composition | `express.Router()` instances with distinct prefixes |\\n| `route-middleware` | Per-route middleware stacks | Middleware arrays in route definitions |\\n| `params` | Parameter processing | `app.param()` for route parameter validation/transform |\\n\\n### Request/Response Handling\\n\\n| Example | Focus Area | Key Express Concepts |\\n|---------|-----------|-------------------|\\n| `content-negotiation` | Format selection | `req.accepts()`, `res.format()` |\\n| `downloads` | File transfers | `res.download()`, `res.sendFile()` |\\n| `cookies` | State via cookies | `res.cookie()`, `req.cookies` (with cookie-parser) |\\n| `cookie-sessions` | Lightweight sessions | `cookie-session` middleware |\\n| `session` | Server-side sessions | `express-session` with store configuration |\\n\\n### Application Structure\\n\\n| Example | Focus Area | Key Express Concepts |\\n|---------|-----------|-------------------|\\n| `mvc` | Separation of concerns | Controllers, models, view layer integration |\\n| `web-service` | API design | RESTful patterns, JSON responses |\\n| `search` | Query processing | Search parameter parsing, result pagination |\\n| `resource` | CRUD operations | HTTP method routing on single path |\\n| `online` | Real-time state | External store integration (Redis) |\\n\\n### View Layer\\n\\n| Example | Focus Area | Key Express Concepts |\\n|---------|-----------|-------------------|\\n| `ejs` | Template rendering | `app.set('view engine')`, `res.render()` |\\n| `markdown` | Custom engines | `app.engine()` for non-standard template formats |\\n| `view-constructor` | Dynamic view creation | Programmatic `View` instantiation |\\n| `view-locals` | Request-scoped data | `res.locals` for middleware-to-view communication |\\n\\n### Security &amp; Identity\\n\\n| Example | Focus Area | Key Express Concepts |\\n|---------|-----------|-------------------|\\n| `auth` | Authentication | Session-based login flows, password verification |\\n| `vhost` | Multi-tenant hosting | `vhost` middleware for domain-based routing |\\n\\n## Relationship to Core Framework\\n\\nThe examples are **consumers** of the Express API, not dependencies of the core library. They validate the public interface through practical application:\\n\\n- Examples import `express` as a package dependency (typically `../..` or published version)\\n- They exercise stable APIs: `Application`, `Router`, `Request`, `Response`, `NextFunction`\\n- New Express features often receive corresponding example additions\\n\\n## Using the Examples\\n\\n### Running an Example\\n\\n```bash\\ncd examples/hello-world\\nnpm install  # if package.json present\\nnode index.js\\n```\\n\\n### Structure Conventions\\n\\nMost examples follow this layout:\\n\\n```\\nexample-name/\\n\u251c\u2500\u2500 index.js          # Application entry point\\n\u251c\u2500\u2500 package.json      # Dependencies (often references parent express)\\n\u2514\u2500\u2500 [views/]          # Templates if applicable\\n    \u2514\u2500\u2500 ...\\n```\\n\\n### Reading Order for New Contributors\\n\\n1. **`hello-world`** \u2192 Request/response fundamentals\\n2. **`route-separation`** \u2192 Scaling beyond single-file applications\\n3. **`mvc`** \u2192 Architectural patterns\\n4. **`error`** \u2192 Production error handling\\n5. **`web-service`** \u2192 API-oriented design\\n\\n## Diagram: Example Dependency on Express Core\\n\\n```mermaid\\nflowchart TD\\n    subgraph Examples[\\\"Example Applications\\\"]\\n        HW[hello-world]\\n        MVC[mvc]\\n        AUTH[auth]\\n        WS[web-service]\\n        EJS[ejs]\\n        ERR[error]\\n    end\\n\\n    Express[express coreApplication / Router / Middleware]\\n\\n    Examples --&gt;|require('express')| Express\\n\\n    style Express fill:#e1f5fe\\n    style Examples fill:#f3e5f5\\n```\\n\\nThis illustrates the unidirectional dependency: examples import and exercise the framework, with no reverse coupling.\",\"other-support\":\"# Other \u2014 support\\n\\n# Test Support Utilities\\n\\nThis module provides shared infrastructure for the Express.js test suite. It consists of three small, focused files that handle environment setup, template rendering for test fixtures, and common assertion helpers for supertest-based HTTP response validation.\\n\\n---\\n\\n## `test/support/env.js`\\n\\nEnvironment bootstrap that runs before the test suite. Sets two process-level flags:\\n\\n| Variable | Value | Purpose |\\n|----------|-------|---------|\\n| `NODE_ENV` | `'test'` | Puts Express and dependencies into test mode |\\n| `NO_DEPRECATION` | `'body-parser,express'` | Suppresses deprecation warnings from `body-parser` and `express` to keep test output clean |\\n\\nThis file is typically required as a mocha `--require` or at the top of test entry points.\\n\\n---\\n\\n## `test/support/tmpl.js`\\n\\nMinimal template engine for rendering test fixture files with simple variable substitution.\\n\\n### `renderFile(fileName, options, callback)`\\n\\nReads a file and replaces `$variable` or `$nested.path` tokens with values from `options`.\\n\\n```javascript\\nvar renderFile = require('./support/tmpl');\\n\\nrenderFile('views/email.tmpl', { user: { name: 'alice' } }, function (err, html) {\\n  // html contains resolved values\\n});\\n```\\n\\n### Variable Syntax\\n\\n| Pattern | Resolution |\\n|---------|-----------|\\n| `$name` | `options.name` |\\n| `$user.name` | `options.user.name` (nested lookup) |\\n\\n### Error Handling\\n\\n- File read errors pass through to `callback(err)`\\n- Substitution errors are caught, wrapped as `RenderError`, and passed to `callback`\\n\\n### `generateVariableLookup(data)`\\n\\nReturns a `String.prototype.replace` replacer function that walks dot-delimited paths against `data`. Used internally by `renderFile`.\\n\\n---\\n\\n## `test/support/utils.js`\\n\\nAssertion factory functions for supertest response objects. All return a function that accepts a `res` object, designed for fluent `.expect()` chaining:\\n\\n```javascript\\nrequest(app)\\n  .get('/')\\n  .expect(200)\\n  .expect(shouldHaveHeader('content-type'))\\n  .expect(shouldNotHaveBody())\\n```\\n\\n### Available Assertions\\n\\n| Export | Signature | Behavior |\\n|--------|-----------|----------|\\n| `shouldHaveBody` | `(buf: Buffer) =&gt; (res) =&gt; void` | Asserts response body matches buffer byte-for-byte (hex comparison) |\\n| `shouldHaveHeader` | `(header: string) =&gt; (res) =&gt; void` | Asserts header exists (case-insensitive) |\\n| `shouldNotHaveBody` | `() =&gt; (res) =&gt; void` | Asserts `res.text` is empty string or undefined |\\n| `shouldNotHaveHeader` | `(header: string) =&gt; (res) =&gt; void` | Asserts header is absent (case-insensitive) |\\n| `shouldSkipQuery` | `(versionString: string) =&gt; boolean` | Returns `true` if Node major version &lt; 22 (for HTTP QUERY method tests) |\\n\\n### Body Comparison Details\\n\\n`shouldHaveBody` normalizes supertest's response body handling: if `res.body` is not already a Buffer, it creates one from `res.text`. This ensures consistent hex comparison regardless of how supertest parsed the response.\\n\\n### Version Gating\\n\\n`shouldSkipQuery` gates tests for the HTTP `QUERY` method, which Node.js fully supports only from version 22 onward. The helper extracts the major version and compares numerically.\\n\\n```javascript\\n// Typical usage in test files\\nconst utils = require('./support/utils');\\n\\nif (utils.shouldSkipQuery(process.version)) {\\n  describe.skip('QUERY method', ...);\\n}\\n```\\n\\n---\\n\\n## Usage Patterns in Test Suite\\n\\nThe utilities are consumed across multiple test files:\\n\\n- **Static file &amp; download tests** (`express.static.js`, `res.download.js`, `res.sendFile.js`) use body and header assertions to verify content delivery and cache headers\\n- **Response method tests** (`res.send.js`, `res.jsonp.js`, `res.redirect.js`, `res.vary.js`) validate header presence/absence and empty bodies\\n- **Acceptance tests** (`cookies.js`) verify cookie-related headers are not leaked\\n\\nThe template renderer supports fixture-based tests that need dynamic content without pulling in a full template engine dependency.\",\"overview\":\"# express \u2014 Wiki\\n\\n# Express\\n\\n**Fast, unopinionated, minimalist web framework for Node.js**\\n\\nExpress is a thin layer of fundamental web application features built on Node.js, designed for building single-page, multi-page, and hybrid web applications and APIs. It provides a robust set of HTTP utility methods and middleware at its core, while remaining unopinionated about how you structure your application.\\n\\n## Architecture Overview\\n\\nAt its heart, Express is composed of a small, focused core that orchestrates the request-response pipeline. The [Core Framework](core-framework.md) wires together routing, middleware, view rendering, and the enhanced request/response prototypes. Application behavior is configured through [Application Configuration](application-configuration.md), which defines dependencies, scripts, and metadata.\\n\\nThe framework's power comes from its composability: middleware functions execute in sequence, routers can be nested and mounted at arbitrary paths, and the view system can be swapped or extended to suit your needs.\\n\\n```mermaid\\nflowchart TB\\n    subgraph Client\\n        Browser[HTTP Client]\\n    end\\n    \\n    subgraph Express[\\\"Express Application\\\"]\\n        App[Applicationlib/application.js]\\n        Router[Routerlib/router/]\\n        Middleware[Middleware Stack]\\n        ReqRes[Enhanced req/reslib/request.jslib/response.js]\\n    end\\n    \\n    subgraph Runtime\\n        Node[Node.js HTTP Server]\\n    end\\n    \\n    Browser --&gt;|HTTP Request| Node\\n    Node --&gt; App\\n    App --&gt; Router\\n    Router --&gt; Middleware\\n    Middleware --&gt; ReqRes\\n    ReqRes --&gt;|HTTP Response| Node\\n    Node --&gt; Browser\\n    \\n    style Express fill:#f9f9f9,stroke:#333,stroke-width:2px\\n```\\n\\n## Key Concepts\\n\\n**Applications and Routers** \u2014 An Express app is created via the factory in `lib/express.js` and configured through the application prototype. Routers are mini Express applications, mountable and composable, enabling modular route organization as demonstrated in the [Multi-Router Example](multi-router-example.md).\\n\\n**Middleware** \u2014 The core execution model. Functions that process requests in sequence, with the ability to terminate the response or pass control to the next function. The [Route Middleware Example](route-middleware-example.md) shows authentication, authorization, and data loading patterns.\\n\\n**Request/Response Enhancement** \u2014 Express augments Node's raw `http.IncomingMessage` and `http.ServerResponse` with a rich API for routing, content negotiation, cookie handling, and view rendering. See the [Content Negotiation Example](content-negotiation-example.md) for format selection patterns.\\n\\n## Examples and Patterns\\n\\nThe repository includes extensive examples covering common web development patterns:\\n\\n- **Routing patterns**: [Route Parameters](route-parameters-example.md) for `app.param()` preprocessing, [Route Map](route-map-example.md) for declarative route definitions, [Route Separation](route-separation-example.md) for organizing by domain concern\\n- **State management**: [Session](session-example.md) (in-memory and Redis-backed), [Cookie Sessions](cookie-sessions-example.md), [Cookies](cookies-example.md)\\n- **Authentication**: [Authentication Example](authentication-example.md) with PBKDF2 password hashing and session fixation protection\\n- **Views and templating**: [EJS Templating](ejs-templating-example.md), [View Locals](view-locals-example.md), [View Constructor](view-constructor-example.md) for custom view systems, [Markdown](markdown-example.md) as a view engine\\n- **Error handling**: [Error Handling Examples](error-handling-examples.md) covering basic propagation and content-negotiated error pages\\n- **Advanced patterns**: [MVC](mvc-example.md) with convention-based routing, [Virtual Hosts](virtual-hosts-example.md), [Web Service](web-service-example.md) with API key validation, [Search](search-example.md) with Redis, [Online](online-example.md) presence tracking, [Downloads](downloads-example.md) with path traversal protection, [Static Files](static-files-example.md), [Resource](resource-example.md) routing, and the minimal [Hello World](hello-world-example.md)\\n\\n## Development Setup\\n\\n```bash\\n# Install dependencies\\nnpm install\\n\\n# Run the test suite\\nnpm test\\n\\n# Run tests with coverage\\nnpm run test-cov\\n\\n# Lint code\\nnpm run lint\\nnpm run lint:fix\\n```\\n\\nThe project uses `npm run test-ci` for continuous integration and `npm run test-tap` for TAP-formatted output.\\n\\n## Documentation\\n\\n- [Project Documentation](project-documentation.md) \u2014 Version history and changelog\\n- [Core Framework](core-framework.md) \u2014 Internal architecture and module structure\\n- [Application Configuration](application-configuration.md) \u2014 Package manifest and tooling configuration\\n\\nFor the full API reference, visit [expressjs.com](https://expressjs.com).\",\"project-documentation\":\"# Project Documentation\\n\\n# History.md \u2014 Express.js Changelog\\n\\nThe `History.md` file is the canonical changelog for the Express.js framework, documenting all releases from the 0.x era through the current 5.x line. It serves as the primary reference for developers upgrading between versions, understanding breaking changes, and tracking the evolution of the API.\\n\\n## Purpose and Role\\n\\nThis file is the **source of truth for version history** across the entire Express ecosystem. Unlike generated changelogs, it is hand-curated by maintainers and serves multiple audiences:\\n\\n- **End users** evaluating upgrade risks and new features\\n- **Middleware authors** adapting to API changes\\n- **Core contributors** ensuring consistency in release notes\\n- **Security researchers** tracking vulnerability fixes\\n\\nThe changelog is organized in **reverse chronological order** (newest first) with a strict hierarchy: major version sections, then individual releases, then categorized changes within each release.\\n\\n## Document Structure\\n\\n### Top-Level Organization\\n\\n```\\nHistory.md\\n\u251c\u2500\u2500 Unreleased Changes          # Accumulated changes since last release\\n\u2502   \u251c\u2500\u2500 \ud83d\ude80 Improvements\\n\u2502   \u251c\u2500\u2500 \u26a1 Performance\\n\u2502   \u2514\u2500\u2500 (other categories)\\n\u251c\u2500\u2500 5.2.1 / 2025-12-01         # Version / Date header\\n\u251c\u2500\u2500 5.2.0 / 2025-12-01\\n\u251c\u2500\u2500 5.1.0 / 2025-03-31\\n\u2502   \u2514\u2500\u2500 ...                    # Nested dependency updates, features, etc.\\n\u251c\u2500\u2500 5.0.0 / 2024-09-10         # Major version with breaking changes\\n\u251c\u2500\u2500 4.x.x releases             # Prior major version maintenance\\n\u251c\u2500\u2500 3.x.x releases\\n\u251c\u2500\u2500 2.x.x releases\\n\u2514\u2500\u2500 1.x.x \u2192 0.x.x releases     # Legacy versions\\n```\\n\\n### Entry Categories\\n\\nEach release groups changes into semantic categories:\\n\\n| Category | Emoji | Used For |\\n|----------|-------|----------|\\n| Improvements | \ud83d\ude80 | New features, enhancements |\\n| Performance | \u26a1 | Optimizations, speed improvements |\\n| Security fixes | (none) | CVE references, advisory links |\\n| Breaking changes | (none) | API removals, behavior changes |\\n| Deprecations | (none) | Warnings about future removals |\\n| Dependency updates | `deps:` | External package version bumps |\\n\\n### Entry Format\\n\\nIndividual entries follow a consistent pattern:\\n\\n```markdown\\n* Change description - by [@username](https://github.com/username) in [#XXXX](https://github.com/expressjs/express/pull/XXXX)\\n\\n* Code example when relevant:\\n    ```js\\n    app.render('index', null, callback); // now works as expected\\n    ```\\n```\\n\\nDependency updates use a compact prefix style:\\n\\n```markdown\\n* deps: `body-parser@^2.2.1`\\n* deps: remove `setprototypeof`\\n```\\n\\n## Key Content Patterns\\n\\n### Breaking Changes\\n\\nMajor versions (5.0.0, 4.0.0, 3.0.0) explicitly enumerate breaking changes. The 5.0.0 release exemplifies this pattern:\\n\\n```markdown\\n* breaking:\\n  * `res.status()` accepts only integers, and input must be greater than 99 and less than 1000\\n    * will throw a `RangeError: Invalid status code: ${code}. Status code must be greater than 99 and less than 1000.` for inputs outside this range\\n    * will throw a `TypeError: Invalid status code: ${code}. Status code must be an integer.` for non integer inputs\\n  * `res.redirect('back')` and `res.location('back')` is no longer a supported magic string, explicitly use `req.get('Referrer') || '/'`.\\n```\\n\\nBreaking changes are **nested with bullet depth** to show related error messages and migration paths.\\n\\n### Security Advisories\\n\\nSecurity fixes include both CVE identifiers and GitHub Security Advisory links:\\n\\n```markdown\\n* Security fix for [CVE-2024-51999](https://www.cve.org/CVERecord?id=CVE-2024-51999) ([GHSA-pj86-cfqh-vqx6](https://github.com/expressjs/express/security/advisories/GHSA-pj86-cfqh-vqx6))\\n```\\n\\nReverted security fixes are explicitly documented to prevent confusion:\\n\\n```markdown\\n* Revert security fix for [CVE-2024-51999](...) ([GHSA-...](...))\\n  * The prior release (5.2.0) included an erroneous breaking change... CVE-2024-51999 has been rejected. The change has been fully reverted...\\n```\\n\\n### Deprecation Notices\\n\\nDeprecations bridge current and future behavior, often with migration examples:\\n\\n```markdown\\n* Deprecate passing `options.maxAge` and `options.expires` to `res.clearCookie`\\n  - Will be ignored in v5, clearCookie will set a cookie with an expires in the past to instruct clients to delete the cookie\\n```\\n\\n### Dependency Evolution\\n\\nThe changelog tracks Express's shifting dependency strategy. The 5.1.0 release shows a significant **dependency reduction**:\\n\\n```markdown\\n* deps: remove `setprototypeof`\\n* deps: remove `safe-buffer`\\n* deps: remove `utils-merge`\\n* deps: remove `methods`\\n* deps: remove `depd`\\n```\\n\\nThese removals reflect Node.js core improvements (e.g., `Object.setPrototypeOf` replacing `setprototypeof`) and internalization of functionality.\\n\\n## Version-Specific Conventions\\n\\n### 5.x Series (Current)\\n\\n- Uses semantic emoji prefixes for categories\\n- Includes contributor attribution with GitHub links\\n- References pull requests explicitly\\n- Maintains `Unreleased Changes` section for ongoing work\\n\\n### 4.x Series (Maintenance)\\n\\n- Simpler format without emojis\\n- Focus on security patches and dependency updates\\n- LTS-style maintenance with minimal new features\\n\\n### 3.x and Earlier (Legacy)\\n\\n- Historical format, less structured\\n- Includes long-removed features like `app.configure()`, `app.router`\\n- Documents middleware bundling (removed in 4.0.0)\\n\\n## Relationship to Codebase\\n\\n`History.md` is a **documentation-only file** with no runtime imports or build-time processing. However, it connects to the codebase through:\\n\\n| Connection Point | How |\\n|-----------------|-----|\\n| `package.json` | `version` field must match the newest dated header |\\n| Git tags | Release tags correspond to version headers |\\n| GitHub Releases | Often generated from or cross-referenced with this file |\\n| Migration guides | Major version documentation extracts from breaking changes sections |\\n\\n## Maintenance Workflow\\n\\nWhen contributing changes that should appear in the changelog:\\n\\n1. Add entries to `Unreleased Changes` during development\\n2. Categorize under appropriate emoji section\\n3. Include `by @username in #PR` attribution\\n4. On release, the maintainer:\\n   - Moves `Unreleased Changes` to a dated version header\\n   - Updates `package.json` version\\n   - Creates git tag\\n\\n## Notable Historical Arcs\\n\\n### Query Parser Evolution\\n\\nThe `query parser` setting demonstrates API evolution across versions:\\n\\n| Version | Change |\\n|---------|--------|\\n| 3.7.0 | Introduced configurable query parser |\\n| 5.0.0-beta.1 | Default changed from `'extended'` to `'simple'` |\\n| 5.2.0/5.2.1 | CVE-2024-51999 confusion and reversion related to extended parser behavior |\\n\\n### Redirect Behavior\\n\\n`res.redirect()` has accumulated refinements:\\n\\n- **4.14.0**: Encode URL if not already encoded\\n- **4.19.0/4.19.2**: Open redirect allow list bypass fixes\\n- **5.0.0**: Remove `'back'` magic string\\n- **5.1.0**: Deprecation warning for undefined arguments\\n- **5.x unreleased**: Improved HTML structure with ``, ``, ``\\n\\n### Body Type Support\\n\\nResponse body handling expanded over time:\\n\\n- **4.16.0**: Add `express.json` and `express.urlencoded` middleware\\n- **4.17.0**: Add `express.raw` and `express.text`\\n- **5.1.0**: Add `Uint8Array` support in `res.send()`\",\"resource-example\":\"# Resource Example\\n\\n# Resource Example\\n\\nAn Express application demonstrating a custom resource routing pattern that maps RESTful HTTP endpoints to controller methods using a declarative API.\\n\\n## Overview\\n\\nThis module creates a standalone Express server that showcases how to build reusable resource routing on top of Express's core routing system. It defines a `resource()` method that automatically wires standard CRUD operations\u2014list, show, destroy, and range queries\u2014to a controller object, reducing boilerplate route definitions.\\n\\nThe server exposes a `users` resource backed by an in-memory array and serves an HTML index page documenting the available endpoints.\\n\\n## The `app.resource()` Extension\\n\\nThe module extends the Express application instance with a `resource()` method that registers multiple routes for a given path and controller object.\\n\\n```javascript\\napp.resource = function(path, obj) {\\n  this.get(path, obj.index);                                    // GET /users\\n  this.get(path + '/:a..:b{.:format}', function(req, res){      // GET /users/1..3 or /users/1..3.json\\n    var a = parseInt(req.params.a, 10);\\n    var b = parseInt(req.params.b, 10);\\n    var format = req.params.format;\\n    obj.range(req, res, a, b, format);\\n  });\\n  this.get(path + '/:id', obj.show);                            // GET /users/1\\n  this.delete(path + '/:id', function(req, res){                // DELETE /users/1\\n    var id = parseInt(req.params.id, 10);\\n    obj.destroy(req, res, id);\\n  });\\n};\\n```\\n\\n### Route Mapping\\n\\n| HTTP Method | Path Pattern | Controller Method | Purpose |\\n|-------------|-----------|-------------------|---------|\\n| `GET` | `/users` | `obj.index` | List all resources |\\n| `GET` | `/users/:a..:b` or `/users/:a..:b.:format` | `obj.range` | Query a subset with optional format |\\n| `GET` | `/users/:id` | `obj.show` | Retrieve single resource |\\n| `DELETE` | `/users/:id` | `obj.destroy` | Remove single resource |\\n\\nThe range route uses Express's regex-like parameter syntax `:a..:b{.:format}` where the `.format` portion is optional (denoted by the curly braces). When present, it triggers content negotiation between JSON and HTML responses.\\n\\n## User Controller\\n\\nThe `User` object implements the controller interface expected by `app.resource()`. It operates on the in-memory `users` array.\\n\\n### `User.index(req, res)`\\n\\nReturns the complete `users` array as JSON.\\n\\n```javascript\\nindex: function(req, res){\\n  res.send(users);\\n}\\n```\\n\\n### `User.show(req, res)`\\n\\nRetrieves a user by array index from `req.params.id`. Returns an error object if the index does not exist.\\n\\n```javascript\\nshow: function(req, res){\\n  res.send(users[req.params.id] || { error: 'Cannot find user' });\\n}\\n```\\n\\n### `User.destroy(req, res, id)`\\n\\nDeletes a user by index. The `id` is pre-parsed by the route handler before being passed to the controller. Returns `'destroyed'` on success or `'Cannot find user'` on failure.\\n\\n```javascript\\ndestroy: function(req, res, id){\\n  var destroyed = id in users;\\n  delete users[id];\\n  res.send(destroyed ? 'destroyed' : 'Cannot find user');\\n}\\n```\\n\\n### `User.range(req, res, a, b, format)`\\n\\nSlices the users array from index `a` to `b` (inclusive). Supports two output formats:\\n\\n- **`json`**: Returns the slice as a JSON array\\n- **`html` (default)**: Renders an unordered list of user names\\n\\n```javascript\\nrange: function(req, res, a, b, format){\\n  var range = users.slice(a, b + 1);\\n  switch (format) {\\n    case 'json':\\n      res.send(range);\\n      break;\\n    case 'html':\\n    default:\\n      var html = '\n' + range.map(function(user){\\n        return '\n' + user.name + '&lt;\\/li&gt;';\\n      }).join('\\\\n') + '&lt;\\/ul&gt;';\\n      res.send(html);\\n      break;\\n  }\\n}\\n```\\n\\n## Data Model\\n\\n```javascript\\nvar users = [\\n  { name: 'tj' },\\n  { name: 'ciaran' },\\n  { name: 'aaron' },\\n  { name: 'guillermo' },\\n  { name: 'simon' },\\n  { name: 'tobi' }\\n];\\n```\\n\\nThe `users` array is a simple in-memory store. Note that `delete users[id]` does not reindex the array\u2014subsequent accesses to deleted indices return `undefined`, which `User.show()` handles by returning an error.\\n\\n## Root Endpoint\\n\\nA convenience HTML page lists all available example URLs:\\n\\n```javascript\\napp.get('/', function(req, res){\\n  res.send([\\n    '\nExamples:&lt;\\/h1&gt; \n'\\n    , '\nGET /users&lt;\\/li&gt;'\\n    , '\nGET /users/1&lt;\\/li&gt;'\\n    , '\nGET /users/3&lt;\\/li&gt;'\\n    , '\nGET /users/1..3&lt;\\/li&gt;'\\n    , '\nGET /users/1..3.json&lt;\\/li&gt;'\\n    , '\nDELETE /users/4&lt;\\/li&gt;'\\n    , '&lt;\\/ul&gt;'\\n  ].join('\\\\n'));\\n});\\n```\\n\\n## Server Bootstrap\\n\\nThe module exports the configured `app` for testing or programmatic use. When run directly (`node examples/resource/index.js`), it starts on port 3000:\\n\\n```javascript\\n/* istanbul ignore next */\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\n## Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   HTTP Request  \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  Express Router \u2502\u2500\u2500\u2500\u2500\u25b6\u2502 Route-Specific  \u2502\\n\u2502  (GET/DELETE)   \u2502     \u2502                 \u2502     \u2502   Middleware    \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                                         \u2502\\n                              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                              \u25bc\\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                    \u2502  User Controller \u2502\\n                    \u2502   (index/show/   \u2502\\n                    \u2502  destroy/range)  \u2502\\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                             \u2502\\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                    \u25bc                 \u25bc\\n              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n              \u2502  JSON   \u2502      \u2502  HTML   \u2502\\n              \u2502 Response\u2502      \u2502 Response\u2502\\n              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## Integration with Express\\n\\nThis example requires the local Express build (`require('../../')`) rather than an npm-installed version. It demonstrates patterns that can be extracted into middleware or application generators:\\n\\n- **Monkey-patching pattern**: Adding `app.resource()` directly to the application instance\\n- **Controller convention**: Expecting controller objects with specific method signatures\\n- **Parameter preprocessing**: Parsing integers in route handlers before passing clean data to controllers\\n\\nThe `send()` calls in all controller methods delegate to Express's `res.send()`, which handles content-type negotiation and response finalization.\",\"route-map-example\":\"# Route Map Example\\n\\n# Route Map Example\\n\\nAn Express.js example demonstrating a declarative route mapping pattern that enables nested route definitions through plain JavaScript objects.\\n\\n## Purpose\\n\\nThis module showcases a technique for organizing Express routes as hierarchical data structures rather than imperative `app.get()`, `app.post()`, etc. calls. The `app.map()` utility recursively traverses a nested object to register routes with their corresponding handler functions, producing cleaner route organization for resource-heavy APIs.\\n\\n## The `app.map()` Method\\n\\nThe core addition is a monkey-patched `map` method on the Express application instance:\\n\\n```javascript\\napp.map = function(a, route){\\n  route = route || '';\\n  for (var key in a) {\\n    switch (typeof a[key]) {\\n      case 'object':\\n        app.map(a[key], route + key);  // Recurse into nested paths\\n        break;\\n      case 'function':\\n        if (verbose) console.log('%s %s', key, route);\\n        app[key](route, a[key]);        // Register: app[method](path, handler)\\n        break;\\n    }\\n  }\\n};\\n```\\n\\n| Parameter | Description |\\n|-----------|-------------|\\n| `a` | Route definition object (nested structure) |\\n| `route` | Accumulated path prefix (defaults to `''`) |\\n\\n### Key Behavior\\n\\n- **Object values** (`{ '/path': { ... } }`): Treated as path segments; recursively processed with concatenated route prefix\\n- **Function values** (`get: fn`): Treated as HTTP method handlers; registered via `app[method](route, handler)`\\n- **Path accumulation**: Nested objects build complete paths (e.g., `'/users'` + `'/:uid'` + `'/pets'` = `'/users/:uid/pets'`)\\n\\n## Route Definitions\\n\\n### Users Resource\\n\\n```javascript\\nvar users = {\\n  list: function(req, res){           // GET /users\\n    res.send('user list');\\n  },\\n  get: function(req, res){            // GET /users/:uid\\n    res.send('user ' + escapeHtml(req.params.uid))\\n  },\\n  delete: function(req, res){         // DELETE /users\\n    res.send('delete users');\\n  }\\n};\\n```\\n\\n### Pets Sub-resource\\n\\n```javascript\\nvar pets = {\\n  list: function(req, res){           // GET /users/:uid/pets\\n    res.send('user ' + escapeHtml(req.params.uid) + '\\\\'s pets')\\n  },\\n  delete: function(req, res){         // DELETE /users/:uid/pets/:pid\\n    res.send('delete ' + escapeHtml(req.params.uid) + '\\\\'s pet ' + escapeHtml(req.params.pid))\\n  }\\n};\\n```\\n\\n## Generated Route Map\\n\\nThe declarative structure:\\n\\n```javascript\\napp.map({\\n  '/users': {\\n    get: users.list,\\n    delete: users.delete,\\n    '/:uid': {\\n      get: users.get,\\n      '/pets': {\\n        get: pets.list,\\n        '/:pid': {\\n          delete: pets.delete\\n        }\\n      }\\n    }\\n  }\\n});\\n```\\n\\nExpands to these Express route registrations:\\n\\n| HTTP Method | Path | Handler |\\n|-------------|------|---------|\\n| `GET` | `/users` | `users.list` |\\n| `DELETE` | `/users` | `users.delete` |\\n| `GET` | `/users/:uid` | `users.get` |\\n| `GET` | `/users/:uid/pets` | `pets.list` |\\n| `DELETE` | `/users/:uid/pets/:pid` | `pets.delete` |\\n\\n## Architecture\\n\\n```mermaid\\ngraph TD\\n    A[app.map(routeTree)] --&gt; B{typeof value}\\n    B --&gt;|object| C[Accumulate path prefix]\\n    C --&gt; A\\n    B --&gt;|function| D[app[method](path, handler)]\\n    \\n    style A fill:#f9f,stroke:#333\\n    style D fill:#bbf,stroke:#333\\n```\\n\\n## Security Considerations\\n\\nThe module uses `escapeHtml` for output rendering:\\n\\n```javascript\\nres.send('user ' + escapeHtml(req.params.uid))\\n```\\n\\nThis prevents XSS when route parameters are reflected in responses. Note that `escapeHtml` is **not** applied to all outputs uniformly\u2014`users.list` and the initial `users.delete` omit escaping entirely.\\n\\n## Environment Behavior\\n\\n| `NODE_ENV` | `verbose` | Console output on route registration |\\n|------------|-----------|--------------------------------------|\\n| `test` | `false` | Silent |\\n| anything else | `true` | Logs each `METHOD /path` |\\n\\n## Entry Point\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\nThe `!module.parent` guard allows the file to be `require()`'d in tests without starting the server, while direct execution (`node examples/route-map/index.js`) boots on port 3000.\",\"route-middleware-example\":\"# Route Middleware Example\\n\\n# Route Middleware Example\\n\\nAn Express.js application demonstrating route-specific middleware patterns for authentication, authorization, and data loading.\\n\\n## Purpose\\n\\nThis example illustrates how to compose reusable middleware functions that execute in sequence for specific routes. It shows three common patterns:\\n\\n- **Data loading middleware** \u2014 fetching resources before route handlers run\\n- **Self-restriction middleware** \u2014 allowing users to access only their own resources\\n- **Role-based middleware** \u2014 restricting access by user role\\n\\nThese patterns separate cross-cutting concerns from route handlers, keeping endpoint logic focused on its primary responsibility.\\n\\n## Application Structure\\n\\n```javascript\\nvar express = require('../../lib/express');\\nvar app = express();\\n```\\n\\nThe application creates a single Express instance and attaches middleware and routes. No module exports are provided; the file is executable directly (`node examples/route-middleware/index.js`) or importable for testing.\\n\\n## Middleware Stack\\n\\n### Global Authentication (Faux)\\n\\n```javascript\\napp.use(function(req, res, next){\\n  req.authenticatedUser = users[0];  // Always \\\"tj\\\" (id: 0, role: 'member')\\n  next();\\n});\\n```\\n\\nAll requests receive a hardcoded authenticated user. In production, this would be replaced with session/JWT validation. The `authenticatedUser` property is attached to the request object for downstream middleware to access.\\n\\n### `loadUser(req, res, next)`\\n\\nRoute parameter middleware that populates `req.user` from the `:id` parameter.\\n\\n| Behavior | Condition |\\n|----------|-----------|\\n| Calls `next()` | User exists in `users` array |\\n| Calls `next(error)` | User not found; error propagated to Express error handlers |\\n\\n```javascript\\napp.get('/user/:id', loadUser, function(req, res){ ... });\\n```\\n\\n### `andRestrictToSelf(req, res, next)`\\n\\nAuthorization guard ensuring the authenticated user matches the requested user.\\n\\nDepends on `loadUser` having already executed (requires `req.user`). Returns `Error('Unauthorized')` for mismatched IDs.\\n\\n```javascript\\napp.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){ ... });\\n```\\n\\n### `andRestrictTo(role)`\\n\\nHigher-order function returning role-checking middleware.\\n\\n```javascript\\nfunction andRestrictTo(role) {\\n  return function(req, res, next) {\\n    if (req.authenticatedUser.role === role) {\\n      next();\\n    } else {\\n      next(new Error('Unauthorized'));\\n    }\\n  }\\n}\\n```\\n\\nUsage: `andRestrictTo('admin')` creates middleware that passes only for users with `role === 'admin'`.\\n\\n## Route Definitions\\n\\n| Method | Path | Middleware Chain | Behavior |\\n|--------|------|------------------|----------|\\n| GET | `/` | \u2014 | Redirects to `/user/0` |\\n| GET | `/user/:id` | `loadUser` | Displays user name |\\n| GET | `/user/:id/edit` | `loadUser`, `andRestrictToSelf` | Displays edit confirmation if self |\\n| DELETE | `/user/:id` | `loadUser`, `andRestrictTo('admin')` | Displays delete confirmation if admin |\\n\\n## Request Flow\\n\\n```mermaid\\nflowchart LR\\n    A[Request] --&gt; B[Global Authreq.authenticatedUser]\\n    B --&gt; C{Route Match}\\n    C --&gt;|GET /user/:id| D[loadUser]\\n    C --&gt;|GET /user/:id/edit| E[loadUser]\\n    C --&gt;|DELETE /user/:id| F[loadUser]\\n    D --&gt; G[Route Handler]\\n    E --&gt; H[andRestrictToSelf]\\n    H --&gt;|pass| I[Route Handler]\\n    H --&gt;|fail| J[Error Handler]\\n    F --&gt; K[andRestrictTo('admin')]\\n    K --&gt;|pass| L[Route Handler]\\n    K --&gt;|fail| J\\n```\\n\\n## Test Interactions\\n\\nThe call graph indicates `index.js` calls `send` from `test/Router.js` during test execution. The `/* istanbul ignore next */` comment on the `app.listen` block prevents coverage measurement of the standalone server startup path, keeping test coverage focused on the middleware logic.\\n\\n## Key Patterns Demonstrated\\n\\n**Middleware factories**: `andRestrictTo` creates parameterized middleware without repeating the authorization logic.\\n\\n**Request object augmentation**: `req.user` and `req.authenticatedUser` carry state between middleware layers\u2014standard Express practice, though not type-safe.\\n\\n**Error propagation**: Failed authorizations and missing users become `next(error)` calls, delegating response formatting to centralized error handlers (see `examples/pages` for that pattern).\",\"route-parameters-example\":\"# Route Parameters Example\\n\\n# Route Parameters Example\\n\\nAn Express.js application demonstrating parameterized route handling with custom parameter conversion and data loading middleware.\\n\\n## Overview\\n\\nThis module showcases Express's `app.param()` API for preprocessing route parameters before handlers execute. It implements two distinct parameter processing strategies: numeric range parsing for slice operations and database-style user lookup by ID.\\n\\n## Parameter Processing Pipeline\\n\\n```mermaid\\ngraph LR\\n    A[Request URL] --&gt; B{Parameter Match?}\\n    B --&gt;|to, from| C[Parse Integer]\\n    B --&gt;|user| D[Lookup User]\\n    C --&gt;|Valid| E[Route Handler]\\n    C --&gt;|NaN| F[400 Bad Request]\\n    D --&gt;|Found| E\\n    D --&gt;|Missing| G[404 Not Found]\\n```\\n\\n## Module Structure\\n\\n### Faux Database\\n\\n```javascript\\nvar users = [\\n  { name: 'tj' }\\n  , { name: 'tobi' }\\n  , { name: 'loki' }\\n  , { name: 'jane' }\\n  , { name: 'bandit' }\\n];\\n```\\n\\nIn-memory array of user objects. Indexes correspond to `:user` parameter values in routes.\\n\\n### Parameter Middleware\\n\\n#### Numeric Conversion (`to`, `from`)\\n\\n```javascript\\napp.param(['to', 'from'], function(req, res, next, num, name){\\n  req.params[name] = parseInt(num, 10);\\n  if( isNaN(req.params[name]) ){\\n    next(createError(400, 'failed to parseInt '+num));\\n  } else {\\n    next();\\n  }\\n});\\n```\\n\\nProcesses parameters named `to` and `from` across all routes. Converts string values to base-10 integers using `parseInt`. Rejects non-numeric values with a 400 Bad Request error via `http-errors`.\\n\\n#### User Loading (`user`)\\n\\n```javascript\\napp.param('user', function(req, res, next, id){\\n  req.user = users[id]\\n  if (req.user) {\\n    next();\\n  } else {\\n    next(createError(404, 'failed to find user'));\\n  }\\n});\\n```\\n\\nLoads user object from the faux database by array index. Attaches found user to `req.user` for downstream handlers. Returns 404 Not Found for out-of-bounds or missing indices.\\n\\n### Route Handlers\\n\\n| Route | Description |\\n|-------|-------------|\\n| `GET /` | Landing page with navigation hints |\\n| `GET /user/:user` | Display single user by ID |\\n| `GET /users/:from-:to` | Display user name range (inclusive) |\\n\\n#### Range Handler Detail\\n\\n```javascript\\napp.get('/users/:from-:to', function (req, res) {\\n  var from = req.params.from;\\n  var to = req.params.to;\\n  var names = users.map(function(user){ return user.name; });\\n  res.send('users ' + names.slice(from, to + 1).join(', '));\\n});\\n```\\n\\nNote the `to + 1` adjustment: `Array.prototype.slice()` excludes the end index, so the handler increments to make the range inclusive as perceived by the API consumer.\\n\\n## Error Handling Strategy\\n\\n| Scenario | HTTP Status | Source |\\n|----------|-------------|--------|\\n| Non-numeric `from`/`to` | 400 | `createError` in param middleware |\\n| User ID out of bounds | 404 | `createError` in param middleware |\\n\\nErrors propagate through Express's middleware chain via `next(err)`, triggering default or configured error handlers.\\n\\n## Bootstrapping\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\nConditional server startup enables both standalone execution (`node index.js`) and test/module importing without port binding. The `module.exports = app` assignment at the top supports the latter pattern.\\n\\n## Key Dependencies\\n\\n- `express` \u2014 web framework (loaded from `../../` relative path, indicating this is within the Express repository)\\n- `http-errors` \u2014 HTTP error object factory for consistent error responses\\n\\n## Integration with Express Core\\n\\nThis example exercises `app.param()` and `req.params`, features implemented in Express's router layer. The `../../` require path suggests this module lives within the Express source tree, serving as a functional test and documentation reference for parameter middleware behavior.\",\"route-separation-example\":\"# Route Separation Example\\n\\n# Route Separation Example\\n\\nAn Express.js application demonstrating how to organize routes into separate modules by domain concern (site, user, post) rather than defining all handlers in a single file.\\n\\n## Purpose\\n\\nThis example illustrates a common pattern for scaling Express applications: splitting route handlers into dedicated modules based on functional area. Each module (`site.js`, `user.js`, `post.js`) exports handler functions that the main application file wires to specific HTTP methods and paths.\\n\\n## Application Entry Point (`index.js`)\\n\\nThe main application file configures Express, sets up middleware, and maps URL patterns to handler functions imported from domain modules.\\n\\n```javascript\\nvar site = require('./site');\\nvar post = require('./post');\\nvar user = require('./user');\\n```\\n\\n### Configuration\\n\\n| Setting | Value | Purpose |\\n|---------|-------|---------|\\n| `view engine` | `ejs` | Uses EJS templating with `&lt;% %&gt;` syntax |\\n| `views` | `./views` | Resolves view templates relative to `__dirname` |\\n\\n### Middleware Stack\\n\\nMiddleware applies in registration order:\\n\\n```javascript\\napp.use(methodOverride('_method'));   // Allow POST-to-PUT override via ?_method=put\\napp.use(cookieParser());              // Parse Cookie header into req.cookies\\napp.use(express.urlencoded({ extended: true }));  // Parse form submissions\\napp.use(express.static(path.join(__dirname, 'public')));  // Serve CSS/assets\\n```\\n\\n`method-override` enables RESTful updates from HTML forms (which only natively support GET/POST) by reading the `_method` query parameter.\\n\\n### Route Table\\n\\n| Method | Path | Handler | Module |\\n|--------|------|---------|--------|\\n| GET | `/` | `site.index` | site |\\n| GET | `/users` | `user.list` | user |\\n| ALL | `/user/:id{/:op}` | `user.load` | user |\\n| GET | `/user/:id` | `user.view` | user |\\n| GET | `/user/:id/view` | `user.view` | user |\\n| GET | `/user/:id/edit` | `user.edit` | user |\\n| PUT | `/user/:id/edit` | `user.update` | user |\\n| GET | `/posts` | `post.list` | post |\\n\\nThe `app.all('/user/:id{/:op}', user.load)` pattern uses Express's parameter matching to preload user data for any `/user/:id/*` route. The `{/:op}` makes the operation segment optional.\\n\\n## Domain Modules\\n\\n### `site.js`\\n\\nSingle handler for the application root:\\n\\n```javascript\\nexports.index = function(req, res){\\n  res.render('index', { title: 'Route Separation Example' });\\n};\\n```\\n\\n### `post.js`\\n\\nManages the fake posts \\\"database\\\" (an in-memory array) and renders the posts list:\\n\\n```javascript\\nexports.list = function(req, res){\\n  res.render('posts', { title: 'Posts', posts: posts });\\n};\\n```\\n\\n### `user.js`\\n\\nMost complex module, implementing full CRUD-like patterns with a fake users array:\\n\\n| Export | Type | Purpose |\\n|--------|------|---------|\\n| `list` | Handler | Renders all users |\\n| `load` | Middleware | Populates `req.user` by array index; 404s if missing |\\n| `view` | Handler | Renders user detail page |\\n| `edit` | Handler | Renders edit form pre-filled with user data |\\n| `update` | Handler | Applies form data to user object, redirects back |\\n\\nThe `load` middleware demonstrates parameter-based preloading:\\n\\n```javascript\\nexports.load = function(req, res, next){\\n  var id = req.params.id;\\n  req.user = users[id];\\n  if (req.user) {\\n    next();  // Continue to route-specific handler\\n  } else {\\n    var err = new Error('cannot find user ' + id);\\n    err.status = 404;\\n    next(err);  // Skip to error handler\\n  }\\n};\\n```\\n\\n## View Templates\\n\\nTemplates use EJS includes for shared layout (`header.ejs`, `footer.ejs`).\\n\\n```\\nviews/\\n\u251c\u2500\u2500 header.ejs      # HTML boilerplate, loads /style.css\\n\u251c\u2500\u2500 footer.ejs      # Closing body/html tags\\n\u251c\u2500\u2500 index.ejs       # Landing page with navigation links\\n\u251c\u2500\u2500 posts/\\n\u2502   \u2514\u2500\u2500 index.ejs   # Definition list of post title/body pairs\\n\u2514\u2500\u2500 users/\\n    \u251c\u2500\u2500 index.ejs   # User list with links to view/edit\\n    \u251c\u2500\u2500 view.ejs    # Read-only user detail\\n    \u2514\u2500\u2500 edit.ejs    # Form with ?_method=put override\\n```\\n\\nThe edit form demonstrates the method-override pattern:\\n\\n```html\\n\n\\n  \\n&lt;\\/form&gt;\\n```\\n\\nThis submits as POST, which `methodOverride('_method')` converts to PUT based on the query string.\\n\\n## Request Flow Architecture\\n\\n```mermaid\\nflowchart LR\\n    A[HTTP Request] --&gt; B[Express Middleware]\\n    B --&gt; C{Route Match?}\\n    C --&gt;|/user/:id/*| D[user.load]\\n    C --&gt;|/posts| E[post.list]\\n    C --&gt;|/| F[site.index]\\n    D --&gt;|next()| G[user.view|edit|update]\\n    D --&gt;|next(err)| H[Error Handler]\\n    G --&gt; I[EJS Render]\\n    E --&gt; I\\n    F --&gt; I\\n```\\n\\n## Key Patterns Demonstrated\\n\\n1. **Module separation by domain**: Each functional area (user, post, site) owns its handlers\\n2. **Middleware-based parameter loading**: `user.load` pre-populates `req.user` for all user-scoped routes\\n3. **RESTful form submissions**: `method-override` bridges HTML form limitations with HTTP verbs\\n4. **Conditional bootstrapping**: `if (!module.parent)` guards direct execution vs. require-as-module\\n\\n## Running the Example\\n\\n```bash\\nnode examples/route-separation/index.js\\n```\\n\\nServer starts on port 3000. The `module.parent` check allows the file to be both a standalone script and a testable module export.\",\"search-example\":\"# Search Example\\n\\n# Search Example\\n\\nA minimal Express application demonstrating real-time search backed by Redis. This example shows how to serve a static search interface, query Redis sets via AJAX, and return matching results without page reloads.\\n\\n## Architecture Overview\\n\\nThe application consists of three layers: a browser-based client, an Express server, and Redis for data storage. The client captures keystrokes and queries the server; the server looks up values in pre-populated Redis sets and returns JSON arrays.\\n\\n```mermaid\\nflowchart LR\\n    Browser[\\\"Browser(client.js)\\\"] --&gt;|GET /search/:query| Express[\\\"Express Server(index.js)\\\"]\\n    Express --&gt;|sMembers| Redis[(Redis)]\\n    Redis --&gt;|string[]| Express\\n    Express --&gt;|JSON| Browser\\n```\\n\\n## Server (`index.js`)\\n\\n### Redis Setup\\n\\nThe server connects to Redis and seeds two search categories as sets:\\n\\n| Key | Members |\\n|-----|---------|\\n| `ferret` | `tobi`, `loki`, `jane` |\\n| `cat` | `manny`, `luna` |\\n\\n```javascript\\nasync function initializeRedis() {\\n  await db.connect();\\n  await db.sAdd('ferret', 'tobi');\\n  // ... additional seed data\\n}\\n```\\n\\nThis function runs before the server starts accepting connections. On failure, it logs the error and exits with code `1`.\\n\\n### Routes\\n\\n| Route | Handler | Purpose |\\n|-------|---------|---------|\\n| `GET /search/{:query}` | `db.sMembers(query)` | Returns array of members for the given set key, or `[]` if key doesn't exist |\\n| `GET /client.js` | `res.sendFile()` | Serves the client-side JavaScript explicitly (excluded from static middleware to avoid serving server files) |\\n\\nThe search route uses `req.params.query` (defaulting to empty string) and delegates to Redis's `sMembers`. Errors are passed to Express error handling via `next(err)`.\\n\\n### Static Files\\n\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\n\\nThe `public/` directory serves `index.html` and any other assets. `client.js` is deliberately excluded from this middleware and served via explicit route to prevent leaking `index.js` or template files.\\n\\n## Client (`public/client.js`)\\n\\nThe client implements live search with `XMLHttpRequest`:\\n\\n1. Captures `keyup` events on the `` element\\n2. Issues `GET /search/{value}` for every keystroke\\n3. Replaces `\n` content with raw response text on `readyState === 4`\\n\\nNo debouncing is implemented\u2014every keystroke triggers a network request.\\n\\n## Entry Point (`public/index.html`)\\n\\nProvides the search interface with two hardcoded suggestions (\\\"ferret\\\" or \\\"cat\\\") and loads `client.js`.\\n\\n## Integration with Express\\n\\nThis example imports Express via a relative path:\\n\\n```javascript\\nvar express = require('../..');\\n```\\n\\nThis resolves to the Express package root two directories above, typical of the `examples/` directory structure in the Express repository. The `module.parent` check allows the file to be imported in tests without starting the server:\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n}\\n```\\n\\n## Running the Example\\n\\nPrerequisites: Redis server running locally.\\n\\n```bash\\n# Install dependencies\\nnpm install redis\\n\\n# Start Redis\\nredis-server\\n\\n# Start the application\\nnode examples/search/index.js\\n```\\n\\nThen open `http://localhost:3000` and type in the search field.\",\"session-example\":\"# Session Example\\n\\n# Session Example Module\\n\\nTwo example applications demonstrating Express session management using `express-session`, with both in-memory and Redis-backed storage.\\n\\n## Files\\n\\n| File | Purpose |\\n|------|---------|\\n| `index.js` | Basic session example with default in-memory store |\\n| `redis.js` | Production-oriented example using Redis as session store |\\n\\n---\\n\\n## `index.js` \u2014 In-Memory Session Store\\n\\nMinimal demonstration of session middleware. Uses the default `MemoryStore` (not suitable for production).\\n\\n### Prerequisites\\n\\n```bash\\nnpm install express-session\\n```\\n\\n### Configuration\\n\\n```javascript\\napp.use(session({\\n  resave: false,           // Skip save if session unmodified\\n  saveUninitialized: false, // Skip creating empty sessions\\n  secret: 'keyboard cat'    // Signing key for session cookie\\n}));\\n```\\n\\n### Session Logic\\n\\nThe root route implements a page view counter:\\n\\n| Condition | Behavior |\\n|-----------|----------|\\n| `req.session.views` exists | Increment counter |\\n| First visit | Initialize counter to `1`, show welcome message |\\n\\n```javascript\\napp.get('/', function(req, res){\\n  var body = '';\\n  if (req.session.views) {\\n    ++req.session.views;\\n  } else {\\n    req.session.views = 1;\\n    body += '\nFirst time visiting? view this page in several browsers :)&lt;\\/p&gt;';\\n  }\\n  res.send(body + '\nviewed ' + req.session.views + '&lt;\\/strong&gt; times.&lt;\\/p&gt;');\\n});\\n```\\n\\n### Startup Behavior\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\nThe `!module.parent` guard allows the file to be required in tests without starting the server.\\n\\n---\\n\\n## `redis.js` \u2014 Redis-Backed Session Store\\n\\nExtends the basic example with persistent, shared session storage suitable for production deployments.\\n\\n### Prerequisites\\n\\n```bash\\n# Install and start Redis server\\n# https://redis.io/\\n\\nnpm install redis morgan connect-redis express-session\\nredis-server\\n```\\n\\n### Architecture\\n\\n```mermaid\\ngraph LR\\n    A[Client] --&gt;|HTTP| B[Express]\\n    B --&gt;|req.session| C[express-session]\\n    C --&gt;|read/write| D[RedisStore]\\n    D --&gt;|TCP| E[(Redis)]\\n    B --&gt;F[morganlogging]\\n```\\n\\n### Store Initialization\\n\\n`connect-redis` requires the `session` object to inherit from `session.Store`:\\n\\n```javascript\\nvar RedisStore = require('connect-redis')(session);\\n```\\n\\nThis pattern\u2014passing `session` to the factory function\u2014is specific to `connect-redis` versions compatible with `express-session` 1.x.\\n\\n### Middleware Stack\\n\\n```javascript\\napp.use(logger('dev'));    // Request logging\\n\\napp.use(session({\\n  resave: false,\\n  saveUninitialized: false,\\n  secret: 'keyboard cat',\\n  store: new RedisStore    // &lt;-- Redis instead of MemoryStore\\n}));\\n```\\n\\n### Route Handler\\n\\nIdentical to `index.js`\u2014the store implementation is transparent to route code.\\n\\n---\\n\\n## Key Differences\\n\\n| Aspect | `index.js` | `redis.js` |\\n|--------|-----------|------------|\\n| **Store** | `MemoryStore` (default) | `RedisStore` |\\n| **Persistence** | Process lifetime only | Survives restarts, shared across instances |\\n| **Logging** | None | `morgan` dev format |\\n| **Startup** | Conditional (`!module.parent`) | Unconditional |\\n| **Production suitability** | No | Yes |\\n\\n---\\n\\n## Integration with Express\\n\\nBoth examples use `require('../..')` to load Express from the repository root, making them self-testing against the local codebase rather than an installed npm package.\\n\\nThe `res.send` calls route through Express's response machinery (`test/Router.js` in the call graph), demonstrating standard response flow with session-populated dynamic content.\",\"static-files-example\":\"# Static Files Example\\n\\n# Static Files Example\\n\\nAn Express.js application demonstrating how to serve static files using the `express.static()` middleware with multiple mounting strategies.\\n\\n## Purpose\\n\\nThis example shows developers how to:\\n- Serve static assets (HTML, CSS, JS, text files) from a filesystem directory\\n- Mount static file serving at URL prefixes\\n- Combine multiple static directories with different URL mappings\\n\\n## Architecture\\n\\n```\\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\u2502   HTTP Client   \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  Express App    \u2502\u2500\u2500\u2500\u2500\u25b6\u2502  morgan logger  \u2502\\n\u2502  (browser/curl) \u2502     \u2502   (port 3000)   \u2502     \u2502  (request log)  \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                \u2502\\n                                \u25bc\\n                       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                       \u2502 express.static  \u2502\\n                       \u2502   middlewares   \u2502\\n                       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n                                \u2502\\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n                    \u25bc           \u25bc           \u25bc\\n              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n              \u2502 /public \u2502 \u2502/public  \u2502 \u2502/public  \u2502\\n              \u2502  (root) \u2502 \u2502/static  \u2502 \u2502  /css   \u2502\\n              \u2502         \u2502 \u2502 prefix  \u2502 \u2502         \u2502\\n              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n```\\n\\n## Application Setup\\n\\n```javascript\\nvar express = require('../..');   // Express framework (local build)\\nvar logger = require('morgan');    // HTTP request logging\\nvar path = require('node:path');   // Cross-platform path resolution\\nvar app = express();\\n```\\n\\nThe example uses a relative require (`'../..'`) because it lives within the Express repository's `examples/` directory, loading the local Express build rather than an npm-installed version.\\n\\n## Middleware Stack\\n\\n| Order | Middleware | Configuration | Purpose |\\n|-------|-----------|---------------|---------|\\n| 1 | `logger('dev')` | default dev format | Log request method, URL, status, response time |\\n| 2 | `express.static(path.join(__dirname, 'public'))` | root mount `/` | Serve files from `./public` at URL root |\\n| 3 | `express.static(path.join(__dirname, 'public'))` | mount path `/static` | Same files, accessible via `/static/` prefix |\\n| 4 | `express.static(path.join(__dirname, 'public', 'css'))` | root mount `/` | Serve CSS files directly from root URL |\\n\\n## Static File Resolution\\n\\n### Mount Point 1: Root (`/`)\\n\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public')));\\n```\\n\\n| Request URL | Filesystem Path | Result |\\n|-------------|-----------------|--------|\\n| `GET /hello.txt` | `./public/hello.txt` | \u2705 \\\"hey\\\" |\\n| `GET /js/app.js` | `./public/js/app.js` | \u2705 `// foo` |\\n| `GET /css/style.css` | `./public/css/style.css` | \u2705 `body { }` |\\n\\n### Mount Point 2: Prefixed (`/static`)\\n\\n```javascript\\napp.use('/static', express.static(path.join(__dirname, 'public')));\\n```\\n\\nThe mount path `/static` is stripped before `express.static` processes the request:\\n\\n| Request URL | Internal Path | Filesystem Path | Result |\\n|-------------|-------------|-----------------|--------|\\n| `GET /static/hello.txt` | `/hello.txt` | `./public/hello.txt` | \u2705 \\\"hey\\\" |\\n| `GET /static/js/app.js` | `/js/app.js` | `./public/js/app.js` | \u2705 `// foo` |\\n\\n### Mount Point 3: Additional Directory (`/`)\\n\\n```javascript\\napp.use(express.static(path.join(__dirname, 'public', 'css')));\\n```\\n\\nThis creates a fallback search path. Files in `./public/css/` become accessible at the URL root:\\n\\n| Request URL | Searches | Resolved Path | Result |\\n|-------------|----------|---------------|--------|\\n| `GET /style.css` | `./public/style.css` (first mount) \u2192 `./public/css/style.css` (second mount) | `./public/css/style.css` | \u2705 `body { }` |\\n\\n&gt; **Note:** The first `express.static` mount attempts `./public/style.css` first. If not found, Express continues to the next matching middleware. Since `./public/css/style.css` exists, the second mount serves it as `/style.css`.\\n\\n## Request Flow\\n\\n```mermaid\\nsequenceDiagram\\n    participant Client\\n    participant Express\\n    participant Logger\\n    participant Static1 as static(/public)\\n    participant Static2 as static(/static)\\n    participant Static3 as static(/public/css)\\n    participant FS as Filesystem\\n\\n    Client-&gt;&gt;Express: GET /js/app.js\\n    Express-&gt;&gt;Logger: log request\\n    Logger--&gt;&gt;Express: continue\\n    Express-&gt;&gt;Static1: try /js/app.js\\n    Static1-&gt;&gt;FS: read ./public/js/app.js\\n    FS--&gt;&gt;Static1: file content\\n    Static1--&gt;&gt;Express: serve file\\n    Express--&gt;&gt;Client: 200 OK + app.js\\n\\n    Client-&gt;&gt;Express: GET /static/hello.txt\\n    Express-&gt;&gt;Logger: log request\\n    Express-&gt;&gt;Static2: strip /static, try /hello.txt\\n    Static2-&gt;&gt;FS: read ./public/hello.txt\\n    FS--&gt;&gt;Static2: \\\"hey\\\"\\n    Static2--&gt;&gt;Express: serve file\\n    Express--&gt;&gt;Client: 200 OK + \\\"hey\\\"\\n```\\n\\n## File Structure\\n\\n```\\nexamples/static-files/\\n\u251c\u2500\u2500 index.js              # Application entry point\\n\u2514\u2500\u2500 public/               # Static asset root\\n    \u251c\u2500\u2500 hello.txt         # Plain text sample\\n    \u251c\u2500\u2500 js/\\n    \u2502   \u2514\u2500\u2500 app.js        # JavaScript sample\\n    \u2514\u2500\u2500 css/\\n        \u2514\u2500\u2500 style.css     # Stylesheet sample\\n```\\n\\n## Running the Example\\n\\n```bash\\nnode examples/static-files/index.js\\n```\\n\\nConsole output:\\n```\\nlistening on port 3000\\ntry:\\n  GET /hello.txt\\n  GET /js/app.js\\n  GET /css/style.css\\n```\\n\\n## Test Commands\\n\\n```bash\\n# Root-mounted files\\ncurl http://localhost:3000/hello.txt\\ncurl http://localhost:3000/js/app.js\\ncurl http://localhost:3000/css/style.css\\n\\n# Prefixed access to same files\\ncurl http://localhost:3000/static/hello.txt\\ncurl http://localhost:3000/static/js/app.js\\n\\n# Direct CSS access via additional mount\\ncurl http://localhost:3000/style.css\\n```\\n\\n## Key Patterns Demonstrated\\n\\n| Pattern | Code | Use Case |\\n|---------|------|----------|\\n| Basic static serving | `app.use(express.static('public'))` | Simple asset hosting |\\n| URL prefixing | `app.use('/static', express.static(...))` | Versioned assets, CDN paths |\\n| Multiple search paths | Multiple `express.static()` calls | Flattened URLs, fallback directories |\\n\\n## Connection to Express Core\\n\\nThis example directly exercises the `express.static` middleware, which is a thin wrapper around the `serve-static` npm package bundled with Express. The `require('../..')` pattern demonstrates that examples run against the local Express source, making this useful for:\\n- Verifying `express.static` behavior during Express development\\n- Testing middleware mounting logic\\n- Validating path resolution across platforms\",\"view-constructor-example\":\"# View Constructor Example\\n\\n# View Constructor Example\\n\\nThis example demonstrates how to replace Express's default view system with a custom `View` constructor that loads templates from remote sources \u2014 specifically, GitHub's raw content CDN. Instead of reading templates from the local filesystem, `GithubView` fetches them over HTTPS at render time.\\n\\n## Architecture Overview\\n\\nThe module consists of two files that work together to override Express's view resolution and rendering pipeline:\\n\\n```mermaid\\nflowchart LR\\n    subgraph Express[\\\"Express Application\\\"]\\n        direction TB\\n        A[\\\"app.set('view', GithubView)\\\"]\\n        B[\\\"app.engine('md', ...)\\\"]\\n        C[\\\"res.render('path/to/file.md')\\\"]\\n    end\\n    \\n    subgraph GithubView[\\\"GithubView Instance\\\"]\\n        D[\\\"constructor(name, options)\\\"]\\n        E[\\\"render(options, fn)\\\"]\\n    end\\n    \\n    subgraph Remote[\\\"GitHub Raw CDN\\\"]\\n        F[\\\"raw.githubusercontent.com\\\"]\\n    end\\n    \\n    C --&gt; D\\n    D --&gt; E\\n    E --&gt;|HTTPS GET| F\\n    F --&gt;|template string| E\\n    E --&gt;|engine(buf, options, fn)| B\\n    B --&gt;|fn(null, html)| C\\n```\\n\\n## Components\\n\\n### `github-view.js`\\n\\nCustom view constructor implementing the interface Express expects from a view class.\\n\\n#### `GithubView(name, options)`\\n\\n| Parameter | Description |\\n|-----------|-------------|\\n| `name` | Template identifier passed to `res.render()`, e.g. `'examples/markdown/views/index.md'` |\\n| `options` | Configuration object from Express, including `options.engines` and `options.root` |\\n\\nThe constructor resolves the template engine by mapping the file extension through `options.engines`, and constructs a GitHub raw URL path from `options.root` (configured as `app.set('views', ...)`).\\n\\n```javascript\\nthis.engine = options.engines[extname(name)];  // looks up 'md' \u2192 marked renderer\\nthis.path = '/' + options.root + '/master/' + name;  // e.g. /expressjs/express/master/Readme.md\\n```\\n\\n#### `GithubView.prototype.render(options, fn)`\\n\\nFetches the remote template via HTTPS, then delegates to the registered engine for actual string-to-HTML transformation.\\n\\nThe callback signature `fn(err, html)` matches Express's internal expectations, allowing seamless integration with `res.render()`.\\n\\n### `index.js`\\n\\nApplication bootstrap that wires the custom view system into Express.\\n\\n| Configuration | Purpose |\\n|---------------|---------|\\n| `app.engine('md', ...)` | Registers `.md` extension handler using `marked.parse` with `{name}` interpolation |\\n| `app.set('views', 'expressjs/express')` | Sets target GitHub repo; consumed by `GithubView` as `options.root` |\\n| `app.set('view', GithubView)` | **Replaces** Express's default `View` class with `GithubView` |\\n\\n## Template Engine: Markdown with Interpolation\\n\\nThe registered `'md'` engine extends `marked.parse` with simple variable substitution:\\n\\n```javascript\\nhtml = html.replace(/\\\\{([^}]+)\\\\}/g, function(_, name){\\n  return options[name] || '';\\n});\\n```\\n\\nThis allows templates from GitHub to reference `app.locals`, `res.locals`, or directly-passed locals like `{ title: 'Example' }`.\\n\\n## Usage Patterns\\n\\n### Render with explicit locals\\n```javascript\\nres.render('examples/markdown/views/index.md', { title: 'Example' });\\n```\\n\\n### Render with no additional locals\\n```javascript\\nres.render('Readme.md');\\n// relies on any pre-configured app.locals or res.locals\\n```\\n\\n## Key Integration Points\\n\\n| Express Default | This Example's Override |\\n|---------------|------------------------|\\n| `express/lib/view.js` | `GithubView` |\\n| Local filesystem lookup (`path.join(viewsDir, name)`) | HTTPS fetch from `raw.githubusercontent.com` |\\n| Synchronous `fs.readFile` | Async `https.request` with buffered response |\\n\\nThe `GithubView` must conform to Express's internal view contract: expose a `render(options, fn)` method that ultimately calls `fn(err, html)` with rendered output. The constructor receives `(name, options)` where `options.engines` contains all registered engines and `options.root` holds the `views` setting.\",\"view-locals-example\":\"# View Locals Example\\n\\n# View Locals Example\\n\\nAn Express.js example demonstrating three progressively cleaner approaches to passing data to EJS views, illustrating the evolution from nested callbacks to middleware-based `res.locals`.\\n\\n## Purpose\\n\\nThis example teaches patterns for sharing data between asynchronous operations and view templates. It compares callback nesting, request object attachment, and `res.locals` \u2014 Express's dedicated mechanism for view-local variables.\\n\\n## Module Structure\\n\\n| File | Role |\\n|------|------|\\n| `index.js` | Express application with three route implementations |\\n| `user.js` | Faux user model with async `all()` and `count()` methods |\\n| `views/index.ejs` | Template rendering user list with `title`, `count`, and `users` |\\n\\n## User Model\\n\\n`user.js` exports a constructor and two static methods simulating database access via `process.nextTick`:\\n\\n```javascript\\nUser.all(fn)    // fn(err, users) \u2014 returns all users\\nUser.count(fn)  // fn(err, count) \u2014 returns total user count\\n```\\n\\nThe faux database contains five users: three ferrets (`Tobi`, `Loki`, `Jane`) and two cats (`Luna`, `Manny`).\\n\\n## Route Implementations\\n\\n### Approach 1: Nested Callbacks (`GET /`)\\n\\nThe naive implementation nests `User.count` inside `User.all`, passing locals directly to `res.render()`:\\n\\n```javascript\\napp.get('/', function(req, res, next){\\n  User.count(function(err, count){\\n    if (err) return next(err);\\n    User.all(function(err, users){\\n      if (err) return next(err);\\n      res.render('index', {\\n        title: 'Users',\\n        count: count,\\n        users: users.filter(ferrets)\\n      });\\n    })\\n  })\\n});\\n```\\n\\n**Drawback**: Deep nesting; `count` and `users` are trapped in closure scope, unavailable to other middleware.\\n\\n### Approach 2: Middleware with `req` Attachment (`GET /middleware`)\\n\\nExtracts data fetching into reusable middleware, attaching results to `req`:\\n\\n```javascript\\nfunction count(req, res, next) {\\n  User.count(function(err, count){\\n    if (err) return next(err);\\n    req.count = count;\\n    next();\\n  })\\n}\\n\\nfunction users(req, res, next) {\\n  User.all(function(err, users){\\n    if (err) return next(err);\\n    req.users = users;\\n    next();\\n  })\\n}\\n\\napp.get('/middleware', count, users, function (req, res) {\\n  res.render('index', {\\n    title: 'Users',\\n    count: req.count,\\n    users: req.users.filter(ferrets)\\n  });\\n});\\n```\\n\\n**Advantage**: Flat structure, reusable middleware, filtering deferred to final handler.\\n\\n### Approach 3: Middleware with `res.locals` (`GET /middleware-locals`)\\n\\nExplicitly exposes locals to the view layer, minimizing `res.render()` arguments:\\n\\n```javascript\\nfunction count2(req, res, next) {\\n  User.count(function(err, count){\\n    if (err) return next(err);\\n    res.locals.count = count;\\n    next();\\n  })\\n}\\n\\nfunction users2(req, res, next) {\\n  User.all(function(err, users){\\n    if (err) return next(err);\\n    res.locals.users = users.filter(ferrets);\\n    next();\\n  })\\n}\\n\\napp.get('/middleware-locals', count2, users2, function (req, res) {\\n  res.render('index', { title: 'Users' });  // count, users auto-available\\n});\\n```\\n\\n**Trade-off**: Filtering occurs in middleware, reducing flexibility for routes needing unfiltered data.\\n\\n## Data Flow Comparison\\n\\n```mermaid\\nflowchart LR\\n    A[HTTP Request] --&gt; B{Approach}\\n    \\n    B --&gt;|Nested| C[Single HandlerUser.count \u2192 User.allres.render with all locals]\\n    B --&gt;|req.*| D[count middlewareusers middlewarefilter in handler]\\n    B --&gt;|res.locals| E[count2 middlewareusers2 middlewareminimal res.render]\\n    \\n    C --&gt; F[EJS Template]\\n    D --&gt; F\\n    E --&gt; F\\n```\\n\\n## Global Locals Pattern\\n\\nThe commented sections demonstrate applying locals across route scopes:\\n\\n```javascript\\n// All routes\\napp.use(function(req, res, next){\\n  res.locals.user = req.user;\\n  res.locals.sess = req.session;\\n  next();\\n});\\n\\n// Prefixed routes only\\napp.use('/api', function(req, res, next){\\n  res.locals.user = req.user;\\n  res.locals.sess = req.session;\\n  next();\\n});\\n\\n// Route-pattern equivalent\\napp.all('/api/*', function(req, res, next){\\n  res.locals.user = req.user;\\n  res.locals.sess = req.session;\\n  next();\\n});\\n```\\n\\n## View Template\\n\\n`views/index.ejs` expects three locals:\\n\\n| Local | Usage |\\n|-------|-------|\\n| `title` | Page `` and `\n` heading |\\n| `users` | Array iterated with `forEach` to list users |\\n| `count` | *Declared in code but unused in template* \u2014 available for extension |\\n\\nNote: The template contains a typo (`&lt;% user.age %&gt;` without `=`) preventing age display.\\n\\n## Running the Example\\n\\n```bash\\nnode examples/view-locals/index.js\\n```\\n\\nThe server listens on port 3000 when invoked directly (`!module.parent`). Visit:\\n- `http://localhost:3000/` \u2014 nested approach\\n- `http://localhost:3000/middleware` \u2014 `req` attachment\\n- `http://localhost:3000/middleware-locals` \u2014 `res.locals`\",\"virtual-hosts-example\":\"# Virtual Hosts Example\\n\\n# Virtual Hosts Example\\n\\nDemonstrates Express.js virtual host routing using the `vhost` middleware to serve different applications based on the hostname in incoming requests.\\n\\n## Overview\\n\\nThis example sets up a single Express server that handles three hostnames\u2014`example.com`, `foo.example.com`, and `bar.example.com`\u2014by routing each to distinct application logic. Wildcard subdomains redirect to the main domain with the subdomain preserved as a path segment, while the apex domain serves content directly.\\n\\n## Architecture\\n\\n```mermaid\\nflowchart LR\\n    subgraph Hostnames\\n        A[*.example.com]\\n        B[example.com]\\n    end\\n    subgraph Apps\\n        C[Redirect App]\\n        D[Main App]\\n    end\\n    A --&gt;|vhost wildcard| C\\n    B --&gt;|vhost exact| D\\n    C --&gt;|302 redirect| D\\n```\\n\\n## Components\\n\\n### Main Application (`main`)\\n\\nThe primary content server. Handles requests for the apex domain `example.com`.\\n\\n| Route | Response |\\n|-------|----------|\\n| `GET /` | `\\\"Hello from main app!\\\"` |\\n| `GET /:sub` | `\\\"requested {sub}\\\"` |\\n\\n```javascript\\nvar main = express();\\n\\nmain.get('/', function(req, res){\\n  res.send('Hello from main app!');\\n});\\n\\nmain.get('/:sub', function(req, res){\\n  res.send('requested ' + req.params.sub);\\n});\\n```\\n\\nThe `/:sub` route captures any single path segment, making `http://example.com:3000/foo` respond with `\\\"requested foo\\\"`.\\n\\n### Redirect Application (`redirect`)\\n\\nHandles all wildcard subdomain matches. Logs the parsed `vhost` object (when run standalone), then issues a 302 redirect to the main domain with the subdomain name appended as a path.\\n\\n```javascript\\nvar redirect = express();\\n\\nredirect.use(function(req, res){\\n  if (!module.parent) console.log(req.vhost);\\n  res.redirect('http://example.com:3000/' + req.vhost[0]);\\n});\\n```\\n\\nThe `req.vhost` property is populated by the `vhost` middleware as an array of captured groups. For `foo.example.com`, `req.vhost[0]` equals `\\\"foo\\\"`, producing a redirect to `http://example.com:3000/foo`.\\n\\n### VHost Router (`app`)\\n\\nThe top-level Express application that composes the `vhost` middleware instances. Registration order matters: more specific or wildcard patterns should typically precede exact matches if they overlap, though in this case `*.example.com` and `example.com` are disjoint.\\n\\n```javascript\\nvar app = module.exports = express();\\n\\napp.use(vhost('*.example.com', redirect));\\napp.use(vhost('example.com', main));\\n```\\n\\n## Execution Modes\\n\\nThe example supports two execution contexts controlled by `module.parent`:\\n\\n| Context | Behavior |\\n|---------|----------|\\n| **Required as module** (`module.parent` truthy) | Exports `app` without starting server or logging; omits `morgan` logger |\\n| **Run directly** (`node examples/vhost/index.js`) | Binds to port 3000, enables request logging, prints startup message, logs `req.vhost` objects |\\n\\n```javascript\\nif (!module.parent) {\\n  app.listen(3000);\\n  console.log('Express started on port 3000');\\n}\\n```\\n\\n## Local Testing Setup\\n\\nThe example requires `/etc/hosts` entries for local resolution:\\n\\n```\\n127.0.0.1  foo.example.com\\n127.0.0.1  bar.example.com\\n127.0.0.1  example.com\\n```\\n\\n### Request Flow Examples\\n\\n| Request | Host Matched | Handling Application | Result |\\n|---------|-------------|----------------------|--------|\\n| `GET http://example.com:3000/` | `example.com` | `main` | `\\\"Hello from main app!\\\"` |\\n| `GET http://foo.example.com:3000/` | `*.example.com` | `redirect` | 302 \u2192 `http://example.com:3000/foo` |\\n| `GET http://bar.example.com:3000/` | `*.example.com` | `redirect` | 302 \u2192 `http://example.com:3000/bar` |\\n\\n## Dependencies\\n\\n- **`../..`** \u2014 Express framework (relative path resolves to repository root)\\n- **`morgan`** \u2014 HTTP request logger (`dev` format)\\n- **`vhost`** \u2014 Virtual host middleware; parses `Host` header and mounts sub-applications conditionally\",\"web-service-example\":\"# Web Service Example\\n\\n# Web Service Example\\n\\nA minimal REST API demonstrating Express middleware patterns, API key validation, error handling, and content negotiation through JSON responses.\\n\\n## Overview\\n\\nThis module implements a read-only web service that exposes user and repository data through authenticated endpoints. It demonstrates several core Express concepts:\\n\\n- **Path-specific middleware** for API key validation on `/api` routes\\n- **Custom error objects** with HTTP status codes\\n- **Error handling middleware** (arity of 4)\\n- **Fallback 404 handler** as terminal middleware\\n- **In-memory data stores** simulating database access\\n\\n## Request Flow\\n\\n```mermaid\\nflowchart LR\\n    A[Client Request] --&gt; B{Path startswith /api?}\\n    B --&gt;|Yes| C[API Key Validation]\\n    B --&gt;|No| G[404 Handler]\\n    C --&gt;|Invalid| D[Error Handler]\\n    C --&gt;|Valid| E[Route Handler]\\n    E --&gt; F[JSON Response]\\n    E --&gt;|Not Found| G\\n    G --&gt; H[404 JSON Response]\\n    D --&gt; I[Error JSON Response]\\n```\\n\\n## Module Exports\\n\\nThe Express application is exported directly, enabling testing and mounting in parent applications:\\n\\n```javascript\\nvar app = module.exports = express();\\n```\\n\\nThe server only binds to port 3000 when this file is the entry point (`!module.parent`), preventing port conflicts during testing or when imported as a submodule.\\n\\n## API Key Validation Middleware\\n\\nMounted at `/api`, this middleware intercepts all routes under that path prefix:\\n\\n```javascript\\napp.use('/api', function(req, res, next){\\n  var key = req.query['api-key'];\\n\\n  if (!key) return next(error(400, 'api key required'));\\n  if (apiKeys.indexOf(key) === -1) return next(error(401, 'invalid api key'))\\n\\n  req.key = key;  // Stashed for downstream route access\\n  next();\\n});\\n```\\n\\nKey behaviors:\\n- Returns `400` when `api-key` query parameter is missing\\n- Returns `401` when the key is not in the `apiKeys` whitelist\\n- Stores validated key on `req.key` for potential rate-limiting or audit logging by route handlers\\n\\n## Error Factory\\n\\nThe `error()` helper creates Error instances with an attached `.status` property, which both Express and Connect recognize for HTTP status code propagation:\\n\\n```javascript\\nfunction error(status, msg) {\\n  var err = new Error(msg);\\n  err.status = status;\\n  return err;\\n}\\n```\\n\\nThis pattern allows middleware to remain agnostic about response formatting\u2014the error handler centralizes how errors are serialized.\\n\\n## Data Layer\\n\\nThree in-memory structures simulate persistent storage:\\n\\n| Variable | Type | Purpose |\\n|----------|------|---------|\\n| `apiKeys` | `Array` | Valid API key whitelist |\\n| `repos` | `Array&lt;{name, url}&gt;` | Global repository catalog |\\n| `users` | `Array&lt;{name}&gt;` | User directory |\\n| `userRepos` | `Object&gt;` | User-to-repository mapping |\\n\\n## Route Handlers\\n\\n| Method | Path | Description | Example |\\n|--------|------|-------------|---------|\\n| GET | `/api/users` | List all users | `?api-key=foo` |\\n| GET | `/api/repos` | List all repositories | `?api-key=foo` |\\n| GET | `/api/user/:name/repos` | Repositories for specific user | `/user/tobi/repos?api-key=foo` |\\n\\nThe user repository route demonstrates parametric routing with fallback to `next()` for 404 handling:\\n\\n```javascript\\napp.get('/api/user/:name/repos', function(req, res, next){\\n  var name = req.params.name;\\n  var user = userRepos[name];\\n\\n  if (user) res.send(user);\\n  else next();  // Falls through to 404 handler\\n});\\n```\\n\\n## Error Handling Stack\\n\\nTwo terminal middleware handlers process requests that escape the route layer:\\n\\n### Error Handler (4-arity)\\n\\n```javascript\\napp.use(function(err, req, res, next){\\n  res.status(err.status || 500);\\n  res.send({ error: err.message });\\n});\\n```\\n\\nExpress distinguishes this as error middleware by its signature `(err, req, res, next)`. It is only invoked when `next(err)` is called or a synchronous error is thrown in prior middleware.\\n\\n### 404 Handler (2-arity)\\n\\n```javascript\\napp.use(function(req, res){\\n  res.status(404);\\n  res.send({ error: \\\"Sorry, can't find that\\\" })\\n});\\n```\\n\\nPlaced last in the middleware stack, this catches any request that reaches it without a prior response. The consistent JSON shape (`{ error: string }`) maintains API contract uniformity.\\n\\n## Connection to Express Core\\n\\nThis example imports Express via a relative path (`../../`), indicating it resides within the Express repository's `examples/` directory. It exercises:\\n\\n- `app.use([path], fn)` \u2014 path-specific middleware mounting\\n- `app.get(path, fn)` \u2014 route registration\\n- `res.send(body)` \u2014 JSON serialization (delegated to `test/Router.js` per call graph)\\n- `res.status(code)` \u2014 status code setting\\n\\nThe `res.send` calls route through Express's response machinery, which handles content negotiation and JSON stringification.\"};\nvar TREE = [{\"name\":\"Project Documentation\",\"slug\":\"project-documentation\",\"files\":[\"History.md\",\"Readme.md\"]},{\"name\":\"Core Framework\",\"slug\":\"core-framework\",\"files\":[\"index.js\",\"lib/application.js\",\"lib/express.js\",\"lib/request.js\",\"lib/response.js\",\"lib/utils.js\",\"lib/view.js\"]},{\"name\":\"Application Configuration\",\"slug\":\"application-configuration\",\"files\":[\"package.json\"]},{\"name\":\"Authentication Example\",\"slug\":\"authentication-example\",\"files\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\"]},{\"name\":\"Content Negotiation Example\",\"slug\":\"content-negotiation-example\",\"files\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\"]},{\"name\":\"Cookie Sessions Example\",\"slug\":\"cookie-sessions-example\",\"files\":[\"examples/cookie-sessions/index.js\"]},{\"name\":\"Cookies Example\",\"slug\":\"cookies-example\",\"files\":[\"examples/cookies/index.js\"]},{\"name\":\"Downloads Example\",\"slug\":\"downloads-example\",\"files\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\"]},{\"name\":\"EJS Templating Example\",\"slug\":\"ejs-templating-example\",\"files\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\"]},{\"name\":\"Error Handling Examples\",\"slug\":\"error-handling-examples\",\"files\":[\"examples/error/index.js\",\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\"]},{\"name\":\"Hello World Example\",\"slug\":\"hello-world-example\",\"files\":[\"examples/hello-world/index.js\"]},{\"name\":\"Markdown Example\",\"slug\":\"markdown-example\",\"files\":[\"examples/markdown/index.js\",\"examples/markdown/views/index.md\"]},{\"name\":\"Multi-Router Example\",\"slug\":\"multi-router-example\",\"files\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\"]},{\"name\":\"MVC Example\",\"slug\":\"mvc-example\",\"files\":[\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\"]},{\"name\":\"Online Example\",\"slug\":\"online-example\",\"files\":[\"examples/online/index.js\"]},{\"name\":\"Route Parameters Example\",\"slug\":\"route-parameters-example\",\"files\":[\"examples/params/index.js\"]},{\"name\":\"Resource Example\",\"slug\":\"resource-example\",\"files\":[\"examples/resource/index.js\"]},{\"name\":\"Route Map Example\",\"slug\":\"route-map-example\",\"files\":[\"examples/route-map/index.js\"]},{\"name\":\"Route Middleware Example\",\"slug\":\"route-middleware-example\",\"files\":[\"examples/route-middleware/index.js\"]},{\"name\":\"Route Separation Example\",\"slug\":\"route-separation-example\",\"files\":[\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"]},{\"name\":\"Search Example\",\"slug\":\"search-example\",\"files\":[\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"]},{\"name\":\"Session Example\",\"slug\":\"session-example\",\"files\":[\"examples/session/index.js\",\"examples/session/redis.js\"]},{\"name\":\"Static Files Example\",\"slug\":\"static-files-example\",\"files\":[\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"]},{\"name\":\"Virtual Hosts Example\",\"slug\":\"virtual-hosts-example\",\"files\":[\"examples/vhost/index.js\"]},{\"name\":\"View Constructor Example\",\"slug\":\"view-constructor-example\",\"files\":[\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\"]},{\"name\":\"View Locals Example\",\"slug\":\"view-locals-example\",\"files\":[\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"]},{\"name\":\"Web Service Example\",\"slug\":\"web-service-example\",\"files\":[\"examples/web-service/index.js\"]},{\"name\":\"Other\",\"slug\":\"other\",\"files\":[],\"children\":[{\"name\":\"Other \u2014 examples\",\"slug\":\"other-examples\",\"files\":[\"examples/README.md\"]},{\"name\":\"Other \u2014 test\",\"slug\":\"other-test\",\"files\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"]},{\"name\":\"Other \u2014 acceptance\",\"slug\":\"other-acceptance\",\"files\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"]},{\"name\":\"Other \u2014 support\",\"slug\":\"other-support\",\"files\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]}]}];\nvar META = {\"fromCommit\":\"f873ac23124ffcff8c040b4bd257b32c29828d53\",\"generatedAt\":\"2026-05-09T02:54:42.430Z\",\"model\":\"kimi-for-coding\",\"moduleFiles\":{\"Project Documentation\":[\"History.md\",\"Readme.md\"],\"Core Framework\":[\"index.js\",\"lib/application.js\",\"lib/express.js\",\"lib/request.js\",\"lib/response.js\",\"lib/utils.js\",\"lib/view.js\"],\"Application Configuration\":[\"package.json\"],\"Authentication Example\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\"],\"Content Negotiation Example\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\"],\"Cookie Sessions Example\":[\"examples/cookie-sessions/index.js\"],\"Cookies Example\":[\"examples/cookies/index.js\"],\"Downloads Example\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\"],\"EJS Templating Example\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\"],\"Error Handling Examples\":[\"examples/error/index.js\",\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\"],\"Hello World Example\":[\"examples/hello-world/index.js\"],\"Markdown Example\":[\"examples/markdown/index.js\",\"examples/markdown/views/index.md\"],\"Multi-Router Example\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\"],\"MVC Example\":[\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\"],\"Online Example\":[\"examples/online/index.js\"],\"Route Parameters Example\":[\"examples/params/index.js\"],\"Resource Example\":[\"examples/resource/index.js\"],\"Route Map Example\":[\"examples/route-map/index.js\"],\"Route Middleware Example\":[\"examples/route-middleware/index.js\"],\"Route Separation Example\":[\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"],\"Search Example\":[\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"],\"Session Example\":[\"examples/session/index.js\",\"examples/session/redis.js\"],\"Static Files Example\":[\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"],\"Virtual Hosts Example\":[\"examples/vhost/index.js\"],\"View Constructor Example\":[\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\"],\"View Locals Example\":[\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"],\"Web Service Example\":[\"examples/web-service/index.js\"],\"Other\":[\"examples/README.md\",\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\",\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\",\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"],\"Other \u2014 examples\":[\"examples/README.md\"],\"Other \u2014 test\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"],\"Other \u2014 acceptance\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"],\"Other \u2014 support\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]},\"moduleTree\":[{\"name\":\"Project Documentation\",\"slug\":\"project-documentation\",\"files\":[\"History.md\",\"Readme.md\"]},{\"name\":\"Core Framework\",\"slug\":\"core-framework\",\"files\":[\"index.js\",\"lib/application.js\",\"lib/express.js\",\"lib/request.js\",\"lib/response.js\",\"lib/utils.js\",\"lib/view.js\"]},{\"name\":\"Application Configuration\",\"slug\":\"application-configuration\",\"files\":[\"package.json\"]},{\"name\":\"Authentication Example\",\"slug\":\"authentication-example\",\"files\":[\"examples/auth/index.js\",\"examples/auth/views/foot.ejs\",\"examples/auth/views/head.ejs\",\"examples/auth/views/login.ejs\"]},{\"name\":\"Content Negotiation Example\",\"slug\":\"content-negotiation-example\",\"files\":[\"examples/content-negotiation/db.js\",\"examples/content-negotiation/index.js\",\"examples/content-negotiation/users.js\"]},{\"name\":\"Cookie Sessions Example\",\"slug\":\"cookie-sessions-example\",\"files\":[\"examples/cookie-sessions/index.js\"]},{\"name\":\"Cookies Example\",\"slug\":\"cookies-example\",\"files\":[\"examples/cookies/index.js\"]},{\"name\":\"Downloads Example\",\"slug\":\"downloads-example\",\"files\":[\"examples/downloads/files/CCTV\u5927\u8d5b\u4e0a\u6d77\u5206\u8d5b\u533a.txt\",\"examples/downloads/files/amazing.txt\",\"examples/downloads/files/notes/groceries.txt\",\"examples/downloads/index.js\"]},{\"name\":\"EJS Templating Example\",\"slug\":\"ejs-templating-example\",\"files\":[\"examples/ejs/index.js\",\"examples/ejs/public/stylesheets/style.css\",\"examples/ejs/views/footer.html\",\"examples/ejs/views/header.html\",\"examples/ejs/views/users.html\"]},{\"name\":\"Error Handling Examples\",\"slug\":\"error-handling-examples\",\"files\":[\"examples/error/index.js\",\"examples/error-pages/index.js\",\"examples/error-pages/views/404.ejs\",\"examples/error-pages/views/500.ejs\",\"examples/error-pages/views/error_header.ejs\",\"examples/error-pages/views/footer.ejs\",\"examples/error-pages/views/index.ejs\"]},{\"name\":\"Hello World Example\",\"slug\":\"hello-world-example\",\"files\":[\"examples/hello-world/index.js\"]},{\"name\":\"Markdown Example\",\"slug\":\"markdown-example\",\"files\":[\"examples/markdown/index.js\",\"examples/markdown/views/index.md\"]},{\"name\":\"Multi-Router Example\",\"slug\":\"multi-router-example\",\"files\":[\"examples/multi-router/controllers/api_v1.js\",\"examples/multi-router/controllers/api_v2.js\",\"examples/multi-router/index.js\"]},{\"name\":\"MVC Example\",\"slug\":\"mvc-example\",\"files\":[\"examples/mvc/controllers/main/index.js\",\"examples/mvc/controllers/pet/index.js\",\"examples/mvc/controllers/pet/views/edit.ejs\",\"examples/mvc/controllers/pet/views/show.ejs\",\"examples/mvc/controllers/user-pet/index.js\",\"examples/mvc/controllers/user/index.js\",\"examples/mvc/controllers/user/views/edit.hbs\",\"examples/mvc/controllers/user/views/list.hbs\",\"examples/mvc/controllers/user/views/show.hbs\",\"examples/mvc/db.js\",\"examples/mvc/index.js\",\"examples/mvc/lib/boot.js\",\"examples/mvc/public/style.css\",\"examples/mvc/views/404.ejs\",\"examples/mvc/views/5xx.ejs\"]},{\"name\":\"Online Example\",\"slug\":\"online-example\",\"files\":[\"examples/online/index.js\"]},{\"name\":\"Route Parameters Example\",\"slug\":\"route-parameters-example\",\"files\":[\"examples/params/index.js\"]},{\"name\":\"Resource Example\",\"slug\":\"resource-example\",\"files\":[\"examples/resource/index.js\"]},{\"name\":\"Route Map Example\",\"slug\":\"route-map-example\",\"files\":[\"examples/route-map/index.js\"]},{\"name\":\"Route Middleware Example\",\"slug\":\"route-middleware-example\",\"files\":[\"examples/route-middleware/index.js\"]},{\"name\":\"Route Separation Example\",\"slug\":\"route-separation-example\",\"files\":[\"examples/route-separation/index.js\",\"examples/route-separation/post.js\",\"examples/route-separation/public/style.css\",\"examples/route-separation/site.js\",\"examples/route-separation/user.js\",\"examples/route-separation/views/footer.ejs\",\"examples/route-separation/views/header.ejs\",\"examples/route-separation/views/index.ejs\",\"examples/route-separation/views/posts/index.ejs\",\"examples/route-separation/views/users/edit.ejs\",\"examples/route-separation/views/users/index.ejs\",\"examples/route-separation/views/users/view.ejs\"]},{\"name\":\"Search Example\",\"slug\":\"search-example\",\"files\":[\"examples/search/index.js\",\"examples/search/public/client.js\",\"examples/search/public/index.html\"]},{\"name\":\"Session Example\",\"slug\":\"session-example\",\"files\":[\"examples/session/index.js\",\"examples/session/redis.js\"]},{\"name\":\"Static Files Example\",\"slug\":\"static-files-example\",\"files\":[\"examples/static-files/index.js\",\"examples/static-files/public/css/style.css\",\"examples/static-files/public/hello.txt\",\"examples/static-files/public/js/app.js\"]},{\"name\":\"Virtual Hosts Example\",\"slug\":\"virtual-hosts-example\",\"files\":[\"examples/vhost/index.js\"]},{\"name\":\"View Constructor Example\",\"slug\":\"view-constructor-example\",\"files\":[\"examples/view-constructor/github-view.js\",\"examples/view-constructor/index.js\"]},{\"name\":\"View Locals Example\",\"slug\":\"view-locals-example\",\"files\":[\"examples/view-locals/index.js\",\"examples/view-locals/user.js\",\"examples/view-locals/views/index.ejs\"]},{\"name\":\"Web Service Example\",\"slug\":\"web-service-example\",\"files\":[\"examples/web-service/index.js\"]},{\"name\":\"Other\",\"slug\":\"other\",\"files\":[],\"children\":[{\"name\":\"Other \u2014 examples\",\"slug\":\"other-examples\",\"files\":[\"examples/README.md\"]},{\"name\":\"Other \u2014 test\",\"slug\":\"other-test\",\"files\":[\"test/Route.js\",\"test/Router.js\",\"test/app.all.js\",\"test/app.engine.js\",\"test/app.head.js\",\"test/app.js\",\"test/app.listen.js\",\"test/app.locals.js\",\"test/app.options.js\",\"test/app.param.js\",\"test/app.render.js\",\"test/app.request.js\",\"test/app.response.js\",\"test/app.route.js\",\"test/app.router.js\",\"test/app.routes.error.js\",\"test/app.use.js\",\"test/config.js\",\"test/exports.js\",\"test/express.json.js\",\"test/express.raw.js\",\"test/express.static.js\",\"test/express.text.js\",\"test/express.urlencoded.js\",\"test/middleware.basic.js\",\"test/regression.js\",\"test/req.accepts.js\",\"test/req.acceptsCharsets.js\",\"test/req.acceptsEncodings.js\",\"test/req.acceptsLanguages.js\",\"test/req.baseUrl.js\",\"test/req.fresh.js\",\"test/req.get.js\",\"test/req.host.js\",\"test/req.hostname.js\",\"test/req.ip.js\",\"test/req.ips.js\",\"test/req.is.js\",\"test/req.path.js\",\"test/req.protocol.js\",\"test/req.query.js\",\"test/req.range.js\",\"test/req.route.js\",\"test/req.secure.js\",\"test/req.signedCookies.js\",\"test/req.stale.js\",\"test/req.subdomains.js\",\"test/req.xhr.js\",\"test/res.append.js\",\"test/res.attachment.js\",\"test/res.clearCookie.js\",\"test/res.cookie.js\",\"test/res.download.js\",\"test/res.format.js\",\"test/res.get.js\",\"test/res.json.js\",\"test/res.jsonp.js\",\"test/res.links.js\",\"test/res.locals.js\",\"test/res.location.js\",\"test/res.redirect.js\",\"test/res.render.js\",\"test/res.send.js\",\"test/res.sendFile.js\",\"test/res.sendStatus.js\",\"test/res.set.js\",\"test/res.status.js\",\"test/res.type.js\",\"test/res.vary.js\",\"test/utils.js\"]},{\"name\":\"Other \u2014 acceptance\",\"slug\":\"other-acceptance\",\"files\":[\"test/acceptance/auth.js\",\"test/acceptance/content-negotiation.js\",\"test/acceptance/cookie-sessions.js\",\"test/acceptance/cookies.js\",\"test/acceptance/downloads.js\",\"test/acceptance/ejs.js\",\"test/acceptance/error-pages.js\",\"test/acceptance/error.js\",\"test/acceptance/hello-world.js\",\"test/acceptance/markdown.js\",\"test/acceptance/multi-router.js\",\"test/acceptance/mvc.js\",\"test/acceptance/params.js\",\"test/acceptance/resource.js\",\"test/acceptance/route-map.js\",\"test/acceptance/route-separation.js\",\"test/acceptance/vhost.js\",\"test/acceptance/web-service.js\"]},{\"name\":\"Other \u2014 support\",\"slug\":\"other-support\",\"files\":[\"test/support/env.js\",\"test/support/tmpl.js\",\"test/support/utils.js\"]}]}]};\n\n(function() {\n  var activePage = 'overview';\n\n  document.addEventListener('DOMContentLoaded', function() {\n    mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' });\n    renderMeta();\n    renderNav();\n    document.getElementById('menu-toggle').addEventListener('click', function() {\n      document.getElementById('sidebar').classList.toggle('open');\n    });\n    if (location.hash &amp;&amp; location.hash.length &gt; 1) {\n      activePage = decodeURIComponent(location.hash.slice(1));\n    }\n    navigateTo(activePage);\n  });\n\n  function renderMeta() {\n    if (!META) return;\n    var el = document.getElementById('meta-info');\n    var parts = [];\n    if (META.generatedAt) {\n      parts.push(new Date(META.generatedAt).toLocaleDateString());\n    }\n    if (META.model) parts.push(META.model);\n    if (META.fromCommit) parts.push(META.fromCommit.slice(0, 8));\n    el.textContent = parts.join(' \\u00b7 ');\n  }\n\n  function renderNav() {\n    var container = document.getElementById('nav-tree');\n    var html = '\n';\n    html += 'Overview';\n    html += '';\n    if (TREE.length &gt; 0) {\n      html += '\nModules';\n      html += buildNavTree(TREE);\n    }\n    container.innerHTML = html;\n    container.addEventListener('click', function(e) {\n      var target = e.target;\n      while (target &amp;&amp; !target.dataset.page) { target = target.parentElement; }\n      if (target &amp;&amp; target.dataset.page) {\n        e.preventDefault();\n        navigateTo(target.dataset.page);\n      }\n    });\n  }\n\n  function buildNavTree(nodes) {\n    var html = '';\n    for (var i = 0; i &lt; nodes.length; i++) {\n      var node = nodes[i];\n      html += '\n';\n      html += '' + escH(node.name) + '';\n      if (node.children &amp;&amp; node.children.length &gt; 0) {\n        html += '\n' + buildNavTree(node.children) + '';\n      }\n      html += '';\n    }\n    return html;\n  }\n\n  function escH(s) {\n    var d = document.createElement('div');\n    d.textContent = s;\n    return d.innerHTML;\n  }\n\n  function navigateTo(page) {\n    activePage = page;\n    location.hash = encodeURIComponent(page);\n\n    var items = document.querySelectorAll('.nav-item');\n    for (var i = 0; i &lt; items.length; i++) {\n      if (items[i].dataset.page === page) {\n        items[i].classList.add('active');\n      } else {\n        items[i].classList.remove('active');\n      }\n    }\n\n    var contentEl = document.getElementById('content');\n    var md = PAGES[page];\n\n    if (!md) {\n      contentEl.innerHTML = '\n\nPage not found\n' + escH(page) + '.md does not exist.';\n      return;\n    }\n\n    contentEl.innerHTML = marked.parse(md);\n\n    // Rewrite .md links to hash navigation\n    var links = contentEl.querySelectorAll('a[href]');\n    for (var i = 0; i &lt; links.length; i++) {\n      var href = links[i].getAttribute('href');\n      if (href &amp;&amp; href.endsWith('.md') &amp;&amp; href.indexOf('://') === -1) {\n        var slug = href.replace(/\\.md$/, '');\n        links[i].setAttribute('href', '#' + encodeURIComponent(slug));\n        (function(s) {\n          links[i].addEventListener('click', function(e) {\n            e.preventDefault();\n            navigateTo(s);\n          });\n        })(slug);\n      }\n    }\n\n    // Convert mermaid code blocks into mermaid divs\n    var mermaidBlocks = contentEl.querySelectorAll('pre code.language-mermaid');\n    for (var i = 0; i &lt; mermaidBlocks.length; i++) {\n      var pre = mermaidBlocks[i].parentElement;\n      var div = document.createElement('div');\n      div.className = 'mermaid';\n      div.textContent = mermaidBlocks[i].textContent;\n      pre.parentNode.replaceChild(div, pre);\n    }\n    try { mermaid.run({ querySelector: '.mermaid' }); } catch(e) {}\n\n    window.scrollTo(0, 0);\n    document.getElementById('sidebar').classList.remove('open');\n  }\n})();\n\n\n\n", "creation_timestamp": "2026-05-09T02:54:50.000000Z"}]}