tr-apisrv 1.0.0 → 2.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.
Files changed (4) hide show
  1. package/README.md +254 -68
  2. package/index.js +700 -70
  3. package/package.json +1 -1
  4. package/test/test.js +952 -10
package/test/test.js CHANGED
@@ -17,7 +17,7 @@ function httpRequest(port, { method = 'GET', path = '/', headers = {}, body } =
17
17
  }, (res) => {
18
18
  let data = '';
19
19
  res.on('data', (d) => data += d);
20
- res.on('end', () => resolve({ status: res.statusCode, data }));
20
+ res.on('end', () => resolve({ status: res.statusCode, data, headers: res.headers }));
21
21
  });
22
22
  req.on('error', reject);
23
23
  if (body) {
@@ -45,12 +45,24 @@ test('handles GET requests', async () => {
45
45
  const port = 12350;
46
46
  const srv = new ApiSrv({
47
47
  port,
48
- callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
48
+ callback: (r) => r.jsonResponse({
49
+ method: r.method,
50
+ params: r.params,
51
+ pathParams: r.pathParams,
52
+ urlParams: r.urlParams,
53
+ bodyParams: r.bodyParams
54
+ })
49
55
  });
50
56
  try {
51
57
  const res = await httpRequest(port, { method: 'GET', path: '/?a=1' });
52
58
  assert.strictEqual(res.status, 200);
53
- assert.deepStrictEqual(JSON.parse(res.data), { method: 'GET', params: { a: '1' } });
59
+ assert.deepStrictEqual(JSON.parse(res.data), {
60
+ method: 'GET',
61
+ params: { a: '1' },
62
+ pathParams: {},
63
+ urlParams: { a: '1' },
64
+ bodyParams: {}
65
+ });
54
66
  } finally {
55
67
  await srv.shutdown();
56
68
  }
@@ -60,7 +72,13 @@ test('handles POST requests', async () => {
60
72
  const port = 12351;
61
73
  const srv = new ApiSrv({
62
74
  port,
63
- callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
75
+ callback: (r) => r.jsonResponse({
76
+ method: r.method,
77
+ params: r.params,
78
+ pathParams: r.pathParams,
79
+ urlParams: r.urlParams,
80
+ bodyParams: r.bodyParams
81
+ })
64
82
  });
65
83
  try {
66
84
  const res = await httpRequest(port, {
@@ -70,7 +88,13 @@ test('handles POST requests', async () => {
70
88
  body: JSON.stringify({ a: 1 })
71
89
  });
72
90
  assert.strictEqual(res.status, 200);
73
- assert.deepStrictEqual(JSON.parse(res.data), { method: 'POST', params: { a: 1 } });
91
+ assert.deepStrictEqual(JSON.parse(res.data), {
92
+ method: 'POST',
93
+ params: { a: 1 },
94
+ pathParams: {},
95
+ urlParams: {},
96
+ bodyParams: { a: 1 }
97
+ });
74
98
  } finally {
75
99
  await srv.shutdown();
76
100
  }
@@ -80,7 +104,13 @@ test('handles PUT requests', async () => {
80
104
  const port = 12352;
81
105
  const srv = new ApiSrv({
82
106
  port,
83
- callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
107
+ callback: (r) => r.jsonResponse({
108
+ method: r.method,
109
+ params: r.params,
110
+ pathParams: r.pathParams,
111
+ urlParams: r.urlParams,
112
+ bodyParams: r.bodyParams
113
+ })
84
114
  });
85
115
  try {
86
116
  const res = await httpRequest(port, {
@@ -90,7 +120,13 @@ test('handles PUT requests', async () => {
90
120
  body: 'a=1'
91
121
  });
92
122
  assert.strictEqual(res.status, 200);
93
- assert.deepStrictEqual(JSON.parse(res.data), { method: 'PUT', params: { a: '1' } });
123
+ assert.deepStrictEqual(JSON.parse(res.data), {
124
+ method: 'PUT',
125
+ params: { a: '1' },
126
+ pathParams: {},
127
+ urlParams: {},
128
+ bodyParams: { a: '1' }
129
+ });
94
130
  } finally {
95
131
  await srv.shutdown();
96
132
  }
@@ -100,12 +136,916 @@ test('handles DELETE requests', async () => {
100
136
  const port = 12353;
101
137
  const srv = new ApiSrv({
102
138
  port,
103
- callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
139
+ callback: (r) => r.jsonResponse({
140
+ method: r.method,
141
+ params: r.params,
142
+ pathParams: r.pathParams,
143
+ urlParams: r.urlParams,
144
+ bodyParams: r.bodyParams
145
+ })
104
146
  });
105
147
  try {
106
148
  const res = await httpRequest(port, { method: 'DELETE', path: '/?a=1' });
107
149
  assert.strictEqual(res.status, 200);
108
- assert.deepStrictEqual(JSON.parse(res.data), { method: 'DELETE', params: { a: '1' } });
150
+ assert.deepStrictEqual(JSON.parse(res.data), {
151
+ method: 'DELETE',
152
+ params: { a: '1' },
153
+ pathParams: {},
154
+ urlParams: { a: '1' },
155
+ bodyParams: {}
156
+ });
157
+ } finally {
158
+ await srv.shutdown();
159
+ }
160
+ });
161
+
162
+ test('handlers can respond with JSON errors via errorResponse', async () => {
163
+ const port = 12354;
164
+ const srv = new ApiSrv({
165
+ port,
166
+ requestHandlers: {
167
+ POST: {
168
+ '/items': (r) => r.errorResponse(400, 'Input data is too complex')
169
+ },
170
+ GET: {
171
+ '/items': (r) => r.errorResponse(404)
172
+ }
173
+ }
174
+ });
175
+ try {
176
+ const invalid = await httpRequest(port, {
177
+ method: 'POST',
178
+ path: '/items',
179
+ headers: { 'Content-Type': 'application/json' },
180
+ body: '{}'
181
+ });
182
+ assert.strictEqual(invalid.status, 400);
183
+ const invalidBody = JSON.parse(invalid.data);
184
+ assert.strictEqual(invalidBody.code, 400);
185
+ assert.strictEqual(invalidBody.message, 'Bad Request (Input data is too complex)');
186
+
187
+ const missing = await httpRequest(port, { method: 'GET', path: '/items' });
188
+ assert.strictEqual(missing.status, 404);
189
+ const missingBody = JSON.parse(missing.data);
190
+ assert.strictEqual(missingBody.code, 404);
191
+ assert.strictEqual(missingBody.message, 'Not Found');
192
+ } finally {
193
+ await srv.shutdown();
194
+ }
195
+ });
196
+
197
+ test('requestHandlers take precedence over callback', async () => {
198
+ const port = 12361;
199
+ const srv = new ApiSrv({
200
+ port,
201
+ callback: (r) => r.jsonResponse({ handled: 'callback' }),
202
+ requestHandlers: {
203
+ GET: {
204
+ '/': (r) => r.jsonResponse({ handled: 'requestHandlers' })
205
+ }
206
+ }
207
+ });
208
+ try {
209
+ const res = await httpRequest(port, { method: 'GET', path: '/' });
210
+ assert.strictEqual(res.status, 200);
211
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'requestHandlers' });
212
+ } finally {
213
+ await srv.shutdown();
214
+ }
215
+ });
216
+
217
+ test('requestHandlers support path templates', async (t) => {
218
+ const port = 12362;
219
+ const warnings = [];
220
+ const warnMock = t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
221
+ const srv = new ApiSrv({
222
+ port,
223
+ callback: (r) => r.jsonResponse({ handled: 'callback' }),
224
+ requestHandlers: {
225
+ GET: {
226
+ '/user/{userId}': (r) => r.jsonResponse({
227
+ handled: 'requestHandlers',
228
+ params: r.params,
229
+ pathParams: r.pathParams,
230
+ urlParams: r.urlParams,
231
+ bodyParams: r.bodyParams
232
+ })
233
+ }
234
+ }
235
+ });
236
+ try {
237
+ const res = await httpRequest(port, { method: 'GET', path: '/user/123?foo=bar&userId=query' });
238
+ assert.strictEqual(res.status, 200);
239
+ assert.deepStrictEqual(JSON.parse(res.data), {
240
+ handled: 'requestHandlers',
241
+ params: { foo: 'bar', userId: '123' },
242
+ pathParams: { userId: '123' },
243
+ urlParams: { foo: 'bar', userId: 'query' },
244
+ bodyParams: {}
245
+ });
246
+ assert.strictEqual(warnings.length, 1);
247
+ assert.match(warnings[0], /userId/);
248
+ assert.match(warnings[0], /query string/);
249
+ } finally {
250
+ t.mock.restoreAll();
251
+ await srv.shutdown();
252
+ }
253
+ });
254
+
255
+ test('requestHandlers match trailing slash when template omits it', async () => {
256
+ const port = 12370;
257
+ const srv = new ApiSrv({
258
+ port,
259
+ requestHandlers: {
260
+ GET: {
261
+ '/slashless': (r) => r.jsonResponse({ handled: 'slashless', path: r.url })
262
+ }
263
+ }
264
+ });
265
+ try {
266
+ let res = await httpRequest(port, { method: 'GET', path: '/slashless' });
267
+ assert.strictEqual(res.status, 200);
268
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'slashless', path: '/slashless' });
269
+
270
+ res = await httpRequest(port, { method: 'GET', path: '/slashless/' });
271
+ assert.strictEqual(res.status, 200);
272
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'slashless', path: '/slashless/' });
273
+ } finally {
274
+ await srv.shutdown();
275
+ }
276
+ });
277
+
278
+ test('requestHandlers require trailing slash when template includes it', async () => {
279
+ const port = 12371;
280
+ const srv = new ApiSrv({
281
+ port,
282
+ requestHandlers: {
283
+ GET: {
284
+ '/needs-slash/': (r) => r.jsonResponse({ handled: 'needs-slash' })
285
+ }
286
+ }
287
+ });
288
+ try {
289
+ const withSlash = await httpRequest(port, { method: 'GET', path: '/needs-slash/' });
290
+ assert.strictEqual(withSlash.status, 200);
291
+ assert.deepStrictEqual(JSON.parse(withSlash.data), { handled: 'needs-slash' });
292
+
293
+ const withoutSlash = await httpRequest(port, { method: 'GET', path: '/needs-slash' });
294
+ assert.strictEqual(withoutSlash.status, 404);
295
+ const body = JSON.parse(withoutSlash.data);
296
+ assert.strictEqual(body.code, 404);
297
+ assert.strictEqual(body.message, 'Not Found');
298
+ } finally {
299
+ await srv.shutdown();
300
+ }
301
+ });
302
+
303
+ test('dynamic template without trailing slash matches both forms', async () => {
304
+ const port = 12372;
305
+ const srv = new ApiSrv({
306
+ port,
307
+ requestHandlers: {
308
+ GET: {
309
+ '/user/{userId}': (r) => r.jsonResponse({
310
+ params: r.params,
311
+ pathParams: r.pathParams,
312
+ urlParams: r.urlParams,
313
+ bodyParams: r.bodyParams
314
+ })
315
+ }
316
+ }
317
+ });
318
+ try {
319
+ let res = await httpRequest(port, { method: 'GET', path: '/user/abc' });
320
+ assert.strictEqual(res.status, 200);
321
+ assert.deepStrictEqual(JSON.parse(res.data), {
322
+ params: { userId: 'abc' },
323
+ pathParams: { userId: 'abc' },
324
+ urlParams: {},
325
+ bodyParams: {}
326
+ });
327
+
328
+ res = await httpRequest(port, { method: 'GET', path: '/user/abc/' });
329
+ assert.strictEqual(res.status, 200);
330
+ assert.deepStrictEqual(JSON.parse(res.data), {
331
+ params: { userId: 'abc' },
332
+ pathParams: { userId: 'abc' },
333
+ urlParams: {},
334
+ bodyParams: {}
335
+ });
336
+ } finally {
337
+ await srv.shutdown();
338
+ }
339
+ });
340
+
341
+ test('dynamic template with trailing slash requires trailing slash in request', async () => {
342
+ const port = 12373;
343
+ const srv = new ApiSrv({
344
+ port,
345
+ requestHandlers: {
346
+ GET: {
347
+ '/user/{userId}/': (r) => r.jsonResponse({ params: r.params })
348
+ }
349
+ }
350
+ });
351
+ try {
352
+ const withSlash = await httpRequest(port, { method: 'GET', path: '/user/abc/' });
353
+ assert.strictEqual(withSlash.status, 200);
354
+ assert.deepStrictEqual(JSON.parse(withSlash.data), { params: { userId: 'abc' } });
355
+
356
+ const withoutSlash = await httpRequest(port, { method: 'GET', path: '/user/abc' });
357
+ assert.strictEqual(withoutSlash.status, 404);
358
+ const body = JSON.parse(withoutSlash.data);
359
+ assert.strictEqual(body.code, 404);
360
+ assert.strictEqual(body.message, 'Not Found');
361
+ } finally {
362
+ await srv.shutdown();
363
+ }
364
+ });
365
+
366
+ test('requestHandlers reject invalid path parameter names', () => {
367
+ assert.throws(() => {
368
+ new ApiSrv({
369
+ port: 12394,
370
+ requestHandlers: {
371
+ GET: {
372
+ '/users/{1bad}': () => {}
373
+ }
374
+ }
375
+ });
376
+ }, /Invalid path parameter name/);
377
+
378
+ assert.throws(() => {
379
+ new ApiSrv({
380
+ port: 12395,
381
+ requestHandlers: {
382
+ GET: {
383
+ '/files/[bad-name]': () => {}
384
+ }
385
+ }
386
+ });
387
+ }, /Invalid path parameter name|Invalid path parameter segment/);
388
+ });
389
+
390
+ test('requestHandlers reject invalid array constraints', () => {
391
+ assert.throws(() => {
392
+ new ApiSrv({
393
+ port: 12396,
394
+ requestHandlers: {
395
+ GET: {
396
+ '/files/[segments:0]': () => {}
397
+ }
398
+ }
399
+ });
400
+ }, /Invalid minimum length/);
401
+
402
+ assert.throws(() => {
403
+ new ApiSrv({
404
+ port: 12397,
405
+ requestHandlers: {
406
+ GET: {
407
+ '/files/[segments:5:2]': () => {}
408
+ }
409
+ }
410
+ });
411
+ }, /Invalid length range/);
412
+
413
+ assert.throws(() => {
414
+ new ApiSrv({
415
+ port: 12398,
416
+ requestHandlers: {
417
+ GET: {
418
+ '/files/[segments:4:four]': () => {}
419
+ }
420
+ }
421
+ });
422
+ }, /Invalid path parameter segment/);
423
+ });
424
+
425
+ test('falls back to callback when requestHandlers do not match', async () => {
426
+ const port = 12363;
427
+ const srv = new ApiSrv({
428
+ port,
429
+ callback: (r) => r.jsonResponse({ handled: 'callback' }),
430
+ requestHandlers: {
431
+ GET: {
432
+ '/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
433
+ }
434
+ }
435
+ });
436
+ try {
437
+ const res = await httpRequest(port, { method: 'GET', path: '/' });
438
+ assert.strictEqual(res.status, 200);
439
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'callback' });
440
+ } finally {
441
+ await srv.shutdown();
442
+ }
443
+ });
444
+
445
+ test('request handler definition objects apply validators', async () => {
446
+ const port = 12376;
447
+ const srv = new ApiSrv({
448
+ port,
449
+ requestHandlers: {
450
+ GET: {
451
+ '/validate/{userId}': {
452
+ callback: (r) => r.jsonResponse({
453
+ params: r.params,
454
+ pathParams: r.pathParams,
455
+ urlParams: r.urlParams
456
+ }),
457
+ options: {
458
+ pathParamsValidator: (pathParams) => ({ userId: Number(pathParams.userId) }),
459
+ urlParamsValidator: async (urlParams) => ({ limit: Number(urlParams.limit) }),
460
+ paramsValidator: async (params) => ({ ...params, validated: true })
461
+ }
462
+ }
463
+ }
464
+ }
465
+ });
466
+ try {
467
+ const res = await httpRequest(port, { method: 'GET', path: '/validate/42?limit=5' });
468
+ assert.strictEqual(res.status, 200);
469
+ assert.deepStrictEqual(JSON.parse(res.data), {
470
+ params: { limit: 5, userId: 42, validated: true },
471
+ pathParams: { userId: 42 },
472
+ urlParams: { limit: 5 }
473
+ });
474
+ } finally {
475
+ await srv.shutdown();
476
+ }
477
+ });
478
+
479
+ test('requestHandlers capture array segments with [variable]', async () => {
480
+ const port = 12367;
481
+ const srv = new ApiSrv({
482
+ port,
483
+ requestHandlers: {
484
+ GET: {
485
+ '/files/[pathParts]': (r) => r.jsonResponse({ params: r.params, pathParams: r.pathParams })
486
+ }
487
+ }
488
+ });
489
+ try {
490
+ const res = await httpRequest(port, { method: 'GET', path: '/files/foo/bar/baz' });
491
+ assert.strictEqual(res.status, 200);
492
+ assert.deepStrictEqual(JSON.parse(res.data), {
493
+ params: { pathParts: ['foo', 'bar', 'baz'] },
494
+ pathParams: { pathParts: ['foo', 'bar', 'baz'] }
495
+ });
496
+ } finally {
497
+ await srv.shutdown();
498
+ }
499
+ });
500
+
501
+ test('requestHandlers capture [variable] segments in the middle of a template', async () => {
502
+ const port = 12368;
503
+ const srv = new ApiSrv({
504
+ port,
505
+ requestHandlers: {
506
+ GET: {
507
+ '/{cmd}/[zap]/{bar}/{pup}': (r) => r.jsonResponse({ params: r.params, pathParams: r.pathParams })
508
+ }
509
+ }
510
+ });
511
+ try {
512
+ const res = await httpRequest(port, { method: 'GET', path: '/do/one/two/three/four' });
513
+ assert.strictEqual(res.status, 200);
514
+ assert.deepStrictEqual(JSON.parse(res.data), {
515
+ params: {
516
+ cmd: 'do',
517
+ zap: ['one', 'two'],
518
+ bar: 'three',
519
+ pup: 'four'
520
+ },
521
+ pathParams: {
522
+ cmd: 'do',
523
+ zap: ['one', 'two'],
524
+ bar: 'three',
525
+ pup: 'four'
526
+ }
527
+ });
528
+ } finally {
529
+ await srv.shutdown();
530
+ }
531
+ });
532
+
533
+ test('array path parameter enforces default length constraints', async () => {
534
+ const port = 12390;
535
+ const srv = new ApiSrv({
536
+ port,
537
+ requestHandlers: {
538
+ GET: {
539
+ '/files/[segments]': (r) => r.jsonResponse({ pathParams: r.pathParams })
540
+ }
541
+ }
542
+ });
543
+ const exactly32 = Array.from({ length: 32 }, (_, i) => `part${i}`);
544
+ const tooMany = Array.from({ length: 33 }, (_, i) => `part${i}`);
545
+ try {
546
+ const within = await httpRequest(port, { method: 'GET', path: `/files/${exactly32.join('/')}` });
547
+ assert.strictEqual(within.status, 200);
548
+ const parsedWithin = JSON.parse(within.data);
549
+ assert.deepStrictEqual(parsedWithin.pathParams.segments, exactly32);
550
+
551
+ const overLimit = await httpRequest(port, { method: 'GET', path: `/files/${tooMany.join('/')}` });
552
+ assert.strictEqual(overLimit.status, 404);
553
+ const body = JSON.parse(overLimit.data);
554
+ assert.strictEqual(body.code, 404);
555
+ assert.strictEqual(body.message, 'Not Found');
556
+ } finally {
557
+ await srv.shutdown();
558
+ }
559
+ });
560
+
561
+ test('array path parameter enforces exact length constraint', async () => {
562
+ const port = 12391;
563
+ const srv = new ApiSrv({
564
+ port,
565
+ requestHandlers: {
566
+ GET: {
567
+ '/files/[segments:4]': (r) => r.jsonResponse({ pathParams: r.pathParams })
568
+ }
569
+ }
570
+ });
571
+ const exactlyFour = Array.from({ length: 4 }, (_, i) => `p${i}`);
572
+ const three = exactlyFour.slice(0, 3);
573
+ const five = [...exactlyFour, 'extra'];
574
+ try {
575
+ const exact = await httpRequest(port, { method: 'GET', path: `/files/${exactlyFour.join('/')}` });
576
+ assert.strictEqual(exact.status, 200);
577
+ const parsedExact = JSON.parse(exact.data);
578
+ assert.deepStrictEqual(parsedExact.pathParams.segments, exactlyFour);
579
+
580
+ const tooFew = await httpRequest(port, { method: 'GET', path: `/files/${three.join('/')}` });
581
+ assert.strictEqual(tooFew.status, 404);
582
+ const bodyFew = JSON.parse(tooFew.data);
583
+ assert.strictEqual(bodyFew.code, 404);
584
+ assert.strictEqual(bodyFew.message, 'Not Found');
585
+
586
+ const tooMany = await httpRequest(port, { method: 'GET', path: `/files/${five.join('/')}` });
587
+ assert.strictEqual(tooMany.status, 404);
588
+ const bodyMany = JSON.parse(tooMany.data);
589
+ assert.strictEqual(bodyMany.code, 404);
590
+ assert.strictEqual(bodyMany.message, 'Not Found');
591
+ } finally {
592
+ await srv.shutdown();
593
+ }
594
+ });
595
+
596
+ test('array path parameter enforces min and max constraints', async () => {
597
+ const port = 12392;
598
+ const srv = new ApiSrv({
599
+ port,
600
+ requestHandlers: {
601
+ GET: {
602
+ '/files/[segments:2:4]': (r) => r.jsonResponse({ pathParams: r.pathParams })
603
+ }
604
+ }
605
+ });
606
+ const two = ['a', 'b'];
607
+ const four = ['a', 'b', 'c', 'd'];
608
+ try {
609
+ const minOk = await httpRequest(port, { method: 'GET', path: `/files/${two.join('/')}` });
610
+ assert.strictEqual(minOk.status, 200);
611
+ const parsedMin = JSON.parse(minOk.data);
612
+ assert.deepStrictEqual(parsedMin.pathParams.segments, two);
613
+
614
+ const maxOk = await httpRequest(port, { method: 'GET', path: `/files/${four.join('/')}` });
615
+ assert.strictEqual(maxOk.status, 200);
616
+ const parsedMax = JSON.parse(maxOk.data);
617
+ assert.deepStrictEqual(parsedMax.pathParams.segments, four);
618
+
619
+ const tooFew = await httpRequest(port, { method: 'GET', path: '/files/a' });
620
+ assert.strictEqual(tooFew.status, 404);
621
+ const bodyFew = JSON.parse(tooFew.data);
622
+ assert.strictEqual(bodyFew.code, 404);
623
+ assert.strictEqual(bodyFew.message, 'Not Found');
624
+
625
+ const tooMany = await httpRequest(port, { method: 'GET', path: '/files/a/b/c/d/e' });
626
+ assert.strictEqual(tooMany.status, 404);
627
+ const bodyMany = JSON.parse(tooMany.data);
628
+ assert.strictEqual(bodyMany.code, 404);
629
+ assert.strictEqual(bodyMany.message, 'Not Found');
630
+ } finally {
631
+ await srv.shutdown();
632
+ }
633
+ });
634
+
635
+ test('array path parameter allows raising the default maximum', async () => {
636
+ const port = 12393;
637
+ const srv = new ApiSrv({
638
+ port,
639
+ requestHandlers: {
640
+ GET: {
641
+ '/files/[segments:10:50]': (r) => r.jsonResponse({ pathParams: r.pathParams })
642
+ }
643
+ }
644
+ });
645
+ const ten = Array.from({ length: 10 }, (_, i) => `s${i}`);
646
+ const forty = Array.from({ length: 40 }, (_, i) => `s${i}`);
647
+ const nine = ten.slice(0, 9);
648
+ const fiftyOne = Array.from({ length: 51 }, (_, i) => `s${i}`);
649
+ try {
650
+ const minOk = await httpRequest(port, { method: 'GET', path: `/files/${ten.join('/')}` });
651
+ assert.strictEqual(minOk.status, 200);
652
+ const parsedMin = JSON.parse(minOk.data);
653
+ assert.deepStrictEqual(parsedMin.pathParams.segments, ten);
654
+
655
+ const extended = await httpRequest(port, { method: 'GET', path: `/files/${forty.join('/')}` });
656
+ assert.strictEqual(extended.status, 200);
657
+ const parsedExtended = JSON.parse(extended.data);
658
+ assert.deepStrictEqual(parsedExtended.pathParams.segments, forty);
659
+
660
+ const belowMin = await httpRequest(port, { method: 'GET', path: `/files/${nine.join('/')}` });
661
+ assert.strictEqual(belowMin.status, 404);
662
+ const bodyLow = JSON.parse(belowMin.data);
663
+ assert.strictEqual(bodyLow.code, 404);
664
+ assert.strictEqual(bodyLow.message, 'Not Found');
665
+
666
+ const aboveMax = await httpRequest(port, { method: 'GET', path: `/files/${fiftyOne.join('/')}` });
667
+ assert.strictEqual(aboveMax.status, 404);
668
+ const bodyHigh = JSON.parse(aboveMax.data);
669
+ assert.strictEqual(bodyHigh.code, 404);
670
+ assert.strictEqual(bodyHigh.message, 'Not Found');
671
+ } finally {
672
+ await srv.shutdown();
673
+ }
674
+ });
675
+
676
+ test('ignoreUrlParams prevents query parsing', async () => {
677
+ const port = 12377;
678
+ let urlValidatorCalled = false;
679
+ const srv = new ApiSrv({
680
+ port,
681
+ requestHandlers: {
682
+ GET: {
683
+ '/items/{itemId}': {
684
+ callback: (r) => r.jsonResponse({
685
+ params: r.params,
686
+ pathParams: r.pathParams,
687
+ hasUrlParams: Object.prototype.hasOwnProperty.call(r, 'urlParams')
688
+ }),
689
+ options: {
690
+ ignoreUrlParams: true,
691
+ urlParamsValidator: () => {
692
+ urlValidatorCalled = true;
693
+ return {};
694
+ }
695
+ }
696
+ }
697
+ }
698
+ }
699
+ });
700
+ try {
701
+ const res = await httpRequest(port, { method: 'GET', path: '/items/abc?foo=bar' });
702
+ assert.strictEqual(res.status, 200);
703
+ assert.deepStrictEqual(JSON.parse(res.data), {
704
+ params: { itemId: 'abc' },
705
+ pathParams: { itemId: 'abc' },
706
+ hasUrlParams: false
707
+ });
708
+ assert.strictEqual(urlValidatorCalled, false);
709
+ } finally {
710
+ await srv.shutdown();
711
+ }
712
+ });
713
+
714
+ test('path parameters override body parameters with warning', async (t) => {
715
+ const port = 12369;
716
+ const warnings = [];
717
+ const warnMock = t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
718
+ const srv = new ApiSrv({
719
+ port,
720
+ requestHandlers: {
721
+ POST: {
722
+ '/user/{userId}': (r) => r.jsonResponse({
723
+ params: r.params,
724
+ pathParams: r.pathParams,
725
+ urlParams: r.urlParams,
726
+ bodyParams: r.bodyParams
727
+ })
728
+ }
729
+ }
730
+ });
731
+ try {
732
+ const res = await httpRequest(port, {
733
+ method: 'POST',
734
+ path: '/user/123',
735
+ headers: { 'Content-Type': 'application/json' },
736
+ body: JSON.stringify({ userId: 'fromBody', name: 'alice' })
737
+ });
738
+ assert.strictEqual(res.status, 200);
739
+ assert.deepStrictEqual(JSON.parse(res.data), {
740
+ params: { userId: '123', name: 'alice' },
741
+ pathParams: { userId: '123' },
742
+ urlParams: {},
743
+ bodyParams: { userId: 'fromBody', name: 'alice' }
744
+ });
745
+ assert.strictEqual(warnings.length, 1);
746
+ assert.match(warnings[0], /userId/);
747
+ assert.match(warnings[0], /request body/);
748
+ } finally {
749
+ t.mock.restoreAll();
750
+ await srv.shutdown();
751
+ }
752
+ });
753
+
754
+ test('returns 404 when no handler matches and callback missing', async () => {
755
+ const port = 12364;
756
+ const srv = new ApiSrv({
757
+ port,
758
+ requestHandlers: {
759
+ GET: {
760
+ '/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
761
+ }
762
+ }
763
+ });
764
+ try {
765
+ const res = await httpRequest(port, { method: 'GET', path: '/bar' });
766
+ assert.strictEqual(res.status, 404);
767
+ assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
768
+ const body = JSON.parse(res.data);
769
+ assert.strictEqual(body.code, 404);
770
+ assert.strictEqual(body.message, 'Not Found');
771
+ } finally {
772
+ await srv.shutdown();
773
+ }
774
+ });
775
+
776
+ test('returns 405 when path matches other method and callback missing', async () => {
777
+ const port = 12365;
778
+ const srv = new ApiSrv({
779
+ port,
780
+ requestHandlers: {
781
+ GET: {
782
+ '/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
783
+ }
784
+ }
785
+ });
786
+ try {
787
+ const res = await httpRequest(port, {
788
+ method: 'POST',
789
+ path: '/foo',
790
+ headers: { 'Content-Type': 'application/json' },
791
+ body: JSON.stringify({})
792
+ });
793
+ assert.strictEqual(res.status, 405);
794
+ assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
795
+ const body = JSON.parse(res.data);
796
+ assert.strictEqual(body.code, 405);
797
+ assert.strictEqual(body.message, 'Method Not Allowed');
798
+ } finally {
799
+ await srv.shutdown();
800
+ }
801
+ });
802
+
803
+ test('rejects dangerous paths by default', async () => {
804
+ const port = 12367;
805
+ let handled = 0;
806
+ const srv = new ApiSrv({
807
+ port,
808
+ callback: (r) => {
809
+ handled++;
810
+ r.jsonResponse({ ok: true });
811
+ }
812
+ });
813
+ try {
814
+ const cases = [
815
+ { path: '/foo//bar', message: 'Bad Request (empty path segment)' },
816
+ { path: '/foo/./bar', message: 'Bad Request (dangerous path segment ".")' },
817
+ { path: '/foo/../bar', message: 'Bad Request (dangerous path segment "..")' }
818
+ ];
819
+ for (const { path, message } of cases) {
820
+ const res = await httpRequest(port, { method: 'GET', path });
821
+ assert.strictEqual(res.status, 400);
822
+ assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
823
+ const body = JSON.parse(res.data);
824
+ assert.strictEqual(body.code, 400);
825
+ assert.strictEqual(body.message, message);
826
+ }
827
+ assert.strictEqual(handled, 0);
828
+ } finally {
829
+ await srv.shutdown();
830
+ }
831
+ });
832
+
833
+ test('dangerous path rejection can be disabled', async () => {
834
+ const port = 12368;
835
+ let handled = 0;
836
+ const srv = new ApiSrv({
837
+ port,
838
+ rejectDangerousPaths: false,
839
+ callback: (r) => {
840
+ handled++;
841
+ r.jsonResponse({ url: r.url });
842
+ }
843
+ });
844
+ try {
845
+ const res = await httpRequest(port, { method: 'GET', path: '/foo//bar' });
846
+ assert.strictEqual(res.status, 200);
847
+ assert.deepStrictEqual(JSON.parse(res.data), { url: '/foo//bar' });
848
+ assert.strictEqual(handled, 1);
849
+ } finally {
850
+ await srv.shutdown();
851
+ }
852
+ });
853
+
854
+ test('requestHandleAdd and requestHandleDelete modify handlers at runtime', async () => {
855
+ const port = 12366;
856
+ const srv = new ApiSrv({ port });
857
+ srv.requestHandleAdd('GET', '/dynamic', (r) => r.jsonResponse({ method: r.method }));
858
+ srv.requestHandleAdd('POST', '/dynamic', (r) => r.jsonResponse({ method: r.method }));
859
+ try {
860
+ let res = await httpRequest(port, { method: 'GET', path: '/dynamic' });
861
+ assert.strictEqual(res.status, 200);
862
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'GET' });
863
+
864
+ res = await httpRequest(port, {
865
+ method: 'POST',
866
+ path: '/dynamic',
867
+ headers: { 'Content-Type': 'application/json' },
868
+ body: JSON.stringify({})
869
+ });
870
+ assert.strictEqual(res.status, 200);
871
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'POST' });
872
+
873
+ srv.requestHandleDelete('GET', '/dynamic');
874
+ res = await httpRequest(port, { method: 'GET', path: '/dynamic' });
875
+ assert.strictEqual(res.status, 405);
876
+ let body = JSON.parse(res.data);
877
+ assert.strictEqual(body.code, 405);
878
+ assert.strictEqual(body.message, 'Method Not Allowed');
879
+
880
+ srv.requestHandleDelete('*', '/dynamic');
881
+ res = await httpRequest(port, {
882
+ method: 'POST',
883
+ path: '/dynamic',
884
+ headers: { 'Content-Type': 'application/json' },
885
+ body: JSON.stringify({})
886
+ });
887
+ assert.strictEqual(res.status, 404);
888
+ body = JSON.parse(res.data);
889
+ assert.strictEqual(body.code, 404);
890
+ assert.strictEqual(body.message, 'Not Found');
891
+ } finally {
892
+ await srv.shutdown();
893
+ }
894
+ });
895
+
896
+ test('requestHandleAdd supports validator options', async () => {
897
+ const port = 12378;
898
+ const srv = new ApiSrv({ port });
899
+ srv.requestHandleAdd('POST', '/items/{itemId}', (r) => r.jsonResponse({
900
+ params: r.params,
901
+ pathParams: r.pathParams,
902
+ bodyParams: r.bodyParams,
903
+ urlParams: r.urlParams
904
+ }), {
905
+ pathParamsValidator: (pathParams) => ({ itemId: Number(pathParams.itemId) }),
906
+ bodyParamsValidator: async (bodyParams) => ({
907
+ name: bodyParams.name.toUpperCase(),
908
+ count: Number(bodyParams.count)
909
+ }),
910
+ paramsValidator: (params) => ({ ...params, validated: true })
911
+ });
912
+ try {
913
+ const res = await httpRequest(port, {
914
+ method: 'POST',
915
+ path: '/items/5',
916
+ headers: { 'Content-Type': 'application/json' },
917
+ body: JSON.stringify({ name: 'foo', count: '3' })
918
+ });
919
+ assert.strictEqual(res.status, 200);
920
+ assert.deepStrictEqual(JSON.parse(res.data), {
921
+ params: { name: 'FOO', count: 3, itemId: 5, validated: true },
922
+ pathParams: { itemId: 5 },
923
+ bodyParams: { name: 'FOO', count: 3 },
924
+ urlParams: {}
925
+ });
926
+ } finally {
927
+ await srv.shutdown();
928
+ }
929
+ });
930
+
931
+ test('requestHandleAdd enforces path template constraints', async () => {
932
+ const port = 12399;
933
+ const srv = new ApiSrv({ port });
934
+ try {
935
+ assert.throws(() => {
936
+ srv.requestHandleAdd('GET', '/bad/{1foo}', () => {});
937
+ }, /Invalid path parameter name/);
938
+
939
+ assert.throws(() => {
940
+ srv.requestHandleAdd('GET', '/bad/[parts:0]', () => {});
941
+ }, /Invalid minimum length/);
942
+ } finally {
943
+ await srv.shutdown();
944
+ }
945
+ });
946
+
947
+ test('authentication runs before parameter parsing', async () => {
948
+ const port = 12379;
949
+ let authSnapshot;
950
+ let handlerSnapshot;
951
+ const srv = new ApiSrv({
952
+ port,
953
+ requestHandlers: {
954
+ POST: {
955
+ '/items/{itemId}': {
956
+ callback: (r) => {
957
+ const normalizedPath = r.pathParams === undefined ? undefined : { ...r.pathParams };
958
+ const normalizedUrl = r.urlParams === undefined ? undefined : { ...r.urlParams };
959
+ handlerSnapshot = {
960
+ bodyParams: r.bodyParams,
961
+ pathParams: normalizedPath,
962
+ urlParams: normalizedUrl,
963
+ params: r.params
964
+ };
965
+ r.jsonResponse({ ok: true });
966
+ }
967
+ }
968
+ }
969
+ },
970
+ authCallback: (r) => {
971
+ authSnapshot = {
972
+ bodyParams: r.bodyParams,
973
+ pathParams: r.pathParams,
974
+ urlParams: r.urlParams,
975
+ params: r.params
976
+ };
977
+ return true;
978
+ }
979
+ });
980
+ try {
981
+ const res = await httpRequest(port, {
982
+ method: 'POST',
983
+ path: '/items/10',
984
+ headers: { 'Content-Type': 'application/json' },
985
+ body: JSON.stringify({ name: 'foo' })
986
+ });
987
+ assert.strictEqual(res.status, 200);
988
+ assert.deepStrictEqual(authSnapshot, {
989
+ bodyParams: undefined,
990
+ pathParams: undefined,
991
+ urlParams: undefined,
992
+ params: undefined
993
+ });
994
+ assert.deepStrictEqual(handlerSnapshot, {
995
+ bodyParams: { name: 'foo' },
996
+ pathParams: { itemId: '10' },
997
+ urlParams: {},
998
+ params: { name: 'foo', itemId: '10' }
999
+ });
1000
+ } finally {
1001
+ await srv.shutdown();
1002
+ }
1003
+ });
1004
+
1005
+ test('authentication failure skips parameter parsing', async () => {
1006
+ const port = 12380;
1007
+ let authCalls = 0;
1008
+ let authSnapshot;
1009
+ const srv = new ApiSrv({
1010
+ port,
1011
+ requestHandlers: {
1012
+ POST: {
1013
+ '/items': {
1014
+ callback: () => {
1015
+ throw new Error('handler must not be invoked');
1016
+ }
1017
+ }
1018
+ }
1019
+ },
1020
+ authCallback: (r) => {
1021
+ authCalls++;
1022
+ authSnapshot = {
1023
+ bodyParams: r.bodyParams,
1024
+ pathParams: r.pathParams,
1025
+ urlParams: r.urlParams,
1026
+ params: r.params
1027
+ };
1028
+ r.res.writeHead(401, { 'Content-Type': 'text/plain' });
1029
+ r.res.end('unauthorized');
1030
+ return false;
1031
+ }
1032
+ });
1033
+ try {
1034
+ const res = await httpRequest(port, {
1035
+ method: 'POST',
1036
+ path: '/items',
1037
+ headers: { 'Content-Type': 'application/json' },
1038
+ body: '{'
1039
+ });
1040
+ assert.strictEqual(res.status, 401);
1041
+ assert.strictEqual(res.data, 'unauthorized');
1042
+ assert.strictEqual(authCalls, 1);
1043
+ assert.deepStrictEqual(authSnapshot, {
1044
+ bodyParams: undefined,
1045
+ pathParams: undefined,
1046
+ urlParams: undefined,
1047
+ params: undefined
1048
+ });
109
1049
  } finally {
110
1050
  await srv.shutdown();
111
1051
  }
@@ -173,7 +1113,9 @@ test('body read timeout returns 408', async () => {
173
1113
  req.write('123'); // intentionally never calling end to trigger timeout
174
1114
  });
175
1115
  assert.strictEqual(res.status, 408);
176
- assert.strictEqual(res.data, 'Timeout occured while reading the request data.\n');
1116
+ const body = JSON.parse(res.data);
1117
+ assert.strictEqual(body.code, 408);
1118
+ assert.strictEqual(body.message, 'Request Timeout');
177
1119
  } finally {
178
1120
  await srv.shutdown();
179
1121
  }