| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
package JSON::Schema::Modern::Utilities; |
| 4 |
# vim: set ts=8 sts=2 sw=2 tw=100 et : |
| 5 |
# ABSTRACT: Internal utilities for JSON::Schema::Modern |
| 6 |
|
| 7 |
our $VERSION = '0.650'; |
| 8 |
|
| 9 |
use 5.020; |
| 10 |
use strictures 2; |
| 11 |
use stable 0.031 'postderef'; |
| 12 |
use experimental 'signatures'; |
| 13 |
no autovivification warn => qw(fetch store exists delete); |
| 14 |
use if "$]" >= 5.022, experimental => 're_strict'; |
| 15 |
use if "$]" < 5.025002, experimental => 'lexical_subs'; |
| 16 |
no if "$]" >= 5.031009, feature => 'indirect'; |
| 17 |
no if "$]" >= 5.033001, feature => 'multidimensional'; |
| 18 |
no if "$]" >= 5.033006, feature => 'bareword_filehandles'; |
| 19 |
no if "$]" >= 5.041009, feature => 'smartmatch'; |
| 20 |
no feature 'switch'; |
| 21 |
use B; |
| 22 |
use Carp qw(carp croak); |
| 23 |
use builtin::compat qw(blessed created_as_number); |
| 24 |
use Scalar::Util 'looks_like_number'; |
| 25 |
use List::Util 'pairmap'; |
| 26 |
use if "$]" < 5.041010, 'List::Util' => 'any'; |
| 27 |
use if "$]" >= 5.041010, experimental => 'keyword_any'; |
| 28 |
use Clone 'clone'; |
| 29 |
use Feature::Compat::Try; |
| 30 |
use Mojo::JSON (); |
| 31 |
use Mojo::JSON::Pointer (); |
| 32 |
use Mojo::Util 'url_escape'; |
| 33 |
use JSON::PP (); |
| 34 |
use Types::Standard qw(Str InstanceOf Enum); |
| 35 |
use Mojo::File 'path'; |
| 36 |
use namespace::clean; |
| 37 |
|
| 38 |
use Exporter 'import'; |
| 39 |
|
| 40 |
our @EXPORT_OK = qw( |
| 41 |
is_type |
| 42 |
get_type |
| 43 |
is_bool |
| 44 |
is_schema |
| 45 |
is_bignum |
| 46 |
is_equal |
| 47 |
is_elements_unique |
| 48 |
canonicalize_uri |
| 49 |
jsonp |
| 50 |
unjsonp |
| 51 |
jsonp_get |
| 52 |
jsonp_elements |
| 53 |
jsonp_set |
| 54 |
local_annotations |
| 55 |
canonical_uri |
| 56 |
E |
| 57 |
A |
| 58 |
abort |
| 59 |
assert_keyword_exists |
| 60 |
assert_keyword_type |
| 61 |
assert_pattern |
| 62 |
assert_uri_reference |
| 63 |
assert_uri |
| 64 |
annotate_self |
| 65 |
sprintf_num |
| 66 |
true |
| 67 |
false |
| 68 |
json_pointer_type |
| 69 |
canonical_uri_type |
| 70 |
core_types_type |
| 71 |
core_formats_type |
| 72 |
register_schema |
| 73 |
load_cached_document |
| 74 |
add_media_type |
| 75 |
delete_media_type |
| 76 |
decode_media_type |
| 77 |
encode_media_type |
| 78 |
match_media_type |
| 79 |
); |
| 80 |
|
| 81 |
use constant HAVE_BUILTIN => "$]" >= 5.035010; |
| 82 |
use if HAVE_BUILTIN, experimental => 'builtin'; |
| 83 |
|
| 84 |
use constant _BUILTIN_BOOLS => 0; |
| 85 |
use constant { |
| 86 |
_BUILTIN_BOOLS && HAVE_BUILTIN |
| 87 |
&& Mojo::JSON::JSON_XS && eval { Cpanel::JSON::XS->VERSION(4.38); 1 } |
| 88 |
? (true => builtin::true, false => builtin::false) |
| 89 |
: (true => JSON::PP::true, false => JSON::PP::false) |
| 90 |
}; |
| 91 |
|
| 92 |
# Mojo::JSON::JSON_XS is false when the environment variable $MOJO_NO_JSON_XS is set |
| 93 |
# and also checks if Cpanel::JSON::XS is installed. |
| 94 |
# Mojo::JSON falls back to its own pure-perl encoder/decoder but does not support all the options |
| 95 |
# that we require here. |
| 96 |
use constant _JSON_BACKEND => |
| 97 |
Mojo::JSON::JSON_XS && eval { Cpanel::JSON::XS->VERSION('4.38'); 1 } ? 'Cpanel::JSON::XS' |
| 98 |
: eval { JSON::PP->VERSION('4.11'); 1 } ? 'JSON::PP' |
| 99 |
: croak 'Cpanel::JSON::XS 4.38 or JSON::PP 4.11 is required'; |
| 100 |
|
| 101 |
# supports the six core types, plus integer (which is also a number) |
| 102 |
# we do NOT check stringy_numbers here -- you must do that in the caller |
| 103 |
# note that sometimes a value may return true for more than one type, e.g. integer+number, |
| 104 |
# or number+string, depending on its internal flags. |
| 105 |
# pass { legacy_ints => 1 } in $config to use draft4 integer behaviour |
| 106 |
# behaviour is consistent with get_type() (where integers are also numbers). |
| 107 |
sub is_type ($type, $value, $config = {}) { |
| 108 |
if ($type eq 'null') { |
| 109 |
return !(defined $value); |
| 110 |
} |
| 111 |
if ($type eq 'boolean') { |
| 112 |
return is_bool($value); |
| 113 |
} |
| 114 |
if ($type eq 'object') { |
| 115 |
return ref $value eq 'HASH'; |
| 116 |
} |
| 117 |
if ($type eq 'array') { |
| 118 |
return ref $value eq 'ARRAY'; |
| 119 |
} |
| 120 |
|
| 121 |
if ($type eq 'string' or $type eq 'number' or $type eq 'integer') { |
| 122 |
return 0 if not defined $value; |
| 123 |
my $flags = B::svref_2object(\$value)->FLAGS; |
| 124 |
|
| 125 |
# dualvars with the same string and (stringified) numeric value could be either a string or a |
| 126 |
# number, and before 5.36 we can't tell the difference, so we will answer yes for both. |
| 127 |
# in 5.36+, stringified numbers still get a PV but don't have POK set, whereas |
| 128 |
# numified strings do have POK set, so we can tell which one came first. |
| 129 |
|
| 130 |
if ($type eq 'string') { |
| 131 |
# like created_as_string, but rejects dualvars with stringwise-unequal string and numeric parts |
| 132 |
return !length ref($value) |
| 133 |
&& !(HAVE_BUILTIN && builtin::is_bool($value)) |
| 134 |
&& $flags & B::SVf_POK |
| 135 |
&& (!($flags & (B::SVf_IOK | B::SVf_NOK)) |
| 136 |
|| do { no warnings 'numeric'; 0+$value eq $value }); |
| 137 |
} |
| 138 |
|
| 139 |
if ($type eq 'number') { |
| 140 |
# floats in json will always be parsed into Math::BigFloat, when allow_bignum is enabled |
| 141 |
return is_bignum($value) || created_as_number($value); |
| 142 |
} |
| 143 |
|
| 144 |
if ($type eq 'integer') { |
| 145 |
if ($config->{legacy_ints}) { |
| 146 |
# in draft4, an integer is "A JSON number without a fraction or exponent part.", |
| 147 |
# therefore 2.0 is NOT an integer |
| 148 |
return ref($value) eq 'Math::BigInt' |
| 149 |
|| ($flags & B::SVf_IOK) && !($flags & B::SVf_NOK) && created_as_number($value); |
| 150 |
} |
| 151 |
else { |
| 152 |
# note: values that are larger than $Config{ivsize} will be represented as an NV, not IV, |
| 153 |
# therefore they will fail this check -- which is why use of Math::BigInt is recommended |
| 154 |
# if the exact type is important, or if loss of any accuracy is unacceptable |
| 155 |
return is_bignum($value) && $value->is_int |
| 156 |
# if dualvar, PV and stringified NV/IV must be identical |
| 157 |
|| created_as_number($value) && int($value) == $value; |
| 158 |
} |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
if ($type =~ /^reference to (.+)\z/) { |
| 163 |
return !blessed($value) && ref($value) eq $1; |
| 164 |
} |
| 165 |
|
| 166 |
return ref($value) eq $type; |
| 167 |
} |
| 168 |
|
| 169 |
# returns one of the six core types, plus integer |
| 170 |
# we do NOT check stringy_numbers here -- you must do that in the caller |
| 171 |
# pass { legacy_ints => 1 } in $config to use draft4 integer behaviour |
| 172 |
# behaviour is consistent with is_type(). |
| 173 |
sub get_type ($value, $config = {}) { |
| 174 |
return 'object' if ref $value eq 'HASH'; |
| 175 |
return 'boolean' if is_bool($value); |
| 176 |
return 'null' if not defined $value; |
| 177 |
return 'array' if ref $value eq 'ARRAY'; |
| 178 |
|
| 179 |
# floats in json will always be parsed into Math::BigFloat, when allow_bignum is enabled |
| 180 |
if (length(my $ref = ref $value)) { |
| 181 |
return $ref eq 'Math::BigInt' ? 'integer' |
| 182 |
: $ref eq 'Math::BigFloat' ? (!$config->{legacy_ints} && $value->is_int ? 'integer' : 'number') |
| 183 |
: (defined blessed($value) ? '' : 'reference to ').$ref; |
| 184 |
} |
| 185 |
|
| 186 |
my $flags = B::svref_2object(\$value)->FLAGS; |
| 187 |
|
| 188 |
# dualvars with the same string and (stringified) numeric value could be either a string or a |
| 189 |
# number, and before 5.36 we can't tell the difference, so we choose number because it has been |
| 190 |
# evaluated as a number already. |
| 191 |
# in 5.36+, stringified numbers still get a PV but don't have POK set, whereas |
| 192 |
# numified strings do have POK set, so we can tell which one came first. |
| 193 |
|
| 194 |
# like created_as_string, but rejects dualvars with stringwise-unequal string and numeric parts |
| 195 |
return 'string' |
| 196 |
if $flags & B::SVf_POK |
| 197 |
&& (!($flags & (B::SVf_IOK | B::SVf_NOK)) |
| 198 |
|| do { no warnings 'numeric'; 0+$value eq $value }); |
| 199 |
|
| 200 |
if ($config->{legacy_ints}) { |
| 201 |
# in draft4, an integer is "A JSON number without a fraction or exponent part.", |
| 202 |
# therefore 2.0 is NOT an integer |
| 203 |
return ($flags & B::SVf_IOK) && !($flags & B::SVf_NOK) ? 'integer' : 'number' |
| 204 |
if created_as_number($value); |
| 205 |
} |
| 206 |
else { |
| 207 |
# note: values that are larger than $Config{ivsize} will be represented as an NV, not IV, |
| 208 |
# therefore they will fail this check -- which is why use of Math::BigInt is recommended |
| 209 |
# if the exact type is important, or loss of any accuracy is unacceptable |
| 210 |
return int($value) == $value ? 'integer' : 'number' if created_as_number($value); |
| 211 |
} |
| 212 |
|
| 213 |
# this might be a scalar with POK|IOK or POK|NOK set |
| 214 |
return 'ambiguous type'; |
| 215 |
} |
| 216 |
|
| 217 |
# lifted from JSON::MaybeXS |
| 218 |
# note: unlike builtin::compat::is_bool on older perls, we do not accept |
| 219 |
# dualvar(0,"") or dualvar(1,"1") because JSON::PP and Cpanel::JSON::XS |
| 220 |
# do not encode these as booleans. |
| 221 |
sub is_bool ($value) { |
| 222 |
HAVE_BUILTIN and builtin::is_bool($value) |
| 223 |
or |
| 224 |
!!blessed($value) |
| 225 |
and ($value->isa('JSON::PP::Boolean') |
| 226 |
or $value->isa('Cpanel::JSON::XS::Boolean') |
| 227 |
or $value->isa('JSON::XS::Boolean')); |
| 228 |
} |
| 229 |
|
| 230 |
sub is_schema ($value) { |
| 231 |
ref $value eq 'HASH' || is_bool($value); |
| 232 |
} |
| 233 |
|
| 234 |
sub is_bignum ($value) { |
| 235 |
ref($value) =~ /^Math::Big(?:Int|Float)\z/; |
| 236 |
} |
| 237 |
|
| 238 |
# compares two arbitrary data payloads for equality, as per |
| 239 |
# https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.4.2.2 |
| 240 |
# $state hashref supports the following fields: |
| 241 |
# - scalarref_booleans (input): treats \0 and \1 as boolean values |
| 242 |
# - stringy_numbers (input): strings will also be compared numerically |
| 243 |
# - path (output): location of the first difference |
| 244 |
# - error (output): description of the first difference |
| 245 |
sub is_equal ($x, $y, $state = {}) { |
| 246 |
$state->{path} //= ''; |
| 247 |
|
| 248 |
my @types = map get_type($_), $x, $y; |
| 249 |
|
| 250 |
$state->{error} = 'ambiguous type encountered', return 0 |
| 251 |
if grep $types[$_] eq 'ambiguous type', 0..1; |
| 252 |
|
| 253 |
if ($state->{scalarref_booleans}) { |
| 254 |
($x, $types[0]) = (0+!!$$x, 'boolean') if $types[0] eq 'reference to SCALAR'; |
| 255 |
($y, $types[1]) = (0+!!$$y, 'boolean') if $types[1] eq 'reference to SCALAR'; |
| 256 |
} |
| 257 |
|
| 258 |
if ($state->{stringy_numbers}) { |
| 259 |
($x, $types[0]) = (0+$x, int(0+$x) == $x ? 'integer' : 'number') |
| 260 |
if $types[0] eq 'string' and looks_like_number($x); |
| 261 |
|
| 262 |
($y, $types[1]) = (0+$y, int(0+$y) == $y ? 'integer' : 'number') |
| 263 |
if $types[1] eq 'string' and looks_like_number($y); |
| 264 |
} |
| 265 |
|
| 266 |
$state->{error} = "wrong type: $types[0] vs $types[1]", return 0 if $types[0] ne $types[1]; |
| 267 |
return 1 if $types[0] eq 'null'; |
| 268 |
($x eq $y and return 1), $state->{error} = 'strings not equal', return 0 |
| 269 |
if $types[0] eq 'string'; |
| 270 |
($x == $y and return 1), $state->{error} = "$types[0]s not equal", return 0 |
| 271 |
if grep $types[0] eq $_, qw(boolean number integer); |
| 272 |
|
| 273 |
my $path = $state->{path}; |
| 274 |
if ($types[0] eq 'object') { |
| 275 |
$state->{error} = 'property count differs: '.keys(%$x).' vs '.keys(%$y), return 0 |
| 276 |
if keys %$x != keys %$y; |
| 277 |
|
| 278 |
if (not is_equal(my $arr_x = [ sort keys %$x ], my $arr_y = [ sort keys %$y ], my $s={})) { |
| 279 |
my $pos = substr($s->{path}, 1); |
| 280 |
$state->{error} = 'property names differ starting at position '.$pos.' ("'.$arr_x->[$pos].'" vs "'.$arr_y->[$pos].'")'; |
| 281 |
return 0; |
| 282 |
} |
| 283 |
|
| 284 |
foreach my $property (sort keys %$x) { |
| 285 |
$state->{path} = jsonp($path, $property); |
| 286 |
return 0 if not is_equal($x->{$property}, $y->{$property}, $state); |
| 287 |
} |
| 288 |
|
| 289 |
return 1; |
| 290 |
} |
| 291 |
|
| 292 |
if ($types[0] eq 'array') { |
| 293 |
$state->{error} = 'element count differs: '.@$x.' vs '.@$y, return 0 if @$x != @$y; |
| 294 |
foreach my $idx (0 .. $x->$#*) { |
| 295 |
$state->{path} = $path.'/'.$idx; |
| 296 |
return 0 if not is_equal($x->[$idx], $y->[$idx], $state); |
| 297 |
} |
| 298 |
return 1; |
| 299 |
} |
| 300 |
|
| 301 |
$state->{error} = 'got surprising type: '.$types[0], return 0; # should never get here |
| 302 |
} |
| 303 |
|
| 304 |
# checks array elements for uniqueness. short-circuits on first pair of matching elements |
| 305 |
# $state hashref supports the following fields: |
| 306 |
# - scalarref_booleans (input): treats \0 and \1 as boolean values |
| 307 |
# - stringy_numbers (input): strings will also be compared numerically |
| 308 |
# - path (output): location of the first difference |
| 309 |
# - error (output): description of the first difference |
| 310 |
# - equal_indices (output): the indices of identical items |
| 311 |
sub is_elements_unique ($array, $state = {}) { |
| 312 |
foreach my $idx0 (0 .. $array->$#*-1) { |
| 313 |
foreach my $idx1 ($idx0+1 .. $array->$#*) { |
| 314 |
if (is_equal($array->[$idx0], $array->[$idx1], $state)) { |
| 315 |
push $state->{equal_indices}->@*, $idx0, $idx1 if exists $state->{equal_indices}; |
| 316 |
return 0; |
| 317 |
} |
| 318 |
} |
| 319 |
} |
| 320 |
return 1; |
| 321 |
} |
| 322 |
|
| 323 |
# given a URI to a schema resource, return the canonical form of this URI |
| 324 |
sub canonicalize_uri ($evaluator, $uri) { |
| 325 |
my $schema_resource = $evaluator->_fetch_from_uri($uri); |
| 326 |
return $schema_resource ? $schema_resource->{canonical_uri} : undef; |
| 327 |
} |
| 328 |
|
| 329 |
# shorthand for creating and appending json pointers |
| 330 |
# the first argument is an already-encoded json pointer; remaining arguments are path segments to be |
| 331 |
# encoded and appended |
| 332 |
sub jsonp { |
| 333 |
carp q{first argument to jsonp should be '' or start with '/'} if length($_[0]) and substr($_[0],0,1) ne '/'; |
| 334 |
return join('/', shift, map s!~!~0!gr =~ s!/!~1!gr, grep defined, @_); |
| 335 |
} |
| 336 |
|
| 337 |
# splits a json pointer apart into its path segments |
| 338 |
sub unjsonp { |
| 339 |
carp q{argument to unjsonp should be '' or start with '/'} if length($_[0]) and substr($_[0],0,1) ne '/'; |
| 340 |
return map s!~0!~!gr =~ s!~1!/!gr, split m!/!, $_[0]; |
| 341 |
} |
| 342 |
|
| 343 |
sub jsonp_get ($data, $pointer) { |
| 344 |
Mojo::JSON::Pointer->new($data)->get($pointer); |
| 345 |
} |
| 346 |
|
| 347 |
# flatten the data structure into a hashref of { pointer => value, ... } |
| 348 |
# (essentially the reverse of jsonp_set($data, $foo->%{$_}) foreach keys $foo) |
| 349 |
sub jsonp_elements ($data, $prefix = '') { |
| 350 |
# recursively walk the structure.. |
| 351 |
my $hash = +{ |
| 352 |
ref $data eq '' ? ($prefix => $data) |
| 353 |
: ref $data eq 'HASH' ? map jsonp_elements($data->{$_}, $prefix.'/'.(s!~!~0!gr =~ s!/!~1!gr))->%*, keys %$data |
| 354 |
: ref $data eq 'ARRAY' ? map jsonp_elements($data->[$_], $prefix.'/'.$_)->%*, 0..$data->$#* |
| 355 |
: croak 'unrecognized type: '. ref $data |
| 356 |
}; |
| 357 |
} |
| 358 |
|
| 359 |
# assigns a value to a data structure at a specific json pointer location |
| 360 |
# operates destructively, in place, unless the root data or type is being modified |
| 361 |
sub jsonp_set ($data, $pointer, $value) { |
| 362 |
croak 'cannot write into a non-reference in void context' |
| 363 |
if not grep ref $data eq $_, qw(HASH ARRAY) and not defined wantarray; |
| 364 |
|
| 365 |
# assigning to the root overwrites existing data |
| 366 |
if (not length $pointer) { |
| 367 |
if (not ref $data or ref $data ne ref $value) { |
| 368 |
return $value if defined wantarray; |
| 369 |
croak 'cannot write into a reference of a different type in void context'; |
| 370 |
} |
| 371 |
|
| 372 |
if (ref $value eq 'HASH') { |
| 373 |
$data = {} if not ref $data; |
| 374 |
$data->%* = $value->%*; |
| 375 |
} |
| 376 |
if (ref $value eq 'ARRAY') { |
| 377 |
$data = [] if not ref $data; |
| 378 |
$data->@* = $value->@*; |
| 379 |
} |
| 380 |
|
| 381 |
return $data; |
| 382 |
} |
| 383 |
|
| 384 |
my @keys = map +(s!~0!~!gr =~ s!~1!/!gr), |
| 385 |
(length $pointer ? (split /\//, $pointer, -1) : ($pointer)); |
| 386 |
|
| 387 |
croak 'cannot write a hashref into a reference to an array in void context' |
| 388 |
if @keys >= 2 and $keys[1] !~ /^(?:\d+|-)\z/a and ref $data eq 'ARRAY' and not defined wantarray; |
| 389 |
|
| 390 |
shift @keys; # always '', indicating the root |
| 391 |
my $curp = \$data; |
| 392 |
|
| 393 |
foreach my $key (@keys) { |
| 394 |
# if needed, first remove the existing data so we can replace with a new hash key or array index |
| 395 |
undef $curp->$* |
| 396 |
if not ref $curp->$* |
| 397 |
or ref $curp->$* eq 'ARRAY' and $key !~ /^(?:\d+|-)\z/a; |
| 398 |
|
| 399 |
# use this existing hash key or array index location, or create new position |
| 400 |
use autovivification 'store'; |
| 401 |
$curp = \( |
| 402 |
ref $curp->$* eq 'HASH' || $key !~ /^(?:\d+|-)\z/a ? $curp->$*->{$key} |
| 403 |
: $key =~ /^\d+\z/a ? $curp->$*->[$key] |
| 404 |
: $curp->$*->[$curp->$*->$#* + 1]); |
| 405 |
} |
| 406 |
|
| 407 |
$curp->$* = $value; |
| 408 |
return $data; |
| 409 |
} |
| 410 |
|
| 411 |
# returns a reusable Types::Standard type for json pointers |
| 412 |
# TODO: move this off into its own distribution, see JSON::Schema::Types |
| 413 |
sub json_pointer_type () { Str->where('!length || m{^/} && !m{~(?![01])}'); } |
| 414 |
|
| 415 |
# a URI without a fragment, or with a json pointer fragment |
| 416 |
sub canonical_uri_type () { |
| 417 |
(InstanceOf['Mojo::URL'])->where(q{!defined($_->fragment) || $_->fragment =~ m{^/} && $_->fragment !~ m{~(?![01])}}); |
| 418 |
} |
| 419 |
|
| 420 |
# Validation §7.1-2: "Note that the "type" keyword in this specification defines an "integer" type |
| 421 |
# which is not part of the data model. Therefore a format attribute can be limited to numbers, but |
| 422 |
# not specifically to integers." |
| 423 |
sub core_types_type () { |
| 424 |
Enum[qw(null object array boolean string number)]; |
| 425 |
} |
| 426 |
|
| 427 |
sub core_formats_type () { |
| 428 |
Enum[qw(date-time date time duration email idn-email hostname idn-hostname ipv4 ipv6 uri uri-reference iri iri-reference uuid uri-template json-pointer relative-json-pointer regex)]; |
| 429 |
} |
| 430 |
|
| 431 |
# simple runtime-wide cache of $ids to schema document objects that are sourced from disk |
| 432 |
{ |
| 433 |
my $document_cache = {}; |
| 434 |
|
| 435 |
# adds a document to the cache, if its URI is in the cacheable list |
| 436 |
# for internal use only!! |
| 437 |
sub __populate_cached_document ($evaluator, $uri, $doc) { |
| 438 |
$document_cache->{$uri} = $doc |
| 439 |
if not exists $document_cache->{$uri} and get_schema_filename($uri); |
| 440 |
} |
| 441 |
|
| 442 |
# Fetches a document from the cache (reading it from disk and creating the document if necessary), |
| 443 |
# and add it to the evaluator. |
| 444 |
# Normally this will just be a cache of schemas that are bundled with this distribution or a related |
| 445 |
# distribution (such as OpenAPI-Modern), as duplicate identifiers are not checked for, unlike for |
| 446 |
# normal schema additions. |
| 447 |
# Only JSON-encoded files are supported at this time. |
| 448 |
sub load_cached_document ($evaluator, $uri) { |
| 449 |
$uri =~ s/#\z//; # older draft $ids use an empty fragment |
| 450 |
|
| 451 |
# see if it already exists as a document in the cache |
| 452 |
my $document = $document_cache->{$uri}; |
| 453 |
|
| 454 |
# otherwise, load it from disk using our filename cache and create the document |
| 455 |
if (not $document and my $filename = get_schema_filename($uri)) { |
| 456 |
my $file = path($filename); |
| 457 |
croak "uri $uri maps to file $file which does not exist" if not -f $file; |
| 458 |
my $schema = $evaluator->_json_decoder->decode($file->slurp); |
| 459 |
|
| 460 |
# avoid calling add_schema, which checksums the file to look for duplicates |
| 461 |
$document = JSON::Schema::Modern::Document->new( |
| 462 |
schema => $schema, |
| 463 |
evaluator => $evaluator, |
| 464 |
skip_ref_checks => 1, |
| 465 |
); |
| 466 |
|
| 467 |
# avoid calling add_document, which checks for duplicate identifiers (and would result in an |
| 468 |
# infinite loop) |
| 469 |
die JSON::Schema::Modern::Result->new( |
| 470 |
output_format => $evaluator->output_format, |
| 471 |
valid => 0, |
| 472 |
errors => [ $document->errors ], |
| 473 |
exception => 1, |
| 474 |
) if $document->has_errors; |
| 475 |
|
| 476 |
$document_cache->{$uri} = $document; |
| 477 |
} |
| 478 |
|
| 479 |
return if not $document; |
| 480 |
|
| 481 |
# bypass the normal collision checks, to avoid an infinite loop: these documents are presumed safe |
| 482 |
$evaluator->_add_resources_unsafe( |
| 483 |
map +($_->[0] => +{ $_->[1]->%*, document => $document }), |
| 484 |
$document->resource_pairs |
| 485 |
); |
| 486 |
|
| 487 |
return $document; |
| 488 |
} |
| 489 |
} |
| 490 |
|
| 491 |
###### media-type mayhem below! |
| 492 |
|
| 493 |
{ |
| 494 |
# a hashref that indexes a media-type or media-range string to a decoder, encoder, and |
| 495 |
# denormalized representation of the string. |
| 496 |
# prepopulated list must match the list of definitions in _predefined_media_types |
| 497 |
my $MEDIA_TYPES = { |
| 498 |
map +(join('/', @$_) => { type => $_->[0], subtype => $_->[1] }), ( |
| 499 |
[ qw(application json) ], |
| 500 |
[ qw(application octet-stream) ], |
| 501 |
[ qw(text *) ], |
| 502 |
[ qw(application x-www-form-urlencoded) ], |
| 503 |
[ qw(application x-ndjson) ], |
| 504 |
# multipart/form-data and multipart/* are special-cased in OpenAPI::Modern: do not add here |
| 505 |
) |
| 506 |
}; |
| 507 |
|
| 508 |
# see RFC9110 §8.3.1 for ABNF |
| 509 |
my $OWS = q{[\x09\x20]*}; |
| 510 |
my $TOKEN = q{(?a:[[:alnum:]!#$%&'*+.^_`|~-]+)}; |
| 511 |
my $QUOTED_STRING = q{"((?:[\x09\20\x21\x23-\x5B\x5D-\x7E\x80-\xFF]|\x5C[\x09\x20-\x7E\x80-\xFF])*)"}; |
| 512 |
|
| 513 |
# parses into hashref: { type => .., subtype => .., params => { .. } } |
| 514 |
my sub _parse_media_type ($media_type_string = '') { |
| 515 |
my ($type, $subtype) = ($media_type_string =~ m{^($TOKEN)/($TOKEN)}); |
| 516 |
return if not defined $type or not defined $subtype; |
| 517 |
pos($media_type_string) = length $&; |
| 518 |
my $leftovers = $'; |
| 519 |
|
| 520 |
# RFC9110 §5.6.4: "The backslash octet ("\") can be used as a single-octet quoting mechanism |
| 521 |
# within quoted-string and comment constructs. Recipients that process the value of a |
| 522 |
# quoted-string MUST handle a quoted-pair as if it were replaced by the octet following the |
| 523 |
# backslash." |
| 524 |
my $params = {}; |
| 525 |
while ($media_type_string =~ /\G$OWS;$OWS($TOKEN)=($TOKEN|$QUOTED_STRING)/g) { |
| 526 |
my ($name, $value, $qs_value) = ($1, $2, $3); |
| 527 |
$leftovers = $'; |
| 528 |
$params->{fc($name)} = defined $qs_value ? ($qs_value =~ s/\x5C(.)/$1/gr) : $value; |
| 529 |
} |
| 530 |
|
| 531 |
return if length $leftovers; # junk was left over |
| 532 |
croak 'cannot parse more than 64 parameters' if keys $params->%* > 64; |
| 533 |
|
| 534 |
# some parameter values are case-insensitive; enumerate them here |
| 535 |
$params->{$_} = fc($params->{$_}) foreach grep exists $params->{$_}, qw(charset); |
| 536 |
|
| 537 |
+{ |
| 538 |
type => fc($type), |
| 539 |
subtype => fc($subtype), |
| 540 |
keys %$params ? (parameters => $params) : (), |
| 541 |
}; |
| 542 |
} |
| 543 |
|
| 544 |
# wrapped in a sub so we don't define them until needed |
| 545 |
my sub _predefined_media_types ($media_type_string) { |
| 546 |
return +{ |
| 547 |
type => 'application', |
| 548 |
subtype => 'json', |
| 549 |
# UTF-8 decoding and encoding is always done, as per the JSON spec. |
| 550 |
# other charsets are not supported: see RFC8259 §11 |
| 551 |
decode => sub ($content_ref, @) { |
| 552 |
\ _JSON_BACKEND->new->allow_nonref(1)->utf8(1)->decode($content_ref->$*); |
| 553 |
}, |
| 554 |
encode => sub ($content_ref, @) { |
| 555 |
\ _JSON_BACKEND->new->allow_nonref(1)->utf8(1)->allow_blessed(1)->convert_blessed(1)->encode($content_ref->$*); |
| 556 |
}, |
| 557 |
owner_addr => 1, |
| 558 |
} |
| 559 |
if $media_type_string eq 'application/json'; |
| 560 |
|
| 561 |
return +{ |
| 562 |
type => 'application', |
| 563 |
subtype => 'octet-stream', |
| 564 |
(map +($_ => sub ($content_ref, @) { $content_ref }), qw(decode encode)), |
| 565 |
owner_addr => 1, |
| 566 |
} |
| 567 |
if $media_type_string eq 'application/octet-stream'; |
| 568 |
|
| 569 |
# identity function, with charset support |
| 570 |
return +{ |
| 571 |
type => 'text', subtype => '*', |
| 572 |
decode => sub ($content_ref, $parameters = {}, @) { |
| 573 |
# RFC2046 §4.1.2: charset is case-insensitive |
| 574 |
# RFC6657 §4: default charset for text/plain is "US-ASCII" |
| 575 |
return $parameters->{charset} ? |
| 576 |
\ Encode::decode($parameters->{charset}, $content_ref->$*, Encode::DIE_ON_ERR | Encode::LEAVE_SRC) |
| 577 |
: $content_ref; |
| 578 |
}, |
| 579 |
encode => sub ($content_ref, $parameters = {}, @) { |
| 580 |
return $parameters->{charset} ? |
| 581 |
\ Encode::encode($parameters->{charset}, $content_ref->$*, Encode::DIE_ON_ERR | Encode::LEAVE_SRC) |
| 582 |
: $content_ref; |
| 583 |
}, |
| 584 |
owner_addr => 1, |
| 585 |
} |
| 586 |
if $media_type_string eq 'text/*'; |
| 587 |
|
| 588 |
return +{ |
| 589 |
type => 'application', |
| 590 |
subtype => 'x-www-form-urlencoded', |
| 591 |
decode => sub ($content_ref, $parameters = {}) { |
| 592 |
my $parsed = Mojo::Parameters->new->charset('UTF-8')->parse($content_ref->$*); |
| 593 |
|
| 594 |
if (($parameters->{type}//'object') eq 'array') { |
| 595 |
\ [ pairmap { +{ $a, $b } } $parsed->pairs->@* ]; |
| 596 |
} |
| 597 |
elsif (($parameters->{type}//'object') eq 'object') { |
| 598 |
\ $parsed->to_hash; |
| 599 |
} |
| 600 |
else { |
| 601 |
die 'unrecognized "type": ', $parameters->{type}; |
| 602 |
} |
| 603 |
}, |
| 604 |
encode => sub ($content_ref, @) { |
| 605 |
# WHATWG §1.3: "The application/x-www-form-urlencoded percent-encode set contains all code |
| 606 |
# points, except the ASCII alphanumeric, U+002A (*), U+002D (-), U+002E (.), and U+005F |
| 607 |
# (_)." |
| 608 |
state sub escape ($str) { |
| 609 |
url_escape(Encode::encode('UTF-8', $str, Encode::DIE_ON_ERR), '^A-Za-z0-9*\-._'); |
| 610 |
} |
| 611 |
|
| 612 |
if (ref $content_ref->$* eq 'ARRAY') { # arrayref of hashref tuples |
| 613 |
\ join '&', map +(join '=', (map +(escape $_), %$_)), $content_ref->$*->@*; |
| 614 |
} |
| 615 |
elsif (ref $content_ref->$* eq 'HASH') { # hashref of strings or arrayref of strings |
| 616 |
\ join '&', |
| 617 |
map do { |
| 618 |
my ($k, $ek) = ($_, escape($_)); |
| 619 |
ref $content_ref->$*->{$k} eq 'ARRAY' |
| 620 |
? (map +($ek.'='.escape($_)), $content_ref->$*->{$k}->@*) |
| 621 |
: $ek.'='.escape($content_ref->$*->{$k}) |
| 622 |
}, |
| 623 |
sort keys $content_ref->$*->%*; |
| 624 |
} |
| 625 |
else { |
| 626 |
die 'unrecognized data type: ', ref $content_ref->$*; |
| 627 |
} |
| 628 |
}, |
| 629 |
owner_addr => 1, |
| 630 |
} |
| 631 |
if $media_type_string eq 'application/x-www-form-urlencoded'; |
| 632 |
|
| 633 |
return +{ |
| 634 |
type => 'application', |
| 635 |
subtype => 'x-ndjson', |
| 636 |
decode => sub ($content_ref, @) { |
| 637 |
my $decoder = _JSON_BACKEND->new->allow_nonref(1)->utf8(1); |
| 638 |
my $line = 0; # line numbers start at 1 |
| 639 |
\[ map do { |
| 640 |
try { ++$line; $decoder->decode($_) } |
| 641 |
catch ($e) { croak 'parse error at line '.$line.': '.$e } |
| 642 |
}, |
| 643 |
split(/\r?\n/, $content_ref->$*) |
| 644 |
]; |
| 645 |
}, |
| 646 |
encode => sub ($content_ref, @) { |
| 647 |
my $encoder = _JSON_BACKEND->new->allow_nonref(1)->utf8(1)->allow_blessed(1)->convert_blessed(1); |
| 648 |
\ join "\n", map $encoder->encode($_), $content_ref->$*->@*; |
| 649 |
}, |
| 650 |
owner_addr => 1, |
| 651 |
} |
| 652 |
if $media_type_string eq 'application/x-ndjson'; |
| 653 |
} |
| 654 |
|
| 655 |
# for internal use by JSON::Schema::Modern only! may be removed without notice! |
| 656 |
sub _get_media_type_decoder ($media_type_string) { |
| 657 |
my $matched_string = match_media_type($media_type_string); |
| 658 |
return undef if not defined $matched_string; |
| 659 |
|
| 660 |
my $definition = $MEDIA_TYPES->{$matched_string}; |
| 661 |
$definition = $MEDIA_TYPES->{$matched_string} = _predefined_media_types($matched_string) |
| 662 |
if not exists $definition->{decode}; |
| 663 |
|
| 664 |
return $definition->{decode}; |
| 665 |
} |
| 666 |
|
| 667 |
sub add_media_type ($media_type_string, $decoder_sub = undef, $encoder_sub = undef, $owner_addr = 1) { |
| 668 |
croak 'decoder is not a subref' if defined $decoder_sub and ref $decoder_sub ne 'CODE'; |
| 669 |
croak 'encoder is not a subref' if defined $encoder_sub and ref $encoder_sub ne 'CODE'; |
| 670 |
|
| 671 |
my $type = _parse_media_type($media_type_string); |
| 672 |
croak "bad media-type string \"$media_type_string\"" if not $type; |
| 673 |
|
| 674 |
croak 'multipart encoders/decoders cannot be defined here: use OpenAPI::Modern' |
| 675 |
if match_media_type($media_type_string, ['multipart/*']); |
| 676 |
|
| 677 |
# populate the cache if it's a bundled type that hasn't been defined yet |
| 678 |
_predefined_media_types($media_type_string) if not exists $MEDIA_TYPES->{$media_type_string}; |
| 679 |
|
| 680 |
if (any { is_equal($type, { $_->%{qw(type subtype parameters)} }) } values %$MEDIA_TYPES) { |
| 681 |
croak 'duplicate media-type found' if $owner_addr == 1; |
| 682 |
|
| 683 |
# track evaluator object that used the deprecated add_media_type interface |
| 684 |
push $MEDIA_TYPES->{$media_type_string}{owner_addr}->@*, $owner_addr; |
| 685 |
return; |
| 686 |
} |
| 687 |
|
| 688 |
$MEDIA_TYPES->{$media_type_string} = { |
| 689 |
decode => $decoder_sub, |
| 690 |
encode => $encoder_sub, |
| 691 |
%$type, |
| 692 |
owner_addr => [ $owner_addr ], # refaddr of the evaluator object that added us |
| 693 |
}; |
| 694 |
|
| 695 |
return; |
| 696 |
} |
| 697 |
|
| 698 |
sub delete_media_type ($media_type_string, $owner_addr = 1) { |
| 699 |
return if not exists $MEDIA_TYPES->{$media_type_string}; |
| 700 |
|
| 701 |
delete $MEDIA_TYPES->{$media_type_string} |
| 702 |
if $owner_addr == 1 |
| 703 |
or $MEDIA_TYPES->{$media_type_string}{owner_addr} = [ |
| 704 |
grep +($_ != 1 && $_ != $owner_addr), $MEDIA_TYPES->{$media_type_string}{owner_addr}->@* |
| 705 |
]; |
| 706 |
} |
| 707 |
|
| 708 |
# wildcards, parameters supported |
| 709 |
# always returns a reference to the decoded data, or undef if no decoder is found |
| 710 |
sub decode_media_type ($media_type_string, $content_ref) { |
| 711 |
croak 'decoder payload must be a reference to a string (not ', |
| 712 |
(length ref $content_ref ? ref $content_ref : 'a non-reference') |
| 713 |
if ref $content_ref ne 'SCALAR'; |
| 714 |
|
| 715 |
my $matched_string = match_media_type($media_type_string); |
| 716 |
return if not $matched_string; |
| 717 |
|
| 718 |
my $definition = $MEDIA_TYPES->{$matched_string}; |
| 719 |
$definition = $MEDIA_TYPES->{$matched_string} = _predefined_media_types($matched_string) |
| 720 |
if not exists $definition->{decode}; |
| 721 |
|
| 722 |
return if not $definition->{decode}; |
| 723 |
|
| 724 |
my $type = _parse_media_type($media_type_string); |
| 725 |
$definition->{decode}->($content_ref, $type->{parameters}//()); |
| 726 |
} |
| 727 |
|
| 728 |
# wildcards, parameters supported |
| 729 |
sub encode_media_type ($media_type_string, $content_ref) { |
| 730 |
croak 'encoder payload must be a reference' if ref $content_ref ne 'REF' and ref $content_ref ne 'SCALAR'; |
| 731 |
|
| 732 |
my $matched_string = match_media_type($media_type_string); |
| 733 |
return if not $matched_string; |
| 734 |
|
| 735 |
my $definition = $MEDIA_TYPES->{$matched_string}; |
| 736 |
$definition = $MEDIA_TYPES->{$matched_string} = _predefined_media_types($matched_string) |
| 737 |
if not exists $definition->{encode}; |
| 738 |
|
| 739 |
return if not $definition->{encode}; |
| 740 |
|
| 741 |
my $type = _parse_media_type($media_type_string); |
| 742 |
$definition->{encode}->($content_ref, $type->{parameters}//()); |
| 743 |
} |
| 744 |
|
| 745 |
# finds best match for a media-type against a list of media-types. if parameter(s) are included in |
| 746 |
# the media-type to be matched, all parameters must be present in the match value. |
| 747 |
sub match_media_type ($media_type_string, $media_types = []) { |
| 748 |
return if not length $media_type_string; |
| 749 |
|
| 750 |
# return immediately if exact match exists |
| 751 |
return $media_type_string |
| 752 |
if @$media_types and any { $_ eq $media_type_string } @$media_types |
| 753 |
or not @$media_types and exists $MEDIA_TYPES->{$media_type_string}; |
| 754 |
|
| 755 |
my $mt = _parse_media_type($media_type_string); |
| 756 |
return if not $mt; |
| 757 |
|
| 758 |
my $types = @$media_types ? +{ map +($_ => _parse_media_type($_)), @$media_types } : $MEDIA_TYPES; |
| 759 |
|
| 760 |
my @matches; # [ rank, candidate ] |
| 761 |
|
| 762 |
# iterate through each provided MT and compare it to the string for matchability.. |
| 763 |
CANDIDATE: |
| 764 |
foreach my $candidate (keys %$types) { |
| 765 |
# if candidate has parameters, all parameters must match; missing parameters ok. |
| 766 |
# the more parameters match the higher the score. |
| 767 |
my $params_matched = 0; |
| 768 |
foreach my $param (keys(($types->{$candidate}{parameters}//{})->%*)) { |
| 769 |
next CANDIDATE if not exists(($mt->{parameters}//{})->{$param}) |
| 770 |
or $types->{$candidate}{parameters}{$param} ne $mt->{parameters}{$param}; |
| 771 |
|
| 772 |
++$params_matched; |
| 773 |
} |
| 774 |
|
| 775 |
push(@matches, [ 0+$params_matched, $candidate ]), next if $candidate eq '*/*'; |
| 776 |
push(@matches, [ 2**8 + $params_matched, $candidate ]), next |
| 777 |
if $types->{$candidate}{subtype} eq '*' |
| 778 |
and $types->{$candidate}{type} eq $mt->{type}; |
| 779 |
|
| 780 |
# exact type + subtype match: best overall |
| 781 |
if ($types->{$candidate}{type} eq $mt->{type}) { |
| 782 |
push(@matches, [ 2**10 + $params_matched, $candidate ]), next |
| 783 |
if $types->{$candidate}{subtype} eq $mt->{subtype}; |
| 784 |
|
| 785 |
# text/foo+plain matches text/plain but not text/bar+plain |
| 786 |
push(@matches, [ 2**9 + $params_matched, $candidate ]), next |
| 787 |
if $mt->{subtype} =~ m{^.+\+(.+)\z} and $types->{$candidate}{subtype} eq $1; |
| 788 |
} |
| 789 |
} |
| 790 |
|
| 791 |
return if not @matches; |
| 792 |
my @sorted = sort { $b->[0] <=> $a->[0] } @matches; |
| 793 |
return $sorted[0]->[1]; |
| 794 |
} |
| 795 |
} |
| 796 |
|
| 797 |
######## NO PUBLIC INTERFACES FOLLOW THIS POINT ######## |
| 798 |
|
| 799 |
# get all annotations produced for the current instance data location (that are visible to this |
| 800 |
# schema location) - remember these are hashrefs, not Annotation objects |
| 801 |
sub local_annotations ($state) { |
| 802 |
grep $_->{instance_location} eq $state->{data_path}, $state->{annotations}->@*; |
| 803 |
} |
| 804 |
|
| 805 |
# shorthand for finding the current uri of the present schema location |
| 806 |
# ensure that this code is kept consistent with the absolute_keyword_location builder in ResultNode |
| 807 |
# Note that this may not be canonical if keyword_path has not yet been reset via the processing of a |
| 808 |
# local identifier keyword (e.g. '$id'). |
| 809 |
sub canonical_uri ($state, @extra_path) { |
| 810 |
return $state->{initial_schema_uri} if not @extra_path and not length($state->{keyword_path}); |
| 811 |
my $uri = $state->{initial_schema_uri}->clone; |
| 812 |
my $fragment = ($uri->fragment//'').(@extra_path ? jsonp($state->{keyword_path}, @extra_path) : $state->{keyword_path}); |
| 813 |
undef $fragment if not length($fragment); |
| 814 |
$uri->fragment($fragment); |
| 815 |
$uri; |
| 816 |
} |
| 817 |
|
| 818 |
# shorthand for creating error objects |
| 819 |
# uses these keys from $state: |
| 820 |
# - initial_schema_uri |
| 821 |
# - keyword (optional) |
| 822 |
# - data_path |
| 823 |
# - traversed_keyword_path |
| 824 |
# - keyword_path |
| 825 |
# - _keyword_path_suffix (optional) |
| 826 |
# - errors |
| 827 |
# - exception (optional; set by abort()) |
| 828 |
# - recommended_response (optional) |
| 829 |
# - depth |
| 830 |
# - traverse (boolean, used for mode) |
| 831 |
# returns defined-false, so callers can use 'return;' to differentiate between |
| 832 |
# failed-with-no-error from failed-with-error. |
| 833 |
sub E ($state, $error_string, @args) { |
| 834 |
croak 'E called in void context' if not defined wantarray; |
| 835 |
|
| 836 |
# sometimes the keyword shouldn't be at the very end of the schema path |
| 837 |
my $sps = delete $state->{_keyword_path_suffix}; |
| 838 |
my @keyword_path_suffix = defined $sps && ref $sps eq 'ARRAY' ? $sps->@* : $sps//(); |
| 839 |
|
| 840 |
# we store the absolute uri in unresolved form until needed, |
| 841 |
# and perform the rest of the calculations later. |
| 842 |
my $uri = [ $state->@{qw(initial_schema_uri keyword_path)}, $state->{keyword}//(), @keyword_path_suffix ]; |
| 843 |
|
| 844 |
my $keyword_location = $state->{traversed_keyword_path} |
| 845 |
.jsonp($state->{keyword_path}, $state->{keyword}//(), @keyword_path_suffix); |
| 846 |
|
| 847 |
require JSON::Schema::Modern::Error; |
| 848 |
push $state->{errors}->@*, JSON::Schema::Modern::Error->new( |
| 849 |
depth => $state->{depth} // 0, |
| 850 |
keyword => $state->{keyword}, |
| 851 |
$state->{traverse} ? () : (instance_location => $state->{data_path}), |
| 852 |
keyword_location => $keyword_location, |
| 853 |
# we calculate absolute_keyword_location when instantiating the Error object for Result |
| 854 |
_uri => $uri, |
| 855 |
error => @args ? sprintf($error_string, @args) : $error_string, |
| 856 |
exception => $state->{exception}, |
| 857 |
($state->%{recommended_response})x!!$state->{recommended_response}, |
| 858 |
mode => $state->{traverse} ? 'traverse' : 'evaluate', |
| 859 |
); |
| 860 |
|
| 861 |
return 0; |
| 862 |
} |
| 863 |
|
| 864 |
# shorthand for creating annotations |
| 865 |
# uses these keys from $state: |
| 866 |
# - initial_schema_uri |
| 867 |
# - keyword (mandatory) |
| 868 |
# - data_path |
| 869 |
# - traversed_keyword_path |
| 870 |
# - keyword_path |
| 871 |
# - annotations |
| 872 |
# - collect_annotations |
| 873 |
# - _unknown (boolean) |
| 874 |
# - depth |
| 875 |
sub A ($state, $annotation) { |
| 876 |
# even if the user requested annotations, we only collect them for later drafts |
| 877 |
# ..but we always collect them if the lowest bit is set, indicating the presence of unevaluated* |
| 878 |
# keywords necessary for accurate validation |
| 879 |
return 1 if not ($state->{collect_annotations} |
| 880 |
& ($state->{specification_version} =~ /^draft[467]\z/ ? ~(1<<8) : ~0)); |
| 881 |
|
| 882 |
# we store the absolute uri in unresolved form until needed, |
| 883 |
# and perform the rest of the calculations later. |
| 884 |
my $uri = [ $state->@{qw(initial_schema_uri keyword_path keyword)} ]; |
| 885 |
|
| 886 |
my $keyword_location = $state->{traversed_keyword_path}.jsonp($state->@{qw(keyword_path keyword)}); |
| 887 |
|
| 888 |
push $state->{annotations}->@*, { |
| 889 |
depth => $state->{depth} // 0, |
| 890 |
keyword => $state->{keyword}, |
| 891 |
instance_location => $state->{data_path}, |
| 892 |
keyword_location => $keyword_location, |
| 893 |
# we calculate absolute_keyword_location when instantiating the Annotation object for Result |
| 894 |
_uri => $uri, |
| 895 |
annotation => $annotation, |
| 896 |
$state->{_unknown} ? (unknown => 1) : (), |
| 897 |
}; |
| 898 |
|
| 899 |
return 1; |
| 900 |
} |
| 901 |
|
| 902 |
# creates an error object, but also aborts evaluation immediately |
| 903 |
# only this error is returned, because other errors on the stack might not actually be "real" |
| 904 |
# errors (consider if we were in the middle of evaluating a "not" or "if"). |
| 905 |
# Therefore this is only appropriate during the evaluation phase, not the traverse phase. |
| 906 |
sub abort ($state, $error_string, @args) { |
| 907 |
()= E({ %$state, exception => 1 }, $error_string, @args); |
| 908 |
croak 'abort() called during traverse' if $state->{traverse}; |
| 909 |
die pop $state->{errors}->@*; |
| 910 |
} |
| 911 |
|
| 912 |
sub assert_keyword_exists ($state, $schema) { |
| 913 |
croak 'assert_keyword_exists called in void context' if not defined wantarray; |
| 914 |
return E($state, '%s keyword is required', $state->{keyword}) if not exists $schema->{$state->{keyword}}; |
| 915 |
return 1; |
| 916 |
} |
| 917 |
|
| 918 |
sub assert_keyword_type ($state, $schema, $type) { |
| 919 |
croak 'assert_keyword_type called in void context' if not defined wantarray; |
| 920 |
return 1 if is_type($type, $schema->{$state->{keyword}}); |
| 921 |
E($state, '%s value is not a%s %s', $state->{keyword}, ($type =~ /^[aeiou]/ ? 'n' : ''), $type); |
| 922 |
} |
| 923 |
|
| 924 |
sub assert_pattern ($state, $pattern) { |
| 925 |
croak 'assert_pattern called in void context' if not defined wantarray; |
| 926 |
try { |
| 927 |
local $SIG{__WARN__} = sub { die @_ }; |
| 928 |
qr/$pattern/; |
| 929 |
} |
| 930 |
catch ($e) { return E($state, $e); }; |
| 931 |
return 1; |
| 932 |
} |
| 933 |
|
| 934 |
# this is only suitable for checking URIs within schemas themselves |
| 935 |
# note that we cannot use $state->{specification_version} to more tightly constrain the plain-name |
| 936 |
# fragment syntax, as we could be checking a $ref to a schema using a different version |
| 937 |
sub assert_uri_reference ($state, $schema) { |
| 938 |
croak 'assert_uri_reference called in void context' if not defined wantarray; |
| 939 |
|
| 940 |
my $string = $schema->{$state->{keyword}}; |
| 941 |
return E($state, '%s value is not a valid URI-reference', $state->{keyword}) |
| 942 |
# see also uri-reference format sub |
| 943 |
if fc(Mojo::URL->new($string)->to_unsafe_string) ne fc($string) |
| 944 |
or $string =~ /[^[:ascii:]]/ # ascii characters only |
| 945 |
or $string =~ /#/ # no fragment, except... |
| 946 |
and $string !~ m{#\z} # allow empty fragment |
| 947 |
and $string !~ m{#[A-Za-z_][A-Za-z0-9_:.-]*\z} # allow plain-name fragment, superset of all drafts |
| 948 |
and $string !~ m{#/(?:[^~]|~[01])*\z}; # allow json pointer fragment |
| 949 |
|
| 950 |
return 1; |
| 951 |
} |
| 952 |
|
| 953 |
# this is only suitable for checking URIs within schemas themselves, |
| 954 |
# which have fragments consisting of plain names (anchors) or json pointers |
| 955 |
sub assert_uri ($state, $schema, $override = undef) { |
| 956 |
croak 'assert_uri called in void context' if not defined wantarray; |
| 957 |
|
| 958 |
my $string = $override // $schema->{$state->{keyword}}; |
| 959 |
my $uri = Mojo::URL->new($string); |
| 960 |
|
| 961 |
return E($state, '"%s" is not a valid URI', $string) |
| 962 |
# see also uri format sub |
| 963 |
if fc($uri->to_unsafe_string) ne fc($string) |
| 964 |
or $string =~ /[^[:ascii:]]/ # ascii characters only |
| 965 |
or not $uri->is_abs # must have a scheme |
| 966 |
or $string =~ /#/ # no fragment, except... |
| 967 |
and $string !~ m{#\z} # empty fragment |
| 968 |
and $string !~ m{#[A-Za-z][A-Za-z0-9_:.-]*\z} # plain-name fragment |
| 969 |
and $string !~ m{#/(?:[^~]|~[01])*\z}; # json pointer fragment |
| 970 |
|
| 971 |
return 1; |
| 972 |
} |
| 973 |
|
| 974 |
# produces an annotation whose value is the same as that of the current schema keyword |
| 975 |
# makes a copy as this is passed back to the user, who cannot be trusted to not mutate it |
| 976 |
sub annotate_self ($state, $schema) { |
| 977 |
A($state, ref $schema->{$state->{keyword}} ? clone($schema->{$state->{keyword}}) |
| 978 |
: $schema->{$state->{keyword}}); |
| 979 |
} |
| 980 |
|
| 981 |
# use original value as stored in the NV, without losing precision |
| 982 |
sub sprintf_num ($value) { |
| 983 |
is_bignum($value) ? $value->bstr : sprintf('%s', $value); |
| 984 |
} |
| 985 |
|
| 986 |
{ |
| 987 |
# simple runtime-wide cache of $ids to filenames that are sourced from disk |
| 988 |
my $schema_filename_cache = {}; |
| 989 |
|
| 990 |
# adds a mapping from a URI to an absolute filename in the global runtime |
| 991 |
# (available to all instances of the evaluator running in the same process). |
| 992 |
sub register_schema ($uri, $filename) { |
| 993 |
$schema_filename_cache->{$uri} = $filename; |
| 994 |
} |
| 995 |
|
| 996 |
sub get_schema_filename ($uri) { |
| 997 |
$schema_filename_cache->{$uri}; |
| 998 |
} |
| 999 |
} |
| 1000 |
|
| 1001 |
1; |
| 1002 |
|
| 1003 |
__END__ |
| 1004 |
|
| 1005 |
=pod |
| 1006 |
|
| 1007 |
=encoding UTF-8 |
| 1008 |
|
| 1009 |
=head1 NAME |
| 1010 |
|
| 1011 |
JSON::Schema::Modern::Utilities - Internal utilities for JSON::Schema::Modern |
| 1012 |
|
| 1013 |
=head1 VERSION |
| 1014 |
|
| 1015 |
version 0.650 |
| 1016 |
|
| 1017 |
I use a linearly-increasing version numbering scheme. No meaning should be |
| 1018 |
presumed or inferred from the version being less than 1.0. |
| 1019 |
|
| 1020 |
=head1 SYNOPSIS |
| 1021 |
|
| 1022 |
use JSON::Schema::Modern::Utilities qw(func1 func2..); |
| 1023 |
|
| 1024 |
=head1 DESCRIPTION |
| 1025 |
|
| 1026 |
This class contains internal utilities to be used by L<JSON::Schema::Modern>, and other useful helpers. |
| 1027 |
|
| 1028 |
=for Pod::Coverage is_bignum local_annotations |
| 1029 |
canonical_uri E A abort assert_keyword_exists assert_keyword_type assert_pattern assert_uri_reference assert_uri |
| 1030 |
annotate_self sprintf_num HAVE_BUILTIN true false |
| 1031 |
register_schema get_schema_filename |
| 1032 |
|
| 1033 |
=head1 FUNCTIONS |
| 1034 |
|
| 1035 |
=for stopwords schema metaschema dualvar jsonp unjsonp OpenAPI subref |
| 1036 |
|
| 1037 |
=head2 is_type |
| 1038 |
|
| 1039 |
if (is_type('string', $value)) { ... } |
| 1040 |
|
| 1041 |
Returns a boolean indicating whether the provided value is of the specified core type (C<null>, |
| 1042 |
C<boolean>, C<string>, C<number>, C<object>, C<array>) or C<integer>. Also optionally takes a hashref |
| 1043 |
C<< { legacy_ints => 1 } >> indicating that draft4 number semantics should apply (where unlike later |
| 1044 |
drafts, C<2.0> is B<not> an integer). |
| 1045 |
|
| 1046 |
=head2 get_type |
| 1047 |
|
| 1048 |
my $type = get_type($value); |
| 1049 |
|
| 1050 |
Returns one of the core types (C<null>, C<boolean>, C<string>, C<number>, C<object>, C<array>) or |
| 1051 |
C<integer>. Also optionally takes a hashref C<< { legacy_ints => 1 } >> indicating that draft4 number |
| 1052 |
semantics should apply. Behaviour is consistent with L</is_type>. |
| 1053 |
|
| 1054 |
=head2 is_bool |
| 1055 |
|
| 1056 |
if (is_bool($value)) { ... } |
| 1057 |
|
| 1058 |
Equivalent to C<is_type('boolean', $value)>. |
| 1059 |
Accepts JSON booleans and L<builtin> booleans, but not dualvars (because JSON encoders do not |
| 1060 |
recognize these as booleans). |
| 1061 |
|
| 1062 |
=head2 is_schema |
| 1063 |
|
| 1064 |
if (is_schema($value)) { ... } |
| 1065 |
|
| 1066 |
Equivalent to C<is_type('object') || is_type('boolean')>. |
| 1067 |
|
| 1068 |
=head2 is_equal |
| 1069 |
|
| 1070 |
if (not is_equal($x, $y, my $state = {})) { |
| 1071 |
say "values differ starting at $state->{path}: $state->{error}"; |
| 1072 |
} |
| 1073 |
|
| 1074 |
Compares two arbitrary data payloads for equality, as per |
| 1075 |
L<Instance Equality in the JSON Schema draft2020-12 specification|https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.4.2.2>. |
| 1076 |
|
| 1077 |
The optional third argument hashref supports the following fields: |
| 1078 |
|
| 1079 |
=over 4 |
| 1080 |
|
| 1081 |
=item * |
| 1082 |
|
| 1083 |
C<scalarref_booleans> (provided by caller input): as in L<JSON::Schema::Modern/scalarref_booleans> |
| 1084 |
|
| 1085 |
=item * |
| 1086 |
|
| 1087 |
C<stringy_numbers> (provided by caller input): when set, strings will also be compared numerically, as in L<JSON::Schema::Modern/stringy_numbers> |
| 1088 |
|
| 1089 |
=item * |
| 1090 |
|
| 1091 |
C<path> (populated by function): if result is false, the json pointer location of the first difference |
| 1092 |
|
| 1093 |
=item * |
| 1094 |
|
| 1095 |
C<error> (populated by function): if result is false, an error description of the first difference |
| 1096 |
|
| 1097 |
=back |
| 1098 |
|
| 1099 |
=head2 is_elements_unique |
| 1100 |
|
| 1101 |
if (not is_elements_unique($arrayref, my $state = {}) { |
| 1102 |
say "lists differ starting at $state->{path}: $state->{error}"; |
| 1103 |
} |
| 1104 |
|
| 1105 |
Compares all elements of an arrayref for uniqueness. |
| 1106 |
|
| 1107 |
The optional second argument hashref supports the same options as L</is_equal>, plus: |
| 1108 |
|
| 1109 |
=over 4 |
| 1110 |
|
| 1111 |
=item * |
| 1112 |
|
| 1113 |
C<equal_indices> (populated by function): if result is false, the list of indices of the (first set of) equal items found. |
| 1114 |
|
| 1115 |
=back |
| 1116 |
|
| 1117 |
=head2 canonicalize_uri |
| 1118 |
|
| 1119 |
# "https://example.com/schema#/$defs/thing" |
| 1120 |
my $uri = canonicalize_uri($evaluator, "https://example.com/schema#my_anchor_to_thing"); |
| 1121 |
|
| 1122 |
Given a URI to a schema resource, returns the canonical form of this URI. |
| 1123 |
|
| 1124 |
=head2 jsonp |
| 1125 |
|
| 1126 |
# '/paths/~1foo~1{foo_id}/get/responses' |
| 1127 |
my $jsonp = jsonp(qw(/paths /foo/{foo_id} get responses)); |
| 1128 |
|
| 1129 |
Constructs a json pointer string from a list of path components, with correct escaping; the first |
| 1130 |
argument must be C<''> or an already-escaped json pointer, to which the rest of the path components |
| 1131 |
are appended after being escaped. |
| 1132 |
|
| 1133 |
=head2 unjsonp |
| 1134 |
|
| 1135 |
# ('', 'paths', '/foo/{foo_id}', 'get', 'responses') |
| 1136 |
my @components = unjsonp('/paths/~1foo~1{foo_id}/get/responses'); |
| 1137 |
|
| 1138 |
Splits a json pointer string into its path components, with correct unescaping. |
| 1139 |
|
| 1140 |
=head2 jsonp_get |
| 1141 |
|
| 1142 |
# 4 |
| 1143 |
my $val = jsonp_get({ a => 1, b => { c => 3, d => 4 } }, '/b/d'); |
| 1144 |
|
| 1145 |
Returns the value of a data structure at a particular json pointer location. |
| 1146 |
|
| 1147 |
=head2 jsonp_elements |
| 1148 |
|
| 1149 |
# { |
| 1150 |
# '/a/b/0' => 'x', |
| 1151 |
# '/a/b/1' => 'y', |
| 1152 |
# '/a/c/d' => 'e', |
| 1153 |
# } |
| 1154 |
jsonp_elements({ a => { b => [ 'x', 'y' ], c => { d => 'e' } } }); |
| 1155 |
|
| 1156 |
Returns all the ( json pointer => value ) tuples of a data structure as a hashref. |
| 1157 |
|
| 1158 |
=head2 jsonp_set |
| 1159 |
|
| 1160 |
my $data = { a => 1, b => { c => 3, d => 4 } }; |
| 1161 |
my $defaults = { |
| 1162 |
'/b/d' => 5, |
| 1163 |
'/b/e' => 6, |
| 1164 |
'/f' => 7, |
| 1165 |
'/g/h/i/1' => [ 10 ], |
| 1166 |
}; |
| 1167 |
jsonp_set($data, $_, $defaults->{$_}) foreach keys %$defaults; |
| 1168 |
|
| 1169 |
# data is now: |
| 1170 |
# { a => 1, b => { c => 3, d => 5, e => 6 }, f => 7, g => { h => { i => [ undef, [ 10 ] ] } } } |
| 1171 |
|
| 1172 |
Given an arbitrary data structure, a json pointer string, and an arbitrary value, assigns that value |
| 1173 |
to the given position in the data structure. This is a destructive operation, overwriting whatever |
| 1174 |
data was there before if needed (even if an incompatible type: e.g. a hash key will overwrite an |
| 1175 |
existing arrayref). Intermediary keys or indexes will spring into existence as needed. |
| 1176 |
|
| 1177 |
=head2 json_pointer_type |
| 1178 |
|
| 1179 |
A L<Type::Tiny> type representing a json pointer string. |
| 1180 |
|
| 1181 |
=head2 canonical_uri_type |
| 1182 |
|
| 1183 |
A L<Type::Tiny> type representing a canonical URI: a L<Mojo::URL> with either no fragment, or with a |
| 1184 |
json pointer fragment. |
| 1185 |
|
| 1186 |
=head2 core_types_type |
| 1187 |
|
| 1188 |
A L<Type::Tiny> type representing the core JSON Schema types. |
| 1189 |
|
| 1190 |
=head2 core_formats_type |
| 1191 |
|
| 1192 |
A L<Type::Tiny> type representing the core JSON Schema formats (across all supported versions). |
| 1193 |
|
| 1194 |
=head2 load_cached_document |
| 1195 |
|
| 1196 |
my $evaluator = JSON::Schema::Modern->new; |
| 1197 |
my $uri = 'https://json-schema.org/draft-07/schema#'; |
| 1198 |
my $document = load_cached_document($evaluator, $uri); |
| 1199 |
|
| 1200 |
my $result = $evaluator->evaluate($data, $uri); |
| 1201 |
|
| 1202 |
Loads a document object from global cache, loading data from disk if needed. This should only be |
| 1203 |
used for officially-published schemas and metaschemas that are bundled with this distribution or |
| 1204 |
another related one. |
| 1205 |
|
| 1206 |
=head2 add_media_type |
| 1207 |
|
| 1208 |
add_media_type('application/my_zip', $decoder_sub, $encoder_sub); |
| 1209 |
add_media_type('audio/*; version=1', $decoder_sub, $encoder_sub); |
| 1210 |
|
| 1211 |
Adds a media-type entry to the registry, or replaces an existing one. This registry is runtime-global, |
| 1212 |
available to any code running in this process. |
| 1213 |
|
| 1214 |
Either or both of the subrefs are optional (use C<undef> for the decoder sub if you only want an |
| 1215 |
encoder); the subref is expected to have the following signature: |
| 1216 |
|
| 1217 |
sub ($content_ref, $parameters = {}, @) |
| 1218 |
|
| 1219 |
The subref will be called with a reference to the content string, and a hashref of the parameters |
| 1220 |
that were parsed from the C<Content-Type> header (if any). Extra arguments are allowed to allow for |
| 1221 |
future flexibility with this interface. |
| 1222 |
|
| 1223 |
These media types are already defined: |
| 1224 |
|
| 1225 |
=for stopwords WHATWG |
| 1226 |
|
| 1227 |
=over 4 |
| 1228 |
|
| 1229 |
=item * |
| 1230 |
|
| 1231 |
C<application/json> L<(RFC 4627)|https://datatracker.ietf.org/doc/html/rfc4627> |
| 1232 |
|
| 1233 |
=item * |
| 1234 |
|
| 1235 |
C<application/schema+json> L<(proposed definition)|https://json-schema.org/draft/2020-12/json-schema-core.html#name-application-schemajson> |
| 1236 |
|
| 1237 |
=item * |
| 1238 |
|
| 1239 |
C<application/schema-instance+json> L<(proposed definition)|https://json-schema.org/draft/2020-12/json-schema-core.html#name-application-schema-instance> |
| 1240 |
|
| 1241 |
=item * |
| 1242 |
|
| 1243 |
C<application/octet-stream> - passes strings through unchanged |
| 1244 |
|
| 1245 |
=item * |
| 1246 |
|
| 1247 |
C<application/x-www-form-urlencoded> L<(WHATWG)|https://url.spec.whatwg.org/#application/x-www-form-urlencoded> |
| 1248 |
|
| 1249 |
=item * |
| 1250 |
|
| 1251 |
C<application/x-ndjson> L<(spec)|https://github.com/ndjson/ndjson-spec> |
| 1252 |
|
| 1253 |
=item * |
| 1254 |
|
| 1255 |
C<text/*> - passes strings through unchanged; supports the charset parameter |
| 1256 |
|
| 1257 |
=back |
| 1258 |
|
| 1259 |
Media-type definitions can be overridden with a new call to C<add_media_type>. |
| 1260 |
|
| 1261 |
See the official L<OpenAPI Media Type Registry|https://spec.openapis.org/registry/media-type> |
| 1262 |
for a registry of known and useful media types; for |
| 1263 |
compatibility reasons, avoid defining a media type listed here with different semantics. |
| 1264 |
|
| 1265 |
=head2 delete_media_type |
| 1266 |
|
| 1267 |
delete_media_type('application/my_zip'); |
| 1268 |
|
| 1269 |
Removes a media-type entry from the registry. The string must match exactly, including case and |
| 1270 |
whitespace. |
| 1271 |
|
| 1272 |
=head2 decode_media_type |
| 1273 |
|
| 1274 |
my $content_ref = decode_media_type('text/plain; charset=UTF-8', \'encoded text'); |
| 1275 |
|
| 1276 |
Finds the best-matching media-type decoder for the given media-type and decodes the content (which |
| 1277 |
must be passed as a reference); returns a reference to the decoded content, or C<undef> if no |
| 1278 |
matching decoder could be found. An exception might be thrown if the data could not be successfully |
| 1279 |
decoded. |
| 1280 |
|
| 1281 |
=head2 encode_media_type |
| 1282 |
|
| 1283 |
my $content_ref = encode_media_type('text/plain; charset=UTF-8', \[ 'decoded content' ]); |
| 1284 |
|
| 1285 |
Finds the best-matching media-type encoder for the given media-type and encodes the content (which |
| 1286 |
must be passed as a reference); returns a reference to the encoded content, or C<undef> if no |
| 1287 |
matching encoder could be found. An exception might be thrown if the data could not be successfully |
| 1288 |
encoded. |
| 1289 |
|
| 1290 |
=head2 match_media_type |
| 1291 |
|
| 1292 |
my $registered_media_type = match_media_type('text/html'); |
| 1293 |
my $ad_hoc_media_type = match_media_type('text/html', [ 'text/plain', 'text/*' ]); |
| 1294 |
|
| 1295 |
Finds the best match for a C<Content-Type> header value from the media-types in the registry, |
| 1296 |
or from an ad-hoc list reference provided in the second argument. |
| 1297 |
|
| 1298 |
Types with structured suffixes will match more generic types when an exact match is not available |
| 1299 |
(e.g. C<application/schema+json> will match an entry for C<application/json>). |
| 1300 |
|
| 1301 |
Exact matches to the C<type/subtype> name are preferred over wildcard matches (e.g. C<text/*>); |
| 1302 |
if parameters are present in the value being matched against (the list of registered media-types, |
| 1303 |
or the list provided to this sub), all parameters must be present and match exactly. |
| 1304 |
|
| 1305 |
Comparisons of type and subtype are done case-insensitively; parameter comparison is case-sensitive, |
| 1306 |
with the exception of C<charset> in C<text/plain>. |
| 1307 |
|
| 1308 |
=head1 GIVING THANKS |
| 1309 |
|
| 1310 |
=for stopwords MetaCPAN GitHub |
| 1311 |
|
| 1312 |
If you found this module to be useful, please show your appreciation by |
| 1313 |
adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern> |
| 1314 |
and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>. |
| 1315 |
|
| 1316 |
=head1 SUPPORT |
| 1317 |
|
| 1318 |
Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>. |
| 1319 |
|
| 1320 |
I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>. |
| 1321 |
|
| 1322 |
=for stopwords OpenAPI |
| 1323 |
|
| 1324 |
You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack |
| 1325 |
server|https://open-api.slack.com>, which are also great resources for finding help. |
| 1326 |
|
| 1327 |
=head1 AUTHOR |
| 1328 |
|
| 1329 |
Karen Etheridge <[email protected]> |
| 1330 |
|
| 1331 |
=head1 COPYRIGHT AND LICENCE |
| 1332 |
|
| 1333 |
This software is copyright (c) 2020 by Karen Etheridge. |
| 1334 |
|
| 1335 |
This is free software; you can redistribute it and/or modify it under |
| 1336 |
the same terms as the Perl 5 programming language system itself. |
| 1337 |
|
| 1338 |
Some schema files have their own licence, in share/LICENSE. |
| 1339 |
|
| 1340 |
=cut |