verquest 0.11.0 → 0.13.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7419f824e6f2966c2301b9f9c2ea9a3df48c6dd7559e7adbbd3ab297476726df
4
- data.tar.gz: ece88f624641894745c5b6d0a5a3dc818839ceb79deef5548657a8e9bf7553c2
3
+ metadata.gz: 25a0c3e261ec4a315a1acd735469afe54c6e6b0e2e2cc03e5033ee2ccd63be1d
4
+ data.tar.gz: 74e8bc5a752eb9d284be7474c52e15769ac486f77998c9932fb14d8edd293acf
5
5
  SHA512:
6
- metadata.gz: d541f01f0945d3003d21edf031eb1dca54256d5ed702b7bae7d08ab99a32407873822a787f509d0512edc93cf8cd09e4220cf7cf2b83bdf2d84c407459902524
7
- data.tar.gz: 43cbf7621f6a84d7f396835bf75358d842b835f92209abc3748bdd83e3287723a0a3895abb452a092e1ded7c9ac9470a6d6987424cfe8201fc13a4f237cceb0c
6
+ metadata.gz: c7f1bd79c153e32820e441331b2038a27db8ae7ecd2350966fee8312853217e390302d78195359debfdfccc2506053e8a7921934e9e284a43315244ccfd4b80c
7
+ data.tar.gz: c32d2717ec9b72db818f34088bb0ba2e1d373e89d60bd104176e085dfecbd469c33bcd2e3e906f3c49b475392a6cb3a609c8a66a2ce5f58b8b1cc8eba809e633
data/.rubocop.yml CHANGED
@@ -10,5 +10,5 @@ plugins:
10
10
  - rubocop-rake
11
11
 
12
12
  AllCops:
13
- TargetRubyVersion: 3.1
13
+ TargetRubyVersion: 3.3
14
14
  NewCops: enable # Enables new cops from plugins, as the main cops are managed by standard (the inherit_gem above)
data/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.13.0] - 2026-11-28
4
+
5
+ ### Added
6
+ - `process(..., reject_unknown_keys: true)` (or `config.reject_unknown_keys`) reports root keys that the version doesn't declare as validation errors of type `unknown`, when params are validated. The message lists the names the version accepts (or ends with "It accepts none."), and `details` has them as `accepted`. The keys are removed before coercion and validation, and their errors come first, in one failure with the other validation errors. Keys that `reject_other_version_keys` reports keep their `other_version` error. Keys the schema accepts (`additionalProperties` not `false`, `unevaluatedProperties` not `false` without `additionalProperties`, or matching `patternProperties`) aren't unknown, and `remove_extra_root_keys` still drops them. Symbol keys are unknown. Pointers escape `~` and `/`. The option takes precedence over `remove_extra_root_keys`, but `config.reject_unknown_keys` doesn't apply to a call that passes `remove_extra_root_keys: true`. It applies to lenient versions. A version with a root `one_of` accepts the keys of any variant.
7
+
8
+ ### Changed
9
+ - `property_names` of a version with a root `one_of` returns the names its variants declare, instead of `[nil]`, and `reject_other_version_keys` recognizes them.
10
+ - With `reject_other_version_keys`, `process` no longer returns early with only the `other_version` errors. It removes those keys and validates the rest, so the `other_version` errors come first in one failure with the unknown-key and other validation errors. Code that expects exactly the `other_version` errors may now get more.
11
+
12
+ ## [0.12.0] - 2026-11-17
13
+
14
+ ### Added
15
+ - A named `one_of` takes schema options: annotations (`description`, `title`, `examples`, `example`, `deprecated`, `readOnly`, `writeOnly`, `externalDocs`, `$comment`), `default` and `x-` extensions. They go on the property schema next to `oneOf`, or next to the outer `anyOf` of a nullable `one_of`. The validation schema takes only `default`, so a nullable `one_of` can default to null. A default that doesn't match the `one_of`, like null on one that isn't nullable, raises `Verquest::DefinitionError`, as does a default on a `one_of` with `required: [:other]`, which would make every request without the `one_of` need `other`. Other options raise `Verquest::DefinitionError`, as do schema options on an unnamed `one_of`.
16
+
17
+ ### Changed
18
+ - A named `one_of` inside `with_options` takes that block's annotation defaults (`description`, `title`, `deprecated`, `readOnly`, `writeOnly`, `externalDocs`), which changes the generated schemas. Other defaults, like `example`, `additional_properties` or `discriminator`, still don't apply to it. Its variants and their properties no longer take the annotations it takes, so they don't repeat the `one_of`'s description; they still take `examples`, `example` and `$comment`.
19
+ - Under `json_schema_version = :openapi30`, documents write `examples` as `example` (its first item, unless the schema has an `example`) and `$comment` as the `x-comment` extension, as OpenAPI 3.0 has neither. A schema with both a keyword and the extension it becomes, like `$comment` and `x-comment`, raises `Verquest::DefinitionError`.
20
+ - Verquest needs Ruby 3.3 or later. Ruby 3.2 reached its end of life on 2026-04-01.
21
+
22
+ ### Fixed
23
+ - An inserted default is a deep copy, so changing its nested Hashes, Arrays or Strings in the processed params no longer changes the default for later requests.
24
+ - A root `one_of` schema takes its version's `description` and the annotations and `x-` extensions of its `schema_options`, which it used to drop. Other schema options on its version, except `additional_properties`, raise `Verquest::DefinitionError`.
25
+ - Schema option keys of `x-` extensions and `$` keywords keep their names, so `"x-my_ext":` is no longer written as `x-myExt`.
26
+
3
27
  ## [0.11.0] - 2026-11-10
4
28
 
5
29
  ### Added
data/README.md CHANGED
@@ -133,6 +133,8 @@ error.errors
133
133
 
