node-server-lens 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,38 +21,49 @@
21
21
 
22
22
  **Server Lens** gives any backend a live monitoring dashboard: server status and IPs, streaming logs, request traffic with week / month / year history, per-endpoint API stats and uptime checks.
23
23
 
24
- Use it two ways:
24
+ Setup is **4 values**. Put the same four in your hub and in every app you want to watch:
25
25
 
26
- | | **Embedded** | **Hub** |
27
- | --- | --- | --- |
28
- | What | A dashboard inside your app at `/server-lens` | One dashboard for many servers, hosted anywhere |
29
- | Setup | `app.use(serverLens())` | `npx node-server-lens` + point servers at it |
30
- | History | Since the app started | Up to ~13 months, saved to disk |
31
- | Best for | One app, local dev, quick checks | Teams, production, many services |
26
+ ```bash
27
+ SERVER_LENS_USER=admin # hub login
28
+ SERVER_LENS_PASS=a-strong-password # hub login
29
+ SERVER_LENS_HUB_URL=https://lens.example.com # where your hub runs
30
+ SERVER_LENS_KEY=a-long-random-key # servers must send this to be accepted
31
+ ```
32
32
 
33
- No database, no build step, one dependency (`ws`). Works with **Express, Next.js, Fastify, Koa, NestJS, Hapi, plain Node**, and **any other language** over HTTP.
33
+ No database, no build step, one dependency (`ws`). Works with **Next.js, Express, Fastify, Koa, NestJS, Hapi, plain Node**, and **any other language** over HTTP.
34
34
 
35
35
  ## ⚡ Quick start
36
36
 
37
- **1. Install**
37
+ **1. Start the hub** in a folder with a `.env` file containing the 4 values. It reads them, signs you in with `SERVER_LENS_USER` and `SERVER_LENS_PASS`, and listens on the port in `SERVER_LENS_HUB_URL`:
38
38
 
39
39
  ```bash
40
- npm install node-server-lens
40
+ npx node-server-lens
41
41
  ```
42
42
 
