@dim24/servin 1.0.0 → 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 CHANGED
@@ -28,6 +28,7 @@
28
28
  - [5.1 Static File & Folder Routing (`serveStatic` & `static`)](#51-static-file--folder-routing-servestatic--static)
29
29
  - [5.2 HTTP Redirects (`wire.redirect` & `redirect`)](#52-http-redirects-wireredirect--redirect)
30
30
  - [5.3 Custom Error Pages (`404`, `401`, `403`, `500`, etc.)](#53-custom-error-pages-404-401-403-500-etc)
31
+ - [5.4 Alias Routing (`alias`)](#54-alias-routing-alias)
31
32
  6. [Server Configuration (`serve`)](#6-server-configuration-serve)
32
33
  - [6.1 All `serve()` Options](#61-all-serve-options)
33
34
  - [6.2 Server Instance Control (`port`, `url`, `fetch`, `close`)](#62-server-instance-control-port-url-fetch-close)
@@ -1461,6 +1462,53 @@ await serve({
1461
1462
  | `error` | `Error \| null` | Original thrown error instance if available. |
1462
1463
  | `wire` | `object` | Active `wire` ambient context handle. |
1463
1464
 
1465
+ ### 5.4 Alias Routing (`alias`)
1466
+
1467
+ Unlike `redirect()` (which responds with a `301`/`302` redirect and changes the browser URL), **alias routing** maps a URL path internally to another static file or API route without changing the URL in the client's browser.
1468
+
1469
+ **1. Config-level aliases via `serve({ alias })`:**
1470
+
1471
+ ```javascript
1472
+ import { serve } from "servin";
1473
+
1474
+ await serve({
1475
+ port: 3000,
1476
+ static: {
1477
+ "/": "./public", // contains home.html, pages/intro.html
1478
+ },
1479
+ alias: {
1480
+ "/": "/home.html",
1481
+ "/home": "/home.html",
1482
+ "/docs/$slug": "/pages/$slug.html",
1483
+ },
1484
+ });
1485
+ ```
1486
+
1487
+ **2. Tree-level `alias(target)` helper inside `api` (composable with `guard()` and `param()`):**
1488
+
1489
+ ```javascript
1490
+ import { serve, alias, guard, param } from "servin";
1491
+
1492
+ await serve({
1493
+ port: 3000,
1494
+ static: { "/": "./public" },
1495
+ api: {
1496
+ home: alias("/home.html"),
1497
+ secret: guard(requireAuth, alias("/secret.html")),
1498
+ user: {
1499
+ $id: param("int", alias((id) => `/v2/users/${id}`)),
1500
+ },
1501
+ v2: {
1502
+ users: {
1503
+ $id: param("int", {
1504
+ get: (id) => ({ userId: id }),
1505
+ }),
1506
+ },
1507
+ },
1508
+ },
1509
+ });
1510
+ ```
1511
+
1464
1512
  ---
1465
1513
 
1466
1514
  ## 6. Server Configuration (`serve`)
@@ -1473,6 +1521,7 @@ await serve({
1473
1521
  | `host` | `string` | `'127.0.0.1'` | Host interface to bind (use `'0.0.0.0'` inside Docker/containers). |
1474
1522
  | `api` | `object` | `{}` | Root domain object defining all routes. |
1475
1523
  | `static` | `string \| StaticDescriptor \| object` | `null` | Root or prefix-mapped static files/directories (e.g., `{ '/assets': './public' }`). |
1524
+ | `alias` | `object \| null` | `null` | Internal route aliases mapping paths to target paths/resolvers (e.g., `{ '/home': '/home.html' }`). |
1476
1525
  | `errors` | `object` | `undefined` | Custom status handlers (`404`, `401`, `403`, `500`, `'4xx'`, `'5xx'`, `default`). |
1477
1526
  | `types` | `object` | `{}` | Named custom parameter types usable via `param('typeName', branch)`. |
1478
1527
  | `session` | `object \| null` | `null` | Session config `{ secret, ttl, cookieName, rolling, secure, sameSite, store }`. |
package/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export { serve } from './src/server.js';
2
2
  export { wire, reactTo } from './src/wire.js';
3
- export { guard, param, serveStatic, redirect } from './src/tree.js';
3
+ export { guard, param, serveStatic, redirect, alias } from './src/tree.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dim24/servin",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "A modern, zero-dependency JavaScript web server built around *Domain-Tree Projection.",
5
5
  "homepage": "https://github.com/harakun24/servin#readme",
6
6
  "bugs": {
package/src/server.js CHANGED
@@ -98,11 +98,84 @@ async function parseBodyPayload(req, webhookConfig) {
98
98
  }
99
99
  }
100
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
+
101
169
  export function serve(config = {}) {
102
170
  const port = config.port ?? 3000;
103
171
  const host = config.host ?? '127.0.0.1';
104
172
  const silent = config.silent ?? false;
105
- const routes = compileDomainTree(config.api || {}, config.types || {}, config.static || null);
173
+ const routes = compileDomainTree(
174
+ config.api || {},
175
+ config.types || {},
176
+ config.static || null,
177
+ config.alias ?? config.aliases ?? null
178
+ );
106
179
  const virtualClientCode = generateVirtualClientModule(routes);
107
180
 
108
181
  const broker = new WebSocketBroker();
@@ -413,9 +486,9 @@ export function serve(config = {}) {
413
486
  });
414
487
  }
415
488
 
416
- const { route, params } = match;
489
+ const { route: initialRoute, params: initialParams } = match;
417
490
 
418
- if (route.meta.priority === 'low' && lagMonitor.isOverloaded()) {
491
+ if (initialRoute.meta.priority === 'low' && lagMonitor.isOverloaded()) {
419
492
  return buildErrorResponse({
420
493
  webReq,
421
494
  status: 503,
@@ -428,6 +501,7 @@ export function serve(config = {}) {
428
501
  req: webReq,
429
502
  method,
430
503
  url,
504
+ params: initialParams,
431
505
  signal: webReq.signal,
432
506
  sessionManager,
433
507
  broker,
@@ -439,27 +513,96 @@ export function serve(config = {}) {
439
513
 
440
514
  applyCorsHeaders(webReq, ctx.outgoingHeaders);
441
515
 
442
- if (route.meta.sunset) {
443
- ctx.outgoingHeaders.set('Deprecation', 'true');
444
- ctx.outgoingHeaders.set('Sunset', new Date(route.meta.sunset).toUTCString());
445
- }
446
-
447
516
  return wireStorage.run(ctx, async () => {
448
517
  let activeLimiterBucket = null;
449
518
  let limiterMax = 0;
519
+ let route = initialRoute;
450
520
 
451
521
  try {
452
522
  if (ctx.sessionHandle && !(sessionManager.store instanceof MemorySessionStore)) {
453
523
  await ctx.sessionHandle.preload();
454
524
  }
455
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
+
456
599
  for (const guardFn of route.guards) {
457
600
  await guardFn();
458
601
  }
459
602
 
460
603
  if (route.redirectDescriptor) {
461
604
  const paramValues = route.paramNames.map((name) => params[name]);
462
- const queryObj = Object.fromEntries(url.searchParams.entries());
605
+ const queryObj = Object.fromEntries(effectiveUrl.searchParams.entries());
463
606
  const targetUrl = typeof route.redirectDescriptor.target === 'function'
464
607
  ? await route.redirectDescriptor.target(...paramValues, queryObj)
465
608
  : route.redirectDescriptor.target;
@@ -503,7 +646,7 @@ export function serve(config = {}) {
503
646
  }
504
647
 
505
648
  const paramValues = route.paramNames.map((name) => params[name]);
506
- const queryObj = Object.fromEntries(url.searchParams.entries());
649
+ const queryObj = Object.fromEntries(effectiveUrl.searchParams.entries());
507
650
  const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
508
651
  const contentType = webReq.headers.get('content-type') || '';
509
652
  const isMultipart = contentType.toLowerCase().startsWith('multipart/form-data');
@@ -604,7 +747,7 @@ export function serve(config = {}) {
604
747
  }
605
748
 
606
749
  const cacheKey = route.nodeCache && method === 'GET'
607
- ? `${route.nodeId}:${JSON.stringify(params)}:${url.search}`
750
+ ? `${route.nodeId}:${JSON.stringify(params)}:${effectiveUrl.search}`
608
751
  : null;
609
752
 
610
753
  if (cacheKey) {
@@ -633,7 +776,7 @@ export function serve(config = {}) {
633
776
 
634
777
  let rawResult;
635
778
  if (route.nodeInFlight && method === 'GET') {
636
- const coalKey = `${route.nodeId}:${JSON.stringify(params)}:${url.search}`;
779
+ const coalKey = `${route.nodeId}:${JSON.stringify(params)}:${effectiveUrl.search}`;
637
780
  let sharedPromise = route.nodeInFlight.get(coalKey);
638
781
  if (!sharedPromise) {
639
782
  sharedPromise = executeHandler().finally(() => route.nodeInFlight.delete(coalKey));
@@ -734,8 +877,8 @@ export function serve(config = {}) {
734
877
  }
735
878
 
736
879
  let cleanOutput = applyRedaction(rawResult, config.redact);
737
- if (method === 'GET' && url.searchParams.has('fields')) {
738
- cleanOutput = applyFieldMask(cleanOutput, url.searchParams.get('fields'));
880
+ if (method === 'GET' && effectiveUrl.searchParams.has('fields')) {
881
+ cleanOutput = applyFieldMask(cleanOutput, effectiveUrl.searchParams.get('fields'));
739
882
  }
740
883
 
741
884
  if (cacheKey && !ctx.isSimulated) {
@@ -900,6 +1043,7 @@ export function serve(config = {}) {
900
1043
  req: syntheticReq,
901
1044
  method: 'WS',
902
1045
  url,
1046
+ params: match.params,
903
1047
  sessionManager,
904
1048
  broker,
905
1049
  deferTracker
@@ -911,7 +1055,41 @@ export function serve(config = {}) {
911
1055
  await ctx.sessionHandle.preload();
912
1056
  }
913
1057
 
914
- for (const guardFn of match.route.guards) {
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) {
915
1093
  await guardFn();
916
1094
  }
917
1095
 
@@ -937,7 +1115,7 @@ export function serve(config = {}) {
937
1115
  });
938
1116
 
939
1117
  const sid = ctx.sessionHandle?.sid || null;
940
- const wsCfg = match.route.meta.wsConfig || {};
1118
+ const wsCfg = activeMatch.route.meta.wsConfig || {};
941
1119
  const linearSocket = createLinearSocket(
942
1120
  tcpSocket,
943
1121
  head,
@@ -947,25 +1125,25 @@ export function serve(config = {}) {
947
1125
  );
948
1126
 
949
1127
  const connData = {};
950
- for (const [k, v] of url.searchParams.entries()) {
1128
+ for (const [k, v] of effectiveUrl.searchParams.entries()) {
951
1129
  if (k !== '__lastSeq') connData[k] = v;
952
1130
  }
953
- const lastSeq = Number(url.searchParams.get('__lastSeq') || 0);
1131
+ const lastSeq = Number(effectiveUrl.searchParams.get('__lastSeq') || 0);
954
1132
  const reqInfo = {
955
1133
  raw: nodeReq,
956
- url,
1134
+ url: effectiveUrl,
957
1135
  data: connData,
958
- query: url.searchParams,
959
- params: match.params,
1136
+ query: effectiveUrl.searchParams,
1137
+ params: activeMatch.params,
960
1138
  lastSeq
961
1139
  };
962
1140
 
963
- const declarativeRunner = getDeclarativeRuntime(match.route);
1141
+ const declarativeRunner = getDeclarativeRuntime(activeMatch.route);
964
1142
  if (declarativeRunner) {
965
1143
  await declarativeRunner(linearSocket, reqInfo);
966
1144
  } else {
967
- const paramValues = match.route.paramNames.map((n) => match.params[n]);
968
- await match.route.handler(...paramValues, linearSocket);
1145
+ const paramValues = activeMatch.route.paramNames.map((n) => activeMatch.params[n]);
1146
+ await activeMatch.route.handler(...paramValues, linearSocket);
969
1147
  }
970
1148
  linearSocket.close(1000, 'Session completed');
971
1149
  } catch (err) {
@@ -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
  });
package/src/tree.js CHANGED
@@ -1,9 +1,10 @@
1
- import { StaticRouteDescriptor, RedirectDescriptor } from './utils.js';
1
+ import { StaticRouteDescriptor, RedirectDescriptor, AliasDescriptor } from './utils.js';
2
2
 
3
3
  const GUARD_META = Symbol('servin.guard');
4
4
  const PARAM_META = Symbol('servin.param');
5
5
 
6
6
  const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
7
+ const ALL_ALIAS_VERBS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'WS'];
7
8
  const META_KEYS = new Set([
8
9
  'expect',
9
10
  'cache',
@@ -129,7 +130,11 @@ function attachMeta(branch, { addGuard, setParam }) {
129
130
  return branch.apply(this, args);
130
131
  };
131
132
  }
132
- } else if (branch instanceof StaticRouteDescriptor || branch instanceof RedirectDescriptor) {
133
+ } else if (
134
+ branch instanceof StaticRouteDescriptor ||
135
+ branch instanceof RedirectDescriptor ||
136
+ branch instanceof AliasDescriptor
137
+ ) {
133
138
  target = Object.assign(Object.create(Object.getPrototypeOf(branch)), branch);
134
139
  } else if (branch && typeof branch === 'object') {
135
140
  target = { ...branch };
@@ -176,6 +181,10 @@ export function redirect(target, status = 301) {
176
181
  return new RedirectDescriptor(target, status);
177
182
  }
178
183
 
184
+ export function alias(target, options = {}) {
185
+ return new AliasDescriptor(target, options);
186
+ }
187
+
179
188
  function parseVerbKey(key) {
180
189
  if (key === 'ws') return ['WS'];
181
190
  const parts = key.split('|').map((s) => s.trim().toUpperCase());
@@ -202,7 +211,7 @@ function classifySegment(seg, customTypes = {}, paramRule = null) {
202
211
  }
203
212
  return { type: 'static', priority: 0, value: seg, parse: null, raw: seg };
204
213
  }
205
- export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig = null) {
214
+ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig = null, aliasConfig = null) {
206
215
  const routes = [];
207
216
  let nodeCounter = 0;
208
217
 
@@ -259,6 +268,28 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
259
268
  });
260
269
  }
261
270
 
271
+ function registerAliasDescriptor(descriptor, fullSegments, dotPath, inheritedGuards, inheritedMeta, verbs = ALL_ALIAS_VERBS) {
272
+ const paramNames = fullSegments.filter((s) => s.type !== 'static').map((s) => s.param);
273
+ const descGuards = [...inheritedGuards, ...(descriptor[GUARD_META] || [])];
274
+
275
+ routes.push({
276
+ nodeId: `alias_${++nodeCounter}`,
277
+ dotPath: dotPath.join('.'),
278
+ segments: fullSegments,
279
+ paramNames,
280
+ verbs,
281
+ aliasDescriptor: descriptor,
282
+ handler: null,
283
+ isAsyncGen: false,
284
+ guards: descGuards,
285
+ meta: inheritedMeta,
286
+ nodeCache: null,
287
+ ancestorCaches: [],
288
+ nodeInFlight: null,
289
+ nodeIdempotency: null
290
+ });
291
+ }
292
+
262
293
  function walk(node, segments, dotPath, inheritedGuards, inheritedMeta, ancestorCaches) {
263
294
  if (!node || typeof node !== 'object') return;
264
295
 
@@ -309,6 +340,11 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
309
340
  continue;
310
341
  }
311
342
 
343
+ if (verbs && value instanceof AliasDescriptor) {
344
+ registerAliasDescriptor(value, segments, [...dotPath, key], guards, meta, verbs);
345
+ continue;
346
+ }
347
+
312
348
  if (verbs && typeof value === 'function') {
313
349
  const paramNames = segments.filter((s) => s.type !== 'static').map((s) => s.param);
314
350
  routes.push({
@@ -370,6 +406,12 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
370
406
  continue;
371
407
  }
372
408
 
409
+ if (value instanceof AliasDescriptor) {
410
+ const seg = classifySegment(key, customTypes, paramRule);
411
+ registerAliasDescriptor(value, [...segments, seg], [...dotPath, key], guards, meta);
412
+ continue;
413
+ }
414
+
373
415
  if (typeof value === 'function') {
374
416
  const seg = classifySegment(key, customTypes, paramRule);
375
417
  const childSegments = [...segments, seg];
@@ -423,6 +465,25 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
423
465
  }
424
466
  }
425
467
 
468
+ if (aliasConfig && typeof aliasConfig === 'object') {
469
+ for (const [sourcePath, target] of Object.entries(aliasConfig)) {
470
+ const desc = target instanceof AliasDescriptor
471
+ ? target
472
+ : new AliasDescriptor(target);
473
+ const cleanPrefix = sourcePath.replace(/^\/+|\/+$/g, '');
474
+ const prefixSegs = cleanPrefix
475
+ ? cleanPrefix.split('/').map((s) => classifySegment(s, customTypes))
476
+ : [];
477
+ registerAliasDescriptor(
478
+ desc,
479
+ prefixSegs,
480
+ ['alias', ...prefixSegs.map((s) => s.raw)],
481
+ [],
482
+ {}
483
+ );
484
+ }
485
+ }
486
+
426
487
  routes.sort((a, b) => {
427
488
  const minLen = Math.min(a.segments.length, b.segments.length);
428
489
  for (let i = 0; i < minLen; i++) {
@@ -877,7 +938,7 @@ export function matchDomainRoute(routes, method, pathname) {
877
938
 
878
939
  export function generateVirtualClientModule(routes) {
879
940
  const manifest = routes
880
- .filter((r) => !r.staticDescriptor && !r.redirectDescriptor)
941
+ .filter((r) => !r.staticDescriptor && !r.redirectDescriptor && !r.aliasDescriptor)
881
942
  .map((r) => ({
882
943
  dotPath: r.dotPath,
883
944
  verbs: r.verbs,
package/src/utils.js CHANGED
@@ -78,6 +78,16 @@ export class RedirectDescriptor {
78
78
  }
79
79
  }
80
80
 
81
+ export class AliasDescriptor {
82
+ constructor(target, options = {}) {
83
+ if (!target || (typeof target !== 'string' && typeof target !== 'function')) {
84
+ throw new TypeError('alias(target, options) requires a target URL/path string or resolver function');
85
+ }
86
+ this.target = target;
87
+ this.options = options;
88
+ }
89
+ }
90
+
81
91
  export function parseDuration(input, fallbackMs = 0) {
82
92
  if (typeof input === 'number') return input;
83
93
  if (typeof input !== 'string') return fallbackMs;