@zero-server/sdk 0.9.0

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 -0
  2. package/README.md +437 -0
  3. package/index.js +412 -0
  4. package/lib/app.js +1172 -0
  5. package/lib/auth/authorize.js +399 -0
  6. package/lib/auth/enrollment.js +367 -0
  7. package/lib/auth/index.js +57 -0
  8. package/lib/auth/jwt.js +731 -0
  9. package/lib/auth/oauth.js +362 -0
  10. package/lib/auth/session.js +588 -0
  11. package/lib/auth/trustedDevice.js +409 -0
  12. package/lib/auth/twoFactor.js +1150 -0
  13. package/lib/auth/webauthn.js +946 -0
  14. package/lib/body/index.js +14 -0
  15. package/lib/body/json.js +109 -0
  16. package/lib/body/multipart.js +440 -0
  17. package/lib/body/raw.js +71 -0
  18. package/lib/body/rawBuffer.js +161 -0
  19. package/lib/body/sendError.js +25 -0
  20. package/lib/body/text.js +75 -0
  21. package/lib/body/typeMatch.js +42 -0
  22. package/lib/body/urlencoded.js +235 -0
  23. package/lib/cli.js +845 -0
  24. package/lib/cluster.js +666 -0
  25. package/lib/debug.js +372 -0
  26. package/lib/env/index.js +465 -0
  27. package/lib/errors.js +683 -0
  28. package/lib/fetch/index.js +256 -0
  29. package/lib/grpc/balancer.js +378 -0
  30. package/lib/grpc/call.js +708 -0
  31. package/lib/grpc/client.js +764 -0
  32. package/lib/grpc/codec.js +1221 -0
  33. package/lib/grpc/credentials.js +398 -0
  34. package/lib/grpc/frame.js +262 -0
  35. package/lib/grpc/health.js +287 -0
  36. package/lib/grpc/index.js +121 -0
  37. package/lib/grpc/metadata.js +461 -0
  38. package/lib/grpc/proto.js +821 -0
  39. package/lib/grpc/reflection.js +590 -0
  40. package/lib/grpc/server.js +445 -0
  41. package/lib/grpc/status.js +118 -0
  42. package/lib/grpc/watch.js +173 -0
  43. package/lib/http/index.js +10 -0
  44. package/lib/http/request.js +727 -0
  45. package/lib/http/response.js +799 -0
  46. package/lib/lifecycle.js +557 -0
  47. package/lib/middleware/compress.js +230 -0
  48. package/lib/middleware/cookieParser.js +237 -0
  49. package/lib/middleware/cors.js +93 -0
  50. package/lib/middleware/csrf.js +137 -0
  51. package/lib/middleware/errorHandler.js +101 -0
  52. package/lib/middleware/helmet.js +176 -0
  53. package/lib/middleware/index.js +17 -0
  54. package/lib/middleware/logger.js +74 -0
  55. package/lib/middleware/rateLimit.js +88 -0
  56. package/lib/middleware/requestId.js +54 -0
  57. package/lib/middleware/static.js +326 -0
  58. package/lib/middleware/timeout.js +72 -0
  59. package/lib/middleware/validator.js +255 -0
  60. package/lib/observe/health.js +326 -0
  61. package/lib/observe/index.js +50 -0
  62. package/lib/observe/logger.js +359 -0
  63. package/lib/observe/metrics.js +805 -0
  64. package/lib/observe/tracing.js +592 -0
  65. package/lib/orm/adapters/json.js +290 -0
  66. package/lib/orm/adapters/memory.js +764 -0
  67. package/lib/orm/adapters/mongo.js +764 -0
  68. package/lib/orm/adapters/mysql.js +933 -0
  69. package/lib/orm/adapters/postgres.js +1144 -0
  70. package/lib/orm/adapters/redis.js +1534 -0
  71. package/lib/orm/adapters/sql-base.js +212 -0
  72. package/lib/orm/adapters/sqlite.js +858 -0
  73. package/lib/orm/audit.js +649 -0
  74. package/lib/orm/cache.js +394 -0
  75. package/lib/orm/geo.js +387 -0
  76. package/lib/orm/index.js +784 -0
  77. package/lib/orm/migrate.js +432 -0
  78. package/lib/orm/model.js +1706 -0
  79. package/lib/orm/plugin.js +375 -0
  80. package/lib/orm/procedures.js +836 -0
  81. package/lib/orm/profiler.js +233 -0
  82. package/lib/orm/query.js +1772 -0
  83. package/lib/orm/replicas.js +241 -0
  84. package/lib/orm/schema.js +307 -0
  85. package/lib/orm/search.js +380 -0
  86. package/lib/orm/seed/data/commerce.js +136 -0
  87. package/lib/orm/seed/data/internet.js +111 -0
  88. package/lib/orm/seed/data/locations.js +204 -0
  89. package/lib/orm/seed/data/names.js +338 -0
  90. package/lib/orm/seed/data/person.js +128 -0
  91. package/lib/orm/seed/data/phone.js +211 -0
  92. package/lib/orm/seed/data/words.js +134 -0
  93. package/lib/orm/seed/factory.js +178 -0
  94. package/lib/orm/seed/fake.js +1186 -0
  95. package/lib/orm/seed/index.js +18 -0
  96. package/lib/orm/seed/rng.js +71 -0
  97. package/lib/orm/seed/seeder.js +125 -0
  98. package/lib/orm/seed/unique.js +68 -0
  99. package/lib/orm/snapshot.js +366 -0
  100. package/lib/orm/tenancy.js +605 -0
  101. package/lib/orm/views.js +350 -0
  102. package/lib/router/index.js +436 -0
  103. package/lib/sse/index.js +8 -0
  104. package/lib/sse/stream.js +349 -0
  105. package/lib/ws/connection.js +451 -0
  106. package/lib/ws/handshake.js +125 -0
  107. package/lib/ws/index.js +14 -0
  108. package/lib/ws/room.js +223 -0
  109. package/package.json +73 -0
  110. package/types/app.d.ts +223 -0
  111. package/types/auth.d.ts +520 -0
  112. package/types/cluster.d.ts +75 -0
  113. package/types/env.d.ts +80 -0
  114. package/types/errors.d.ts +316 -0
  115. package/types/fetch.d.ts +43 -0
  116. package/types/grpc.d.ts +432 -0
  117. package/types/index.d.ts +384 -0
  118. package/types/lifecycle.d.ts +60 -0
  119. package/types/middleware.d.ts +320 -0
  120. package/types/observe.d.ts +304 -0
  121. package/types/orm.d.ts +1887 -0
  122. package/types/request.d.ts +109 -0
  123. package/types/response.d.ts +157 -0
  124. package/types/router.d.ts +78 -0
  125. package/types/sse.d.ts +78 -0
  126. package/types/websocket.d.ts +126 -0
