blib/lib/JSON/Schema/Validate.pm untested

filter: Statementstmt 0.0% 0 / 1898 Branchbran 0.0% 0 / 1242 Conditioncond 0.0% 0 / 677 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 120 Podpod 0.0% 0 / 92 totaltotal 0.0% 0 / 4029 CC 622 SCAR 76.5
CC
622
Cov
0%
_compile_node
6006.0
_compile_js_node
5550.0
register_builtin_formats
4830.0
CRAP 2106.6
1 ##----------------------------------------------------------------------------
2 ## JSON Schema Validator - ~/lib/JSON/Schema/Validate.pm
3 ## Version v0.9.0
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2025/11/07
7 ## Modified 2026/03/01
8 ## All rights reserved
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package JSON::Schema::Validate;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 use warnings::register;
20 use vars qw( $VERSION $DEBUG );
21 use B ();
22 use JSON ();
23 use Scalar::Util qw( blessed looks_like_number reftype refaddr );
24 use List::Util qw( first any all );
25 use Encode ();
26 our $VERSION = 'v0.9.0';
27 };
28  
29 use v5.16.0;
30 use strict;
31 use warnings;
32  
33 sub new
34 {
35 my $class = shift( @_ );
36 my $schema = shift( @_ );
37 if( defined( $schema ) && ( !ref( $schema ) || ref( $schema ) ne 'HASH' ) )
38 {
39 die( "You provided a value (", overload::StrVal( $schema ), "), but it is not an hash reference. You must create a new $class object like this: $class->new( \$schema, \%opts );" );
40 }
41  
42 my $self =
43 {
44 comment_handler => undef,
45 # boolean
46 compile_on => 0,
47 # { schema, anchors, id_index, base }
48 compiled => undef,
49 # boolean; when 0, failures don’t invalidate; when 1, they do
50 content_assert => 0,
51 content_decoders => {},
52 errors => [],
53 # boolean; when true, then non-standard extensions are enabled.
54 extensions => 0,
55 formats => {},
56 # boolean
57 ignore_req_vocab => 0,
58 last_error => '',
59 last_trace => [],
60 max_errors => 200,
61 media_validators => {},
62 # boolean
63 normalize_instance => 1,
64 # boolean: when true, prune unknown properties before validate()
65 prune_unknown => 0,
66 # ($abs_uri) -> $schema_hashref
67 resolver => undef,
68 schema => _clone( $schema ),
69 # 0 = unlimited
70 trace_limit => 0,
71 # boolean
72 trace_on => 0,
73 # 0 = record all
74 trace_sample => 0,
75 # boolean; when true, 'uniqueKeys' extension is enabled.
76 unique_keys => 0,
77 # internal boolean; not an option
78 vocab_checked => 0,
79 vocab_support => {},
80 };
81  
82 bless( $self, $class );
83 my $opts = $self->_get_args_as_hash( @_ );
84 my @bool_options = qw(
85 content_assert
86 extensions
87 ignore_req_vocab
88 normalize_instance
89 prune_unknown
90 unique_keys
91 );
92 foreach my $opt ( @bool_options )
93 {
94 next unless( exists( $opts->{ $opt } ) );
95 $self->{ $opt } = $opts->{ $opt } ? 1 : 0
96 }
97 # Make sure the boolean value for 'extensions' is propagated to 'unique_keys' unless the option 'unique_keys' has been explicitly specified, and then we do not want to overwrite it.
98 $self->{unique_keys} = $self->{extensions} unless( exists( $opts->{unique_keys} ) );
99 if( exists( $opts->{ignore_unknown_required_vocab} ) )
100 {
101 $self->{ignore_req_vocab} = $opts->{ignore_unknown_required_vocab} ? 1 : 0;
102 }
103 if( exists( $opts->{compile} ) )
104 {
105 $self->{compile_on} = $opts->{compile} ? 1 : 0;
106 }
107 if( exists( $opts->{trace} ) )
108 {
109 $self->{trace_on} = $opts->{trace} ? 1 : 0;
110 }
111  
112 my @other_options = qw( max_errors trace_limit );
113 foreach my $opt ( @other_options )
114 {
115 next unless( exists( $opts->{ $opt } ) );
116 $self->{ $opt } = $opts->{ $opt };
117 }
118  
119 if( exists( $opts->{trace_sample} ) )
120 {
121 # Check for percentage integer (0 to 100)
122 if( $opts->{trace_sample} =~ /^([0-9]{1,2}|100)$/ )
123 {
124 $self->{trace_sample} = $opts->{trace_sample};
125 }
126 else
127 {
128 warn( "Warning only: invalid value for option 'trace_sample'." ) if( warnings::enabled() );
129 }
130 }
131  
132 # User-supplied format callbacks (override precedence left to caller order)
133 if( $opts->{format} && ref( $opts->{format} ) eq 'HASH' )
134 {
135 $self->{formats}->{ $_ } = $opts->{format}->{ $_ } for( keys( %{$opts->{format}} ) );
136 }
137 $self->{vocab_support} = $opts->{vocab_support} ? { %{$opts->{vocab_support}} } : {};
138  
139 $self->_check_vocabulary_required unless( $self->{ignore_req_vocab} );
140 $self->_register_builtin_media_validators() if( $self->{content_assert} );
141 $self->{compiled} = _compile_root( $self->{schema} ) if( $self->{compile_on} );
142 return( $self );
143 }
144  
145 # $js->compile -> enables it
146 # $js->compile(1) -> enables it
147 # $js->compile(0) -> disables it
148 sub compile
149 {
150 my( $self, $bool ) = @_;
151 my $on = defined( $bool ) ? $bool : 1;
152 $self->{compile_on} = $on;
153  
154 if( $self->{compile_on} && !$self->{compiled} )
155 {
156 $self->{compiled} = _compile_root( $self->{schema} );
157 }
158 return( $self );
159 }
160  
161 sub compile_js
162 {
163 my $self = shift( @_ );
164 my $opts = $self->_get_args_as_hash( @_ );
165  
166 my $schema = $self->{schema}
167 or die( "No schema loaded; cannot compile to JavaScript" );
168  
169 # Public JS API name, e.g. "validateIncorporation"
170 my $name = exists( $opts->{name} ) && defined( $opts->{name} ) && length( $opts->{name} )
171 ? $opts->{name}
172 : 'validate';
173  
174 # Max errors to collect on the client side
175 my $max_errors = exists( $opts->{max_errors} ) ? int( $opts->{max_errors} ) : 200;
176 $max_errors = 0 if( $max_errors < 0 );
177  
178 my %seen; # schema_pointer -> function name
179 my $counter = 0; # for generating unique function names
180 my @funcs; # accumulated JS validator functions
181  
182 my $root_ptr = '#';
183  
184 # Pass $opts down so we can see ecma => ... inside the compiler.
185 my $root_fn = $self->_compile_js_node( $schema, $root_ptr, \%seen, \@funcs, \$counter, $schema, $opts );
186  
187 my $js = '';
188  
189 $js .= <<'JS_RUNTIME';
190 (function(global)
191 {
192 "use strict";
193  
194 function _jsv_err(ctx, path, keyword, message, schemaPtr)
195 {
196 if(ctx.maxErrors && ctx.errors.length >= ctx.maxErrors)
197 {
198 return;
199 }
200 ctx.errors.push({
201 path: path,
202 keyword: keyword,
203 message: message,
204 schema_pointer: schemaPtr
205 });
206 }
207  
208 function _jsv_typeOf(x)
209 {
210 if(x === null)
211 {
212 return "null";
213 }
214 if(Array.isArray ? Array.isArray(x) : Object.prototype.toString.call(x) === "[object Array]")
215 {
216 return "array";
217 }
218 var t = typeof x;
219 if(t === "number" && isFinite(x) && Math.floor(x) === x)
220 {
221 // distinguish "integer" for convenience
222 return "integer";
223 }
224 return t;
225 }
226  
227 function _jsv_hasOwn(obj, prop)
228 {
229 return Object.prototype.hasOwnProperty.call(obj, prop);
230 }
231  
232 JS_RUNTIME
233  
234 # Public entry point
235 $js .= <<"JS_RUNTIME";
236 function $name(instance)
237 {
238 var ctx = { errors: [], maxErrors: $max_errors };
239 $root_fn(instance, "#", ctx);
240 return ctx.errors;
241 }
242  
243 JS_RUNTIME
244  
245 # Attach to global (browser: window) in a conservative way
246 $js .= <<"JS_RUNTIME";
247 if(typeof global === 'object' && global)
248 {
249 global.$name = $name;
250 }
251  
252 JS_RUNTIME
253  
254 # Emit all compiled validator functions, indented one level
255 $js .= join( "\n\n", map{ ' ' . join( "\n ", split( /\n/, $_ ) ) } @funcs );
256  
257 $js .= <<'JS_RUNTIME';
258  
259 })(this);
260 JS_RUNTIME
261  
262 return( $js );
263 }
264  
265 # $js->content_checks -> enables it
266 # $js->content_checks(1) -> enables it
267 # $js->content_checks(0) -> disables it
268 sub content_checks
269 {
270 my( $self, $bool ) = @_;
271 my $on = defined( $bool ) ? $bool : 1;
272 $self->{content_assert} = $on ? 1 : 0;
273 $self->_register_builtin_media_validators() if( $self->{content_assert} );
274 return( $self );
275 }
276  
277 # TODO: Backward compatibility, but need to remove it
278 {
279 no warnings 'once';
280 *enable_content_checks = \&content_checks;
281 }
282  
283 sub error { $_[0]->{last_error} }
284  
285 # We return a copy of the array reference containing the error objects
286 sub errors { return( [@{$_[0]->{errors}}] ); }
287  
288 sub extensions
289 {
290 my( $self, $bool ) = @_;
291 my $on = defined( $bool ) ? $bool : 1;
292 $self->{extensions} = $on;
293 $self->unique_keys( $on );
294 return( $self );
295 }
296  
297 sub get_trace
298 {
299 my( $self ) = @_;
300 return( [@{ $self->{last_trace} || [] }] );
301 }
302  
303 # Accessor-only method. See trace_limit for its mutator alter ego.
304 sub get_trace_limit { 0 + ( $_[0]->{trace_limit} // 0 ) }
305  
306 # $js->ignore_unknown_required_vocab -> enables it
307 # $js->ignore_unknown_required_vocab(1) -> enables it
308 # $js->ignore_unknown_required_vocab(0) -> disables it
309 sub ignore_unknown_required_vocab
310 {
311 my( $self, $bool ) = @_;
312 my $on = defined( $bool ) ? $bool : 1;
313 $self->{ignore_req_vocab} = $on;
314 return( $self );
315 }
316  
317 sub is_compile_enabled { $_[0]->{compile_on} ? 1 : 0 }
318  
319 sub is_content_checks_enabled { $_[0]->{content_assert} ? 1 : 0 }
320  
321 # Accessor only method. See trace or the mutator vession.
322 sub is_trace_on { $_[0]->{trace_on} ? 1 : 0 }
323  
324 sub is_unique_keys_enabled { $_[0]->{unique_keys} ? 1 : 0 }
325  
326 sub is_unknown_required_vocab_ignored { $_[0]->{ignore_req_vocab} ? 1 : 0 }
327  
328 sub is_valid
329 {
330 my $self = shift( @_ );
331 my $data = shift( @_ );
332  
333 my $opts = $self->_get_args_as_hash( @_ );
334 # Optional: allow overriding max_errors for this call only
335 # (e.g. $v->is_valid( $data, max_errors => 1 );)
336 $opts->{max_errors} //= 1;
337  
338 # validate already populates $self->{errors}; is_valid just returns boolean
339 return( $self->validate( $data, $opts ) ? 1 : 0 );
340 }
341  
342 # Example:
343 # my $pruned = $js->prune_instance( $incoming_data );
344 sub prune_instance
345 {
346 my( $self, $data ) = @_;
347  
348 # Work on a cloned copy if normalize_instance is on,
349 # to remain consistent with validate().
350 if( $self->{normalize_instance} )
351 {
352 $data = _clone( $data );
353 }
354  
355 return( $self->_prune_with_schema( $self->{schema}, $data ) );
356 }
357  
358 sub prune_unknown
359 {
360 my( $self, $bool ) = @_;
361 my $on = defined( $bool ) ? $bool : 1;
362 $self->{prune_unknown} = $on ? 1 : 0;
363 return( $self );
364 }
365  
366 sub register_builtin_formats
367 {
368 my( $self ) = @_;
369  
370 local $@;
371 my $has_iso = eval{ require DateTime::Format::ISO8601; 1 } ? 1 : 0;
372 my $has_tp = eval{ require Time::Piece; 1 } ? 1 : 0;
373 my $has_dt = eval{ require DateTime; 1 } ? 1 : 0;
374 my $has_idn = eval{ require Net::IDN::Encode; 1 } ? 1 : 0;
375 # perl -MRegexp::Common=Email::Address -lE 'say $Regexp::Common::RE{Email}{Address}'
376 state $email_re = qr/\A(?:(?^u:(?:(?^u:(?>(?^u:(?^u:(?>(?^u:(?>(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*))|\.|\s*"(?^u:(?^u:[^\\"])|(?^u:\\(?^u:[^\x0A\x0D])))+"\s*))+))|(?>(?^u:(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*))|(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*"(?^u:(?^u:[^\\"])|(?^u:\\(?^u:[^\x0A\x0D])))*"(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*)))+))?)(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*<(?^u:(?^u:(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*(?^u:(?>[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+(?:\.[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+)*))(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*))|(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*"(?^u:(?^u:[^\\"])|(?^u:\\(?^u:[^\x0A\x0D])))*"(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*)))\@(?^u:(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*(?^u:(?>[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+(?:\.[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+)*))(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*))|(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*\[(?:\s*(?^u:(?^u:[^\[\]\\])|(?^u:\\(?^u:[^\x0A\x0D]))))*\s*\](?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*))))>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*)))|(?^u:(?^u:(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*(?^u:(?>[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+(?:\.[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+)*))(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*))|(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*"(?^u:(?^u:[^\\"])|(?^u:\\(?^u:[^\x0A\x0D])))*"(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*)))\@(?^u:(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*(?^u:(?>[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+(?:\.[^\x00-\x1F\x7F()<>\[\]:;@\\,."\s]+)*))(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*))|(?^u:(?>(?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*\[(?:\s*(?^u:(?^u:[^\[\]\\])|(?^u:\\(?^u:[^\x0A\x0D]))))*\s*\](?^u:(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))|(?>\s+))*)))))(?>(?^u:(?>\s*\((?:\s*(?^u:(?^u:(?>[^()\\]+))|(?^u:\\(?^u:[^\x0A\x0D]))|))*\s*\)\s*))*)))\z/;
377  
378 my %F;
379  
380 # RFC3339 date-time / date / time
381 $F{'date-time'} = sub
382 {
383 my( $s ) = @_;
384 return(0) unless( defined( $s ) && !ref( $s ) );
385  
386 # Preferred path when DateTime::Format::ISO8601 is available
387 if( $has_iso )
388 {
389 return( eval{ DateTime::Format::ISO8601->parse_datetime( $s ) ? 1 : 0 } ? 1 : 0 );
390 }
391  
392 # YYYY-MM-DDThh:mm:ss[.fraction](Z|±hh:mm)
393 return(0) unless( $s =~ /\A
394 (\d{4})-(\d{2})-(\d{2}) # date
395 T
396 (\d{2}):(\d{2}):(\d{2}) # time
397 (?:\.\d+)? # optional fraction
398 (?:Z|[+\-]\d{2}:\d{2}) # offset
399 \z/x );
400  
401 my( $y, $m, $d, $H, $M, $S ) = ( $1, $2, $3, $4, $5, $6 );
402  
403 # Time::Piece is a core module (available since perl 5.10): use it first
404 if( $has_tp )
405 {
406 # strptime validates calendar correctness (e.g. rejects Feb 30)
407 # We feed it the bare datetime without offset/fraction (already captured above)
408 my $bare = sprintf( '%04d-%02d-%02dT%02d:%02d:%02d', $y, $m, $d, $H, $M, $S );
409 return( eval{ Time::Piece->strptime( $bare, '%Y-%m-%dT%H:%M:%S' ); 1 } ? 1 : 0 );
410 }
411  
412 # Fall back to DateTime if available
413 if( $has_dt )
414 {
415 return( eval
416 {
417 DateTime->new(
418 year => $y,
419 month => $m,
420 day => $d,
421 hour => $H,
422 minute => $M,
423 second => $S
424 );
425 1
426 } ? 1 : 0 );
427 }
428  
429 # Last resort: the regex above was already sufficient for structural checks
430 return(1);
431 };
432  
433 $F{'date'} = sub
434 {
435 my( $s ) = @_;
436 return(0) unless( defined( $s ) && !ref( $s ) );
437 return(0) unless( $s =~ /\A(\d{4})-(\d{2})-(\d{2})\z/ );
438 my( $y, $m, $d ) = ( $1, $2, $3 );
439  
440 # Time::Piece is core — prefer it
441 if( $has_tp )
442 {
443 return( eval{ Time::Piece->strptime( $s, '%Y-%m-%d' ); 1 } ? 1 : 0 );
444 }
445  
446 # Fall back to DateTime if available
447 if( $has_dt )
448 {
449 return( eval{ DateTime->new( year => $y, month => $m, day => $d ); 1 } ? 1 : 0 );
450 }
451  
452 # Last resort: structural regex already passed above
453 return(1);
454 };
455  
456 $F{'time'} = sub
457 {
458 my( $s ) = @_;
459 return(0) unless( defined( $s ) && !ref( $s ) );
460 if( $has_iso )
461 {
462 return eval{ DateTime::Format::ISO8601->parse_datetime( "1970-01-01T$s" ) ? 1 : 0 } ? 1 : 0;
463 }
464 return $s =~ /\A
465 (?:[01]\d|2[0-3]) # HH
466 :
467 (?:[0-5]\d) # MM
468 :
469 (?:[0-5]\d) # SS
470 (?:\.\d+)? # .fraction
471 (?:Z|[+\-](?:[01]\d|2[0-3]):[0-5]\d)? # offset
472 \z/x ? 1 : 0;
473 };
474  
475 # Duration (RFC 3339 §5.6 / ISO 8601)
476 # Valid: P1Y, P3M, P1Y2M3DT4H5M6S, PT10S, P1W
477 # Invalid: P, PT, P1Y2M3DT (T with nothing after it, or no designator at all)
478 $F{'duration'} = sub
479 {
480 my( $s ) = @_;
481 return(0) unless( defined( $s ) && !ref( $s ) );
482  
483 # Week form: PnW (stands alone; no mixing with other designators per ISO 8601)
484 return(1) if( $s =~ /\AP\d+W\z/ );
485  
486 # Full form: at least one date *or* time component must be present
487 # The T separator must be followed by at least one time designator
488 return( $s =~ /\A
489 P
490 (?:(\d+)Y)?
491 (?:(\d+)M)?
492 (?:(\d+)D)?
493 (?:T
494 (?=\d) # T must be followed by at least one digit
495 (?:(\d+)H)?
496 (?:(\d+)M)?
497 (?:(\d+(?:\.\d+)?)S)?
498 )?
499 \z/x && ( defined($1) || defined($2) || defined($3) || defined($4) || defined($5) || defined($6) )
500 ? 1 : 0 );
501 };
502  
503 # Email / IDN email
504 # Plain email (ASCII) — unchanged
505 $F{'email'} = sub
506 {
507 my( $s ) = @_;
508 return(0) unless( defined( $s ) && !ref( $s ) );
509 return( $s =~ $email_re ? 1 : 0 );
510 };
511  
512 # IDN email: punycode the domain, validate with same regex
513 $F{'idn-email'} = sub
514 {
515 my( $s ) = @_;
516 return(0) unless( defined( $s ) && !ref( $s ) );
517 return(0) unless( $s =~ /\A(.+)\@(.+)\z/s ); # keep local-part as-is (EAI allows UTF-8)
518 my( $local, $domain ) = ( $1, $2 );
519  
520 if( $has_idn )
521 {
522 local $@;
523 my $ascii = eval{ Net::IDN::Encode::domain_to_ascii( $domain ) };
524 return(0) unless( defined( $ascii ) && length( $ascii ) );
525  
526 my $candidate = "$local\@$ascii";
527 return( $candidate =~ $email_re ? 1 : 0 );
528 }
529  
530 # Fallback: if the domain already *looks* ASCII, validate directly
531 if( $domain =~ /\A[[:ascii:]]+\z/ )
532 {
533 my $candidate = "$local\@$domain";
534 return( $candidate =~ $email_re ? 1 : 0 );
535 }
536  
537 # Without IDN module, fall back to permissive Unicode domain check + ASCII regex
538 return(0);
539 };
540  
541 # Hostnames
542 $F{'hostname'} = sub
543 {
544 my( $s ) = @_;
545 return(0) unless( defined( $s ) && !ref( $s ) );
546 return(0) if( length( $s ) > 253 );
547 for my $label ( split( /\./, $s ) )
548 {
549 return(0) unless( length( $label ) >= 1 && length( $label ) <= 63 );
550 return(0) unless( $label =~ /\A[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?\z/ );
551 }
552 return(1);
553 };
554  
555 $F{'idn-hostname'} = sub
556 {
557 my( $s ) = @_;
558 return(0) unless( defined( $s ) && !ref( $s ) );
559 if( $has_idn )
560 {
561 local $@;
562 my $ascii = eval{ Net::IDN::Encode::domain_to_ascii( $s ) };
563 return(0) unless( defined( $ascii ) && length( $ascii ) );
564 return( $F{'hostname'}->( $ascii ) ? 1 : 0 );
565 }
566  
567 # Fallback: permissive Unicode label check (as you had), then ASCII hostname rule
568 return(0) if( length( $s ) > 253 );
569 for my $label ( split( /\./, $s ) )
570 {
571 return(0) unless( length( $label ) >= 1 && length( $label ) <= 63 );
572 return(0) unless( $label =~ /\A[[:alnum:]\pL\pN](?:[[:alnum:]\pL\pN\-]*[[:alnum:]\pL\pN])?\z/u );
573 }
574 return(1);
575 };
576  
577 # IP addresses
578 $F{'ipv4'} = sub
579 {
580 my( $s ) = @_;
581 return(0) unless( defined( $s ) && !ref( $s ) );
582 return $s =~ /\A
583 (25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.
584 (25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.
585 (25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.
586 (25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)
587 \z/x ? 1 : 0;
588 };
589  
590 $F{'ipv6'} = sub
591 {
592 my( $s ) = @_;
593 return(0) unless( defined( $s ) && !ref( $s ) );
594 return $s =~ /\A
595 (?: (?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}
596 | (?:[0-9A-Fa-f]{1,4}:){1,7}:
597 | (?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}
598 | (?:[0-9A-Fa-f]{1,4}:){1,5}(?::[0-9A-Fa-f]{1,4}){1,2}
599 | (?:[0-9A-Fa-f]{1,4}:){1,4}(?::[0-9A-Fa-f]{1,4}){1,3}
600 | (?:[0-9A-Fa-f]{1,4}:){1,3}(?::[0-9A-Fa-f]{1,4}){1,4}
601 | (?:[0-9A-Fa-f]{1,4}:){1,2}(?::[0-9A-Fa-f]{1,4}){1,5}
602 | [0-9A-Fa-f]{1,4}:(?:(?::[0-9A-Fa-f]{1,4}){1,6})
603 | :(?:(?::[0-9A-Fa-f]{1,4}){1,7}|:)
604 | (?:[0-9A-Fa-f]{1,4}:){6}
605 (?:\d{1,3}\.){3}\d{1,3}
606 | ::(?:[0-9A-Fa-f]{1,4}:){0,5}
607 (?:\d{1,3}\.){3}\d{1,3}
608 | (?:[0-9A-Fa-f]{1,4}:){1,5}:
609 (?:\d{1,3}\.){3}\d{1,3}
610 )
611 \z/x ? 1 : 0;
612 };
613  
614 # URI/IRI
615 $F{'uri'} = sub
616 {
617 my( $s ) = @_;
618 return(0) unless( defined( $s ) && !ref( $s ) );
619 return( $s =~ /\A[A-Za-z][A-Za-z0-9+\-.]*:[^\s]+\z/ ? 1 : 0 );
620 };
621  
622 $F{'uri-reference'} = sub
623 {
624 my( $s ) = @_;
625 return(0) unless( defined( $s ) && !ref( $s ) );
626 return( $s =~ /\A(?:[A-Za-z][A-Za-z0-9+\-.]*:)?[^\s]+\z/ ? 1 : 0 );
627 };
628  
629 $F{'iri'} = sub
630 {
631 my( $s ) = @_;
632 return(0) unless( defined( $s ) && !ref( $s ) );
633 # Must have a scheme (letters followed by colon) per RFC 3987 §2.2
634 # Scheme: ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
635 # After scheme: at least one non-whitespace character
636 return( $s =~ /\A[A-Za-z][A-Za-z0-9+\-.]*:[^\s]+\z/u ? 1 : 0 );
637 };
638  
639 # UUID
640 $F{'uuid'} = sub
641 {
642 my( $s ) = @_;
643 return(0) unless( defined( $s ) && !ref( $s ) );
644 return( $s =~ /\A[a-fA-F0-9]{8}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{12}\z/ ? 1 : 0 );
645 };
646  
647 # JSON Pointer / Relative JSON Pointer
648 $F{'json-pointer'} = sub
649 {
650 my( $s ) = @_;
651 return(0) unless( defined( $s ) && !ref( $s ) );
652 return(1) if( $s eq '' );
653 return( $s =~ m{\A/(?:[^~/]|~[01])*(?:/(?:[^~/]|~[01])*)*\z} ? 1 : 0 );
654 };
655  
656 $F{'relative-json-pointer'} = sub
657 {
658 my( $s ) = @_;
659 return(0) unless( defined( $s ) && !ref( $s ) );
660 return(1) if( $s =~ /\A0\z/ );
661 return( $s =~ m,\A[1-9]\d*(?:#|(?:/(?:[^~/]|~[01])*)*)\z, ? 1 : 0 );
662 };
663  
664 # Regex
665 $F{'regex'} = sub
666 {
667 my( $s ) = @_;
668 return(0) unless( defined( $s ) && !ref( $s ) );
669 local $@;
670 return( eval{ "" =~ /$s/; 1 } ? 1 : 0 );
671 };
672  
673 while( my( $k, $v ) = each( %F ) )
674 {
675 $self->{formats}->{ $k } = $v unless( exists( $self->{formats}->{ $k } ) );
676 }
677  
678 return( $self );
679 }
680  
681 sub register_content_decoder
682 {
683 my( $self, $name, $cb ) = @_;
684 if( ref( $cb ) eq 'CODE' )
685 {
686 $self->{content_decoders}->{ lc( "$name" ) } = $cb;
687 }
688 else
689 {
690 die( "content decoder must be a code reference" );
691 }
692 return( $self );
693 }
694  
695 sub register_format
696 {
697 my( $self, $name, $code ) = @_;
698 die( "format name required" ) unless( defined( $name ) && length( $name ) );
699 die( "format validator must be a coderef" ) unless( ref( $code ) eq 'CODE' );
700 $self->{formats}->{ $name } = $code;
701 return( $self );
702 }
703  
704 sub register_media_validator
705 {
706 my( $self, $type, $cb ) = @_;
707 if( ref( $cb ) eq 'CODE' )
708 {
709 $self->{media_validators}->{ lc( "$type" ) } = $cb;
710 }
711 else
712 {
713 die( "media validator must be a code reference" );
714 }
715 return( $self );
716 }
717  
718 sub set_comment_handler
719 {
720 my( $self, $code ) = @_;
721 if( @_ > 1 )
722 {
723 if( defined( $code ) && ref( $code ) ne 'CODE' )
724 {
725 warn( "Warning only: the handler provided is not a code reference." ) if( warnings::enabled() );
726 return( $self );
727 }
728 $self->{comment_handler} = $code;
729 }
730 return( $self );
731 }
732  
733 sub set_resolver
734 {
735 my( $self, $code ) = @_;
736 if( @_ > 1 )
737 {
738 if( defined( $code ) && ref( $code ) ne 'CODE' )
739 {
740 warn( "Warning only: the handler provided is not a code reference." ) if( warnings::enabled() );
741 return( $self );
742 }
743 $self->{resolver} = $code;
744 }
745 return( $self );
746 }
747  
748 sub set_vocabulary_support
749 {
750 my( $self, $h ) = @_;
751 $self->{vocab_support} = { %{ $h || {} } };
752 $self->{vocab_checked} = 0;
753 return( $self );
754 }
755  
756 # This is a mutator only method
757 # $js->trace -> enables it
758 # $js->trace(1) -> enables it
759 # $js->trace(0) -> disables it
760 # Always returns the object
761 # See is_trace_on for the accessor method
762 sub trace
763 {
764 my( $self, $bool ) = @_;
765 my $on = defined( $bool ) ? $bool : 1;
766 $self->{trace_on} = $on;
767 return( $self );
768 }
769  
770 sub trace_limit
771 {
772 my( $self, $n ) = @_;
773 $self->{trace_limit} = 0 + ( $n || 0 );
774 return( $self );
775 }
776  
777 sub trace_sample
778 {
779 my( $self, $pct ) = @_;
780 $self->{trace_sample} = 0 + ( $pct || 0 );
781 return( $self );
782 }
783  
784 sub unique_keys
785 {
786 my( $self, $bool ) = @_;
787 my $on = defined( $bool ) ? $bool : 1;
788 $self->{unique_keys} = $on;
789 return( $self );
790 }
791  
792 sub validate
793 {
794 my $self = shift( @_ );
795 my $data = shift( @_ );
796 my $opts = $self->_get_args_as_hash( @_ );
797  
798 $self->{errors} = [];
799 $self->{last_error} = '';
800  
801 # Ensure we have the compiled root (indexing/anchors) even in lazy mode
802 $self->{compiled} = _compile_root( $self->{schema} ) unless( $self->{compiled} );
803  
804 # One-time $vocabulary check (Draft 2020-12)
805 if( !$self->{vocab_checked} )
806 {
807 my $root = $self->{schema};
808 if( ref( $root ) eq 'HASH' &&
809 ref( $root->{'$vocabulary'} ) eq 'HASH' )
810 {
811 my $decl = $root->{'$vocabulary'}; # { uri => JSON::true|false, ... }
812 my $support = $self->{vocab_support} || {};
813 for my $uri ( keys( %$decl ) )
814 {
815 next unless( $decl->{ $uri } ); # only enforce for required=true
816 next if( $support->{ $uri } ); # caller says it's supported
817 unless( $self->{ignore_req_vocab} )
818 {
819 die( "Required vocabulary not supported: $uri" );
820 }
821 }
822 }
823 $self->{vocab_checked} = 1;
824 }
825  
826 # Because Perl scalar are not JSON scalar, we force the Perl structure into strict JSON types, eliminating all Perl duality and guaranteeing predictable validation semantics.
827 if( $self->{normalize_instance} )
828 {
829 $data = _clone( $data );
830 }
831  
832 # Optional pre-validation pruning of unknown properties / nested objects.
833 # This only happens if explicitly enabled via prune_unknown => 1.
834 if( $self->{prune_unknown} )
835 {
836 $data = $self->_prune_with_schema( $self->{schema}, $data );
837 }
838  
839 my $ctx =
840 {
841 root => $self->{compiled},
842 instance_root => $data,
843 resolver => $self->{resolver},
844 formats => $self->{formats},
845 errors => $self->{errors},
846 max_errors => ( ( defined( $opts->{max_errors} ) && $opts->{max_errors} =~ /^\d+$/ ) ? $opts->{max_errors} : $self->{max_errors} ),
847 error_count => 0,
848  
849 # paths / recursion
850 ptr_stack => ['#'],
851 id_stack => [ $self->{compiled}->{base} ],
852 dyn_stack => [ {} ], # dynamicAnchor scope frames
853 visited => {}, # "schema_ptr|inst_addr" => 1
854  
855 # annotation (for unevaluated*)
856 ann_mode => 1,
857 compile_on => ( defined( $opts->{compile_on} ) ? ( $opts->{compile_on} ? 1 : 0 ) : ( $self->{compile_on} ? 1 : 0 ) ),
858  
859 # trace
860 trace_on => ( defined( $opts->{trace_on} ) ? ( $opts->{trace_on} ? 1 : 0 ) : ( $self->{trace_on} ? 1 : 0 ) ),
861 trace_sample => $self->{trace_sample} || 0,
862 trace_limit => ( defined( $opts->{trace_limit} ) && $opts->{trace_limit} =~ /^\d+$/ ) ? $opts->{trace_limit} : ( $self->{trace_limit} || 0 ),
863 trace => [],
864  
865 # content assertion & helpers
866 content_assert => ( defined( $opts->{content_assert} ) ? ( $opts->{content_assert} ? 1 : 0 ) : ( $self->{content_assert} ? 1 : 0 ) ),
867 media_validators => $self->{media_validators},
868 content_decoders => $self->{content_decoders},
869  
870 comment_handler => $self->{comment_handler},
871  
872 # extensions
873 unique_keys => $self->{unique_keys},
874 extensions => $self->{extensions},
875 };
876  
877 # Guarantee at least one trace entry when trace is enabled
878 if( $ctx->{trace_on} )
879 {
880 push( @{$ctx->{trace}},
881 {
882 schema_ptr => '#',
883 keyword => 'validate',
884 inst_path => '#',
885 outcome => 'start',
886 note => 'start',
887 });
888 }
889  
890 my $res = _v( $ctx, '#', $self->{compiled}->{schema}, $data );
891  
892 $self->{last_trace} = $ctx->{trace};
893  
894 if( !$res->{ok} )
895 {
896 # $self->{last_error} = _first_error_text( $self->{errors} );
897 $self->{last_error} = scalar( @{$self->{errors}} ) ? $self->{errors}->[0] : '';
898 return(0);
899 }
900 return(1);
901 }
902  
903 sub _apply_dynamic_ref
904 {
905 my( $ctx, $schema_ptr, $ref, $inst ) = @_;
906  
907 if( $ref =~ /\#(.+)\z/ )
908 {
909 my $name = $1;
910 for( my $i = $#{ $ctx->{dyn_stack} }; $i >= 0; $i-- )
911 {
912 my $frame = $ctx->{dyn_stack}->[$i];
913 if( my $node = $frame->{ $name } )
914 {
915 my $sp = _ptr_of_node( $ctx->{root}, $node );
916 return( _v( $ctx, $sp, $node, $inst ) );
917 }
918 }
919 }
920  
921 return( _apply_ref( $ctx, $schema_ptr, $ref, $inst ) );
922 }
923  
924 # $ref and $dynamicRef
925 sub _apply_ref
926 {
927 my( $ctx, $schema_ptr, $ref, $inst ) = @_;
928  
929 my $base = $ctx->{id_stack}->[-1];
930 my $abs = _resolve_uri( $base, $ref );
931  
932 # Direct absolute ID/anchor hit
933 if( my $node = $ctx->{root}->{id_index}->{ $abs } )
934 {
935 my $sp = _ptr_of_node( $ctx->{root}, $node );
936 return( _v( $ctx, $sp, $node, $inst ) );
937 }
938  
939 # Local fragment
940 if( $ref =~ /^\#/ )
941 {
942 # 1) Try anchors (e.g. "#foo" / "#MyAnchor")
943 if( my $n = $ctx->{root}->{anchors}->{ $ref } )
944 {
945 return( _v( $ctx, $ref, $n, $inst ) );
946 }
947 if( $ref =~ /^\#([A-Za-z0-9._-]+)\z/ )
948 {
949 my $cand = $base . '#' . $1;
950 if( my $node = $ctx->{root}->{id_index}->{ $cand } )
951 {
952 my $sp = _ptr_of_node( $ctx->{root}, $node );
953 return( _v( $ctx, $sp, $node, $inst ) );
954 }
955 }
956 # 2) If it’s a JSON Pointer ( "#/..." ), use _jsv_resolve_internal_ref
957 if( $ref =~ m{\A\#/(?:[^~/]|~[01])} )
958 {
959 # or pulled from id_index; same one used in compile_js
960 my $root_schema = $ctx->{root}->{schema} or return( _err_res( $ctx, $schema_ptr, "missing schema", '$ref' ) );
961  
962 my $node = _jsv_resolve_internal_ref( $root_schema, $ref );
963 if( $node )
964 {
965 return( _v( $ctx, $ref, $node, $inst ) );
966 }
967  
968 return _err_res(
969 $ctx,
970 $schema_ptr,
971 "unresolved JSON Pointer fragment in \$ref: $abs",
972 '$ref'
973 );
974 }
975 # 3) If not a JSON Pointer and not an anchor, fall through to external resolver / error
976 }
977  
978 # External resolver hook
979 if( $ctx->{resolver} )
980 {
981 local $@;
982 my $ext = eval{ $ctx->{resolver}->( $abs ) };
983 return( _err_res( $ctx, $schema_ptr, "resolver failed for \$ref: $abs", '$ref' ) ) unless( $ext && ref( $ext ) );
984  
985 my $ext_base = _normalize_uri( ( ref( $ext ) eq 'HASH' && $ext->{'$id'} ) ? $ext->{'$id'} : $abs );
986  
987 my( $frag ) = ( $abs =~ /(\#.*)\z/ );
988 my ( $anchors, $ids ) = ( {}, {} );
989 _index_schema_202012( $ext, $ext_base, '#', $anchors, $ids );
990  
991 push( @{$ctx->{id_stack}}, $ext_base );
992  
993 # If the abs URI included a JSON Pointer fragment, honor it here
994 my $target_ptr = '#';
995 if( defined( $frag ) && length( $frag ) )
996 {
997 if( $frag =~ m{\A\#/(?:[^~/]|~[01])} )
998 {
999 # JSON Pointer fragment
1000 if( my $node = $anchors->{ $frag } )
1001 {
1002 my $r = _v( $ctx, $frag, $node, $inst );
1003 pop( @{$ctx->{id_stack}} );
1004 return( $r );
1005 }
1006 else
1007 {
1008 pop( @{$ctx->{id_stack}} );
1009 return( _err_res( $ctx, $schema_ptr, "unresolved JSON Pointer fragment in \$ref: $abs", '$ref' ) );
1010 }
1011 }
1012 elsif( $frag =~ /\A\#([A-Za-z0-9._-]+)\z/ )
1013 {
1014 my $cand = $ext_base . '#' . $1;
1015 if( my $node = $ids->{ $cand } )
1016 {
1017 my $sp = _ptr_of_node( { anchors => $anchors }, $node ) || '#';
1018 my $r = _v( $ctx, $sp, $node, $inst );
1019 pop( @{$ctx->{id_stack}} );
1020 return( $r );
1021 }
1022 }
1023 }
1024  
1025 my $r = _v( $ctx, '#', $ext, $inst );
1026 pop( @{$ctx->{id_stack}} );
1027 return( $r );
1028 }
1029  
1030 return( _err_res( $ctx, $schema_ptr, "unresolved \$ref: $ref (abs: $abs)", '$ref' ) );
1031 }
1032  
1033 sub _canon
1034 {
1035 my( $v ) = @_;
1036 state $json = JSON->new->allow_nonref(1)->canonical(1)->convert_blessed(1);
1037 return( $json->encode( $v ) );
1038 }
1039  
1040 sub _check_vocabulary_required
1041 {
1042 my( $self ) = @_;
1043 return(1) if( $self->{vocab_checked} );
1044  
1045 my $root = $self->{schema};
1046 if( ref( $root ) eq 'HASH' && ref( $root->{'$vocabulary'} ) eq 'HASH' )
1047 {
1048 my $decl = $root->{'$vocabulary'};
1049 my $support = $self->{vocab_support} || {};
1050 for my $uri ( keys( %$decl ) )
1051 {
1052 # required only
1053 next unless( $decl->{ $uri } );
1054 next if( $support->{ $uri } );
1055 # TODO: Maybe we should return an exception rather than dying; it would be more user-friendly
1056 die( "Required vocabulary not supported: $uri" );
1057 }
1058 }
1059 return( $self->{vocab_checked} = 1 );
1060 }
1061  
1062 sub _clone
1063 {
1064 my( $v ) = @_;
1065 state $json = JSON->new->allow_nonref(1)->canonical(1);
1066 return( $json->decode( $json->encode( $v ) ) );
1067 }
1068  
1069 sub _compile_js_node
1070 {
1071 my $self = shift( @_ );
1072 my( $S, $sp, $seen, $funcs, $counter_ref, $root, $opts ) = @_;
1073  
1074 $opts ||= {};
1075 my $ecma = exists( $opts->{ecma} ) ? $opts->{ecma} : 'auto';
1076 my $force_unicode =
1077 defined( $ecma ) &&
1078 $ecma =~ /^\d+$/ &&
1079 $ecma >= 2018;
1080  
1081 # Re-use same JS function for the same schema pointer
1082 if( exists( $seen->{ $sp } ) )
1083 {
1084 return( $seen->{ $sp } );
1085 }
1086  
1087 # Support pointer-alias schemas such as:
1088 # definitions => { address => "#/definitions/jp_address" }
1089 if( defined( $S ) && !ref( $S ) && $S =~ /^#\// )
1090 {
1091 my $target_ptr = $S;
1092  
1093 # If we already compiled that pointer, just alias it
1094 if( exists( $seen->{ $target_ptr } ) )
1095 {
1096 $seen->{ $sp } = $seen->{ $target_ptr };
1097 return( $seen->{ $target_ptr } );
1098 }
1099  
1100 my $target_schema = _jsv_resolve_internal_ref( $root, $target_ptr );
1101  
1102 # Follow chains of pointer-aliases
1103 if( defined( $target_schema ) && !ref( $target_schema ) )
1104 {
1105 my %followed;
1106 while(
1107 defined( $target_schema ) &&
1108 !ref( $target_schema ) &&
1109 $target_schema =~ /^#\//
1110 )
1111 {
1112 last if( $followed{ $target_schema }++ );
1113 $target_ptr = $target_schema;
1114 $target_schema = _jsv_resolve_internal_ref( $root, $target_ptr );
1115 }
1116 }
1117  
1118 unless( defined( $target_schema ) )
1119 {
1120 # Could not resolve: emit a no-op validator (server still enforces)
1121 my $id = $$counter_ref++;
1122 my $fn = "jsv_node_${id}";
1123 $seen->{ $sp } = $fn;
1124 push( @$funcs, <<JS_RUNTIME );
1125 // $sp (unresolved pointer-alias $S)
1126 function $fn(inst, path, ctx)
1127 {
1128 }
1129 JS_RUNTIME
1130 return( $fn );
1131 }
1132  
1133 unless( ref( $target_schema ) eq 'HASH' )
1134 {
1135 die(
1136 "Internal error: pointer-alias '$S' at '$sp' did not resolve to an object schema " .
1137 "(got " . ( ref( $target_schema ) || 'scalar' ) . ")."
1138 );
1139 }
1140  
1141 my $base_fn = $self->_compile_js_node( $target_schema, $target_ptr, $seen, $funcs, $counter_ref, $root, $opts );
1142  
1143 # Alias this pointer to the target validator
1144 $seen->{ $sp } = $base_fn;
1145 return( $base_fn );
1146 }
1147  
1148 # NOTE: $ref
1149 # 0) $ref handling (internal refs only)
1150 if( ref( $S ) eq 'HASH' &&
1151 exists( $S->{'$ref'} ) )
1152 {
1153 my $ref = $S->{'$ref'};
1154  
1155 # Only support internal refs ("#/...") in JS
1156 if( defined( $ref ) && $ref =~ /^#/ )
1157 {
1158 my $target_ptr = $ref;
1159  
1160 # If we already compiled that pointer, just alias and return it
1161 if( exists( $seen->{ $target_ptr } ) )
1162 {
1163 $seen->{ $sp } = $seen->{ $target_ptr };
1164 return( $seen->{ $target_ptr } );
1165 }
1166  
1167 # Otherwise, resolve pointer against the root schema
1168 my $target_schema = _jsv_resolve_internal_ref( $root, $target_ptr );
1169  
1170  
1171 # Support "pointer alias" schemas such as:
1172 # definitions => { address => "#/definitions/jp_address" }
1173 # Keep resolving until we reach a real schema hash.
1174 if( defined( $target_schema ) && !ref( $target_schema ) )
1175 {
1176 my %followed;
1177 while(
1178 defined( $target_schema ) &&
1179 !ref( $target_schema ) &&
1180 $target_schema =~ /^#\//
1181 )
1182 {
1183 last if( $followed{ $target_schema }++ );
1184 $target_ptr = $target_schema;
1185 $target_schema = _jsv_resolve_internal_ref( $root, $target_ptr );
1186 }
1187 }
1188  
1189 unless( defined( $target_schema ) )
1190 {
1191 # Pointer could not be resolved. As a safety fallback,
1192 # make this node a no-op on the client (server will still enforce).
1193 my $id = $$counter_ref++;
1194 my $fn = "jsv_node_${id}";
1195 $seen->{ $sp } = $fn;
1196 push( @$funcs, <<JS_RUNTIME );
1197 // $sp
1198 function $fn(inst, path, ctx)
1199 {
1200 }
1201  
1202 JS_RUNTIME
1203 return( $fn );
1204 }
1205  
1206 unless( ref( $target_schema ) eq 'HASH' )
1207 {
1208 die( "Internal error: \$ref target '$target_ptr' did not resolve to a schema object (got " .
1209 ( defined( $target_schema ) ? ref( $target_schema ) || 'scalar' : 'undef' ) .
1210 "). If you are using pointer-alias definitions, they must ultimately resolve to an object schema." );
1211 }
1212  
1213 # Compile the target, then merge sibling keywords
1214 my $base_fn = $self->_compile_js_node( $target_schema, $target_ptr, $seen, $funcs, $counter_ref, $root, $opts );
1215  
1216 # Create a wrapper that runs both the referenced schema AND local keywords
1217 my $id = $$counter_ref++;
1218 my $wrapper_fn = "jsv_node_$id";
1219 $seen->{ $sp } = $wrapper_fn;
1220  
1221 my @wrapper_body;
1222 push( @wrapper_body, <<JS_RUNTIME );
1223 // $sp (\$ref + siblings)
1224 function $wrapper_fn(inst, path, ctx)
1225 {
1226 $base_fn(inst, path, ctx);
1227 if(ctx.errors.length >= ctx.maxErrors) return;
1228 JS_RUNTIME
1229  
1230 # Now compile the current node again, but skip the $ref
1231 my $local_S = { %$S }; # shallow copy
1232 delete( $local_S->{'$ref'} );
1233 my $local_sp = _join_ptr( $sp, '__local__' );
1234 my $local_fn = $self->_compile_js_node( $local_S, $local_sp, $seen, $funcs, $counter_ref, $root, $opts );
1235  
1236 if( $local_fn ne $wrapper_fn )
1237 {
1238 push( @wrapper_body, <<JS_RUNTIME );
1239 $local_fn(inst, path, ctx);
1240 JS_RUNTIME
1241 }
1242  
1243 push( @wrapper_body, <<JS_RUNTIME );
1244 }
1245 JS_RUNTIME
1246 push( @$funcs, join( '', @wrapper_body ) );
1247 return( $wrapper_fn );
1248 }
1249  
1250 # External refs (URLs, etc.) are not resolved on the client.
1251 # Full resolution is done server-side.
1252 }
1253  
1254 my $id = $$counter_ref++;
1255 my $fn = "jsv_node_$id";
1256 $seen->{ $sp } = $fn;
1257  
1258 my @body;
1259  
1260 push( @body, <<JS_RUNTIME );
1261 // $sp
1262 function $fn(inst, path, ctx)
1263 {
1264 JS_RUNTIME
1265  
1266 # NOTE: combinator (allOf / anyOf / oneOf / not / if-then-else)
1267 if( ref( $S ) eq 'HASH' )
1268 {
1269 # allOf – AND of subschemas
1270 if( exists( $S->{allOf} ) &&
1271 ref( $S->{allOf} ) eq 'ARRAY' &&
1272 @{$S->{allOf}} )
1273 {
1274 for my $i ( 0 .. $#{$S->{allOf}} )
1275 {
1276 my $sub_sp = _join_ptr( $sp, 'allOf', $i );
1277 my $sub_fn = $self->_compile_js_node( $S->{allOf}->[ $i ], $sub_sp, $seen, $funcs, $counter_ref, $root, $opts );
1278  
1279 push( @body, <<JS_RUNTIME );
1280 // $sub_sp
1281 $sub_fn(inst, path + '/allOf/$i', ctx);
1282 if(ctx.maxErrors && ctx.errors.length >= ctx.maxErrors) return;
1283 JS_RUNTIME
1284 }
1285  
1286 # IMPORTANT: we do *not* return here.
1287 # Other local keywords (type, properties, contains, ...) must still run.
1288 }
1289  
1290 # anyOf – at least one must validate (we only emit a single anyOf error)
1291 if( exists( $S->{anyOf} ) &&
1292 ref( $S->{anyOf} ) eq 'ARRAY' &&
1293 @{$S->{anyOf}} )
1294 {
1295 push( @body, <<JS_RUNTIME );
1296 (function()
1297 {
1298 var baseErrors = ctx.errors;
1299 var matched = false;
1300  
1301 JS_RUNTIME
1302  
1303 for my $i ( 0 .. $#{$S->{anyOf}} )
1304 {
1305 my $sub_sp = _join_ptr( $sp, 'anyOf', $i );
1306 my $sub_fn = $self->_compile_js_node( $S->{anyOf}->[ $i ], $sub_sp, $seen, $funcs, $counter_ref, $root, $opts );
1307  
1308 push( @body, <<JS_RUNTIME );
1309 if(matched) return;
1310 ctx.errors = [];
1311 // $sub_sp
1312 $sub_fn(inst, path + '/anyOf/$i', ctx);
1313 if(ctx.errors.length === 0)
1314 {
1315 matched = true;
1316 ctx.errors = baseErrors;
1317 return;
1318 }
1319 JS_RUNTIME
1320 }
1321  
1322 my $sp_qp = _js_quote( $sp );
1323 push( @body, <<JS_RUNTIME );
1324 ctx.errors = baseErrors;
1325 if(!matched)
1326 {
1327 _jsv_err(ctx, path, 'anyOf', 'no subschema matched', $sp_qp);
1328 }
1329 })();
1330 // return;
1331 JS_RUNTIME
1332 }
1333  
1334 # oneOf – exactly one must validate
1335 if( exists( $S->{oneOf} ) &&
1336 ref( $S->{oneOf} ) eq 'ARRAY' &&
1337 @{$S->{oneOf}} )
1338 {
1339 push( @body, <<JS_RUNTIME );
1340 (function()
1341 {
1342 var baseErrors = ctx.errors;
1343 var hits = 0;
1344  
1345 JS_RUNTIME
1346  
1347 for my $i ( 0 .. $#{$S->{oneOf}} )
1348 {
1349 my $sub_sp = _join_ptr( $sp, 'oneOf', $i );
1350 my $sub_fn = $self->_compile_js_node( $S->{oneOf}->[ $i ], $sub_sp, $seen, $funcs, $counter_ref, $root, $opts );
1351  
1352 push( @body, <<JS_RUNTIME );
1353 ctx.errors = [];
1354 // $sub_sp
1355 $sub_fn(inst, path + '/oneOf/$i', ctx);
1356 if(ctx.errors.length === 0)
1357 {
1358 hits++;
1359 }
1360 JS_RUNTIME
1361 }
1362  
1363 my $sp_qp = _js_quote( $sp );
1364 push( @body, <<JS_RUNTIME );
1365 ctx.errors = baseErrors;
1366 if(hits !== 1)
1367 {
1368 _jsv_err(ctx, path, 'oneOf', 'exactly one subschema must match, but ' + hits + ' did', $sp_qp);
1369 }
1370 })();
1371 // return;
1372 JS_RUNTIME
1373 }
1374  
1375 # not – but we SKIP "negative required" patterns on the client
1376 if( exists( $S->{not} ) )
1377 {
1378 my $skip_not = 0;
1379  
1380 if( ref( $S->{not} ) eq 'HASH' )
1381 {
1382 my $N = $S->{not};
1383  
1384 # Direct: { "not": { "required": [...] } }
1385 if( exists( $N->{required} ) &&
1386 ref( $N->{required} ) eq 'ARRAY' )
1387 {
1388 $skip_not = 1;
1389 }
1390 # Or: { "not": { "anyOf": [ {required:...}, ... ] } }
1391 elsif( exists( $N->{anyOf} ) &&
1392 ref( $N->{anyOf} ) eq 'ARRAY' )
1393 {
1394 my $all_req = 1;
1395 for my $elt ( @{$N->{anyOf}} )
1396 {
1397 if( !( ref( $elt ) eq 'HASH' &&
1398 exists( $elt->{required} ) &&
1399 ref( $elt->{required} ) eq 'ARRAY' ) )
1400 {
1401 $all_req = 0;
1402 last;
1403 }
1404 }
1405 $skip_not = 1 if( $all_req );
1406 }
1407 }
1408  
1409 if( !$skip_not )
1410 {
1411 my $sub_sp = _join_ptr( $sp, 'not' );
1412 my $sub_fn = $self->_compile_js_node( $S->{not}, $sub_sp, $seen, $funcs, $counter_ref, $root, $opts );
1413 my $sp_qp = _js_quote( $sp );
1414 push( @body, <<JS_RUNTIME );
1415 (function()
1416 {
1417 var baseErrors = ctx.errors;
1418 ctx.errors = [];
1419 // $sub_sp
1420 $sub_fn(inst, path + '/not', ctx);
1421 var failed = (ctx.errors.length > 0);
1422 ctx.errors = baseErrors;
1423 if(!failed)
1424 {
1425 _jsv_err(ctx, path, 'not', 'instance matched forbidden schema', $sp_qp);
1426 }
1427 })();
1428 // return;
1429 JS_RUNTIME
1430 }
1431 else
1432 {
1433 # Skip "not + required" style rules on the client;
1434 # they are enforced server-side only.
1435 push( @body, <<JS_RUNTIME );
1436 // NOTE: 'not' at $sp is a negative-required pattern; skipped client-side.
1437 JS_RUNTIME
1438 }
1439 }
1440  
1441 # if / then / else (branch errors are enforced, "if" errors are not)
1442 if( exists( $S->{if} ) )
1443 {
1444 my $if_sp = _join_ptr( $sp, 'if' );
1445 my $if_fn = $self->_compile_js_node( $S->{if}, $if_sp, $seen, $funcs, $counter_ref, $root, $opts );
1446  
1447 push( @body, <<JS_RUNTIME );
1448 (function()
1449 {
1450 var baseErrors = ctx.errors;
1451 var tmp = [];
1452 ctx.errors = tmp;
1453 // $if_sp
1454 $if_fn(inst, path + '/if', ctx);
1455 var failed = (tmp.length > 0);
1456 ctx.errors = baseErrors;
1457 JS_RUNTIME
1458  
1459 if( $S->{then} )
1460 {
1461 my $then_sp = _join_ptr( $sp, 'then' );
1462 my $then_fn = $self->_compile_js_node( $S->{then}, $then_sp, $seen, $funcs, $counter_ref, $root, $opts );
1463 push( @body, <<JS_RUNTIME );
1464 if(!failed)
1465 {
1466 $then_fn(inst, path + '/then', ctx);
1467 }
1468 JS_RUNTIME
1469 }
1470 if( $S->{else} )
1471 {
1472 my $else_sp = _join_ptr( $sp, 'else' );
1473 my $else_fn = $self->_compile_js_node( $S->{else}, $else_sp, $seen, $funcs, $counter_ref, $root, $opts );
1474 push( @body, <<JS_RUNTIME );
1475 else
1476 {
1477 $else_fn(inst, path + '/else', ctx);
1478 }
1479 JS_RUNTIME
1480 }
1481  
1482 push( @body, <<JS_RUNTIME );
1483 })();
1484 JS_RUNTIME
1485 # Do NOT return here; this node can also have local constraints
1486 }
1487  
1488 # uniqueKeys extension when enabled
1489 if( $self->{unique_keys} &&
1490 exists( $S->{uniqueKeys} ) &&
1491 ref( $S->{uniqueKeys} ) eq 'ARRAY' )
1492 {
1493 for my $keyset_ref ( @{$S->{uniqueKeys}} )
1494 {
1495 next unless( ref( $keyset_ref ) eq 'ARRAY' && @$keyset_ref );
1496  
1497 my @keys = map{ _js_quote( $_ ) } @$keyset_ref;
1498 my $qsp = _js_quote( $sp );
1499  
1500 push( @body, <<JS_RUNTIME );
1501 if(Array.isArray(inst))
1502 {
1503 var seen = {};
1504 for(var i = 0; i < inst.length; i++)
1505 {
1506 var item = inst[i];
1507 var key = '';
1508 try
1509 {
1510 key = [ @keys ].map(function(k){ return item[k]; }).join('\x1E'); // RS separator
1511 }
1512 catch(e) {}
1513 if(seen.hasOwnProperty(key))
1514 {
1515 _jsv_err(ctx, path, 'uniqueKeys', 'duplicate items with keys [@$keyset_ref]', $qsp);
1516 break;
1517 }
1518 seen[key] = true;
1519 }
1520 }
1521 JS_RUNTIME
1522 }
1523 }
1524 }
1525  
1526 my $has_type_keyword = ( ref( $S ) eq 'HASH' && exists( $S->{type} ) ) ? 1 : 0;
1527  
1528 # NOTE: type
1529 # 1) type
1530 if( exists( $S->{type} ) )
1531 {
1532 my @types = ref( $S->{type} ) eq 'ARRAY' ? @{$S->{type}} : ( $S->{type} );
1533  
1534 # Special-case "number" vs "integer": _jsv_typeOf returns "integer" for ints
1535 my @checks;
1536 for my $t ( @types )
1537 {
1538 if( $t eq 'number' )
1539 {
1540 # accept "number" or "integer" from _jsv_typeOf
1541 push( @checks, q{tt === 'number' || tt === 'integer'} );
1542 }
1543 else
1544 {
1545 my $qt = _js_quote( $t );
1546 push( @checks, "tt === $qt" );
1547 }
1548 }
1549  
1550 my $cond = join( ' || ', @checks );
1551 my $msg = 'expected type ' .
1552 ( @types == 1 ? $types[0] : '[' . join( ',', @types ) . ']' ) .
1553 ' but found ';
1554 my $qmsg = _js_quote( $msg );
1555 my $qsp = _js_quote( $sp );
1556  
1557 push( @body, <<JS_RUNTIME );
1558 var tt = _jsv_typeOf(inst);
1559 if(!( $cond ))
1560 {
1561 _jsv_err(ctx, path, 'type', $qmsg + tt, $qsp);
1562 return;
1563 }
1564 JS_RUNTIME
1565 }
1566  
1567 # NOTE: enum
1568 # 2) enum
1569 if( exists( $S->{enum} ) &&
1570 ref( $S->{enum} ) eq 'ARRAY' &&
1571 @{$S->{enum}} )
1572 {
1573 my @vals = @{$S->{enum}};
1574 my @vs_js = map{ _js_quote( $_ ) } @vals;
1575 my $qsp = _js_quote( $sp );
1576  
1577 local $" = ', ';
1578 push( @body, <<JS_RUNTIME );
1579 (function()
1580 {
1581 var ok = false;
1582 var v = inst;
1583 var list = [ @vs_js ];
1584 for(var i = 0; i < list.length; i++)
1585 {
1586 if(v === list[i])
1587 {
1588 ok = true;
1589 break;
1590 }
1591 }
1592 if(!ok)
1593 {
1594 _jsv_err(ctx, path, 'enum', 'value is not in enum list', $qsp);
1595 }
1596 })();
1597 JS_RUNTIME
1598 }
1599  
1600 # NOTE: const
1601 # 3) const (primitive only)
1602 if( exists( $S->{const} ) )
1603 {
1604 # For simplicity on the JS side, only support primitive const reliably.
1605 # (Object/array equality is non-trivial; we keep it minimal for now.)
1606 my $c = $S->{const};
1607 my $qsp = _js_quote( $sp );
1608  
1609 if( !ref( $c ) )
1610 {
1611 my $cv = _js_quote( $c );
1612 push( @body, <<JS_RUNTIME );
1613 if(inst !== $cv)
1614 {
1615 _jsv_err(ctx, path, 'const', 'value does not match const', $qsp);
1616 }
1617 JS_RUNTIME
1618 }
1619 else
1620 {
1621 # Complex const -> skip in JS (server will still enforce)
1622 push( @body, <<JS_RUNTIME );
1623 // NOTE: const at $sp is non-primitive; not enforced client-side.
1624  
1625 JS_RUNTIME
1626 }
1627 }
1628  
1629 # NOTE: required
1630 # 4) required (objects)
1631 if( exists( $S->{required} ) &&
1632 ref( $S->{required} ) eq 'ARRAY' &&
1633 @{$S->{required}} )
1634 {
1635 push( @body, <<JS_RUNTIME );
1636 if(_jsv_typeOf(inst) === 'object')
1637 {
1638 JS_RUNTIME
1639  
1640 for my $p ( @{$S->{required}} )
1641 {
1642 my $qp = _js_quote( $p );
1643 my $sp2 = _join_ptr( $sp, 'properties', $p );
1644 my $qsp2 = _js_quote( $sp2 );
1645  
1646 my $msg = "required property '$p' is missing";
1647 my $qmsg = _js_quote( $msg );
1648  
1649 push( @body, <<JS_RUNTIME );
1650 if(!_jsv_hasOwn(inst, $qp))
1651 {
1652 _jsv_err(ctx, path, 'required', $qmsg, $qsp2);
1653 }
1654 JS_RUNTIME
1655 }
1656  
1657 push( @body, <<JS_RUNTIME );
1658 }
1659 JS_RUNTIME
1660 }
1661  
1662 # NOTE: string && pattern
1663 # 5) string length & pattern
1664 my $has_string_constraints =
1665 exists( $S->{minLength} ) ||
1666 exists( $S->{maxLength} ) ||
1667 exists( $S->{pattern} );
1668  
1669 if( $has_string_constraints )
1670 {
1671 my $qsp = _js_quote( $sp );
1672  
1673 push( @body, <<JS_RUNTIME );
1674 if(_jsv_typeOf(inst) === 'string')
1675 {
1676 JS_RUNTIME
1677  
1678 if( exists( $S->{minLength} ) )
1679 {
1680 my $min = int( $S->{minLength} );
1681 push( @body, <<JS_RUNTIME );
1682 if(inst.length < $min)
1683 {
1684 _jsv_err(ctx, path, 'minLength', 'string shorter than minLength $min', $qsp);
1685 }
1686 JS_RUNTIME
1687 }
1688  
1689 if( exists( $S->{maxLength} ) )
1690 {
1691 my $max = int( $S->{maxLength} );
1692 push( @body, <<JS_RUNTIME );
1693 if(inst.length > $max)
1694 {
1695 _jsv_err(ctx, path, 'maxLength', 'string longer than maxLength $max', $qsp);
1696 }
1697 JS_RUNTIME
1698 }
1699  
1700 if( exists( $S->{pattern} ) &&
1701 defined( $S->{pattern} ) &&
1702 length( $S->{pattern} ) )
1703 {
1704 my $pat = $S->{pattern};
1705 # my $qpat = _js_quote( $pat );
1706 # from \x{FF70} to \uFF70
1707 # from \p{Katakana} to \p{sc=Katakana}
1708 my $qpat = _re_to_js( $pat );
1709  
1710 if( $force_unicode )
1711 {
1712 # ecma >= 2018: always try with "u" flag (Unicode mode)
1713 push( @body, <<JS_RUNTIME );
1714 try
1715 {
1716 var re = new RegExp("$qpat", "u");
1717 if(!re.test(inst))
1718 {
1719 _jsv_err(ctx, path, 'pattern', 'string does not match pattern', $qsp);
1720 }
1721 }
1722 catch(e)
1723 {
1724 // Browser does not support Unicode property escapes or this pattern.
1725 }
1726 JS_RUNTIME
1727 }
1728 else
1729 {
1730 # auto / ES5 mode: detect "advanced" patterns
1731 if( $pat =~ /\\p\{|\\P\{|\\X|\\R|\(\?[A-Za-z]/ )
1732 {
1733 # Attempt Unicode mode with "u" flag, but gracefully fall back
1734 push( @body, <<JS_RUNTIME );
1735 (function()
1736 {
1737 var re = null;
1738 try
1739 {
1740 re = new RegExp("$qpat", "u");
1741 }
1742 catch(e)
1743 {
1744 // Older browser; skip Unicode-property-based pattern on client.
1745 }
1746 if(re && !re.test(inst))
1747 {
1748 _jsv_err(ctx, path, 'pattern', 'string does not match pattern', $qsp);
1749 }
1750 })();
1751 JS_RUNTIME
1752 }
1753 else
1754 {
1755 # Simple ECMA 5-compatible pattern
1756 push( @body, <<JS_RUNTIME );
1757 try
1758 {
1759 var re = new RegExp("$qpat");
1760 if(!re.test(inst))
1761 {
1762 _jsv_err(ctx, path, 'pattern', 'string does not match pattern', $qsp);
1763 }
1764 }
1765 catch(e)
1766 {
1767 // If pattern is not JS-compatible, we silently skip on the client.
1768 }
1769 JS_RUNTIME
1770 }
1771 }
1772 }
1773  
1774 push( @body, <<JS_RUNTIME );
1775 }
1776 JS_RUNTIME
1777 }
1778  
1779 # NOTE: minimum, maximum, etc
1780 # 6) numeric bounds (minimum/maximum/exclusive*)
1781 my $has_num_constraints =
1782 exists( $S->{minimum} ) ||
1783 exists( $S->{maximum} ) ||
1784 exists( $S->{exclusiveMinimum} ) ||
1785 exists( $S->{exclusiveMaximum} );
1786  
1787 if( $has_num_constraints )
1788 {
1789 # For consistency with string/pattern/etc, we report the
1790 # schema pointer of the *owning schema* ($sp), not the
1791 # child keyword location (.../minimum).
1792 my $qsp_num = _js_quote( $sp );
1793 my $qmsg_expected_num = _js_quote( 'expected number but found ' );
1794  
1795 push( @body, <<'JS_RUNTIME' );
1796 var t = _jsv_typeOf(inst);
1797  
1798 // Coerce numeric-looking strings to numbers, for friendlier UX
1799 if(t === 'string' && /^[+-]?(?:\d+|\d*\.\d+)$/.test(inst))
1800 {
1801 inst = +inst;
1802 t = _jsv_typeOf(inst);
1803 }
1804  
1805 if(t === 'number' || t === 'integer')
1806 {
1807 JS_RUNTIME
1808  
1809 if( exists( $S->{minimum} ) )
1810 {
1811 my $min = 0 + $S->{minimum};
1812 push( @body, <<JS_RUNTIME );
1813 if(inst < $min)
1814 {
1815 _jsv_err(ctx, path, 'minimum', 'number is less than minimum $min', $qsp_num);
1816 }
1817 JS_RUNTIME
1818 }
1819  
1820 if( exists( $S->{maximum} ) )
1821 {
1822 my $max = 0 + $S->{maximum};
1823 push( @body, <<JS_RUNTIME );
1824 if(inst > $max)
1825 {
1826 _jsv_err(ctx, path, 'maximum', 'number is greater than maximum $max', $qsp_num);
1827 }
1828 JS_RUNTIME
1829 }
1830  
1831 if( exists( $S->{exclusiveMinimum} ) )
1832 {
1833 my $emin = 0 + $S->{exclusiveMinimum};
1834 push( @body, <<JS_RUNTIME );
1835 if(inst <= $emin)
1836 {
1837 _jsv_err(ctx, path, 'exclusiveMinimum',
1838 'number is <= exclusiveMinimum $emin', $qsp_num);
1839 }
1840 JS_RUNTIME
1841 }
1842  
1843 if( exists( $S->{exclusiveMaximum} ) )
1844 {
1845 my $emax = 0 + $S->{exclusiveMaximum};
1846 push( @body, <<JS_RUNTIME );
1847 if(inst >= $emax)
1848 {
1849 _jsv_err(ctx, path, 'exclusiveMaximum',
1850 'number is >= exclusiveMaximum $emax', $qsp_num);
1851 }
1852 JS_RUNTIME
1853 }
1854  
1855 # Close the "if(t === 'number' || t === 'integer')" and, if needed,
1856 # add a fallback type error when no explicit "type" keyword exists.
1857 if( $has_type_keyword )
1858 {
1859 push( @body, <<'JS_RUNTIME' );
1860 }
1861 JS_RUNTIME
1862 }
1863 else
1864 {
1865 push( @body, <<JS_RUNTIME );
1866 }
1867 else
1868 {
1869 _jsv_err(ctx, path, 'type', $qmsg_expected_num + t, $qsp_num);
1870 }
1871 JS_RUNTIME
1872 }
1873 }
1874  
1875 # NOTE: items / minItems / maxItems
1876 # 7) array items & minItems/maxItems
1877 my $has_array_len =
1878 exists( $S->{minItems} ) ||
1879 exists( $S->{maxItems} );
1880  
1881 if( exists( $S->{items} ) || $has_array_len )
1882 {
1883 my $qsp = _js_quote( $sp );
1884  
1885 # Precompile single-schema "items"
1886 my $items_fn;
1887 if( exists( $S->{items} ) && ref( $S->{items} ) eq 'HASH' )
1888 {
1889 my $items_ptr = _join_ptr( $sp, 'items' );
1890 $items_fn = $self->_compile_js_node( $S->{items}, $items_ptr, $seen, $funcs, $counter_ref, $root, $opts );
1891 }
1892  
1893 my $min_items = exists( $S->{minItems} ) ? int( $S->{minItems} ) : undef;
1894 my $max_items = exists( $S->{maxItems} ) ? int( $S->{maxItems} ) : undef;
1895  
1896 my( $qmsg_min, $qmsg_max );
1897 if( defined( $min_items ) )
1898 {
1899 my $msg_min = "array has fewer than $min_items items";
1900 $qmsg_min = _js_quote( $msg_min );
1901 }
1902 if( defined( $max_items ) )
1903 {
1904 my $msg_max = "array has more than $max_items items";
1905 $qmsg_max = _js_quote( $msg_max );
1906 }
1907  
1908 push( @body, <<JS_RUNTIME );
1909 if(_jsv_typeOf(inst) === 'array')
1910 {
1911 JS_RUNTIME
1912  
1913 if( defined( $min_items ) )
1914 {
1915 push( @body, <<JS_RUNTIME );
1916 if(inst.length < $min_items)
1917 {
1918 _jsv_err(ctx, path, 'minItems', $qmsg_min, $qsp);
1919 }
1920 JS_RUNTIME
1921 }
1922  
1923 if( defined( $max_items ) )
1924 {
1925 push( @body, <<JS_RUNTIME );
1926 if(inst.length > $max_items)
1927 {
1928 _jsv_err(ctx, path, 'maxItems', $qmsg_max, $qsp);
1929 }
1930 JS_RUNTIME
1931 }
1932  
1933 if( $items_fn )
1934 {
1935 push( @body, <<JS_RUNTIME );
1936 for(var i = 0; i < inst.length; i++)
1937 {
1938 $items_fn(inst[i], path + '/' + i, ctx);
1939 if(ctx.maxErrors && ctx.errors && ctx.errors.length >= ctx.maxErrors)
1940 {
1941 return;
1942 }
1943 }
1944 JS_RUNTIME
1945 }
1946  
1947 push( @body, <<JS_RUNTIME );
1948 }
1949 JS_RUNTIME
1950 }
1951  
1952 # NOTE: properties
1953 # 8) properties (objects) – recurse into children
1954 if( exists( $S->{properties} ) &&
1955 ref( $S->{properties} ) eq 'HASH' )
1956 {
1957 push( @body, <<JS_RUNTIME );
1958 if(_jsv_typeOf(inst) === 'object')
1959 {
1960 JS_RUNTIME
1961  
1962 for my $p ( sort( keys( %{$S->{properties}} ) ) )
1963 {
1964 my $child = $S->{properties}->{ $p };
1965 my $child_ptr = _join_ptr( $sp, 'properties', $p );
1966 my $child_fn = $self->_compile_js_node( $child, $child_ptr, $seen, $funcs, $counter_ref, $root, $opts );
1967  
1968 my $qp = _js_quote( $p );
1969 my $path_suffix = '/' . $p;
1970 my $path_suffix_q = _js_quote( $path_suffix );
1971  
1972 push( @body, <<JS_RUNTIME );
1973 if(_jsv_hasOwn(inst, $qp))
1974 {
1975 // $child_ptr
1976 $child_fn(inst[$qp], path + $path_suffix_q, ctx);
1977 }
1978 JS_RUNTIME
1979 }
1980  
1981 push( @body, <<JS_RUNTIME );
1982 }
1983 JS_RUNTIME
1984 }
1985  
1986 # NOTE: definitions – recurse into named schemas
1987 if( exists( $S->{definitions} ) &&
1988 ref( $S->{definitions} ) eq 'HASH' )
1989 {
1990 for my $name ( sort keys %{ $S->{definitions} } )
1991 {
1992 my $child = $S->{definitions}->{ $name };
1993 my $child_ptr = _join_ptr( $sp, 'definitions', $name );
1994 my $child_fn = $self->_compile_js_node( $child, $child_ptr, $seen, $funcs, $counter_ref, $root, $opts );
1995  
1996 # No runtime call needed here — definitions don't validate by themselves.
1997 # We just need them compiled so pointer-based lookup can see them.
1998 }
1999 }
2000  
2001 # NOTE: contains
2002 # 9) contains / minContains / maxContains (arrays)
2003 if( exists( $S->{contains} ) )
2004 {
2005 my $contains_schema = $S->{contains};
2006 my $contains_ptr = _join_ptr( $sp, 'contains' );
2007 my $contains_fn = $self->_compile_js_node( $contains_schema, $contains_ptr, $seen, $funcs, $counter_ref, $root, $opts );
2008 my $qsp_contains = _js_quote( $contains_ptr );
2009  
2010 my $have_min = exists( $S->{minContains} );
2011 my $have_max = exists( $S->{maxContains} );
2012 my $min = $have_min ? int( $S->{minContains} ) : 0;
2013 my $max = $have_max ? int( $S->{maxContains} ) : 0;
2014  
2015 my $msg_min = "array has fewer than $min items matching contains subschema";
2016 my $qmsg_min = _js_quote( $msg_min );
2017 my $msg_max = "array has more than $max items matching contains subschema";
2018 my $qmsg_max = _js_quote( $msg_max );
2019 my $msg_cont = "array does not contain any item matching contains subschema";
2020 my $qmsg_cont= _js_quote( $msg_cont );
2021  
2022 push( @body, <<JS_RUNTIME );
2023 if(_jsv_typeOf(inst) === 'array')
2024 {
2025 var matchCount = 0;
2026 for(var i = 0; i < inst.length; i++)
2027 {
2028 var tmpCtx = { errors: [], maxErrors: ctx.maxErrors };
2029 // $contains_ptr
2030 $contains_fn(inst[i], path + '/' + i, tmpCtx);
2031 if(tmpCtx.errors.length === 0)
2032 {
2033 matchCount++;
2034 }
2035 }
2036 JS_RUNTIME
2037  
2038 if( $have_min )
2039 {
2040 push( @body, <<JS_RUNTIME );
2041 if(matchCount < $min)
2042 {
2043 _jsv_err(ctx, path, 'minContains', $qmsg_min, $qsp_contains);
2044 }
2045 JS_RUNTIME
2046 }
2047  
2048 if( $have_max )
2049 {
2050 push( @body, <<JS_RUNTIME );
2051 if(matchCount > $max)
2052 {
2053 _jsv_err(ctx, path, 'maxContains', $qmsg_max, $qsp_contains);
2054 }
2055 JS_RUNTIME
2056 }
2057  
2058 # Plain "contains" only if no min/max are present
2059 if( !$have_min && !$have_max )
2060 {
2061 push( @body, <<JS_RUNTIME );
2062 if(matchCount === 0)
2063 {
2064 _jsv_err(ctx, path, 'contains', $qmsg_cont, $qsp_contains);
2065 }
2066 JS_RUNTIME
2067 }
2068  
2069 push( @body, <<JS_RUNTIME );
2070 }
2071 JS_RUNTIME
2072 }
2073  
2074 push( @body, <<JS_RUNTIME );
2075 }
2076 JS_RUNTIME
2077  
2078 push( @$funcs, join( '', @body ) );
2079  
2080 return( $fn );
2081 }
2082  
2083 sub _compile_node
2084 {
2085 my( $root, $ptr, $S ) = @_;
2086  
2087 # Non-hash schemas (incl. booleans) => trivial pass
2088 return sub
2089 {
2090 my( $ctx, $inst ) = @_;
2091 return( { ok => 1, props => {}, items => {} } );
2092 } unless( ref( $S ) eq 'HASH' );
2093  
2094 # Capture presence and values so runtime avoids hash lookups
2095 my $has_type = exists( $S->{type} );
2096 my $type_spec = $S->{type};
2097  
2098 my $has_const = exists( $S->{const} );
2099 my $const_val = $S->{const};
2100  
2101 my $has_enum = exists( $S->{enum} );
2102 my $enum_vals = $S->{enum};
2103  
2104 my %numk = map{ $_ => $S->{ $_ } } grep{ exists( $S->{ $_ } ) }
2105 qw( multipleOf minimum maximum exclusiveMinimum exclusiveMaximum );
2106  
2107 my $has_strlen = ( exists( $S->{minLength} ) || exists( $S->{maxLength} ) || exists( $S->{pattern} ) ) ? 1 : 0;
2108 my $has_format = exists( $S->{format} );
2109 my $format_name = $S->{format};
2110  
2111 my $has_unique_keys =
2112 exists( $S->{uniqueKeys} ) &&
2113 ref( $S->{uniqueKeys} ) eq 'ARRAY';
2114  
2115 # Precompile child closures (same structure our interpreter walks)
2116 my %child;
2117  
2118 # Arrays
2119 if( ref( $S->{prefixItems} ) eq 'ARRAY' )
2120 {
2121 for my $i ( 0 .. $#{ $S->{prefixItems} } )
2122 {
2123 my $cp = _join_ptr( $ptr, "prefixItems/$i" );
2124 $child{ "prefix:$i" } = _compile_node( $root, $cp, $S->{prefixItems}->[$i] );
2125 }
2126 }
2127 if( ref( $S->{items} ) eq 'HASH' )
2128 {
2129 $child{ "items" } = _compile_node( $root, _join_ptr( $ptr, "items" ), $S->{items} );
2130 }
2131 if( exists( $S->{contains} ) && ref( $S->{contains} ) )
2132 {
2133 $child{ "contains" } = _compile_node( $root, _join_ptr( $ptr, "contains" ), $S->{contains} );
2134 }
2135 if( exists( $S->{unevaluatedItems} ) && ref( $S->{unevaluatedItems} ) eq 'HASH' )
2136 {
2137 $child{ "unevaluatedItems" } = _compile_node( $root, _join_ptr( $ptr, "unevaluatedItems" ), $S->{unevaluatedItems} );
2138 }
2139  
2140 # Objects
2141 if( ref( $S->{properties} ) eq 'HASH' )
2142 {
2143 for my $k ( keys( %{$S->{properties}} ) )
2144 {
2145 my $cp = _join_ptr( $ptr, "properties/$k" );
2146 $child{ "prop:$k" } = _compile_node( $root, $cp, $S->{properties}->{ $k } );
2147 }
2148 }
2149 if( ref( $S->{patternProperties} ) eq 'HASH' )
2150 {
2151 for my $re ( keys( %{ $S->{patternProperties} } ) )
2152 {
2153 my $cp = _join_ptr( $ptr, "patternProperties/$re" );
2154 $child{ "pat:$re" } = _compile_node( $root, $cp, $S->{patternProperties}->{ $re } );
2155 }
2156 }
2157 if( exists( $S->{additionalProperties} ) && ref( $S->{additionalProperties} ) eq 'HASH' )
2158 {
2159 $child{ "additional" } = _compile_node( $root, _join_ptr( $ptr, "additionalProperties" ), $S->{additionalProperties} );
2160 }
2161 if( exists( $S->{propertyNames} ) && ref( $S->{propertyNames} ) eq 'HASH' )
2162 {
2163 $child{ "propnames" } = _compile_node( $root, _join_ptr( $ptr, "propertyNames" ), $S->{propertyNames} );
2164 }
2165 if( exists( $S->{dependentSchemas} ) && ref( $S->{dependentSchemas} ) eq 'HASH' )
2166 {
2167 for my $k ( keys( %{$S->{dependentSchemas}} ) )
2168 {
2169 my $cp = _join_ptr( $ptr, "dependentSchemas/$k" );
2170 $child{ "deps:$k" } = _compile_node( $root, $cp, $S->{dependentSchemas}->{ $k } );
2171 }
2172 }
2173 if( exists( $S->{unevaluatedProperties} ) && ref( $S->{unevaluatedProperties} ) eq 'HASH' )
2174 {
2175 $child{ "ueprops" } = _compile_node( $root, _join_ptr( $ptr, "unevaluatedProperties" ), $S->{unevaluatedProperties} );
2176 }
2177  
2178 # Combinators
2179 for my $kw ( qw( allOf anyOf oneOf not ) )
2180 {
2181 next unless( exists( $S->{ $kw } ) );
2182 if( $kw eq 'not' )
2183 {
2184 $child{ "not" } = _compile_node( $root, _join_ptr( $ptr, "not" ), $S->{not} ) if( ref( $S->{not} ) );
2185 next;
2186 }
2187 if( ref( $S->{ $kw } ) eq 'ARRAY' )
2188 {
2189 for my $i ( 0 .. $#{$S->{ $kw }} )
2190 {
2191 my $cp = _join_ptr( $ptr, "$kw/$i" );
2192 $child{ "$kw:$i" } = _compile_node( $root, $cp, $S->{ $kw }->[$i] );
2193 }
2194 }
2195 }
2196  
2197 # Conditionals
2198 if( exists( $S->{if} ) && ref( $S->{if} ) eq 'HASH' )
2199 {
2200 $child{ "if" } = _compile_node( $root, _join_ptr( $ptr, 'if' ), $S->{if} );
2201 $child{ "then" } = _compile_node( $root, _join_ptr( $ptr, 'then' ), $S->{then} ) if( exists( $S->{then} ) && ref( $S->{then} ) );
2202 $child{ "else" } = _compile_node( $root, _join_ptr( $ptr, 'else' ), $S->{else} ) if( exists( $S->{else} ) && ref( $S->{else} ) );
2203 }
2204  
2205 # Return specialized validator
2206 return sub
2207 {
2208 my( $ctx, $inst ) = @_;
2209  
2210 # Parity with interpreter: trace node visit
2211 _t( $ctx, $ptr, 'node', undef, 'visit' ) if( $ctx->{trace_on} );
2212  
2213 # Type / const / enum
2214 if( $has_type ) { _k_type( $ctx, $inst, $type_spec, $ptr ) or return( _fail() ); }
2215 if( $has_const ) { _k_const( $ctx, $inst, $const_val, $ptr ) or return( _fail() ); }
2216 if( $has_enum ) { _k_enum( $ctx, $inst, $enum_vals, $ptr ) or return( _fail() ); }
2217  
2218 # uniqueKeys extension (compiled path)
2219 if( $ctx->{unique_keys} && $has_unique_keys && ref( $inst ) eq 'ARRAY' )
2220 {
2221 my $r = _k_unique_keys( $ctx, $ptr, $S->{uniqueKeys}, $inst );
2222 return( $r ) unless( $r->{ok} );
2223 }
2224  
2225 # Numbers
2226 if( _is_number( $inst ) )
2227 {
2228 for my $k ( qw( multipleOf minimum maximum exclusiveMinimum exclusiveMaximum ) )
2229 {
2230 next unless( exists( $numk{ $k } ) );
2231 _k_number( $ctx, $inst, $k, $numk{$k}, $ptr ) or return( _fail() );
2232 }
2233 }
2234  
2235 # Strings
2236 if( !ref( $inst ) && defined( $inst ) )
2237 {
2238 if( $has_strlen ) { _k_string( $ctx, $inst, $S, $ptr ) or return( _fail() ); }
2239 if( $has_format ) { _k_format( $ctx, $inst, $format_name, $ptr ) or return( _fail() ); }
2240  
2241 # contentEncoding / contentMediaType / contentSchema (compiled path)
2242 if( exists( $S->{contentEncoding} ) ||
2243 exists( $S->{contentMediaType} ) ||
2244 exists( $S->{contentSchema} ) )
2245 {
2246 my $assert = $ctx->{content_assert} ? 1 : 0;
2247 my $bytes = "$inst";
2248 my $decoded_ref;
2249  
2250 if( exists( $S->{contentEncoding} ) )
2251 {
2252 my $dec = _content_decode( $ctx, $S->{contentEncoding}, $bytes );
2253 if( !defined( $dec ) )
2254 {
2255 return( _err_res( $ctx, $ptr, "contentEncoding '$S->{contentEncoding}' decode failed", 'contentEncoding' ) ) if( $assert );
2256 }
2257 else
2258 {
2259 $bytes = $dec;
2260 }
2261 }
2262  
2263 if( exists( $S->{contentMediaType} ) )
2264 {
2265 my( $mt, $params ) = _parse_media_type( $S->{contentMediaType} );
2266 if( my $cb = $ctx->{media_validators}->{ $mt } )
2267 {
2268 my( $ok, $msg, $maybe_decoded ) = _safe_invoke( $cb, $bytes, $params );
2269 if( !$ok )
2270 {
2271 return( _err_res( $ctx, $ptr, ( $msg || "contentMediaType '$mt' validation failed" ), 'contentMediaType' ) ) if( $assert );
2272 }
2273 # If the media validator decoded into a Perl structure, keep it
2274 $decoded_ref = $maybe_decoded if( ref( $maybe_decoded ) );
2275 # If it produced new octets/text, keep that too
2276 $bytes = $maybe_decoded if( defined( $maybe_decoded ) && !ref( $maybe_decoded ) );
2277 }
2278 else
2279 {
2280 if( $mt =~ m{\Atext/} && ( ( $params->{charset} || '' ) =~ /\Autf-?8\z/i ) )
2281 {
2282 local $@;
2283 my $ok = eval
2284 {
2285 require Encode;
2286 Encode::decode( 'UTF-8', $bytes, Encode::FB_CROAK );
2287 1;
2288 } ? 1 : 0;
2289 if( !$ok && $assert )
2290 {
2291 return( _err_res( $ctx, $ptr, "contentMediaType '$mt' invalid UTF-8", 'contentMediaType' ) );
2292 }
2293 }
2294 }
2295 }
2296  
2297 if( exists( $S->{contentSchema} ) )
2298 {
2299 my $val;
2300  
2301 if( ref( $decoded_ref ) )
2302 {
2303 # already decoded by media validator (e.g. application/json)
2304 $val = $decoded_ref;
2305 }
2306 else
2307 {
2308 local $@;
2309 # still a string of bytes; try JSON decode now
2310 $val = eval{ JSON->new->allow_nonref(1)->utf8(1)->decode( $bytes ) };
2311 }
2312  
2313 if( !defined( $val ) )
2314 {
2315 return( _err_res( $ctx, $ptr, "contentSchema present but payload not JSON-decodable", 'contentSchema' ) ) if( $assert );
2316 }
2317 else
2318 {
2319 my $r = _v( $ctx, _join_ptr( $ptr, 'contentSchema' ), $S->{contentSchema}, $val );
2320 return( $r ) unless( $r->{ok} );
2321 }
2322 }
2323 }
2324 }
2325  
2326 my %ann_props;
2327 my %ann_items;
2328  
2329 # Arrays
2330 if( ref( $inst ) eq 'ARRAY' )
2331 {
2332 my $r = _k_array_all( $ctx, $ptr, $S, $inst );
2333 return( $r ) unless( $r->{ok} );
2334 %ann_items = ( %ann_items, %{$r->{items}} );
2335 }
2336  
2337 # Objects
2338 if( ref( $inst ) eq 'HASH' )
2339 {
2340 my $r = _k_object_all( $ctx, $ptr, $S, $inst );
2341 return( $r ) unless( $r->{ok} );
2342 %ann_props = ( %ann_props, %{$r->{props}} );
2343 }
2344  
2345 # Combinators
2346 # allOf: all subschemas must pass, and we merge their annotations.
2347 if( exists( $S->{allOf} ) && ref( $S->{allOf} ) eq 'ARRAY' )
2348 {
2349 my( %p, %it );
2350 for my $i ( 0 .. $#{ $S->{allOf} } )
2351 {
2352 my $r = $child{ "allOf:$i" }->( $ctx, $inst );
2353 return $r unless $r->{ok};
2354 %p = ( %p, %{$r->{props}} );
2355 %it = ( %it, %{$r->{items}} );
2356 }
2357 %ann_props = ( %ann_props, %p );
2358 %ann_items = ( %ann_items, %it );
2359 }
2360  
2361 # anyOf: at least one subschema must pass; do NOT leak errors from
2362 # non-selected branches into the main context.
2363 if( exists( $S->{anyOf} ) && ref( $S->{anyOf} ) eq 'ARRAY' )
2364 {
2365 my $ok = 0;
2366 my( %p, %it );
2367 my @branch_errs;
2368  
2369 for my $i ( 0 .. $#{ $S->{anyOf} } )
2370 {
2371 # Shadow context for this branch
2372 my %shadow = %$ctx;
2373 my @errs;
2374 $shadow{errors} = \@errs;
2375 $shadow{error_count} = 0;
2376  
2377 my $r = $child{ "anyOf:$i" }->( \%shadow, $inst );
2378  
2379 if( $r->{ok} )
2380 {
2381 $ok = 1;
2382 %p = ( %p, %{$r->{props}} );
2383 %it = ( %it, %{$r->{items}} );
2384 last;
2385 }
2386  
2387 push( @branch_errs, \@errs );
2388 }
2389  
2390 unless( $ok )
2391 {
2392 # No branch matched: merge collected branch errors into main context
2393 for my $aref ( @branch_errs )
2394 {
2395 next unless( @$aref );
2396 push( @{$ctx->{errors}}, @$aref );
2397 $ctx->{error_count} += scalar( @$aref );
2398 }
2399  
2400 return( _err_res( $ctx, $ptr, "instance does not satisfy anyOf", 'anyOf' ) );
2401 }
2402  
2403 %ann_props = ( %ann_props, %p );
2404 %ann_items = ( %ann_items, %it );
2405 }
2406  
2407 # oneOf: exactly one subschema must pass; again, isolate branch errors.
2408 if( exists( $S->{oneOf} ) && ref( $S->{oneOf} ) eq 'ARRAY' )
2409 {
2410 my $hits = 0;
2411  
2412 for my $i ( 0 .. $#{ $S->{oneOf} } )
2413 {
2414 my %shadow = %$ctx;
2415 my @errs;
2416 $shadow{errors} = \@errs;
2417 $shadow{error_count} = 0;
2418  
2419 my $r = $child{ "oneOf:$i" }->( \%shadow, $inst );
2420 $hits++ if( $r->{ok} );
2421 }
2422  
2423 return( _err_res( $ctx, $ptr, "instance satisfies $hits subschemas in oneOf (expected exactly 1)", 'oneOf' ) )
2424 unless( $hits == 1 );
2425 }
2426  
2427 # not: the inner schema must **fail**; its own errors are irrelevant
2428 # on success, so we run it entirely in a shadow context.
2429 if( exists( $S->{not} ) && ref( $S->{not} ) )
2430 {
2431 my %shadow = %$ctx;
2432 my @errs;
2433 $shadow{errors} = \@errs;
2434 $shadow{error_count} = 0;
2435  
2436 my $r = $child{ "not" }->( \%shadow, $inst );
2437  
2438 # If inner schema passes, then "not" fails
2439 return( _err_res( $ctx, $ptr, "instance matches forbidden not-schema", 'not' ) )
2440 if( $r->{ok} );
2441  
2442 # Otherwise, "not" is satisfied; ignore inner errors entirely
2443 }
2444  
2445 # Conditionals
2446 if( exists( $S->{if} ) && ref( $S->{if} ) )
2447 {
2448 my $cond = $child{ "if" }->( $ctx, $inst );
2449 if( $cond->{ok} )
2450 {
2451 if( exists( $child{ "then" } ) )
2452 {
2453 my $r = $child{ "then" }->( $ctx, $inst );
2454 return( $r ) unless( $r->{ok} );
2455 }
2456 }
2457 else
2458 {
2459 if( exists( $child{ "else" } ) )
2460 {
2461 my $r = $child{ "else" }->( $ctx, $inst );
2462 return( $r ) unless( $r->{ok} );
2463 }
2464 }
2465 }
2466  
2467 _t( $ctx, $ptr, 'node', undef, 'pass' ) if( $ctx->{trace_on} );
2468 return( { ok => 1, props => \%ann_props, items => \%ann_items } );
2469 };
2470 }
2471  
2472 # Compilation / Indexing
2473 sub _compile_root
2474 {
2475 my( $schema ) = @_;
2476  
2477 if( ref( $schema ) eq 'HASH' )
2478 {
2479 $schema->{'$defs'} ||= delete( $schema->{definitions} ) if( exists( $schema->{definitions} ) );
2480 }
2481  
2482 my $base = _normalize_uri( ( ref( $schema ) eq 'HASH' && $schema->{'$id'} ) ? $schema->{'$id'} : '#' );
2483  
2484 my $anchors = {};
2485 my $id_index = {};
2486  
2487 _index_schema_202012( $schema, $base, '#', $anchors, $id_index );
2488  
2489 return({
2490 schema => $schema,
2491 anchors => $anchors, # "#/a/b/0"
2492 id_index => $id_index, # absolute IDs and #anchors
2493 base => $base,
2494 fn_index => {}, # cache of ptr => compiled closure
2495 });
2496 }
2497  
2498 sub _content_decode
2499 {
2500 my( $ctx, $enc, $s ) = @_;
2501 $enc = lc( $enc // '' );
2502  
2503 if( my $cb = $ctx->{content_decoders}->{ $enc } )
2504 {
2505 my( $ok, $msg, $out ) = _safe_invoke( $cb, $s );
2506 return( $ok ? $out : undef );
2507 }
2508  
2509 if( $enc eq 'base64' )
2510 {
2511 my $out = _strict_base64_decode( $s );
2512 # undef on failure is exactly what we want
2513 return( $out );
2514 }
2515  
2516 # Unknown encoding (annotation only unless assert)
2517 return;
2518 }
2519  
2520 # Errors, utils, pointers, URIs
2521 sub _err
2522 {
2523 my( $ctx, $schema_ptr, $msg, $keyword ) = @_;
2524 return(0) if( $ctx->{error_count} >= $ctx->{max_errors} );
2525  
2526 # Instance path: use current ptr_stack top if available, else '#'
2527 my $inst_path = $ctx->{ptr_stack} && @{$ctx->{ptr_stack}}
2528 ? ( $ctx->{ptr_stack}->[-1] // '#' )
2529 : '#';
2530  
2531 push( @{$ctx->{errors}}, JSON::Schema::Validate::Error->new(
2532 path => $inst_path,
2533 message => $msg,
2534 keyword => $keyword, # may be undef (back-compat)
2535 schema_pointer => $schema_ptr, # where in the schema this came from
2536 ));
2537 $ctx->{error_count}++;
2538 return(0);
2539 }
2540  
2541 sub _err_res
2542 {
2543 my( $ctx, $schema_ptr, $msg, $keyword ) = @_;
2544 _err( $ctx, $schema_ptr, $msg, $keyword );
2545 return( { ok => 0, props => {}, items => {} } );
2546 }
2547  
2548 # Used by _prune* methods
2549 sub _extract_array_shape
2550 {
2551 my( $self, $schema, $out ) = @_;
2552  
2553 return unless( ref( $schema ) eq 'HASH' );
2554  
2555 if( ref( $schema->{prefixItems} ) eq 'ARRAY' )
2556 {
2557 my $src = $schema->{prefixItems};
2558 for my $i ( 0 .. $#$src )
2559 {
2560 # First win: do not override an existing prefix schema at this index
2561 $out->{prefix_items}->[ $i ] = $src->[ $i ]
2562 unless( defined( $out->{prefix_items}->[ $i ] ) );
2563 }
2564 }
2565  
2566 if( exists( $schema->{items} ) && ref( $schema->{items} ) eq 'HASH' )
2567 {
2568 # Again, first win: if we already have items from another branch, keep it.
2569 $out->{items} = $schema->{items} unless( $out->{items} );
2570 }
2571  
2572 # allOf mixins for arrays as well
2573 if( ref( $schema->{allOf} ) eq 'ARRAY' )
2574 {
2575 foreach my $sub ( @{$schema->{allOf}} )
2576 {
2577 $self->_extract_array_shape( $sub, $out );
2578 }
2579 }
2580  
2581 # anyOf / oneOf / not ignored for same reason as objects.
2582 }
2583  
2584 # Used by _prune* methods
2585 sub _extract_object_shape
2586 {
2587 my( $self, $schema, $out ) = @_;
2588  
2589 return unless( ref( $schema ) eq 'HASH' );
2590  
2591 # Direct properties
2592 if( ref( $schema->{properties} ) eq 'HASH' )
2593 {
2594 foreach my $k ( keys( %{$schema->{properties}} ) )
2595 {
2596 # First win: do not override an already-collected subschema
2597 $out->{props}->{ $k } = $schema->{properties}->{ $k }
2598 unless( exists( $out->{props}->{ $k } ) );
2599 }
2600 }
2601  
2602 # patternProperties
2603 if( ref( $schema->{patternProperties} ) eq 'HASH' )
2604 {
2605 foreach my $re ( keys( %{$schema->{patternProperties}} ) )
2606 {
2607 push( @{$out->{patterns}}, [ $re, $schema->{patternProperties}->{ $re } ] );
2608 }
2609 }
2610  
2611 # additionalProperties
2612 if( exists( $schema->{additionalProperties} ) )
2613 {
2614 my $ap = $schema->{additionalProperties};
2615  
2616 # JSON booleans or plain scalars
2617 if( !ref( $ap ) || ( blessed( $ap ) && $ap->isa( 'JSON::PP::Boolean' ) ) )
2618 {
2619 if( $ap )
2620 {
2621 # true: additionalProperties allowed; keep any stricter setting we might already have
2622 $out->{allow_ap} = 1 unless( defined( $out->{allow_ap} ) && !$out->{allow_ap} );
2623 # do not touch ap_schema here
2624 }
2625 else
2626 {
2627 # false: forbidden regardless of earlier "true"
2628 $out->{allow_ap} = 0;
2629 $out->{ap_schema} = undef;
2630 }
2631 }
2632 elsif( ref( $ap ) eq 'HASH' )
2633 {
2634 # Schema for additionals
2635 $out->{allow_ap} = 1;
2636 $out->{ap_schema} = $ap;
2637 }
2638 }
2639  
2640 # allOf mixins: merge their object keywords as well.
2641 if( ref( $schema->{allOf} ) eq 'ARRAY' )
2642 {
2643 foreach my $sub ( @{$schema->{allOf}} )
2644 {
2645 $self->_extract_object_shape( $sub, $out );
2646 }
2647 }
2648  
2649 # NOTE:
2650 # We intentionally ignore anyOf / oneOf / not for pruning.
2651 # Without performing full validation against each branch, we cannot
2652 # safely decide which properties are truly forbidden, so we err on
2653 # the side of *keeping* more rather than over-pruning.
2654 }
2655  
2656 sub _fail { return( { ok => 0, props => {}, items => {} } ); }
2657  
2658 sub _first_error_text
2659 {
2660 my( $errs ) = @_;
2661 return( '' ) unless( @$errs );
2662 my $e = $errs->[0];
2663 return( "$e" );
2664 }
2665  
2666 sub _get_args_as_hash
2667 {
2668 my $self = shift( @_ );
2669 return( {} ) if( !scalar( @_ ) );
2670 my $ref = {};
2671 if( scalar( @_ ) == 1 &&
2672 defined( $_[0] ) &&
2673 ( ref( $_[0] ) || '' ) eq 'HASH' )
2674 {
2675 $ref = shift( @_ );
2676 }
2677 elsif( !( scalar( @_ ) % 2 ) )
2678 {
2679 $ref = { @_ };
2680 }
2681 else
2682 {
2683 die( "Uneven number of parameters provided: '", join( "', '", map( overload::StrVal( $_ ), @_ ) ), "'" );
2684 }
2685 return( $ref );
2686 }
2687  
2688 sub _index_schema_202012
2689 {
2690 my( $node, $base_uri, $ptr, $anchors, $id_index ) = @_;
2691  
2692 $anchors->{ $ptr } = $node;
2693  
2694 my $here_base = $base_uri;
2695  
2696 if( ref( $node ) eq 'HASH' )
2697 {
2698 if( exists( $node->{'$id'} ) && defined( $node->{'$id'} ) && $node->{'$id'} ne '' )
2699 {
2700 $here_base = _resolve_uri( $base_uri, $node->{'$id'} );
2701 $id_index->{ $here_base } = $node;
2702 }
2703  
2704 if( exists( $node->{'$anchor'} ) && defined( $node->{'$anchor'} ) && $node->{'$anchor'} ne '' )
2705 {
2706 my $abs = $here_base . '#' . $node->{'$anchor'};
2707 $id_index->{ $abs } = $node;
2708 }
2709  
2710 if( exists( $node->{'$dynamicAnchor'} ) && defined( $node->{'$dynamicAnchor'} ) && $node->{'$dynamicAnchor'} ne '' )
2711 {
2712 my $abs = $here_base . '#dyn:' . $node->{'$dynamicAnchor'};
2713 $id_index->{ $abs } = $node;
2714 }
2715  
2716 for my $k ( sort( keys( %$node ) ) )
2717 {
2718 my $child = $node->{ $k };
2719 my $child_ptr = _join_ptr( $ptr, $k );
2720 _index_schema_202012( $child, $here_base, $child_ptr, $anchors, $id_index );
2721 }
2722 }
2723 elsif( ref( $node ) eq 'ARRAY' )
2724 {
2725 for my $i ( 0 .. $#$node )
2726 {
2727 my $child = $node->[$i];
2728 my $child_ptr = _join_ptr( $ptr, $i );
2729 _index_schema_202012( $child, $here_base, $child_ptr, $anchors, $id_index );
2730 }
2731 }
2732 }
2733  
2734 sub _inst_addr
2735 {
2736 my( $inst, $ptr ) = @_;
2737 return( "SCALAR:$ptr" ) unless( ref( $inst ) );
2738 return( ref( $inst ) . ':' . refaddr( $inst ) );
2739 }
2740  
2741 # truthy helpers
2742 sub _is_hash { my $v = shift; return ref($v) eq 'HASH' ? 1 : 0; }
2743  
2744 sub _is_number
2745 {
2746 my( $v ) = @_;
2747  
2748 return(0) if( ref( $v ) );
2749 return(0) unless( defined( $v ) );
2750  
2751 # Strict JSON typing: accept only scalars that actually carry numeric flags.
2752 # JSON marks numbers with IOK/NOK; plain strings (even "12") will not have them.
2753 my $sv = B::svref_2object( \$v );
2754 my $flags = $sv->FLAGS;
2755  
2756 local $@;
2757 # SVf_IOK = 0x02000000, SVf_NOK = 0x04000000 on most builds;
2758 # we do not hardcode constants—B::SV’s FLAGS is stable to test with these bitmasks.
2759 # Use string eval to avoid importing platform-specific constants.
2760 my $SVf_IOK = eval{ B::SVf_IOK() } || 0x02000000;
2761 my $SVf_NOK = eval{ B::SVf_NOK() } || 0x04000000;
2762  
2763 return( ( $flags & ( $SVf_IOK | $SVf_NOK ) ) ? 1 : 0 );
2764 }
2765  
2766 sub _is_true { my $v = shift( @_ ); return( ref( $v ) eq 'HASH' ? 0 : $v ? 1 : 0 ); }
2767  
2768 sub _join_ptr
2769 {
2770 my( $base, @tokens ) = @_;
2771  
2772 # Default base to '#' if not provided
2773 $base = '#' unless( defined( $base ) && length( $base ) );
2774  
2775 my $ptr = $base;
2776  
2777 for my $token ( @tokens )
2778 {
2779 next unless( defined( $token ) );
2780  
2781 # Proper rfc6901 JSON Pointer escaping
2782 $token =~ s/~/~0/g;
2783 $token =~ s/\//~1/g;
2784  
2785 if( $ptr eq '#' )
2786 {
2787 $ptr = "#/$token";
2788 }
2789 else
2790 {
2791 $ptr .= "/$token";
2792 }
2793 }
2794  
2795 return( $ptr );
2796 }
2797  
2798 sub _js_quote
2799 {
2800 my $s = shift( @_ );
2801 $s = '' unless( defined( $s ) );
2802 $s =~ s/\\/\\\\/g;
2803 $s =~ s/'/\\'/g;
2804 $s =~ s/\r\n/\n/g;
2805 $s =~ s/\r/\n/g;
2806 $s =~ s/\n/\\n/g;
2807 return( "'$s'" );
2808 }
2809  
2810 sub _json_equal
2811 {
2812 my( $a, $b ) = @_;
2813 return( _canon( $a ) eq _canon( $b ) );
2814 }
2815  
2816 # Very small JSON Pointer resolver for internal refs ("#/...") for JS compile
2817 sub _jsv_resolve_internal_ref
2818 {
2819 my( $root, $ptr ) = @_;
2820  
2821 return( $root ) if( !defined( $ptr ) || $ptr eq '' || $ptr eq '#' );
2822  
2823 # Expect something like "#/definitions/address"
2824 $ptr =~ s/^#//;
2825  
2826 my @tokens = split( /\//, $ptr );
2827 shift( @tokens ) if( @tokens && $tokens[0] eq '' );
2828  
2829 my $node = $root;
2830  
2831 TOKEN:
2832 for my $tok ( @tokens )
2833 {
2834 # rfc6901 JSON Pointer unescaping
2835 $tok =~ s/~1/\//g;
2836 $tok =~ s/~0/~/g;
2837  
2838 if( ref( $node ) eq 'HASH' )
2839 {
2840 # Draft 2020-12 alias: allow "definitions" to hit "$defs" if needed
2841 if( $tok eq 'definitions' &&
2842 !exists( $node->{definitions} ) &&
2843 exists( $node->{'$defs'} ) )
2844 {
2845 $tok = '$defs';
2846 }
2847  
2848 unless( exists( $node->{ $tok } ) )
2849 {
2850 # Optional: help debug resolution problems
2851 warn( "_jsv_resolve_internal_ref: token '$tok' not found in current hash for pointer '$ptr'\n" )
2852 if( $JSON::Schema::Validate::DEBUG );
2853 return;
2854 }
2855 $node = $node->{ $tok };
2856 }
2857 elsif( ref( $node ) eq 'ARRAY' )
2858 {
2859 unless( $tok =~ /^\d+$/ && $tok < @$node )
2860 {
2861 warn( "_jsv_resolve_internal_ref: array index '$tok' out of range for pointer '$ptr'\n" )
2862 if( $JSON::Schema::Validate::DEBUG );
2863 return;
2864 }
2865 $node = $node->[ $tok ];
2866 }
2867 else
2868 {
2869 warn( "_jsv_resolve_internal_ref: reached non-container node while resolving '$ptr'\n" )
2870 if( $JSON::Schema::Validate::DEBUG );
2871 return;
2872 }
2873 }
2874  
2875 return( $node );
2876 }
2877  
2878 # Keyword groups
2879 sub _k_array_all
2880 {
2881 my( $ctx, $sp, $S, $A ) = @_;
2882  
2883 if( exists( $S->{minItems} ) && @$A < $S->{minItems} )
2884 {
2885 return( _err_res( $ctx, $sp, "array has fewer than minItems $S->{minItems}", 'minItems' ) );
2886 }
2887 if( exists( $S->{maxItems} ) && @$A > $S->{maxItems} )
2888 {
2889 return( _err_res( $ctx, $sp, "array has more than maxItems $S->{maxItems}", 'maxItems' ) );
2890 }
2891  
2892 if( $S->{uniqueItems} )
2893 {
2894 my %seen;
2895 for my $i ( 0 .. $#$A )
2896 {
2897 my $k = _canon( $A->[$i] );
2898 if( $seen{ $k }++ )
2899 {
2900 return( _err_res( $ctx, _join_ptr( $sp, $i ), "array items not unique", 'uniqueItems' ) );
2901 }
2902 }
2903 }
2904  
2905 my %items_ann;
2906  
2907 if( ref( $S->{prefixItems} ) eq 'ARRAY' )
2908 {
2909 my $tuple = $S->{prefixItems};
2910 for my $i ( 0 .. $#$A )
2911 {
2912 push( @{$ctx->{ptr_stack}}, _join_ptr( $sp, $i ) );
2913  
2914 if( $i <= $#$tuple )
2915 {
2916 my $r = _v( $ctx, _join_ptr( $sp, "prefixItems/$i" ), $tuple->[$i], $A->[$i] );
2917 return( $r ) unless( $r->{ok} );
2918 $items_ann{ $i } = 1;
2919 }
2920 elsif( exists( $S->{items} ) && ref( $S->{items} ) eq 'HASH' )
2921 {
2922 my $r = _v( $ctx, _join_ptr( $sp, "items" ), $S->{items}, $A->[$i] );
2923 return( $r ) unless( $r->{ok} );
2924 $items_ann{ $i } = 1;
2925 }
2926  
2927 pop( @{$ctx->{ptr_stack}} );
2928 }
2929 }
2930 elsif( ref( $S->{items} ) eq 'HASH' )
2931 {
2932 for my $i ( 0 .. $#$A )
2933 {
2934 push( @{$ctx->{ptr_stack}}, _join_ptr( $sp, $i ) );
2935 my $r = _v( $ctx, _join_ptr( $sp, "items" ), $S->{items}, $A->[$i] );
2936 return( $r ) unless( $r->{ok} );
2937 $items_ann{ $i } = 1;
2938 pop( @{$ctx->{ptr_stack}} );
2939 }
2940 }
2941  
2942 if( exists( $S->{contains} ) )
2943 {
2944 my $matches = 0;
2945  
2946 # Quiet sub-context to avoid emitting errors for non-matching items
2947 for my $i ( 0 .. $#$A )
2948 {
2949 my %shadow = %$ctx;
2950 my @errs;
2951 $shadow{errors} = \@errs;
2952 $shadow{error_count} = 0;
2953  
2954 my $tmp = _v( \%shadow, _join_ptr( $sp, "contains" ), $S->{contains}, $A->[$i] );
2955 $matches++ if( $tmp->{ok} );
2956 }
2957  
2958 my $minc = defined( $S->{minContains} ) ? $S->{minContains} : 1;
2959 my $maxc = defined( $S->{maxContains} ) ? $S->{maxContains} : ( 2**31 - 1 );
2960  
2961 return( _err_res( $ctx, $sp, "contains matched $matches < minContains $minc", 'minContains' ) ) if( $matches < $minc );
2962 return( _err_res( $ctx, $sp, "contains matched $matches > maxContains $maxc", 'maxContains' ) ) if( $matches > $maxc );
2963 }
2964  
2965 if( exists( $S->{unevaluatedItems} ) )
2966 {
2967 my @unknown = ();
2968 for my $i ( 0 .. $#$A )
2969 {
2970 next if( $items_ann{ $i } );
2971 push( @unknown, $i );
2972 }
2973 my $UE = $S->{unevaluatedItems};
2974 if( !_is_true( $UE ) && !_is_hash( $UE ) )
2975 {
2976 return( _err_res( $ctx, $sp, "unevaluatedItems not allowed at indices: " . join( ',', @unknown ), 'unevaluatedItems' ) ) if( @unknown );
2977 }
2978 elsif( ref( $UE ) eq 'HASH' )
2979 {
2980 for my $i ( @unknown )
2981 {
2982 my $r = _v( $ctx, _join_ptr( $sp, "unevaluatedItems" ), $UE, $A->[$i] );
2983 return( $r ) unless( $r->{ok} );
2984 $items_ann{ $i } = 1;
2985 }
2986 }
2987 }
2988  
2989 return( { ok => 1, props => {}, items => \%items_ann } );
2990 }
2991  
2992 sub _k_combinator
2993 {
2994 my( $ctx, $sp, $S, $inst, $kw ) = @_;
2995  
2996  
2997 # allOf: all subschemas must pass, we merge their annotations
2998 if( $kw eq 'allOf' )
2999 {
3000 my %props;
3001 my %items;
3002  
3003 for my $i ( 0 .. $#{$S->{allOf}} )
3004 {
3005 my $r = _v( $ctx, _join_ptr( $sp, "allOf/$i" ), $S->{allOf}->[ $i ], $inst );
3006 return( $r ) unless( $r->{ok} );
3007  
3008 %props = ( %props, %{$r->{props}} );
3009 %items = ( %items, %{$r->{items}} );
3010 }
3011  
3012 return( { ok => 1, props => \%props, items => \%items } );
3013 }
3014  
3015 # anyOf: at least one subschema must pass.
3016 # Errors from failing branches must NOT leak into the main context.
3017 if( $kw eq 'anyOf' )
3018 {
3019 my @branch_errs;
3020  
3021 for my $i ( 0 .. $#{$S->{anyOf}} )
3022 {
3023 # Shadow context: isolate errors for this branch
3024 my %shadow = %$ctx;
3025 my @errs;
3026 $shadow{errors} = \@errs;
3027 $shadow{error_count} = 0;
3028  
3029 my $r = _v( \%shadow, _join_ptr( $sp, "anyOf/$i" ), $S->{anyOf}->[ $i ], $inst );
3030  
3031 if( $r->{ok} )
3032 {
3033 # One branch passed: combinator satisfied.
3034 # Ignore all other branch errors.
3035 return( { ok => 1, props => {}, items => {} } );
3036 }
3037  
3038 push( @branch_errs, \@errs );
3039 }
3040  
3041 # No branch matched: merge collected branch errors into main context
3042 for my $aref ( @branch_errs )
3043 {
3044 next unless( @$aref );
3045 push( @{$ctx->{errors}}, @$aref );
3046 $ctx->{error_count} += scalar( @$aref );
3047 }
3048  
3049 return( _err_res( $ctx, $sp, "instance does not satisfy anyOf", 'anyOf' ) );
3050 }
3051  
3052 # oneOf: exactly one subschema must pass.
3053 # Again, do not leak errors from non-selected branches.
3054 if( $kw eq 'oneOf' )
3055 {
3056 my @ok_results;
3057 my @branch_errs;
3058  
3059 for my $i ( 0 .. $#{$S->{oneOf}} )
3060 {
3061 my %shadow = %$ctx;
3062 my @errs;
3063 $shadow{errors} = \@errs;
3064 $shadow{error_count} = 0;
3065  
3066 my $r = _v( \%shadow, _join_ptr( $sp, "oneOf/$i" ), $S->{oneOf}->[$i], $inst );
3067  
3068 if( $r->{ok} )
3069 {
3070 push( @ok_results, $r );
3071 }
3072 else
3073 {
3074 push( @branch_errs, \@errs );
3075 }
3076 }
3077  
3078 if( @ok_results == 1 )
3079 {
3080 # Exactly one branch matched: combinator satisfied.
3081 # Do NOT bubble up branch props/items through oneOf.
3082 return( { ok => 1, props => {}, items => {} } );
3083 }
3084  
3085 # Zero or >1 matched -> failure; merge branch errors
3086 for my $aref ( @branch_errs )
3087 {
3088 next unless( @$aref );
3089 push( @{$ctx->{errors}}, @$aref );
3090 $ctx->{error_count} += scalar( @$aref );
3091 }
3092  
3093 return(
3094 _err_res(
3095 $ctx,
3096 $sp,
3097 "instance satisfies " . scalar( @ok_results ) . " schemas in oneOf (expected exactly 1)",
3098 'oneOf'
3099 )
3100 );
3101 }
3102  
3103 # not: subschema must NOT validate.
3104 # Any errors from validating the inner schema are irrelevant on success.
3105 if( $kw eq 'not' )
3106 {
3107 my %shadow = %$ctx;
3108 my @errs;
3109 $shadow{errors} = \@errs;
3110 $shadow{error_count} = 0;
3111  
3112 my $r = _v( \%shadow, _join_ptr( $sp, "not" ), $S->{not}, $inst );
3113  
3114 # If inner schema passes, then "not" fails
3115 return( _err_res( $ctx, $sp, "instance matches forbidden not-schema", 'not' ) )
3116 if( $r->{ok} );
3117  
3118 # Otherwise, "not" is satisfied; ignore inner errors entirely
3119 return( { ok => 1, props => {}, items => {} } );
3120 }
3121  
3122 # Unknown / unsupported combinator (defensive default)
3123 return( { ok => 1, props => {}, items => {} } );
3124 }
3125  
3126 sub _k_const
3127 {
3128 my( $ctx, $v, $const, $ptr ) = @_;
3129 return(1) if( _json_equal( $v, $const ) );
3130 return( _err( $ctx, $ptr, "const mismatch", 'const' ) );
3131 }
3132  
3133 sub _k_enum
3134 {
3135 my( $ctx, $v, $arr, $ptr ) = @_;
3136 for my $e ( @$arr )
3137 {
3138 return(1) if( _json_equal( $v, $e ) );
3139 }
3140 return( _err( $ctx, $ptr, "value not in enum", 'enum' ) );
3141 }
3142  
3143 sub _k_format
3144 {
3145 my( $ctx, $s, $fmt, $ptr ) = @_;
3146 my $cb = $ctx->{formats}->{ $fmt };
3147 return(1) unless( $cb );
3148 local $@;
3149 my $ok = eval{ $cb->( $s ) ? 1 : 0 };
3150 return( $ok ? 1 : _err( $ctx, $ptr, "string fails format '$fmt'", 'format' ) );
3151 }
3152  
3153 sub _k_if_then_else
3154 {
3155 my( $ctx, $sp, $S, $inst ) = @_;
3156  
3157 # Evaluate "if" in a shadow context so its errors do NOT leak
3158 my %shadow = %$ctx;
3159 my @errs;
3160 $shadow{errors} = \@errs;
3161 $shadow{error_count} = 0;
3162  
3163 my $cond = _v( \%shadow, _join_ptr( $sp, 'if' ), $S->{if}, $inst );
3164  
3165 if( $cond->{ok} )
3166 {
3167 _t( $ctx, $sp, 'if', undef, 'pass', 'then' ) if( $ctx->{trace_on} );
3168 return( { ok => 1, props => {}, items => {} } )
3169 unless( exists( $S->{then} ) );
3170  
3171 # Apply "then" against the REAL context
3172 return( _v( $ctx, _join_ptr( $sp, 'then' ), $S->{then}, $inst ) );
3173 }
3174 else
3175 {
3176 _t( $ctx, $sp, 'if', undef, 'pass', 'else' ) if( $ctx->{trace_on} );
3177 return( { ok => 1, props => {}, items => {} } )
3178 unless( exists( $S->{else} ) );
3179  
3180 # Apply "else" against the REAL context
3181 return( _v( $ctx, _join_ptr( $sp, 'else' ), $S->{else}, $inst ) );
3182 }
3183 }
3184  
3185 sub _k_number
3186 {
3187 my( $ctx, $v, $kw, $arg, $ptr ) = @_;
3188 if( $kw eq 'multipleOf' )
3189 {
3190 # Guard per spec: multipleOf must be > 0
3191 if( !defined( $arg ) || $arg <= 0 )
3192 {
3193 _t( $ctx, $ptr, 'multipleOf', undef, 'fail', 'arg<=0' ) if( $ctx->{trace_on} );
3194 return( _err( $ctx, $ptr, "multipleOf must be > 0", 'multipleOf' ) );
3195 }
3196 # Float-tolerant multiple check
3197 # my $ok = abs( ( $v / $arg ) - int( $v / $arg + 1e-10 ) ) < 1e-9;
3198 my $ok = abs( ( $v / $arg ) - int( $v / $arg + 0.0000000001 ) ) < 1e-9;
3199 _t( $ctx, $ptr, 'multipleOf', undef, $ok ? 'pass' : 'fail', "$v mod $arg" ) if( $ctx->{trace_on} );
3200 return( $ok ? 1 : _err( $ctx, $ptr, "number not multipleOf $arg" ) );
3201 }
3202 elsif( $kw eq 'minimum' )
3203 {
3204 _t( $ctx, $ptr, 'minimum', undef, $v >= $arg ? 'pass' : 'fail', "$v >= $arg" ) if( $ctx->{trace_on} );
3205 return( $v >= $arg ? 1 : _err( $ctx, $ptr, "number less than minimum $arg", 'minimum' ) );
3206 }
3207 elsif( $kw eq 'maximum' )
3208 {
3209 _t( $ctx, $ptr, 'maximum', undef, $v <= $arg ? 'pass' : 'fail', "$v <= $arg" ) if( $ctx->{trace_on} );
3210 return( $v <= $arg ? 1 : _err( $ctx, $ptr, "number greater than maximum $arg", 'maximum' ) );
3211 }
3212 elsif( $kw eq 'exclusiveMinimum' )
3213 {
3214 _t( $ctx, $ptr, 'exclusiveMinimum', undef, $v > $arg ? 'pass' : 'fail', "$v > $arg" ) if( $ctx->{trace_on} );
3215 return( $v > $arg ? 1 : _err( $ctx, $ptr, "number not greater than exclusiveMinimum $arg", 'exclusiveMinimum' ) );
3216 }
3217 elsif( $kw eq 'exclusiveMaximum' )
3218 {
3219 _t( $ctx, $ptr, 'exclusiveMaximum', undef, $v < $arg ? 'pass' : 'fail', "$v < $arg" ) if( $ctx->{trace_on} );
3220 return( $v < $arg ? 1 : _err( $ctx, $ptr, "number not less than exclusiveMaximum $arg", 'exclusiveMaximum' ) );
3221 }
3222 return(1);
3223 }
3224  
3225 sub _k_object_all
3226 {
3227 my( $ctx, $sp, $S, $H ) = @_;
3228  
3229 my $ok = 1;
3230  
3231 my $bail_if_max = sub
3232 {
3233 return( $ctx->{max_errors} && $ctx->{error_count} >= $ctx->{max_errors} ) ? 1 : 0;
3234 };
3235  
3236 if( exists( $S->{minProperties} ) && ( scalar( keys( %$H ) ) ) < $S->{minProperties} )
3237 {
3238 _err_res( $ctx, $sp, "object has fewer than minProperties $S->{minProperties}", 'minProperties' );
3239 $ok = 0;
3240 return( { ok => 0, props => {}, items => {} } ) if( $bail_if_max->() );
3241 }
3242 if( exists( $S->{maxProperties} ) && ( scalar( keys( %$H ) ) ) > $S->{maxProperties} )
3243 {
3244 _err_res( $ctx, $sp, "object has more than maxProperties $S->{maxProperties}", 'maxProperties' );
3245 $ok = 0;
3246 return( { ok => 0, props => {}, items => {} } ) if( $bail_if_max->() );
3247 }
3248  
3249 # Merge required from:
3250 # - top-level "required" (array only)
3251 # - property-level { required => 1 } or { optional => 0 }
3252 my %required;
3253  
3254 if( exists( $S->{required} ) && ref( $S->{required} ) eq 'ARRAY' )
3255 {
3256 $required{ $_ } = 1 for( @{ $S->{required} } );
3257 }
3258  
3259 if( my $P = $S->{properties} )
3260 {
3261 for my $k ( keys( %$P ) )
3262 {
3263 my $pd = $P->{ $k };
3264 next unless( ref( $pd ) eq 'HASH' );
3265  
3266 if( exists( $pd->{required} ) )
3267 {
3268 $required{ $k } = $pd->{required} ? 1 : 0;
3269 }
3270 if( exists( $pd->{optional} ) )
3271 {
3272 $required{ $k } = $pd->{optional} ? 0 : 1; # optional => 0 means required
3273 }
3274 }
3275 }
3276  
3277 for my $rq ( grep{ $required{ $_ } } keys( %required ) )
3278 {
3279 next if( exists( $H->{ $rq } ) );
3280 _t( $ctx,$sp, 'required', undef, 'fail', $rq ) if( $ctx->{trace_on} );
3281  
3282 my @need = sort grep { $required{ $_ } } keys %required;
3283 my @have = sort keys %$H;
3284  
3285 my $need_str = @need ? join( ', ', @need ) : '(none)';
3286 my $have_str = @have ? join( ', ', @have ) : '(none)';
3287  
3288 my $msg = "required property '$rq' is missing "
3289 . "(required: $need_str; present: $have_str)";
3290  
3291 _err_res(
3292 $ctx,
3293 _join_ptr( $sp, $rq ),
3294 $msg,
3295 'required'
3296 );
3297  
3298 $ok = 0;
3299 return( { ok => 0, props => {}, items => {} } ) if( $bail_if_max->() );
3300 }
3301  
3302 if( exists( $S->{propertyNames} ) && ref( $S->{propertyNames} ) eq 'HASH' )
3303 {
3304 for my $k ( keys( %$H ) )
3305 {
3306 my $r = _v( $ctx, _join_ptr( $sp, "propertyNames" ), $S->{propertyNames}, $k );
3307 if( !$r->{ok} )
3308 {
3309 $ok = 0;
3310 return( { ok => 0, props => {}, items => {} } ) if( $bail_if_max->() );
3311 }
3312 }
3313 }
3314  
3315 my $props = $S->{properties} || {};
3316 my $patprops = $S->{patternProperties} || {};
3317 my $addl_set = exists( $S->{additionalProperties} );
3318 my $addl = $addl_set ? $S->{additionalProperties} : JSON::true;
3319  
3320 my %ann;
3321  
3322 for my $k ( sort( keys( %$H ) ) )
3323 {
3324 my $v = $H->{ $k };
3325 my $matched = 0;
3326  
3327 my $child_path = _join_ptr( $sp, $k );
3328 push( @{$ctx->{ptr_stack}}, $child_path );
3329  
3330 if( exists( $props->{ $k } ) )
3331 {
3332 my $r = _v( $ctx, _join_ptr( $sp, "properties/$k" ), $props->{ $k }, $v );
3333 if( !$r->{ok} )
3334 {
3335 $ok = 0;
3336 pop( @{$ctx->{ptr_stack}} );
3337 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3338 next;
3339 }
3340 $ann{ $k } = 1;
3341 $matched = 1;
3342 }
3343  
3344 unless( $matched )
3345 {
3346 local $@;
3347 for my $re ( keys( %$patprops ) )
3348 {
3349 my $re_ok = eval{ $k =~ /$re/ };
3350 next unless( $re_ok );
3351  
3352 my $r = _v( $ctx, _join_ptr( $sp, "patternProperties/$re" ), $patprops->{ $re }, $v );
3353 if( !$r->{ok} )
3354 {
3355 $ok = 0;
3356 pop( @{$ctx->{ptr_stack}} );
3357 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3358 next;
3359 }
3360 $ann{ $k } = 1;
3361 $matched = 1;
3362 }
3363 }
3364  
3365 unless( $matched )
3366 {
3367 if( $addl_set && !_is_true( $addl ) && !_is_hash( $addl ) )
3368 {
3369 _err_res( $ctx, _join_ptr( $sp, $k ), "additionalProperties not allowed: '$k'", 'additionalProperties' );
3370 $ok = 0;
3371 pop( @{$ctx->{ptr_stack}} );
3372 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3373 next;
3374 }
3375 elsif( ref( $addl ) eq 'HASH' )
3376 {
3377 my $r = _v( $ctx, _join_ptr( $sp, "additionalProperties" ), $addl, $v );
3378 if( !$r->{ok} )
3379 {
3380 $ok = 0;
3381 pop( @{$ctx->{ptr_stack}} );
3382 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3383 next;
3384 }
3385 $ann{ $k } = 1;
3386 }
3387 }
3388  
3389 pop( @{$ctx->{ptr_stack}} );
3390 }
3391  
3392 if( my $depR = $S->{dependentRequired} )
3393 {
3394 for my $k ( keys( %$depR ) )
3395 {
3396 next unless( exists( $H->{ $k } ) );
3397 for my $need ( @{$depR->{ $k } || []} )
3398 {
3399 next if( exists( $H->{ $need } ) );
3400 _err_res( $ctx, _join_ptr( $sp, $need ), "dependentRequired: '$need' required when '$k' is present", 'dependentRequired' );
3401 $ok = 0;
3402 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3403 }
3404 }
3405 }
3406  
3407 if( my $depS = $S->{dependentSchemas} )
3408 {
3409 for my $k ( keys( %$depS ) )
3410 {
3411 next unless( exists( $H->{ $k } ) );
3412 my $r = _v( $ctx, _join_ptr( $sp, "dependentSchemas/$k" ), $depS->{ $k }, $H );
3413 if( !$r->{ok} )
3414 {
3415 $ok = 0;
3416 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3417 }
3418 }
3419 }
3420  
3421 if( exists( $S->{unevaluatedProperties} ) )
3422 {
3423 my @unknown = grep { !$ann{ $_ } } keys( %$H );
3424 my $UE = $S->{unevaluatedProperties};
3425  
3426 if( !_is_true( $UE ) && !_is_hash( $UE ) )
3427 {
3428 if( @unknown )
3429 {
3430 _err_res( $ctx, $sp, "unevaluatedProperties not allowed: " . join( ',', @unknown ), 'unevaluatedProperties' );
3431 $ok = 0;
3432 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3433 }
3434 }
3435 elsif( ref( $UE ) eq 'HASH' )
3436 {
3437 for my $k ( @unknown )
3438 {
3439 my $r = _v( $ctx, _join_ptr( $sp, "unevaluatedProperties" ), $UE, $H->{ $k } );
3440 if( !$r->{ok} )
3441 {
3442 $ok = 0;
3443 return( { ok => 0, props => \%ann, items => {} } ) if( $bail_if_max->() );
3444 next;
3445 }
3446 $ann{ $k } = 1;
3447 }
3448 }
3449 }
3450  
3451 return( { ok => ( $ok ? 1 : 0 ), props => \%ann, items => {} } );
3452 }
3453  
3454 sub _k_string
3455 {
3456 my( $ctx, $s, $S, $ptr ) = @_;
3457 my $len = _strlen( $s );
3458  
3459 if( exists( $S->{minLength} ) && $len < $S->{minLength} )
3460 {
3461 _t( $ctx, $ptr, 'minLength', undef, 'fail', "len=$len < $S->{minLength}" ) if( $ctx->{trace_on} );
3462 return( _err( $ctx, $ptr, "string shorter than minLength $S->{minLength}", 'minLength' ) );
3463 }
3464 _t( $ctx, $ptr, 'minLength', undef, 'pass', "len=$len >= $S->{minLength}" ) if( exists( $S->{minLength} ) && $ctx->{trace_on} );
3465  
3466 if( exists( $S->{maxLength} ) && $len > $S->{maxLength} )
3467 {
3468 _t( $ctx, $ptr, 'maxLength', undef, 'fail', "len=$len > $S->{maxLength}" ) if( $ctx->{trace_on} );
3469 return( _err( $ctx, $ptr, "string longer than maxLength $S->{maxLength}", 'maxLength' ) );
3470 }
3471 _t( $ctx, $ptr, 'maxLength', undef, 'pass', "len=$len <= $S->{maxLength}" ) if( exists( $S->{maxLength} ) && $ctx->{trace_on} );
3472  
3473 if( exists( $S->{pattern} ) )
3474 {
3475 my $re = $S->{pattern};
3476 local $@;
3477 my $ok = eval{ $s =~ /$re/ };
3478 _t( $ctx, $ptr, 'pattern', undef, $ok ? 'pass' : 'fail', "/$re/" ) if( $ctx->{trace_on} );
3479 return( _err( $ctx, $ptr, "string does not match pattern /$re/", 'pattern' ) ) unless( $ok );
3480 }
3481 return(1);
3482 }
3483  
3484 # Primitive keyword helpers
3485 sub _k_type
3486 {
3487 my( $ctx, $v, $type_kw, $ptr ) = @_;
3488  
3489 my @alts = ref( $type_kw ) eq 'ARRAY' ? @$type_kw : ( $type_kw );
3490  
3491 # First, allow inline schemas in the union
3492 my $i = 0;
3493 for my $alt ( @alts )
3494 {
3495 if( ref( $alt ) eq 'HASH' )
3496 {
3497 my $r = _v( $ctx, _join_ptr( $ptr, "type/$i" ), $alt, $v );
3498 return(1) if( $r->{ok} );
3499 }
3500 $i++;
3501 }
3502  
3503 # Then, try string type names
3504 for my $t ( @alts )
3505 {
3506 next if( ref( $t ) );
3507 return(1) if( _match_type( $v, $t ) );
3508 }
3509  
3510 my $exp = join( '|', map{ ref( $_ ) ? 'schema' : $_ } @alts );
3511 return( _err( $ctx, $ptr, "type mismatch: expected $exp", 'type' ) );
3512 }
3513  
3514 sub _k_unique_keys
3515 {
3516 my( $ctx, $sp, $uk_def, $array ) = @_;
3517 unless( ref( $uk_def ) eq 'ARRAY' && @$uk_def )
3518 {
3519 return( { ok => 1, props => {}, items => {} } );
3520 }
3521  
3522 for my $key_set ( @$uk_def )
3523 {
3524 next unless( ref( $key_set ) eq 'ARRAY' && @$key_set );
3525  
3526 my %seen;
3527 for my $i ( 0 .. $#$array )
3528 {
3529 my $item = $array->[$i];
3530 next unless( ref( $item ) eq 'HASH' );
3531  
3532 my @key_vals;
3533 my $all_present = 1;
3534 for my $key ( @$key_set )
3535 {
3536 if( exists( $item->{ $key } ) )
3537 {
3538 push( @key_vals, _canon( $item->{ $key } ) );
3539 }
3540 else
3541 {
3542 $all_present = 0;
3543 last;
3544 }
3545 }
3546  
3547 # Skip items that do not have *all* keys in this key set
3548 next unless( $all_present );
3549  
3550 my $composite = join( "\0", @key_vals );
3551 if( exists( $seen{ $composite } ) )
3552 {
3553 my $prev_i = $seen{ $composite };
3554 my $keys = join( ', ', map { "'$_'" } @$key_set );
3555 push( @{$ctx->{ptr_stack}}, _join_ptr( $sp, $i ) );
3556 my $res = _err_res(
3557 $ctx,
3558 $sp,
3559 "uniqueKeys violation: items[$prev_i] and items[$i] have identical values for key(s) [$keys]",
3560 'uniqueKeys',
3561 );
3562 pop( @{$ctx->{ptr_stack}} );
3563  
3564 return( $res );
3565 }
3566 $seen{ $composite } = $i;
3567 }
3568 }
3569  
3570 return( { ok => 1, props => {}, items => {} } );
3571 }
3572  
3573 sub _match_type
3574 {
3575 my( $v, $t ) = @_;
3576  
3577 return(1) if( $t eq 'null' && !defined( $v ) );
3578  
3579 if( $t eq 'boolean' )
3580 {
3581 return(0) if( !defined( $v ) );
3582 if( blessed( $v ) && ( ref( $v ) =~ /Boolean/ ) )
3583 {
3584 my $s = "$v";
3585 return( ( $s eq '0' || $s eq '1' ) ? 1 : 0 );
3586 }
3587 return( ( $v =~ /\A(?:0|1|true|false)\z/i ) ? 1 : 0 );
3588 }
3589  
3590 if( $t eq 'integer' )
3591 {
3592 return(0) unless( _is_number( $v ) );
3593 return( ( $v =~ /\A-?(?:0|[1-9][0-9]*)\z/ ) ? 1 : 0 );
3594 }
3595  
3596 if( $t eq 'number' )
3597 {
3598 return( _is_number( $v ) );
3599 }
3600  
3601 if( $t eq 'string' )
3602 {
3603 # Must be a scalar, defined, and NOT a numeric SV under strict typing.
3604 return( (!ref( $v ) && defined( $v ) && !_is_number( $v )) ? 1 : 0 );
3605 }
3606  
3607 return(1) if( $t eq 'array' && ref( $v ) eq 'ARRAY' );
3608 return(1) if( $t eq 'object' && ref( $v ) eq 'HASH' );
3609  
3610 return(0);
3611 }
3612  
3613 sub _normalize_uri
3614 {
3615 my( $u ) = @_;
3616 return( '#' ) unless( defined( $u ) && length( $u ) );
3617 return( $u );
3618 }
3619  
3620 sub _parse_media_type
3621 {
3622 my( $s ) = @_;
3623 my( $type, @rest ) = split( /;/, "$s" );
3624 $type ||= '';
3625 $type =~ s/\s+//g;
3626 my %p;
3627 for my $kv ( @rest )
3628 {
3629 my( $k, $v ) = split( /=/, $kv, 2 );
3630 next unless( defined( $k ) );
3631 $k =~ s/\s+//g;
3632 $v = '' unless( defined( $v ) );
3633 $v =~ s/^\s+|\s+$//g;
3634 # Allow single or double quote, but be consistent
3635 $v =~ s/^(?<quote>["'])(.*)\g{quote}$/$2/;
3636 $p{ lc( $k ) } = $v;
3637 }
3638 return( lc( $type ), \%p );
3639 }
3640  
3641 sub _prune_array_with_schema
3642 {
3643 my( $self, $schema, $data ) = @_;
3644  
3645 my @out;
3646  
3647 my $shape =
3648 {
3649 prefix_items => [], # index => subschema
3650 items => undef # subschema for additional items
3651 };
3652  
3653 $self->_extract_array_shape( $schema, $shape );
3654  
3655 for my $i ( 0 .. $#$data )
3656 {
3657 my $item = $data->[ $i ];
3658 my $item_schema;
3659  
3660 if( defined( $shape->{prefix_items}->[ $i ] ) )
3661 {
3662 $item_schema = $shape->{prefix_items}->[ $i ];
3663 }
3664 elsif( $shape->{items} )
3665 {
3666 $item_schema = $shape->{items};
3667 }
3668  
3669 if( $item_schema && ref( $item ) )
3670 {
3671 $out[ $i ] = $self->_prune_with_schema( $item_schema, $item );
3672 }
3673 else
3674 {
3675 # No structural knowledge or scalar item: keep as-is
3676 $out[ $i ] = $item;
3677 }
3678 }
3679  
3680 return( \@out );
3681 }
3682  
3683 sub _prune_object_with_schema
3684 {
3685 my( $self, $schema, $data ) = @_;
3686  
3687 # Collect effective object shape from this schema and any allOf mixins.
3688 my $shape =
3689 {
3690 props => {}, # property name => subschema
3691 patterns => [], # [ regex, subschema ] ...
3692 allow_ap => 1, # additionalProperties allowed?
3693 ap_schema => undef # subschema for additionalProperties, if any
3694 };
3695  
3696 $self->_extract_object_shape( $schema, $shape );
3697  
3698 my %clean;
3699  
3700 KEY:
3701 foreach my $key ( keys( %$data ) )
3702 {
3703 my $val = $data->{ $key };
3704  
3705 # 1) Direct properties
3706 if( exists( $shape->{props}->{ $key } ) )
3707 {
3708 my $sub = $shape->{props}->{ $key };
3709 $clean{ $key } = $self->_prune_with_schema( $sub, $val );
3710 next KEY;
3711 }
3712  
3713 # 2) patternProperties
3714 foreach my $pair ( @{$shape->{patterns}} )
3715 {
3716 my( $re, $pschema ) = @$pair;
3717 my $ok;
3718  
3719 {
3720 local $@;
3721 $ok = eval{ $key =~ /$re/ ? 1 : 0; };
3722 }
3723  
3724 next unless( $ok );
3725  
3726 $clean{ $key } = $self->_prune_with_schema( $pschema, $val );
3727 next KEY;
3728 }
3729  
3730 # 3) additionalProperties
3731 if( $shape->{allow_ap} )
3732 {
3733 if( $shape->{ap_schema} && ref( $val ) )
3734 {
3735 $clean{ $key } = $self->_prune_with_schema( $shape->{ap_schema}, $val );
3736 }
3737 else
3738 {
3739 # allowed, but no further structure known
3740 $clean{ $key } = $val;
3741 }
3742 }
3743 else
3744 {
3745 # additionalProperties is false (or equivalent) => drop unknown key
3746 next KEY;
3747 }
3748 }
3749  
3750 return( \%clean );
3751 }
3752  
3753 sub _prune_with_schema
3754 {
3755 my( $self, $schema, $data ) = @_;
3756  
3757 # Boolean schemas and non-hash schemas: do not attempt pruning.
3758 return( $data ) unless( ref( $schema ) eq 'HASH' );
3759  
3760 # Only prune structured values; scalars we leave untouched.
3761 if( ref( $data ) eq 'HASH' )
3762 {
3763 return( $self->_prune_object_with_schema( $schema, $data ) );
3764 }
3765 elsif( ref( $data ) eq 'ARRAY' )
3766 {
3767 return( $self->_prune_array_with_schema( $schema, $data ) );
3768 }
3769  
3770 return( $data );
3771 }
3772  
3773 sub _ptr_of_node
3774 {
3775 my( $root, $target ) = @_;
3776 for my $p ( keys( %{$root->{anchors}} ) )
3777 {
3778 my $n = $root->{anchors}->{ $p };
3779 return( $p ) if( $n eq $target );
3780 }
3781 return( '#' );
3782 }
3783  
3784 my %SCRIPT_LIKE = map{ $_ => 1 } qw(
3785 Hiragana Katakana Han Hangul Latin Cyrillic Greek
3786 Hebrew Thai Armenian Georgian
3787 Arabic Devanagari Bengali Gurmukhi Gujarati Oriya
3788 Tamil Telugu Kannada Malayalam Sinhala
3789 Lao Tibetan Myanmar Khmer
3790 );
3791 sub _re_to_js
3792 {
3793 my $re = shift( @_ );
3794 my %opt = @_;
3795  
3796 # style: 'literal' => for use in /.../u
3797 # 'string' => for use in new RegExp("...", "u")
3798 my $style = $opt{style} || 'string';
3799  
3800 return if( !defined( $re ) || !length( $re ) );
3801  
3802 #
3803 # 1) Convert \x{...} (Perl) to \u.... or \u{....} (JS)
3804 # - 1–4 hex digits -> \uHHHH
3805 # - 5–6 hex digits -> \u{HHHHH} (requires /u in JS)
3806 #
3807 $re =~ s{
3808 \\x\{([0-9A-Fa-f]{1,6})\}
3809 }{
3810 my $hex = uc( $1 );
3811 if( length( $hex ) <= 4 )
3812 {
3813 "\\u$hex";
3814 }
3815 else
3816 {
3817 "\\u\{$hex\}";
3818 }
3819 }egx;
3820  
3821 # Script eXtended
3822 #
3823 # 2) Convert \p{Katakana} / \P{Katakana}
3824 # to \p{scx=Katakana} / \P{scx=Katakana}
3825 # (Script_Extensions so it covers half-width too)
3826 #
3827 $re =~ s[
3828 \\([pP])\{([^}]+)\}
3829 ][
3830 my( $p, $name ) = ( $1, $2 );
3831  
3832 my $norm = $name;
3833 $norm =~ s/^\s+|\s+$//g;
3834 $norm = ucfirst( lc( $norm ) );
3835  
3836 if( exists( $SCRIPT_LIKE{ $norm } ) )
3837 {
3838 "\\$p\{scx=$norm\}";
3839 }
3840 else
3841 {
3842 # Pass other properties through unchanged:
3843 # \p{L}, \p{Letter}, \p{Nd}, etc.
3844 "\\$p\{$name\}";
3845 }
3846 ]egx;
3847  
3848 #
3849 # 3) Optionally escape backslashes for JS string literal
3850 #
3851 if( $style eq 'string' )
3852 {
3853 $re =~ s{\\}{\\\\}g; # existing
3854 $re =~ s{"}{\\"}g; # escape "
3855 $re =~ s{\n}{\\n}g;
3856 $re =~ s{\r}{\\r}g;
3857 $re =~ s{/}{\/}g;
3858 }
3859  
3860 # For 'literal', we leave backslashes as-is, for use in /.../u
3861  
3862 return( $re );
3863 }
3864  
3865 sub _register_builtin_media_validators
3866 {
3867 my( $self ) = @_;
3868  
3869 # Example: application/json
3870 $self->register_media_validator( 'application/json' => sub
3871 {
3872 my( $bytes, $params ) = @_;
3873 local $@;
3874 my $v = eval{ JSON->new->allow_nonref(1)->decode( $bytes ) };
3875 return( 0, 'invalid JSON', undef ) if( $@ );
3876 # JSON value is valid even if it’s 0, "", or false
3877 return( 1, undef, $v );
3878 } );
3879  
3880 return( $self );
3881 }
3882  
3883 sub _resolve_uri
3884 {
3885 my( $base, $ref ) = @_;
3886 return( $ref ) if( !defined( $base ) || $base eq '' || $ref =~ /^[A-Za-z][A-Za-z0-9+\-.]*:/ );
3887 if( $ref =~ /^\#/ )
3888 {
3889 ( my $no_frag = $base ) =~ s/\#.*$//;
3890 return( $no_frag . $ref );
3891 }
3892 return( $base . $ref ) if( $base =~ /\/$/ );
3893 ( my $dir = $base ) =~ s{[^/]*$}{};
3894 return( $dir . $ref );
3895 }
3896  
3897 sub _safe_invoke
3898 {
3899 my( $cb, @args ) = @_;
3900 local $@;
3901 # Force list context to preserve (ok, msg, out) style returns
3902 my @ret = eval{ $cb->( @args ) };
3903 return( 0, ( $@ || 'callback failed' ), undef ) if( $@ );
3904  
3905 # If callback returns (ok, msg, out) or (ok, msg)
3906 if( @ret >= 2 )
3907 {
3908 my( $ok, $msg, $out ) = ( $ret[0] ? 1 : 0, $ret[1], $ret[2] );
3909 return( $ok, $msg, $out );
3910 }
3911  
3912 # If callback returns a single value
3913 if( @ret == 1 )
3914 {
3915 my $v = $ret[0];
3916 # Reference => treat as decoded structure (success)
3917 return( 1, undef, $v ) if( ref( $v ) );
3918 # Defined scalar => truthiness decides; scalar can be treated as decoded bytes
3919 return( $v ? 1 : 0, undef, ( defined( $v ) ? $v : undef ) );
3920 }
3921  
3922 # Empty list => treat as failure (safer default)
3923 return( 0, 'callback returned no value', undef );
3924 }
3925  
3926 sub _strlen
3927 {
3928 my( $s ) = @_;
3929 $s = Encode::decode( 'UTF-8', "$s", Encode::FB_DEFAULT ) unless( Encode::is_utf8( $s ) );
3930 my @cp = unpack( 'U*', $s );
3931 return( scalar( @cp ) );
3932 }
3933  
3934 # Strict base64: validates alphabet, padding, length, and round-trips
3935 sub _strict_base64_decode
3936 {
3937 my( $s ) = @_;
3938 return unless( defined( $s ) );
3939  
3940 # strip ASCII whitespace per RFC 4648 §3.3 (tests commonly include raw)
3941 ( my $norm = "$s" ) =~ s/\s+//g;
3942  
3943 # valid alphabet + padding only
3944 return unless( $norm =~ /\A[A-Za-z0-9+\/]*={0,2}\z/ );
3945  
3946 # length must be a multiple of 4
3947 return unless( ( length( $norm ) % 4 ) == 0 );
3948  
3949 local $@;
3950 return unless( eval{ require MIME::Base64; 1 } );
3951  
3952 my $out = MIME::Base64::decode_base64( $norm );
3953  
3954 # re-encode and compare to ensure no silent salvage
3955 my $re = MIME::Base64::encode_base64( $out, '' );
3956 # RFC allows omitting trailing '=' if not needed; normalize both
3957 $re =~ s/\s+//g;
3958 $norm =~ s/\s+//g;
3959 return unless( $re eq $norm );
3960 return( $out );
3961 }
3962  
3963 sub _t
3964 {
3965 my( $ctx, $schema_ptr, $keyword, $inst_path, $outcome, $note ) = @_;
3966 return unless( $ctx->{trace_on} );
3967  
3968 if( $ctx->{trace_limit} && @{$ctx->{trace}} >= $ctx->{trace_limit} )
3969 {
3970 return;
3971 }
3972 if( $ctx->{trace_sample} )
3973 {
3974 return if( int( rand(100) ) >= $ctx->{trace_sample} );
3975 }
3976  
3977 push( @{$ctx->{trace}},
3978 {
3979 schema_ptr => $schema_ptr,
3980 keyword => $keyword,
3981 inst_path => ( $ctx->{ptr_stack}->[-1] // '#' ),
3982 outcome => $outcome, # 'pass' | 'fail'
3983 note => $note, # short string
3984 });
3985 }
3986  
3987 # Validation core with annotation + recursion
3988 # _v returns { ok => 0|1, props => {k=>1,...}, items => {i=>1,...} }
3989 sub _v
3990 {
3991 my( $ctx, $schema_ptr, $schema, $inst ) = @_;
3992  
3993 # Recursion guard only for reference types
3994 if( ref( $inst ) )
3995 {
3996 my $inst_addr = _inst_addr( $inst, $ctx->{ptr_stack}->[-1] );
3997 my $vkey = "$schema_ptr|$inst_addr";
3998 return( { ok => 1, props => {}, items => {} } ) if( $ctx->{visited}->{ $vkey }++ );
3999 }
4000  
4001 # Enter dynamicAnchor scope if present
4002 my $frame_added = 0;
4003 if( ref( $schema ) eq 'HASH' &&
4004 exists( $schema->{'$dynamicAnchor'} ) &&
4005 defined( $schema->{'$dynamicAnchor'} ) &&
4006 $schema->{'$dynamicAnchor'} ne '' )
4007 {
4008 my %frame = %{$ctx->{dyn_stack}->[-1]}; # inherit
4009 $frame{ $schema->{'$dynamicAnchor'} } = $schema;
4010 push( @{$ctx->{dyn_stack}}, \%frame );
4011 $frame_added = 1;
4012 }
4013  
4014 my $res = _v_node( $ctx, $schema_ptr, $schema, $inst );
4015  
4016 if( $frame_added )
4017 {
4018 pop( @{$ctx->{dyn_stack}} );
4019 }
4020  
4021 return( $res );
4022 }
4023  
4024 sub _v_node
4025 {
4026 my( $ctx, $schema_ptr, $schema, $inst ) = @_;
4027  
4028 # $ref / $dynamicRef first
4029 if( ref( $schema ) eq 'HASH' &&
4030 exists( $schema->{'$ref'} ) )
4031 {
4032 return( _apply_ref( $ctx, $schema_ptr, $schema->{'$ref'}, $inst ) );
4033 }
4034 if( ref( $schema ) eq 'HASH' &&
4035 exists( $schema->{'$dynamicRef'} ) )
4036 {
4037 return( _apply_dynamic_ref( $ctx, $schema_ptr, $schema->{'$dynamicRef'}, $inst ) );
4038 }
4039 if( ref( $schema ) eq 'HASH' &&
4040 exists( $schema->{'$comment'} ) &&
4041 defined( $schema->{'$comment'} ) )
4042 {
4043 my $c = $schema->{'$comment'};
4044 if( my $cb = $ctx->{comment_handler} )
4045 {
4046 local $@;
4047 eval{ $cb->( $schema_ptr, "$c" ) };
4048 # ignore callback errors to keep validation resilient
4049 }
4050 _t( $ctx, $schema_ptr, '$comment', undef, 'visit', "$c" ) if( $ctx->{trace_on} );
4051 }
4052  
4053 _t( $ctx, $schema_ptr, 'node', undef, 'visit' ) if( $ctx->{trace_on} );
4054  
4055 # Use compiled validator if enabled
4056 if( $ctx->{compile_on} )
4057 {
4058 my $fn = $ctx->{root}->{fn_index}->{ $schema_ptr };
4059 unless( $fn )
4060 {
4061 $fn = _compile_node( $ctx->{root}, $schema_ptr, $schema );
4062 $ctx->{root}->{fn_index}->{ $schema_ptr } = $fn;
4063 }
4064 return( $fn->( $ctx, $inst ) );
4065 }
4066  
4067 return( { ok => 1, props => {}, items => {} } ) unless( ref( $schema ) eq 'HASH' );
4068  
4069 my $ptr = $schema_ptr;
4070  
4071 # Types / const / enum
4072 if( exists( $schema->{type} ) )
4073 {
4074 _k_type( $ctx, $inst, $schema->{type}, $ptr ) or return( _fail() );
4075 }
4076 if( exists( $schema->{const} ) )
4077 {
4078 _k_const( $ctx, $inst, $schema->{const}, $ptr ) or return( _fail() );
4079 }
4080 if( exists( $schema->{enum} ) )
4081 {
4082 _k_enum( $ctx, $inst, $schema->{enum}, $ptr ) or return( _fail() );
4083 }
4084 _t( $ctx, $schema_ptr, 'type/const/enum', undef, 'pass', '' ) if( $ctx->{trace_on} );
4085  
4086 if( $ctx->{unique_keys} &&
4087 exists( $schema->{uniqueKeys} ) &&
4088 ref( $schema->{uniqueKeys} ) eq 'ARRAY' &&
4089 ref( $inst ) eq 'ARRAY' )
4090 {
4091 my $r = _k_unique_keys( $ctx, $ptr, $schema->{uniqueKeys}, $inst );
4092 return( $r ) unless( $r->{ok} );
4093 }
4094  
4095 # Numbers
4096 if( _is_number( $inst ) )
4097 {
4098 for my $k ( qw( multipleOf minimum maximum exclusiveMinimum exclusiveMaximum ) )
4099 {
4100 next unless( exists( $schema->{ $k } ) );
4101 _k_number( $ctx, $inst, $k, $schema->{ $k }, $ptr ) or return( _fail() );
4102 }
4103 }
4104  
4105 # Strings
4106 if( !ref( $inst ) && defined( $inst ) )
4107 {
4108 if( exists( $schema->{minLength} ) || exists( $schema->{maxLength} ) || exists( $schema->{pattern} ) )
4109 {
4110 _k_string( $ctx, $inst, $schema, $ptr ) or return( _fail() );
4111 }
4112 if( exists( $schema->{format} ) )
4113 {
4114 _k_format( $ctx, $inst, $schema->{format}, $ptr ) or return( _fail() );
4115 }
4116  
4117 # contentEncoding / contentMediaType / contentSchema
4118 if( exists( $schema->{contentEncoding} ) ||
4119 exists( $schema->{contentMediaType} ) ||
4120 exists( $schema->{contentSchema} ) )
4121 {
4122 my $assert = $ctx->{content_assert} ? 1 : 0;
4123 my $bytes = "$inst";
4124 my $decoded_ref;
4125  
4126 if( exists( $schema->{contentEncoding} ) )
4127 {
4128 my $dec = _content_decode( $ctx, $schema->{contentEncoding}, $bytes );
4129 if( !defined( $dec ) )
4130 {
4131 return( _err_res( $ctx, $ptr, "contentEncoding '$schema->{contentEncoding}' decode failed", 'contentEncoding' ) ) if( $assert );
4132 }
4133 else
4134 {
4135 $bytes = $dec;
4136 }
4137 }
4138  
4139 if( exists( $schema->{contentMediaType} ) )
4140 {
4141 my( $mt, $params ) = _parse_media_type( $schema->{contentMediaType} );
4142 if( my $cb = $ctx->{media_validators}->{ $mt } )
4143 {
4144 my( $ok, $msg, $maybe_decoded ) = _safe_invoke( $cb, $bytes, $params );
4145 if( !$ok )
4146 {
4147 return( _err_res( $ctx, $ptr, ( $msg || "contentMediaType '$mt' validation failed", 'contentMediaType' ) ) ) if( $assert );
4148 }
4149 $decoded_ref = $maybe_decoded if( ref( $maybe_decoded ) );
4150 $bytes = $maybe_decoded if( defined( $maybe_decoded ) && !ref( $maybe_decoded ) );
4151 }
4152 else
4153 {
4154 if( $mt =~ m{\Atext/} && ( ( $params->{charset} || '' ) =~ /\Autf-?8\z/i ) )
4155 {
4156 local $@;
4157 my $ok = eval
4158 {
4159 require Encode;
4160 Encode::decode( 'UTF-8', $bytes, Encode::FB_CROAK );
4161 1;
4162 } ? 1 : 0;
4163 if( !$ok && $assert )
4164 {
4165 return( _err_res( $ctx, $ptr, "contentMediaType '$mt' invalid UTF-8", 'contentMediaType' ) );
4166 }
4167 }
4168 }
4169 }
4170  
4171 if( exists( $schema->{contentSchema} ) )
4172 {
4173 my $val;
4174 if( ref( $decoded_ref ) )
4175 {
4176 $val = $decoded_ref; # already decoded by media validator
4177 }
4178 else
4179 {
4180 local $@;
4181 $val = eval{ JSON->new->allow_nonref(1)->utf8(1)->decode( $bytes ) };
4182 }
4183  
4184 if( !defined( $val ) )
4185 {
4186 return( _err_res( $ctx, $ptr, "contentSchema present but payload not JSON-decodable", 'contentSchema' ) ) if( $assert );
4187 }
4188 else
4189 {
4190 my $r = _v( $ctx, _join_ptr( $ptr, 'contentSchema' ), $schema->{contentSchema}, $val );
4191 return( $r ) unless( $r->{ok} );
4192 }
4193 }
4194 }
4195 }
4196  
4197 my %ann_props;
4198 my %ann_items;
4199  
4200 # Arrays
4201 if( ref( $inst ) eq 'ARRAY' )
4202 {
4203 my $r = _k_array_all( $ctx, $schema_ptr, $schema, $inst );
4204 return( $r ) unless( $r->{ok} );
4205 %ann_items = ( %ann_items, %{ $r->{items} } );
4206 }
4207 _t( $ctx, $schema_ptr, 'array', undef, 'pass', '' ) if( ref( $inst ) eq 'ARRAY' && $ctx->{trace_on} );
4208  
4209 # Objects
4210 if( ref( $inst ) eq 'HASH' )
4211 {
4212 my $r = _k_object_all( $ctx, $schema_ptr, $schema, $inst );
4213 return( $r ) unless( $r->{ok} );
4214 %ann_props = ( %ann_props, %{ $r->{props} } );
4215 }
4216 _t( $ctx, $schema_ptr, 'object', undef, 'pass', '' ) if( ref( $inst ) eq 'HASH' && $ctx->{trace_on} );
4217  
4218 # Combinators
4219 for my $comb ( qw( allOf anyOf oneOf not ) )
4220 {
4221 next unless( exists( $schema->{ $comb } ) );
4222 my $r = _k_combinator( $ctx, $schema_ptr, $schema, $inst, $comb );
4223 return( $r ) unless( $r->{ok} );
4224 %ann_props = ( %ann_props, %{ $r->{props} } );
4225 %ann_items = ( %ann_items, %{ $r->{items} } );
4226 _t( $ctx, $schema_ptr, $comb, undef, 'pass', '' ) if( $ctx->{trace_on} );
4227 }
4228  
4229 # Conditionals
4230 if( exists( $schema->{if} ) )
4231 {
4232 my $r = _k_if_then_else( $ctx, $schema_ptr, $schema, $inst );
4233 return( $r ) unless( $r->{ok} );
4234 %ann_props = ( %ann_props, %{ $r->{props} } );
4235 %ann_items = ( %ann_items, %{ $r->{items} } );
4236 }
4237  
4238 _t( $ctx, $schema_ptr, 'node', undef, 'pass' ) if( $ctx->{trace_on} );
4239 return( { ok => 1, props => \%ann_props, items => \%ann_items } );
4240 }
4241  
4242 # NOTE: JSON::Schema::Validate::Error
4243 package JSON::Schema::Validate::Error;
4244 BEGIN
4245 {
4246 use strict;
4247 use warnings;
4248 use vars qw( $VERSION );
4249 use overload (
4250 '""' => 'as_string',
4251 'eq' => sub{ _obj_eq(@_) },
4252 'ne' => sub{ !_obj_eq(@_) },
4253 '==' => sub{ _obj_eq(@_) },
4254 '!=' => sub{ !_obj_eq(@_) },
4255 bool => sub{1},
4256 fallback => 1,
4257 );
4258 our $VERSION = 'v0.1.0';
4259 };
4260  
4261 use strict;
4262 use warnings;
4263 use utf8;
4264  
4265 sub new
4266 {
4267 my $that = shift( @_ );
4268 my $ref = {};
4269 # Legacy instantiation
4270 # We make sure this is not one single option that was provided to us.
4271 if( @_ == 2 && $_[0] !~ /^(?:path|message|keyword|schema_pointer)$/ )
4272 {
4273 @$ref{qw( path message )} = @_;
4274 }
4275 else
4276 {
4277 my $args = { @_ };
4278 for( qw( path message keyword schema_pointer ) )
4279 {
4280 $ref->{ $_ } = $args->{ $_ } if( exists( $args->{ $_ } ) );
4281 }
4282 }
4283 return( bless( $ref => ( ref( $that ) || $that ) ) );
4284 }
4285  
4286 sub as_hash
4287 {
4288 my $self = shift( @_ );
4289 my $ref = {};
4290 my @keys = qw( keyword message path schema_pointer );
4291 @$ref{ @keys } = @$self{ @keys };
4292 return( $ref );
4293 }
4294  
4295 sub as_string
4296 {
4297 my $self = shift( @_ );
4298 my $sp = $self->schema_pointer // '';
4299 my $path = $self->path // '';
4300 my $msg = $self->message // '';
4301 # Dual-path if avail
4302 return( $sp ? "${sp} → ${path}: ${msg}" : "${path}: ${msg}" );
4303 }
4304  
4305 sub keyword
4306 {
4307 my $self = shift( @_ );
4308 $self->{keyword} = shift( @_ ) if( @_ );
4309 return( $self->{keyword} );
4310 }
4311  
4312 sub message
4313 {
4314 my $self = shift( @_ );
4315 $self->{message} = shift( @_ ) if( @_ );
4316 return( $self->{message} );
4317 }
4318  
4319 sub path
4320 {
4321 my $self = shift( @_ );
4322 $self->{path} = shift( @_ ) if( @_ );
4323 return( $self->{path} );
4324 }
4325  
4326 sub schema_pointer
4327 {
4328 my $self = shift( @_ );
4329 $self->{schema_pointer} = shift( @_ ) if( @_ );
4330 return( $self->{schema_pointer} );
4331 }
4332  
4333 sub _obj_eq
4334 {
4335 no overloading;
4336 my $self = shift( @_ );
4337 my $other = shift( @_ );
4338 my $me;
4339 if( defined( $other ) &&
4340 Scalar::Util::blessed( $other ) &&
4341 $other->isa( 'JSON::Schema::Validate::Error' ) )
4342 {
4343 if( ( $self->message // '' ) eq ( $other->message // '' ) &&
4344 ( $self->path // '' ) eq ( $other->path // '' ) )
4345 {
4346 return(1);
4347 }
4348 else
4349 {
4350 return(0);
4351 }
4352 }
4353 # Compare error message
4354 elsif( !ref( $other ) )
4355 {
4356 my $me = $self->message // '';
4357 return( $me eq $other );
4358 }
4359 # Otherwise some reference data to which we cannot compare
4360 return(0) ;
4361 }
4362  
4363 1;
4364 # NOTE: POD
4365 __END__