qhttpx 2.1.0 → 2.3.1

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 (267) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +117 -221
  3. package/dist/chunk-QW72SEAS.mjs +98 -0
  4. package/dist/{src/cli/index.d.ts → cli.d.mts} +0 -1
  5. package/dist/cli.d.ts +1 -0
  6. package/dist/cli.js +287 -0
  7. package/dist/cli.mjs +209 -0
  8. package/dist/index.d.mts +433 -0
  9. package/dist/index.d.ts +433 -0
  10. package/dist/index.js +1955 -0
  11. package/dist/index.mjs +1863 -0
  12. package/dist/qhttpx-core-new.linux-x64-gnu.node +0 -0
  13. package/dist/qhttpx-core-new.node +0 -0
  14. package/dist/qhttpx-core-new.win32-x64-msvc.node +0 -0
  15. package/examples/benchmark.ts +67 -0
  16. package/examples/body_demo.ts +32 -0
  17. package/examples/chat_client.ts +36 -0
  18. package/examples/chat_demo.ts +41 -0
  19. package/examples/cluster_demo.ts +26 -0
  20. package/examples/cors_demo.ts +25 -0
  21. package/examples/db_auth_demo.ts +66 -0
  22. package/examples/demo.ts +52 -0
  23. package/examples/headers_demo.ts +24 -0
  24. package/examples/hello.ts +7 -0
  25. package/examples/http2_demo.ts +52 -0
  26. package/examples/magic-dev.ts +15 -0
  27. package/examples/middleware_demo.ts +34 -0
  28. package/examples/mongo_demo.ts +40 -0
  29. package/examples/native_policy_demo.ts +33 -0
  30. package/examples/observability_demo.ts +24 -0
  31. package/examples/public/1mb.dat +1 -0
  32. package/examples/query_demo.ts +29 -0
  33. package/examples/response_demo.ts +21 -0
  34. package/examples/routing_demo.ts +24 -0
  35. package/examples/server.ts +51 -0
  36. package/examples/static_demo.ts +29 -0
  37. package/examples/test_middleware_client.ts +33 -0
  38. package/examples/test_query_client.ts +34 -0
  39. package/examples/test_response_client.ts +30 -0
  40. package/examples/tls_demo.ts +32 -0
  41. package/examples/upload_demo.ts +43 -0
  42. package/examples/uploads/test.txt +1 -0
  43. package/examples/verify_upload.ts +69 -0
  44. package/examples/ws_client.ts +26 -0
  45. package/examples/ws_demo.ts +21 -0
  46. package/package.json +65 -81
  47. package/CHANGELOG.md +0 -285
  48. package/dist/examples/api-server.d.ts +0 -1
  49. package/dist/examples/api-server.js +0 -80
  50. package/dist/examples/basic.d.ts +0 -1
  51. package/dist/examples/basic.js +0 -9
  52. package/dist/examples/compression.d.ts +0 -1
  53. package/dist/examples/compression.js +0 -15
  54. package/dist/examples/cors.d.ts +0 -1
  55. package/dist/examples/cors.js +0 -18
  56. package/dist/examples/errors.d.ts +0 -1
  57. package/dist/examples/errors.js +0 -26
  58. package/dist/examples/file-upload.d.ts +0 -1
  59. package/dist/examples/file-upload.js +0 -22
  60. package/dist/examples/fusion.d.ts +0 -1
  61. package/dist/examples/fusion.js +0 -21
  62. package/dist/examples/rate-limiting.d.ts +0 -1
  63. package/dist/examples/rate-limiting.js +0 -17
  64. package/dist/examples/validation.d.ts +0 -1
  65. package/dist/examples/validation.js +0 -22
  66. package/dist/examples/websockets.d.ts +0 -1
  67. package/dist/examples/websockets.js +0 -19
  68. package/dist/package.json +0 -107
  69. package/dist/src/benchmarks/quantam-users.d.ts +0 -1
  70. package/dist/src/benchmarks/quantam-users.js +0 -56
  71. package/dist/src/benchmarks/quick-bench.d.ts +0 -1
  72. package/dist/src/benchmarks/quick-bench.js +0 -57
  73. package/dist/src/benchmarks/simple-json.d.ts +0 -1
  74. package/dist/src/benchmarks/simple-json.js +0 -171
  75. package/dist/src/benchmarks/ultra-mode.d.ts +0 -1
  76. package/dist/src/benchmarks/ultra-mode.js +0 -64
  77. package/dist/src/cli/index.js +0 -222
  78. package/dist/src/client/index.d.ts +0 -17
  79. package/dist/src/client/index.js +0 -72
  80. package/dist/src/core/batch.d.ts +0 -24
  81. package/dist/src/core/batch.js +0 -97
  82. package/dist/src/core/body-parser.d.ts +0 -15
  83. package/dist/src/core/body-parser.js +0 -121
  84. package/dist/src/core/buffer-pool.d.ts +0 -41
  85. package/dist/src/core/buffer-pool.js +0 -70
  86. package/dist/src/core/config.d.ts +0 -7
  87. package/dist/src/core/config.js +0 -50
  88. package/dist/src/core/context-pool.d.ts +0 -12
  89. package/dist/src/core/context-pool.js +0 -34
  90. package/dist/src/core/errors.d.ts +0 -34
  91. package/dist/src/core/errors.js +0 -70
  92. package/dist/src/core/fusion.d.ts +0 -20
  93. package/dist/src/core/fusion.js +0 -191
  94. package/dist/src/core/logger.d.ts +0 -22
  95. package/dist/src/core/logger.js +0 -49
  96. package/dist/src/core/metrics.d.ts +0 -50
  97. package/dist/src/core/metrics.js +0 -123
  98. package/dist/src/core/resources.d.ts +0 -9
  99. package/dist/src/core/resources.js +0 -25
  100. package/dist/src/core/scheduler.d.ts +0 -38
  101. package/dist/src/core/scheduler.js +0 -126
  102. package/dist/src/core/scope.d.ts +0 -41
  103. package/dist/src/core/scope.js +0 -107
  104. package/dist/src/core/serializer.d.ts +0 -10
  105. package/dist/src/core/serializer.js +0 -82
  106. package/dist/src/core/server.d.ts +0 -179
  107. package/dist/src/core/server.js +0 -1511
  108. package/dist/src/core/stream.d.ts +0 -15
  109. package/dist/src/core/stream.js +0 -71
  110. package/dist/src/core/tasks.d.ts +0 -29
  111. package/dist/src/core/tasks.js +0 -87
  112. package/dist/src/core/timer.d.ts +0 -11
  113. package/dist/src/core/timer.js +0 -29
  114. package/dist/src/core/types.d.ts +0 -225
  115. package/dist/src/core/types.js +0 -19
  116. package/dist/src/core/websocket.d.ts +0 -25
  117. package/dist/src/core/websocket.js +0 -86
  118. package/dist/src/core/worker-queue.d.ts +0 -41
  119. package/dist/src/core/worker-queue.js +0 -73
  120. package/dist/src/database/adapters/memory.d.ts +0 -21
  121. package/dist/src/database/adapters/memory.js +0 -90
  122. package/dist/src/database/adapters/mongo.d.ts +0 -11
  123. package/dist/src/database/adapters/mongo.js +0 -141
  124. package/dist/src/database/adapters/postgres.d.ts +0 -10
  125. package/dist/src/database/adapters/postgres.js +0 -111
  126. package/dist/src/database/adapters/sqlite.d.ts +0 -10
  127. package/dist/src/database/adapters/sqlite.js +0 -42
  128. package/dist/src/database/coalescer.d.ts +0 -14
  129. package/dist/src/database/coalescer.js +0 -134
  130. package/dist/src/database/manager.d.ts +0 -35
  131. package/dist/src/database/manager.js +0 -87
  132. package/dist/src/database/types.d.ts +0 -20
  133. package/dist/src/database/types.js +0 -2
  134. package/dist/src/index.d.ts +0 -52
  135. package/dist/src/index.js +0 -92
  136. package/dist/src/middleware/compression.d.ts +0 -2
  137. package/dist/src/middleware/compression.js +0 -133
  138. package/dist/src/middleware/cors.d.ts +0 -2
  139. package/dist/src/middleware/cors.js +0 -66
  140. package/dist/src/middleware/presets.d.ts +0 -15
  141. package/dist/src/middleware/presets.js +0 -52
  142. package/dist/src/middleware/rate-limit.d.ts +0 -14
  143. package/dist/src/middleware/rate-limit.js +0 -83
  144. package/dist/src/middleware/security.d.ts +0 -10
  145. package/dist/src/middleware/security.js +0 -74
  146. package/dist/src/middleware/static.d.ts +0 -11
  147. package/dist/src/middleware/static.js +0 -191
  148. package/dist/src/openapi/generator.d.ts +0 -19
  149. package/dist/src/openapi/generator.js +0 -149
  150. package/dist/src/router/radix-router.d.ts +0 -18
  151. package/dist/src/router/radix-router.js +0 -89
  152. package/dist/src/router/radix-tree.d.ts +0 -21
  153. package/dist/src/router/radix-tree.js +0 -175
  154. package/dist/src/router/router.d.ts +0 -37
  155. package/dist/src/router/router.js +0 -203
  156. package/dist/src/testing/index.d.ts +0 -25
  157. package/dist/src/testing/index.js +0 -84
  158. package/dist/src/utils/cookies.d.ts +0 -3
  159. package/dist/src/utils/cookies.js +0 -59
  160. package/dist/src/utils/logger.d.ts +0 -2
  161. package/dist/src/utils/logger.js +0 -45
  162. package/dist/src/utils/signals.d.ts +0 -6
  163. package/dist/src/utils/signals.js +0 -31
  164. package/dist/src/utils/sse.d.ts +0 -6
  165. package/dist/src/utils/sse.js +0 -32
  166. package/dist/src/validation/index.d.ts +0 -3
  167. package/dist/src/validation/index.js +0 -19
  168. package/dist/src/validation/simple.d.ts +0 -5
  169. package/dist/src/validation/simple.js +0 -102
  170. package/dist/src/validation/types.d.ts +0 -32
  171. package/dist/src/validation/types.js +0 -12
  172. package/dist/src/validation/zod.d.ts +0 -4
  173. package/dist/src/validation/zod.js +0 -18
  174. package/dist/src/views/index.d.ts +0 -1
  175. package/dist/src/views/index.js +0 -17
  176. package/dist/src/views/types.d.ts +0 -3
  177. package/dist/src/views/types.js +0 -2
  178. package/dist/tests/adapters.test.d.ts +0 -1
  179. package/dist/tests/adapters.test.js +0 -106
  180. package/dist/tests/batch.test.d.ts +0 -1
  181. package/dist/tests/batch.test.js +0 -117
  182. package/dist/tests/body-parser.test.d.ts +0 -1
  183. package/dist/tests/body-parser.test.js +0 -52
  184. package/dist/tests/compression-sse.test.d.ts +0 -1
  185. package/dist/tests/compression-sse.test.js +0 -87
  186. package/dist/tests/cookies.test.d.ts +0 -1
  187. package/dist/tests/cookies.test.js +0 -63
  188. package/dist/tests/cors.test.d.ts +0 -1
  189. package/dist/tests/cors.test.js +0 -55
  190. package/dist/tests/database.test.d.ts +0 -1
  191. package/dist/tests/database.test.js +0 -80
  192. package/dist/tests/dx.test.d.ts +0 -1
  193. package/dist/tests/dx.test.js +0 -114
  194. package/dist/tests/ecosystem.test.d.ts +0 -1
  195. package/dist/tests/ecosystem.test.js +0 -133
  196. package/dist/tests/features.test.d.ts +0 -1
  197. package/dist/tests/features.test.js +0 -47
  198. package/dist/tests/fusion.test.d.ts +0 -1
  199. package/dist/tests/fusion.test.js +0 -92
  200. package/dist/tests/http-basic.test.d.ts +0 -1
  201. package/dist/tests/http-basic.test.js +0 -124
  202. package/dist/tests/logger.test.d.ts +0 -1
  203. package/dist/tests/logger.test.js +0 -33
  204. package/dist/tests/middleware.test.d.ts +0 -1
  205. package/dist/tests/middleware.test.js +0 -109
  206. package/dist/tests/observability.test.d.ts +0 -1
  207. package/dist/tests/observability.test.js +0 -59
  208. package/dist/tests/openapi.test.d.ts +0 -1
  209. package/dist/tests/openapi.test.js +0 -64
  210. package/dist/tests/plugin.test.d.ts +0 -1
  211. package/dist/tests/plugin.test.js +0 -65
  212. package/dist/tests/plugins.test.d.ts +0 -1
  213. package/dist/tests/plugins.test.js +0 -71
  214. package/dist/tests/rate-limit.test.d.ts +0 -1
  215. package/dist/tests/rate-limit.test.js +0 -77
  216. package/dist/tests/resources.test.d.ts +0 -1
  217. package/dist/tests/resources.test.js +0 -47
  218. package/dist/tests/scheduler.test.d.ts +0 -1
  219. package/dist/tests/scheduler.test.js +0 -46
  220. package/dist/tests/schema-routes.test.d.ts +0 -1
  221. package/dist/tests/schema-routes.test.js +0 -79
  222. package/dist/tests/security.test.d.ts +0 -1
  223. package/dist/tests/security.test.js +0 -83
  224. package/dist/tests/server-db.test.d.ts +0 -1
  225. package/dist/tests/server-db.test.js +0 -72
  226. package/dist/tests/smoke.test.d.ts +0 -1
  227. package/dist/tests/smoke.test.js +0 -10
  228. package/dist/tests/sqlite-fusion.test.d.ts +0 -1
  229. package/dist/tests/sqlite-fusion.test.js +0 -92
  230. package/dist/tests/static.test.d.ts +0 -1
  231. package/dist/tests/static.test.js +0 -102
  232. package/dist/tests/stream.test.d.ts +0 -1
  233. package/dist/tests/stream.test.js +0 -44
  234. package/dist/tests/task-metrics.test.d.ts +0 -1
  235. package/dist/tests/task-metrics.test.js +0 -53
  236. package/dist/tests/tasks.test.d.ts +0 -1
  237. package/dist/tests/tasks.test.js +0 -62
  238. package/dist/tests/testing.test.d.ts +0 -1
  239. package/dist/tests/testing.test.js +0 -47
  240. package/dist/tests/validation.test.d.ts +0 -1
  241. package/dist/tests/validation.test.js +0 -107
  242. package/dist/tests/websocket.test.d.ts +0 -1
  243. package/dist/tests/websocket.test.js +0 -146
  244. package/dist/vitest.config.d.ts +0 -2
  245. package/dist/vitest.config.js +0 -9
  246. package/docs/AEGIS.md +0 -91
  247. package/docs/API_REFERENCE.md +0 -749
  248. package/docs/BENCHMARKS.md +0 -39
  249. package/docs/CAPABILITIES.md +0 -70
  250. package/docs/CLI.md +0 -43
  251. package/docs/DATABASE.md +0 -142
  252. package/docs/ECOSYSTEM.md +0 -146
  253. package/docs/ERRORS.md +0 -112
  254. package/docs/FUSION.md +0 -87
  255. package/docs/MIDDLEWARE.md +0 -65
  256. package/docs/MIGRATION_1.9_TO_2.0.md +0 -495
  257. package/docs/NEXT_STEPS.md +0 -99
  258. package/docs/OPENAPI.md +0 -99
  259. package/docs/PLUGINS.md +0 -59
  260. package/docs/PRODUCTION_DEPLOYMENT.md +0 -798
  261. package/docs/REAL_WORLD_EXAMPLES.md +0 -109
  262. package/docs/ROADMAP.md +0 -366
  263. package/docs/ROUTING.md +0 -78
  264. package/docs/SECURITY.md +0 -876
  265. package/docs/STATIC.md +0 -61
  266. package/docs/VALIDATION.md +0 -114
  267. package/docs/WEBSOCKETS.md +0 -76
