blib/lib/PAGI/Request/Negotiate.pm

filter: Statementstmt 100% 83 / 83 Branchbran 95.2% 40 / 42 Conditioncond 64.7% 11 / 17 MC/DCmcdc 50.0% 5 / 10 Subroutinesub 100% 9 / 9 Podpod 100% 6 / 6 totaltotal 92.2% 154 / 167 CC 34 SCAR 18.9
CC
34
Cov
94%
parse_accept
11.0
best_match
7.0
quality_for_type
6.1
CRAP 6.6
« blib/lib/PAGI/Utils.pm ↑ Summary blib/lib/PAGI/Middleware/Healthcheck.pm »
1 package PAGI::Request::Negotiate;
2 23 $PAGI::Request::Negotiate::VERSION = '0.002002';
3 23 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 23 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6  
7 =head1 NAME
8  
9 PAGI::Request::Negotiate - Content negotiation utilities for PAGI
10  
11 =head1 SYNOPSIS
12  
13 use PAGI::Request::Negotiate;
14  
15 # Parse Accept header
16 my @types = PAGI::Request::Negotiate->parse_accept(
17 'text/html, application/json;q=0.9, */*;q=0.1'
18 );
19 # Returns: (['text/html', 1], ['application/json', 0.9], ['*/*', 0.1])
20  
21 # Find best match
22 my $best = PAGI::Request::Negotiate->best_match(
23 ['application/json', 'text/html'],
24 'text/html, application/json;q=0.9'
25 );
26 # Returns: 'text/html'
27  
28 # Check if type is acceptable
29 my $accepts = PAGI::Request::Negotiate->accepts_type(
30 'text/html, application/json',
31 'json'
32 );
33  
34 # Get quality value for type
35 my $quality = PAGI::Request::Negotiate->quality_for_type(
36 'application/json;q=0.9',
37 'json'
38 );
39  
40 =head1 DESCRIPTION
41  
42 PAGI::Request::Negotiate provides utilities for HTTP content negotiation,
43 including parsing Accept headers and finding the best matching content type.
44  
45 This module supports quality values, wildcards (*/*, type/*), and common
46 MIME type shortcuts (json, html, xml, etc.).
47  
48 =head1 CLASS METHODS
49  
50 =cut
51  
52 # Common MIME type shortcuts
53 23 my %TYPE_SHORTCUTS = (
54 html => 'text/html',
55 text => 'text/plain',
56 txt => 'text/plain',
57 json => 'application/json',
58 xml => 'application/xml',
59 atom => 'application/atom+xml',
60 rss => 'application/rss+xml',
61 css => 'text/css',
62 js => 'application/javascript',
63 png => 'image/png',
64 jpg => 'image/jpeg',
65 jpeg => 'image/jpeg',
66 gif => 'image/gif',
67 svg => 'image/svg+xml',
68 pdf => 'application/pdf',
69 zip => 'application/zip',
70 form => 'application/x-www-form-urlencoded',
71 );
72  
73 =head2 parse_accept
74  
75 my @types = PAGI::Request::Negotiate->parse_accept($header);
76  
77 Parse an Accept header and return a list of arrayrefs containing
78 C<[media_type, quality]> sorted by preference (quality descending,
79 then specificity descending).
80  
81 If no Accept header is provided, returns a single entry for C<*/*> with
82 quality 1.
83  
84 Quality values are clamped to the range [0, 1].
85  
86 Specificity ordering: exact types > type/* > */*
87  
88 =cut
89  
90 38 ▶sub parse_accept {
Subroutine parse_accept: called CC=11 SCAR=24.0
Pod documented
91 38 my ($class, $header) = @_;
92 # No Accept header means accept everything
93 38 ▶ return (['*/*', 1]) unless defined $header && length $header;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header and length $header 2 36 38
Condition100%3/3
defined $header and length $header
!ll&&!rl&&r
1136
MC/DC100%2/2
defined $header and length $header
defined $header length $header
Truth table100%3/3
A and B
A= defined $headerB= length $header
ABresult
0X0
100
111
94  
95 36 my @types;
96  
97 36 for my $part (split /\s*,\s*/, $header) {
98 # Parse: type/subtype;param=value;q=0.9;ext=value
99 75 my ($type, @params) = split /\s*;\s*/, $part;
100 75 ▶ next unless defined $type && length $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type and length $type 0 75 75
Condition33%1/3
defined $type and length $type
!ll&&!rl&&r
0075
MC/DC0%0/2
defined $type and length $type
defined $type length $type
Truth table33%1/3
A and B
A= defined $typeB= length $type
ABresult
0X0
100
111
101  
102 # Normalize type
103 75 $type = lc($type);
104 75 $type =~ s/^\s+//;
105 75 $type =~ s/\s+$//;
106  
107 # Extract quality value (default 1)
108 75 my $quality = 1;
109 75 for my $param (@params) {
110 28 ▶ if ($param =~ /^q\s*=\s*(-?[0-9.]+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($param =~ /^q\s*=\s*(-?[0-9.]+)$/i) 27 1 28
111 27 $quality = $1 + 0; # Convert to number
112 27 ▶ $quality = 1 if $quality > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $quality > 1 1 26 27
113 27 ▶ $quality = 0 if $quality < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $quality < 0 1 26 27
114 27 last;
115 }
116 }
117  
118 75 push @types, [$type, $quality];
119 }
120  
121 # Sort by quality (highest first), then by specificity
122 @types = sort {
123 # Primary: quality (descending)
124 36 my $cmp = $b->[1] <=> $a->[1];
125 45 ▶ return $cmp if $cmp;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp 30 15 45
126  
127 # Secondary: specificity (more specific first)
128 # */* < type/* < type/subtype
129 15 my $spec_a = _specificity($a->[0]);
130 15 my $spec_b = _specificity($b->[0]);
131 15 return $spec_b <=> $spec_a;
132 } @types;
133  
134 36 return @types;
135 }
136  
137 # Calculate specificity score for sorting
138 # Returns: 0 for */*, 1 for type/*, 2 for type/subtype
139 35 ▶sub _specificity {
Subroutine _specificity: called CC=3 SCAR=11.0
140 35 my ($type) = @_;
141 35 ▶ return 0 if $type eq '*/*';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "*/*" 3 32 35
142 32 ▶ return 1 if $type =~ m{^[^/]+/\*$};
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ m[^[^/]+/\*$] 3 29 32
143 29 return 2;
144 }
145  
146 =head2 best_match
147  
148 my $type = PAGI::Request::Negotiate->best_match(\@supported, $accept_header);
149  
150 Find the best matching content type from C<@supported> based on the
151 Accept header. Returns the best match or undef if none acceptable.
152  
153 C<@supported> can contain full MIME types or shortcuts (html, json, xml, etc.)
154  
155 The returned value is from the C<@supported> array (preserves shortcuts).
156  
157 =cut
158  
159 11 ▶sub best_match {
Subroutine best_match: called CC=7 SCAR=19.5
Pod documented
160 11 my ($class, $supported, $accept_header) = @_;
161 11 ▶ return unless $supported && @$supported;
Branch: 1 branch
BranchTrueFalseTotal
unless $supported and @$supported 1 10 11
Condition66%2/3
$supported and @$supported
!ll&&!rl&&r
0110
MC/DC50%1/2
$supported and @$supported
$supported @$supported
Truth table66%2/3
A and B
A= $supportedB= @$supported
ABresult
0X0
100
111
162  
163 # Parse Accept header
164 10 my @accepted = $class->parse_accept($accept_header);
165  
166 # Normalize supported types (expand shortcuts)
167 10 my @normalized = map { $class->normalize_type($_) } @$supported;
168  
169 # Find best match
170 10 for my $accepted (@accepted) {
171 14 my ($type, $quality) = @$accepted;
172 14 ▶ next if $quality == 0; # Explicitly rejected
Branch: 1 branch
BranchTrueFalseTotal
if $quality == 0 0 14 14
173  
174 14 for my $i (0 .. $#normalized) {
175 19 ▶ if ($class->type_matches($normalized[$i], $type)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class->type_matches($normalized[$i], $type)) 8 11 19
176 # Return original (possibly shortcut) type
177 8 return $supported->[$i];
178 }
179 }
180 }
181  
182 2 return;
183 }
184  
185 =head2 type_matches
186  
187 my $bool = PAGI::Request::Negotiate->type_matches($type, $pattern);
188  
189 Check if a media type matches a pattern. Patterns can include wildcards
190 like C<*/*> or C<text/*>.
191  
192 Both type and pattern are compared case-insensitively.
193  
194 =cut
195  
196 71 ▶sub type_matches {
Subroutine type_matches: called CC=5 SCAR=16.1
Pod documented
197 71 my ($class, $type, $pattern) = @_;
198 71 $type = lc($type);
199 71 $pattern = lc($pattern);
200  
201 # Exact match
202 71 ▶ return 1 if $type eq $pattern;
Branch: 1 branch
BranchTrueFalseTotal
if $type eq $pattern 16 55 71
203  
204 # Wildcard match
205 55 ▶ return 1 if $pattern eq '*/*';
Branch: 1 branch
BranchTrueFalseTotal
if $pattern eq "*/*" 6 49 55
206  
207 # Type wildcard (e.g., text/*)
208 49 ▶ if ($pattern =~ m{^([^/]+)/\*$}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern =~ m[^([^/]+)/\*$]) 6 43 49
209 6 my $major = $1;
210 6 ▶ return 1 if $type =~ m{^\Q$major\E/};
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ m[^\Q$major\E/] 4 2 6
211 }
212  
213 45 return 0;
214 }
215  
216 =head2 normalize_type
217  
218 my $mime = PAGI::Request::Negotiate->normalize_type($type);
219  
220 Convert a type shortcut to its full MIME type. Known shortcuts include:
221  
222 html => text/html
223 json => application/json
224 xml => application/xml
225 atom => application/atom+xml
226 rss => application/rss+xml
227 text => text/plain
228 txt => text/plain
229 css => text/css
230 js => application/javascript
231 png => image/png
232 jpg => image/jpeg
233 jpeg => image/jpeg
234 gif => image/gif
235 svg => image/svg+xml
236 pdf => application/pdf
237 zip => application/zip
238 form => application/x-www-form-urlencoded
239  
240 If the type is already a MIME type (contains '/'), it's returned as-is.
241  
242 Unknown shortcuts are prefixed with 'application/'.
243  
244 =cut
245  
246 54 ▶sub normalize_type {
Subroutine normalize_type: called CC=3 SCAR=11.0
Pod documented
247 54 my ($class, $type) = @_;
248 54 ▶ return $type if $type =~ m{/};
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ m[/] 22 32 54
249 32 ▶ return $TYPE_SHORTCUTS{lc($type)} // "application/$type";
Condition100%2/2
$TYPE_SHORTCUTS{lc $type} // "application/$type"
l!l
311
MC/DC100%1/1
$TYPE_SHORTCUTS{lc $type} // "application/$type"
$TYPE_SHORTCUTS{lc $type}
Truth table100%2/2
A
A= $TYPE_SHORTCUTS{lc $type}
Aresult
11
00
250 }
251  
252 =head2 accepts_type
253  
254 my $bool = PAGI::Request::Negotiate->accepts_type($accept_header, $type);
255  
256 Check if a specific content type is acceptable based on the Accept header.
257  
258 The type can be a full MIME type or a shortcut.
259  
260 Returns false if the type has quality=0 (explicitly rejected).
261  
262 =cut
263  
264 14 ▶sub accepts_type {
Subroutine accepts_type: called CC=5 SCAR=16.1
Pod documented
265 14 my ($class, $accept_header, $type) = @_;
266 14 $type = $class->normalize_type($type);
267  
268 14 my @accepted = $class->parse_accept($accept_header);
269  
270 14 for my $accepted (@accepted) {
271 23 my ($pattern, $quality) = @$accepted;
272 23 ▶ next if $quality == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $quality == 0 1 22 23
273  
274 # Check both directions: type matches pattern OR pattern matches type
275 # This allows accepts('text/*') to return true if client accepts 'text/html'
276 22 ▶ return 1 if $class->type_matches($type, $pattern);
Branch: 1 branch
BranchTrueFalseTotal
if $class->type_matches($type, $pattern) 7 15 22
277 15 ▶ return 1 if $class->type_matches($pattern, $type);
Branch: 1 branch
BranchTrueFalseTotal
if $class->type_matches($pattern, $type) 2 13 15
278 }
279  
280 5 return 0;
281 }
282  
283 =head2 quality_for_type
284  
285 my $q = PAGI::Request::Negotiate->quality_for_type($accept_header, $type);
286  
287 Get the quality value for a specific type. Returns 0 if not acceptable.
288  
289 When multiple patterns match (e.g., both text/* and text/html), returns
290 the quality of the most specific match.
291  
292 The type can be a full MIME type or a shortcut.
293  
294 =cut
295  
296 4 ▶sub quality_for_type {
Subroutine quality_for_type: called CC=6 SCAR=18.0
Pod documented
297 4 my ($class, $accept_header, $type) = @_;
298 4 $type = $class->normalize_type($type);
299  
300 4 my @accepted = $class->parse_accept($accept_header);
301  
302 4 my $best_quality = 0;
303 4 my $best_specificity = -1;
304  
305 4 for my $accepted (@accepted) {
306 9 my ($pattern, $quality) = @$accepted;
307  
308 9 ▶ if ($class->type_matches($type, $pattern)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class->type_matches($type, $pattern)) 5 4 9
309 5 my $spec = _specificity($pattern);
310 5 ▶ if ($spec > $best_specificity ||
Branch: 1 branch
BranchTrueFalseTotal
if ($spec > $best_specificity or $spec == $best_specificity and $quality > $best_quality) 4 1 5
Condition50%3/6
$spec > $best_specificity or $spec == $best_specificity and $quality > $best_quality
l!l&&r!l&&!r
401
$spec == $best_specificity and $quality > $best_quality
!ll&&!rl&&r
100
MC/DC33%1/3
$spec > $best_specificity or $spec == $best_specificity and $quality > $best_quality
$spec > $best_specificity $spec == $best_specificity $quality > $best_quality
Truth table50%2/4
A or B and C
A= $spec > $best_specificityB= $spec == $best_specificityC= $quality > $best_quality
ABCresult
1XX1
0111
00X0
0100
311 ($spec == $best_specificity && $quality > $best_quality)) {
312 4 $best_quality = $quality;
313 4 $best_specificity = $spec;
314 }
315 }
316 }
317  
318 4 return $best_quality;
319 }
320  
321 =head1 EXAMPLES
322  
323 =head2 Content Negotiation in a PAGI App
324  
325 use PAGI::Request;
326 use PAGI::Request::Negotiate;
327  
328 async sub app ($scope, $receive, $send) {
329 # Scope headers are an arrayref of [name, value] pairs, not a hash.
330 # Read them through PAGI::Request, not $scope->{headers}{...}.
331 my $req = PAGI::Request->new($scope, $receive);
332 my $accept = $req->header('accept') // '*/*';
333  
334 my $format = PAGI::Request::Negotiate->best_match(
335 ['json', 'html', 'xml'],
336 $accept
337 );
338  
339 my ($body, $content_type);
340 if ($format eq 'json') {
341 $body = '{"message":"Hello"}';
342 $content_type = 'application/json';
343 } elsif ($format eq 'html') {
344 $body = '<h1>Hello</h1>';
345 $content_type = 'text/html';
346 } else {
347 $body = '<message>Hello</message>';
348 $content_type = 'application/xml';
349 }
350  
351 await $send->({
352 type => 'http.response.start',
353 status => 200,
354 headers => [['content-type', $content_type]],
355 });
356  
357 await $send->({
358 type => 'http.response.body',
359 body => $body,
360 });
361 }
362  
363 =head1 SEE ALSO
364  
365 L<PAGI::Request>, L<PAGI>
366  
367 RFC 7231 Section 5.3 - Content Negotiation
368  
369 =head1 AUTHOR
370  
371 PAGI Contributors
372  
373 =cut
374  
375 23 1;
« blib/lib/PAGI/Utils.pm ↑ Summary blib/lib/PAGI/Middleware/Healthcheck.pm »