@dim24/servin 0.0.1 → 0.2.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.
- package/README.md +1032 -1062
- package/example/index.js +1 -1
- package/index.js +1 -1
- package/package.json +1 -1
- package/src/server.js +257 -28
- package/src/servin.test.js +77 -261
- package/src/tree.js +216 -17
- package/src/utils.js +139 -16
- package/src/wire.js +21 -0
package/example/index.js
CHANGED
package/index.js
CHANGED
package/package.json
CHANGED
package/src/server.js
CHANGED
|
@@ -10,7 +10,8 @@ import {
|
|
|
10
10
|
runUndoStack,
|
|
11
11
|
flushDebugLogs,
|
|
12
12
|
getReactions,
|
|
13
|
-
ServinAbortError
|
|
13
|
+
ServinAbortError,
|
|
14
|
+
ServinRedirect
|
|
14
15
|
} from './wire.js';
|
|
15
16
|
import { SessionManager, MemorySessionStore } from './session.js';
|
|
16
17
|
import {
|
|
@@ -31,6 +32,7 @@ import {
|
|
|
31
32
|
FileStreamResponse,
|
|
32
33
|
HtmlResponse,
|
|
33
34
|
buildFileHttpResponse,
|
|
35
|
+
buildStaticHttpResponse,
|
|
34
36
|
createLagMonitor
|
|
35
37
|
} from './utils.js';
|
|
36
38
|
|
|
@@ -99,7 +101,7 @@ export function serve(config = {}) {
|
|
|
99
101
|
const port = config.port ?? 3000;
|
|
100
102
|
const host = config.host ?? '127.0.0.1';
|
|
101
103
|
const silent = config.silent ?? false;
|
|
102
|
-
const routes = compileDomainTree(config.api || {});
|
|
104
|
+
const routes = compileDomainTree(config.api || {}, config.types || {}, config.static || null);
|
|
103
105
|
const virtualClientCode = generateVirtualClientModule(routes);
|
|
104
106
|
|
|
105
107
|
const broker = new WebSocketBroker();
|
|
@@ -148,6 +150,141 @@ export function serve(config = {}) {
|
|
|
148
150
|
}
|
|
149
151
|
}
|
|
150
152
|
|
|
153
|
+
function findErrorHandler(status) {
|
|
154
|
+
const errorsCfg = config.errors;
|
|
155
|
+
if (!errorsCfg || typeof errorsCfg !== 'object') return null;
|
|
156
|
+
|
|
157
|
+
if (Object.prototype.hasOwnProperty.call(errorsCfg, status)) {
|
|
158
|
+
return errorsCfg[status];
|
|
159
|
+
}
|
|
160
|
+
const statusStr = String(status);
|
|
161
|
+
if (Object.prototype.hasOwnProperty.call(errorsCfg, statusStr)) {
|
|
162
|
+
return errorsCfg[statusStr];
|
|
163
|
+
}
|
|
164
|
+
if (status >= 400 && status < 500 && errorsCfg['4xx']) {
|
|
165
|
+
return errorsCfg['4xx'];
|
|
166
|
+
}
|
|
167
|
+
if (status >= 500 && errorsCfg['5xx']) {
|
|
168
|
+
return errorsCfg['5xx'];
|
|
169
|
+
}
|
|
170
|
+
return errorsCfg.default ?? null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function buildErrorResponse({ webReq, status, defaultPayload, existingCtx = null, rawError = null, extraHeaders = null }) {
|
|
174
|
+
const handler = findErrorHandler(status);
|
|
175
|
+
const url = existingCtx?.url || new URL(webReq.url);
|
|
176
|
+
const method = existingCtx?.method || webReq.method.toUpperCase();
|
|
177
|
+
|
|
178
|
+
if (!handler) {
|
|
179
|
+
const headers = existingCtx?.outgoingHeaders || new Headers();
|
|
180
|
+
if (extraHeaders) {
|
|
181
|
+
for (const [k, v] of Object.entries(extraHeaders)) headers.set(k, v);
|
|
182
|
+
}
|
|
183
|
+
if (status === 405 && !defaultPayload) {
|
|
184
|
+
return new Response(null, { status: 405, headers });
|
|
185
|
+
}
|
|
186
|
+
return Response.json(defaultPayload || { error: 'Error' }, { status, headers });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const ctx = existingCtx || createRequestContext({
|
|
190
|
+
req: webReq,
|
|
191
|
+
method,
|
|
192
|
+
url,
|
|
193
|
+
signal: webReq.signal,
|
|
194
|
+
sessionManager,
|
|
195
|
+
broker,
|
|
196
|
+
deferTracker
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
if (!existingCtx) {
|
|
200
|
+
applyCorsHeaders(webReq, ctx.outgoingHeaders);
|
|
201
|
+
}
|
|
202
|
+
if (extraHeaders) {
|
|
203
|
+
for (const [k, v] of Object.entries(extraHeaders)) {
|
|
204
|
+
ctx.outgoingHeaders.set(k, v);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
ctx.statusCode = status;
|
|
209
|
+
ctx.statusExplicit = false;
|
|
210
|
+
|
|
211
|
+
const runCustomizer = async () => {
|
|
212
|
+
try {
|
|
213
|
+
const result = typeof handler === 'function'
|
|
214
|
+
? await handler({
|
|
215
|
+
status,
|
|
216
|
+
message: defaultPayload?.error || '',
|
|
217
|
+
details: defaultPayload?.details,
|
|
218
|
+
path: url.pathname,
|
|
219
|
+
method,
|
|
220
|
+
error: rawError,
|
|
221
|
+
wire
|
|
222
|
+
})
|
|
223
|
+
: handler;
|
|
224
|
+
|
|
225
|
+
if (!ctx.isSimulated) {
|
|
226
|
+
await ctx.sessionHandle?.commit(ctx.outgoingHeaders).catch(() => { });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (result instanceof Response) return result;
|
|
230
|
+
|
|
231
|
+
if (result instanceof FileStreamResponse) {
|
|
232
|
+
const fileRes = await buildFileHttpResponse(result, webReq.headers, {
|
|
233
|
+
method,
|
|
234
|
+
statusOverride: ctx.statusCode
|
|
235
|
+
});
|
|
236
|
+
ctx.outgoingHeaders.forEach((v, k) => {
|
|
237
|
+
if (!fileRes.headers.has(k)) fileRes.headers.set(k, v);
|
|
238
|
+
});
|
|
239
|
+
return fileRes;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (result instanceof HtmlResponse) {
|
|
243
|
+
if (!ctx.outgoingHeaders.has('content-type')) {
|
|
244
|
+
ctx.outgoingHeaders.set('Content-Type', 'text/html; charset=utf-8');
|
|
245
|
+
}
|
|
246
|
+
return new Response(result.html, {
|
|
247
|
+
status: ctx.statusCode,
|
|
248
|
+
headers: ctx.outgoingHeaders
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (typeof result === 'string') {
|
|
253
|
+
if (!ctx.outgoingHeaders.has('content-type')) {
|
|
254
|
+
ctx.outgoingHeaders.set('Content-Type', 'text/plain; charset=utf-8');
|
|
255
|
+
}
|
|
256
|
+
return new Response(result, {
|
|
257
|
+
status: ctx.statusCode,
|
|
258
|
+
headers: ctx.outgoingHeaders
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (result === null || result === undefined) {
|
|
263
|
+
return new Response(null, { status: ctx.statusCode, headers: ctx.outgoingHeaders });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return Response.json(result, {
|
|
267
|
+
status: ctx.statusCode,
|
|
268
|
+
headers: ctx.outgoingHeaders
|
|
269
|
+
});
|
|
270
|
+
} catch (err) {
|
|
271
|
+
if (err instanceof ServinRedirect) {
|
|
272
|
+
if (!ctx.isSimulated) {
|
|
273
|
+
await ctx.sessionHandle?.commit(ctx.outgoingHeaders).catch(() => { });
|
|
274
|
+
}
|
|
275
|
+
ctx.outgoingHeaders.set('Location', err.location);
|
|
276
|
+
return new Response(null, { status: err.status, headers: ctx.outgoingHeaders });
|
|
277
|
+
}
|
|
278
|
+
return Response.json(defaultPayload || { error: 'Internal Server Error' }, {
|
|
279
|
+
status,
|
|
280
|
+
headers: ctx.outgoingHeaders
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
return existingCtx ? runCustomizer() : wireStorage.run(ctx, runCustomizer);
|
|
286
|
+
}
|
|
287
|
+
|
|
151
288
|
async function writeSnapshot(ctx, route, err) {
|
|
152
289
|
if (!config.snapshotOnError) return;
|
|
153
290
|
try {
|
|
@@ -248,19 +385,30 @@ export function serve(config = {}) {
|
|
|
248
385
|
}
|
|
249
386
|
|
|
250
387
|
if (match.status === 404) {
|
|
251
|
-
return
|
|
388
|
+
return buildErrorResponse({
|
|
389
|
+
webReq,
|
|
390
|
+
status: 404,
|
|
391
|
+
defaultPayload: { error: 'Not Found' }
|
|
392
|
+
});
|
|
252
393
|
}
|
|
253
394
|
if (match.status === 405) {
|
|
254
|
-
return
|
|
395
|
+
return buildErrorResponse({
|
|
396
|
+
webReq,
|
|
397
|
+
status: 405,
|
|
398
|
+
defaultPayload: null,
|
|
399
|
+
extraHeaders: { Allow: match.allow }
|
|
400
|
+
});
|
|
255
401
|
}
|
|
256
402
|
|
|
257
403
|
const { route, params } = match;
|
|
258
404
|
|
|
259
405
|
if (route.meta.priority === 'low' && lagMonitor.isOverloaded()) {
|
|
260
|
-
return
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
406
|
+
return buildErrorResponse({
|
|
407
|
+
webReq,
|
|
408
|
+
status: 503,
|
|
409
|
+
defaultPayload: { error: 'Service temporarily overloaded' },
|
|
410
|
+
extraHeaders: { 'Retry-After': '2' }
|
|
411
|
+
});
|
|
264
412
|
}
|
|
265
413
|
|
|
266
414
|
const ctx = createRequestContext({
|
|
@@ -296,6 +444,53 @@ export function serve(config = {}) {
|
|
|
296
444
|
await guardFn();
|
|
297
445
|
}
|
|
298
446
|
|
|
447
|
+
// Handle declarative RedirectDescriptor
|
|
448
|
+
if (route.redirectDescriptor) {
|
|
449
|
+
const paramValues = route.paramNames.map((name) => params[name]);
|
|
450
|
+
const queryObj = Object.fromEntries(url.searchParams.entries());
|
|
451
|
+
const targetUrl = typeof route.redirectDescriptor.target === 'function'
|
|
452
|
+
? await route.redirectDescriptor.target(...paramValues, queryObj)
|
|
453
|
+
: route.redirectDescriptor.target;
|
|
454
|
+
|
|
455
|
+
if (!ctx.isSimulated) {
|
|
456
|
+
await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
|
|
457
|
+
}
|
|
458
|
+
ctx.outgoingHeaders.set('Location', String(targetUrl));
|
|
459
|
+
return new Response(null, {
|
|
460
|
+
status: route.redirectDescriptor.status,
|
|
461
|
+
headers: ctx.outgoingHeaders
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Handle StaticRouteDescriptor (file or folder)
|
|
466
|
+
if (route.staticDescriptor) {
|
|
467
|
+
const staticRes = await buildStaticHttpResponse(
|
|
468
|
+
route.staticDescriptor,
|
|
469
|
+
params.subpath || '',
|
|
470
|
+
webReq.headers,
|
|
471
|
+
method
|
|
472
|
+
);
|
|
473
|
+
|
|
474
|
+
if (staticRes.errorStatus) {
|
|
475
|
+
return buildErrorResponse({
|
|
476
|
+
webReq,
|
|
477
|
+
status: staticRes.errorStatus,
|
|
478
|
+
defaultPayload: { error: staticRes.message },
|
|
479
|
+
existingCtx: ctx
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
if (!ctx.isSimulated) {
|
|
484
|
+
await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
|
|
485
|
+
}
|
|
486
|
+
ctx.outgoingHeaders.forEach((v, k) => {
|
|
487
|
+
if (!staticRes.response.headers.has(k)) {
|
|
488
|
+
staticRes.response.headers.set(k, v);
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
return staticRes.response;
|
|
492
|
+
}
|
|
493
|
+
|
|
299
494
|
const paramValues = route.paramNames.map((name) => params[name]);
|
|
300
495
|
const queryObj = Object.fromEntries(url.searchParams.entries());
|
|
301
496
|
const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
|
|
@@ -310,12 +505,13 @@ export function serve(config = {}) {
|
|
|
310
505
|
if (route.meta.expect) {
|
|
311
506
|
const validationErrors = validateExpect(payload, route.meta.expect);
|
|
312
507
|
if (validationErrors.length > 0) {
|
|
313
|
-
ctx.statusCode = 422;
|
|
314
508
|
if (!ctx.isSimulated) await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
|
|
315
|
-
return
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
509
|
+
return buildErrorResponse({
|
|
510
|
+
webReq,
|
|
511
|
+
status: 422,
|
|
512
|
+
defaultPayload: { error: 'Validation Failed', details: validationErrors },
|
|
513
|
+
existingCtx: ctx
|
|
514
|
+
});
|
|
319
515
|
}
|
|
320
516
|
}
|
|
321
517
|
}
|
|
@@ -335,11 +531,13 @@ export function serve(config = {}) {
|
|
|
335
531
|
|
|
336
532
|
if (bucket.remaining <= 0) {
|
|
337
533
|
const retrySec = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
{
|
|
342
|
-
|
|
534
|
+
return buildErrorResponse({
|
|
535
|
+
webReq,
|
|
536
|
+
status: 429,
|
|
537
|
+
defaultPayload: { error: 'Too Many Requests' },
|
|
538
|
+
existingCtx: ctx,
|
|
539
|
+
extraHeaders: { 'Retry-After': String(retrySec) }
|
|
540
|
+
});
|
|
343
541
|
}
|
|
344
542
|
|
|
345
543
|
activeLimiterBucket = bucket;
|
|
@@ -384,7 +582,7 @@ export function serve(config = {}) {
|
|
|
384
582
|
|
|
385
583
|
// Idempotency Check for Mutations
|
|
386
584
|
const idemHeader = webReq.headers.get('idempotency-key');
|
|
387
|
-
const idemKey = route.nodeIdempotency && idemHeader ? `${route.
|
|
585
|
+
const idemKey = route.nodeIdempotency && idemHeader ? `${route.nodeId}:${idemHeader}` : null;
|
|
388
586
|
if (idemKey && !ctx.isSimulated) {
|
|
389
587
|
const cachedIdem = route.nodeIdempotency.get(idemKey);
|
|
390
588
|
if (cachedIdem && cachedIdem.expiresAt > Date.now()) {
|
|
@@ -484,7 +682,19 @@ export function serve(config = {}) {
|
|
|
484
682
|
}
|
|
485
683
|
|
|
486
684
|
if (rawResult instanceof FileStreamResponse) {
|
|
487
|
-
|
|
685
|
+
const fileRes = await buildFileHttpResponse(rawResult, webReq.headers, {
|
|
686
|
+
method,
|
|
687
|
+
returnMissing: true
|
|
688
|
+
});
|
|
689
|
+
if (!fileRes) {
|
|
690
|
+
return buildErrorResponse({
|
|
691
|
+
webReq,
|
|
692
|
+
status: 404,
|
|
693
|
+
defaultPayload: { error: 'File Not Found' },
|
|
694
|
+
existingCtx: ctx
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
return fileRes;
|
|
488
698
|
}
|
|
489
699
|
|
|
490
700
|
if (rawResult instanceof HtmlResponse) {
|
|
@@ -535,16 +745,32 @@ export function serve(config = {}) {
|
|
|
535
745
|
headers: ctx.outgoingHeaders
|
|
536
746
|
});
|
|
537
747
|
} catch (err) {
|
|
748
|
+
if (err instanceof ServinRedirect) {
|
|
749
|
+
if (ctx.isSimulated) {
|
|
750
|
+
await runUndoStack(ctx);
|
|
751
|
+
} else {
|
|
752
|
+
await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
|
|
753
|
+
}
|
|
754
|
+
ctx.outgoingHeaders.set('Location', err.location);
|
|
755
|
+
return new Response(null, {
|
|
756
|
+
status: err.status,
|
|
757
|
+
headers: ctx.outgoingHeaders
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
|
|
538
761
|
await runUndoStack(ctx);
|
|
539
762
|
if (!ctx.isSimulated) {
|
|
540
763
|
await ctx.sessionHandle?.commit(ctx.outgoingHeaders).catch(() => { });
|
|
541
764
|
}
|
|
542
765
|
|
|
543
766
|
if (err instanceof ServinAbortError) {
|
|
544
|
-
return
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
767
|
+
return buildErrorResponse({
|
|
768
|
+
webReq,
|
|
769
|
+
status: err.status,
|
|
770
|
+
defaultPayload: { error: err.message },
|
|
771
|
+
existingCtx: ctx,
|
|
772
|
+
rawError: err
|
|
773
|
+
});
|
|
548
774
|
}
|
|
549
775
|
|
|
550
776
|
flushDebugLogs(ctx, err);
|
|
@@ -556,10 +782,13 @@ export function serve(config = {}) {
|
|
|
556
782
|
return Response.json(custom, { status: 500, headers: ctx.outgoingHeaders });
|
|
557
783
|
}
|
|
558
784
|
|
|
559
|
-
return
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
785
|
+
return buildErrorResponse({
|
|
786
|
+
webReq,
|
|
787
|
+
status: 500,
|
|
788
|
+
defaultPayload: { error: 'Internal Server Error' },
|
|
789
|
+
existingCtx: ctx,
|
|
790
|
+
rawError: err
|
|
791
|
+
});
|
|
563
792
|
} finally {
|
|
564
793
|
if (activeLimiterBucket) {
|
|
565
794
|
const cost = ctx.costExplicit ? ctx.costPoints : 1;
|