riffer 0.54.0 → 0.55.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.
Files changed (83) hide show
  1. checksums.yaml +4 -4
  2. data/.claude/rules/rbs-inline.md +6 -6
  3. data/.release-please-manifest.json +1 -1
  4. data/.ruby-version +1 -1
  5. data/CHANGELOG.md +28 -0
  6. data/README.md +24 -0
  7. data/Steepfile +2 -2
  8. data/docs/AGENTS.md +37 -12
  9. data/docs/CATALOG.md +8 -8
  10. data/docs/CONFIGURATION.md +47 -16
  11. data/docs/MCP.md +3 -4
  12. data/docs/STREAM_EVENTS.md +1 -1
  13. data/docs/TOOLS.md +11 -11
  14. data/docs/TRACING.md +1 -1
  15. data/docs/providers/AMAZON_BEDROCK.md +2 -0
  16. data/docs/providers/ANTHROPIC.md +32 -36
  17. data/docs/providers/CUSTOM_PROVIDERS.md +35 -0
  18. data/docs/providers/GEMINI.md +76 -26
  19. data/docs/providers/GOOGLE_CLOUD.md +363 -0
  20. data/docs/providers/PROVIDERS.md +30 -18
  21. data/docs-site/manifest.yml +3 -0
  22. data/lib/riffer/agent/structured_output.rb +6 -1
  23. data/lib/riffer/config/anthropic.rb +9 -0
  24. data/lib/riffer/config/gemini.rb +9 -0
  25. data/lib/riffer/config/google_cloud.rb +38 -0
  26. data/lib/riffer/config.rb +3 -0
  27. data/lib/riffer/http/client.rb +141 -0
  28. data/lib/riffer/http.rb +5 -0
  29. data/lib/riffer/mcp/client.rb +0 -1
  30. data/lib/riffer/params/any_of.rb +37 -9
  31. data/lib/riffer/params/param.rb +35 -14
  32. data/lib/riffer/params.rb +34 -19
  33. data/lib/riffer/providers/amazon_bedrock.rb +38 -5
  34. data/lib/riffer/providers/anthropic/client.rb +49 -0
  35. data/lib/riffer/providers/anthropic.rb +19 -452
  36. data/lib/riffer/providers/anthropic_compatible/messages_api/stream.rb +195 -0
  37. data/lib/riffer/providers/anthropic_compatible/messages_api.rb +293 -0
  38. data/lib/riffer/providers/anthropic_compatible.rb +5 -0
  39. data/lib/riffer/providers/anthropic_vertex.rb +66 -0
  40. data/lib/riffer/providers/base.rb +4 -7
  41. data/lib/riffer/providers/gemini/client.rb +17 -85
  42. data/lib/riffer/providers/gemini.rb +213 -81
  43. data/lib/riffer/providers/google_cloud/client.rb +106 -0
  44. data/lib/riffer/providers/google_cloud.rb +99 -0
  45. data/lib/riffer/providers/repository.rb +2 -0
  46. data/lib/riffer/version.rb +1 -1
  47. data/lib/riffer/wire/sse.rb +51 -0
  48. data/lib/riffer/wire.rb +31 -0
  49. data/lib/riffer.rb +18 -0
  50. data/rbs_collection.lock.yaml +24 -4
  51. data/sig/_private/faraday.rbs +8 -0
  52. data/sig/_private/googleauth.rbs +7 -0
  53. data/sig/generated/riffer/config/anthropic.rbs +6 -0
  54. data/sig/generated/riffer/config/gemini.rbs +6 -0
  55. data/sig/generated/riffer/config/google_cloud.rbs +28 -0
  56. data/sig/generated/riffer/config.rbs +2 -0
  57. data/sig/generated/riffer/http/client.rbs +59 -0
  58. data/sig/generated/riffer/http.rbs +4 -0
  59. data/sig/generated/riffer/params/any_of.rbs +13 -5
  60. data/sig/generated/riffer/params/param.rbs +10 -5
  61. data/sig/generated/riffer/params.rbs +8 -4
  62. data/sig/generated/riffer/providers/amazon_bedrock.rbs +14 -2
  63. data/sig/generated/riffer/providers/anthropic/client.rbs +34 -0
  64. data/sig/generated/riffer/providers/anthropic.rbs +5 -124
  65. data/sig/generated/riffer/providers/anthropic_compatible/messages_api/stream.rbs +71 -0
  66. data/sig/generated/riffer/providers/anthropic_compatible/messages_api.rbs +99 -0
  67. data/sig/generated/riffer/providers/anthropic_compatible.rbs +4 -0
  68. data/sig/generated/riffer/providers/anthropic_vertex.rbs +45 -0
  69. data/sig/generated/riffer/providers/gemini/client.rbs +11 -34
  70. data/sig/generated/riffer/providers/gemini.rbs +66 -4
  71. data/sig/generated/riffer/providers/google_cloud/client.rbs +71 -0
  72. data/sig/generated/riffer/providers/google_cloud.rbs +64 -0
  73. data/sig/generated/riffer/wire/sse.rbs +23 -0
  74. data/sig/generated/riffer/wire.rbs +17 -0
  75. data/sig/generated/riffer.rbs +12 -0
  76. data/sig/manual/riffer/providers/anthropic_compatible/messages_api.rbs +8 -0
  77. data/sig/manual/riffer/providers/gemini.rbs +8 -0
  78. data/sig/manual/riffer/providers/google_cloud.rbs +8 -0
  79. data/sig/manual/riffer/wire.rbs +5 -0
  80. metadata +61 -5
  81. data/sig/_private/anthropic.rbs +0 -17
  82. data/sig/_private/riffer/providers/anthropic.rbs +0 -6
  83. data/sig/_private/riffer/providers/gemini.rbs +0 -7