@@ -0,0 +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
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @module observe
3
+ * @description Observability suite — structured logging, metrics, tracing,
4
+ * and health checks. Zero external dependencies.
5
+ */
6
+ const { Logger, structuredLogger, LEVELS, LEVEL_NAMES } = require('./logger');
7
+ const {
8
+ Counter, Gauge, Histogram,
9
+ MetricsRegistry, DEFAULT_BUCKETS,
10
+ createDefaultMetrics, metricsMiddleware, metricsEndpoint,
11
+ } = require('./metrics');
12
+ const {
13
+ Span, Tracer,
14
+ parseTraceparent, formatTraceparent,
15
+ tracingMiddleware, instrumentFetch,
16
+ } = require('./tracing');
17
+ const {
18
+ healthCheck, createHealthHandlers,
19
+ memoryCheck, eventLoopCheck, diskSpaceCheck,
20
+ } = require('./health');
21
+
22
+ module.exports = {
23
+ // Structured Logging
24
+ Logger,
25
+ structuredLogger,
26
+ LEVELS,
27
+ LEVEL_NAMES,
28
+ // Metrics
29
+ Counter,
30
+ Gauge,
31
+ Histogram,
32
+ MetricsRegistry,
33
+ DEFAULT_BUCKETS,
34
+ createDefaultMetrics,
35
+ metricsMiddleware,
36
+ metricsEndpoint,
37
+ // Tracing
38
+ Span,
39
+ Tracer,
40
+ parseTraceparent,
41
+ formatTraceparent,
42
+ tracingMiddleware,
43
+ instrumentFetch,
44
+ // Health Checks
45
+ healthCheck,
46
+ createHealthHandlers,
47
+ memoryCheck,
48
+ eventLoopCheck,
49
+ diskSpaceCheck,
50
+ };