jsonschema_rs 0.62.0 → 0.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +21 -1
- data/Cargo.toml +2 -2
- data/README.md +24 -0
- data/ext/jsonschema/Cargo.lock +13 -13
- data/ext/jsonschema/Cargo.toml +3 -3
- data/lib/jsonschema/version.rb +1 -1
- data/sig/jsonschema.rbs +50 -7
- data/src/json_text.rs +239 -0
- data/src/lib.rs +102 -35
- data/src/options.rs +141 -34
- data/src/ser.rs +1 -1
- metadata +3 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 11341f312f2370a4aad4177a118b755a93c5c5125b9f16909a3789ac4d32b723
|
|
4
|
+
data.tar.gz: 459de3dbe56f54449b438e4ba989e1a5210c25cbcd79592c907861feae30538d
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 2a1321a9cf38d77fe449faf466b01272c37e39072e970c009fcc9eff7d88de8df13db108dd73fb822d2d03b01a7e7a3b25d791c513ee718579255a35214f89eb
|
|
7
|
+
data.tar.gz: 20c4f5cbbfe0baf5a7a1a1c6172426b04c5bac79c5572e993ff93d7ead9453766c4996a89481c52395fc245d1ff392b4648d9db5daf81d082be6e826a7eca773
|
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.63.0] - 2026-11-22
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `JsonTextValidator`, validating instances given as JSON text without building Ruby objects for them.
|
|
10
|
+
- `JSONSchema.number_format`, a custom `format` check that reads numbers.
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- `$ref` to a bundled meta-schema of a draft other than the schema's own, such as `https://json-schema.org/draft/2020-12/schema` from a Draft 7 schema, failing to resolve.
|
|
15
|
+
- `$ref` to a `json-schema.org` URI with no bundled meta-schema, such as `http://json-schema.org/draft-03/schema#`, never retrieved.
|
|
16
|
+
- Error messages for an empty `enum` ending after "is not one of" instead of naming the empty `enum`.
|
|
17
|
+
- `HttpOptions.new(ca_cert: ...)` accepting a file without certificates.
|
|
18
|
+
- Draft 4 schemas with an empty `enum`, or one with equal members such as `[0, 0.0]`, passing the meta-schema check.
|
|
19
|
+
- `HttpOptions.new(ca_cert: ...)` reporting invalid PEM as an HTTP client build error instead of a certificate parse error that names the file.
|
|
20
|
+
- Custom keyword `iter_errors` returning a non-exception producing a message prefixed with `RuntimeError: ` and no `cause`.
|
|
21
|
+
- Named backreferences such as `(?<n>x)\k<n>` failing to build in `pattern`, `patternProperties` and `propertyNames`.
|
|
22
|
+
- Patterns with a backreference or lookaround matching `\d`, `\w`, `\s` and `.` beyond ECMA 262, and rejecting a backreference to a group that did not match.
|
|
23
|
+
|
|
5
24
|
## [0.62.0] - 2026-11-21
|
|
6
25
|
|
|
7
26
|
### Added
|
|
@@ -854,7 +873,8 @@
|
|
|
854
873
|
|
|
855
874
|
- Initial public release
|
|
856
875
|
|
|
857
|
-
[Unreleased]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.
|
|
876
|
+
[Unreleased]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.63.0...HEAD
|
|
877
|
+
[0.63.0]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.62.0...ruby-v0.63.0
|
|
858
878
|
[0.62.0]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.61.2...ruby-v0.62.0
|
|
859
879
|
[0.61.2]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.61.1...ruby-v0.61.2
|
|
860
880
|
[0.61.1]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.61.0...ruby-v0.61.1
|
data/Cargo.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "jsonschema-rb"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.63.0"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
authors = ["Dmitry Dygalo <dmitry@dygalo.dev>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -14,7 +14,7 @@ crate-type = ["cdylib"]
|
|
|
14
14
|
|
|
15
15
|
[dependencies]
|
|
16
16
|
strum = "0.28.0"
|
|
17
|
-
jsonschema = { version = "0.
|
|
17
|
+
jsonschema = { version = "0.63.0", default-features = false, features = ["magnus", "arbitrary-precision", "resolve-http", "resolve-file", "tls-ring", "macros", "idna", "json-text"] }
|
|
18
18
|
magnus = { version = "0.9", features = ["rb-sys"] }
|
|
19
19
|
rb-sys = "0.9"
|
|
20
20
|
serde = { workspace = true }
|
data/README.md
CHANGED
|
@@ -119,6 +119,22 @@ validator = JSONSchema::Draft7Validator.new(schema)
|
|
|
119
119
|
|
|
120
120
|
With a chosen draft (a draft-specific class or `draft:`), the `$schema` URI is not retrieved: pass a custom meta-schema in `registry:` so its `$vocabulary` applies.
|
|
121
121
|
|
|
122
|
+
### Validating JSON text
|
|
123
|
+
|
|
124
|
+
When instances arrive as JSON text, such as request bodies or queue messages,
|
|
125
|
+
`JsonTextValidator` validates the string directly, without building Ruby objects for it.
|
|
126
|
+
It takes the same keyword arguments as `validator_for`, plus `draft:`:
|
|
127
|
+
|
|
128
|
+
```ruby
|
|
129
|
+
validator = JSONSchema::JsonTextValidator.new({ "type" => "object", "required" => ["id"] })
|
|
130
|
+
|
|
131
|
+
validator.valid?('{"id": 1}') # => true
|
|
132
|
+
validator.valid?('{"name": "x"}') # => false
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Text that is not a single JSON document raises `ArgumentError`, and a repeated key keeps its last
|
|
136
|
+
value, as with `JSON.parse`. Custom keywords receive the instance as Ruby objects.
|
|
137
|
+
|
|
122
138
|
### Custom format validators
|
|
123
139
|
|
|
124
140
|
Pass a Proc or lambda that takes a `String` and returns a boolean via `formats`. Drafts 2019-09 and 2020-12 treat `format` as an annotation, so set `validate_formats: true` to get it checked:
|
|
@@ -133,6 +149,14 @@ validator = JSONSchema.validator_for(
|
|
|
133
149
|
)
|
|
134
150
|
```
|
|
135
151
|
|
|
152
|
+
To check numbers, wrap the callable in `JSONSchema.number_format`; it receives an `Integer`, `Float` or `BigDecimal`:
|
|
153
|
+
|
|
154
|
+
```ruby
|
|
155
|
+
int32 = JSONSchema.number_format(->(number) { number.between?(-(2**31), (2**31) - 1) })
|
|
156
|
+
validator = JSONSchema.validator_for({ "format" => "int32" }, validate_formats: true, formats: { "int32" => int32 })
|
|
157
|
+
validator.valid?(2**31) # => false
|
|
158
|
+
```
|
|
159
|
+
|
|
136
160
|
### Custom keyword validators
|
|
137
161
|
|
|
138
162
|
```ruby
|
data/ext/jsonschema/Cargo.lock
CHANGED
|
@@ -693,9 +693,9 @@ dependencies = [
|
|
|
693
693
|
|
|
694
694
|
[[package]]
|
|
695
695
|
name = "jsonschema"
|
|
696
|
-
version = "0.
|
|
696
|
+
version = "0.63.0"
|
|
697
697
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
698
|
-
checksum = "
|
|
698
|
+
checksum = "f4d2afab27172a0073112ce84a64ec7fd06f3b8bdad37d46e86c53c933ed232b"
|
|
699
699
|
dependencies = [
|
|
700
700
|
"ahash",
|
|
701
701
|
"bytecount",
|
|
@@ -727,9 +727,9 @@ dependencies = [
|
|
|
727
727
|
|
|
728
728
|
[[package]]
|
|
729
729
|
name = "jsonschema-macros"
|
|
730
|
-
version = "0.
|
|
730
|
+
version = "0.63.0"
|
|
731
731
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
732
|
-
checksum = "
|
|
732
|
+
checksum = "d3dc0b4debd8aecd40d1f0d432d5ecf259c24b6feaccb8ebc8c610338c5d0f89"
|
|
733
733
|
dependencies = [
|
|
734
734
|
"jsonschema-macros-core",
|
|
735
735
|
"proc-macro2",
|
|
@@ -737,9 +737,9 @@ dependencies = [
|
|
|
737
737
|
|
|
738
738
|
[[package]]
|
|
739
739
|
name = "jsonschema-macros-core"
|
|
740
|
-
version = "0.
|
|
740
|
+
version = "0.63.0"
|
|
741
741
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
742
|
-
checksum = "
|
|
742
|
+
checksum = "197a3766e68338d53685acd4120d7bdc3e1419f0a044a1e4110f8f6ecc1bc1b6"
|
|
743
743
|
dependencies = [
|
|
744
744
|
"fancy-regex",
|
|
745
745
|
"indexmap",
|
|
@@ -756,7 +756,7 @@ dependencies = [
|
|
|
756
756
|
|
|
757
757
|
[[package]]
|
|
758
758
|
name = "jsonschema-rb-ext"
|
|
759
|
-
version = "0.
|
|
759
|
+
version = "0.63.0"
|
|
760
760
|
dependencies = [
|
|
761
761
|
"jsonschema",
|
|
762
762
|
"magnus",
|
|
@@ -770,18 +770,18 @@ dependencies = [
|
|
|
770
770
|
|
|
771
771
|
[[package]]
|
|
772
772
|
name = "jsonschema-regex"
|
|
773
|
-
version = "0.
|
|
773
|
+
version = "0.63.0"
|
|
774
774
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
775
|
-
checksum = "
|
|
775
|
+
checksum = "19532291f4c1f5a5726be72105a0d73620b714ef12256e9748cc863cf122dc1c"
|
|
776
776
|
dependencies = [
|
|
777
777
|
"regex-syntax",
|
|
778
778
|
]
|
|
779
779
|
|
|
780
780
|
[[package]]
|
|
781
781
|
name = "jsonschema-value"
|
|
782
|
-
version = "0.
|
|
782
|
+
version = "0.63.0"
|
|
783
783
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
784
|
-
checksum = "
|
|
784
|
+
checksum = "d455c96d26f5c8527d7824f3f9ac810fec24d1448a3f7a254a006ea542e3dcf9"
|
|
785
785
|
dependencies = [
|
|
786
786
|
"ahash",
|
|
787
787
|
"bytecount",
|
|
@@ -1137,9 +1137,9 @@ dependencies = [
|
|
|
1137
1137
|
|
|
1138
1138
|
[[package]]
|
|
1139
1139
|
name = "referencing"
|
|
1140
|
-
version = "0.
|
|
1140
|
+
version = "0.63.0"
|
|
1141
1141
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
1142
|
-
checksum = "
|
|
1142
|
+
checksum = "1225f3e462cea1e4a8e169dd539f9d8a7592780b5b261d0e07e5cbb9efb28e4e"
|
|
1143
1143
|
dependencies = [
|
|
1144
1144
|
"ahash",
|
|
1145
1145
|
"fluent-uri",
|
data/ext/jsonschema/Cargo.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "jsonschema-rb-ext"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.63.0"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
publish = false
|
|
6
6
|
|
|
@@ -10,10 +10,10 @@ name = "jsonschema_rb"
|
|
|
10
10
|
path = "../../src/lib.rs"
|
|
11
11
|
|
|
12
12
|
[dependencies]
|
|
13
|
-
jsonschema = { version = "0.
|
|
13
|
+
jsonschema = { version = "0.63.0", default-features = false, features = ["magnus", "arbitrary-precision", "resolve-http", "resolve-file", "tls-ring", "macros", "idna", "json-text"] }
|
|
14
14
|
magnus = { version = "0.9", features = ["rb-sys"] }
|
|
15
15
|
rb-sys = "0.9"
|
|
16
|
-
referencing = "0.
|
|
16
|
+
referencing = "0.63.0"
|
|
17
17
|
serde = { version = "1", features = ["derive"] }
|
|
18
18
|
serde_json = { version = "1", features = ["arbitrary_precision"] }
|
|
19
19
|
strum = "0.28.0"
|
data/lib/jsonschema/version.rb
CHANGED
data/sig/jsonschema.rbs
CHANGED
|
@@ -373,6 +373,13 @@ module JSONSchema
|
|
|
373
373
|
?base_uri: String?
|
|
374
374
|
) -> Canonical::CanonicalSchema
|
|
375
375
|
|
|
376
|
+
# A `format` check that reads numbers, for the `formats` option; other instances pass it.
|
|
377
|
+
def self.number_format: (^(Numeric) -> bool check) -> NumberFormat
|
|
378
|
+
|
|
379
|
+
# A `format` check that reads numbers, made by `JSONSchema.number_format`.
|
|
380
|
+
class NumberFormat
|
|
381
|
+
end
|
|
382
|
+
|
|
376
383
|
# Create a validator with auto-detected draft version.
|
|
377
384
|
def self.validator_for: (
|
|
378
385
|
untyped schema,
|
|
@@ -382,7 +389,7 @@ module JSONSchema
|
|
|
382
389
|
?base_uri: String?,
|
|
383
390
|
?retriever: (^(String) -> untyped)?,
|
|
384
391
|
?mask: String?,
|
|
385
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
392
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
386
393
|
?keywords: Hash[String, Class]?,
|
|
387
394
|
?registry: Registry?,
|
|
388
395
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -451,7 +458,7 @@ module JSONSchema
|
|
|
451
458
|
?base_uri: String?,
|
|
452
459
|
?retriever: (^(String) -> untyped)?,
|
|
453
460
|
?mask: String?,
|
|
454
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
461
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
455
462
|
?keywords: Hash[String, Class]?,
|
|
456
463
|
?registry: Registry?,
|
|
457
464
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -471,7 +478,7 @@ module JSONSchema
|
|
|
471
478
|
?base_uri: String?,
|
|
472
479
|
?retriever: (^(String) -> untyped)?,
|
|
473
480
|
?mask: String?,
|
|
474
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
481
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
475
482
|
?keywords: Hash[String, Class]?,
|
|
476
483
|
?registry: Registry?,
|
|
477
484
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -491,7 +498,7 @@ module JSONSchema
|
|
|
491
498
|
?base_uri: String?,
|
|
492
499
|
?retriever: (^(String) -> untyped)?,
|
|
493
500
|
?mask: String?,
|
|
494
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
501
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
495
502
|
?keywords: Hash[String, Class]?,
|
|
496
503
|
?registry: Registry?,
|
|
497
504
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -509,7 +516,7 @@ module JSONSchema
|
|
|
509
516
|
?base_uri: String?,
|
|
510
517
|
?retriever: (^(String) -> untyped)?,
|
|
511
518
|
?mask: String?,
|
|
512
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
519
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
513
520
|
?keywords: Hash[String, Class]?,
|
|
514
521
|
?registry: Registry?,
|
|
515
522
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -528,7 +535,7 @@ module JSONSchema
|
|
|
528
535
|
?vocabularies: Array[String]?,
|
|
529
536
|
?base_uri: String?,
|
|
530
537
|
?retriever: (^(String) -> untyped)?,
|
|
531
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
538
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
532
539
|
?keywords: Hash[String, Class]?,
|
|
533
540
|
?registry: Registry?,
|
|
534
541
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -549,7 +556,7 @@ module JSONSchema
|
|
|
549
556
|
?base_uri: String?,
|
|
550
557
|
?retriever: (^(String) -> untyped)?,
|
|
551
558
|
?mask: String?,
|
|
552
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
559
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
553
560
|
?keywords: Hash[String, Class]?,
|
|
554
561
|
?registry: Registry?,
|
|
555
562
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -573,6 +580,42 @@ module JSONSchema
|
|
|
573
580
|
|
|
574
581
|
def inspect: () -> String
|
|
575
582
|
end
|
|
583
|
+
|
|
584
|
+
# Validates instances given as JSON text, without building Ruby objects for them.
|
|
585
|
+
class JsonTextValidator
|
|
586
|
+
def initialize: (
|
|
587
|
+
untyped schema,
|
|
588
|
+
?draft: draft?,
|
|
589
|
+
?validate_formats: bool?,
|
|
590
|
+
?ignore_unknown_formats: bool?,
|
|
591
|
+
?vocabularies: Array[String]?,
|
|
592
|
+
?base_uri: String?,
|
|
593
|
+
?retriever: (^(String) -> untyped)?,
|
|
594
|
+
?mask: String?,
|
|
595
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
596
|
+
?keywords: Hash[String, Class]?,
|
|
597
|
+
?registry: Registry?,
|
|
598
|
+
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
599
|
+
?email_options: EmailOptions?,
|
|
600
|
+
?http_options: HttpOptions?,
|
|
601
|
+
?offline: bool?
|
|
602
|
+
) -> void
|
|
603
|
+
|
|
604
|
+
# Whether the JSON text holds a valid document.
|
|
605
|
+
def valid?: (String text) -> bool
|
|
606
|
+
|
|
607
|
+
# Raise on the first error of the document in the JSON text.
|
|
608
|
+
def validate!: (String text) -> nil
|
|
609
|
+
|
|
610
|
+
# Iterate validation errors. Returns Array when no block given, nil when block given.
|
|
611
|
+
def each_error: (String text) -> Array[ValidationError]
|
|
612
|
+
| (String text) { (ValidationError) -> void } -> nil
|
|
613
|
+
|
|
614
|
+
# Evaluate the document in the JSON text and return structured output.
|
|
615
|
+
def evaluate: (String text) -> Evaluation
|
|
616
|
+
|
|
617
|
+
def inspect: () -> String
|
|
618
|
+
end
|
|
576
619
|
public
|
|
577
620
|
|
|
578
621
|
# Validators for every subschema, keyed by URI fragment such as `"#/$defs/User"`.
|
data/src/json_text.rs
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
//! `JSONSchema::JsonTextValidator`: validates instances given as JSON text.
|
|
2
|
+
use std::panic::AssertUnwindSafe;
|
|
3
|
+
|
|
4
|
+
use jsonschema::json::{Array, JsonNumber, JsonText, JsonTextDocument, JsonTextNode, Node, Object};
|
|
5
|
+
use magnus::{
|
|
6
|
+
function, method, prelude::*, scan_args::scan_args, DataTypeFunctions, Error, RModule, RString,
|
|
7
|
+
Ruby, Value,
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
use crate::{
|
|
11
|
+
build_parsed_options, build_validator, catch_unwind_silent, handle_callback_panic,
|
|
12
|
+
options::{extract_kwargs, CallbackRoots, CompilationRootsRef},
|
|
13
|
+
raise_validation_error,
|
|
14
|
+
ser::to_schema_value,
|
|
15
|
+
to_ruby_error_value, BuiltValidator, Evaluation, InstanceRoot, KeywordCauseScope,
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/// A validator for instances given as JSON text, without building Ruby objects for them.
|
|
19
|
+
///
|
|
20
|
+
/// Holds the same GC-protection state as `Validator`.
|
|
21
|
+
#[derive(magnus::TypedData)]
|
|
22
|
+
#[magnus(class = "JSONSchema::JsonTextValidator", free_immediately, size, mark)]
|
|
23
|
+
pub struct JsonTextValidator {
|
|
24
|
+
validator: jsonschema::Validator<JsonText>,
|
|
25
|
+
mask: Option<String>,
|
|
26
|
+
callback_roots: CallbackRoots,
|
|
27
|
+
_compilation_roots: CompilationRootsRef,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
impl DataTypeFunctions for JsonTextValidator {
|
|
31
|
+
fn mark(&self, marker: &magnus::gc::Marker) {
|
|
32
|
+
// Avoid panicking in Ruby GC mark paths; preserving existing roots is safer than aborting.
|
|
33
|
+
let roots = match self.callback_roots.lock() {
|
|
34
|
+
Ok(roots) => roots,
|
|
35
|
+
Err(poisoned) => poisoned.into_inner(),
|
|
36
|
+
};
|
|
37
|
+
for root in roots.iter().copied() {
|
|
38
|
+
marker.mark(root);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Copied so Ruby code that validation runs cannot change the text under it.
|
|
44
|
+
fn json_text(ruby: &Ruby, instance: Value) -> Result<Vec<u8>, Error> {
|
|
45
|
+
let Some(mut string) = RString::from_value(instance) else {
|
|
46
|
+
return Err(Error::new(
|
|
47
|
+
ruby.exception_type_error(),
|
|
48
|
+
format!(
|
|
49
|
+
"JSON text must be a String, not {}",
|
|
50
|
+
instance.class().inspect()
|
|
51
|
+
),
|
|
52
|
+
));
|
|
53
|
+
};
|
|
54
|
+
// As `JSON.parse` does: binary strings are read as UTF-8, other encodings converted to it.
|
|
55
|
+
let encoding = string.enc_get();
|
|
56
|
+
if encoding != ruby.utf8_encindex()
|
|
57
|
+
&& encoding != ruby.usascii_encindex()
|
|
58
|
+
&& encoding != ruby.ascii8bit_encindex()
|
|
59
|
+
{
|
|
60
|
+
string = string.funcall("encode", ("UTF-8",))?;
|
|
61
|
+
}
|
|
62
|
+
// SAFETY: the bytes are copied before any Ruby code runs.
|
|
63
|
+
#[allow(unsafe_code)]
|
|
64
|
+
let bytes = unsafe { string.as_slice() }.to_vec();
|
|
65
|
+
Ok(bytes)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
fn parse<'a>(ruby: &Ruby, text: &'a [u8]) -> Result<JsonTextDocument<'a>, Error> {
|
|
69
|
+
JsonText::parse(text)
|
|
70
|
+
.map_err(|error| Error::new(ruby.exception_arg_error(), format!("Invalid JSON: {error}")))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// What `JSON.parse` builds: members in document order, `Integer` for integers, `Float` otherwise.
|
|
74
|
+
pub(crate) fn text_node_to_ruby(ruby: &Ruby, node: &JsonTextNode<'_>) -> Result<Value, Error> {
|
|
75
|
+
if let Some(object) = node.as_object() {
|
|
76
|
+
let hash = ruby.hash_new();
|
|
77
|
+
for (name, value) in object.members() {
|
|
78
|
+
hash.aset(ruby.str_new(&name), text_node_to_ruby(ruby, &value)?)?;
|
|
79
|
+
}
|
|
80
|
+
return Ok(hash.as_value());
|
|
81
|
+
}
|
|
82
|
+
if let Some(array) = node.as_array() {
|
|
83
|
+
let list = ruby.ary_new_capa(array.len());
|
|
84
|
+
for element in array.elements() {
|
|
85
|
+
list.push(text_node_to_ruby(ruby, &element)?)?;
|
|
86
|
+
}
|
|
87
|
+
return Ok(list.as_value());
|
|
88
|
+
}
|
|
89
|
+
if let Some(string) = node.as_string() {
|
|
90
|
+
return Ok(ruby.str_new(&string).as_value());
|
|
91
|
+
}
|
|
92
|
+
if let Some(number) = node.as_number() {
|
|
93
|
+
if let Some(value) = number.as_i64() {
|
|
94
|
+
return Ok(ruby.integer_from_i64(value).as_value());
|
|
95
|
+
}
|
|
96
|
+
let digits = JsonNumber::as_str(&number);
|
|
97
|
+
if digits.contains(['.', 'e', 'E']) {
|
|
98
|
+
// Past `f64` this is infinite, as with `JSON.parse`.
|
|
99
|
+
let value: f64 = digits.parse().expect("a checked number");
|
|
100
|
+
return Ok(ruby.float_from_f64(value).as_value());
|
|
101
|
+
}
|
|
102
|
+
return ruby.str_new(&digits).funcall("to_i", ());
|
|
103
|
+
}
|
|
104
|
+
Ok(match node.as_boolean() {
|
|
105
|
+
Some(true) => ruby.qtrue().as_value(),
|
|
106
|
+
Some(false) => ruby.qfalse().as_value(),
|
|
107
|
+
None => ruby.qnil().as_value(),
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
impl JsonTextValidator {
|
|
112
|
+
fn new_impl(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
|
|
113
|
+
let parsed_args = scan_args::<(Value,), (), (), (), _, ()>(args)?;
|
|
114
|
+
let (schema,) = parsed_args.required;
|
|
115
|
+
let kw = extract_kwargs(ruby, parsed_args.keywords)?;
|
|
116
|
+
let json_schema = to_schema_value(ruby, schema)?;
|
|
117
|
+
let parsed = build_parsed_options::<JsonText>(ruby, kw, None)?;
|
|
118
|
+
let BuiltValidator {
|
|
119
|
+
validator,
|
|
120
|
+
callback_roots,
|
|
121
|
+
compilation_roots,
|
|
122
|
+
} = build_validator(
|
|
123
|
+
ruby,
|
|
124
|
+
parsed.options,
|
|
125
|
+
parsed.registry,
|
|
126
|
+
parsed.retriever,
|
|
127
|
+
parsed.callback_roots,
|
|
128
|
+
parsed.compilation_roots,
|
|
129
|
+
&json_schema,
|
|
130
|
+
)?;
|
|
131
|
+
Ok(Self {
|
|
132
|
+
validator,
|
|
133
|
+
mask: parsed.mask,
|
|
134
|
+
callback_roots,
|
|
135
|
+
_compilation_roots: compilation_roots,
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
fn is_valid(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<bool, Error> {
|
|
140
|
+
let text = json_text(ruby, instance)?;
|
|
141
|
+
let document = parse(ruby, &text)?;
|
|
142
|
+
catch_unwind_silent(AssertUnwindSafe(|| {
|
|
143
|
+
rb_self.validator.is_valid(document.root())
|
|
144
|
+
}))
|
|
145
|
+
.map_err(|err| handle_callback_panic(ruby, err))
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
fn validate(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<(), Error> {
|
|
149
|
+
let text = json_text(ruby, instance)?;
|
|
150
|
+
let document = parse(ruby, &text)?;
|
|
151
|
+
let _scope = KeywordCauseScope::enter();
|
|
152
|
+
match catch_unwind_silent(AssertUnwindSafe(|| {
|
|
153
|
+
rb_self.validator.validate(document.root())
|
|
154
|
+
})) {
|
|
155
|
+
Ok(Ok(())) => Ok(()),
|
|
156
|
+
Ok(Err(error)) => Err(raise_validation_error(
|
|
157
|
+
ruby,
|
|
158
|
+
error,
|
|
159
|
+
Some(InstanceRoot::Text(document.root())),
|
|
160
|
+
rb_self.mask.as_deref(),
|
|
161
|
+
)),
|
|
162
|
+
Err(err) => Err(handle_callback_panic(ruby, err)),
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
fn iter_errors(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<Value, Error> {
|
|
167
|
+
let text = json_text(ruby, instance)?;
|
|
168
|
+
let document = parse(ruby, &text)?;
|
|
169
|
+
let _scope = KeywordCauseScope::enter();
|
|
170
|
+
let convert = |error| {
|
|
171
|
+
to_ruby_error_value(
|
|
172
|
+
ruby,
|
|
173
|
+
error,
|
|
174
|
+
Some(InstanceRoot::Text(document.root())),
|
|
175
|
+
rb_self.mask.as_deref(),
|
|
176
|
+
)
|
|
177
|
+
};
|
|
178
|
+
if ruby.block_given() {
|
|
179
|
+
// Building the iterator validates, which can run Ruby callbacks.
|
|
180
|
+
let mut errors = catch_unwind_silent(AssertUnwindSafe(|| {
|
|
181
|
+
rb_self.validator.iter_errors(document.root())
|
|
182
|
+
}))
|
|
183
|
+
.map_err(|err| handle_callback_panic(ruby, err))?;
|
|
184
|
+
loop {
|
|
185
|
+
match catch_unwind_silent(AssertUnwindSafe(|| errors.next())) {
|
|
186
|
+
Ok(Some(error)) => {
|
|
187
|
+
ruby.yield_value::<Value, Value>(convert(error)?)?;
|
|
188
|
+
}
|
|
189
|
+
Ok(None) => return Ok(ruby.qnil().as_value()),
|
|
190
|
+
Err(err) => return Err(handle_callback_panic(ruby, err)),
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
let errors = catch_unwind_silent(AssertUnwindSafe(|| {
|
|
195
|
+
rb_self
|
|
196
|
+
.validator
|
|
197
|
+
.iter_errors(document.root())
|
|
198
|
+
.collect::<Vec<_>>()
|
|
199
|
+
}))
|
|
200
|
+
.map_err(|err| handle_callback_panic(ruby, err))?;
|
|
201
|
+
let array = ruby.ary_new_capa(errors.len());
|
|
202
|
+
for error in errors {
|
|
203
|
+
array.push(convert(error)?)?;
|
|
204
|
+
}
|
|
205
|
+
Ok(array.as_value())
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
fn evaluate(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<Evaluation, Error> {
|
|
209
|
+
let text = json_text(ruby, instance)?;
|
|
210
|
+
let document = parse(ruby, &text)?;
|
|
211
|
+
let _scope = KeywordCauseScope::enter();
|
|
212
|
+
catch_unwind_silent(AssertUnwindSafe(|| {
|
|
213
|
+
rb_self.validator.evaluate(document.root())
|
|
214
|
+
}))
|
|
215
|
+
.map(Evaluation::new)
|
|
216
|
+
.map_err(|err| handle_callback_panic(ruby, err))
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
fn inspect(&self) -> &'static str {
|
|
220
|
+
match self.validator.draft() {
|
|
221
|
+
jsonschema::Draft::Draft4 => "#<JSONSchema::JsonTextValidator: Draft4>",
|
|
222
|
+
jsonschema::Draft::Draft6 => "#<JSONSchema::JsonTextValidator: Draft6>",
|
|
223
|
+
jsonschema::Draft::Draft7 => "#<JSONSchema::JsonTextValidator: Draft7>",
|
|
224
|
+
jsonschema::Draft::Draft201909 => "#<JSONSchema::JsonTextValidator: Draft201909>",
|
|
225
|
+
_ => "#<JSONSchema::JsonTextValidator: Draft202012>",
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
pub fn define_class(ruby: &Ruby, module: &RModule) -> Result<(), Error> {
|
|
231
|
+
let class = module.define_class("JsonTextValidator", ruby.class_object())?;
|
|
232
|
+
class.define_singleton_method("new", function!(JsonTextValidator::new_impl, -1))?;
|
|
233
|
+
class.define_method("valid?", method!(JsonTextValidator::is_valid, 1))?;
|
|
234
|
+
class.define_method("validate!", method!(JsonTextValidator::validate, 1))?;
|
|
235
|
+
class.define_method("each_error", method!(JsonTextValidator::iter_errors, 1))?;
|
|
236
|
+
class.define_method("evaluate", method!(JsonTextValidator::evaluate, 1))?;
|
|
237
|
+
class.define_method("inspect", method!(JsonTextValidator::inspect, 0))?;
|
|
238
|
+
Ok(())
|
|
239
|
+
}
|
data/src/lib.rs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
mod canonical;
|
|
9
9
|
mod error_kind;
|
|
10
10
|
mod evaluation;
|
|
11
|
+
mod json_text;
|
|
11
12
|
mod options;
|
|
12
13
|
mod registry;
|
|
13
14
|
mod retriever;
|
|
@@ -18,7 +19,8 @@ mod validator_map;
|
|
|
18
19
|
use jsonschema::{
|
|
19
20
|
json::{
|
|
20
21
|
magnus_child, magnus_invalidate_members_cache, magnus_is_object, magnus_probe_root,
|
|
21
|
-
magnus_take_pending_error,
|
|
22
|
+
magnus_take_pending_error, Array, Json, JsonText, JsonTextNode, Magnus,
|
|
23
|
+
MagnusPendingErrorScope, Node, Object, RbNode,
|
|
22
24
|
},
|
|
23
25
|
paths::LocationSegment,
|
|
24
26
|
ValidationOptions,
|
|
@@ -46,6 +48,7 @@ use std::{
|
|
|
46
48
|
use crate::{
|
|
47
49
|
error_kind::ValidationErrorKind,
|
|
48
50
|
evaluation::Evaluation,
|
|
51
|
+
json_text::text_node_to_ruby,
|
|
49
52
|
options::{
|
|
50
53
|
extract_evaluate_kwargs, extract_kwargs, extract_kwargs_no_draft, make_options_from_kwargs,
|
|
51
54
|
parse_draft_symbol, CallbackRoots, CompilationRoots, CompilationRootsRef, ExtractedKwargs,
|
|
@@ -86,21 +89,21 @@ define_rb_intern!(static ID_SYM_SCHEMA_PATH_POINTER: "schema_path_pointer");
|
|
|
86
89
|
define_rb_intern!(static ID_SYM_EVALUATION_PATH_POINTER: "evaluation_path_pointer");
|
|
87
90
|
define_rb_intern!(static ID_SYM_ABSOLUTE_KEYWORD_LOCATION: "absolute_keyword_location");
|
|
88
91
|
|
|
89
|
-
struct BuiltValidator {
|
|
90
|
-
validator: jsonschema::Validator<
|
|
92
|
+
struct BuiltValidator<F: Json = Magnus> {
|
|
93
|
+
validator: jsonschema::Validator<F>,
|
|
91
94
|
callback_roots: CallbackRoots,
|
|
92
95
|
compilation_roots: CompilationRootsRef,
|
|
93
96
|
}
|
|
94
97
|
|
|
95
|
-
fn build_validator(
|
|
98
|
+
fn build_validator<F: Json>(
|
|
96
99
|
ruby: &Ruby,
|
|
97
|
-
options: ValidationOptions<'_, Arc<dyn jsonschema::Retrieve>,
|
|
100
|
+
options: ValidationOptions<'_, Arc<dyn jsonschema::Retrieve>, F>,
|
|
98
101
|
registry: Option<&jsonschema::Registry<'_>>,
|
|
99
102
|
retriever: Option<RubyRetriever>,
|
|
100
103
|
callback_roots: CallbackRoots,
|
|
101
104
|
compilation_roots: Arc<CompilationRoots>,
|
|
102
105
|
schema: &serde_json::Value,
|
|
103
|
-
) -> Result<BuiltValidator
|
|
106
|
+
) -> Result<BuiltValidator<F>, Error> {
|
|
104
107
|
let mut options = match retriever {
|
|
105
108
|
Some(ret) => options.with_retriever(ret),
|
|
106
109
|
None => options,
|
|
@@ -128,11 +131,14 @@ fn build_validator(
|
|
|
128
131
|
})
|
|
129
132
|
}
|
|
130
133
|
|
|
131
|
-
fn build_parsed_options(
|
|
134
|
+
fn build_parsed_options<F: Json>(
|
|
132
135
|
ruby: &Ruby,
|
|
133
136
|
kw: ExtractedKwargs,
|
|
134
137
|
draft_override: Option<jsonschema::Draft>,
|
|
135
|
-
) -> Result<ParsedOptions<'_>, Error>
|
|
138
|
+
) -> Result<ParsedOptions<'_, F>, Error>
|
|
139
|
+
where
|
|
140
|
+
options::RubyKeyword: for<'i> jsonschema::Keyword<'i, F>,
|
|
141
|
+
{
|
|
136
142
|
let (
|
|
137
143
|
draft_val,
|
|
138
144
|
validate_formats,
|
|
@@ -248,7 +254,7 @@ fn build_verbose_message(
|
|
|
248
254
|
mut message: String,
|
|
249
255
|
schema_path: &jsonschema::paths::Location,
|
|
250
256
|
instance_path: &jsonschema::paths::Location,
|
|
251
|
-
root_instance: Option<
|
|
257
|
+
root_instance: Option<InstanceRoot<'_>>,
|
|
252
258
|
failing_instance: &serde_json::Value,
|
|
253
259
|
mask: Option<&str>,
|
|
254
260
|
) -> String {
|
|
@@ -316,14 +322,14 @@ fn build_verbose_message(
|
|
|
316
322
|
let segment = unescape_segment(segment);
|
|
317
323
|
let segment = segment.as_ref();
|
|
318
324
|
let is_index = match current {
|
|
319
|
-
Some(node) if
|
|
325
|
+
Some(node) if node.is_object() => false,
|
|
320
326
|
_ => is_index_segment(segment),
|
|
321
327
|
};
|
|
322
328
|
message.push('[');
|
|
323
329
|
push_segment(&mut message, segment, is_index);
|
|
324
330
|
message.push(']');
|
|
325
331
|
|
|
326
|
-
current = current.and_then(|node|
|
|
332
|
+
current = current.and_then(|node| node.child(segment, is_index));
|
|
327
333
|
}
|
|
328
334
|
message.push_str(":\n ");
|
|
329
335
|
|
|
@@ -346,6 +352,57 @@ fn error_message(error: &jsonschema::ValidationError<'_>, mask: Option<&str>) ->
|
|
|
346
352
|
}
|
|
347
353
|
}
|
|
348
354
|
|
|
355
|
+
/// Where an error reads its instance from: the Ruby object validated, or the JSON text.
|
|
356
|
+
#[derive(Clone, Copy)]
|
|
357
|
+
pub(crate) enum InstanceRoot<'a> {
|
|
358
|
+
Object(RbNode<'a>),
|
|
359
|
+
Text(JsonTextNode<'a>),
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
impl InstanceRoot<'_> {
|
|
363
|
+
fn is_object(self) -> bool {
|
|
364
|
+
match self {
|
|
365
|
+
InstanceRoot::Object(node) => magnus_is_object(node),
|
|
366
|
+
InstanceRoot::Text(node) => node.as_object().is_some(),
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
fn child(self, segment: &str, is_index: bool) -> Option<Self> {
|
|
371
|
+
match self {
|
|
372
|
+
InstanceRoot::Object(node) => magnus_child(node, segment, is_index).map(Self::Object),
|
|
373
|
+
InstanceRoot::Text(node) => if is_index {
|
|
374
|
+
node.as_array()?.elements().nth(segment.parse().ok()?)
|
|
375
|
+
} else {
|
|
376
|
+
node.as_object()?.get(&JsonText::prepare_key(segment))
|
|
377
|
+
}
|
|
378
|
+
.map(Self::Text),
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// The instance at `location`, or `None` to convert the error's JSON copy instead. JSON text
|
|
383
|
+
// builds only that value, as `JSON.parse` would, never the rest of the document.
|
|
384
|
+
fn instance_at(self, ruby: &Ruby, location: &str) -> Result<Option<Value>, Error> {
|
|
385
|
+
match self {
|
|
386
|
+
InstanceRoot::Object(root) => Ok(plain_instance_at(ruby, root, location)),
|
|
387
|
+
InstanceRoot::Text(root) => text_node_at(root, location)
|
|
388
|
+
.map(|node| text_node_to_ruby(ruby, &node))
|
|
389
|
+
.transpose(),
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
fn text_node_at<'a>(root: JsonTextNode<'a>, location: &str) -> Option<JsonTextNode<'a>> {
|
|
395
|
+
let mut current = root;
|
|
396
|
+
for segment in location.split('/').skip(1) {
|
|
397
|
+
current = if let Some(object) = current.as_object() {
|
|
398
|
+
object.get(&JsonText::prepare_key(&unescape_segment(segment)))?
|
|
399
|
+
} else {
|
|
400
|
+
current.as_array()?.elements().nth(parse_index(segment)?)?
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
Some(current)
|
|
404
|
+
}
|
|
405
|
+
|
|
349
406
|
// The Ruby value at `location` under `root` when it holds only plain JSON types; `None` makes the
|
|
350
407
|
// caller convert the JSON copy.
|
|
351
408
|
fn plain_instance_at(ruby: &Ruby, root: RbNode<'_>, location: &str) -> Option<Value> {
|
|
@@ -421,7 +478,7 @@ fn is_plain_json(ruby: &Ruby, value: Value, depth: u16) -> bool {
|
|
|
421
478
|
fn into_ruby_error(
|
|
422
479
|
ruby: &Ruby,
|
|
423
480
|
error: jsonschema::ValidationError<'_>,
|
|
424
|
-
root_instance: Option<
|
|
481
|
+
root_instance: Option<InstanceRoot<'_>>,
|
|
425
482
|
message: &str,
|
|
426
483
|
mask: Option<&str>,
|
|
427
484
|
) -> Result<Value, Error> {
|
|
@@ -455,8 +512,10 @@ fn into_ruby_error(
|
|
|
455
512
|
let kind_obj = ValidationErrorKind::new(ruby, &parts.kind, mask)?;
|
|
456
513
|
// Scalars convert faster than the path to them is followed.
|
|
457
514
|
let original = match parts.instance.as_ref() {
|
|
458
|
-
serde_json::Value::Array(_) | serde_json::Value::Object(_) => root_instance
|
|
459
|
-
|
|
515
|
+
serde_json::Value::Array(_) | serde_json::Value::Object(_) => match root_instance {
|
|
516
|
+
Some(root) => root.instance_at(ruby, parts.instance_path.as_str())?,
|
|
517
|
+
None => None,
|
|
518
|
+
},
|
|
460
519
|
_ => None,
|
|
461
520
|
};
|
|
462
521
|
let rb_instance = match original {
|
|
@@ -512,7 +571,7 @@ fn into_ruby_error(
|
|
|
512
571
|
fn to_ruby_error_value(
|
|
513
572
|
ruby: &Ruby,
|
|
514
573
|
error: jsonschema::ValidationError<'_>,
|
|
515
|
-
root_instance: Option<
|
|
574
|
+
root_instance: Option<InstanceRoot<'_>>,
|
|
516
575
|
mask: Option<&str>,
|
|
517
576
|
) -> Result<Value, Error> {
|
|
518
577
|
let message = error_message(&error, mask);
|
|
@@ -527,7 +586,7 @@ pub(crate) fn referencing_error(ruby: &Ruby, message: String) -> Error {
|
|
|
527
586
|
fn raise_validation_error(
|
|
528
587
|
ruby: &Ruby,
|
|
529
588
|
error: jsonschema::ValidationError<'_>,
|
|
530
|
-
root_instance: Option<
|
|
589
|
+
root_instance: Option<InstanceRoot<'_>>,
|
|
531
590
|
mask: Option<&str>,
|
|
532
591
|
) -> Error {
|
|
533
592
|
let message = error_message(&error, mask);
|
|
@@ -677,7 +736,7 @@ impl Validator {
|
|
|
677
736
|
Ok(Err(error)) => Err(raise_validation_error(
|
|
678
737
|
ruby,
|
|
679
738
|
error,
|
|
680
|
-
Some(node),
|
|
739
|
+
Some(InstanceRoot::Object(node)),
|
|
681
740
|
rb_self.mask.as_deref(),
|
|
682
741
|
)),
|
|
683
742
|
Err(err) => Err(handle_callback_panic(ruby, err)),
|
|
@@ -690,8 +749,11 @@ impl Validator {
|
|
|
690
749
|
let _scope = KeywordCauseScope::enter();
|
|
691
750
|
|
|
692
751
|
if ruby.block_given() {
|
|
693
|
-
// Lazy path: yield errors one at a time to the block
|
|
694
|
-
|
|
752
|
+
// Lazy path: yield errors one at a time to the block. Building the iterator
|
|
753
|
+
// validates, which can run Ruby callbacks.
|
|
754
|
+
let mut iter =
|
|
755
|
+
catch_unwind_silent(AssertUnwindSafe(|| rb_self.validator.iter_errors(node)))
|
|
756
|
+
.map_err(|err| handle_callback_panic(ruby, err))?;
|
|
695
757
|
loop {
|
|
696
758
|
let result = catch_unwind_silent(AssertUnwindSafe(|| iter.next()));
|
|
697
759
|
match result {
|
|
@@ -699,7 +761,7 @@ impl Validator {
|
|
|
699
761
|
let ruby_error = to_ruby_error_value(
|
|
700
762
|
ruby,
|
|
701
763
|
error,
|
|
702
|
-
Some(node),
|
|
764
|
+
Some(InstanceRoot::Object(node)),
|
|
703
765
|
rb_self.mask.as_deref(),
|
|
704
766
|
)?;
|
|
705
767
|
ruby.yield_value::<Value, Value>(ruby_error)?;
|
|
@@ -721,7 +783,7 @@ impl Validator {
|
|
|
721
783
|
arr.push(to_ruby_error_value(
|
|
722
784
|
ruby,
|
|
723
785
|
error,
|
|
724
|
-
Some(node),
|
|
786
|
+
Some(InstanceRoot::Object(node)),
|
|
725
787
|
rb_self.mask.as_deref(),
|
|
726
788
|
)?)?;
|
|
727
789
|
}
|
|
@@ -810,7 +872,7 @@ fn validator_for(ruby: &Ruby, args: &[Value]) -> Result<Validator, Error> {
|
|
|
810
872
|
let kw = extract_kwargs_no_draft(ruby, parsed_args.keywords)?;
|
|
811
873
|
|
|
812
874
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
813
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
875
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
814
876
|
let BuiltValidator {
|
|
815
877
|
validator,
|
|
816
878
|
callback_roots,
|
|
@@ -838,7 +900,7 @@ fn validator_map_for(ruby: &Ruby, args: &[Value]) -> Result<validator_map::Valid
|
|
|
838
900
|
let kw = extract_kwargs_no_draft(ruby, parsed_args.keywords)?;
|
|
839
901
|
|
|
840
902
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
841
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
903
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
842
904
|
let callback_roots = parsed.callback_roots;
|
|
843
905
|
let compilation_roots = parsed.compilation_roots;
|
|
844
906
|
let mask = parsed.mask;
|
|
@@ -879,7 +941,7 @@ fn bundle(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
|
|
|
879
941
|
let kw = extract_kwargs(ruby, parsed_args.keywords)?;
|
|
880
942
|
|
|
881
943
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
882
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
944
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
883
945
|
let mut options = match parsed.retriever {
|
|
884
946
|
Some(ret) => parsed.options.with_retriever(ret),
|
|
885
947
|
None => parsed.options,
|
|
@@ -902,7 +964,7 @@ fn dereference(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
|
|
|
902
964
|
let kw = extract_kwargs(ruby, parsed_args.keywords)?;
|
|
903
965
|
|
|
904
966
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
905
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
967
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
906
968
|
let mut options = match parsed.retriever {
|
|
907
969
|
Some(ret) => parsed.options.with_retriever(ret),
|
|
908
970
|
None => parsed.options,
|
|
@@ -934,7 +996,7 @@ fn is_valid(ruby: &Ruby, args: &[Value]) -> Result<bool, Error> {
|
|
|
934
996
|
let kw = extract_kwargs(ruby, parsed_args.keywords)?;
|
|
935
997
|
|
|
936
998
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
937
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
999
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
938
1000
|
let BuiltValidator {
|
|
939
1001
|
validator,
|
|
940
1002
|
compilation_roots: _compilation_roots,
|
|
@@ -962,7 +1024,7 @@ fn validate(ruby: &Ruby, args: &[Value]) -> Result<(), Error> {
|
|
|
962
1024
|
let kw = extract_kwargs(ruby, parsed_args.keywords)?;
|
|
963
1025
|
|
|
964
1026
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
965
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
1027
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
966
1028
|
let BuiltValidator {
|
|
967
1029
|
validator,
|
|
968
1030
|
compilation_roots: _compilation_roots,
|
|
@@ -983,7 +1045,7 @@ fn validate(ruby: &Ruby, args: &[Value]) -> Result<(), Error> {
|
|
|
983
1045
|
Ok(Err(error)) => Err(raise_validation_error(
|
|
984
1046
|
ruby,
|
|
985
1047
|
error,
|
|
986
|
-
Some(node),
|
|
1048
|
+
Some(InstanceRoot::Object(node)),
|
|
987
1049
|
parsed.mask.as_deref(),
|
|
988
1050
|
)),
|
|
989
1051
|
Err(err) => Err(handle_callback_panic(ruby, err)),
|
|
@@ -998,7 +1060,7 @@ fn each_error(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
|
|
|
998
1060
|
let kw = extract_kwargs(ruby, parsed_args.keywords)?;
|
|
999
1061
|
|
|
1000
1062
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
1001
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
1063
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
1002
1064
|
let BuiltValidator {
|
|
1003
1065
|
validator,
|
|
1004
1066
|
compilation_roots: _compilation_roots,
|
|
@@ -1020,8 +1082,12 @@ fn each_error(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
|
|
|
1020
1082
|
loop {
|
|
1021
1083
|
match catch_unwind_silent(AssertUnwindSafe(|| iter.next())) {
|
|
1022
1084
|
Ok(Some(error)) => {
|
|
1023
|
-
let ruby_error =
|
|
1024
|
-
|
|
1085
|
+
let ruby_error = to_ruby_error_value(
|
|
1086
|
+
ruby,
|
|
1087
|
+
error,
|
|
1088
|
+
Some(InstanceRoot::Object(node)),
|
|
1089
|
+
parsed.mask.as_deref(),
|
|
1090
|
+
)?;
|
|
1025
1091
|
ruby.yield_value::<Value, Value>(ruby_error)?;
|
|
1026
1092
|
}
|
|
1027
1093
|
Ok(None) => break,
|
|
@@ -1040,7 +1106,7 @@ fn each_error(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
|
|
|
1040
1106
|
arr.push(to_ruby_error_value(
|
|
1041
1107
|
ruby,
|
|
1042
1108
|
error,
|
|
1043
|
-
Some(node),
|
|
1109
|
+
Some(InstanceRoot::Object(node)),
|
|
1044
1110
|
parsed.mask.as_deref(),
|
|
1045
1111
|
)?)?;
|
|
1046
1112
|
}
|
|
@@ -1058,7 +1124,7 @@ fn evaluate(ruby: &Ruby, args: &[Value]) -> Result<Evaluation, Error> {
|
|
|
1058
1124
|
let kw = extract_evaluate_kwargs(ruby, parsed_args.keywords)?;
|
|
1059
1125
|
|
|
1060
1126
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
1061
|
-
let parsed = build_parsed_options(ruby, kw, None)?;
|
|
1127
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
|
|
1062
1128
|
let BuiltValidator {
|
|
1063
1129
|
validator,
|
|
1064
1130
|
compilation_roots: _compilation_roots,
|
|
@@ -1102,7 +1168,7 @@ macro_rules! define_draft_validator {
|
|
|
1102
1168
|
let kw = extract_kwargs_no_draft(ruby, parsed_args.keywords)?;
|
|
1103
1169
|
|
|
1104
1170
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
1105
|
-
let parsed = build_parsed_options(ruby, kw, Some($draft))?;
|
|
1171
|
+
let parsed = build_parsed_options::<Magnus>(ruby, kw, Some($draft))?;
|
|
1106
1172
|
let BuiltValidator {
|
|
1107
1173
|
validator,
|
|
1108
1174
|
callback_roots,
|
|
@@ -1263,7 +1329,7 @@ fn meta_validate(ruby: &Ruby, args: &[Value]) -> Result<(), Error> {
|
|
|
1263
1329
|
}
|
|
1264
1330
|
#[allow(unsafe_code)]
|
|
1265
1331
|
let node = RbNode::new(schema.as_raw());
|
|
1266
|
-
raise_validation_error(ruby, error, Some(node), None)
|
|
1332
|
+
raise_validation_error(ruby, error, Some(InstanceRoot::Object(node)), None)
|
|
1267
1333
|
};
|
|
1268
1334
|
if let Some(registry) = registry {
|
|
1269
1335
|
let json_schema = to_schema_value(ruby, schema)?;
|
|
@@ -1395,6 +1461,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
|
1395
1461
|
canonical::init_canonical(ruby, &module)?;
|
|
1396
1462
|
|
|
1397
1463
|
// Validator class
|
|
1464
|
+
json_text::define_class(ruby, &module)?;
|
|
1398
1465
|
let validator_class = module.define_class("Validator", ruby.class_object())?;
|
|
1399
1466
|
validator_class.define_method("valid?", method!(Validator::is_valid, 1))?;
|
|
1400
1467
|
validator_class.define_method("validate!", method!(Validator::validate, 1))?;
|
data/src/options.rs
CHANGED
|
@@ -10,15 +10,18 @@ use magnus::{
|
|
|
10
10
|
prelude::*,
|
|
11
11
|
scan_args::{get_kwargs, scan_args, KwArgs},
|
|
12
12
|
value::Opaque,
|
|
13
|
-
Error, Exception, RArray, RHash, RModule, Ruby, Symbol, TryConvert, Value,
|
|
13
|
+
DataTypeFunctions, Error, Exception, RArray, RHash, RModule, Ruby, Symbol, TryConvert, Value,
|
|
14
14
|
};
|
|
15
15
|
|
|
16
|
-
use jsonschema::json::{
|
|
16
|
+
use jsonschema::json::{
|
|
17
|
+
magnus_invalidate_members_cache, Json, JsonText, JsonTextNode, Magnus, RbNode,
|
|
18
|
+
};
|
|
17
19
|
|
|
18
20
|
use crate::{
|
|
21
|
+
json_text::text_node_to_ruby,
|
|
19
22
|
registry::Registry,
|
|
20
23
|
retriever::{make_retriever, DetachedRetriever, RubyRetriever},
|
|
21
|
-
ser::{map_to_ruby, value_to_ruby},
|
|
24
|
+
ser::{map_to_ruby, number_to_ruby, value_to_ruby},
|
|
22
25
|
static_id::{define_rb_intern, StaticId},
|
|
23
26
|
CUSTOM_KEYWORD_CAUSE, LAST_CALLBACK_ERROR,
|
|
24
27
|
};
|
|
@@ -59,9 +62,9 @@ define_rb_intern!(static SYM_CALL: "call");
|
|
|
59
62
|
define_rb_intern!(static SYM_NEW: "new");
|
|
60
63
|
define_rb_intern!(static SYM_VALIDATE: "validate");
|
|
61
64
|
|
|
62
|
-
pub struct ParsedOptions<'i> {
|
|
65
|
+
pub struct ParsedOptions<'i, F: Json = Magnus> {
|
|
63
66
|
pub mask: Option<String>,
|
|
64
|
-
pub options: jsonschema::ValidationOptions<'i, Arc<dyn jsonschema::Retrieve>,
|
|
67
|
+
pub options: jsonschema::ValidationOptions<'i, Arc<dyn jsonschema::Retrieve>, F>,
|
|
65
68
|
pub registry: Option<&'i jsonschema::Registry<'static>>,
|
|
66
69
|
pub retriever: Option<RubyRetriever>,
|
|
67
70
|
pub callback_roots: CallbackRoots,
|
|
@@ -371,8 +374,18 @@ struct RubyFormatChecker {
|
|
|
371
374
|
impl RubyFormatChecker {
|
|
372
375
|
fn check(&self, value: &str) -> bool {
|
|
373
376
|
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
374
|
-
|
|
375
|
-
|
|
377
|
+
Self::outcome(ruby.get_inner(self.proc).call((value,)))
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
fn check_number(&self, number: &serde_json::Number) -> bool {
|
|
381
|
+
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
382
|
+
Self::outcome(
|
|
383
|
+
number_to_ruby(&ruby, number)
|
|
384
|
+
.and_then(|number| ruby.get_inner(self.proc).call((number,))),
|
|
385
|
+
)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
fn outcome(result: Result<bool, Error>) -> bool {
|
|
376
389
|
magnus_invalidate_members_cache();
|
|
377
390
|
match result {
|
|
378
391
|
Ok(v) => v,
|
|
@@ -386,13 +399,39 @@ impl RubyFormatChecker {
|
|
|
386
399
|
}
|
|
387
400
|
}
|
|
388
401
|
|
|
402
|
+
/// A `format` check that reads numbers, made by `JSONSchema.number_format`.
|
|
403
|
+
#[derive(magnus::TypedData)]
|
|
404
|
+
#[magnus(class = "JSONSchema::NumberFormat", free_immediately, mark)]
|
|
405
|
+
pub struct NumberFormat {
|
|
406
|
+
check: Opaque<Value>,
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
impl DataTypeFunctions for NumberFormat {
|
|
410
|
+
fn mark(&self, marker: &magnus::gc::Marker) {
|
|
411
|
+
marker.mark(self.check);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
fn number_format(ruby: &Ruby, check: Value) -> Result<NumberFormat, Error> {
|
|
416
|
+
let responds_to_call: bool = check.funcall("respond_to?", (SYM_CALL.to_symbol(),))?;
|
|
417
|
+
if !responds_to_call {
|
|
418
|
+
return Err(Error::new(
|
|
419
|
+
ruby.exception_type_error(),
|
|
420
|
+
"number_format expects a callable (Proc or Lambda)",
|
|
421
|
+
));
|
|
422
|
+
}
|
|
423
|
+
Ok(NumberFormat {
|
|
424
|
+
check: Opaque::from(check),
|
|
425
|
+
})
|
|
426
|
+
}
|
|
427
|
+
|
|
389
428
|
/// Wrapper for a Ruby custom keyword validator factory.
|
|
390
429
|
struct RubyKeywordFactory {
|
|
391
430
|
class: Opaque<Value>,
|
|
392
431
|
}
|
|
393
432
|
|
|
394
433
|
/// Wrapper for a Ruby custom keyword validator instance.
|
|
395
|
-
struct RubyKeyword {
|
|
434
|
+
pub struct RubyKeyword {
|
|
396
435
|
instance: Opaque<Value>,
|
|
397
436
|
}
|
|
398
437
|
|
|
@@ -403,13 +442,14 @@ fn node_to_ruby(node: RbNode<'_>) -> Value {
|
|
|
403
442
|
}
|
|
404
443
|
}
|
|
405
444
|
|
|
406
|
-
impl
|
|
407
|
-
fn
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
445
|
+
impl RubyKeyword {
|
|
446
|
+
fn validate_object<'i>(
|
|
447
|
+
&self,
|
|
448
|
+
ruby: &Ruby,
|
|
449
|
+
instance: Value,
|
|
450
|
+
) -> Result<(), jsonschema::ValidationError<'i>> {
|
|
411
451
|
let keyword = ruby.get_inner(self.instance);
|
|
412
|
-
let result: Result<Value, _> = keyword.funcall("validate", (
|
|
452
|
+
let result: Result<Value, _> = keyword.funcall("validate", (instance,));
|
|
413
453
|
magnus_invalidate_members_cache();
|
|
414
454
|
match result {
|
|
415
455
|
Ok(_) => Ok(()),
|
|
@@ -423,28 +463,25 @@ impl<'i> jsonschema::Keyword<'i, Magnus> for RubyKeyword {
|
|
|
423
463
|
}
|
|
424
464
|
}
|
|
425
465
|
|
|
426
|
-
fn
|
|
427
|
-
let
|
|
428
|
-
let
|
|
429
|
-
let inst = ruby.get_inner(self.instance);
|
|
430
|
-
let result: Result<Value, _> = inst.funcall("validate", (rb_instance,));
|
|
466
|
+
fn is_valid_object(&self, ruby: &Ruby, instance: Value) -> bool {
|
|
467
|
+
let keyword = ruby.get_inner(self.instance);
|
|
468
|
+
let result: Result<Value, _> = keyword.funcall("validate", (instance,));
|
|
431
469
|
magnus_invalidate_members_cache();
|
|
432
470
|
result.is_ok()
|
|
433
471
|
}
|
|
434
472
|
|
|
435
|
-
fn
|
|
473
|
+
fn iter_errors_object<'i>(
|
|
436
474
|
&self,
|
|
437
|
-
|
|
475
|
+
ruby: &Ruby,
|
|
476
|
+
instance: Value,
|
|
438
477
|
) -> Box<dyn Iterator<Item = jsonschema::ValidationError<'i>> + 'i> {
|
|
439
|
-
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
440
478
|
let keyword = ruby.get_inner(self.instance);
|
|
441
479
|
// Without an `iter_errors` method, fall back to the single-error `validate` path.
|
|
442
480
|
if !keyword.respond_to("iter_errors", false).unwrap_or(false) {
|
|
443
|
-
return Box::new(self.
|
|
481
|
+
return Box::new(self.validate_object(ruby, instance).err().into_iter());
|
|
444
482
|
}
|
|
445
|
-
let rb_instance = node_to_ruby(instance);
|
|
446
483
|
let array = keyword
|
|
447
|
-
.funcall::<_, _, Value>("iter_errors", (
|
|
484
|
+
.funcall::<_, _, Value>("iter_errors", (instance,))
|
|
448
485
|
.and_then(|result| result.funcall::<_, _, RArray>("to_a", ()));
|
|
449
486
|
magnus_invalidate_members_cache();
|
|
450
487
|
let array = match array {
|
|
@@ -463,7 +500,7 @@ impl<'i> jsonschema::Keyword<'i, Magnus> for RubyKeyword {
|
|
|
463
500
|
})
|
|
464
501
|
.and_then(|index| array.entry::<Value>(index));
|
|
465
502
|
let error = match item {
|
|
466
|
-
Ok(item) => ruby_value_to_error(
|
|
503
|
+
Ok(item) => ruby_value_to_error(ruby, item),
|
|
467
504
|
Err(error) => error,
|
|
468
505
|
};
|
|
469
506
|
errors.push(custom_error_from_ruby(error));
|
|
@@ -472,8 +509,55 @@ impl<'i> jsonschema::Keyword<'i, Magnus> for RubyKeyword {
|
|
|
472
509
|
}
|
|
473
510
|
}
|
|
474
511
|
|
|
512
|
+
impl<'i> jsonschema::Keyword<'i, Magnus> for RubyKeyword {
|
|
513
|
+
fn validate(&self, instance: RbNode<'i>) -> Result<(), jsonschema::ValidationError<'i>> {
|
|
514
|
+
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
515
|
+
self.validate_object(&ruby, node_to_ruby(instance))
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
fn is_valid(&self, instance: RbNode<'i>) -> bool {
|
|
519
|
+
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
520
|
+
self.is_valid_object(&ruby, node_to_ruby(instance))
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
fn iter_errors(
|
|
524
|
+
&self,
|
|
525
|
+
instance: RbNode<'i>,
|
|
526
|
+
) -> Box<dyn Iterator<Item = jsonschema::ValidationError<'i>> + 'i> {
|
|
527
|
+
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
528
|
+
self.iter_errors_object(&ruby, node_to_ruby(instance))
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// The keyword class reads Ruby objects, so a node of JSON text becomes one first.
|
|
533
|
+
impl<'i> jsonschema::Keyword<'i, JsonText> for RubyKeyword {
|
|
534
|
+
fn validate(&self, instance: JsonTextNode<'i>) -> Result<(), jsonschema::ValidationError<'i>> {
|
|
535
|
+
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
536
|
+
match text_node_to_ruby(&ruby, &instance) {
|
|
537
|
+
Ok(object) => self.validate_object(&ruby, object),
|
|
538
|
+
Err(error) => Err(custom_error_from_ruby(error)),
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
fn is_valid(&self, instance: JsonTextNode<'i>) -> bool {
|
|
543
|
+
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
544
|
+
text_node_to_ruby(&ruby, &instance).is_ok_and(|object| self.is_valid_object(&ruby, object))
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
fn iter_errors(
|
|
548
|
+
&self,
|
|
549
|
+
instance: JsonTextNode<'i>,
|
|
550
|
+
) -> Box<dyn Iterator<Item = jsonschema::ValidationError<'i>> + 'i> {
|
|
551
|
+
let ruby = Ruby::get().expect("Ruby VM should be initialized");
|
|
552
|
+
match text_node_to_ruby(&ruby, &instance) {
|
|
553
|
+
Ok(object) => self.iter_errors_object(&ruby, object),
|
|
554
|
+
Err(error) => Box::new(std::iter::once(custom_error_from_ruby(error))),
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
475
559
|
// Wrap a yielded Ruby value as an `Error`, preserving exception instances so they surface as
|
|
476
|
-
// `#cause`; a non-exception
|
|
560
|
+
// `#cause`; a non-exception becomes a `RuntimeError` holding its text.
|
|
477
561
|
fn ruby_value_to_error(ruby: &Ruby, value: Value) -> Error {
|
|
478
562
|
if let Ok(exception) = Exception::try_convert(value) {
|
|
479
563
|
return Error::from(exception);
|
|
@@ -481,7 +565,13 @@ fn ruby_value_to_error(ruby: &Ruby, value: Value) -> Error {
|
|
|
481
565
|
let message = value
|
|
482
566
|
.funcall::<_, _, String>("to_s", ())
|
|
483
567
|
.unwrap_or_else(|_| "custom keyword error".to_string());
|
|
484
|
-
|
|
568
|
+
match ruby
|
|
569
|
+
.exception_runtime_error()
|
|
570
|
+
.new_instance((message.as_str(),))
|
|
571
|
+
{
|
|
572
|
+
Ok(exception) => Error::from(exception),
|
|
573
|
+
Err(error) => error,
|
|
574
|
+
}
|
|
485
575
|
}
|
|
486
576
|
|
|
487
577
|
// Build a custom `ValidationError` from a Ruby error, queuing the exception as the error's cause so
|
|
@@ -493,7 +583,7 @@ fn custom_error_from_ruby<'i>(error: Error) -> jsonschema::ValidationError<'i> {
|
|
|
493
583
|
}
|
|
494
584
|
|
|
495
585
|
#[allow(clippy::too_many_arguments)]
|
|
496
|
-
pub fn make_options_from_kwargs(
|
|
586
|
+
pub fn make_options_from_kwargs<F: Json>(
|
|
497
587
|
ruby: &Ruby,
|
|
498
588
|
draft: Option<jsonschema::Draft>,
|
|
499
589
|
validate_formats: Option<bool>,
|
|
@@ -509,7 +599,10 @@ pub fn make_options_from_kwargs(
|
|
|
509
599
|
email_options_val: Option<Value>,
|
|
510
600
|
http_options_val: Option<Value>,
|
|
511
601
|
offline: Option<bool>,
|
|
512
|
-
) -> Result<ParsedOptions<'_>, Error>
|
|
602
|
+
) -> Result<ParsedOptions<'_, F>, Error>
|
|
603
|
+
where
|
|
604
|
+
RubyKeyword: for<'i> jsonschema::Keyword<'i, F>,
|
|
605
|
+
{
|
|
513
606
|
let offline = offline.unwrap_or(false);
|
|
514
607
|
if offline && retriever_val.is_some() {
|
|
515
608
|
return Err(Error::new(
|
|
@@ -517,7 +610,7 @@ pub fn make_options_from_kwargs(
|
|
|
517
610
|
"`offline` cannot be used together with `retriever`",
|
|
518
611
|
));
|
|
519
612
|
}
|
|
520
|
-
let mut opts = jsonschema::options_for::<
|
|
613
|
+
let mut opts = jsonschema::options_for::<F>().with_retriever(DetachedRetriever(None));
|
|
521
614
|
let mut registry = None;
|
|
522
615
|
let mut retriever = None;
|
|
523
616
|
let retriever_was_provided = retriever_val.is_some();
|
|
@@ -608,7 +701,13 @@ pub fn make_options_from_kwargs(
|
|
|
608
701
|
for item in formats_hash.enumeratorize("each", ()) {
|
|
609
702
|
let pair: magnus::RArray = magnus::TryConvert::try_convert(item?)?;
|
|
610
703
|
let name: String = pair.entry(0)?;
|
|
611
|
-
let callback: Value = pair.entry(1)?;
|
|
704
|
+
let mut callback: Value = pair.entry(1)?;
|
|
705
|
+
let reads_numbers = if let Ok(number_format) = <&NumberFormat>::try_convert(callback) {
|
|
706
|
+
callback = ruby.get_inner(number_format.check);
|
|
707
|
+
true
|
|
708
|
+
} else {
|
|
709
|
+
false
|
|
710
|
+
};
|
|
612
711
|
|
|
613
712
|
let responds_to_call: bool =
|
|
614
713
|
callback.funcall("respond_to?", (SYM_CALL.to_symbol(),))?;
|
|
@@ -650,7 +749,13 @@ pub fn make_options_from_kwargs(
|
|
|
650
749
|
proc: Opaque::from(proc),
|
|
651
750
|
};
|
|
652
751
|
|
|
653
|
-
opts =
|
|
752
|
+
opts = if reads_numbers {
|
|
753
|
+
opts.with_number_format(name, move |number: &serde_json::Number| {
|
|
754
|
+
checker.check_number(number)
|
|
755
|
+
})
|
|
756
|
+
} else {
|
|
757
|
+
opts.with_format(name, move |value: &str| checker.check(value))
|
|
758
|
+
};
|
|
654
759
|
}
|
|
655
760
|
}
|
|
656
761
|
|
|
@@ -761,7 +866,7 @@ pub fn make_options_from_kwargs(
|
|
|
761
866
|
Ok(Box::new(RubyKeyword {
|
|
762
867
|
instance: opaque_inst,
|
|
763
868
|
})
|
|
764
|
-
as Box<dyn for<'i> jsonschema::Keyword<'i,
|
|
869
|
+
as Box<dyn for<'i> jsonschema::Keyword<'i, F>>)
|
|
765
870
|
}
|
|
766
871
|
Err(e) => Err(jsonschema::ValidationError::custom(format!(
|
|
767
872
|
"Failed to instantiate keyword class '{name_err}': {e}"
|
|
@@ -1166,6 +1271,8 @@ impl HttpOptions {
|
|
|
1166
1271
|
}
|
|
1167
1272
|
|
|
1168
1273
|
pub fn define_classes(ruby: &Ruby, module: &RModule) -> Result<(), Error> {
|
|
1274
|
+
module.define_class("NumberFormat", ruby.class_object())?;
|
|
1275
|
+
module.define_singleton_method("number_format", function!(number_format, 1))?;
|
|
1169
1276
|
let email_class = module.define_class("EmailOptions", ruby.class_object())?;
|
|
1170
1277
|
email_class.define_singleton_method("new", function!(EmailOptions::new_impl, -1))?;
|
|
1171
1278
|
email_class.define_method("require_tld", method!(EmailOptions::require_tld, 0))?;
|
data/src/ser.rs
CHANGED
|
@@ -800,7 +800,7 @@ pub fn value_to_ruby(ruby: &Ruby, value: &JsonValue) -> Result<Value, Error> {
|
|
|
800
800
|
}
|
|
801
801
|
|
|
802
802
|
#[inline]
|
|
803
|
-
fn number_to_ruby(ruby: &Ruby, number: &Number) -> Result<Value, Error> {
|
|
803
|
+
pub(crate) fn number_to_ruby(ruby: &Ruby, number: &Number) -> Result<Value, Error> {
|
|
804
804
|
if let Some(i) = number.as_i64() {
|
|
805
805
|
return Ok(ruby.into_value(i));
|
|
806
806
|
}
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: jsonschema_rs
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.63.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Dmitry Dygalo
|
|
@@ -66,6 +66,7 @@ files:
|
|
|
66
66
|
- src/canonical.rs
|
|
67
67
|
- src/error_kind.rs
|
|
68
68
|
- src/evaluation.rs
|
|
69
|
+
- src/json_text.rs
|
|
69
70
|
- src/lib.rs
|
|
70
71
|
- src/options.rs
|
|
71
72
|
- src/registry.rs
|
|
@@ -80,7 +81,7 @@ metadata:
|
|
|
80
81
|
homepage_uri: https://github.com/Stranger6667/jsonschema/tree/master/crates/jsonschema-rb
|
|
81
82
|
source_code_uri: https://github.com/Stranger6667/jsonschema
|
|
82
83
|
changelog_uri: https://github.com/Stranger6667/jsonschema/blob/master/crates/jsonschema-rb/CHANGELOG.md
|
|
83
|
-
documentation_uri: https://github.com/Stranger6667/jsonschema/blob/ruby-v0.
|
|
84
|
+
documentation_uri: https://github.com/Stranger6667/jsonschema/blob/ruby-v0.63.0/crates/jsonschema-rb/README.md
|
|
84
85
|
bug_tracker_uri: https://github.com/Stranger6667/jsonschema/issues
|
|
85
86
|
funding_uri: https://github.com/sponsors/Stranger6667
|
|
86
87
|
rubygems_mfa_required: 'true'
|