@@ -4,15 +4,17 @@ Providers are adapters that connect Riffer to LLM services. They implement a com
4
4
 
5
5
  ## Available Providers
6
6
 
7
- | Provider | Identifier | Gem Required |
8
- | -------------- | ---------------- | ------------------------ |
9
- | OpenAI | `openai` | `openai` |
10
- | Azure OpenAI | `azure_openai` | `openai` |
11
- | Amazon Bedrock | `amazon_bedrock` | `aws-sdk-bedrockruntime` |
12
- | Anthropic | `anthropic` | `anthropic` |
13
- | Gemini | `gemini` | None |
14
- | OpenRouter | `openrouter` | `openai` |
15
- | Mock | `mock` | None |
7
+ | Provider | Identifier | Gem Required |
8
+ | --------------------- | ------------------ | ------------------------ |
9
+ | OpenAI | `openai` | `openai` |
10
+ | Azure OpenAI | `azure_openai` | `openai` |
11
+ | Amazon Bedrock | `amazon_bedrock` | `aws-sdk-bedrockruntime` |
12
+ | Anthropic | `anthropic` | None |
13
+ | Gemini | `gemini` | None |
14
+ | Google Cloud (Gemini) | `google_cloud` | `googleauth` |
15
+ | Google Cloud (Claude) | `anthropic_vertex` | `googleauth` |
16
+ | OpenRouter | `openrouter` | `openai` |
17
+ | Mock | `mock` | None |
16
18
 
17
19
  ## Model String Format
18
20
 
@@ -24,7 +26,9 @@ class MyAgent < Riffer::Agent
24
26
  model 'azure_openai/gpt-5-mini' # Azure OpenAI
25
27
  model 'amazon_bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0' # Bedrock
26
28
  model 'anthropic/claude-haiku-4-5-20251001' # Anthropic
27
- model 'gemini/gemini-2.5-flash-lite' # Gemini
29
+ model 'gemini/gemini-3.5-flash-lite' # Gemini
30
+ model 'google_cloud/gemini-3.5-flash-lite' # Google Cloud (Gemini)
31
+ model 'anthropic_vertex/claude-haiku-5-5' # Google Cloud (Claude)
28
32
  model 'openrouter/anthropic/claude-sonnet-4.6' # OpenRouter
29
33
  model 'mock/any' # Mock provider
30
34
  end
@@ -34,14 +38,15 @@ end
34
38
 
35
39
  Every credential comes from configuration: `Riffer::Providers::OpenAI.new` takes no arguments.
36
40
 
37
- | Provider | Configured credentials |
38
- | -------------- | ----------------------------------------------------------------- |
39
- | OpenAI | `config.openai.api_key`, `config.openai.base_url` |
40
- | Azure OpenAI | `config.azure_openai.api_key`, `config.azure_openai.endpoint` |
41
- | Anthropic | `config.anthropic.api_key` |
42
- | Amazon Bedrock | `config.amazon_bedrock.api_token`, `config.amazon_bedrock.region` |
43
- | Gemini | `config.gemini.api_key` |
44
- | OpenRouter | `config.openrouter.api_key` |
41
+ | Provider | Configured credentials |
42
+ | ------------------------------ | ----------------------------------------------------------------- |
43
+ | OpenAI | `config.openai.api_key`, `config.openai.base_url` |
44
+ | Azure OpenAI | `config.azure_openai.api_key`, `config.azure_openai.endpoint` |
45
+ | Anthropic | `config.anthropic.api_key`, `config.anthropic.base_url` |
46
+ | Amazon Bedrock | `config.amazon_bedrock.api_token`, `config.amazon_bedrock.region` |
47
+ | Gemini | `config.gemini.api_key`, `config.gemini.base_url` |
48
+ | Google Cloud (Gemini, Claude) | `config.google_cloud.project_id`, `.location`, `.credentials` |
49
+ | OpenRouter | `config.openrouter.api_key` |
45
50
 