@@ -1,749 +0,0 @@
1
- # QHttpX 2.0.1 API Reference
2
-
3
- **Complete Guide to QHttpX Methods and Options**
4
-
5
- ---
6
-
7
- ## Table of Contents
8
-
9
- 1. [App Initialization](#app-initialization)
10
- 2. [Route Definitions](#route-definitions)
11
- 3. [Context Methods](#context-methods)
12
- 4. [Configuration](#configuration)
13
- 5. [Error Handling](#error-handling)
14
- 6. [Middleware](#middleware)
15
- 7. [Advanced Features](#advanced-features)
16
-
17
- ---
18
-
19
- ## App Initialization
20
-
21
- ### `new QHTTPX(options)`
22
-
23
- Creates a new QHttpX application instance.
24
-
25
- **Signature:**
26
- ```typescript
27
- const app = new QHTTPX(options?: QHTTPXOptions);
28
- ```
29
-
30
- **Options:**
31
- ```typescript
32
- interface QHTTPXOptions {
33
- // Port configuration (default: 3000)
34
- port?: number;
35
-
36
- // Worker count for clustering (default: CPU cores)
37
- workers?: number;
38
-
39
- // Buffer pool for request/response optimization
40
- bufferPool?: BufferPoolConfig;
41
-
42
- // Request fusion settings (coalesce identical concurrent requests)
43
- fusion?: RequestFusionOptions | boolean;
44
-
45
- // Database manager
46
- db?: DatabaseManager;
47
-
48
- // View engine (for template rendering)
49
- views?: ViewEngine;
50
-
51
- // Validation library (default: simple schema validation)
52
- validator?: Validator;
53
-
54
- // Rate limiting configuration
55
- rateLimit?: RateLimitOptions | boolean;
56
-
57
- // CORS configuration
58
- cors?: CorsOptions | boolean;
59
-
60
- // Compression settings
61
- compression?: CompressionOptions | boolean;
62
-
63
- // Security headers
64
- security?: SecurityHeadersOptions | boolean;
65
-
66
- // Production mode optimizations
67
- production?: boolean;
68
-
69
- // Logging configuration
70
- logging?: LoggerOptions;
71
-
72
- // Enable metrics collection
73
- metrics?: boolean;
74
-
75
- // Custom tracer for observability
76
- tracer?: QHTTPXTracer;
77
- }
78
- ```
79
-
80
- **Example:**
81
- ```typescript
82
- const app = new QHTTPX({
83
- port: 3000,
84
- workers: 4,
85
- production: true,
86
- fusion: { maxWait: 10 },
87
- metrics: true,
88
- });
89
- ```
90
-
91
- ---
92
-
93
- ### `app.start(port?, callback?)`
94
-
95
- Starts the HTTP server.
96
-
97
- **Signature:**
98
- ```typescript
99
- start(port?: number, callback?: () => void): Promise<void>;
100
- ```
101
-
102
- **Returns:** Promise that resolves when server is listening
103
-
104
- **Example:**
105
- ```typescript
106
- // Using Promise
107
- app.start(3000).then(() => {
108
- console.log('Server running');
109
- }).catch(console.error);
110
-
111
- // Using async/await
112
- async function start() {
113
- await app.start(3000);
114
- console.log('Server running');
115
- }
116
- start();
117
-
118
- // With callback (backward compat)
119
- app.start(3000, () => {
120
- console.log('Server running');
121
- });
122
- ```
123
-
124
- ---
125
-
126
- ### Configuration Methods (Fluent API)
127
-
128
- All return `this` for chaining.
129
-
130
- #### `app.production()`
131
- Enables production optimizations (compression, caching, etc).
132
-
133
- ```typescript
134
- app.production();
135
- ```
136
-
137
- #### `app.fusion(enabled?: boolean | options)`
138
- Enables request fusion (coalesce identical concurrent requests).
139
-
140
- ```typescript
141
- app.fusion(true);
142
- app.fusion({ maxWait: 10, maxSize: 100 });
143
- ```
144
-
145
- #### `app.metrics(enabled?: boolean)`
146
- Enables metrics collection for performance monitoring.
147
-
148
- ```typescript
149
- app.metrics(true);
150
- ```
151
-
152
- #### `app.security(options)`
153
- Configures security settings (CORS, rate limiting, headers).
154
-
155
- ```typescript
156
- app.security({
157
- cors: { origin: '*' },
158
- rateLimit: { max: 100, windowMs: 60000 },
159
- headers: true,
160
- });
161
- ```
162
-
163
- #### `app.cors(options)`
164
- Configures CORS.
165
-
166
- ```typescript
167
- app.cors({
168
- origin: ['http://localhost:3000', 'https://example.com'],
169
- methods: ['GET', 'POST'],
170
- credentials: true,
171
- });
172
- ```
173
-
174
- #### `app.rateLimit(options)`
175
- Configures rate limiting.
176
-
177
- ```typescript
178
- app.rateLimit({
179
- windowMs: 15 * 60 * 1000, // 15 minutes
180
- max: 100, // 100 requests
181
- keyGenerator: (ctx) => ctx.ip,
182
- });
183
- ```
184
-
185
- ---
186
-
187
- ## Route Definitions
188
-
189
- ### HTTP Method Signatures
190
-
191
- ```typescript
192
- // GET request
193
- app.get(path, handler);
194
- app.get(path, options, handler);
195
-
196
- // POST request
197
- app.post(path, handler);
198
- app.post(path, options, handler);
199
-
200
- // PUT request
201
- app.put(path, handler);
202
- app.put(path, options, handler);
203
-
204
- // DELETE request
205
- app.delete(path, handler);
206
- app.delete(path, options, handler);
207
-
208
- // PATCH request
209
- app.patch(path, handler);
210
- app.patch(path, options, handler);
211
-
212
- // HEAD request
213
- app.head(path, handler);
214
- app.head(path, options, handler);
215
-
216
- // OPTIONS request
217
- app.options(path, handler);
218
- app.options(path, options, handler);
219
- ```
220
-
221
- ### Route Handler
222
-
223
- ```typescript
224
- type QHTTPXHandler = (ctx: QHTTPXContext) => void | Promise<void>;
225
- ```
226
-
227
- The handler receives a `QHTTPXContext` object with all request/response utilities.
228
-
229
- ### Route Options
230
-
231
- ```typescript
232
- interface QHTTPXRouteOptions {
233
- // JSON Schema for validation
234
- schema?: {
235
- body?: any; // Validate request body
236
- params?: any; // Validate URL parameters
237
- query?: any; // Validate query string
238
- headers?: any; // Validate headers
239
- response?: any; // Document response shape
240
- };
241
-
242
- // Route priority for execution order
243
- priority?: 'critical' | 'standard' | 'best-effort';
244
-
245
- // Pre-built static response (optimization)
246
- staticResponse?: any;
247
- }
248
- ```
249
-
250
- ### Examples
251
-
252
- ```typescript
253
- // Simple GET
254
- app.get('/', ({ json }) => {
255
- json({ status: 'ok' }, 200);
256
- });
257
-
258
- // With URL parameters
259
- app.get('/users/:id', ({ params, json }) => {
260
- const userId = params.id;
261
- json({ userId }, 200);
262
- });
263
-
264
- // With query parameters
265
- app.get('/search', ({ query, json }) => {
266
- const q = query.q; // ?q=hello
267
- json({ results: [] }, 200);
268
- });
269
-
270
- // With validation schema
271
- app.post('/users',
272
- {
273
- schema: {
274
- body: {
275
- type: 'object',
276
- required: ['email', 'name'],
277
- properties: {
278
- email: { type: 'string', format: 'email' },
279
- name: { type: 'string', minLength: 2 },
280
- }
281
- }
282
- }
283
- },
284
- ({ body, json }) => {
285
- const { email, name } = body as any;
286
- json({ created: true, email, name }, 201);
287
- }
288
- );
289
-
290
- // With priority routing
291
- app.post('/admin/users',
292
- { priority: 'critical' },
293
- ({ body, json }) => {
294
- json({ admin: true }, 201);
295
- }
296
- );
297
- ```
298
-
299
- ---
300
-
301
- ## Context Methods
302
-
303
- The context object (first parameter to handlers) contains request/response utilities.
304
-
305
- ### Request Properties
306
-
307
- ```typescript
308
- ctx.req: IncomingMessage // Node HTTP request
309
- ctx.res: ServerResponse // Node HTTP response
310
- ctx.method: HTTPMethod // GET, POST, PUT, DELETE, etc
311
- ctx.url: URL // Parsed URL object
312
- ctx.path: string // URL path (/users/123)
313
- ctx.headers: IncomingHttpHeaders // Request headers
314
- ctx.ip: string // Client IP address
315
- ctx.params: Record<string, string> // URL parameters ({id: '123'})
316
- ctx.query: Record<string, any> // Query parameters ({sort: 'asc'})
317
- ctx.body: unknown // Parsed request body
318
- ctx.cookies: Record<string, string>// Cookies
319
- ctx.files?: QHTTPXFile[] // Uploaded files
320
- ```
321
-
322
- ### Response Methods
323
-
324
- #### `json(body, status?)`
325
- Sends JSON response.
326
-
327
- ```typescript
328
- ctx.json({ message: 'ok' }, 200);
329
- ctx.json({ error: 'not found' }, 404);
330
- ctx.json({ users: [] }); // default status 200
331
- ```
332
-
333
- #### `send(body, status?)`
334
- Sends text/buffer response.
335
-
336
- ```typescript
337
- ctx.send('Hello world', 200);
338
- ctx.send(Buffer.from('data'), 200);
339
- ```
340
-
341
- #### `html(html, status?)`
342
- Sends HTML response.
343
-
344
- ```typescript
345
- ctx.html('<h1>Hello</h1>', 200);
346
- ```
347
-
348
- #### `redirect(url, status?)`
349
- Redirects to URL.
350
-
351
- ```typescript
352
- ctx.redirect('/login', 302);
353
- ```
354
-
355
- #### `setCookie(name, value, options?)`
356
- Sets a cookie.
357
-
358
- ```typescript
359
- ctx.setCookie('sessionId', 'abc123', {
360
- httpOnly: true,
361
- secure: true,
362
- maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
363
- sameSite: 'lax',
364
- });
365
- ```
366
-
367
- ### Validation and Data
368
-
369
- #### `validate(schema, data?)`
370
- Validates data against schema.
371
-
372
- ```typescript
373
- const validated = await ctx.validate({
374
- type: 'object',
375
- required: ['email'],
376
- properties: { email: { type: 'string' } }
377
- }, data);
378
- ```
379
-
380
- #### `render(view, locals?)`
381
- Renders template view.
382
-
383
- ```typescript
384
- await ctx.render('users/list', { users: [] });
385
- ```
386
-
387
- #### `db`
388
- Database manager (if configured).
389
-
390
- ```typescript
391
- const users = await ctx.db?.query('SELECT * FROM users');
392
- ```
393
-
394
- ### Error Handling
395
-
396
- #### `httpError(status, message?, options?)`
397
- Creates an HTTP error.
398
-
399
- ```typescript
400
- throw ctx.httpError(404, 'User not found');
401
- throw ctx.httpError(400, 'Invalid input', {
402
- code: 'VALIDATION_ERROR',
403
- details: { field: 'email' }
404
- });
405
- ```
406
-
407
- ---
408
-
409
- ## Configuration
410
-
411
- ### Security Options
412
-
413
- ```typescript
414
- interface SecurityOptions {
415
- cors?: CorsOptions | boolean;
416
- rateLimit?: RateLimitOptions;
417
- headers?: SecurityHeadersOptions | boolean;
418
- }
419
-
420
- interface CorsOptions {
421
- origin?: string | string[] | ((origin: string) => boolean);
422
- methods?: string[];
423
- allowedHeaders?: string[];
424
- credentials?: boolean;
425
- maxAge?: number;
426
- }
427
-
428
- interface RateLimitOptions {
429
- windowMs: number; // Time window in ms
430
- max: number; // Max requests per window
431
- trustProxy?: boolean; // Trust X-Forwarded-For
432
- standardHeaders?: boolean; // Return RateLimit-* headers
433
- keyGenerator?: (ctx: QHTTPXContext) => string; // Custom key
434
- handler?: QHTTPXHandler; // Custom handler for limited requests
435
- skip?: (ctx: QHTTPXContext) => boolean; // Skip rate limiting
436
- }
437
- ```
438
-
439
- ### Compression Options
440
-
441
- ```typescript
442
- interface CompressionOptions {
443
- threshold?: number; // Min size to compress (bytes)
444
- level?: number; // Compression level (0-9)
445
- brotli?: boolean; // Enable Brotli compression
446
- }
447
- ```
448
-
449
- ### Request Fusion Options
450
-
451
- ```typescript
452
- interface RequestFusionOptions {
453
- maxWait?: number; // Max ms to wait for coalescing
454
- maxSize?: number; // Max concurrent requests to coalesce
455
- }
456
- ```
457
-
458
- ---
459
-
460
- ## Error Handling
461
-
462
- ### Global Error Handler
463
-
464
- ```typescript
465
- app.onError(({ req, res, error, json }) => {
466
- console.error('Error:', error);
467
-
468
- if (error instanceof HttpError) {
469
- json({ error: error.message, code: error.code }, error.status);
470
- } else {
471
- json({ error: 'Internal server error' }, 500);
472
- }
473
- });
474
- ```
475
-
476
- ### Not Found Handler
477
-
478
- ```typescript
479
- app.notFound(({ url, json }) => {
480
- json({ error: 'Not found', path: url.pathname }, 404);
481
- });
482
- ```
483
-
484
- ### Method Not Allowed Handler
485
-
486
- ```typescript
487
- app.methodNotAllowed(({ method, path, json }) => {
488
- json({ error: 'Method not allowed', method, path }, 405);
489
- });
490
- ```
491
-
492
- ---
493
-
494
- ## Middleware
495
-
496
- ### Global Middleware
497
-
498
- ```typescript
499
- app.use(async (ctx) => {
500
- // Log request
501
- console.log(`${ctx.method} ${ctx.path}`);
502
-
503
- // Perform operation
504
-
505
- // Continue to next handler
506
- if (ctx.next) await ctx.next();
507
- });
508
- ```
509
-
510
- ### Route-Specific Middleware (via schema options)
511
-
512
- ```typescript
513
- app.post('/admin/users',
514
- {
515
- priority: 'critical', // Run before standard routes
516
- },
517
- ({ json }) => {
518
- // Only critical routes run here
519
- json({ admin: true }, 201);
520
- }
521
- );
522
- ```
523
-
524
- ---
525
-
526
- ## Advanced Features
527
-
528
- ### Request Fusion
529
-
530
- Automatically coalesces identical concurrent requests into a single backend operation.
531
-
532
- ```typescript
533
- app.fusion(true);
534
-
535
- // GET /expensive route
536
- app.get('/expensive', async ({ json }) => {
537
- await sleep(2000); // Expensive operation
538
- json({ data: 'result' }, 200);
539
- });
540
-
541
- // 100 users request simultaneously
542
- // → Only 1 backend operation executes
543
- // → All 100 users get same response
544
- // → Saves 99 database queries!
545
- ```
546
-
547
- ### Metrics Collection
548
-
549
- ```typescript
550
- app.metrics(true);
551
-
552
- // Access via GET /metrics endpoint
553
- // Shows: request count, response times, memory usage, etc
554
- ```
555
-
556
- ### WebSocket Support
557
-
558
- ```typescript
559
- app.upgrade('/chat', (ws) => {
560
- ws.join('general');
561
-
562
- ws.on('message', (msg) => {
563
- ws.broadcast('general', msg);
564
- });
565
- });
566
-
567
- app.get('/rooms', ({ json }) => {
568
- const rooms = ws.getRooms();
569
- json({ rooms }, 200);
570
- });
571
- ```
572
-
573
- ### Batch Operations
574
-
575
- ```typescript
576
- // Batch GET
577
- app.post('/batch/get', ({ body, json }) => {
578
- const { ids } = body;
579
- const results = ids.map(id => db.query(`SELECT * FROM users WHERE id = ?`, [id]));
580
- json({ results }, 200);
581
- });
582
-
583
- // Batch CREATE
584
- app.post('/batch/create', ({ body, json }) => {
585
- const { items } = body;
586
- const results = items.map(item => db.query('INSERT ...', [item]));
587
- json({ created: results.length }, 201);
588
- });
589
- ```
590
-
591
- ### OpenAPI/Swagger Documentation
592
-
593
- ```typescript
594
- app.openapi({
595
- title: 'My API',
596
- version: '1.0.0',
597
- basePath: '/api',
598
- });
599
-
600
- // Auto-generates /openapi.json and /swagger documentation
601
- ```
602
-
603
- ---
604
-
605
- ## Common Patterns
606
-
607
- ### Error Handling Pattern
608
-
609
- ```typescript
610
- app.post('/users', async ({ body, json, httpError }) => {
611
- try {
612
- // Validate
613
- if (!body.email) {
614
- throw httpError(400, 'Email required');
615
- }
616
-
617
- // Process
618
- const user = await createUser(body);
619
-
620
- // Respond
621
- json({ user }, 201);
622
- } catch (error) {
623
- if (error instanceof HttpError) {
624
- json({ error: error.message }, error.status);
625
- } else {
626
- console.error(error);
627
- json({ error: 'Internal server error' }, 500);
628
- }
629
- }
630
- });
631
- ```
632
-
633
- ### Authentication Pattern
634
-
635
- ```typescript
636
- app.use(async ({ headers, json, next }) => {
637
- const token = headers.authorization?.replace('Bearer ', '');
638
-
639
- if (!token) {
640
- // Skip auth for public routes
641
- if (ctx.path.startsWith('/public/')) {
642
- if (next) await next();
643
- return;
644
- }
645
- json({ error: 'Unauthorized' }, 401);
646
- return;
647
- }
648
-
649
- // Verify token
650
- const user = await verifyToken(token);
651
- if (!user) {
652
- json({ error: 'Invalid token' }, 401);
653
- return;
654
- }
655
-
656
- // Store in context
657
- ctx.state.user = user;
658
- if (next) await next();
659
- });
660
- ```
661
-
662
- ### Caching Pattern
663
-
664
- ```typescript
665
- const cache = new Map();
666
-
667
- app.get('/users', ({ json, query }) => {
668
- const cacheKey = `users:${JSON.stringify(query)}`;
669
-
670
- // Check cache
671
- if (cache.has(cacheKey)) {
672
- json({ ...cache.get(cacheKey), fromCache: true }, 200);
673
- return;
674
- }
675
-
676
- // Fetch
677
- const users = db.query('SELECT * FROM users');
678
-
679
- // Cache
680
- cache.set(cacheKey, { users });
681
-
682
- json({ users }, 200);
683
- });
684
- ```
685
-
686
- ---
687
-
688
- ## Type Definitions
689
-
690
- Complete TypeScript support available:
691
-
692
- ```typescript
693
- import {
694
- QHTTPX,
695
- QHTTPXContext,
696
- HttpError,
697
- RequestFusionOptions,
698
- QHTTPXOptions,
699
- } from 'qhttpx';
700
-
701
- const app: QHTTPX = new QHTTPX();
702
-
703
- app.get('/path', (ctx: QHTTPXContext) => {
704
- ctx.json({ data: 'value' }, 200);
705
- });
706
- ```
707
-
708
- ---
709
-
710
- ## Performance Tuning
711
-
712
- ### Enable All Optimizations
713
-
714
- ```typescript
715
- const app = new QHTTPX({
716
- production: true,
717
- fusion: { maxWait: 10, maxSize: 100 },
718
- compression: { level: 6, brotli: true },
719
- metrics: true,
720
- bufferPool: { size: 1024 * 1024 }, // 1MB buffer pool
721
- });
722
-
723
- app
724
- .production()
725
- .fusion(true)
726
- .metrics(true);
727
- ```
728
-
729
- ### Monitor Performance
730
-
731
- ```typescript
732
- app.onError(({ error, requestStart, json }) => {
733
- const duration = Date.now() - (requestStart || 0);
734
- if (duration > 1000) {
735
- console.warn(`Slow request: ${duration}ms`);
736
- }
737
- json({ error: error.message }, 500);
738
- });
739
- ```
740
-
741
- ---
742
-
743
- ## More Information
744
-
745
- - **Examples:** See `examples/` directory
746
- - **Benchmarks:** See `benchmarks/` directory
747
- - **Migration:** See [MIGRATION_1.9_TO_2.0.md](./MIGRATION_1.9_TO_2.0.md)
748
- - **Production:** See [PRODUCTION_DEPLOYMENT.md](./PRODUCTION_DEPLOYMENT.md)
749
- - **Security:** See [SECURITY.md](./SECURITY.md)