@ooneex/http-header 0.0.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 ADDED
@@ -0,0 +1,1328 @@
1
+ # @ooneex/http-header
2
+
3
+ A comprehensive TypeScript/JavaScript library for working with HTTP headers. This package provides powerful classes and utilities to easily manipulate, read, and manage HTTP headers with type safety and convenient methods for common operations.
4
+
5
+ ![Browser](https://img.shields.io/badge/Browser-Compatible-green?style=flat-square&logo=googlechrome)
6
+ ![Bun](https://img.shields.io/badge/Bun-Compatible-orange?style=flat-square&logo=bun)
7
+ ![Deno](https://img.shields.io/badge/Deno-Compatible-blue?style=flat-square&logo=deno)
8
+ ![Node.js](https://img.shields.io/badge/Node.js-Compatible-green?style=flat-square&logo=node.js)
9
+ ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)
10
+ ![MIT License](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)
11
+
12
+ ## Features
13
+
14
+ ✅ **Complete Header Management** - Full support for reading and writing HTTP headers
15
+
16
+ ✅ **Type-Safe** - Full TypeScript support with proper type definitions
17
+
18
+ ✅ **User Agent Parsing** - Built-in user agent detection and parsing with device information
19
+
20
+ ✅ **Content Type Handling** - Easy MIME type and charset management
21
+
22
+ ✅ **Authentication Support** - Built-in methods for Basic Auth, Bearer tokens
23
+
24
+ ✅ **Cookie Management** - Comprehensive cookie parsing and setting with all options
25
+
26
+ ✅ **CORS Support** - Easy Cross-Origin Resource Sharing header management
27
+
28
+ ✅ **Security Headers** - Built-in support for common security headers (CSP, HSTS, XSS)
29
+
30
+ ✅ **Caching Headers** - Cache control and ETags management
31
+
32
+ ✅ **Client IP Detection** - Multiple methods to detect client IP addresses
33
+
34
+ ✅ **Method Chaining** - Fluent API for easy header manipulation
35
+
36
+ ✅ **Cross-Platform** - Works in Browser, Node.js, Bun, and Deno
37
+
38
+ ✅ **Zero Config** - Works out of the box with sensible defaults
39
+
40
+ ## Installation
41
+
42
+ ### Bun
43
+ ```bash
44
+ bun add @ooneex/http-header
45
+ ```
46
+
47
+ ### pnpm
48
+ ```bash
49
+ pnpm add @ooneex/http-header
50
+ ```
51
+
52
+ ### Yarn
53
+ ```bash
54
+ yarn add @ooneex/http-header
55
+ ```
56
+
57
+ ### npm
58
+ ```bash
59
+ npm install @ooneex/http-header
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ ### Basic Header Operations
65
+
66
+ ```typescript
67
+ import { Header } from '@ooneex/http-header';
68
+
69
+ const header = new Header();
70
+
71
+ // Adding headers
72
+ header.add('Content-Type', 'application/json')
73
+ .add('Accept', 'application/json')
74
+ .set('Authorization', 'Bearer token123');
75
+
76
+ // Reading headers
77
+ const contentType = header.get('Content-Type'); // "application/json"
78
+ const hasAuth = header.has('Authorization'); // true
79
+
80
+ // Converting to JSON
81
+ const headerObj = header.toJson();
82
+ console.log(headerObj); // { "Content-Type": "application/json", ... }
83
+ ```
84
+
85
+ ### Content Type Management
86
+
87
+ ```typescript
88
+ import { Header } from '@ooneex/http-header';
89
+
90
+ const header = new Header();
91
+
92
+ // Setting content types with optional charset
93
+ header.contentType('application/json', 'UTF-8');
94
+
95
+ // Convenience methods
96
+ header.setJson('UTF-8') // application/json; charset=UTF-8
97
+ .setHtml('UTF-8') // text/html; charset=UTF-8
98
+ .setText('UTF-8') // text/plain; charset=UTF-8
99
+ .setForm('UTF-8') // application/x-www-form-urlencoded; charset=UTF-8
100
+ .setFormData() // multipart/form-data
101
+ .setBlobType(); // application/octet-stream
102
+
103
+ // Content negotiation
104
+ header.setAccept('application/json')
105
+ .setLang('en-US')
106
+ .setAcceptEncoding(['gzip', 'br', 'deflate']);
107
+ ```
108
+
109
+ ### Authentication Headers
110
+
111
+ ```typescript
112
+ import { Header } from '@ooneex/http-header';
113
+
114
+ const header = new Header();
115
+
116
+ // Basic authentication
117
+ header.setBasicAuth('dXNlcjpwYXNz'); // Sets "Authorization: Basic dXNlcjpwYXNz"
118
+
119
+ // Bearer token
120
+ header.setBearerToken('your-jwt-token'); // Sets "Authorization: Bearer your-jwt-token"
121
+
122
+ // Custom authorization
123
+ header.setAuthorization('Custom token123');
124
+
125
+ // Reading authentication (using ReadonlyHeader)
126
+ console.log(header.getBasicAuth()); // Returns token or null
127
+ console.log(header.getBearerToken()); // Returns token or null
128
+ console.log(header.getAuthorization()); // Returns full header or null
129
+ ```
130
+
131
+ ### Cookie Management
132
+
133
+ ```typescript
134
+ import { Header, ReadonlyHeader } from '@ooneex/http-header';
135
+
136
+ const header = new Header();
137
+
138
+ // Setting cookies with options
139
+ header.setCookie('sessionId', 'abc123', {
140
+ httpOnly: true,
141
+ secure: true,
142
+ maxAge: 3600,
143
+ path: '/',
144
+ domain: '.example.com',
145
+ sameSite: 'Strict'
146
+ });
147
+
148
+ // Setting multiple cookies
149
+ header.setCookies([
150
+ { name: 'user', value: 'john', options: { maxAge: 86400 } },
151
+ { name: 'theme', value: 'dark', options: { path: '/app' } }
152
+ ]);
153
+
154
+ // Reading cookies (from request headers)
155
+ const readonlyHeader = new ReadonlyHeader(requestHeaders);
156
+ const cookies = readonlyHeader.getCookies(); // { sessionId: 'abc123', user: 'john' }
157
+ const userCookie = readonlyHeader.getCookie('user'); // 'john'
158
+
159
+ // Removing cookies
160
+ header.removeCookie('sessionId', { path: '/', domain: '.example.com' });
161
+ ```
162
+
163
+ ### CORS Headers
164
+
165
+ ```typescript
166
+ import { Header } from '@ooneex/http-header';
167
+
168
+ const header = new Header();
169
+
170
+ // CORS configuration
171
+ header.setAccessControlAllowOrigin('*')
172
+ .setAccessControlAllowMethods(['GET', 'POST', 'PUT', 'DELETE'])
173
+ .setAccessControlAllowHeaders(['Content-Type', 'Authorization'])
174
+ .setAccessControlAllowCredentials(true);
175
+
176
+ // Reading CORS settings
177
+ console.log(header.getAccessControlAllowOrigin()); // '*'
178
+ console.log(header.getAccessControlAllowMethods()); // ['GET', 'POST', 'PUT', 'DELETE']
179
+ ```
180
+
181
+ ### Security Headers
182
+
183
+ ```typescript
184
+ import { Header } from '@ooneex/http-header';
185
+
186
+ const header = new Header();
187
+
188
+ // Security headers setup
189
+ header.setContentSecurityPolicy("default-src 'self'; script-src 'unsafe-inline'")
190
+ .setStrictTransportSecurity(31536000, true, true) // 1 year, includeSubDomains, preload
191
+ .setXContentTypeOptions('nosniff')
192
+ .setXFrameOptions('DENY')
193
+ .setXXSSProtection(true, 'block');
194
+
195
+ // Reading security headers
196
+ console.log(header.getContentSecurityPolicy());
197
+ console.log(header.getStrictTransportSecurity());
198
+ ```
199
+
200
+ ### Caching Headers
201
+
202
+ ```typescript
203
+ import { Header } from '@ooneex/http-header';
204
+
205
+ const header = new Header();
206
+
207
+ // Cache control
208
+ header.setCacheControl('public, max-age=3600')
209
+ .setEtag('"abc123"')
210
+ .setLastModified(new Date())
211
+ .setIfModifiedSince(new Date(Date.now() - 86400000));
212
+
213
+ // Reading cache headers
214
+ console.log(header.getCacheControl()); // 'public, max-age=3600'
215
+ console.log(header.getEtag()); // '"abc123"'
216
+ console.log(header.getLastModified()); // Date object
217
+ ```
218
+
219
+ ### Request Information
220
+
221
+ ```typescript
222
+ import { Header } from '@ooneex/http-header';
223
+
224
+ const header = new Header();
225
+
226
+ // Request headers
227
+ header.setHost('api.example.com')
228
+ .setUserAgent('MyApp/1.0')
229
+ .setReferer('https://example.com/page')
230
+ .setOrigin('https://example.com');
231
+
232
+ // Reading request info
233
+ console.log(header.getHost()); // 'api.example.com'
234
+ console.log(header.getUserAgent()); // Parsed user agent object
235
+ console.log(header.getReferer()); // 'https://example.com/page'
236
+ ```
237
+
238
+ ### Client IP Detection
239
+
240
+ ```typescript
241
+ import { ReadonlyHeader } from '@ooneex/http-header';
242
+
243
+ const requestHeader = new ReadonlyHeader(incomingHeaders);
244
+
245
+ // Get client IP (tries X-Forwarded-For, then X-Real-IP)
246
+ const clientIp = requestHeader.getIp();
247
+
248
+ // Get all possible IPs
249
+ const allIps = requestHeader.getClientIps();
250
+
251
+ // Specific headers
252
+ const forwardedFor = requestHeader.getXForwardedFor();
253
+ const realIp = requestHeader.getXRealIP();
254
+ ```
255
+
256
+ ### User Agent Parsing
257
+
258
+ ```typescript
259
+ import { ReadonlyHeader } from '@ooneex/http-header';
260
+
261
+ const header = new ReadonlyHeader(requestHeaders);
262
+
263
+ const userAgent = header.getUserAgent();
264
+ if (userAgent) {
265
+ console.log(userAgent.browser.name); // 'Chrome'
266
+ console.log(userAgent.browser.version); // '91.0.4472.124'
267
+ console.log(userAgent.os.name); // 'Windows'
268
+ console.log(userAgent.device.type); // 'mobile'
269
+ }
270
+ ```
271
+
272
+ ### Method Chaining
273
+
274
+ ```typescript
275
+ import { Header } from '@ooneex/http-header';
276
+
277
+ const header = new Header();
278
+
279
+ // Fluent API
280
+ header.setJson()
281
+ .setBearerToken('token')
282
+ .setCookie('session', 'abc123', { httpOnly: true })
283
+ .setAccessControlAllowOrigin('*')
284
+ .setCacheControl('no-cache');
285
+ ```
286
+
287
+ ### Working with Native Headers
288
+
289
+ ```typescript
290
+ import { Header, ReadonlyHeader } from '@ooneex/http-header';
291
+
292
+ // From native Headers object
293
+ const nativeHeaders = new Headers();
294
+ nativeHeaders.set('Content-Type', 'application/json');
295
+
296
+ const header = new Header(nativeHeaders);
297
+
298
+ // Access native Headers instance
299
+ const native = header.native;
300
+
301
+ // Convert to plain object
302
+ const headerObject = header.toJson();
303
+
304
+ // Create readonly instance
305
+ const readonlyHeader = new ReadonlyHeader(nativeHeaders);
306
+ ```
307
+
308
+ ### Request Type Detection
309
+
310
+ ```typescript
311
+ import { ReadonlyHeader } from '@ooneex/http-header';
312
+
313
+ const requestHeader = new ReadonlyHeader(incomingHeaders);
314
+
315
+ // Check request characteristics
316
+ const isSecure = requestHeader.isSecure(); // HTTPS check via X-Forwarded-Proto
317
+ const isAjax = requestHeader.isAjax(); // XMLHttpRequest check
318
+ const isCors = requestHeader.isCorsRequest(); // Has Origin header
319
+ ```
320
+
321
+ ## API Reference
322
+
323
+ ### `Header` Class
324
+
325
+ The main class for creating and manipulating HTTP headers with full read/write capabilities.
326
+
327
+ #### Constructor
328
+
329
+ **`new Header(headers?: Headers)`**
330
+
331
+ Creates a new Header instance, optionally from existing Headers object.
332
+
333
+ **Parameters:**
334
+ - `headers` - Optional existing Headers object
335
+
336
+ **Example:**
337
+ ```typescript
338
+ const header = new Header();
339
+ const headerFromExisting = new Header(existingHeaders);
340
+ ```
341
+
342
+ #### Core Methods
343
+
344
+ **`add(name: HeaderFieldType, value: string): Header`**
345
+
346
+ Append header value (multiple values allowed).
347
+
348
+ **Example:**
349
+ ```typescript
350
+ header.add('Accept', 'application/json')
351
+ .add('Accept', 'text/html'); // Results in: "application/json, text/html"
352
+ ```
353
+
354
+ **`set(name: HeaderFieldType, value: string): Header`**
355
+
356
+ Set header value (overwrites existing).
357
+
358
+ **Example:**
359
+ ```typescript
360
+ header.set('Content-Type', 'application/json');
361
+ ```
362
+
363
+ **`remove(name: HeaderFieldType): Header`**
364
+
365
+ Remove header completely.
366
+
367
+ **Example:**
368
+ ```typescript
369
+ header.remove('Authorization');
370
+ ```
371
+
372
+ **`get(name: HeaderFieldType): string | null`**
373
+
374
+ Get header value.
375
+
376
+ **Example:**
377
+ ```typescript
378
+ const contentType = header.get('Content-Type'); // 'application/json' or null
379
+ ```
380
+
381
+ **`has(name: HeaderFieldType): boolean`**
382
+
383
+ Check if header exists.
384
+
385
+ **Example:**
386
+ ```typescript
387
+ const hasAuth = header.has('Authorization'); // true or false
388
+ ```
389
+
390
+ #### Content Type Methods
391
+
392
+ **`contentType(type: MimeType, charset?: CharsetType): Header`**
393
+
394
+ Set content type with optional charset.
395
+
396
+ **Example:**
397
+ ```typescript
398
+ header.contentType('application/json', 'UTF-8');
399
+ ```
400
+
401
+ **`contentLength(length: number): Header`**
402
+
403
+ Set content length.
404
+
405
+ **Example:**
406
+ ```typescript
407
+ header.contentLength(1024);
408
+ ```
409
+
410
+ **`contentDisposition(value: string): Header`**
411
+
412
+ Set content disposition.
413
+
414
+ **Example:**
415
+ ```typescript
416
+ header.contentDisposition('attachment; filename="file.pdf"');
417
+ ```
418
+
419
+ #### Content Type Convenience Methods
420
+
421
+ **`setJson(charset?: CharsetType): Header`**
422
+
423
+ Set JSON content type.
424
+
425
+ **Example:**
426
+ ```typescript
427
+ header.setJson('UTF-8'); // Sets "application/json; charset=UTF-8"
428
+ ```
429
+
430
+ **`setHtml(charset?: CharsetType): Header`**
431
+
432
+ Set HTML content type.
433
+
434
+ **Example:**
435
+ ```typescript
436
+ header.setHtml('UTF-8'); // Sets "text/html; charset=UTF-8"
437
+ ```
438
+
439
+ **`setText(charset?: CharsetType): Header`**
440
+
441
+ Set plain text content type.
442
+
443
+ **Example:**
444
+ ```typescript
445
+ header.setText('UTF-8'); // Sets "text/plain; charset=UTF-8"
446
+ ```
447
+
448
+ **`setForm(charset?: CharsetType): Header`**
449
+
450
+ Set form URL encoded content type.
451
+
452
+ **Example:**
453
+ ```typescript
454
+ header.setForm(); // Sets "application/x-www-form-urlencoded"
455
+ ```
456
+
457
+ **`setFormData(charset?: CharsetType): Header`**
458
+
459
+ Set multipart form data content type.
460
+
461
+ **Example:**
462
+ ```typescript
463
+ header.setFormData(); // Sets "multipart/form-data"
464
+ ```
465
+
466
+ **`setBlobType(charset?: CharsetType): Header`**
467
+
468
+ Set binary content type.
469
+
470
+ **Example:**
471
+ ```typescript
472
+ header.setBlobType(); // Sets "application/octet-stream"
473
+ ```
474
+
475
+ #### Authentication Methods
476
+
477
+ **`setAuthorization(value: string): Header`**
478
+
479
+ Set authorization header.
480
+
481
+ **Example:**
482
+ ```typescript
483
+ header.setAuthorization('Bearer token123');
484
+ ```
485
+
486
+ **`setBasicAuth(token: string): Header`**
487
+
488
+ Set basic authentication.
489
+
490
+ **Example:**
491
+ ```typescript
492
+ header.setBasicAuth('dXNlcjpwYXNzd29yZA==');
493
+ ```
494
+
495
+ **`setBearerToken(token: string): Header`**
496
+
497
+ Set bearer token authentication.
498
+
499
+ **Example:**
500
+ ```typescript
501
+ header.setBearerToken('your-jwt-token');
502
+ ```
503
+
504
+ #### Cookie Methods
505
+
506
+ **`setCookie(name: string, value: string, options?: CookieOptions): Header`**
507
+
508
+ Set single cookie with options.
509
+
510
+ **Example:**
511
+ ```typescript
512
+ header.setCookie('session', 'abc123', {
513
+ httpOnly: true,
514
+ secure: true,
515
+ maxAge: 3600
516
+ });
517
+ ```
518
+
519
+ **`setCookies(cookies: Array<{name: string, value: string, options?: CookieOptions}>): Header`**
520
+
521
+ Set multiple cookies.
522
+
523
+ **Example:**
524
+ ```typescript
525
+ header.setCookies([
526
+ { name: 'user', value: 'john', options: { maxAge: 86400 } },
527
+ { name: 'theme', value: 'dark' }
528
+ ]);
529
+ ```
530
+
531
+ **`removeCookie(name: string, options?: {domain?: string, path?: string}): Header`**
532
+
533
+ Remove cookie by setting expiry in the past.
534
+
535
+ **Example:**
536
+ ```typescript
537
+ header.removeCookie('session', { path: '/', domain: '.example.com' });
538
+ ```
539
+
540
+ #### CORS Methods
541
+
542
+ **`setAccessControlAllowOrigin(origin: string): Header`**
543
+
544
+ Set allowed origins for CORS.
545
+
546
+ **Example:**
547
+ ```typescript
548
+ header.setAccessControlAllowOrigin('*');
549
+ header.setAccessControlAllowOrigin('https://example.com');
550
+ ```
551
+
552
+ **`setAccessControlAllowMethods(methods: MethodType[]): Header`**
553
+
554
+ Set allowed HTTP methods for CORS.
555
+
556
+ **Example:**
557
+ ```typescript
558
+ header.setAccessControlAllowMethods(['GET', 'POST', 'PUT', 'DELETE']);
559
+ ```
560
+
561
+ **`setAccessControlAllowHeaders(headers: string[]): Header`**
562
+
563
+ Set allowed headers for CORS.
564
+
565
+ **Example:**
566
+ ```typescript
567
+ header.setAccessControlAllowHeaders(['Content-Type', 'Authorization']);
568
+ ```
569
+
570
+ **`setAccessControlAllowCredentials(allow: boolean): Header`**
571
+
572
+ Set credentials policy for CORS.
573
+
574
+ **Example:**
575
+ ```typescript
576
+ header.setAccessControlAllowCredentials(true);
577
+ ```
578
+
579
+ #### Security Methods
580
+
581
+ **`setContentSecurityPolicy(policy: string): Header`**
582
+
583
+ Set Content Security Policy.
584
+
585
+ **Example:**
586
+ ```typescript
587
+ header.setContentSecurityPolicy("default-src 'self'; script-src 'unsafe-inline'");
588
+ ```
589
+
590
+ **`setStrictTransportSecurity(maxAge: number, includeSubDomains?: boolean, preload?: boolean): Header`**
591
+
592
+ Set HTTP Strict Transport Security.
593
+
594
+ **Example:**
595
+ ```typescript
596
+ header.setStrictTransportSecurity(31536000, true, true); // 1 year, include subdomains, preload
597
+ ```
598
+
599
+ **`setXContentTypeOptions(value?: string): Header`**
600
+
601
+ Set X-Content-Type-Options header.
602
+
603
+ **Example:**
604
+ ```typescript
605
+ header.setXContentTypeOptions('nosniff');
606
+ ```
607
+
608
+ **`setXFrameOptions(value: "DENY" | "SAMEORIGIN" | string): Header`**
609
+
610
+ Set X-Frame-Options header.
611
+
612
+ **Example:**
613
+ ```typescript
614
+ header.setXFrameOptions('DENY');
615
+ ```
616
+
617
+ **`setXXSSProtection(enabled?: boolean, mode?: string): Header`**
618
+
619
+ Set XSS protection header.
620
+
621
+ **Example:**
622
+ ```typescript
623
+ header.setXXSSProtection(true, 'block');
624
+ ```
625
+
626
+ #### Caching Methods
627
+
628
+ **`setCacheControl(value: string): Header`**
629
+
630
+ Set cache control header.
631
+
632
+ **Example:**
633
+ ```typescript
634
+ header.setCacheControl('public, max-age=3600');
635
+ ```
636
+
637
+ **`setEtag(value: string): Header`**
638
+
639
+ Set entity tag for caching.
640
+
641
+ **Example:**
642
+ ```typescript
643
+ header.setEtag('"abc123"');
644
+ ```
645
+
646
+ **`setLastModified(date: Date): Header`**
647
+
648
+ Set last modified date.
649
+
650
+ **Example:**
651
+ ```typescript
652
+ header.setLastModified(new Date());
653
+ ```
654
+
655
+ **`setIfModifiedSince(date: Date): Header`**
656
+
657
+ Set conditional request date.
658
+
659
+ **Example:**
660
+ ```typescript
661
+ header.setIfModifiedSince(new Date(Date.now() - 86400000));
662
+ ```
663
+
664
+ #### Request Methods
665
+
666
+ **`setHost(host: string): Header`**
667
+
668
+ Set host header.
669
+
670
+ **Example:**
671
+ ```typescript
672
+ header.setHost('api.example.com');
673
+ ```
674
+
675
+ **`setUserAgent(userAgent: string): Header`**
676
+
677
+ Set user agent string.
678
+
679
+ **Example:**
680
+ ```typescript
681
+ header.setUserAgent('MyApp/1.0 (Windows NT 10.0)');
682
+ ```
683
+
684
+ **`setReferer(referer: string): Header`**
685
+
686
+ Set referer header.
687
+
688
+ **Example:**
689
+ ```typescript
690
+ header.setReferer('https://example.com/page');
691
+ ```
692
+
693
+ **`setOrigin(origin: string): Header`**
694
+
695
+ Set origin header.
696
+
697
+ **Example:**
698
+ ```typescript
699
+ header.setOrigin('https://example.com');
700
+ ```
701
+
702
+ #### Utility Methods
703
+
704
+ **`setLocation(location: string): Header`**
705
+
706
+ Set location header for redirects.
707
+
708
+ **Example:**
709
+ ```typescript
710
+ header.setLocation('https://example.com/new-page');
711
+ ```
712
+
713
+ **`setCustom(value: string): Header`**
714
+
715
+ Set custom X-Custom header.
716
+
717
+ **Example:**
718
+ ```typescript
719
+ header.setCustom('MyApp Response');
720
+ ```
721
+
722
+ **`toJson(): Record<string, string>`**
723
+
724
+ Convert headers to plain object.
725
+
726
+ **Example:**
727
+ ```typescript
728
+ const headerObj = header.toJson();
729
+ console.log(headerObj); // { "Content-Type": "application/json", ... }
730
+ ```
731
+
732
+ ### `ReadonlyHeader` Class
733
+
734
+ Read-only interface for safely accessing header information without modification capabilities.
735
+
736
+ #### Getter Methods
737
+
738
+ **`get(name: HeaderFieldType): string | null`**
739
+
740
+ Get header value.
741
+
742
+ **Example:**
743
+ ```typescript
744
+ const contentType = readonlyHeader.get('Content-Type');
745
+ ```
746
+
747
+ **`has(name: HeaderFieldType): boolean`**
748
+
749
+ Check header existence.
750
+
751
+ **Example:**
752
+ ```typescript
753
+ const hasAuth = readonlyHeader.has('Authorization');
754
+ ```
755
+
756
+ **`toJson(): Record<string, string>`**
757
+
758
+ Convert to object.
759
+
760
+ **Example:**
761
+ ```typescript
762
+ const headers = readonlyHeader.toJson();
763
+ ```
764
+
765
+ #### Content Methods
766
+
767
+ **`getContentType(): MimeType | "*/*" | null`**
768
+
769
+ Get content type.
770
+
771
+ **Example:**
772
+ ```typescript
773
+ const contentType = readonlyHeader.getContentType(); // 'application/json'
774
+ ```
775
+
776
+ **`getContentLength(): number`**
777
+
778
+ Get content length (0 if not set).
779
+
780
+ **Example:**
781
+ ```typescript
782
+ const length = readonlyHeader.getContentLength(); // 1024
783
+ ```
784
+
785
+ **`getCharset(): CharsetType | null`**
786
+
787
+ Extract charset from content type.
788
+
789
+ **Example:**
790
+ ```typescript
791
+ const charset = readonlyHeader.getCharset(); // 'UTF-8'
792
+ ```
793
+
794
+ **`getContentDisposition(): string | null`**
795
+
796
+ Get content disposition.
797
+
798
+ **Example:**
799
+ ```typescript
800
+ const disposition = readonlyHeader.getContentDisposition();
801
+ ```
802
+
803
+ **`getAccept(): MimeType | "*/*" | null`**
804
+
805
+ Get accept header.
806
+
807
+ **Example:**
808
+ ```typescript
809
+ const accept = readonlyHeader.getAccept(); // 'application/json'
810
+ ```
811
+
812
+ **`getLang(): {code: string, region?: string} | null`**
813
+
814
+ Parse accept-language header.
815
+
816
+ **Example:**
817
+ ```typescript
818
+ const lang = readonlyHeader.getLang(); // { code: 'en', region: 'US' }
819
+ ```
820
+
821
+ **`getAcceptEncoding(): EncodingType[] | null`**
822
+
823
+ Get accepted encodings.
824
+
825
+ **Example:**
826
+ ```typescript
827
+ const encodings = readonlyHeader.getAcceptEncoding(); // ['gzip', 'br']
828
+ ```
829
+
830
+ #### Authentication Methods
831
+
832
+ **`getAuthorization(): string | null`**
833
+
834
+ Get authorization header.
835
+
836
+ **Example:**
837
+ ```typescript
838
+ const auth = readonlyHeader.getAuthorization(); // 'Bearer token123'
839
+ ```
840
+
841
+ **`getBasicAuth(): string | null`**
842
+
843
+ Extract basic auth token.
844
+
845
+ **Example:**
846
+ ```typescript
847
+ const token = readonlyHeader.getBasicAuth(); // 'dXNlcjpwYXNz'
848
+ ```
849
+
850
+ **`getBearerToken(): string | null`**
851
+
852
+ Extract bearer token.
853
+
854
+ **Example:**
855
+ ```typescript
856
+ const token = readonlyHeader.getBearerToken(); // 'your-jwt-token'
857
+ ```
858
+
859
+ #### Cookie Methods
860
+
861
+ **`getCookies(): Record<string, string> | null`**
862
+
863
+ Parse all cookies.
864
+
865
+ **Example:**
866
+ ```typescript
867
+ const cookies = readonlyHeader.getCookies(); // { session: 'abc123', user: 'john' }
868
+ ```
869
+
870
+ **`getCookie(name: string): string | null`**
871
+
872
+ Get specific cookie value.
873
+
874
+ **Example:**
875
+ ```typescript
876
+ const sessionId = readonlyHeader.getCookie('session'); // 'abc123'
877
+ ```
878
+
879
+ #### Request Info Methods
880
+
881
+ **`getHost(): string | null`**
882
+
883
+ Get host header.
884
+
885
+ **Example:**
886
+ ```typescript
887
+ const host = readonlyHeader.getHost(); // 'api.example.com'
888
+ ```
889
+
890
+ **`getUserAgent(): IUserAgent | null`**
891
+
892
+ Parse user agent string.
893
+
894
+ **Example:**
895
+ ```typescript
896
+ const ua = readonlyHeader.getUserAgent();
897
+ console.log(ua?.browser.name); // 'Chrome'
898
+ ```
899
+
900
+ **`getReferer(): string | null`**
901
+
902
+ Get referer header.
903
+
904
+ **Example:**
905
+ ```typescript
906
+ const referer = readonlyHeader.getReferer(); // 'https://example.com'
907
+ ```
908
+
909
+ **`getOrigin(): string | null`**
910
+
911
+ Get origin header.
912
+
913
+ **Example:**
914
+ ```typescript
915
+ const origin = readonlyHeader.getOrigin(); // 'https://example.com'
916
+ ```
917
+
918
+ #### IP Detection Methods
919
+
920
+ **`getIp(): string | null`**
921
+
922
+ Get client IP using smart detection.
923
+
924
+ **Example:**
925
+ ```typescript
926
+ const ip = readonlyHeader.getIp(); // '192.168.1.100'
927
+ ```
928
+
929
+ **`getXForwardedFor(): string | null`**
930
+
931
+ Get X-Forwarded-For header.
932
+
933
+ **Example:**
934
+ ```typescript
935
+ const forwarded = readonlyHeader.getXForwardedFor(); // '192.168.1.100, 10.0.0.1'
936
+ ```
937
+
938
+ **`getXRealIP(): string | null`**
939
+
940
+ Get X-Real-IP header.
941
+
942
+ **Example:**
943
+ ```typescript
944
+ const realIp = readonlyHeader.getXRealIP(); // '192.168.1.100'
945
+ ```
946
+
947
+ **`getClientIps(): string[]`**
948
+
949
+ Get all possible client IPs.
950
+
951
+ **Example:**
952
+ ```typescript
953
+ const ips = readonlyHeader.getClientIps(); // ['192.168.1.100', '10.0.0.1']
954
+ ```
955
+
956
+ #### CORS Methods
957
+
958
+ **`getAccessControlAllowOrigin(): string | null`**
959
+
960
+ Get allowed origins.
961
+
962
+ **Example:**
963
+ ```typescript
964
+ const origin = readonlyHeader.getAccessControlAllowOrigin(); // '*'
965
+ ```
966
+
967
+ **`getAccessControlAllowMethods(): MethodType[] | null`**
968
+
969
+ Get allowed methods.
970
+
971
+ **Example:**
972
+ ```typescript
973
+ const methods = readonlyHeader.getAccessControlAllowMethods(); // ['GET', 'POST']
974
+ ```
975
+
976
+ **`getAccessControlAllowHeaders(): string[] | null`**
977
+
978
+ Get allowed headers.
979
+
980
+ **Example:**
981
+ ```typescript
982
+ const headers = readonlyHeader.getAccessControlAllowHeaders(); // ['Content-Type']
983
+ ```
984
+
985
+ **`getAccessControlAllowCredentials(): boolean | null`**
986
+
987
+ Get credentials policy.
988
+
989
+ **Example:**
990
+ ```typescript
991
+ const credentials = readonlyHeader.getAccessControlAllowCredentials(); // true
992
+ ```
993
+
994
+ #### Security Methods
995
+
996
+ **`getContentSecurityPolicy(): string | null`**
997
+
998
+ Get CSP policy.
999
+
1000
+ **Example:**
1001
+ ```typescript
1002
+ const csp = readonlyHeader.getContentSecurityPolicy();
1003
+ ```
1004
+
1005
+ **`getStrictTransportSecurity(): string | null`**
1006
+
1007
+ Get HSTS header.
1008
+
1009
+ **Example:**
1010
+ ```typescript
1011
+ const hsts = readonlyHeader.getStrictTransportSecurity();
1012
+ ```
1013
+
1014
+ **`getXContentTypeOptions(): string | null`**
1015
+
1016
+ Get X-Content-Type-Options.
1017
+
1018
+ **Example:**
1019
+ ```typescript
1020
+ const options = readonlyHeader.getXContentTypeOptions(); // 'nosniff'
1021
+ ```
1022
+
1023
+ **`getXFrameOptions(): string | null`**
1024
+
1025
+ Get X-Frame-Options.
1026
+
1027
+ **Example:**
1028
+ ```typescript
1029
+ const frameOptions = readonlyHeader.getXFrameOptions(); // 'DENY'
1030
+ ```
1031
+
1032
+ **`getXXSSProtection(): string | null`**
1033
+
1034
+ Get XSS protection header.
1035
+
1036
+ **Example:**
1037
+ ```typescript
1038
+ const xssProtection = readonlyHeader.getXXSSProtection(); // '1; mode=block'
1039
+ ```
1040
+
1041
+ #### Caching Methods
1042
+
1043
+ **`getCacheControl(): string | null`**
1044
+
1045
+ Get cache control.
1046
+
1047
+ **Example:**
1048
+ ```typescript
1049
+ const cacheControl = readonlyHeader.getCacheControl(); // 'public, max-age=3600'
1050
+ ```
1051
+
1052
+ **`getEtag(): string | null`**
1053
+
1054
+ Get entity tag.
1055
+
1056
+ **Example:**
1057
+ ```typescript
1058
+ const etag = readonlyHeader.getEtag(); // '"abc123"'
1059
+ ```
1060
+
1061
+ **`getLastModified(): Date | null`**
1062
+
1063
+ Get last modified date.
1064
+
1065
+ **Example:**
1066
+ ```typescript
1067
+ const lastModified = readonlyHeader.getLastModified(); // Date object
1068
+ ```
1069
+
1070
+ **`getIfModifiedSince(): Date | null`**
1071
+
1072
+ Get conditional date.
1073
+
1074
+ **Example:**
1075
+ ```typescript
1076
+ const ifModifiedSince = readonlyHeader.getIfModifiedSince(); // Date object
1077
+ ```
1078
+
1079
+ **`getIfNoneMatch(): string | null`**
1080
+
1081
+ Get if-none-match header.
1082
+
1083
+ **Example:**
1084
+ ```typescript
1085
+ const ifNoneMatch = readonlyHeader.getIfNoneMatch(); // '"abc123"'
1086
+ ```
1087
+
1088
+ #### Detection Methods
1089
+
1090
+ **`isSecure(): boolean`**
1091
+
1092
+ Check if HTTPS (via X-Forwarded-Proto).
1093
+
1094
+ **Example:**
1095
+ ```typescript
1096
+ const isHttps = readonlyHeader.isSecure(); // true
1097
+ ```
1098
+
1099
+ **`isAjax(): boolean`**
1100
+
1101
+ Check if XMLHttpRequest.
1102
+
1103
+ **Example:**
1104
+ ```typescript
1105
+ const isAjax = readonlyHeader.isAjax(); // true
1106
+ ```
1107
+
1108
+ **`isCorsRequest(): boolean`**
1109
+
1110
+ Check if CORS request (has Origin).
1111
+
1112
+ **Example:**
1113
+ ```typescript
1114
+ const isCors = readonlyHeader.isCorsRequest(); // true
1115
+ ```
1116
+
1117
+ ### Type Definitions
1118
+
1119
+ #### `CookieOptions`
1120
+
1121
+ Interface for cookie configuration options.
1122
+
1123
+ ```typescript
1124
+ interface CookieOptions {
1125
+ domain?: string;
1126
+ path?: string;
1127
+ expires?: Date;
1128
+ maxAge?: number;
1129
+ secure?: boolean;
1130
+ httpOnly?: boolean;
1131
+ sameSite?: "Strict" | "Lax" | "None";
1132
+ }
1133
+ ```
1134
+
1135
+ **Example:**
1136
+ ```typescript
1137
+ const options: CookieOptions = {
1138
+ httpOnly: true,
1139
+ secure: true,
1140
+ maxAge: 3600,
1141
+ sameSite: 'Strict'
1142
+ };
1143
+ ```
1144
+
1145
+ #### `IUserAgent`
1146
+
1147
+ Interface representing parsed user agent information.
1148
+
1149
+ ```typescript
1150
+ interface IUserAgent {
1151
+ readonly browser: {
1152
+ name?: string;
1153
+ version?: string;
1154
+ major?: string;
1155
+ };
1156
+ readonly engine: {
1157
+ name?: string;
1158
+ version?: string;
1159
+ };
1160
+ readonly os: {
1161
+ name?: string;
1162
+ version?: string;
1163
+ };
1164
+ readonly device: {
1165
+ vendor?: string;
1166
+ model?: string;
1167
+ type?: string;
1168
+ };
1169
+ readonly cpu: {
1170
+ architecture?: string;
1171
+ };
1172
+ }
1173
+ ```
1174
+
1175
+ **Example:**
1176
+ ```typescript
1177
+ const userAgent: IUserAgent = {
1178
+ browser: { name: 'Chrome', version: '91.0.4472.124' },
1179
+ os: { name: 'Windows', version: '10' },
1180
+ device: { type: 'desktop' },
1181
+ // ... other properties
1182
+ };
1183
+ ```
1184
+
1185
+ #### Other Types
1186
+
1187
+ **`HeaderFieldType`**
1188
+
1189
+ Union type of standard header names plus custom headers.
1190
+
1191
+ **Example:**
1192
+ ```typescript
1193
+ const headerName: HeaderFieldType = 'Content-Type';
1194
+ const customHeader: HeaderFieldType = 'X-Custom-Header';
1195
+ ```
1196
+
1197
+ **`MethodType`**
1198
+
1199
+ HTTP methods type.
1200
+
1201
+ **Example:**
1202
+ ```typescript
1203
+ const method: MethodType = 'GET'; // 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD'
1204
+ ```
1205
+
1206
+ **`EncodingType`**
1207
+
1208
+ Content encoding types.
1209
+
1210
+ **Example:**
1211
+ ```typescript
1212
+ const encoding: EncodingType = 'gzip'; // 'deflate' | 'gzip' | 'compress' | 'br' | 'identity' | '*'
1213
+ ```
1214
+
1215
+ **`CharsetType`**
1216
+
1217
+ Character set types.
1218
+
1219
+ **Example:**
1220
+ ```typescript
1221
+ const charset: CharsetType = 'UTF-8'; // 'ISO-8859-1' | '7-BIT' | 'UTF-8' | 'UTF-16' | 'US-ASCII'
1222
+ ```
1223
+
1224
+ ## Integration Examples
1225
+
1226
+ ### Express.js Integration
1227
+
1228
+ ```typescript
1229
+ import express from 'express';
1230
+ import { Header, ReadonlyHeader } from '@ooneex/http-header';
1231
+
1232
+ const app = express();
1233
+
1234
+ app.use((req, res, next) => {
1235
+ // Parse incoming headers
1236
+ const incomingHeader = new ReadonlyHeader(new Headers(req.headers as any));
1237
+
1238
+ // Create response headers
1239
+ const responseHeader = new Header()
1240
+ .setJson()
1241
+ .setCacheControl('no-cache')
1242
+ .setAccessControlAllowOrigin('*');
1243
+
1244
+ // Apply headers to response
1245
+ responseHeader.native.forEach((value, key) => {
1246
+ res.setHeader(key, value);
1247
+ });
1248
+
1249
+ next();
1250
+ });
1251
+
1252
+ app.listen(3000);
1253
+ ```
1254
+
1255
+ ### Fetch API Integration
1256
+
1257
+ ```typescript
1258
+ import { Header, ReadonlyHeader } from '@ooneex/http-header';
1259
+
1260
+ // Create request headers
1261
+ const requestHeader = new Header()
1262
+ .setJson()
1263
+ .setBearerToken('your-token')
1264
+ .setUserAgent('MyApp/1.0');
1265
+
1266
+ const response = await fetch('https://api.example.com/data', {
1267
+ method: 'POST',
1268
+ headers: requestHeader.native,
1269
+ body: JSON.stringify({ data: 'example' })
1270
+ });
1271
+
1272
+ // Parse response headers
1273
+ const responseHeader = new ReadonlyHeader(response.headers);
1274
+ const contentType = responseHeader.getContentType();
1275
+ ```
1276
+
1277
+ ### Bun Server Integration
1278
+
1279
+ ```typescript
1280
+ import { Header, ReadonlyHeader } from '@ooneex/http-header';
1281
+
1282
+ Bun.serve({
1283
+ port: 3000,
1284
+ fetch(request) {
1285
+ // Parse request headers
1286
+ const requestHeader = new ReadonlyHeader(request.headers);
1287
+
1288
+ // Create response headers
1289
+ const responseHeader = new Header()
1290
+ .setJson()
1291
+ .setCookie('session', 'abc123', { httpOnly: true })
1292
+ .setAccessControlAllowOrigin('*');
1293
+
1294
+ return new Response(
1295
+ JSON.stringify({ message: 'Hello World' }),
1296
+ {
1297
+ headers: responseHeader.native
1298
+ }
1299
+ );
1300
+ }
1301
+ });
1302
+ ```
1303
+
1304
+ ## License
1305
+
1306
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
1307
+
1308
+ ## Contributing
1309
+
1310
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
1311
+
1312
+ ### Development Setup
1313
+
1314
+ 1. Clone the repository
1315
+ 2. Install dependencies: `bun install`
1316
+ 3. Run tests: `bun run test`
1317
+ 4. Build the project: `bun run build`
1318
+
1319
+ ### Guidelines
1320
+
1321
+ - Write tests for new features
1322
+ - Follow the existing code style
1323
+ - Update documentation for API changes
1324
+ - Ensure all tests pass before submitting PR
1325
+
1326
+ ---
1327
+
1328
+ Made with ❤️ by the Ooneex team