@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tony Wiedman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,437 @@
1
+ <p align="center">
2
+ <img src="documentation/public/icons/logo-animated.svg" alt="zero-server logo" width="300" height="300">
3
+ </p>
4
+
5
+ <h1 align="center">zero-server</h1>
6
+
7
+ [![npm version](https://img.shields.io/npm/v/%40zero-server%2Fsdk.svg)](https://www.npmjs.com/package/@zero-server/sdk)
8
+ [![npm downloads](https://img.shields.io/npm/dm/%40zero-server%2Fsdk.svg)](https://www.npmjs.com/package/@zero-server/sdk)
9
+ [![GitHub](https://img.shields.io/badge/GitHub-zero--server-blue.svg)](https://github.com/tonywied17/zero-server)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
11
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org)
12
+ [![Dependencies](https://img.shields.io/badge/dependencies-0-success.svg)](package.json)
13
+ [![Tests](https://img.shields.io/badge/tests-7385%20passed-brightgreen.svg)](https://github.com/tonywied17/zero-server/actions)
14
+ [![Coverage](https://img.shields.io/badge/coverage-97.01%25-brightgreen.svg)](https://github.com/tonywied17/zero-server)
15
+
16
+ > **Zero-dependency backend framework for Node.js — routing, ORM, auth, WebSocket, SSE, observability, and 20+ middleware from a single `require`.**
17
+
18
+ <p align="center">
19
+ <strong>
20
+ <a href="https://z-server.com">📖 Full Documentation &amp; Live Playground →</a>
21
+ </strong>
22
+ </p>
23
+
24
+ ---
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ npm install @zero-server/sdk
30
+ ```
31
+
32
+ Requires Node.js 18+. No external dependencies — everything is built on Node.js core APIs.
33
+
34
+ ### Or install only what you need (scoped packages)
35
+
36
+ `@zero-server/sdk` is the meta-package that re-exports every module. If you want a smaller install footprint, every section of the SDK is also published as its own scoped package and re-exports just that surface from the SDK:
37
+
38
+ | Package | Surface |
39
+ |---|---|
40
+ | `@zero-server/core` | `createApp`, `Router`, `Request`, `Response` |
41
+ | `@zero-server/body` | `json`, `urlencoded`, `text`, `raw`, `multipart` |
42
+ | `@zero-server/middleware` | `cors`, `helmet`, `compress`, `rateLimit`, `logger`, `timeout`, `requestId`, `cookieParser`, `csrf`, `validate`, `errorHandler`, `static` |
43
+ | `@zero-server/auth` | `jwt`, `session`, `oauth`, `authorize`, `twoFactor`, `webauthn`, `trustedDevice`, `enrollment` |
44
+ | `@zero-server/orm` | `Database`, `Model`, `Query`, `TYPES`, migrations, seeders, replicas, search, geo, tenancy, audit |
45
+ | `@zero-server/realtime` | `WebSocketConnection`, `WebSocketPool`, `SSEStream` |
46
+ | `@zero-server/grpc` | gRPC server, client, codec, status, metadata, framing, health, reflection, balancer |
47
+ | `@zero-server/observe` | `MetricsRegistry`, `Tracer`, structured `Logger`, health checks |
48
+ | `@zero-server/lifecycle` | `LifecycleManager`, `ClusterManager`, `clusterize` |
49
+ | `@zero-server/env` | typed `.env` loader |
50
+ | `@zero-server/fetch` | server-side `fetch` client |
51
+ | `@zero-server/errors` | every typed `HttpError` class plus ORM/framework errors |
52
+
53
+ ```bash
54
+ npm install @zero-server/core @zero-server/body @zero-server/middleware
55
+ ```
56
+
57
+ > All scoped packages depend on `@zero-server/sdk` and pin to the same version, so mixing-and-matching is safe.
58
+
59
+ ---
60
+
61
+ ## Quick Start
62
+
63
+ ```js
64
+ const { createApp, json } = require('@zero-server/sdk')
65
+ const app = createApp()
66
+
67
+ app.use(json())
68
+ app.post('/echo', (req, res) => res.json({ received: req.body }))
69
+ app.listen(3000, () => console.log('Listening on :3000'))
70
+ ```
71
+
72
+ ---
73
+
74
+ ## Features
75
+
76
+ ### Routing
77
+
78
+ `get`, `post`, `put`, `delete`, `patch`, `head`, `options`, `all`, plus `Router()` sub-apps with `use()` mounting. Route chaining via `chain(path)`, route grouping via `group(prefix, ...mw, cb)`, wildcard & parameter patterns, and `param()` pre-processing. Full route introspection with `routes()`.
79
+
80
+ ### Body Parsers
81
+
82
+ `json()`, `urlencoded()`, `text()`, `raw()`, and `multipart()` with streaming file uploads, size limits, and progress tracking.
83
+
84
+ ### Middleware
85
+
86
+ 20+ built-in middleware — all zero-dependency:
87
+
88
+ | Middleware | Purpose |
89
+ |---|---|
90
+ | `cors()` | Cross-origin resource sharing |
91
+ | `helmet()` | Security headers |
92
+ | `compress()` | Gzip, Brotli, and deflate compression |
93
+ | `rateLimit()` | Per-IP request throttling |
94
+ | `logger()` | Request logging with timing and colors |
95
+ | `timeout()` | Request timeout enforcement |
96
+ | `requestId()` | Unique request IDs |
97
+ | `cookieParser()` | Cookie parsing with signed cookie support |
98
+ | `csrf()` | CSRF token protection |
99
+ | `validate()` | Schema-based request validation |
100
+ | `errorHandler()` | Centralized error handling |
101
+ | `static()` | Static file serving with ETags and HTTP/2 push |
102
+
103
+ ### Authentication & Authorization
104
+
105
+ Full auth stack with no external libraries:
106
+
107
+ - **JWT** — `jwt()` middleware, `jwtSign()`, `jwtVerify()`, `jwtDecode()`, JWKS key sets, access/refresh token pairs
108
+ - **Sessions** — `session()` middleware with in-memory store (pluggable)
109
+ - **OAuth 2.0** — `oauth()` middleware with PKCE, pre-configured providers (Google, GitHub, Microsoft, etc.)
110
+ - **Authorization** — `authorize()` policies, `can()` / `canAny()` permission checks, `gate()` middleware
111
+
112
+ ### ORM & Database
113
+
114
+ Full-featured ORM with 7 adapters — memory, JSON file, SQLite, MySQL, PostgreSQL, MongoDB, and Redis:
115
+
116
+ ```js
117
+ const { Database, Model, TYPES } = require('@zero-server/sdk')
118
+
119
+ const db = Database.connect('sqlite', { filename: 'app.db' })
120
+
121
+ class User extends Model {
122
+ static table = 'users'
123
+ static schema = {
124
+ name: { type: TYPES.STRING, required: true },
125
+ email: { type: TYPES.STRING, unique: true },
126
+ }
127
+ }
128
+
129
+ db.register(User)
130
+ await db.sync()
131
+
132
+ await User.create({ name: 'Alice', email: 'alice@example.com' })
133
+ const users = await User.find({ name: 'Alice' })
134
+ ```
135
+
136
+ **Query builder** — `where()`, `select()`, `orderBy()`, `limit()`, `offset()`, `join()`, `groupBy()`, `having()`, `paginate()`, `findOrCreate()`
137
+
138
+ **Advanced ORM features:**
139
+
140
+ | Feature | Description |
141
+ |---|---|
142
+ | Migrations | `Migrator` with up/down, rollback, and status tracking |
143
+ | Seeding | `Seeder`, `Factory`, and `Fake` for test data generation |
144
+ | Query caching | In-memory LRU cache with TTL and write-through invalidation |
145
+ | Read replicas | `ReplicaManager` with automatic primary/replica routing |
146
+ | Full-text search | `FullTextSearch` with indexing and ranked results |
147
+ | Geo queries | `GeoQuery` with distance, bounding box, and nearest-neighbor |
148
+ | Multi-tenancy | `TenantManager` with isolated per-tenant scoping |
149
+ | Audit logging | `AuditLog` for change tracking with diffs and user attribution |
150
+ | Schema snapshots | EF Core-style snapshot diffing with auto-generated migrations |
151
+ | Query profiler | N+1 detection, slow query tracking, and execution analysis |
152
+ | Views & procedures | `DatabaseView`, `StoredProcedure`, `StoredFunction`, `TriggerManager` |
153
+ | Plugins | `PluginManager` for extending ORM behavior |
154
+
155
+ ### Real-Time
156
+
157
+ - **WebSocket** — `app.ws(path, handler)` with RFC 6455, `WebSocketPool` for rooms, broadcasting, and sub-protocols
158
+ - **Server-Sent Events** — `res.sse()` with auto-IDs, named events, and keep-alive
159
+
160
+ ### Observability
161
+
162
+ Built-in Prometheus metrics, health checks, distributed tracing, and structured logging — zero dependencies.
163
+
164
+ ```js
165
+ const { createApp, metricsMiddleware } = require('@zero-server/sdk')
166
+ const app = createApp()
167
+
168
+ // Auto-instrument all HTTP requests (counters, histograms, active connections)
169
+ app.use(metricsMiddleware({ registry: app.metrics() }))
170
+
171
+ // Expose endpoints
172
+ app.metricsEndpoint() // GET /metrics (Prometheus scrape target)
173
+ app.health() // GET /healthz (liveness probe)
174
+ app.ready() // GET /readyz (readiness probe)
175
+
176
+ // Custom metrics
177
+ const logins = app.metrics().counter({
178
+ name: 'user_logins_total',
179
+ help: 'Total login attempts',
180
+ labels: ['provider'],
181
+ })
182
+ logins.inc({ provider: 'github' })
183
+
184
+ app.listen(3000)
185
+ ```
186
+
187
+ **Scrape with Prometheus** — create a `prometheus.yml`:
188
+
189
+ ```yaml
190
+ scrape_configs:
191
+ - job_name: 'my-app'
192
+ scrape_interval: 5s
193
+ static_configs:
194
+ - targets: ['localhost:3000']
195
+ ```
196
+
197
+ ```bash
198
+ docker run -d -p 9090:9090 -v ./prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
199
+ # Open http://localhost:9090 → Graph → query http_requests_total
200
+ ```
201
+
202
+ **Also includes:**
203
+ - **Distributed tracing** — `Tracer` and `Span` with W3C Trace Context (`traceparent` propagation), `instrumentFetch()` for outgoing requests
204
+ - **Structured logging** — `Logger` with levels, JSON output, and namespaced `debug()` logger
205
+
206
+ ### Lifecycle & Clustering
207
+
208
+ - **Graceful shutdown** — signal handlers (SIGTERM/SIGINT), in-flight request draining, automatic WebSocket/SSE/database cleanup
209
+ - **Clustering** — `clusterize()` for multi-worker processes with auto-respawn and exponential backoff
210
+
211
+ ### CLI
212
+
213
+ Scaffolding and database management via `npx zh`:
214
+
215
+ ```bash
216
+ npx zh migrate # run pending migrations
217
+ npx zh migrate:rollback # rollback last migration
218
+ npx zh migrate:status # show migration status
219
+ npx zh seed # run seeders
220
+ npx zh make:model User # scaffold a model
221
+ npx zh make:migration name # create migration file
222
+ npx zh make:seeder User # create seeder file
223
+ ```
224
+
225
+ ### Environment Config
226
+
227
+ Typed `.env` loader with schema validation, multi-file support (`.env`, `.env.local`, `.env.{NODE_ENV}`), variable interpolation, and type coercion (string, number, boolean, integer, array, json, url, port, enum).
228
+
229
+ ### HTTP Client
230
+
231
+ Built-in `fetch()` with HTTPS/mTLS support, timeouts, `AbortSignal`, progress callbacks, and JSON/form/stream bodies.
232
+
233
+ ### HTTPS & HTTP/2
234
+
235
+ ```js
236
+ app.listen(443, {
237
+ key: fs.readFileSync('key.pem'),
238
+ cert: fs.readFileSync('cert.pem'),
239
+ }, () => console.log('HTTPS on 443'))
240
+ ```
241
+
242
+ Native HTTP/2 with automatic HTTP/1.1 fallback. `req.secure`, `req.protocol`, `ws.secure`, and `sse.secure` everywhere.
243
+
244
+ ### Error Handling
245
+
246
+ 20+ typed error classes (`NotFoundError`, `ValidationError`, `ForbiddenError`, `PayloadTooLargeError`, `DatabaseError`, `MigrationError`, etc.) plus `createError(status, message)` factory and `isHttpError()` check. Built-in CRLF injection prevention, prototype pollution filtering, path traversal guards, and filename sanitization.
247
+
248
+ ### TypeScript
249
+
250
+ Full type definitions for every API, middleware option, ORM model, auth flow, and plugin interface.
251
+
252
+ ---
253
+
254
+ ## Production Example
255
+
256
+ ```js
257
+ const path = require('path')
258
+ const {
259
+ createApp, Router, cors, json, urlencoded, compress,
260
+ helmet, timeout, requestId, cookieParser, logger,
261
+ static: serveStatic, rateLimit, jwt, session,
262
+ Database, Model, TYPES, env, clusterize,
263
+ WebSocketPool,
264
+ } = require('@zero-server/sdk')
265
+
266
+ env.load({
267
+ PORT: { type: 'port', default: 3000 },
268
+ JWT_SECRET: { type: 'string', required: true },
269
+ DB_PATH: { type: 'string', default: './data.db' },
270
+ })
271
+
272
+ clusterize(() => {
273
+ const app = createApp()
274
+ const db = Database.connect('sqlite', { filename: env.DB_PATH })
275
+
276
+ // Middleware stack
277
+ app.use(helmet())
278
+ app.use(logger())
279
+ app.use(cors())
280
+ app.use(compress())
281
+ app.use(timeout(30_000))
282
+ app.use(rateLimit())
283
+ app.use(cookieParser())
284
+ app.use(session({ secret: env.JWT_SECRET }))
285
+ app.use(json())
286
+ app.use(urlencoded())
287
+ app.use(serveStatic(path.join(__dirname, 'public')))
288
+
289
+ // Observability
290
+ app.health()
291
+ app.ready()
292
+ app.metricsEndpoint()
293
+
294
+ // API routes
295
+ const api = Router()
296
+ api.get('/health', (req, res) => res.json({ status: 'ok' }))
297
+ api.get('/users/:id', jwt({ secret: env.JWT_SECRET }), (req, res) => {
298
+ res.json({ id: req.params.id, user: req.user })
299
+ })
300
+ app.use('/api', api)
301
+
302
+ // WebSocket
303
+ const pool = new WebSocketPool()
304
+ app.ws('/chat', (ws) => {
305
+ pool.add(ws)
306
+ pool.join(ws, 'lobby')
307
+ ws.on('message', msg => pool.toRoom('lobby', msg, ws))
308
+ })
309
+
310
+ // SSE
311
+ app.get('/events', (req, res) => {
312
+ const sse = res.sse({ retry: 3000, autoId: true })
313
+ sse.send('connected')
314
+ })
315
+
316
+ app.listen(env.PORT, () => console.log(`Worker ${process.pid} on :${env.PORT}`))
317
+ })
318
+ ```
319
+
320
+ ---
321
+
322
+ ## Exports
323
+
324
+ All exports from the package root:
325
+
326
+ ```js
327
+ const {
328
+ // Core
329
+ createApp, Router, version,
330
+
331
+ // Body parsers
332
+ json, urlencoded, text, raw, multipart,
333
+
334
+ // Middleware
335
+ cors, helmet, compress, rateLimit, logger,
336
+ timeout, requestId, cookieParser, csrf,
337
+ validate, errorHandler, static: serveStatic,
338
+
339
+ // Auth
340
+ jwt, jwtSign, jwtVerify, jwtDecode, jwks, tokenPair,
341
+ session, Session, MemoryStore,
342
+ oauth, generatePKCE, generateState, OAUTH_PROVIDERS,
343
+ authorize, can, canAny, Policy, gate,
344
+
345
+ // ORM
346
+ Database, Model, TYPES, Query,
347
+ Migrator, defineMigration,
348
+ Seeder, SeederRunner, Factory, Fake,
349
+ QueryCache, QueryProfiler, ReplicaManager,
350
+ FullTextSearch, GeoQuery, TenantManager, AuditLog,
351
+ DatabaseView, StoredProcedure, StoredFunction, TriggerManager,
352
+ PluginManager, buildSnapshot, diffSnapshots,
353
+
354
+ // Observability
355
+ Logger, structuredLogger,
356
+ Counter, Gauge, Histogram, MetricsRegistry,
357
+ metricsMiddleware, metricsEndpoint,
358
+ Span, Tracer, tracingMiddleware, instrumentFetch,
359
+ healthCheck, memoryCheck, eventLoopCheck, diskSpaceCheck,
360
+
361
+ // Real-time
362
+ WebSocketConnection, WebSocketPool, SSEStream,
363
+
364
+ // Utilities
365
+ fetch, env, debug,
366
+ ClusterManager, clusterize,
367
+ LifecycleManager, LIFECYCLE_STATE,
368
+
369
+ // Errors
370
+ HttpError, BadRequestError, UnauthorizedError,
371
+ ForbiddenError, NotFoundError, ValidationError,
372
+ ConflictError, PayloadTooLargeError, TooManyRequestsError,
373
+ TimeoutError, DatabaseError, MigrationError,
374
+ createError, isHttpError,
375
+
376
+ // CLI
377
+ CLI, runCLI,
378
+ } = require('@zero-server/sdk')
379
+ ```
380
+
381
+ ---
382
+
383
+ ## Documentation
384
+
385
+ | Resource | Description |
386
+ |---|---|
387
+ | **[z-server.com](https://z-server.com)** | Interactive documentation with live playground, search, and examples |
388
+ | **[API.md](API.md)** | Full API reference with tables, examples, and options for every export |
389
+
390
+ ### Run docs locally
391
+
392
+ ```bash
393
+ cp documentation/.env.example documentation/.env
394
+ npm run docs
395
+ # open http://localhost:7273
396
+ ```
397
+
398
+ ---
399
+
400
+ ## File Layout
401
+
402
+ ```
403
+ lib/
404
+ app.js — App class (middleware, routing, listen, ws upgrade, lifecycle)
405
+ auth/ — JWT, OAuth 2.0, sessions, and authorization policies
406
+ body/ — body parsers (json, urlencoded, text, raw, multipart)
407
+ cli.js — CLI runner (migrate, seed, scaffold commands)
408
+ cluster.js — multi-worker clustering with auto-respawn
409
+ debug.js — namespaced debug logger
410
+ env/ — typed .env loader with schema validation
411
+ errors.js — 20+ HttpError classes and factory
412
+ fetch/ — HTTP/HTTPS client
413
+ http/ — Request & Response wrappers
414
+ lifecycle.js — graceful shutdown and lifecycle management
415
+ middleware/ — cors, helmet, logger, rateLimit, compress, static, timeout,
416
+ requestId, cookieParser, csrf, validate, errorHandler
417
+ observe/ — Prometheus metrics, W3C tracing, health checks, structured logging
418
+ orm/ — Database, Model, Query, adapters, migrations, seeds, cache,
419
+ replicas, search, geo, tenancy, audit, views, procedures, plugins
420
+ router/ — Router with sub-app mounting and pattern matching
421
+ sse/ — SSE stream controller
422
+ ws/ — WebSocket connection, handshake, and room management
423
+ types/ — full TypeScript definitions
424
+ documentation/ — live demo server, controllers, and playground UI
425
+ test/ — vitest test suite (6000+ tests, 95%+ coverage)
426
+ ```
427
+
428
+ ## Testing
429
+
430
+ ```bash
431
+ npm test # vitest run (single pass)
432
+ npm run test:watch # vitest (watch mode)
433
+ ```
434
+
435
+ ## License
436
+
437
+ MIT