134
134
  Set `config.current_version` to drop the `version:` argument, or `config.validation_error_handling = :result` to get a `Verquest::Result` instead of an exception (see [Configuration](#configuration)). For query and path parameters in controllers, see [Rails and rswag](docs/rails.md).
135
135
 
136
+ With [`reject_unknown_keys`](#reject-unknown-keys) on, `params` also carries `controller`, `action`, `format` and route keys, so every request fails with an `unknown` error. Pass `request.request_parameters` or `request.query_parameters` instead, and turn off `wrap_parameters` in those controllers, as ParamsWrapper merges its wrapper key into `request_parameters`.
137
+
136
138
  ### JSON schema for OpenAPI
137
139
 
138
140
  `to_schema` returns the JSON Schema of a version for your API documentation. References stay `$ref`s:
@@ -358,7 +360,7 @@ OpenAPI 3.0 has no `null` type, so with `json_schema_version = :openapi30` docum
358
360
  - merged into a nullable constant (with `null` in its `enum`) or a `one_of` without a discriminator;
359
361
  - next to an `allOf` around a nullable reference (`{"allOf" => [{"$ref" => "..."}], "nullable" => true}`) or a nullable `one_of` with a discriminator, which keeps null outside the discriminated `oneOf`, as versponse does.
360
362
 
361
- OpenAPI 3.0 also has no `dependentRequired` (from `required: [:other]`), so documents write it as the `x-dependentRequired` extension. Validation still enforces it.
363
+ OpenAPI 3.0 also has no `dependentRequired` (from `required: [:other]`), so documents write it as the `x-dependentRequired` extension. Validation still enforces it. Nor does it have `examples` or `$comment`: documents write the first example as `example`, unless the schema has one, and `$comment` as the `x-comment` extension. A schema with both `$comment` and `x-comment`, or `dependentRequired` and `x-dependentRequired`, raises `Verquest::DefinitionError`.
362
364
 
363
365
  Mixed types become an `anyOf` of single types, each nullable when the property is. Strict OpenAPI 3.0.3 tools honour `nullable` only next to `type`, so they may still treat a nullable reference or `one_of` as not nullable. Validation schemas keep the forms above, which validators honour.
364
366
 
@@ -560,9 +562,10 @@ OrderRequest.process({"order_id" => "o1", "payment" => {"method" => "card", "car
560
562
  "discriminator" => {"propertyName" => "method", "mapping" => {"card" => "#/components/schemas/CardPaymentComponent", "bank" => "#/components/schemas/BankPaymentComponent"}}}
561
563
  ```
562
564
 
563
- - Without `name:`, the whole request is one of the variants (`one_of discriminator: :type do ... end` as the only property of a version).
565
+ - Without `name:`, the whole request is one of the variants (`one_of discriminator: :type do ... end` as the only property of a version). Its schema takes the version's `description` and the annotations and `x-` extensions of its `schema_options`; other schema options, except `additional_properties`, raise `Verquest::DefinitionError`.
564
566
  - Without `discriminator:`, the value must match exactly one variant's schema. Validation rejects it otherwise; with validation off, mapping raises `Verquest::MappingError`.
565
567
  - `one_of` works inside objects, collections and other variants, and with `nullable: true` and `map:`.
568
+ - A named `one_of` takes schema options: annotations (`description:`, `title:`, `examples:`, `example:`, `deprecated:`, `read_only:`, `write_only:`, `external_docs:`, `"$comment":`), `default:` and `x-` extensions (`"x-internal": true`). They go on the property schema next to `oneOf`, or next to the outer `anyOf` of a nullable `one_of`; the validation schema takes only `default:`, which must match the `one_of` (null only when it is `nullable: true`) and can't go with `required: [:other]`. From `with_options`, it takes only `description`, `title`, `deprecated`, `read_only`, `write_only` and `external_docs`, and its variants take none of those, only the block's `examples`, `example` and `$comment`. Other options, like `additional_properties:`, `min_properties:` or `parameter_examples:`, raise `Verquest::DefinitionError`. So do schema options on an unnamed `one_of`; describe its version or the enclosing property instead.
566
569
 
567
570
  #### oneOf discriminators in validation
568
571
 
@@ -927,7 +930,34 @@ DealsIndexQuery.process({"site_id" => "site_1"}, version: "2025-06", reject_othe
927
930
  # [{pointer: "/site_id", type: "other_version", message: "`site_id` isn't available in version 2025-06", details: nil}]
928
931
  ```
929
932
 
930
- `remove_extra_root_keys` still drops keys that no version declares, such as `utm_source`. The check works for body requests too, and runs only when `process` validates the params. `config.reject_other_version_keys` sets the default (`false`).
933
+ `process` removes those keys and still validates the rest, so the `other_version` errors come first in one failure with the other validation errors. `remove_extra_root_keys` still drops keys that no version declares, such as `utm_source`. The check works for body requests too, and runs only when `process` validates the params. `config.reject_other_version_keys` sets the default (`false`).
934
+
935
+ #### Reject unknown keys
936
+
937
+ With `reject_unknown_keys: true`, `process` reports every root key that the version doesn't accept as a validation error, and lists the names it declares:
938
+
939
+ ```ruby
940
+ DealsIndexQuery.process({"page" => "0", "colour" => "red"}, version: "2025-06", reject_unknown_keys: true)
941
+ # raises Verquest::InvalidParamsError with
942
+ # [{pointer: "/colour", type: "unknown",
943
+ # message: "`colour` isn't a parameter of version 2025-06. It accepts: page, archived, sort_direction, status, created.",
944
+ # details: {accepted: ["page", "archived", "sort_direction", "status", "created"]}},
945
+ # {pointer: "/page", ...}]
946
+ ```
947
+
948
+ - `process` removes the unknown keys before it coerces and validates the params, so the schema doesn't also report them as additional properties. The `other_version` errors come first, then the unknown-key errors, then the other validation errors, in one failure.
949
+ - A version that declares no properties ends the message with "It accepts none." and has `accepted: []`.
950
+ - With `reject_other_version_keys: true`, a key that only another version declares gets its `other_version` error instead. Without it, that key is unknown.
951
+ - A key the schema accepts isn't unknown: any key when `additionalProperties` isn't `false` (see `config.default_additional_properties`), or, without `additionalProperties`, when `unevaluatedProperties` isn't `false`, and keys that match `patternProperties`. `remove_extra_root_keys` still drops them; without it, `process` keeps and validates them. Other keywords that restrict keys, like `propertyNames`, are left to the schema's errors.
952
+ - The option takes precedence over `remove_extra_root_keys`: unknown keys are reported, not dropped. `config.reject_unknown_keys` doesn't apply to a call that passes `remove_extra_root_keys: true`, so that call still drops extra keys.
953
+ - The pointer escapes `~` and `/` in the key, as in `/a~1b` for `a/b`.
954
+ - A lenient version reports unknown keys too; it never removes them as a correction. Corrections to other params are still yielded.
955
+ - A version whose root is a `one_of` accepts the keys of any variant, and `accepted` and `property_names` list them all. A key of another variant than the one sent is left to the `oneOf` errors.
956
+ - Corrections can be yielded even when `process` then fails, for example with an unknown key.
957
+ - `process` reads String keys, as `ActionController::Parameters` gives them. A Symbol key is unknown; a declared one gets the message "`name` isn't a String key; process reads String keys only".
958
+ - In Rails, pass `request.request_parameters` or `request.query_parameters`, not `params`, and turn off `wrap_parameters` (see [Process params in a Rails controller](#process-params-in-a-rails-controller)).
959
+
960
+ The check works for body, query and path requests, and runs only when `process` validates the params. `config.reject_unknown_keys` sets the default (`false`).
931
961
 
932
962
  ### Path parameters
933
963
 
@@ -986,6 +1016,9 @@ Verquest.configure do |config|
986
1016
 
987
1017
  # Report root keys that only another version declares, see Filters
988
1018
  config.reject_other_version_keys = false # default
1019
+
1020
+ # Report root keys that the version doesn't declare, instead of removing them, see Filters
1021
+ config.reject_unknown_keys = false # default
989
1022
 
990
1023
  # Set custom version resolver
991
1024
  config.version_resolver = CustomVersionResolver # default is `Verquest::VersionResolver`
data/docs/rails.md CHANGED
@@ -66,6 +66,8 @@ module VerquestParams
66
66
  @path_params = by_location.fetch(:path, []).to_h { |declaration| process_path_param(declaration) }
67
67
  # Unknown query keys (cache busters, tracking) are dropped instead of rejected. Add
68
68
  # `reject_other_version_keys: true` to reject keys from another version, such as a newer filter.
69
+ # `reject_unknown_keys: true` rejects every undeclared key; with it, turn off `wrap_parameters`,
70
+ # which adds its wrapper key to `request_parameters`.
69
71
  # A lenient request (config.lenient_through) yields each value it corrected instead of rejecting.
70
72
  @query_params = by_location[:query]&.first&.dig(:class)&.process(request.query_parameters, remove_extra_root_keys: true) do |correction|
71
73
  Rails.logger.info("Corrected query param: #{correction.to_h.except(:from)}")
@@ -14,12 +14,13 @@ module Verquest
14
14
  #
15
15
  # Transforms all keys in the given hash from snake_case (e.g., "max_length")
16
16
  # to camelCase (e.g., "maxLength") format, which is commonly used in JSON Schema.
17
+ # Keys of x- extensions and $ keywords are kept as they are, as their names are exact.
17
18
  # The transformation happens in place, modifying the original hash.
18
19
  #
19
20
  # @param hash [Hash] The hash containing snake_case keys
20
21
  # @return [Hash] The same hash with keys transformed to camelCase
21
22
  def camelize(hash)
22
- hash.transform_keys! { |key| snake_to_camel(key.to_s).to_sym }
23
+ hash.transform_keys! { |key| key.to_s.start_with?("x-", "$") ? key.to_sym : snake_to_camel(key.to_s).to_sym }
23
24
  end
24
25
 
25
26
  # Converts a snake_case string to camelCase
@@ -462,39 +462,118 @@ module Verquest
462
462
  # @param required [Boolean, Array<Symbol>, nil] Whether this property is required
463
463
  # @param nullable [Boolean] Whether this property can be null
464
464
  # @param map [String, nil] An optional mapping to another property
465
+ # @param schema_options [Hash] Additional schema options for a named oneOf property: annotations, like a description,
466
+ # a default and x- extensions. Only annotations without examples come from the with_options defaults
467
+ # (see Verquest::Properties::OneOf::DEFAULT_ANNOTATION_KEYWORDS), and the variants of a named oneOf
468
+ # don't take the with_options annotations
465
469
  # @yield Block defining the schema options using reference declarations
466
470
  # @return [void]
467
- def one_of(name: nil, discriminator: nil, required: nil, nullable: nil, map: nil, &block)
471
+ # @raise [Verquest::DefinitionError] If schema options are given without a name, or aren't annotations,
472
+ # a default or x- extensions (see Verquest::Properties::OneOf.schema_option?)
473
+ def one_of(name: nil, discriminator: nil, required: nil, nullable: nil, map: nil, **schema_options, &block)
474
+ previous_scope = current_scope
475
+ previous_options = default_options
476
+ camelize(schema_options)
468
477
  required = default_options.fetch(:required, false) if required.nil?
469
478
  nullable = default_options.fetch(:nullable, false) if nullable.nil?
479
+ schema_options = one_of_schema_options(name, schema_options)
470
480
 
471
- one_of = Properties::OneOf.new(name:, discriminator:, required:, nullable:, map:)
481
+ one_of = Properties::OneOf.new(name:, discriminator:, required:, nullable:, map:, **schema_options)
472
482
  current_scope.add(one_of)
473
483
 
474
484
  if block_given?
475
- previous_scope = current_scope
476
485
  @current_scope = one_of
486
+ # A named oneOf holds the with_options annotations it takes, so its variants don't repeat them
487
+ @default_options = default_options.except(*Properties::OneOf::DEFAULT_ANNOTATION_OPTIONS) if name
477
488
 
478
489
  instance_exec(&block)
479
490
  end
480
491
  ensure
481
- @current_scope = previous_scope if block_given?
492
+ if block_given?
493
+ @current_scope = previous_scope
494
+ @default_options = previous_options
495
+ end
496
+ end
497
+
498
+ # Schema options of a oneOf, with the annotation defaults of with_options for a named one
499
+ #
500
+ # A named oneOf takes only annotations without examples from the with_options
501
+ # defaults, and Verquest::Properties::OneOf checks the options it's given.
502
+ # An unnamed oneOf stands for its scope and has no property schema to hold
503
+ # options, so it ignores the defaults and rejects its own options.
504
+ #
505
+ # @param name [Symbol, nil] The oneOf property name
506
+ # @param schema_options [Hash] The camelized schema options given to the oneOf
507
+ # @return [Hash] The schema options for the oneOf property
508
+ # @raise [Verquest::DefinitionError] If schema options are given without a name
509
+ def one_of_schema_options(name, schema_options)
510
+ return default_options.slice(*Properties::OneOf::DEFAULT_ANNOTATION_OPTIONS).merge(schema_options) if name
511
+ return schema_options if schema_options.empty?
512
+
513
+ alternative = current_scope.is_a?(Version) ? "describe the version" : "put the options on the enclosing property"
514
+ raise DefinitionError, "An unnamed one_of in version '#{@defining_version&.name}' can't take schema options " \
515
+ "(#{schema_options.keys.join(", ")}), give it a name: or #{alternative}"
482
516
  end
483
517
 
484
- # Errors for root keys that only another version declares
518
+ # Removes the root keys that only another version declares, with an error for each
485
519
  #
486
520
  # @param params [Hash] The params being processed
487
521
  # @param version [Verquest::Version] The resolved version
488
- # @return [Array<Hash>] One error per key, in the format of validation errors
489
- def other_version_key_errors(params, version)
490
- other_names = versions.property_names - version.all_properties.keys
522
+ # @return [Array(Hash, Array<Hash>)] The params without those keys, and one error per key
523
+ def without_other_version_keys(params, version)
524
+ other_names = versions.property_names - version.root_property_names
525
+ found = params.keys.select { |key| other_names.include?(key.to_s) }
526
+ return [params, []] if found.empty?
527
+
528
+ errors = found.map { |key| root_key_error(key.to_s, "other_version", "`#{key}` isn't available in version #{version.name}") }
529
+ [params.except(*found), errors]
530
+ end
491
531
 
492
- params.keys.filter_map do |key|
493
- key = key.to_s
494
- next unless other_names.include?(key)
532
+ # Removes the root keys the version doesn't accept, with an error for each
533
+ #
534
+ # A key is accepted when it's a declared String key, or when the schema accepts it
535
+ # (additionalProperties isn't false, or it matches patternProperties). Keys only another
536
+ # version declares stay unknown here; with reject_other_version_keys,
537
+ # {#without_other_version_keys} removes and reports them before this runs.
538
+ #
539
+ # @param params [Hash] The params being processed
540
+ # @param version [Verquest::Version] The resolved version
541
+ # @param remove_accepted [Boolean] Whether to also remove undeclared keys the schema accepts, as remove_extra_root_keys does
542
+ # @return [Array(Hash, Array<Hash>)] The params without the removed keys, and one error per unknown key
543
+ def without_unknown_keys(params, version, remove_accepted:)
544
+ undeclared = params.keys.reject { |key| key.is_a?(String) && version.declares_root_key?(key) }
545
+ return [params, []] if undeclared.empty?
546
+
547
+ unknown = undeclared.reject { |key| key.is_a?(String) && version.accepts_root_key?(key) }
548
+ [params.except(*(remove_accepted ? undeclared : unknown)), unknown.map { |key| unknown_key_error(key, version) }]
549
+ end
495
550
 
496
- {pointer: "/#{key}", type: "other_version", message: "`#{key}` isn't available in version #{version.name}", details: nil}
551
+ # The error for a root key the version doesn't accept
552
+ #
553
+ # @param key [String, Symbol, Object] The unknown key
554
+ # @param version [Verquest::Version] The resolved version
555
+ # @return [Hash] The error, in the format of validation errors
556
+ def unknown_key_error(key, version)
557
+ accepted = version.root_property_names
558
+ name = key.to_s
559
+ message = if !key.is_a?(String) && accepted.include?(name)
560
+ "`#{name}` isn't a String key; process reads String keys only"
561
+ else
562
+ "`#{name}` isn't a parameter of version #{version.name}. #{accepted.empty? ? "It accepts none." : "It accepts: #{accepted.join(", ")}."}"
497
563
  end
564
+
565
+ root_key_error(name, "unknown", message, {accepted:})
566
+ end
567
+
568
+ # Builds the validation error of a root key
569
+ #
570
+ # @param name [String] The root key
571
+ # @param type [String] The error type
572
+ # @param message [String] The error message
573
+ # @param details [Hash, nil] The error details
574
+ # @return [Hash] The error, with an escaped JSON pointer
575
+ def root_key_error(name, type, message, details = nil)
576
+ {pointer: Correction.pointer([name]), type:, message:, details:}
498
577
  end
499
578
 
500
579
  # Reports failed params according to the validation_error_handling setting
@@ -16,13 +16,17 @@ module Verquest
16
16
  # @param validate [Boolean, nil] Whether to validate the params, defaults to configuration setting
17
17
  # @param remove_extra_root_keys [Boolean, nil] Whether to remove extra keys at the root level, defaults to configuration setting
18
18
  # @param reject_other_version_keys [Boolean, nil] Whether to report root keys only another version declares as validation errors (only when validating), defaults to configuration setting
19
+ # @param reject_unknown_keys [Boolean, nil] Whether to report root keys the version doesn't accept as validation errors (only when validating;
20
+ # for a root one_of, keys no variant accepts), instead of removing them, defaults to configuration setting unless remove_extra_root_keys is true
19
21
  # @param lenient [Boolean, nil] Whether a query or path request corrects values instead of rejecting them, defaults to
20
22
  # comparing the requested version with the configuration's lenient_through
21
23
  # @yieldparam correction [Verquest::Correction] Each correction a lenient request made
22
24
  # @return [Verquest::Result, Hash] When validation_error_handling is :result, returns a Success result with mapped params or Failure result with validation errors.
23
25
  # When validation_error_handling is :raise, returns mapped params directly or raises InvalidParamsError with validation errors.
24
- def process(params, version: nil, validate: nil, remove_extra_root_keys: nil, reject_other_version_keys: nil, lenient: nil, &on_correction)
26
+ def process(params, version: nil, validate: nil, remove_extra_root_keys: nil, reject_other_version_keys: nil, reject_unknown_keys: nil, lenient: nil, &on_correction)
25
27
  validate = Verquest.configuration.validate_params if validate.nil?
28
+ # An explicit remove_extra_root_keys: true wins over config.reject_unknown_keys
29
+ reject_unknown_keys = remove_extra_root_keys != true && Verquest.configuration.reject_unknown_keys if reject_unknown_keys.nil?
26
30
  remove_extra_root_keys = Verquest.configuration.remove_extra_root_keys if remove_extra_root_keys.nil?
27
31
  reject_other_version_keys = Verquest.configuration.reject_other_version_keys if reject_other_version_keys.nil?
28
32
 
@@ -33,11 +37,17 @@ module Verquest
33
37
  params = params.dup
34
38
  params = params.to_unsafe_h if params.respond_to?(:to_unsafe_h)
35
39
 
36
- if validate && reject_other_version_keys && (other_version_errors = other_version_key_errors(params, version_class)).any?
37
- return validation_failure(other_version_errors)
40
+ key_errors = []
41
+ if validate && reject_other_version_keys
42
+ params, key_errors = without_other_version_keys(params, version_class)
38
43
  end
39
44
 
40
- params = params.slice(*version_class.all_properties.keys) if remove_extra_root_keys && !version_class.combination?
45
+ if validate && reject_unknown_keys
46
+ params, unknown_errors = without_unknown_keys(params, version_class, remove_accepted: remove_extra_root_keys && !version_class.combination?)
47
+ key_errors += unknown_errors
48
+ elsif remove_extra_root_keys && !version_class.combination?
49
+ params = params.slice(*version_class.all_properties.keys)
50
+ end
41
51
  sent = params
42
52
  corrections = []
43
53
  params = version_class.coerce_params(params, lenient:) { |correction| corrections << correction }
@@ -45,6 +55,7 @@ module Verquest
45
55
 
46
56
  params, errors, invalid = validate ? validated_params(params, version_class, lenient:) : [params, [], []]
47
57
  with_invalid_corrections(corrections, invalid, sent).each(&on_correction) if on_correction
58
+ errors = key_errors + errors
48
59
  return validation_failure(errors) if errors.any?
49
60
 
50
61
  mapped_result(params, version_class)
@@ -56,9 +67,10 @@ module Verquest
56
67
  # DealsIndexQuery.property_names(version: "2025-06") # => ["page", "archived", "sort_direction", "status", "created"]
57
68
  #
58
69
  # @param version [String, nil] Specific version to use, defaults to configuration setting
59
- # @return [Array<String>] Root property names in declaration order, inherited ones included
70
+ # @return [Array<String>] Root property names in declaration order, inherited ones included; for a root one_of,
71
+ # the names of its variants
60
72
  def property_names(version: nil)
61
- resolve(version).all_properties.keys
73
+ resolve(version).root_property_names
62
74
  end
63
75
 
64
76
  # Returns the names of the filters the version declares
@@ -70,12 +70,18 @@ module Verquest
70
70
  # Controls whether `process` reports root keys that only another version of the request declares, when it validates params
71
71
  # @return [Boolean] true to report them as validation errors, false to treat them as unknown keys (default)
72
72
  #
73
+ # @!attribute [rw] reject_unknown_keys
74
+ # Controls whether `process` reports root keys that the resolved version doesn't accept, when it validates params.
75
+ # It takes precedence over remove_extra_root_keys, except in a call that passes remove_extra_root_keys: true.
76
+ # A version with a root one_of accepts the keys of any of its variants
77
+ # @return [Boolean] true to report them as validation errors, false to leave them to remove_extra_root_keys (default)
78
+ #
73
79
  # @!attribute [rw] lenient_through
74
80
  # The last version whose query and path requests are corrected instead of rejected (see {Verquest::Correction})
75
81
  # @return [String, nil] A version name; nil (default) makes every request strict
76
82
  attr_accessor :validate_params, :json_schema_version, :validation_error_handling,
77
83
  :remove_extra_root_keys, :insert_property_defaults, :default_additional_properties,
78
- :query_array_explode, :reject_other_version_keys, :lenient_through
84
+ :query_array_explode, :reject_other_version_keys, :reject_unknown_keys, :lenient_through
79
85
 
80
86
  # @!attribute [r] current_version
81
87
  # A callable object that returns the current API version to use when not explicitly specified
@@ -104,6 +110,7 @@ module Verquest
104
110
  @default_additional_properties = false
105
111
  @query_array_explode = true
106
112
  @reject_other_version_keys = false
113
+ @reject_unknown_keys = false
107
114
  @lenient_through = nil
108
115
  end
109
116
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Verquest
4
- GEM_VERSION = "0.11.0"
4
+ GEM_VERSION = "0.13.0"
5
5
  end
@@ -10,7 +10,9 @@ module Verquest
10
10
  # - an `anyOf` with a single null alternative becomes `nullable: true`, with an `allOf` around a `$ref`
11
11
  # (OpenAPI 3.0 ignores keywords next to `$ref`) or a discriminated `oneOf` (which would reject null),
12
12
  # and `null` added to an `enum`
13
- # - `dependentRequired` becomes the `x-dependentRequired` extension
13
+ # - `dependentRequired` becomes the `x-dependentRequired` extension, and `$comment` the `x-comment` extension
14
+ # (a schema with both a keyword and its extension raises Verquest::DefinitionError)
15
+ # - `examples` becomes `example`, its first item, unless the schema has an `example`
14
16
  #
15
17
  # Only schema positions are visited, so a property named "type" is never read as the keyword.
16
18
  #
@@ -34,7 +36,7 @@ module Verquest
34
36
  ].freeze
35
37
 
36
38
  # Keywords OpenAPI 3.0 lacks, written as extensions
37
- RENAMED = {"dependentRequired" => "x-dependentRequired"}.freeze
39
+ RENAMED = {"dependentRequired" => "x-dependentRequired", "$comment" => "x-comment"}.freeze
38
40
 
39
41
  module_function
40
42
 
@@ -44,7 +46,34 @@ module Verquest
44
46
  return schema unless schema.is_a?(::Hash)
45
47
 
46
48
  # The null alternative goes first, so a merged alternative's type array meets nullable in type_union
47
- type_union(nullable_any_of(schema).to_h { |keyword, value| [RENAMED.fetch(keyword, keyword), child(keyword, value)] })
49
+ schema = single_example(nullable_any_of(schema))
50
+ check_renamed(schema)
51
+ type_union(schema.to_h { |keyword, value| [RENAMED.fetch(keyword, keyword), child(keyword, value)] })
52
+ end
53
+
54
+ # Raises when a schema has a keyword and the extension it's written as, so one would overwrite the other
55
+ #
56
+ # @param schema [Hash] A schema
57
+ # @return [void]
58
+ # @raise [Verquest::DefinitionError] If the schema has both
59
+ def check_renamed(schema)
60
+ RENAMED.each do |keyword, extension|
61
+ next unless schema.key?(keyword) && schema.key?(extension)
62
+
63
+ raise DefinitionError, "A schema has both #{keyword} and #{extension}, which OpenAPI 3.0 documents write #{keyword} as"
64
+ end
65
+ end
66
+
67
+ # OpenAPI 3.0 has a single `example` and no `examples`
68
+ #
69
+ # @param schema [Hash] A schema
70
+ # @return [Hash] The schema without examples, with the first one as its example unless it has one
71
+ def single_example(schema)
72
+ examples = schema["examples"]
73
+ return schema unless examples.is_a?(::Array)
74
+ return schema.except("examples") if schema.key?("example") || examples.empty?
75
+
76
+ schema.except("examples").merge("example" => examples.first)
48
77
  end
49
78
 
50
79
  # @param keyword [String] The schema keyword
@@ -123,6 +152,6 @@ module Verquest
123
152
  schema.key?("enum") ? schema.merge("enum" => schema["enum"] | [nil]) : schema
124
153
  end
125
154
 
126
- private_class_method :child, :type_union, :any_of, :nullable_any_of, :nullable_alternative, :nullable_enum
155
+ private_class_method :check_renamed, :single_example, :child, :type_union, :any_of, :nullable_any_of, :nullable_alternative, :nullable_enum
127
156
  end
128
157
  end
@@ -34,6 +34,32 @@ module Verquest
34
34
  # With a discriminator, the validation schema keeps the discriminator (see DiscriminatedSchema),
35
35
  # so OpenAPI 3.0 and 3.1 validators validate only the variant the discriminator selects.
36
36
  class OneOf < Base
37
+ # Annotation keywords a named oneOf takes, which go only into the documentation schema
38
+ ANNOTATION_KEYWORDS = %w[description title examples example deprecated readOnly writeOnly externalDocs $comment].freeze
39
+
40
+ # Annotation keywords a named oneOf takes from the with_options defaults. Examples and
41
+ # $comment are left out, as they're written for the sibling properties and may not fit
42
+ # the oneOf, so they go to its variants instead.
43
+ DEFAULT_ANNOTATION_KEYWORDS = (ANNOTATION_KEYWORDS - %w[examples example $comment]).freeze
44
+
45
+ # DEFAULT_ANNOTATION_KEYWORDS as the with_options keys the DSL slices
46
+ DEFAULT_ANNOTATION_OPTIONS = DEFAULT_ANNOTATION_KEYWORDS.map(&:to_sym).freeze
47
+
48
+ # Keywords a named oneOf takes besides annotations, which also go into the validation schema
49
+ VALIDATION_KEYWORDS = %w[default].freeze
50
+
51
+ # Whether a named oneOf takes the schema option
52
+ #
53
+ # A named oneOf takes annotations, a default and x- extensions. Any other keyword
54
+ # would constrain the value next to the variants, or isn't a schema keyword.
55
+ #
56
+ # @param key [String, Symbol] The camelized schema option key
57
+ # @return [Boolean] true if the oneOf takes the option
58
+ def self.schema_option?(key)
59
+ key = key.to_s
60
+ ANNOTATION_KEYWORDS.include?(key) || VALIDATION_KEYWORDS.include?(key) || key.start_with?("x-")
61
+ end
62
+
37
63
  # @return [String, nil] The discriminator property name for schema selection
38
64
  attr_reader :discriminator
39
65
 
@@ -45,13 +71,21 @@ module Verquest
45
71
  # @param required [Boolean, Array<Symbol>] Whether this property is required, or array of dependency names
46
72
  # @param nullable [Boolean] Whether this property can be null
47
73
  # @param map [String, nil] The mapping path for this property
48
- def initialize(name: nil, discriminator: nil, required: false, nullable: false, map: nil)
74
+ # @param schema_options [Hash] Additional JSON schema options for a named oneOf property, like a description
75
+ # (see .schema_option?)
76
+ # @raise [Verquest::DefinitionError] If a schema option isn't an annotation, a default or an x- extension,
77
+ # or the oneOf has a default and requires other properties
78
+ def initialize(name: nil, discriminator: nil, required: false, nullable: false, map: nil, **schema_options)
49
79
  @name = name&.to_s
50
80
  @required = required
51
81
  @nullable = nullable
52
82
  @map = map
53
83
  @discriminator = discriminator&.to_s
54
84
  @schemas = {}
85
+ @schema_options = schema_options.transform_keys(&:to_s)
86
+ @checked_default_schemas = {}
87
+ check_schema_options
88
+ check_default_dependencies
55
89
  end
56
90
 
57
91
  # Add a schema option to this oneOf
@@ -78,19 +112,24 @@ module Verquest
78
112
  # @return [Hash] The schema definition with oneOf array and optional discriminator
79
113
  def to_schema
80
114
  freeze_schemas
81
- wrap_schema(nullable_schema(build_schema_with_refs))
115
+ wrap_schema(nullable_schema(build_schema_with_refs).merge(schema_options))
82
116
  end
83
117
 
84
118
  # Generate validation schema for this oneOf property
85
119
  #
86
120
  # Unlike to_schema which uses $ref, the validation schema includes
87
- # the full inline schema definitions for each option.
121
+ # the full inline schema definitions for each option. Of the schema
122
+ # options, it keeps only the default, as annotations and extensions
123
+ # don't take part in validation.
88
124
  #
89
125
  # @param version [String, nil] The version to generate validation schema for
90
126
  # @return [Hash] The validation schema with inline schema definitions
127
+ # @raise [Verquest::DefinitionError] If the default doesn't match the schema
91
128
  def to_validation_schema(version: nil)
92
129
  freeze_schemas
93
- wrap_schema(nullable_schema(build_validation_schema(version: version)))
130
+ schema = nullable_schema(build_validation_schema(version: version))
131
+ check_default(schema)
132
+ wrap_schema(schema.merge(schema_options.slice(*VALIDATION_KEYWORDS)))
94
133
  end
95
134
 
96
135
  # Create mapping for this oneOf property
@@ -163,7 +202,48 @@ module Verquest
163
202
 
164
203
  private
165
204
 
166
- attr_reader :schemas
205
+ attr_reader :schemas, :schema_options
206
+
207
+ # Raises for schema options a oneOf doesn't take (see .schema_option?)
208
+ #
209
+ # @return [void]
210
+ # @raise [Verquest::DefinitionError] If a schema option isn't an annotation, a default or an x- extension
211
+ def check_schema_options
212
+ rejected = schema_options.keys.reject { |key| self.class.schema_option?(key) }
213
+ return if rejected.empty?
214
+
215
+ raise DefinitionError, "one_of '#{name}' can't take #{rejected.join(", ")}, " \
216
+ "it takes only #{(ANNOTATION_KEYWORDS + VALIDATION_KEYWORDS).join(", ")} and x- extensions"
217
+ end
218
+
219
+ # Raises when the oneOf has a default and requires other properties, as inserting
220
+ # the default would make every request without the oneOf need them
221
+ #
222
+ # @return [void]
223
+ # @raise [Verquest::DefinitionError] If the oneOf has a default and requires other properties
224
+ def check_default_dependencies
225
+ return unless schema_options.key?("default") && required.is_a?(::Array)
226
+
227
+ raise DefinitionError, "one_of '#{name}' has a default and requires #{required.join(", ")}, " \
228
+ "so every request without #{name} would need #{required.join(", ")}"
229
+ end
230
+
231
+ # Raises when the default doesn't match the oneOf, so inserting it wouldn't fail the request
232
+ #
233
+ # Each schema is checked once, as versions that inherit the oneOf share it.
234
+ #
235
+ # @param schema [Hash] The validation schema without the default
236
+ # @return [void]
237
+ # @raise [Verquest::DefinitionError] If the default doesn't match the schema
238
+ def check_default(schema)
239
+ return unless schema_options.key?("default")
240
+
241
+ default = schema_options["default"]
242
+ key = [schema, Verquest.configuration.json_schema_uri]
243
+ return if @checked_default_schemas[key] ||= JSONSchemer.schema(schema, meta_schema: key[1]).valid?(default)
244
+
245
+ raise DefinitionError, "one_of '#{name}' has a default, #{default.inspect}, that doesn't match its schema"
246
+ end
167
247
 
168
248
  # Freezes the schemas hash to prevent further modifications
169
249
  # This is called on first read access to ensure immutability after setup
@@ -125,6 +125,36 @@ module Verquest
125
125
  @all_properties || super
126
126
  end
127
127
 
128
+ # Returns the names of the root properties, as clients send them
129
+ #
130
+ # For a root one_of, the names any variant declares.
131
+ #
132
+ # @return [Array<String>] Frozen root property names in declaration order
133
+ def root_property_names
134
+ @root_property_names || all_properties.keys.freeze
135
+ end
136
+
137
+ # Checks whether the schema accepts a root key, declared or not
138
+ #
139
+ # A key the version doesn't declare is accepted when additionalProperties
140
+ # isn't false (or, without it, unevaluatedProperties isn't false) or the key
141
+ # matches a patternProperties pattern. For a root
142
+ # one_of, a key is accepted when any variant accepts it.
143
+ #
144
+ # @param key [String] A root key from the params
145
+ # @return [Boolean] true when the schema accepts the key
146
+ def accepts_root_key?(key)
147
+ declares_root_key?(key) || @open_root || @root_key_patterns.any? { |pattern| pattern.match?(key) }
148
+ end
149
+
150
+ # Checks whether the version declares a root key
151
+ #
152
+ # @param key [String] A root key from the params
153
+ # @return [Boolean] true when the key is one of {#root_property_names}
154
+ def declares_root_key?(key)
155
+ @root_property_set.include?(key)
156
+ end
157
+
128
158
  # Copy properties and conditions from another version
129
159
  #
130
160
  # @param version [Verquest::Version] The version to copy properties from
@@ -169,6 +199,7 @@ module Verquest
169
199
  prepare_external_mapping
170
200
  end
171
201
 
202
+ prepare_root_keys
172
203
  prepare_parameters if parameters?
173
204
  @property_defaults = property_defaults?(validation_schema)
174
205
  @transformer = Transformer.new(layout: transformer_layout)
@@ -347,6 +378,61 @@ module Verquest
347
378
 
348
379
  private
349
380
 
381
+ # Stores which root keys the schema accepts, for {#accepts_root_key?}
382
+ #
383
+ # A root one_of takes the union of its variants, read from the validation schema:
384
+ # their property names and patterns, and open when any variant is open or isn't
385
+ # an object schema with properties.
386
+ #
387
+ # @return [void]
388
+ def prepare_root_keys
389
+ roots = combination? ? root_variant_schemas : [schema_options]
390
+ names = combination? ? roots.flat_map { |root| root.fetch("properties", {}).keys }.uniq : all_properties.keys
391
+
392
+ @root_property_names = names.freeze
393
+ @root_property_set = names.to_set.freeze
394
+ @open_root = roots.any? { |root| open_object_schema?(root) || (combination? && !root.key?("properties")) }
395
+ @root_key_patterns = roots.flat_map { |root| root.fetch("patternProperties", {}).keys }.uniq
396
+ .map { |pattern| Regexp.new(pattern.to_s) }.freeze
397
+ end
398
+
399
+ # Returns the object schemas of a root one_of's variants
400
+ #
401
+ # Follows local $refs (a discriminated one_of keeps its variants in definitions)
402
+ # and unwraps the anyOf of a nullable variant, leaving out its null schema.
403
+ #
404
+ # @return [Array<Hash>] The variants' object schemas
405
+ def root_variant_schemas
406
+ validation_schema.fetch("oneOf", []).flat_map { |variant| object_schemas(variant) }
407
+ end
408
+
409
+ # @param schema [Hash] A variant schema, or an entry of its anyOf
410
+ # @return [Array<Hash>] The object schemas it stands for
411
+ def object_schemas(schema)
412
+ if (ref = schema["$ref"])&.start_with?("#/")
413
+ object_schemas(validation_schema.dig(*ref.delete_prefix("#/").split("/")) || {})
414
+ elsif schema.key?("anyOf") && !schema.key?("properties")
415
+ schema["anyOf"].flat_map { |entry| object_schemas(entry) }
416
+ elsif schema["type"] == "null"
417
+ []
418
+ else
419
+ [schema]
420
+ end
421
+ end
422
+
423
+ # Checks whether an object schema accepts keys it doesn't declare
424
+ #
425
+ # additionalProperties decides when it's set, as it evaluates every key;
426
+ # without it, unevaluatedProperties does.
427
+ #
428
+ # @param schema [Hash] An object schema
429
+ # @return [Boolean] true when undeclared keys are accepted
430
+ def open_object_schema?(schema)
431
+ return schema["additionalProperties"] != false if schema.key?("additionalProperties")
432
+
433
+ schema["unevaluatedProperties"] != false
434
+ end
435
+
350
436
  # Collects names from `then`/`else` branches and `allOf`, `anyOf` and `oneOf` entries, conservatively
351
437
  # (a name any alternative requires counts); `if` and `not` don't require anything
352
438
  #
@@ -398,7 +484,39 @@ module Verquest
398
484
  key = [Verquest.configuration.json_schema_uri, insert_property_defaults_setting]
399
485
 
400
486
  @validation_schemers_lock.synchronize do
401
- @validation_schemers[key] ||= JSONSchemer.schema(validation_schema, meta_schema: key[0], insert_property_defaults: key[1])
487
+ @validation_schemers[key] ||= JSONSchemer.schema(
488
+ validation_schema, meta_schema: key[0], insert_property_defaults: key[1], property_default_resolver: property_default_resolver(key[1])
489
+ )
490
+ end
491
+ end
492
+
493
+ # Returns a resolver that inserts a deep copy of the default
494
+ #
495
+ # json_schemer inserts a shallow copy, so the params would share nested Hashes and Arrays
496
+ # with the schema, and changing them would change the default for later requests.
497
+ #
498
+ # @param setting [Boolean, Symbol] The insert_property_defaults value to compile with
499
+ # @return [Proc, nil] The resolver, or nil when defaults aren't inserted
500
+ def property_default_resolver(setting)
501
+ return unless setting
502
+
503
+ symbol = setting == :symbol
504
+ resolver = symbol ? JSONSchemer::Schema::SYMBOL_PROPERTY_DEFAULT_RESOLVER : JSONSchemer::Schema::DEFAULT_PROPERTY_DEFAULT_RESOLVER
505
+ proc do |instance, property, results|
506
+ resolver.call(instance, property, results).tap do |inserted|
507
+ key = symbol ? property.to_sym : property
508
+ instance[key] = copy_default(instance[key]) if inserted
509
+ end
510
+ end
511
+ end
512
+
513
+ # @param value [Object] An inserted default
514
+ # @return [Object] A copy of the value with copies of its Hashes, Arrays and Strings
515
+ def copy_default(value)
516
+ case value
517
+ when Hash then value.transform_values { |item| copy_default(item) }
518
+ when Array then value.map { |item| copy_default(item) }
519
+ else value.dup
402
520
  end
403
521
  end
404
522
 
@@ -432,14 +550,30 @@ module Verquest
432
550
  # Generates the JSON schema for combination schemas (oneOf at root level)
433
551
  #
434
552
  # For combination schemas, the schema is delegated directly to the oneOf
435
- # property since it represents the entire request structure.
553
+ # property since it represents the entire request structure. It takes the
554
+ # version's description and the annotations and x- extensions of its schema
555
+ # options. additionalProperties is left out, as the variants set their own.
436
556
  #
437
557
  # @return [Hash] The schema from the oneOf property
438
558
  # @raise [ArgumentError] If the version also has conditions
559
+ # @raise [Verquest::DefinitionError] If the version has other schema options
439
560
  def prepare_combination_schema
440
561
  raise ArgumentError, "Conditions can not be declared next to a root-level one_of" if conditions.any?
441
562
 
442
- @schema = document_schema(properties.values.first.to_schema)
563
+ annotations = combination_annotations
564
+ annotations["description"] = description if description
565
+ @schema = document_schema(properties.values.first.to_schema.merge(annotations))
566
+ end
567
+
568
+ # @return [Hash] The annotations and x- extensions of the schema options
569
+ # @raise [Verquest::DefinitionError] If the version has other schema options
570
+ def combination_annotations
571
+ options = schema_options.except("additionalProperties")
572
+ rejected = options.keys.reject { |key| key != "default" && Properties::OneOf.schema_option?(key) }
573
+ return options if rejected.empty?
574
+
575
+ raise DefinitionError, "The root one_of of version '#{name}' can't take schema options (#{rejected.join(", ")}), " \
576
+ "it takes only annotations and x- extensions"
443
577
  end
444
578
 
445
579
  # @return [Hash] The schema the meta-schema checks: the document under OpenAPI 3.0, the validation schema otherwise
@@ -66,11 +66,13 @@ module Verquest
66
66
 
67
67
  # Returns the root property names declared by any version
68
68
  #
69
+ # A version with a root one_of contributes the names of its variants.
70
+ #
69
71
  # Cached until the next version is added.
70
72
  #
71
73
  # @return [Array<String>] The property names
72
74
  def property_names
73
- @property_names ||= versions.values.flat_map { |version| version.all_properties.keys }.uniq.freeze
75
+ @property_names ||= versions.values.flat_map(&:root_property_names).uniq.freeze
74
76
  end
75
77
 
76
78
  private
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: verquest
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.11.0
4
+ version: 0.13.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Petr Hlavicka
@@ -132,7 +132,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
132
132
  requirements:
133
133
  - - ">="
134
134
  - !ruby/object:Gem::Version
135
- version: '3.2'
135
+ version: '3.3'
136
136
  required_rubygems_version: !ruby/object:Gem::Requirement
137
137
  requirements:
138
138
  - - ">="