43
- **2. Add one line before your routes**
43
+ Generate a key with `openssl rand -hex 24`. For hosting it properly, see [Host the hub](#-host-the-hub).
44
44
 
45
- ```js
46
- const serverLens = require('node-server-lens');
45
+ **2. Connect an app.** Install the package:
47
46
 
48
- app.use(serverLens());
47
+ ```bash
48
+ npm install node-server-lens
49
49
  ```
50
50
 
51
- **3. Open** `http://localhost:3000/server-lens` (use your app's port).
51
+ Add the connection code for your framework:
52
+
53
+ | Framework | Connection code |
54
+ | --- | --- |
55
+ | **Next.js** | `instrumentation.ts`: `export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument(); }`<br>and in `next.config`: `serverExternalPackages: ['node-server-lens']` |
56
+ | **Express / NestJS** | `app.use(require('node-server-lens')());` before your routes |
57
+ | **Fastify, Koa, Hapi, any Node** | `require('node-server-lens').instrument();` at the top of your entry file |
58
+ | **Other languages** | [HTTP ingest API](#ingest-schema) |
59
+
60
+ Put the same 4 values in the app's `.env` (`.env.local` for Next.js) and restart it.
52
61
 
53
- That's it. Using Next.js, Fastify or Koa instead? See [Connect your servers](#-connect-your-servers).
62
+ **3. Open your hub URL and sign in.** The app shows up within a few seconds. Repeat step 2 for every server you want to watch.
54
63
 
55
- > **Try it without your own project:** `git clone https://github.com/Sathishram2000/Node-Server-Lens.git && cd Node-Server-Lens && npm install && npm run demo`, then open http://localhost:4000. The demo runs a hub, two sample APIs and an uptime check, with a year of sample history.
64
+ > **No hub?** Leave out `SERVER_LENS_HUB_URL` and the app serves its own dashboard at `/server-lens` instead (signed in with `SERVER_LENS_USER` / `SERVER_LENS_PASS`). That's handy for local development.
65
+ >
66
+ > **Try it without your own project:** `git clone https://github.com/Sathishram2000/Node-Server-Lens.git && cd Node-Server-Lens && npm install && npm run demo`, then open http://localhost:4000.
56
67
 
57
68
  ## 🤖 Set up with an AI coding agent
58
69
 
@@ -63,45 +74,39 @@ Add Server Lens monitoring (npm package "node-server-lens", docs: https://github
63
74
 
64
75
  1. Detect the backend framework and language from the project files.
65
76
  2. If it runs on Node.js, install "node-server-lens" with the package manager that matches the lockfile (npm, pnpm, yarn or bun).
66
- 3. Wire it up, matching the project's module style (ESM import or CommonJS require) and TypeScript if used:
67
- - Express, Connect, or NestJS on the Express adapter: in the file that creates the app, add
68
- app.use(serverLens({ ...options })) BEFORE any routes.
69
- - Next.js: create instrumentation.ts (in src/ if the project uses src/, otherwise the project root) with
70
- export async function register() {
71
- if (process.env.NEXT_RUNTIME === 'nodejs') {
72
- const { instrument } = await import('node-server-lens');
73
- instrument({ ...options });
77
+ 3. Add the connection code. It needs no options: the package reads its settings from environment variables.
78
+ Match the project's module style (ESM import or CommonJS require) and use TypeScript if the project does.
79
+ - Next.js: create instrumentation.ts (in src/ if the project uses src/, otherwise the project root):
80
+ export async function register() {
81
+ if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument();
74
82
  }
75
- }
83
+ If instrumentation.ts already exists, add that line inside its register() function.
76
84
  Then add 'node-server-lens' to serverExternalPackages in next.config
77
85
  (Next.js 14: experimental.serverComponentsExternalPackages).
86
+ - Express, Connect, or NestJS on the Express adapter: in the file that creates the app, add
87
+ app.use(require('node-server-lens')()) BEFORE any routes.
78
88
  - Fastify, Koa, Hapi, plain http/https, or any other Node server: at the very top of the entry file,
79
- before the server starts, call require('node-server-lens').instrument({ ...options })
80
- (or the ESM import equivalent).
89
+ before the server starts, call require('node-server-lens').instrument().
81
90
  - Not Node.js (Python, Go, PHP, Ruby, Java, .NET...): do not install the npm package. Add a small
82
91
  middleware that records method, route pattern, path, status, duration in ms, client IP and timestamp
83
92
  for each request, batches them, and POSTs them every 5 seconds to `${SERVER_LENS_HUB_URL}/api/ingest`
84
93
  with the header "Authorization: Bearer ${SERVER_LENS_KEY}", using the JSON format in the
85
94
  "HTTP ingest API" section of the docs. Only run it when both variables are set, and never let a
86
95
  failed POST break a request.
87
- 4. Options to pass (Node.js):
88
- - name: this project's name
89
- - auth: { username: process.env.SERVER_LENS_USER, password: process.env.SERVER_LENS_PASS },
90
- only when both variables are set (otherwise leave auth out)
91
- - hub: { url: process.env.SERVER_LENS_HUB_URL, key: process.env.SERVER_LENS_KEY },
92
- only when SERVER_LENS_HUB_URL is set
93
- 5. Add SERVER_LENS_USER, SERVER_LENS_PASS, SERVER_LENS_HUB_URL and SERVER_LENS_KEY with empty values to
94
- .env.example (create it if missing). Never commit real secrets.
95
- 6. Start the app, request /server-lens, and confirm it returns HTTP 200. Tell me the dashboard URL and
96
- which files you changed.
96
+ 4. Add these 4 variables with empty values to .env.example (create it if missing), and tell me to fill
97
+ them in my real env file (.env.local for Next.js, .env otherwise). Never commit real secrets.
98
+ SERVER_LENS_USER=
99
+ SERVER_LENS_PASS=
100
+ SERVER_LENS_HUB_URL=
101
+ SERVER_LENS_KEY=
102
+ 5. Tell me which files you changed, and remind me to restart the app after setting the values.
97
103
  ```
98
104
 
99
105
  <details>
100
106
  <summary>What the prompt sets up</summary>
101
107
 
102
- - **Node.js apps** get the embedded dashboard at `/server-lens`, plus hub reporting once you set `SERVER_LENS_HUB_URL` and `SERVER_LENS_KEY`.
108
+ - The app reports to your hub as soon as the 4 values are set. It appears in the hub's server switcher under its `package.json` name (override with `SERVER_LENS_NAME`).
103
109
  - **Other languages** get a small reporter that sends data to your hub.
104
- - Login is enabled as soon as you set `SERVER_LENS_USER` and `SERVER_LENS_PASS`.
105
110
  - Nothing secret is written to the code; values come from environment variables.
106
111
 
107
112
  Always review the changes before you commit them.
@@ -133,78 +138,57 @@ Also included: a styled sign-in page with 7-day sessions and a sign-out button,
133
138
 
134
139
  ## 🔌 Connect your servers
135
140
 
136
- Keep keys and passwords in environment variables, never in code. Every option is listed in the [reference](#agent-options).
141
+ Every app needs the package, one piece of connection code, and the 4 values in its environment (see [Quick start](#-quick-start)). Optional extras are in the [reference](#agent-options).
137
142
 
138
143
  <details open>
139
- <summary><b>Express · Connect · NestJS (Express adapter) · plain Node http</b></summary>
144
+ <summary><b>Next.js</b></summary>
140
145
 
141
- ```js
142
- const serverLens = require('node-server-lens');
146
+ Works with `next dev`, `next start` and custom servers (Node.js runtime, App or Pages router).
143
147
 
144
- app.use(serverLens({
145
- name: 'orders-api',
146
- auth: { username: 'admin', password: process.env.SERVER_LENS_PASS }, // protect /server-lens
147
- hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY }, // optional: report to a hub
148
- }));
148
+ `instrumentation.ts` in the project root (or `src/`):
149
+
150
+ ```ts
151
+ export async function register() {
152
+ if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument();
153
+ }
149
154
  ```
150
155
 
151
- Plain Node `http`:
156
+ `next.config.js` / `next.config.ts`:
152
157
 
153
158
  ```js
154
- const http = require('http');
155
- const lens = require('node-server-lens')();
156
-
157
- http.createServer((req, res) => lens(req, res, () => {
158
- res.end('ok'); // your handler
159
- })).listen(3000);
159
+ module.exports = { serverExternalPackages: ['node-server-lens'] };
160
+ // Next.js 14: module.exports = { experimental: { serverComponentsExternalPackages: ['node-server-lens'] } };
160
161
  ```
161
162
 
162
- ESM works too: `import serverLens from 'node-server-lens'`.
163
+ `.env.local`: the 4 values. Restart the dev server after changing them.
164
+
165
+ Pages and API routes are recorded and `/_next/*` assets are skipped. Edge runtime routes aren't captured, because they don't run in Node.
163
166
  </details>
164
167
 
165
168
  <details>
166
- <summary><b>Next.js</b></summary>
167
-
168
- Works with `next start` and `next dev` (Node.js runtime, App or Pages router).
169
-
170
- 1. `npm install node-server-lens`
171
- 2. Create `instrumentation.ts` in the project root (or in `src/` if you use it):
169
+ <summary><b>Express · Connect · NestJS (Express adapter) · plain Node http</b></summary>
172
170
 
173
- ```ts
174
- export async function register() {
175
- if (process.env.NEXT_RUNTIME === 'nodejs') {
176
- const { instrument } = await import('node-server-lens');
177
- instrument({
178
- name: 'web',
179
- auth: { username: 'admin', password: process.env.SERVER_LENS_PASS! },
180
- hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY! }, // optional
181
- });
182
- }
183
- }
171
+ ```js
172
+ app.use(require('node-server-lens')()); // before your routes
184
173
  ```
185
174
 
186
- 3. Keep the package out of the bundle in `next.config.js`:
175
+ Plain Node `http`:
187
176
 
188
177
  ```js
189
- module.exports = { serverExternalPackages: ['node-server-lens'] };
190
- // Next.js 14: module.exports = { experimental: { serverComponentsExternalPackages: ['node-server-lens'] } };
178
+ const lens = require('node-server-lens')();
179
+ http.createServer((req, res) => lens(req, res, () => res.end('ok'))).listen(3000);
191
180
  ```
192
181
 
193
- Pages and API routes are recorded and `/_next/*` assets are skipped. The dashboard is served at `/server-lens` on your Next.js app. Routes on the Edge runtime aren't captured, because they don't run in Node.
182
+ ESM: `import serverLens from 'node-server-lens'; app.use(serverLens());`
194
183
  </details>
195
184
 
196
185
  <details>
197
186
  <summary><b>Fastify · Koa · Hapi · any other Node server</b></summary>
198
187
 
199
- `instrument()` hooks into Node's own `http`/`https` servers, so it works with any framework without touching your routes. Call it once, before the server starts:
188
+ `instrument()` hooks into Node's own `http`/`https` servers, so it works with any framework without touching your routes. Put it at the top of your entry file, before the server starts:
200
189
 
201
190
  ```js
202
- require('node-server-lens').instrument({
203
- name: 'billing',
204
- hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY },
205
- });
206
-
207
- // ...then start Fastify / Koa / Hapi as usual
191
+ require('node-server-lens').instrument();
208
192
  ```
209
193
  </details>
210
194
 
@@ -297,6 +281,8 @@ lens.log('warn', 'disk usage at', 91, '%');
297
281
  The hub is one Node process that saves history to one JSON file. Give it a **persistent disk**, an **ingest key** and a **login**, and put it behind **HTTPS**.
298
282
 
299
283
  ```bash
284
+ npx node-server-lens # reads ./.env (the 4 values)
285
+ # or pass them directly:
300
286
  npx node-server-lens --port 4000 --key "$(openssl rand -hex 24)" --user admin --pass 'change-me'
301
287
  ```
302
288
 
@@ -394,10 +380,10 @@ Serverless platforms (Vercel functions, AWS Lambda) aren't a good fit for the **
394
380
  | Option | Default | Description |
395
381
  | --- | --- | --- |
396
382
  | `path` | `'/server-lens'` | Where the embedded dashboard is served |
397
- | `auth` | none | `{ username, password }` shows the sign-in page; or `(req) => boolean` to plug in your own auth |
398
- | `dashboard` | `true` | `false` turns off the embedded dashboard (hub reporting only) |
399
- | `hub` | none | `{ url, key, id?, name?, interval? }` to report to a hub |
400
- | `name` | hostname | Display name |
383
+ | `hub` | from `SERVER_LENS_HUB_URL` + `SERVER_LENS_KEY` | `{ url, key, id?, name?, interval? }`; `false` turns reporting off |
384
+ | `auth` | from `SERVER_LENS_USER` + `SERVER_LENS_PASS` | Login for the in-app dashboard: `{ username, password }`, or `(req) => boolean` for your own auth |
385
+ | `dashboard` | on only when no hub is set | `true` serves `/server-lens` inside the app even when reporting to a hub |
386
+ | `name` | `SERVER_LENS_NAME`, else `package.json` name, else hostname | Name shown in the hub |
401
387
  | `title` | `'Server Lens'` | Dashboard title |
402
388
  | `captureConsole` | `true` | Capture `console.*` into live logs |
403
389
  | `ignore` | `[]` | Path prefixes or RegExps not to record (`instrument` also skips `/_next/` and `/favicon.ico`) |
@@ -414,7 +400,8 @@ The returned middleware also has `attach(server)`, `log(level, ...args)`, `snaps
414
400
 
415
401
  | Flag | Environment variable | Default |
416
402
  | --- | --- | --- |
417
- | `--port` | `PORT` | `4000` |
403
+ | `--env` | | `./.env` if it exists (loads the `SERVER_LENS_*` values; Node 20.12+) |
404
+ | `--port` | `PORT` | the port in `SERVER_LENS_HUB_URL`, else `4000` |
418
405
  | `--host` | `HOST` | `0.0.0.0` |
419
406
  | `--key` | `SERVER_LENS_KEY` | random for each run (printed at start) |
420
407
  | `--user` / `--pass` | `SERVER_LENS_USER` / `SERVER_LENS_PASS` | none (open) |
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
+ const fs = require('fs');
3
4
  const crypto = require('crypto');
4
5
  const { createHub } = require('../src/hub');
5
6
 
@@ -9,16 +10,28 @@ if (argv.includes('-h') || argv.includes('--help')) {
9
10
 
10
11
  Usage: server-lens [hub] [options]
11
12
 
12
- --port <n> Port to listen on (env PORT, default 4000)
13
+ --env <file> Load settings from this file (default: ./.env if present)
14
+ --port <n> Port to listen on (env PORT, else the port in SERVER_LENS_HUB_URL, else 4000)
13
15
  --host <addr> Interface to bind (env HOST, default 0.0.0.0)
14
16
  --key <secret> Ingest key agents must send (env SERVER_LENS_KEY, generated if empty)
15
- --user <name> Dashboard basic-auth user (env SERVER_LENS_USER)
16
- --pass <pass> Dashboard basic-auth pass (env SERVER_LENS_PASS)
17
+ --user <name> Dashboard login username (env SERVER_LENS_USER)
18
+ --pass <pass> Dashboard login password (env SERVER_LENS_PASS)
17
19
  --data <file> Where history is stored (env SERVER_LENS_DATA, default ./server-lens-data.json)
18
20
  --check <sec> URL monitor interval (env SERVER_LENS_CHECK, default 30)
19
21
  --title <text> Dashboard title`);
20
22
  process.exit(0);
21
23
  }
24
+ // Load the same SERVER_LENS_* values the apps use, from --env <file> or ./.env
25
+ const envIdx = argv.indexOf('--env');
26
+ const envFile = envIdx >= 0 ? argv[envIdx + 1] : fs.existsSync('.env') ? '.env' : null;
27
+ if (envFile) {
28
+ try {
29
+ if (!process.loadEnvFile) throw new Error('needs Node.js 20.12 or newer (or pass the values as env vars / flags)');
30
+ process.loadEnvFile(envFile); console.log(`Loaded settings from ${envFile}`);
31
+ }
32
+ catch (e) { console.error(`Could not load ${envFile}: ${e.message}`); if (envIdx >= 0) process.exit(1); }
33
+ }
34
+
22
35
  const arg = (name, env, def) => {
23
36
  const i = argv.indexOf(`--${name}`);
24
37
  return i >= 0 && argv[i + 1] ? argv[i + 1] : process.env[env] || def;
@@ -32,7 +45,9 @@ if (!key) {
32
45
  const user = arg('user', 'SERVER_LENS_USER'), pass = arg('pass', 'SERVER_LENS_PASS');
33
46
  if (!user) console.warn('Warning: the dashboard has no login. Set SERVER_LENS_USER and SERVER_LENS_PASS before exposing it publicly.');
34
47
 
35
- const port = Number(arg('port', 'PORT', 4000));
48
+ let urlPort;
49
+ try { urlPort = new URL(process.env.SERVER_LENS_HUB_URL).port; } catch { /* not set */ }
50
+ const port = Number(arg('port', 'PORT', urlPort || 4000));
36
51
  const host = arg('host', 'HOST', '0.0.0.0');
37
52
  const hub = createHub({
38
53
  key,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-server-lens",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Self-hosted, real-time monitoring for all your servers: live logs over WebSocket, request traffic with week/month/year history, API stats, uptime checks. Express, Next.js, any Node server, or any language over HTTP.",
5
5
  "main": "src/index.js",
6
6
  "bin": {
package/public/index.html CHANGED
@@ -465,15 +465,22 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
465
465
  <p class="muted">Pick how this server should report to the hub.</p>
466
466
  <div class="seg" id="addTabs"><button data-t="node" class="on">Node.js / Express</button><button data-t="next">Next.js</button><button data-t="url">Any URL</button><button data-t="api">Other languages</button></div>
467
467
  <div data-p="node">
468
- <div class="step">1 · Install the agent</div><pre>npm install node-server-lens</pre>
469
- <div class="step">2 · Add it before your routes (Express, NestJS or plain http). Fastify, Koa or Hapi: use <span class="mono">instrument()</span> as in the Next.js tab</div>
470
- <pre id="snipNode"></pre>
468
+ <div class="step">1 · Install</div><pre>npm install node-server-lens</pre>
469
+ <div class="step">2 · Add one line before your routes (Express, NestJS, plain http)</div>
470
+ <pre>app.use(require('node-server-lens')());</pre>
471
+ <div class="step">Fastify, Koa, Hapi or anything else: put this at the top of your entry file instead</div>
472
+ <pre>require('node-server-lens').instrument();</pre>
473
+ <div class="step">3 · Add these values to the app's <span class="mono">.env</span> and restart it</div>
474
+ <pre class="snipEnv"></pre>
471
475
  </div>
472
476
  <div data-p="next" hidden>
473
- <div class="step">1 · <span class="mono">npm install node-server-lens</span>, then add <span class="mono">instrumentation.ts</span> at the project root</div>
477
+ <div class="step">1 · Install</div><pre>npm install node-server-lens</pre>
478
+ <div class="step">2 · Create <span class="mono">instrumentation.ts</span> in the project root (or <span class="mono">src/</span>)</div>
474
479
  <pre id="snipNext"></pre>
475
- <div class="step">2 · Keep it out of the bundle in <span class="mono">next.config.js</span></div>
476
- <pre>module.exports = { serverExternalPackages: ['node-server-lens'] };</pre>
480
+ <div class="step">3 · In <span class="mono">next.config</span>, keep it out of the bundle</div>
481
+ <pre>serverExternalPackages: ['node-server-lens'],</pre>
482
+ <div class="step">4 · Add these values to <span class="mono">.env.local</span> and restart</div>
483
+ <pre class="snipEnv"></pre>
477
484
  </div>
478
485
  <form data-p="url" hidden id="urlForm">
479
486
  <p class="muted">No code needed. The hub checks the URL every 30 seconds and tracks uptime and response time: works for Python, Go, PHP, Java, Rails, static sites, anything with HTTP.</p>
@@ -874,20 +881,13 @@ $('fleet').addEventListener('keydown', (e) => {
874
881
 
875
882
  /* ---------- connect dialog ---------- */
876
883
  const hubUrl = location.origin + CFG.base;
877
- $('snipNode').textContent = `const serverLens = require('node-server-lens');
878
-
879
- app.use(serverLens({
880
- name: 'orders-api',
881
- hub: { url: '${hubUrl}', key: process.env.SERVER_LENS_KEY },
882
- }));`;
884
+ const envVals = `SERVER_LENS_USER=your-hub-username
885
+ SERVER_LENS_PASS=your-hub-password
886
+ SERVER_LENS_HUB_URL=${hubUrl}
887
+ SERVER_LENS_KEY=your-hub-key`;
888
+ document.querySelectorAll('.snipEnv').forEach((el) => (el.textContent = envVals));
883
889
  $('snipNext').textContent = `export async function register() {
884
- if (process.env.NEXT_RUNTIME === 'nodejs') {
885
- const { instrument } = await import('node-server-lens');
886
- instrument({
887
- name: 'web',
888
- hub: { url: '${hubUrl}', key: process.env.SERVER_LENS_KEY },
889
- });
890
- }
890
+ if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument();
891
891
  }`;
892
892
  $('snipApi').textContent = `curl -X POST ${hubUrl}/api/ingest \\
893
893
  -H "Authorization: Bearer $SERVER_LENS_KEY" \\
package/src/hub.js CHANGED
@@ -22,7 +22,8 @@ function createHub(opts = {}) {
22
22
  const self = localSource({ id: 'hub', name: opts.name || 'Server Lens Hub', captureConsole: opts.captureConsole !== false });
23
23
  const sources = new Map([[self.id, self]]);
24
24
  // hub itself is listed last so the first real server is the default view
25
- const list = () => [...sources.values()].filter((s) => s !== self).concat(self);
25
+ const rank = (s) => (s.health() === 'offline' || s.health() === 'down' ? 1 : 0);
26
+ const list = () => [...sources.values()].filter((s) => s !== self).sort((a, b) => rank(a) - rank(b)).concat(self); // live servers first
26
27
  const dash = createDashboard({ base, title: opts.title || 'Server Lens', auth: opts.auth, interval: opts.interval, hub: true, sources: { list, get: (id) => sources.get(id) } });
27
28
  dash.watch(self);
28
29
 
package/src/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export interface HubTarget {
10
10
  id?: string;
11
11
  /** Display name in the hub. Default: `name` option or hostname */
12
12
  name?: string;
13
- /** Push interval in ms. Default 5000 */
13
+ /** Push interval in ms. Default 2000 */
14
14
  interval?: number;
15
15
  }
16
16
 
@@ -21,10 +21,10 @@ export interface ServerLensOptions {
21
21
  name?: string;
22
22
  /** Protect the dashboard with basic auth or a custom check */
23
23
  auth?: { username: string; password: string } | ((req: IncomingMessage) => boolean);
24
- /** Set false to only report to a hub (no embedded dashboard) */
24
+ /** In-app dashboard at `path`. Default: on only when no hub is configured */
25
25
  dashboard?: boolean;
26
- /** Report this server to a Server Lens hub */
27
- hub?: HubTarget;
26
+ /** Report to a hub. Default: from SERVER_LENS_HUB_URL + SERVER_LENS_KEY; false to disable */
27
+ hub?: HubTarget | false;
28
28
  /** Capture console.log/info/warn/error/debug into live logs. Default true */
29
29
  captureConsole?: boolean;
30
30
  /** Paths (prefix string or RegExp) not to record */
package/src/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  'use strict';
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
2
5
  const http = require('http');
3
6
  const https = require('https');
4
7
  const { normalizePath } = require('./metrics');
@@ -6,6 +9,29 @@ const { localSource } = require('./source');
6
9
  const { createDashboard, normBase } = require('./dashboard');
7
10
  const { createHub } = require('./hub');
8
11
 
12
+ /**
13
+ * Options not passed in code come from the environment:
14
+ * SERVER_LENS_HUB_URL + SERVER_LENS_KEY → report to that hub (and no dashboard inside the app)
15
+ * SERVER_LENS_USER + SERVER_LENS_PASS → login for the in-app dashboard, when it is on
16
+ * SERVER_LENS_NAME → display name (default: package.json name, then hostname)
17
+ */
18
+ function resolveOptions(opts) {
19
+ const env = process.env;
20
+ const hub = opts.hub !== undefined ? opts.hub || null
21
+ : env.SERVER_LENS_HUB_URL ? { url: env.SERVER_LENS_HUB_URL, key: env.SERVER_LENS_KEY || '' } : null;
22
+ const auth = opts.auth !== undefined ? opts.auth
23
+ : env.SERVER_LENS_USER && env.SERVER_LENS_PASS ? { username: env.SERVER_LENS_USER, password: env.SERVER_LENS_PASS } : undefined;
24
+ return {
25
+ ...opts, hub, auth,
26
+ name: opts.name || env.SERVER_LENS_NAME || packageName() || os.hostname(),
27
+ dashboard: opts.dashboard !== undefined ? opts.dashboard : !hub, // with a hub, watch it there
28
+ };
29
+ }
30
+
31
+ function packageName() {
32
+ try { return JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8')).name || ''; } catch { return ''; }
33
+ }
34
+
9
35
  /**
10
36
  * Create a Server Lens agent. It is an Express/Connect-style middleware:
11
37
  * app.use(serverLens())
@@ -13,7 +39,9 @@ const { createHub } = require('./hub');
13
39
  * http.createServer((req, res) => lens(req, res, () => handler(req, res)))
14
40
  * or, for any Node server (Next.js, Fastify, Koa, NestJS…), use serverLens.instrument().
15
41
  */
16
- function serverLens(opts = {}) {
42
+ function serverLens(options = {}) {
43
+ const opts = resolveOptions(options);
44
+ if (opts.hub && !opts.hub.key) process.emitWarning('server-lens: SERVER_LENS_KEY is not set; the hub will reject this server.');
17
45
  const base = normBase(opts.path);
18
46
  const ignore = opts.ignore || [];
19
47
  const src = localSource({ name: opts.name, captureConsole: opts.captureConsole !== false, maxLogs: opts.maxLogs, maxRoutes: opts.maxRoutes, maxRecent: opts.maxRecent });
@@ -87,6 +115,7 @@ function instrument(opts = {}) {
87
115
  S.prototype.emit = function (ev, a, b, c) {
88
116
  if (ev === 'request') { lens.bind(this); lens(a, b, () => orig.call(this, ev, a, b)); return true; }
89
117
  if (ev === 'upgrade' && lens.isWs(a)) { lens.bind(this); lens.handleUpgrade(a, b, c); return true; }
118
+ if (ev === 'listening') lens.bind(this); // know the port before the first request arrives
90
119
  return orig.apply(this, arguments);
91
120
  };
92
121
  }
@@ -95,18 +124,25 @@ function instrument(opts = {}) {
95
124
  }
96
125
 
97
126
  /** Batches requests, logs and system samples and pushes them to a Server Lens hub. */
98
- function createReporter({ url, key, id, name, interval = 5000 }, src) {
127
+ function createReporter({ url, key, id, name, interval = 2000 }, src) {
99
128
  if (!url) throw new Error('server-lens: hub.url is required');
100
129
  const endpoint = `${String(url).replace(/\/+$/, '')}/api/ingest`;
101
- let requests = [], logs = [], warned = false, busy = false;
130
+ let requests = [], logs = [], warned = false, busy = false, serverId = id;
131
+ const started = Date.now();
102
132
  src.logs.on('log', (e) => { logs.push({ ts: e.ts, level: e.level, msg: e.msg }); if (logs.length > 1000) logs.shift(); });
103
133
 
104
134
  async function flush() {
105
135
  if (busy) return;
106
- busy = true;
107
136
  const info = src.info();
137
+ // The id must not change once chosen, or the hub shows the server twice. Wait (up to 60s) for the
138
+ // HTTP server to start listening so the id can include the port.
139
+ if (!serverId) {
140
+ if (!info.port && Date.now() - started < 60000) return;
141
+ serverId = `${info.hostname}-${info.port || 'app'}`.toLowerCase().replace(/[^\w.-]+/g, '-');
142
+ }
143
+ busy = true;
108
144
  const body = {
109
- id: id || `${info.hostname}-${info.port || 'app'}`.toLowerCase().replace(/[^\w.-]+/g, '-'),
145
+ id: serverId,
110
146
  name: name || src.name, info,
111
147
  sample: src.metrics.samples[src.metrics.samples.length - 1],
112
148
  requests: requests.slice(0, 5000), logs: logs.slice(0, 1000),