46
51
  Out of the box, each provider builds an SDK client from these credentials. Everything else — timeouts, retries, proxies, custom auth — is configured by assigning your own client (an instance, or a `Proc` resolved on every LLM call) to `Riffer.config.<provider>.client`. See [Configuration → Provider Clients](../CONFIGURATION.md#provider-clients).
47
52
 
@@ -182,6 +187,12 @@ Riffer::Providers::Repository.find(:anthropic)
182
187
  Riffer::Providers::Repository.find(:gemini)
183
188
  # => Riffer::Providers::Gemini
184
189
 
190
+ Riffer::Providers::Repository.find(:google_cloud)
191
+ # => Riffer::Providers::GoogleCloud
192
+
193
+ Riffer::Providers::Repository.find(:anthropic_vertex)
194
+ # => Riffer::Providers::AnthropicVertex
195
+
185
196
  Riffer::Providers::Repository.find(:openrouter)
186
197
  # => Riffer::Providers::OpenRouter
187
198
 
@@ -198,4 +209,5 @@ Riffer::Providers::Repository.find(:mock)
198
209
  - [Mock](MOCK_PROVIDER.md) - Mock provider for testing
199
210
  - [Custom Providers](CUSTOM_PROVIDERS.md) - Creating your own provider
200
211
  - [Gemini](GEMINI.md) - Gemini models via Google GenAI API
212
+ - [Google Cloud](GOOGLE_CLOUD.md) - Gemini and Claude models on Agent Platform (formerly Vertex AI)
201
213
  - [OpenRouter](OPENROUTER.md) - Unified gateway across many vendors
@@ -91,6 +91,9 @@ groups:
91
91
  - source: providers/GEMINI.md
92
92
  slug: providers/gemini
93
93
  description: Google Gemini models
94
+ - source: providers/GOOGLE_CLOUD.md
95
+ slug: providers/google-cloud
96
+ description: Gemini and Claude on Agent Platform
94
97
  - source: providers/OPENROUTER.md
95
98
  slug: providers/openrouter
96
99
  description: Hundreds of models, one API
@@ -58,7 +58,12 @@ class Riffer::Agent::StructuredOutput
58
58
  #: (Hash[Symbol, untyped]) -> untyped
59
59
  def placeholder(schema)
60
60
  return schema[:enum].join(" | ") if schema[:enum]
61
- return placeholder(schema[:anyOf].first) if schema[:anyOf]
61
+
62
+ if schema[:anyOf]
63
+ examples = schema[:anyOf].map { |branch| placeholder(branch) }
64
+ # Showing one primitive branch would steer the model to that type only.
65
+ return examples.all?(String) ? examples.join(" | ") : examples.first
66
+ end
62
67
 
63
68
  case schema[:type]
64
69
  when "object" then (schema[:properties] || {}).transform_values { |property| placeholder(property) }
@@ -4,12 +4,15 @@
4
4
  class Riffer::Config::Anthropic
5
5
  attr_reader :api_key #: String? # @dynamic api_key
6
6
 
7
+ attr_reader :base_url #: String? # @dynamic base_url
8
+
7
9
  attr_accessor :client #: untyped # @dynamic client, client=
8
10
 
9
11
  #--
10
12
  #: () -> void
11
13
  def initialize
12
14
  @api_key = nil
15
+ @base_url = nil
13
16
  @client = nil
14
17
  end
15
18
 
@@ -18,4 +21,10 @@ class Riffer::Config::Anthropic
18
21
  def api_key=(value)
19
22
  @api_key = Riffer::Helpers::Validate.optional_string(value, attribute: "api_key")
20
23
  end
24
+
25
+ #--
26
+ #: (untyped) -> void
27
+ def base_url=(value)
28
+ @base_url = Riffer::Helpers::Validate.optional_string(value, attribute: "base_url")
29
+ end
21
30
  end
@@ -4,12 +4,15 @@
4
4
  class Riffer::Config::Gemini
5
5
  attr_reader :api_key #: String? # @dynamic api_key
6
6
 
7
+ attr_reader :base_url #: String? # @dynamic base_url
8
+
7
9
  attr_accessor :client #: untyped # @dynamic client, client=
8
10
 
9
11
  #--
10
12
  #: () -> void
11
13
  def initialize
12
14
  @api_key = nil
15
+ @base_url = nil
13
16
  @client = nil
14
17
  end
15
18
 
@@ -18,4 +21,10 @@ class Riffer::Config::Gemini
18
21
  def api_key=(value)
19
22
  @api_key = Riffer::Helpers::Validate.optional_string(value, attribute: "api_key")
20
23
  end
24
+
25
+ #--
26
+ #: (untyped) -> void
27
+ def base_url=(value)
28
+ @base_url = Riffer::Helpers::Validate.optional_string(value, attribute: "base_url")
29
+ end
21
30
  end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ class Riffer::Config::GoogleCloud
5
+ attr_reader :project_id #: String? # @dynamic project_id
6
+
7
+ # The default +"global"+ endpoint routes requests to any region, so it
8
+ # carries no data-residency guarantee.
9
+ attr_reader :location #: String # @dynamic location
10
+
11
+ # A googleauth credentials object; +nil+ resolves Application Default
12
+ # Credentials.
13
+ attr_accessor :credentials #: untyped # @dynamic credentials, credentials=
14
+
15
+ attr_accessor :client #: untyped # @dynamic client, client=
16
+
17
+ #--
18
+ #: () -> void
19
+ def initialize
20
+ @project_id = nil
21
+ @location = "global"
22
+ @credentials = nil
23
+ @client = nil
24
+ end
25
+
26
+ #--
27
+ #: (untyped) -> void
28
+ def project_id=(value)
29
+ @project_id = Riffer::Helpers::Validate.optional_string(value, attribute: "project_id")
30
+ end
31
+
32
+ # +nil+ restores the +"global"+ default.
33
+ #--
34
+ #: (untyped) -> void
35
+ def location=(value)
36
+ @location = Riffer::Helpers::Validate.optional_string(value, attribute: "location") || "global"
37
+ end
38
+ end
data/lib/riffer/config.rb CHANGED
@@ -14,6 +14,8 @@ class Riffer::Config
14
14
 
15
15
  attr_reader :gemini #: Riffer::Config::Gemini # @dynamic gemini
16
16
 
17
+ attr_reader :google_cloud #: Riffer::Config::GoogleCloud # @dynamic google_cloud
18
+
17
19
  attr_reader :openai #: Riffer::Config::OpenAI # @dynamic openai
18
20
 
19
21
  attr_reader :openrouter #: Riffer::Config::OpenRouter # @dynamic openrouter
@@ -91,6 +93,7 @@ class Riffer::Config
91
93
  @anthropic = Anthropic.new
92
94
  @azure_openai = AzureOpenAI.new
93
95
  @gemini = Gemini.new
96
+ @google_cloud = GoogleCloud.new
94
97
  @openai = OpenAI.new
95
98
  @openrouter = OpenRouter.new
96
99
  @evals = Evals.new
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "faraday"
5
+ require "json"
6
+
7
+ class Riffer::HTTP::Client
8
+ # @rbs @connection: Faraday::Connection
9
+ # @rbs @extra_headers: Hash[String, String]
10
+
11
+ DEFAULT_OPEN_TIMEOUT = 10 #: Integer
12
+ DEFAULT_READ_TIMEOUT = 600 #: Integer
13
+
14
+ # +headers+ are sent on every request and win over the subclass's auth and
15
+ # version headers, as do headers set on the +connection+.
16
+ #--
17
+ #: (?headers: Hash[String, String], ?connection: Faraday::Connection?) -> void
18
+ def initialize(headers: {}, connection: nil)
19
+ @extra_headers = headers
20
+ @connection = connection || Faraday.new(
21
+ request: { open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT },
22
+ )
23
+ end
24
+
25
+ # Raises Riffer::APIError on a non-success status.
26
+ #--
27
+ #: (String, Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
28
+ def post(path, body)
29
+ response = request(path, body)
30
+ raise_api_error!(response.status, response.body) unless response.success?
31
+ JSON.parse(response.body, symbolize_names: true)
32
+ end
33
+
34
+ # Raises Riffer::APIError on a non-success status; the error body is never yielded.
35
+ #--
36
+ #: (String, Hash[Symbol, untyped]) { (String) -> void } -> void
37
+ def post_stream(path, body, &)
38
+ streamed = false
39
+ yielded = false
40
+ held = +""
41
+
42
+ # A proc, not a lambda: httpx and typhoeus pass no env. Without one the
43
+ # status is unknown until the response returns, so every chunk is held.
44
+ on_data = proc do |chunk, bytes_received, env|
45
+ streamed = true
46
+ # Faraday restarts bytes_received on each attempt. httpx passes the chunk
47
+ # size instead, so attempts are only told apart when there is an env.
48
+ if env && bytes_received == chunk.bytesize
49
+ if yielded
50
+ raise Riffer::Error, "the stream restarted after data was delivered; " \
51
+ "retry middleware must not retry streaming requests mid-body"
52
+ end
53
+ held.clear
54
+ end
55
+
56
+ if env&.success?
57
+ unless chunk.empty?
58
+ yielded = true
59
+ yield(chunk)
60
+ end
61
+ else
62
+ held << chunk
63
+ end
64
+ end
65
+
66
+ response = request(path, body, on_data: on_data)
67
+ unyielded = streamed ? held : response.body
68
+ raise_api_error!(response.status, unyielded) unless response.success?
69
+ yield(unyielded) unless unyielded.empty?
70
+ end
71
+
72
+ private
73
+
74
+ #--
75
+ #: (String) -> String
76
+ def url_for(path)
77
+ raise NotImplementedError, "Subclasses must implement #url_for"
78
+ end
79
+
80
+ # Called per request so short-lived credentials can refresh.
81
+ #--
82
+ #: () -> Hash[String, String]
83
+ def headers
84
+ raise NotImplementedError, "Subclasses must implement #headers"
85
+ end
86
+
87
+ #--
88
+ #: () -> String
89
+ def error_label
90
+ raise NotImplementedError, "Subclasses must implement #error_label"
91
+ end
92
+
93
+ #--
94
+ #: (Hash[Symbol, untyped], String) -> String
95
+ def error_message(parsed, raw)
96
+ error = parsed[:error]
97
+ case error
98
+ when Hash then error[:message] || parsed[:message] || raw
99
+ when String then error
100
+ else parsed[:message] || raw
101
+ end
102
+ end
103
+
104
+ # Headers go on the request, never on the connection, which may be shared
105
+ # across fibers and keeps whatever headers the caller configured on it.
106
+ # Faraday matches header names case-insensitively, so a caller's header
107
+ # replaces the subclass's whatever its casing. The content and encoding
108
+ # headers below are always riffer's: the body and the stream depend on them.
109
+ #--
110
+ #: (String, Hash[Symbol, untyped], ?on_data: Proc?) -> Faraday::Response
111
+ def request(path, body, on_data: nil)
112
+ @connection.post(url_for(path)) do |req|
113
+ req.headers.update(@extra_headers)
114
+ headers.each { |name, value| req.headers[name] ||= value }
115
+ req.headers["content-type"] = "application/json"
116
+ if on_data
117
+ req.headers["accept"] = "text/event-stream"
118
+ # Net::HTTP buffers a gzip body until EOF, which stalls the stream.
119
+ req.headers["accept-encoding"] = "identity"
120
+ req.options.on_data = on_data
121
+ end
122
+ req.body = body.to_json
123
+ end
124
+ end
125
+
126
+ #--
127
+ #: (Integer, String) -> bot
128
+ def raise_api_error!(status, raw)
129
+ parsed = begin
130
+ JSON.parse(raw, symbolize_names: true)
131
+ rescue JSON::ParserError
132
+ nil
133
+ end
134
+ # Vertex AI wraps its error object in a one-element array.
135
+ parsed = parsed.first if parsed.is_a?(Array) && parsed.length == 1
136
+ fields = parsed.is_a?(Hash) ? parsed : {} #: Hash[Symbol, untyped]
137
+
138
+ message = "#{error_label} API error (#{status}): #{error_message(fields, raw)}"
139
+ raise Riffer::APIError.new(message, status: status, body: raw)
140
+ end
141
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module Riffer::HTTP
5
+ end
@@ -8,7 +8,6 @@ class Riffer::Mcp::Client
8
8
  #: (endpoint: String, ?headers: (Hash[String, String] | Proc), ?client: untyped?) -> void
9
9
  def initialize(endpoint:, headers: {}, client: nil)
10
10
  depends_on "mcp"
11
- depends_on "faraday"
12
11
 
13
12
  @client = client || begin
14
13
  resolved_headers = Riffer::Helpers::CallOrValue.resolve(headers)
@@ -2,21 +2,49 @@
2
2
  # rbs_inline: enabled
3
3
 
4
4
  class Riffer::Params::AnyOf
5
- attr_reader :variants #: Array[Riffer::Params] # @dynamic variants
5
+ # @rbs @name: Symbol
6
+
7
+ attr_reader :variants #: Array[Riffer::Params | Riffer::Params::Param] # @dynamic variants
6
8
 
7
9
  #--
8
- #: () -> void
9
- def initialize
10
+ #: (Symbol) -> void
11
+ def initialize(name)
12
+ @name = name
10
13
  @variants = []
11
14
  end
12
15
 
13
16
  #--
14
- #: () ?{ (Riffer::Params) [self: Riffer::Params] -> void } -> void
15
- def variant(&block)
16
- raise Riffer::ArgumentError, "variant requires a block defining its properties" unless block
17
+ #: (?Module?, ?description: String?, ?enum: Array[untyped]?, ?format: String?) ?{ (Riffer::Params) [self: Riffer::Params] -> void } -> void
18
+ def variant(type = nil, description: nil, enum: nil, format: nil, &block)
19
+ if type
20
+ raise Riffer::ArgumentError, "variant takes a type or a block, not both" if block
21
+
22
+ @variants << primitive(type, description, enum, format)
23
+ elsif block
24
+ if description || enum || format
25
+ raise Riffer::ArgumentError, "description:, enum: and format: only apply to a primitive variant"
26
+ end
27
+
28
+ params = Riffer::Params.new
29
+ params.instance_eval(&block)
30
+ @variants << params
31
+ else
32
+ raise Riffer::ArgumentError, "variant requires a type or a block defining its properties"
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ #--
39
+ #: (Module, String?, Array[untyped]?, String?) -> Riffer::Params::Param
40
+ def primitive(type, description, enum, format)
41
+ unless Riffer::Params::Param::PRIMITIVE_TYPES.include?(type)
42
+ primitives = Riffer::Params::Param::PRIMITIVE_TYPES.map(&:name).join(", ")
43
+ raise Riffer::ArgumentError, "variant type must be a primitive type (#{primitives}), got #{type}"
44
+ end
17
45
 
18
- params = Riffer::Params.new
19
- params.instance_eval(&block)
20
- @variants << params
46
+ Riffer::Params::Param.new(
47
+ name: @name, type: type, required: true, description: description, enum: enum, format: format,
48
+ )
21
49
  end
22
50
  end
@@ -46,12 +46,12 @@ class Riffer::Params::Param
46
46
 
47
47
  attr_reader :nested_params #: Riffer::Params? # @dynamic nested_params
48
48
 
49
- attr_reader :variants #: Array[Riffer::Params]? # @dynamic variants
49
+ attr_reader :variants #: Array[Riffer::Params | Riffer::Params::Param]? # @dynamic variants
50
50
 
51
51
  #--
52
52
  #: (Symbol, Hash[Symbol, untyped], required: bool) -> Riffer::Params::Param
53
53
  def self.from_json_schema(name, schema, required:)
54
- variants = resolve_variants(schema[:anyOf]) if schema.key?(:anyOf)
54
+ variants = resolve_variants(name, schema[:anyOf]) if schema.key?(:anyOf)
55
55
  ruby_type = variants ? Riffer::Params::AnyOf : json_type_to_ruby(schema[:type])
56
56
  nested = resolve_nested_params(ruby_type, schema)
57
57
  item_type, dimensions, items = resolve_typed_items(schema) if ruby_type == Array && !nested
@@ -72,15 +72,19 @@ class Riffer::Params::Param
72
72
  end
73
73
 
74
74
  #--
75
- #: (Array[Hash[Symbol, untyped]]) -> Array[Riffer::Params]
76
- def self.resolve_variants(branches)
75
+ #: (Symbol, Array[Hash[Symbol, untyped]]) -> Array[Riffer::Params | Riffer::Params::Param]
76
+ def self.resolve_variants(name, branches)
77
77
  # Strict schemas add a null branch to optional fields; nullability comes from +required+.
78
78
  variants = branches.reject { |branch| branch[:type] == "null" }.map do |branch|
79
- raise Riffer::ArgumentError, "Unsupported anyOf branch: #{branch.to_json}" unless branch[:type] == "object"
80
-
81
- Riffer::Params.from_json_schema(branch)
79
+ if branch[:type] == "object"
80
+ Riffer::Params.from_json_schema(branch)
81
+ elsif PRIMITIVE_TYPES.include?(JSON_TYPE_MAPPINGS[branch[:type]]) && !branch.key?(:anyOf)
82
+ from_json_schema(name, branch, required: true)
83
+ else
84
+ raise Riffer::ArgumentError, "Unsupported anyOf branch: #{branch.to_json}"
85
+ end
82
86
  end
83
- raise Riffer::ArgumentError, "anyOf requires at least two object branches" if variants.size < 2
87
+ raise Riffer::ArgumentError, "anyOf requires at least two branches" if variants.size < 2
84
88
 
85
89
  variants
86
90
  end
@@ -133,13 +137,14 @@ class Riffer::Params::Param
133
137
  #--
134
138
  #: (untyped) -> Module
135
139
  def self.json_type_to_ruby(type)
136
- key = type.is_a?(Array) ? type.find { |t| t != "null" } : type
137
- JSON_TYPE_MAPPINGS.fetch(key) { raise Riffer::ArgumentError, "Unsupported JSON Schema type: #{type.inspect}" }
140
+ types = Array(type) - ["null"]
141
+ ruby_type = JSON_TYPE_MAPPINGS[types.first] if types.one?
142
+ ruby_type || raise(Riffer::ArgumentError, "Unsupported JSON Schema type: #{type.inspect}")
138
143
  end
139
144
  private_class_method :json_type_to_ruby
140
145
 
141
146
  #--
142
- #: (name: Symbol, type: Module, required: bool, ?description: String?, ?enum: Array[untyped]?, ?format: String?, ?default: untyped, ?item_type: Module?, ?dimensions: Integer, ?nested_params: Riffer::Params?, ?variants: Array[Riffer::Params]?) -> void
147
+ #: (name: Symbol, type: Module, required: bool, ?description: String?, ?enum: Array[untyped]?, ?format: String?, ?default: untyped, ?item_type: Module?, ?dimensions: Integer, ?nested_params: Riffer::Params?, ?variants: Array[Riffer::Params | Riffer::Params::Param]?) -> void
143
148
  def initialize(name:, type:, required:, description: nil, enum: nil, format: nil, default: nil, item_type: nil,
144
149
  dimensions: 1, nested_params: nil, variants: nil)
145
150
  if type == Riffer::Params::AnyOf && variants.nil?
@@ -158,8 +163,9 @@ class Riffer::Params::Param
158
163
  @dimensions = dimensions
159
164
  @nested_params = nested_params
160
165
  @variants = variants
161
- # Checked here rather than in Params so from_json_schema enforces it too.
166
+ # Checked here rather than in Params so from_json_schema enforces them too.
162
167
  validate_format! if format
168
+ validate_variant_order! if variants
163
169
  end
164
170
 
165
171
  #--
@@ -172,7 +178,7 @@ class Riffer::Params::Param
172
178
  elsif type == Float
173
179
  value.is_a?(Numeric)
174
180
  elsif type == Riffer::Params::AnyOf
175
- value.is_a?(Hash)
181
+ Array(variants).any? { |variant| variant.is_a?(Riffer::Params) ? value.is_a?(Hash) : variant.valid_type?(value) }
176
182
  else
177
183
  value.is_a?(type)
178
184
  end
@@ -181,7 +187,10 @@ class Riffer::Params::Param
181
187
  #--
182
188
  #: () -> String
183
189
  def type_name
184
- return "object" if type == Riffer::Params::AnyOf
190
+ if type == Riffer::Params::AnyOf
191
+ names = Array(variants).map { |variant| variant.is_a?(Riffer::Params) ? "object" : variant.type_name }
192
+ return names.uniq.join(" or ")
193
+ end
185
194
 
186
195
  TYPE_MAPPINGS[type] || type.to_s.downcase
187
196
  end
@@ -253,6 +262,18 @@ class Riffer::Params::Param
253
262
  @default = Riffer::Helpers::DeepDup.call(source.default)
254
263
  end
255
264
 
265
+ # The first matching variant wins, and a Float variant without an enum accepts any number.
266
+ #--
267
+ #: () -> void
268
+ def validate_variant_order!
269
+ primitives = Array(variants).grep(Riffer::Params::Param) #: Array[Riffer::Params::Param]
270
+ float = primitives.index { |variant| variant.type == Float && variant.enum.nil? }
271
+ integer = primitives.rindex { |variant| variant.type == Integer }
272
+ return unless float && integer && float < integer
273
+
274
+ raise Riffer::ArgumentError, "#{name}: an Integer variant after a Float variant without enum: can never match"
275
+ end
276
+
256
277
  #--
257
278
  #: () -> void
258
279
  def validate_format!
data/lib/riffer/params.rb CHANGED
@@ -34,7 +34,7 @@ class Riffer::Params
34
34
  def required(name, type, description: nil, enum: nil, format: nil, of: nil, &)
35
35
  item_type, dimensions = unwrap_of(of)
36
36
  nested = build_nested(type, item_type, enum, &) unless type == Riffer::Params::AnyOf
37
- variants = build_variants(of, enum, &) if type == Riffer::Params::AnyOf
37
+ variants = build_variants(name, of, enum, &) if type == Riffer::Params::AnyOf
38
38
  @parameters << Riffer::Params::Param.new(
39
39
  name: name,
40
40
  type: type,
@@ -55,7 +55,7 @@ class Riffer::Params
55
55
  def optional(name, type, description: nil, enum: nil, format: nil, default: nil, of: nil, &)
56
56
  item_type, dimensions = unwrap_of(of)
57
57
  nested = build_nested(type, item_type, enum, &) unless type == Riffer::Params::AnyOf
58
- variants = build_variants(of, enum, &) if type == Riffer::Params::AnyOf
58
+ variants = build_variants(name, of, enum, &) if type == Riffer::Params::AnyOf
59
59
  @parameters << Riffer::Params::Param.new(
60
60
  name: name,
61
61
  type: type,
@@ -90,19 +90,8 @@ class Riffer::Params
90
90
  next
91
91
  end
92
92
 
93
- unless param.valid_type?(value)
94
- errors << "#{param.name} must be a #{param.type_name}"
95
- next
96
- end
97
-
98
- # A typed array's enum and format constrain its items, which validate_typed_array checks.
99
- if param.enum && !param.item_type && !param.enum.include?(value)
100
- errors << "#{param.name} must be one of: #{param.enum.join(', ')}"
101
- next
102
- end
103
-
104
- if param.format && !param.item_type && !Riffer::Params::Format.valid?(param.format, value)
105
- errors << "#{param.name} must be a valid #{param.format}"
93
+ if (error = value_error(param, value))
94
+ errors << "#{param.name} #{error}"
106
95
  next
107
96
  end
108
97
 
@@ -185,19 +174,32 @@ class Riffer::Params
185
174
  end
186
175
 
187
176
  #--
188
- #: ((Module | Array[untyped])?, Array[untyped]?) ?{ (Riffer::Params::AnyOf) [self: Riffer::Params::AnyOf] -> void } -> Array[Riffer::Params]
189
- def build_variants(of, enum, &block)
177
+ #: (Symbol, (Module | Array[untyped])?, Array[untyped]?) ?{ (Riffer::Params::AnyOf) [self: Riffer::Params::AnyOf] -> void } -> Array[Riffer::Params | Riffer::Params::Param]
178
+ def build_variants(name, of, enum, &block)
190
179
  raise Riffer::ArgumentError, "of: cannot be used with AnyOf" if of
191
180
  raise Riffer::ArgumentError, "enum: cannot be used with AnyOf" if enum
192
181
  raise Riffer::ArgumentError, "AnyOf requires a block defining its variants" unless block
193
182
 
194
- any_of = Riffer::Params::AnyOf.new
183
+ any_of = Riffer::Params::AnyOf.new(name)
195
184
  any_of.instance_eval(&block)
196
185
  raise Riffer::ArgumentError, "AnyOf requires at least two variants" if any_of.variants.size < 2
197
186
 
198
187
  any_of.variants
199
188
  end
200
189
 
190
+ #--
191
+ #: (Riffer::Params::Param, untyped) -> String?
192
+ def value_error(param, value)
193
+ return "must be a #{param.type_name}" unless param.valid_type?(value)
194
+
195
+ # A typed array's enum and format constrain its items, which validate_typed_array checks.
196
+ return "must be one of: #{param.enum.join(', ')}" if param.enum && !param.item_type && !param.enum.include?(value)
197
+
198
+ return unless param.format && !param.item_type && !Riffer::Params::Format.valid?(param.format, value)
199
+
200
+ "must be a valid #{param.format}"
201
+ end
202
+
201
203
  #--
202
204
  #: (Riffer::Params::Param, untyped, Array[String]) -> untyped
203
205
  def validate_nested(param, value, errors)
@@ -229,13 +231,26 @@ class Riffer::Params
229
231
  end
230
232
 
231
233
  #--
232
- #: (Riffer::Params::Param, Hash[Symbol, untyped], Array[String]) -> Hash[Symbol, untyped]
234
+ #: (Riffer::Params::Param, untyped, Array[String]) -> untyped
233
235
  def validate_any_of(param, value, errors)
234
236
  variants = param.variants
235
237
  return value unless variants
236
238
 
237
239
  variant_errors = [] #: Array[String]
238
240
  variants.each.with_index(1) do |variant, number|
241
+ if variant.is_a?(Riffer::Params::Param)
242
+ error = value_error(variant, value)
243
+ return coerce_value(variant.type, value) unless error
244
+
245
+ variant_errors << "variant #{number} (#{error})"
246
+ next
247
+ end
248
+
249
+ unless value.is_a?(Hash)
250
+ variant_errors << "variant #{number} (must be a object)"
251
+ next
252
+ end
253
+
239
254
  validated = variant.validate(value)
240
255
  # Each variant's schema sets additionalProperties: false on every object
241
256
  # it declares, so a key outside this variant rules it out.