@dim24/servin 0.2.2 → 1.1.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.
- package/README.md +805 -77
- package/index.js +1 -1
- package/package.json +1 -1
- package/src/server.js +229 -24
- package/src/servin.test.js +118 -1
- package/src/tree.js +641 -20
- package/src/utils.js +10 -0
- package/src/websocket.js +332 -6
package/index.js
CHANGED
package/package.json
CHANGED
package/src/server.js
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
import {
|
|
23
23
|
WebSocketBroker,
|
|
24
24
|
createLinearSocket,
|
|
25
|
+
createDeclarativeWsRuntime,
|
|
25
26
|
performWsHandshake
|
|
26
27
|
} from './websocket.js';
|
|
27
28
|
import {
|
|
@@ -97,20 +98,105 @@ async function parseBodyPayload(req, webhookConfig) {
|
|
|
97
98
|
}
|
|
98
99
|
}
|
|
99
100
|
|
|
101
|
+
async function resolveAliasChain({ initialMatch, initialUrl, routes, method, onGuard }) {
|
|
102
|
+
const visitedAliases = new Set();
|
|
103
|
+
let activeMatch = initialMatch;
|
|
104
|
+
let effectiveUrl = initialUrl;
|
|
105
|
+
let inheritedMeta = {};
|
|
106
|
+
|
|
107
|
+
while (activeMatch.status === 200 && activeMatch.route.aliasDescriptor) {
|
|
108
|
+
const aliasRoute = activeMatch.route;
|
|
109
|
+
if (visitedAliases.has(aliasRoute.nodeId) || visitedAliases.size >= 10) {
|
|
110
|
+
throw new ServinAbortError(500, 'Alias routing loop detected');
|
|
111
|
+
}
|
|
112
|
+
visitedAliases.add(aliasRoute.nodeId);
|
|
113
|
+
|
|
114
|
+
if (onGuard) {
|
|
115
|
+
await onGuard(aliasRoute.guards);
|
|
116
|
+
}
|
|
117
|
+
inheritedMeta = { ...inheritedMeta, ...aliasRoute.meta };
|
|
118
|
+
|
|
119
|
+
const desc = aliasRoute.aliasDescriptor;
|
|
120
|
+
const paramValues = aliasRoute.paramNames.map((name) => activeMatch.params[name]);
|
|
121
|
+
const queryObj = Object.fromEntries(effectiveUrl.searchParams.entries());
|
|
122
|
+
|
|
123
|
+
let rawTarget = typeof desc.target === 'function'
|
|
124
|
+
? await desc.target(...paramValues, queryObj)
|
|
125
|
+
: desc.target;
|
|
126
|
+
|
|
127
|
+
if (typeof rawTarget !== 'string' || !rawTarget.trim()) {
|
|
128
|
+
throw new ServinAbortError(500, 'Invalid alias target');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (typeof desc.target === 'string') {
|
|
132
|
+
rawTarget = rawTarget.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (full, name) => {
|
|
133
|
+
if (!Object.prototype.hasOwnProperty.call(activeMatch.params, name)) return full;
|
|
134
|
+
const val = String(activeMatch.params[name]);
|
|
135
|
+
return val.split('/').map(encodeURIComponent).join('/');
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const normalizedTarget = rawTarget.startsWith('/') ? rawTarget : `/${rawTarget}`;
|
|
140
|
+
const targetUrl = new URL(normalizedTarget, effectiveUrl.origin);
|
|
141
|
+
|
|
142
|
+
const mergedParams = new URLSearchParams(targetUrl.searchParams);
|
|
143
|
+
for (const [k, v] of effectiveUrl.searchParams.entries()) {
|
|
144
|
+
mergedParams.set(k, v);
|
|
145
|
+
}
|
|
146
|
+
targetUrl.search = mergedParams.toString();
|
|
147
|
+
effectiveUrl = targetUrl;
|
|
148
|
+
|
|
149
|
+
if (method === 'GET' && effectiveUrl.pathname === '/@client.js') {
|
|
150
|
+
return {
|
|
151
|
+
isVirtualClient: true,
|
|
152
|
+
match: activeMatch,
|
|
153
|
+
url: effectiveUrl,
|
|
154
|
+
inheritedMeta
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
activeMatch = matchDomainRoute(routes, method, effectiveUrl.pathname);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
isVirtualClient: false,
|
|
163
|
+
match: activeMatch,
|
|
164
|
+
url: effectiveUrl,
|
|
165
|
+
inheritedMeta
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
100
169
|
export function serve(config = {}) {
|
|
101
170
|
const port = config.port ?? 3000;
|
|
102
171
|
const host = config.host ?? '127.0.0.1';
|
|
103
172
|
const silent = config.silent ?? false;
|
|
104
|
-
const routes = compileDomainTree(
|
|
173
|
+
const routes = compileDomainTree(
|
|
174
|
+
config.api || {},
|
|
175
|
+
config.types || {},
|
|
176
|
+
config.static || null,
|
|
177
|
+
config.alias ?? config.aliases ?? null
|
|
178
|
+
);
|
|
105
179
|
const virtualClientCode = generateVirtualClientModule(routes);
|
|
106
180
|
|
|
107
181
|
const broker = new WebSocketBroker();
|
|
182
|
+
const declarativeRuntimes = new Map();
|
|
108
183
|
const sessionManager = config.session ? new SessionManager(config.session, broker) : null;
|
|
109
184
|
const lagMonitor = createLagMonitor(config.lagThresholdMs ?? 60);
|
|
110
185
|
const rateBuckets = new Map();
|
|
111
186
|
const activeDefers = new Set();
|
|
112
187
|
const recordedTests = new Map();
|
|
113
188
|
|
|
189
|
+
function getDeclarativeRuntime(route) {
|
|
190
|
+
const cfg = route.meta?.wsConfig;
|
|
191
|
+
if (!cfg || typeof cfg !== 'object' || (!cfg.open && !cfg.actions && !cfg.close && !cfg.state)) {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
if (!declarativeRuntimes.has(route.nodeId)) {
|
|
195
|
+
declarativeRuntimes.set(route.nodeId, createDeclarativeWsRuntime(broker, cfg));
|
|
196
|
+
}
|
|
197
|
+
return declarativeRuntimes.get(route.nodeId);
|
|
198
|
+
}
|
|
199
|
+
|
|
114
200
|
const deferTracker = {
|
|
115
201
|
track(promise) {
|
|
116
202
|
activeDefers.add(promise);
|
|
@@ -400,9 +486,9 @@ export function serve(config = {}) {
|
|
|
400
486
|
});
|
|
401
487
|
}
|
|
402
488
|
|
|
403
|
-
const { route, params } = match;
|
|
489
|
+
const { route: initialRoute, params: initialParams } = match;
|
|
404
490
|
|
|
405
|
-
if (
|
|
491
|
+
if (initialRoute.meta.priority === 'low' && lagMonitor.isOverloaded()) {
|
|
406
492
|
return buildErrorResponse({
|
|
407
493
|
webReq,
|
|
408
494
|
status: 503,
|
|
@@ -415,6 +501,7 @@ export function serve(config = {}) {
|
|
|
415
501
|
req: webReq,
|
|
416
502
|
method,
|
|
417
503
|
url,
|
|
504
|
+
params: initialParams,
|
|
418
505
|
signal: webReq.signal,
|
|
419
506
|
sessionManager,
|
|
420
507
|
broker,
|
|
@@ -426,28 +513,96 @@ export function serve(config = {}) {
|
|
|
426
513
|
|
|
427
514
|
applyCorsHeaders(webReq, ctx.outgoingHeaders);
|
|
428
515
|
|
|
429
|
-
if (route.meta.sunset) {
|
|
430
|
-
ctx.outgoingHeaders.set('Deprecation', 'true');
|
|
431
|
-
ctx.outgoingHeaders.set('Sunset', new Date(route.meta.sunset).toUTCString());
|
|
432
|
-
}
|
|
433
|
-
|
|
434
516
|
return wireStorage.run(ctx, async () => {
|
|
435
517
|
let activeLimiterBucket = null;
|
|
436
518
|
let limiterMax = 0;
|
|
519
|
+
let route = initialRoute;
|
|
437
520
|
|
|
438
521
|
try {
|
|
439
522
|
if (ctx.sessionHandle && !(sessionManager.store instanceof MemorySessionStore)) {
|
|
440
523
|
await ctx.sessionHandle.preload();
|
|
441
524
|
}
|
|
442
525
|
|
|
526
|
+
const resolved = await resolveAliasChain({
|
|
527
|
+
initialMatch: match,
|
|
528
|
+
initialUrl: url,
|
|
529
|
+
routes,
|
|
530
|
+
method,
|
|
531
|
+
onGuard: async (guards) => {
|
|
532
|
+
for (const guardFn of guards) {
|
|
533
|
+
await guardFn();
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
if (resolved.isVirtualClient) {
|
|
539
|
+
if (!ctx.isSimulated) {
|
|
540
|
+
await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
|
|
541
|
+
}
|
|
542
|
+
ctx.outgoingHeaders.set('Content-Type', 'application/javascript; charset=utf-8');
|
|
543
|
+
ctx.outgoingHeaders.set('Cache-Control', 'no-cache');
|
|
544
|
+
return new Response(virtualClientCode, { status: 200, headers: ctx.outgoingHeaders });
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const activeMatch = resolved.match;
|
|
548
|
+
const effectiveUrl = resolved.url;
|
|
549
|
+
|
|
550
|
+
if (method === 'OPTIONS' && activeMatch.status === 405) {
|
|
551
|
+
const headers = new Headers({
|
|
552
|
+
Allow: activeMatch.allow,
|
|
553
|
+
'Access-Control-Allow-Methods': `${activeMatch.allow}, OPTIONS`,
|
|
554
|
+
'Access-Control-Allow-Headers': webReq.headers.get('access-control-request-headers') || 'Content-Type, Authorization, Idempotency-Key, X-Simulate'
|
|
555
|
+
});
|
|
556
|
+
applyCorsHeaders(webReq, headers);
|
|
557
|
+
return new Response(null, { status: 204, headers });
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (activeMatch.status === 404) {
|
|
561
|
+
return buildErrorResponse({
|
|
562
|
+
webReq,
|
|
563
|
+
status: 404,
|
|
564
|
+
defaultPayload: { error: 'Not Found' },
|
|
565
|
+
existingCtx: ctx
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
if (activeMatch.status === 405) {
|
|
569
|
+
return buildErrorResponse({
|
|
570
|
+
webReq,
|
|
571
|
+
status: 405,
|
|
572
|
+
defaultPayload: null,
|
|
573
|
+
existingCtx: ctx,
|
|
574
|
+
extraHeaders: { Allow: activeMatch.allow }
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
route = activeMatch.route;
|
|
579
|
+
const params = activeMatch.params;
|
|
580
|
+
ctx.url = effectiveUrl;
|
|
581
|
+
ctx.params = params;
|
|
582
|
+
|
|
583
|
+
const effectiveMeta = { ...resolved.inheritedMeta, ...route.meta };
|
|
584
|
+
if (effectiveMeta.priority === 'low' && lagMonitor.isOverloaded()) {
|
|
585
|
+
return buildErrorResponse({
|
|
586
|
+
webReq,
|
|
587
|
+
status: 503,
|
|
588
|
+
defaultPayload: { error: 'Service temporarily overloaded' },
|
|
589
|
+
existingCtx: ctx,
|
|
590
|
+
extraHeaders: { 'Retry-After': '2' }
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (effectiveMeta.sunset) {
|
|
595
|
+
ctx.outgoingHeaders.set('Deprecation', 'true');
|
|
596
|
+
ctx.outgoingHeaders.set('Sunset', new Date(effectiveMeta.sunset).toUTCString());
|
|
597
|
+
}
|
|
598
|
+
|
|
443
599
|
for (const guardFn of route.guards) {
|
|
444
600
|
await guardFn();
|
|
445
601
|
}
|
|
446
602
|
|
|
447
|
-
// Handle declarative RedirectDescriptor
|
|
448
603
|
if (route.redirectDescriptor) {
|
|
449
604
|
const paramValues = route.paramNames.map((name) => params[name]);
|
|
450
|
-
const queryObj = Object.fromEntries(
|
|
605
|
+
const queryObj = Object.fromEntries(effectiveUrl.searchParams.entries());
|
|
451
606
|
const targetUrl = typeof route.redirectDescriptor.target === 'function'
|
|
452
607
|
? await route.redirectDescriptor.target(...paramValues, queryObj)
|
|
453
608
|
: route.redirectDescriptor.target;
|
|
@@ -462,7 +617,6 @@ export function serve(config = {}) {
|
|
|
462
617
|
});
|
|
463
618
|
}
|
|
464
619
|
|
|
465
|
-
// Handle StaticRouteDescriptor (file or folder)
|
|
466
620
|
if (route.staticDescriptor) {
|
|
467
621
|
const staticRes = await buildStaticHttpResponse(
|
|
468
622
|
route.staticDescriptor,
|
|
@@ -492,7 +646,7 @@ export function serve(config = {}) {
|
|
|
492
646
|
}
|
|
493
647
|
|
|
494
648
|
const paramValues = route.paramNames.map((name) => params[name]);
|
|
495
|
-
const queryObj = Object.fromEntries(
|
|
649
|
+
const queryObj = Object.fromEntries(effectiveUrl.searchParams.entries());
|
|
496
650
|
const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
|
|
497
651
|
const contentType = webReq.headers.get('content-type') || '';
|
|
498
652
|
const isMultipart = contentType.toLowerCase().startsWith('multipart/form-data');
|
|
@@ -548,7 +702,6 @@ export function serve(config = {}) {
|
|
|
548
702
|
? [...paramValues, payload, queryObj]
|
|
549
703
|
: [...paramValues, queryObj];
|
|
550
704
|
|
|
551
|
-
// SSE Async Generator Streaming
|
|
552
705
|
if (route.isAsyncGen) {
|
|
553
706
|
if (!ctx.isSimulated) await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
|
|
554
707
|
ctx.outgoingHeaders.set('Content-Type', 'text/event-stream; charset=utf-8');
|
|
@@ -580,7 +733,6 @@ export function serve(config = {}) {
|
|
|
580
733
|
return new Response(stream, { status: ctx.statusCode, headers: ctx.outgoingHeaders });
|
|
581
734
|
}
|
|
582
735
|
|
|
583
|
-
// Idempotency Check for Mutations
|
|
584
736
|
const idemHeader = webReq.headers.get('idempotency-key');
|
|
585
737
|
const idemKey = route.nodeIdempotency && idemHeader ? `${route.nodeId}:${idemHeader}` : null;
|
|
586
738
|
if (idemKey && !ctx.isSimulated) {
|
|
@@ -594,9 +746,8 @@ export function serve(config = {}) {
|
|
|
594
746
|
}
|
|
595
747
|
}
|
|
596
748
|
|
|
597
|
-
// Self-Invalidating Cache Lookup for GET
|
|
598
749
|
const cacheKey = route.nodeCache && method === 'GET'
|
|
599
|
-
? `${route.nodeId}:${JSON.stringify(params)}:${
|
|
750
|
+
? `${route.nodeId}:${JSON.stringify(params)}:${effectiveUrl.search}`
|
|
600
751
|
: null;
|
|
601
752
|
|
|
602
753
|
if (cacheKey) {
|
|
@@ -625,7 +776,7 @@ export function serve(config = {}) {
|
|
|
625
776
|
|
|
626
777
|
let rawResult;
|
|
627
778
|
if (route.nodeInFlight && method === 'GET') {
|
|
628
|
-
const coalKey = `${route.nodeId}:${JSON.stringify(params)}:${
|
|
779
|
+
const coalKey = `${route.nodeId}:${JSON.stringify(params)}:${effectiveUrl.search}`;
|
|
629
780
|
let sharedPromise = route.nodeInFlight.get(coalKey);
|
|
630
781
|
if (!sharedPromise) {
|
|
631
782
|
sharedPromise = executeHandler().finally(() => route.nodeInFlight.delete(coalKey));
|
|
@@ -648,7 +799,6 @@ export function serve(config = {}) {
|
|
|
648
799
|
rawResult = await executeHandler();
|
|
649
800
|
}
|
|
650
801
|
|
|
651
|
-
// Invalidate node cache and ancestor caches on successful mutations
|
|
652
802
|
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !ctx.isSimulated) {
|
|
653
803
|
if (route.nodeCache) {
|
|
654
804
|
const prefix = `${route.nodeId}:${JSON.stringify(params)}:`;
|
|
@@ -727,8 +877,8 @@ export function serve(config = {}) {
|
|
|
727
877
|
}
|
|
728
878
|
|
|
729
879
|
let cleanOutput = applyRedaction(rawResult, config.redact);
|
|
730
|
-
if (method === 'GET' &&
|
|
731
|
-
cleanOutput = applyFieldMask(cleanOutput,
|
|
880
|
+
if (method === 'GET' && effectiveUrl.searchParams.has('fields')) {
|
|
881
|
+
cleanOutput = applyFieldMask(cleanOutput, effectiveUrl.searchParams.get('fields'));
|
|
732
882
|
}
|
|
733
883
|
|
|
734
884
|
if (cacheKey && !ctx.isSimulated) {
|
|
@@ -893,6 +1043,7 @@ export function serve(config = {}) {
|
|
|
893
1043
|
req: syntheticReq,
|
|
894
1044
|
method: 'WS',
|
|
895
1045
|
url,
|
|
1046
|
+
params: match.params,
|
|
896
1047
|
sessionManager,
|
|
897
1048
|
broker,
|
|
898
1049
|
deferTracker
|
|
@@ -904,7 +1055,41 @@ export function serve(config = {}) {
|
|
|
904
1055
|
await ctx.sessionHandle.preload();
|
|
905
1056
|
}
|
|
906
1057
|
|
|
907
|
-
|
|
1058
|
+
const resolved = await resolveAliasChain({
|
|
1059
|
+
initialMatch: match,
|
|
1060
|
+
initialUrl: url,
|
|
1061
|
+
routes,
|
|
1062
|
+
method: 'WS',
|
|
1063
|
+
onGuard: async (guards) => {
|
|
1064
|
+
for (const guardFn of guards) {
|
|
1065
|
+
await guardFn();
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
if (resolved.match.status !== 200) {
|
|
1071
|
+
tcpSocket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
|
|
1072
|
+
tcpSocket.destroy();
|
|
1073
|
+
emitAccessLog({
|
|
1074
|
+
method: 'WS',
|
|
1075
|
+
url,
|
|
1076
|
+
status: 404,
|
|
1077
|
+
durationMs: performance.now() - t0,
|
|
1078
|
+
cached: false,
|
|
1079
|
+
simulated: false,
|
|
1080
|
+
requestId: ctx.requestId,
|
|
1081
|
+
ip: clientIp,
|
|
1082
|
+
userAgent
|
|
1083
|
+
});
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
const activeMatch = resolved.match;
|
|
1088
|
+
const effectiveUrl = resolved.url;
|
|
1089
|
+
ctx.url = effectiveUrl;
|
|
1090
|
+
ctx.params = activeMatch.params;
|
|
1091
|
+
|
|
1092
|
+
for (const guardFn of activeMatch.route.guards) {
|
|
908
1093
|
await guardFn();
|
|
909
1094
|
}
|
|
910
1095
|
|
|
@@ -930,16 +1115,36 @@ export function serve(config = {}) {
|
|
|
930
1115
|
});
|
|
931
1116
|
|
|
932
1117
|
const sid = ctx.sessionHandle?.sid || null;
|
|
1118
|
+
const wsCfg = activeMatch.route.meta.wsConfig || {};
|
|
933
1119
|
const linearSocket = createLinearSocket(
|
|
934
1120
|
tcpSocket,
|
|
935
1121
|
head,
|
|
936
1122
|
broker,
|
|
937
|
-
|
|
1123
|
+
wsCfg,
|
|
938
1124
|
sid
|
|
939
1125
|
);
|
|
940
1126
|
|
|
941
|
-
const
|
|
942
|
-
|
|
1127
|
+
const connData = {};
|
|
1128
|
+
for (const [k, v] of effectiveUrl.searchParams.entries()) {
|
|
1129
|
+
if (k !== '__lastSeq') connData[k] = v;
|
|
1130
|
+
}
|
|
1131
|
+
const lastSeq = Number(effectiveUrl.searchParams.get('__lastSeq') || 0);
|
|
1132
|
+
const reqInfo = {
|
|
1133
|
+
raw: nodeReq,
|
|
1134
|
+
url: effectiveUrl,
|
|
1135
|
+
data: connData,
|
|
1136
|
+
query: effectiveUrl.searchParams,
|
|
1137
|
+
params: activeMatch.params,
|
|
1138
|
+
lastSeq
|
|
1139
|
+
};
|
|
1140
|
+
|
|
1141
|
+
const declarativeRunner = getDeclarativeRuntime(activeMatch.route);
|
|
1142
|
+
if (declarativeRunner) {
|
|
1143
|
+
await declarativeRunner(linearSocket, reqInfo);
|
|
1144
|
+
} else {
|
|
1145
|
+
const paramValues = activeMatch.route.paramNames.map((n) => activeMatch.params[n]);
|
|
1146
|
+
await activeMatch.route.handler(...paramValues, linearSocket);
|
|
1147
|
+
}
|
|
943
1148
|
linearSocket.close(1000, 'Session completed');
|
|
944
1149
|
} catch (err) {
|
|
945
1150
|
if (err instanceof ServinAbortError) {
|
package/src/servin.test.js
CHANGED
|
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
|
|
3
3
|
import fs from 'node:fs/promises';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { serve, wire, guard, serveStatic, redirect } from '../index.js';
|
|
6
|
+
import { serve, wire, guard, param, serveStatic, redirect, alias } from '../index.js';
|
|
7
7
|
|
|
8
8
|
test('Static routing, Redirect, dan Custom Error Pages (404, 401, 403)', async () => {
|
|
9
9
|
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'servin-extra-'));
|
|
@@ -105,4 +105,121 @@ test('Static routing, Redirect, dan Custom Error Pages (404, 401, 403)', async (
|
|
|
105
105
|
await instance.close();
|
|
106
106
|
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
107
107
|
}
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('Alias routing (config alias, helper alias(), dynamic params, guards, query merge, and loop protection)', async () => {
|
|
111
|
+
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'servin-alias-'));
|
|
112
|
+
await fs.mkdir(path.join(tmpDir, 'pages'), { recursive: true });
|
|
113
|
+
await fs.writeFile(path.join(tmpDir, 'home.html'), '<h1>Home Page</h1>', 'utf8');
|
|
114
|
+
await fs.writeFile(path.join(tmpDir, 'about.html'), '<h1>About Page</h1>', 'utf8');
|
|
115
|
+
await fs.writeFile(path.join(tmpDir, 'secret.html'), '<h1>Secret Page</h1>', 'utf8');
|
|
116
|
+
await fs.writeFile(path.join(tmpDir, 'pages', 'intro.html'), '<h1>Intro Docs</h1>', 'utf8');
|
|
117
|
+
|
|
118
|
+
const requireAuth = () => {
|
|
119
|
+
if (wire.headers.get('x-auth') !== 'ok') {
|
|
120
|
+
wire.abort(401, 'Unauthorized');
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const instance = await serve({
|
|
125
|
+
port: 0,
|
|
126
|
+
silent: true,
|
|
127
|
+
static: {
|
|
128
|
+
'/': tmpDir
|
|
129
|
+
},
|
|
130
|
+
alias: {
|
|
131
|
+
'/': '/home.html',
|
|
132
|
+
'/home': '/home.html',
|
|
133
|
+
'/docs/$slug': '/pages/$slug.html',
|
|
134
|
+
'/loop-a': '/loop-b',
|
|
135
|
+
'/loop-b': '/loop-a'
|
|
136
|
+
},
|
|
137
|
+
api: {
|
|
138
|
+
about: alias('/about.html'),
|
|
139
|
+
secret: guard(requireAuth, alias('/secret.html')),
|
|
140
|
+
'active-items': alias('/v2/items?status=active'),
|
|
141
|
+
user: {
|
|
142
|
+
$id: param('int', alias((id) => `/v2/users/${id}`))
|
|
143
|
+
},
|
|
144
|
+
v2: {
|
|
145
|
+
items: {
|
|
146
|
+
get(query) {
|
|
147
|
+
return { items: true, status: query.status, sort: query.sort || null };
|
|
148
|
+
},
|
|
149
|
+
post(payload) {
|
|
150
|
+
return { created: payload };
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
users: {
|
|
154
|
+
$id: param('int', {
|
|
155
|
+
get(id) {
|
|
156
|
+
return { userId: id };
|
|
157
|
+
}
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const base = instance.url;
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
// 1. /home mengakses /home.html tanpa redirect (status 200)
|
|
168
|
+
const homeRes = await fetch(`${base}/home`, { redirect: 'manual' });
|
|
169
|
+
assert.equal(homeRes.status, 200);
|
|
170
|
+
assert.match(homeRes.headers.get('content-type'), /text\/html/);
|
|
171
|
+
assert.equal(await homeRes.text(), '<h1>Home Page</h1>');
|
|
172
|
+
|
|
173
|
+
// 2. Root / alias ke /home.html
|
|
174
|
+
const rootRes = await fetch(`${base}/`, { redirect: 'manual' });
|
|
175
|
+
assert.equal(rootRes.status, 200);
|
|
176
|
+
assert.equal(await rootRes.text(), '<h1>Home Page</h1>');
|
|
177
|
+
|
|
178
|
+
// 3. Helper alias() di dalam api tree
|
|
179
|
+
const aboutRes = await fetch(`${base}/about`, { redirect: 'manual' });
|
|
180
|
+
assert.equal(aboutRes.status, 200);
|
|
181
|
+
assert.equal(await aboutRes.text(), '<h1>About Page</h1>');
|
|
182
|
+
|
|
183
|
+
// 4. Dynamic param interpolation pada config alias (/docs/$slug -> /pages/$slug.html)
|
|
184
|
+
const docsRes = await fetch(`${base}/docs/intro`);
|
|
185
|
+
assert.equal(docsRes.status, 200);
|
|
186
|
+
assert.equal(await docsRes.text(), '<h1>Intro Docs</h1>');
|
|
187
|
+
|
|
188
|
+
// 5. Guard pada alias route
|
|
189
|
+
const unauthRes = await fetch(`${base}/secret`);
|
|
190
|
+
assert.equal(unauthRes.status, 401);
|
|
191
|
+
|
|
192
|
+
const authRes = await fetch(`${base}/secret`, { headers: { 'x-auth': 'ok' } });
|
|
193
|
+
assert.equal(authRes.status, 200);
|
|
194
|
+
assert.equal(await authRes.text(), '<h1>Secret Page</h1>');
|
|
195
|
+
|
|
196
|
+
// 6. Alias ke API route (GET dengan default query + incoming query, dan POST)
|
|
197
|
+
const itemsGet = await fetch(`${base}/active-items?sort=asc`);
|
|
198
|
+
assert.equal(itemsGet.status, 200);
|
|
199
|
+
assert.deepEqual(await itemsGet.json(), { items: true, status: 'active', sort: 'asc' });
|
|
200
|
+
|
|
201
|
+
const itemsPost = await fetch(`${base}/active-items`, {
|
|
202
|
+
method: 'POST',
|
|
203
|
+
headers: { 'Content-Type': 'application/json' },
|
|
204
|
+
body: JSON.stringify({ name: 'Book' })
|
|
205
|
+
});
|
|
206
|
+
assert.equal(itemsPost.status, 200);
|
|
207
|
+
assert.deepEqual(await itemsPost.json(), { created: { name: 'Book' } });
|
|
208
|
+
|
|
209
|
+
// 7. Dynamic resolver function pada alias()
|
|
210
|
+
const userRes = await fetch(`${base}/user/42`);
|
|
211
|
+
assert.equal(userRes.status, 200);
|
|
212
|
+
assert.deepEqual(await userRes.json(), { userId: 42 });
|
|
213
|
+
|
|
214
|
+
// 8. Method yang tidak didukung target tetap mengembalikan 405
|
|
215
|
+
const postHomeRes = await fetch(`${base}/home`, { method: 'POST' });
|
|
216
|
+
assert.equal(postHomeRes.status, 405);
|
|
217
|
+
|
|
218
|
+
// 9. Proteksi loop tak terbatas pada alias
|
|
219
|
+
const loopRes = await fetch(`${base}/loop-a`);
|
|
220
|
+
assert.equal(loopRes.status, 500);
|
|
221
|
+
} finally {
|
|
222
|
+
await instance.close();
|
|
223
|
+
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
224
|
+
}
|
|
108
225
|
});
|