@zero-server/sdk 0.9.1 → 0.9.2

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.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,326 +1,326 @@
1
- /**
2
- * @module observe/health
3
- * @description Health check middleware with liveness and readiness probes.
4
- * Kubernetes-compatible `/healthz` and `/readyz` endpoints with
5
- * composable checks (database ping, memory, event loop lag,
6
- * disk space) and custom check registration.
7
- *
8
- * Returns `200` when healthy, `503` when degraded or during
9
- * shutdown drain phase, with a JSON body detailing each check.
10
- *
11
- * @example
12
- * const { healthCheck } = require('@zero-server/sdk');
13
- *
14
- * app.get('/healthz', healthCheck());
15
- * app.get('/readyz', healthCheck({
16
- * checks: {
17
- * database: () => db.ping(),
18
- * cache: () => redis.ping(),
19
- * },
20
- * }));
21
- *
22
- * @example | Using the App Integration
23
- * app.health('/healthz');
24
- * app.ready('/readyz', {
25
- * database: () => db.ping(),
26
- * });
27
- */
28
- const os = require('os');
29
-
30
- // -- Built-in Checks -----------------------------------------------
31
-
32
- /**
33
- * Check memory usage against a threshold.
34
- *
35
- * @param {object} [opts] - Check options.
36
- * @param {number} [opts.maxHeapUsedPercent=90] - Max heap usage percentage.
37
- * @param {number} [opts.maxRssBytes] - Max RSS in bytes.
38
- * @returns {Function} Check function.
39
- *
40
- * @example
41
- * app.get('/healthz', healthCheck({
42
- * checks: { memory: memoryCheck({ maxHeapUsedPercent: 85 }) },
43
- * }));
44
- */
45
- function memoryCheck(opts = {})
46
- {
47
- const maxPercent = typeof opts.maxHeapUsedPercent === 'number' ? opts.maxHeapUsedPercent : 90;
48
- const maxRss = opts.maxRssBytes || Infinity;
49
-
50
- return () =>
51
- {
52
- const mem = process.memoryUsage();
53
- const heapPercent = (mem.heapUsed / mem.heapTotal) * 100;
54
- const healthy = heapPercent < maxPercent && mem.rss < maxRss;
55
-
56
- return {
57
- healthy,
58
- details: {
59
- heapUsed: mem.heapUsed,
60
- heapTotal: mem.heapTotal,
61
- heapPercent: Math.round(heapPercent * 100) / 100,
62
- rss: mem.rss,
63
- external: mem.external,
64
- },
65
- };
66
- };
67
- }
68
-
69
- /**
70
- * Check event loop lag against a threshold.
71
- *
72
- * @param {object} [opts] - Check options.
73
- * @param {number} [opts.maxLagMs=500] - Max acceptable lag in ms.
74
- * @returns {Function} Check function.
75
- *
76
- * @example
77
- * app.get('/healthz', healthCheck({
78
- * checks: { eventLoop: eventLoopCheck({ maxLagMs: 200 }) },
79
- * }));
80
- */
81
- function eventLoopCheck(opts = {})
82
- {
83
- const maxLag = opts.maxLagMs || 500;
84
- let _lastCheck = process.hrtime.bigint();
85
- let _lag = 0;
86
-
87
- // Sample event loop lag periodically
88
- const _check = () =>
89
- {
90
- const now = process.hrtime.bigint();
91
- const expected = 1_000_000_000n; // 1 second in nanoseconds
92
- const actual = now - _lastCheck;
93
- _lag = Math.max(0, Number(actual - expected) / 1e6); // ms
94
- _lastCheck = now;
95
- };
96
-
97
- const timer = setInterval(_check, 1000);
98
- if (timer.unref) timer.unref();
99
-
100
- const check = () => ({
101
- healthy: _lag < maxLag,
102
- details: { lagMs: Math.round(_lag * 100) / 100, maxLagMs: maxLag },
103
- });
104
-
105
- // Expose cleanup for testing
106
- check._cleanup = () => clearInterval(timer);
107
- return check;
108
- }
109
-
110
- /**
111
- * Check available disk space (simple heuristic using os.freemem).
112
- *
113
- * @param {object} [opts] - Check options.
114
- * @param {number} [opts.minFreeBytes=104857600] - Minimum free memory in bytes (default: 100MB).
115
- * @returns {Function} Check function.
116
- */
117
- function diskSpaceCheck(opts = {})
118
- {
119
- const minFree = opts.minFreeBytes || 104857600; // 100MB
120
-
121
- return () =>
122
- {
123
- const free = os.freemem();
124
- return {
125
- healthy: free > minFree,
126
- details: {
127
- freeMemory: free,
128
- totalMemory: os.totalmem(),
129
- minRequired: minFree,
130
- },
131
- };
132
- };
133
- }
134
-
135
- // -- Health Check Handler ------------------------------------------
136
-
137
- /**
138
- * Create a health check route handler.
139
- *
140
- * Returns a JSON response with the status of all registered checks.
141
- * Returns `200` when all checks pass, `503` when any check fails
142
- * or when the application is in drain/shutdown state.
143
- *
144
- * Response format:
145
- * ```json
146
- * {
147
- * "status": "healthy",
148
- * "uptime": 12345,
149
- * "timestamp": "2026-01-01T00:00:00.000Z",
150
- * "checks": {
151
- * "database": { "healthy": true, "duration": 5, "details": {} }
152
- * }
153
- * }
154
- * ```
155
- *
156
- * @param {object} [opts] - Options.
157
- * @param {Object<string, Function>} [opts.checks] - Named check functions. Each returns `{ healthy, details }` or a boolean/Promise.
158
- * @param {number} [opts.timeout=5000] - Max time to wait for all checks in ms.
159
- * @param {boolean} [opts.verbose=true] - Include check details in response.
160
- * @param {Function} [opts.onFailure] - `(results) => void` — called when any check fails.
161
- * @returns {Function} Route handler `(req, res) => void`.
162
- *
163
- * @example
164
- * app.get('/healthz', healthCheck());
165
- *
166
- * @example
167
- * app.get('/readyz', healthCheck({
168
- * checks: {
169
- * database: async () => {
170
- * await db.ping();
171
- * return { healthy: true };
172
- * },
173
- * cache: () => ({ healthy: cacheClient.isConnected }),
174
- * },
175
- * }));
176
- *
177
- * @example | Auto-deregister from Load Balancer
178
- * app.get('/readyz', healthCheck({
179
- * checks: {
180
- * lifecycle: () => ({ healthy: app.lifecycleState === 'running' }),
181
- * },
182
- * }));
183
- */
184
- function healthCheck(opts = {})
185
- {
186
- const checks = opts.checks || {};
187
- const timeout = opts.timeout || 5000;
188
- const verbose = opts.verbose !== false;
189
- const onFailure = typeof opts.onFailure === 'function' ? opts.onFailure : null;
190
-
191
- return async (req, res) =>
192
- {
193
- const start = Date.now();
194
-
195
- // Check lifecycle state (auto-deregister during shutdown)
196
- const app = req.app;
197
- if (app && app.lifecycleState && app.lifecycleState !== 'running')
198
- {
199
- res.status(503).json({
200
- status: 'unavailable',
201
- reason: 'shutdown',
202
- lifecycleState: app.lifecycleState,
203
- timestamp: new Date().toISOString(),
204
- });
205
- return;
206
- }
207
-
208
- const checkNames = Object.keys(checks);
209
- const results = {};
210
- let allHealthy = true;
211
-
212
- if (checkNames.length > 0)
213
- {
214
- // Run all checks concurrently with timeout
215
- const promises = checkNames.map(async (name) =>
216
- {
217
- const checkStart = Date.now();
218
- try
219
- {
220
- const result = await Promise.race([
221
- Promise.resolve(checks[name]()),
222
- new Promise((_, reject) =>
223
- setTimeout(() => reject(new Error('Check timed out')), timeout)
224
- ),
225
- ]);
226
-
227
- const duration = Date.now() - checkStart;
228
-
229
- if (typeof result === 'boolean')
230
- {
231
- results[name] = { healthy: result, duration };
232
- }
233
- else if (result && typeof result === 'object')
234
- {
235
- results[name] = { healthy: !!result.healthy, duration };
236
- if (verbose && result.details) results[name].details = result.details;
237
- }
238
- else
239
- {
240
- results[name] = { healthy: true, duration };
241
- }
242
- }
243
- catch (err)
244
- {
245
- results[name] = {
246
- healthy: false,
247
- duration: Date.now() - checkStart,
248
- error: err.message,
249
- };
250
- }
251
-
252
- if (!results[name].healthy) allHealthy = false;
253
- });
254
-
255
- await Promise.all(promises);
256
- }
257
-
258
- const body = {
259
- status: allHealthy ? 'healthy' : 'unhealthy',
260
- uptime: process.uptime(),
261
- timestamp: new Date().toISOString(),
262
- duration: Date.now() - start,
263
- };
264
-
265
- if (checkNames.length > 0) body.checks = results;
266
-
267
- if (!allHealthy && onFailure)
268
- {
269
- try { onFailure(results); }
270
- catch (_) { /* ignore callback errors */ }
271
- }
272
-
273
- res.status(allHealthy ? 200 : 503).json(body);
274
- };
275
- }
276
-
277
- // -- Convenience Health & Ready Factory ----------------------------
278
-
279
- /**
280
- * Create paired liveness and readiness handlers for an app.
281
- * Liveness includes basic process checks; readiness includes
282
- * all registered dependency checks.
283
- *
284
- * @param {object} [opts] - Options.
285
- * @param {Object<string, Function>} [opts.checks] - Named readiness checks.
286
- * @param {boolean} [opts.includeMemory=false] - Include memory check in liveness.
287
- * @param {boolean} [opts.includeEventLoop=false] - Include event loop lag check.
288
- * @param {number} [opts.timeout=5000] - Check timeout.
289
- * @returns {{ health: Function, ready: Function }} Route handlers.
290
- *
291
- * @example
292
- * const { health, ready } = createHealthHandlers({
293
- * checks: { database: () => db.ping() },
294
- * includeMemory: true,
295
- * });
296
- * app.get('/healthz', health);
297
- * app.get('/readyz', ready);
298
- */
299
- function createHealthHandlers(opts = {})
300
- {
301
- const livenessChecks = {};
302
- if (opts.includeMemory) livenessChecks.memory = memoryCheck(opts.memoryOpts);
303
- if (opts.includeEventLoop) livenessChecks.eventLoop = eventLoopCheck(opts.eventLoopOpts);
304
-
305
- const readinessChecks = { ...livenessChecks };
306
- if (opts.checks)
307
- {
308
- for (const [name, fn] of Object.entries(opts.checks))
309
- {
310
- readinessChecks[name] = fn;
311
- }
312
- }
313
-
314
- return {
315
- health: healthCheck({ checks: livenessChecks, timeout: opts.timeout }),
316
- ready: healthCheck({ checks: readinessChecks, timeout: opts.timeout, onFailure: opts.onFailure }),
317
- };
318
- }
319
-
320
- module.exports = {
321
- healthCheck,
322
- createHealthHandlers,
323
- memoryCheck,
324
- eventLoopCheck,
325
- diskSpaceCheck,
326
- };
1
+ /**
2
+ * @module observe/health
3
+ * @description Health check middleware with liveness and readiness probes.
4
+ * Kubernetes-compatible `/healthz` and `/readyz` endpoints with
5
+ * composable checks (database ping, memory, event loop lag,
6
+ * disk space) and custom check registration.
7
+ *
8
+ * Returns `200` when healthy, `503` when degraded or during
9
+ * shutdown drain phase, with a JSON body detailing each check.
10
+ *
11
+ * @example
12
+ * const { healthCheck } = require('@zero-server/sdk');
13
+ *
14
+ * app.get('/healthz', healthCheck());
15
+ * app.get('/readyz', healthCheck({
16
+ * checks: {
17
+ * database: () => db.ping(),
18
+ * cache: () => redis.ping(),
19
+ * },
20
+ * }));
21
+ *
22
+ * @example | Using the App Integration
23
+ * app.health('/healthz');
24
+ * app.ready('/readyz', {
25
+ * database: () => db.ping(),
26
+ * });
27
+ */
28
+ const os = require('os');
29
+
30
+ // -- Built-in Checks -----------------------------------------------
31
+
32
+ /**
33
+ * Check memory usage against a threshold.
34
+ *
35
+ * @param {object} [opts] - Check options.
36
+ * @param {number} [opts.maxHeapUsedPercent=90] - Max heap usage percentage.
37
+ * @param {number} [opts.maxRssBytes] - Max RSS in bytes.
38
+ * @returns {Function} Check function.
39
+ *
40
+ * @example
41
+ * app.get('/healthz', healthCheck({
42
+ * checks: { memory: memoryCheck({ maxHeapUsedPercent: 85 }) },
43
+ * }));
44
+ */
45
+ function memoryCheck(opts = {})
46
+ {
47
+ const maxPercent = typeof opts.maxHeapUsedPercent === 'number' ? opts.maxHeapUsedPercent : 90;
48
+ const maxRss = opts.maxRssBytes || Infinity;
49
+
50
+ return () =>
51
+ {
52
+ const mem = process.memoryUsage();
53
+ const heapPercent = (mem.heapUsed / mem.heapTotal) * 100;
54
+ const healthy = heapPercent < maxPercent && mem.rss < maxRss;
55
+
56
+ return {
57
+ healthy,
58
+ details: {
59
+ heapUsed: mem.heapUsed,
60
+ heapTotal: mem.heapTotal,
61
+ heapPercent: Math.round(heapPercent * 100) / 100,
62
+ rss: mem.rss,
63
+ external: mem.external,
64
+ },
65
+ };
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Check event loop lag against a threshold.
71
+ *
72
+ * @param {object} [opts] - Check options.
73
+ * @param {number} [opts.maxLagMs=500] - Max acceptable lag in ms.
74
+ * @returns {Function} Check function.
75
+ *
76
+ * @example
77
+ * app.get('/healthz', healthCheck({
78
+ * checks: { eventLoop: eventLoopCheck({ maxLagMs: 200 }) },
79
+ * }));
80
+ */
81
+ function eventLoopCheck(opts = {})
82
+ {
83
+ const maxLag = opts.maxLagMs || 500;
84
+ let _lastCheck = process.hrtime.bigint();
85
+ let _lag = 0;
86
+
87
+ // Sample event loop lag periodically
88
+ const _check = () =>
89
+ {
90
+ const now = process.hrtime.bigint();
91
+ const expected = 1_000_000_000n; // 1 second in nanoseconds
92
+ const actual = now - _lastCheck;
93
+ _lag = Math.max(0, Number(actual - expected) / 1e6); // ms
94
+ _lastCheck = now;
95
+ };
96
+
97
+ const timer = setInterval(_check, 1000);
98
+ if (timer.unref) timer.unref();
99
+
100
+ const check = () => ({
101
+ healthy: _lag < maxLag,
102
+ details: { lagMs: Math.round(_lag * 100) / 100, maxLagMs: maxLag },
103
+ });
104
+
105
+ // Expose cleanup for testing
106
+ check._cleanup = () => clearInterval(timer);
107
+ return check;
108
+ }
109
+
110
+ /**
111
+ * Check available disk space (simple heuristic using os.freemem).
112
+ *
113
+ * @param {object} [opts] - Check options.
114
+ * @param {number} [opts.minFreeBytes=104857600] - Minimum free memory in bytes (default: 100MB).
115
+ * @returns {Function} Check function.
116
+ */
117
+ function diskSpaceCheck(opts = {})
118
+ {
119
+ const minFree = opts.minFreeBytes || 104857600; // 100MB
120
+
121
+ return () =>
122
+ {
123
+ const free = os.freemem();
124
+ return {
125
+ healthy: free > minFree,
126
+ details: {
127
+ freeMemory: free,
128
+ totalMemory: os.totalmem(),
129
+ minRequired: minFree,
130
+ },
131
+ };
132
+ };
133
+ }
134
+
135
+ // -- Health Check Handler ------------------------------------------
136
+
137
+ /**
138
+ * Create a health check route handler.
139
+ *
140
+ * Returns a JSON response with the status of all registered checks.
141
+ * Returns `200` when all checks pass, `503` when any check fails
142
+ * or when the application is in drain/shutdown state.
143
+ *
144
+ * Response format:
145
+ * ```json
146
+ * {
147
+ * "status": "healthy",
148
+ * "uptime": 12345,
149
+ * "timestamp": "2026-01-01T00:00:00.000Z",
150
+ * "checks": {
151
+ * "database": { "healthy": true, "duration": 5, "details": {} }
152
+ * }
153
+ * }
154
+ * ```
155
+ *
156
+ * @param {object} [opts] - Options.
157
+ * @param {Object<string, Function>} [opts.checks] - Named check functions. Each returns `{ healthy, details }` or a boolean/Promise.
158
+ * @param {number} [opts.timeout=5000] - Max time to wait for all checks in ms.
159
+ * @param {boolean} [opts.verbose=true] - Include check details in response.
160
+ * @param {Function} [opts.onFailure] - `(results) => void` — called when any check fails.
161
+ * @returns {Function} Route handler `(req, res) => void`.
162
+ *
163
+ * @example
164
+ * app.get('/healthz', healthCheck());
165
+ *
166
+ * @example
167
+ * app.get('/readyz', healthCheck({
168
+ * checks: {
169
+ * database: async () => {
170
+ * await db.ping();
171
+ * return { healthy: true };
172
+ * },
173
+ * cache: () => ({ healthy: cacheClient.isConnected }),
174
+ * },
175
+ * }));
176
+ *
177
+ * @example | Auto-deregister from Load Balancer
178
+ * app.get('/readyz', healthCheck({
179
+ * checks: {
180
+ * lifecycle: () => ({ healthy: app.lifecycleState === 'running' }),
181
+ * },
182
+ * }));
183
+ */
184
+ function healthCheck(opts = {})
185
+ {
186
+ const checks = opts.checks || {};
187
+ const timeout = opts.timeout || 5000;
188
+ const verbose = opts.verbose !== false;
189
+ const onFailure = typeof opts.onFailure === 'function' ? opts.onFailure : null;
190
+
191
+ return async (req, res) =>
192
+ {
193
+ const start = Date.now();
194
+
195
+ // Check lifecycle state (auto-deregister during shutdown)
196
+ const app = req.app;
197
+ if (app && app.lifecycleState && app.lifecycleState !== 'running')
198
+ {
199
+ res.status(503).json({
200
+ status: 'unavailable',
201
+ reason: 'shutdown',
202
+ lifecycleState: app.lifecycleState,
203
+ timestamp: new Date().toISOString(),
204
+ });
205
+ return;
206
+ }
207
+
208
+ const checkNames = Object.keys(checks);
209
+ const results = {};
210
+ let allHealthy = true;
211
+
212
+ if (checkNames.length > 0)
213
+ {
214
+ // Run all checks concurrently with timeout
215
+ const promises = checkNames.map(async (name) =>
216
+ {
217
+ const checkStart = Date.now();
218
+ try
219
+ {
220
+ const result = await Promise.race([
221
+ Promise.resolve(checks[name]()),
222
+ new Promise((_, reject) =>
223
+ setTimeout(() => reject(new Error('Check timed out')), timeout)
224
+ ),
225
+ ]);
226
+
227
+ const duration = Date.now() - checkStart;
228
+
229
+ if (typeof result === 'boolean')
230
+ {
231
+ results[name] = { healthy: result, duration };
232
+ }
233
+ else if (result && typeof result === 'object')
234
+ {
235
+ results[name] = { healthy: !!result.healthy, duration };
236
+ if (verbose && result.details) results[name].details = result.details;
237
+ }
238
+ else
239
+ {
240
+ results[name] = { healthy: true, duration };
241
+ }
242
+ }
243
+ catch (err)
244
+ {
245
+ results[name] = {
246
+ healthy: false,
247
+ duration: Date.now() - checkStart,
248
+ error: err.message,
249
+ };
250
+ }
251
+
252
+ if (!results[name].healthy) allHealthy = false;
253
+ });
254
+
255
+ await Promise.all(promises);
256
+ }
257
+
258
+ const body = {
259
+ status: allHealthy ? 'healthy' : 'unhealthy',
260
+ uptime: process.uptime(),
261
+ timestamp: new Date().toISOString(),
262
+ duration: Date.now() - start,
263
+ };
264
+
265
+ if (checkNames.length > 0) body.checks = results;
266
+
267
+ if (!allHealthy && onFailure)
268
+ {
269
+ try { onFailure(results); }
270
+ catch (_) { /* ignore callback errors */ }
271
+ }
272
+
273
+ res.status(allHealthy ? 200 : 503).json(body);
274
+ };
275
+ }
276
+
277
+ // -- Convenience Health & Ready Factory ----------------------------
278
+
279
+ /**
280
+ * Create paired liveness and readiness handlers for an app.
281
+ * Liveness includes basic process checks; readiness includes
282
+ * all registered dependency checks.
283
+ *
284
+ * @param {object} [opts] - Options.
285
+ * @param {Object<string, Function>} [opts.checks] - Named readiness checks.
286
+ * @param {boolean} [opts.includeMemory=false] - Include memory check in liveness.
287
+ * @param {boolean} [opts.includeEventLoop=false] - Include event loop lag check.
288
+ * @param {number} [opts.timeout=5000] - Check timeout.
289
+ * @returns {{ health: Function, ready: Function }} Route handlers.
290
+ *
291
+ * @example
292
+ * const { health, ready } = createHealthHandlers({
293
+ * checks: { database: () => db.ping() },
294
+ * includeMemory: true,
295
+ * });
296
+ * app.get('/healthz', health);
297
+ * app.get('/readyz', ready);
298
+ */
299
+ function createHealthHandlers(opts = {})
300
+ {
301
+ const livenessChecks = {};
302
+ if (opts.includeMemory) livenessChecks.memory = memoryCheck(opts.memoryOpts);
303
+ if (opts.includeEventLoop) livenessChecks.eventLoop = eventLoopCheck(opts.eventLoopOpts);
304
+
305
+ const readinessChecks = { ...livenessChecks };
306
+ if (opts.checks)
307
+ {
308
+ for (const [name, fn] of Object.entries(opts.checks))
309
+ {
310
+ readinessChecks[name] = fn;
311
+ }
312
+ }
313
+
314
+ return {
315
+ health: healthCheck({ checks: livenessChecks, timeout: opts.timeout }),
316
+ ready: healthCheck({ checks: readinessChecks, timeout: opts.timeout, onFailure: opts.onFailure }),
317
+ };
318
+ }
319
+
320
+ module.exports = {
321
+ healthCheck,
322
+ createHealthHandlers,
323
+ memoryCheck,
324
+ eventLoopCheck,
325
+ diskSpaceCheck,
326
+ };