rapitapir 0.1.2 → 2.1.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +7 -7
  3. data/.rubocop_todo.yml +88 -0
  4. data/CHANGELOG.md +29 -1
  5. data/README.md +1339 -236
  6. data/RUBY_WEEKLY_LAUNCH_POST.md +200 -0
  7. data/docs/RAILS_INTEGRATION_IMPLEMENTATION.md +209 -0
  8. data/docs/SINATRA_EXTENSION.md +399 -348
  9. data/docs/STRICT_VALIDATION.md +229 -0
  10. data/docs/VALIDATION_IMPROVEMENTS.md +218 -0
  11. data/docs/adr/0001-base-class-strategy.md +33 -0
  12. data/docs/adr/0002-type-shortcut-and-type-system.md +30 -0
  13. data/docs/adr/0003-openapi-source-of-truth.md +32 -0
  14. data/docs/adr/0004-client-generation-typescript-first.md +34 -0
  15. data/docs/adr/0005-auth-architecture.md +32 -0
  16. data/docs/adr/0006-observability-defaults.md +30 -0
  17. data/docs/adr/0007-ai-scope-and-boundaries.md +30 -0
  18. data/docs/adr/README.md +46 -0
  19. data/docs/adr/template.md +24 -0
  20. data/docs/ai-integration-plan.md +112 -0
  21. data/docs/auto-derivation.md +505 -92
  22. data/docs/blueprint.md +92 -4
  23. data/docs/endpoint-definition.md +536 -129
  24. data/docs/implementation-status.md +1 -1
  25. data/docs/n8n-integration.md +212 -0
  26. data/docs/observability.md +810 -500
  27. data/docs/using-mcp.md +93 -0
  28. data/examples/ai/knowledge_base_rag.rb +83 -0
  29. data/examples/ai/user_management_mcp.rb +92 -0
  30. data/examples/ai/user_validation_llm.rb +187 -0
  31. data/examples/auto_derivation_ruby_friendly.rb +44 -113
  32. data/examples/cli/user_api_endpoints.rb +63 -36
  33. data/examples/demo_api.rb +57 -18
  34. data/examples/enterprise_extension_demo.rb +13 -13
  35. data/examples/enterprise_rapitapir_api.rb +81 -93
  36. data/examples/nocodb/nocodb_scaffold/Gemfile +22 -0
  37. data/examples/nocodb/nocodb_scaffold/README.md +10 -0
  38. data/examples/nocodb/nocodb_scaffold/Rakefile +7 -0
  39. data/examples/nocodb/nocodb_scaffold/app/api/app.rb +1139 -0
  40. data/examples/nocodb/nocodb_scaffold/app/models/email_template.rb +6 -0
  41. data/examples/nocodb/nocodb_scaffold/app/models/faq.rb +6 -0
  42. data/examples/nocodb/nocodb_scaffold/app/models/feature.rb +6 -0
  43. data/examples/nocodb/nocodb_scaffold/app/models/idea.rb +6 -0
  44. data/examples/nocodb/nocodb_scaffold/app/models/itinerary_day.rb +6 -0
  45. data/examples/nocodb/nocodb_scaffold/app/models/route.rb +6 -0
  46. data/examples/nocodb/nocodb_scaffold/app/models/subscriber.rb +6 -0
  47. data/examples/nocodb/nocodb_scaffold/app/models/tour.rb +6 -0
  48. data/examples/nocodb/nocodb_scaffold/app/models/webhook.rb +6 -0
  49. data/examples/nocodb/nocodb_scaffold/app/models_loader.rb +3 -0
  50. data/examples/nocodb/nocodb_scaffold/config/database.yml +11 -0
  51. data/examples/nocodb/nocodb_scaffold/config.ru +9 -0
  52. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152012_create_features.rb +10 -0
  53. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152013_create_tours.rb +10 -0
  54. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152014_create_routes.rb +10 -0
  55. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152015_create_itinerary_days.rb +10 -0
  56. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152016_create_subscribers.rb +10 -0
  57. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152017_create_email_templates.rb +10 -0
  58. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152018_create_faqs.rb +10 -0
  59. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152019_create_webhooks.rb +10 -0
  60. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152020_create_ideas.rb +10 -0
  61. data/examples/nocodb/swagger.json +4378 -0
  62. data/examples/production_ready_example.rb +78 -58
  63. data/examples/rails/RAILS_8_GUIDE.md +165 -0
  64. data/examples/rails/RAILS_LOADING_FIX.rb +35 -0
  65. data/examples/rails/README.md +497 -0
  66. data/examples/rails/comprehensive_test.rb +91 -0
  67. data/examples/rails/config/routes.rb +48 -0
  68. data/examples/rails/debug_controller.rb +63 -0
  69. data/examples/rails/detailed_test.rb +46 -0
  70. data/examples/rails/enhanced_users_controller.rb +278 -0
  71. data/examples/rails/final_server_test.rb +50 -0
  72. data/examples/rails/hello_world_app.rb +116 -0
  73. data/examples/rails/hello_world_controller.rb +186 -0
  74. data/examples/rails/hello_world_routes.rb +28 -0
  75. data/examples/rails/rails8_minimal_demo.rb +132 -0
  76. data/examples/rails/rails8_simple_demo.rb +140 -0
  77. data/examples/rails/rails8_working_demo.rb +255 -0
  78. data/examples/rails/real_world_blog_api.rb +510 -0
  79. data/examples/rails/server_test.rb +46 -0
  80. data/examples/rails/test_direct_processing.rb +41 -0
  81. data/examples/rails/test_hello_world.rb +80 -0
  82. data/examples/rails/test_rails_integration.rb +54 -0
  83. data/examples/rails/traditional_app/Gemfile +37 -0
  84. data/examples/rails/traditional_app/README.md +265 -0
  85. data/examples/rails/traditional_app/app/controllers/api/v1/posts_controller.rb +254 -0
  86. data/examples/rails/traditional_app/app/controllers/api/v1/users_controller.rb +220 -0
  87. data/examples/rails/traditional_app/app/controllers/application_controller.rb +86 -0
  88. data/examples/rails/traditional_app/app/controllers/application_controller_simplified.rb +87 -0
  89. data/examples/rails/traditional_app/app/controllers/documentation_controller.rb +149 -0
  90. data/examples/rails/traditional_app/app/controllers/health_controller.rb +42 -0
  91. data/examples/rails/traditional_app/config/routes.rb +25 -0
  92. data/examples/rails/traditional_app/config/routes_best_practice.rb +25 -0
  93. data/examples/rails/traditional_app/config/routes_simplified.rb +36 -0
  94. data/examples/rails/traditional_app_runnable.rb +406 -0
  95. data/examples/rails/users_controller.rb +4 -1
  96. data/examples/serverless/Gemfile +43 -0
  97. data/examples/serverless/QUICKSTART.md +331 -0
  98. data/examples/serverless/README.md +520 -0
  99. data/examples/serverless/aws_lambda_example.rb +307 -0
  100. data/examples/serverless/aws_sam_template.yaml +215 -0
  101. data/examples/serverless/azure_functions_example.rb +407 -0
  102. data/examples/serverless/deploy.rb +204 -0
  103. data/examples/serverless/gcp_cloud_functions_example.rb +367 -0
  104. data/examples/serverless/gcp_function.yaml +23 -0
  105. data/examples/serverless/host.json +24 -0
  106. data/examples/serverless/package.json +32 -0
  107. data/examples/serverless/spec/aws_lambda_spec.rb +196 -0
  108. data/examples/serverless/spec/spec_helper.rb +89 -0
  109. data/examples/serverless/vercel.json +31 -0
  110. data/examples/serverless/vercel_example.rb +404 -0
  111. data/examples/simple_demo_api.rb +40 -7
  112. data/examples/strict_validation_examples.rb +104 -0
  113. data/examples/user_api.rb +130 -132
  114. data/examples/validation_error_examples.rb +173 -0
  115. data/lib/rapitapir/ai/llm_instruction.rb +456 -0
  116. data/lib/rapitapir/ai/mcp.rb +134 -0
  117. data/lib/rapitapir/ai/rag.rb +287 -0
  118. data/lib/rapitapir/ai/rag_middleware.rb +147 -0
  119. data/lib/rapitapir/auth/oauth2.rb +44 -58
  120. data/lib/rapitapir/cli/command.rb +392 -6
  121. data/lib/rapitapir/cli/mcp_export.rb +18 -0
  122. data/lib/rapitapir/cli/scaffold_generator.rb +639 -0
  123. data/lib/rapitapir/cli/validator.rb +3 -7
  124. data/lib/rapitapir/core/endpoint.rb +59 -6
  125. data/lib/rapitapir/core/enhanced_endpoint.rb +3 -7
  126. data/lib/rapitapir/dsl/enhanced_structures.rb +1 -1
  127. data/lib/rapitapir/dsl/fluent_endpoint_builder.rb +53 -0
  128. data/lib/rapitapir/endpoint_registry.rb +47 -0
  129. data/lib/rapitapir/observability/health_check.rb +4 -4
  130. data/lib/rapitapir/observability/logging.rb +10 -10
  131. data/lib/rapitapir/openapi/schema_generator.rb +46 -2
  132. data/lib/rapitapir/schema.rb +2 -2
  133. data/lib/rapitapir/server/enhanced_rack_adapter.rb +11 -8
  134. data/lib/rapitapir/server/middleware.rb +2 -2
  135. data/lib/rapitapir/server/rack_adapter.rb +1 -3
  136. data/lib/rapitapir/server/rails/configuration.rb +77 -0
  137. data/lib/rapitapir/server/rails/controller_base.rb +185 -0
  138. data/lib/rapitapir/server/rails/documentation_helpers.rb +76 -0
  139. data/lib/rapitapir/server/rails/resource_builder.rb +181 -0
  140. data/lib/rapitapir/server/rails/routes.rb +114 -0
  141. data/lib/rapitapir/server/rails_adapter.rb +10 -3
  142. data/lib/rapitapir/server/rails_adapter_class.rb +1 -3
  143. data/lib/rapitapir/server/rails_controller.rb +1 -3
  144. data/lib/rapitapir/server/rails_integration.rb +67 -0
  145. data/lib/rapitapir/server/rails_response_handler.rb +16 -3
  146. data/lib/rapitapir/server/sinatra_adapter.rb +29 -5
  147. data/lib/rapitapir/server/sinatra_integration.rb +4 -4
  148. data/lib/rapitapir/sinatra/extension.rb +2 -2
  149. data/lib/rapitapir/sinatra/oauth2_helpers.rb +34 -40
  150. data/lib/rapitapir/types/array.rb +4 -0
  151. data/lib/rapitapir/types/auto_derivation.rb +4 -20
  152. data/lib/rapitapir/types/datetime.rb +1 -3
  153. data/lib/rapitapir/types/float.rb +2 -6
  154. data/lib/rapitapir/types/hash.rb +40 -2
  155. data/lib/rapitapir/types/integer.rb +4 -12
  156. data/lib/rapitapir/types/object.rb +6 -2
  157. data/lib/rapitapir/types.rb +6 -2
  158. data/lib/rapitapir/version.rb +1 -1
  159. data/lib/rapitapir.rb +5 -3
  160. data/rapitapir.gemspec +3 -2
  161. metadata +142 -8
@@ -8,14 +8,27 @@ module RapiTapir
8
8
  private
9
9
 
10
10
  def render_rapitapir_response(result, endpoint)
11
+ # Extract custom status code if provided
12
+ status_code = 200
13
+ response_data = result
14
+
15
+ if result.is_a?(Hash) && result.key?(:_status)
16
+ status_code = result[:_status]
17
+ response_data = result.except(:_status)
18
+ elsif result.is_a?(Hash) && result.key?('_status')
19
+ status_code = result['_status']
20
+ response_data = result.except('_status')
21
+ else
22
+ status_code = determine_rails_status_code(endpoint)
23
+ end
24
+
11
25
  output = endpoint.outputs.find { |o| o.kind == :json } || endpoint.outputs.first
12
- status_code = determine_rails_status_code(endpoint)
13
26
 
14
27
  if output&.kind == :xml
15
- render xml: result, status: status_code
28
+ render xml: response_data, status: status_code
16
29
  else
17
30
  # Default to JSON for nil output, :json kind, or unknown kinds
18
- render json: result, status: status_code
31
+ render json: response_data, status: status_code
19
32
  end
20
33
  end
21
34
 
@@ -24,9 +24,7 @@ module RapiTapir
24
24
 
25
25
  # Register an endpoint with automatic Sinatra route creation
26
26
  def register_endpoint(endpoint, handler = nil, &block)
27
- unless endpoint.is_a?(RapiTapir::Core::Endpoint)
28
- raise ArgumentError, 'Endpoint must be a RapiTapir::Core::Endpoint'
29
- end
27
+ raise ArgumentError, 'Endpoint must be a RapiTapir::Core::Endpoint' unless endpoint.is_a?(RapiTapir::Core::Endpoint)
30
28
 
31
29
  endpoint.validate!
32
30
 
@@ -43,7 +41,6 @@ module RapiTapir
43
41
 
44
42
  private
45
43
 
46
- # rubocop:disable Metrics/AbcSize
47
44
  def register_sinatra_route(endpoint_info)
48
45
  method_name = endpoint_info[:endpoint].method.to_s.downcase.to_sym
49
46
  path_pattern = convert_path_to_sinatra(endpoint_info[:endpoint].path)
@@ -61,7 +58,6 @@ module RapiTapir
61
58
  end
62
59
  end
63
60
  end
64
- # rubocop:enable Metrics/AbcSize
65
61
 
66
62
  public
67
63
 
@@ -72,6 +68,18 @@ module RapiTapir
72
68
  processed_inputs = extract_sinatra_inputs(request, params, endpoint_data[:endpoint])
73
69
  result = @app.instance_exec(processed_inputs, &endpoint_data[:handler])
74
70
  send_successful_response(endpoint_data, result)
71
+ rescue RapiTapir::Types::CoercionError => e
72
+ detailed_error_response(400, 'Validation Error', e.reason, {
73
+ field: extract_field_from_error(e),
74
+ value: e.value,
75
+ expected_type: e.type
76
+ })
77
+ rescue RapiTapir::Types::ValidationError => e
78
+ detailed_error_response(400, 'Validation Error', e.message, {
79
+ errors: e.errors,
80
+ value: e.value,
81
+ expected_type: e.type.to_s
82
+ })
75
83
  rescue ArgumentError => e
76
84
  error_response(400, e.message)
77
85
  rescue StandardError => e
@@ -85,6 +93,22 @@ module RapiTapir
85
93
  [status_code, { 'Content-Type' => 'application/json' }, [error_data.to_json]]
86
94
  end
87
95
 
96
+ def detailed_error_response(status_code, error, message, details = {})
97
+ error_data = {
98
+ error: error,
99
+ message: message
100
+ }
101
+ error_data.merge!(details) if details.any?
102
+ [status_code, { 'Content-Type' => 'application/json' }, [error_data.to_json]]
103
+ end
104
+
105
+ def extract_field_from_error(error)
106
+ # Try to extract field name from error message
107
+ # Match both "Field 'field_name':" and "Required field 'field_name'"
108
+ match = error.reason.match(/(?:Field|Required field) '([^']+)'/)
109
+ match[1] if match
110
+ end
111
+
88
112
  def execute_endpoint_handler(endpoint_data, processed_inputs)
89
113
  case endpoint_data[:handler]
90
114
  when Proc
@@ -23,8 +23,8 @@ module RapiTapir
23
23
  end
24
24
 
25
25
  # Mount an endpoint in Sinatra
26
- def mount_endpoint(endpoint, &handler)
27
- rapitapir_adapter.mount(endpoint, &handler)
26
+ def mount_endpoint(endpoint, &)
27
+ rapitapir_adapter.mount(endpoint, &)
28
28
 
29
29
  # Register the route with Sinatra
30
30
  method_name = endpoint.method.to_s.downcase
@@ -42,8 +42,8 @@ module RapiTapir
42
42
  end
43
43
 
44
44
  # Register error handlers
45
- def rapitapir_error(error_class, &handler)
46
- rapitapir_adapter.on_error(error_class, &handler)
45
+ def rapitapir_error(error_class, &)
46
+ rapitapir_adapter.on_error(error_class, &)
47
47
  end
48
48
 
49
49
  # Generate OpenAPI spec for all mounted endpoints
@@ -29,9 +29,9 @@ module RapiTapir
29
29
  # Class methods added to the Sinatra application
30
30
  module ClassMethods
31
31
  # Configure RapiTapir integration
32
- def rapitapir(&block)
32
+ def rapitapir(&)
33
33
  config = settings.rapitapir_config
34
- config.instance_eval(&block) if block_given?
34
+ config.instance_eval(&) if block_given?
35
35
  setup_rapitapir_integration
36
36
  end
37
37
 
@@ -10,37 +10,37 @@ module RapiTapir
10
10
  # Configure Auth0 OAuth2 authentication
11
11
  def auth0_oauth2(scheme_name = :oauth2_auth0, domain:, audience:, **options)
12
12
  auth_scheme = RapiTapir::Auth::OAuth2::Auth0Scheme.new(scheme_name, {
13
- domain: domain,
14
- audience: audience,
15
- **options
16
- })
17
-
13
+ domain: domain,
14
+ audience: audience,
15
+ **options
16
+ })
17
+
18
18
  # Store the auth scheme for use in endpoint protection
19
19
  settings.rapitapir_config.add_auth_scheme(scheme_name, auth_scheme)
20
-
20
+
21
21
  # Add authentication helper methods
22
22
  helpers do
23
23
  include OAuth2HelperMethods
24
24
  end
25
-
25
+
26
26
  auth_scheme
27
27
  end
28
28
 
29
29
  # Configure generic OAuth2 authentication with token introspection
30
30
  def oauth2_introspection(scheme_name = :oauth2, introspection_endpoint:, client_id:, client_secret:, **options)
31
31
  auth_scheme = RapiTapir::Auth::OAuth2::GenericScheme.new(scheme_name, {
32
- introspection_endpoint: introspection_endpoint,
33
- client_id: client_id,
34
- client_secret: client_secret,
35
- **options
36
- })
37
-
32
+ introspection_endpoint: introspection_endpoint,
33
+ client_id: client_id,
34
+ client_secret: client_secret,
35
+ **options
36
+ })
37
+
38
38
  settings.rapitapir_config.add_auth_scheme(scheme_name, auth_scheme)
39
-
39
+
40
40
  helpers do
41
41
  include OAuth2HelperMethods
42
42
  end
43
-
43
+
44
44
  auth_scheme
45
45
  end
46
46
 
@@ -58,7 +58,7 @@ module RapiTapir
58
58
  before do
59
59
  # Skip protection for excluded paths
60
60
  next if except.any? { |pattern| request.path_info.match?(pattern) }
61
-
61
+
62
62
  authorize_oauth2!(required_scopes: scopes, scheme: scheme)
63
63
  end
64
64
  end
@@ -69,20 +69,18 @@ module RapiTapir
69
69
  # Authenticate and authorize with OAuth2
70
70
  def authorize_oauth2!(required_scopes: [], scheme: :oauth2_auth0)
71
71
  auth_scheme = settings.rapitapir_config.auth_schemes[scheme]
72
-
73
- unless auth_scheme
74
- halt 500, { error: 'OAuth2 authentication not configured' }.to_json
75
- end
72
+
73
+ halt 500, { error: 'OAuth2 authentication not configured' }.to_json unless auth_scheme
76
74
 
77
75
  begin
78
76
  context = auth_scheme.authenticate(request)
79
-
77
+
80
78
  unless context
81
79
  challenge = auth_scheme.challenge
82
80
  headers 'WWW-Authenticate' => challenge
83
- halt 401, {
81
+ halt 401, {
84
82
  error: 'unauthorized',
85
- error_description: 'Access token required'
83
+ error_description: 'Access token required'
86
84
  }.to_json
87
85
  end
88
86
 
@@ -92,7 +90,7 @@ module RapiTapir
92
90
  # Check required scopes if specified
93
91
  if required_scopes.any?
94
92
  missing_scopes = required_scopes - context.scopes
95
-
93
+
96
94
  if missing_scopes.any?
97
95
  halt 403, {
98
96
  error: 'insufficient_scope',
@@ -135,34 +133,34 @@ module RapiTapir
135
133
  # Check if user has specific scope
136
134
  def has_scope?(scope)
137
135
  return false unless current_auth_context
138
-
136
+
139
137
  current_auth_context.scopes.include?(scope.to_s)
140
138
  end
141
139
 
142
140
  # Check if user has all required scopes
143
141
  def has_scopes?(*scopes)
144
142
  return false unless current_auth_context
145
-
143
+
146
144
  scopes.all? { |scope| has_scope?(scope) }
147
145
  end
148
146
 
149
147
  # Check if user has any of the specified scopes
150
148
  def has_any_scope?(*scopes)
151
149
  return false unless current_auth_context
152
-
150
+
153
151
  scopes.any? { |scope| has_scope?(scope) }
154
152
  end
155
153
 
156
154
  # Require specific scopes for the current request
157
155
  def require_scopes!(*scopes)
158
156
  missing_scopes = scopes.reject { |scope| has_scope?(scope) }
159
-
160
- if missing_scopes.any?
161
- halt 403, {
162
- error: 'insufficient_scope',
163
- error_description: "Missing required scopes: #{missing_scopes.join(', ')}"
164
- }.to_json
165
- end
157
+
158
+ return unless missing_scopes.any?
159
+
160
+ halt 403, {
161
+ error: 'insufficient_scope',
162
+ error_description: "Missing required scopes: #{missing_scopes.join(', ')}"
163
+ }.to_json
166
164
  end
167
165
 
168
166
  # Extract token from Authorization header
@@ -226,11 +224,7 @@ module RapiTapir
226
224
  end
227
225
 
228
226
  # Extend the Sinatra extension with OAuth2 helpers if it exists
229
- if defined?(RapiTapir::Sinatra::Extension)
230
- RapiTapir::Sinatra::Extension::ClassMethods.include(RapiTapir::Sinatra::OAuth2Helpers)
231
- end
227
+ RapiTapir::Sinatra::Extension::ClassMethods.include(RapiTapir::Sinatra::OAuth2Helpers) if defined?(RapiTapir::Sinatra::Extension)
232
228
 
233
229
  # Extend endpoint building with OAuth2 methods
234
- if defined?(RapiTapir::DSL::FluentEndpointBuilder)
235
- RapiTapir::DSL::FluentEndpointBuilder.include(RapiTapir::Sinatra::OAuth2EndpointExtensions)
236
- end
230
+ RapiTapir::DSL::FluentEndpointBuilder.include(RapiTapir::Sinatra::OAuth2EndpointExtensions) if defined?(RapiTapir::DSL::FluentEndpointBuilder)
@@ -136,12 +136,16 @@ module RapiTapir
136
136
  schema[:uniqueItems] = constraints[:unique_items] if constraints[:unique_items]
137
137
  end
138
138
 
139
+ public
140
+
139
141
  def to_s
140
142
  item_type_str = format_item_type_string
141
143
  constraint_part = format_constraints_string
142
144
  "Array[#{item_type_str}]#{constraint_part}"
143
145
  end
144
146
 
147
+ private
148
+
145
149
  def format_item_type_string
146
150
  item_type.respond_to?(:to_s) ? item_type.to_s : item_type.class.name
147
151
  end
@@ -13,7 +13,7 @@ module RapiTapir
13
13
  # - Protocol Buffer message classes
14
14
  #
15
15
  # All methods support field filtering via only/except parameters.
16
- # rubocop:disable Metrics/ModuleLength
16
+ # rubocop:disable-next Metrics/ModuleLength
17
17
  module AutoDerivation
18
18
  class << self
19
19
  # Derive schema from a plain Hash with sample values
@@ -22,7 +22,6 @@ module RapiTapir
22
22
  # @param only [Array<Symbol>] Only include these fields
23
23
  # @param except [Array<Symbol>] Exclude these fields
24
24
  # @return [RapiTapir::Types::Hash]
25
- # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
26
25
  def from_hash(hash, only: nil, except: nil)
27
26
  raise ArgumentError, "Expected Hash, got #{hash.class}" unless hash.is_a?(::Hash)
28
27
 
@@ -39,7 +38,6 @@ module RapiTapir
39
38
 
40
39
  create_hash_type(schema_hash)
41
40
  end
42
- # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
43
41
 
44
42
  # Derive schema from JSON Schema object
45
43
  #
@@ -47,11 +45,8 @@ module RapiTapir
47
45
  # @param only [Array<Symbol>] Only include these fields
48
46
  # @param except [Array<Symbol>] Exclude these fields
49
47
  # @return [RapiTapir::Types::Hash]
50
- # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
51
48
  def from_json_schema(json_schema, only: nil, except: nil)
52
- unless json_schema.is_a?(::Hash) && json_schema['type'] == 'object'
53
- raise ArgumentError, 'JSON Schema must be an object type'
54
- end
49
+ raise ArgumentError, 'JSON Schema must be an object type' unless json_schema.is_a?(::Hash) && json_schema['type'] == 'object'
55
50
 
56
51
  properties = json_schema['properties'] || {}
57
52
  required_fields = Array(json_schema['required'])
@@ -69,7 +64,6 @@ module RapiTapir
69
64
 
70
65
  RapiTapir::Types.hash(schema_hash)
71
66
  end
72
- # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
73
67
 
74
68
  # Derive schema from OpenStruct instance
75
69
  #
@@ -77,7 +71,7 @@ module RapiTapir
77
71
  # @param only [Array<Symbol>] Only include these fields
78
72
  # @param except [Array<Symbol>] Exclude these fields
79
73
  # @return [RapiTapir::Types::Hash]
80
- # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Style/OpenStructUse
74
+ # rubocop:disable-next Style/OpenStructUse
81
75
  def from_open_struct(open_struct, only: nil, except: nil)
82
76
  raise ArgumentError, "Expected OpenStruct, got #{open_struct.class}" unless open_struct.is_a?(OpenStruct)
83
77
 
@@ -93,7 +87,6 @@ module RapiTapir
93
87
 
94
88
  create_hash_type(schema_hash)
95
89
  end
96
- # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Style/OpenStructUse
97
90
 
98
91
  # Derive schema from Protobuf message class
99
92
  #
@@ -101,11 +94,8 @@ module RapiTapir
101
94
  # @param only [Array<Symbol>] Only include these fields
102
95
  # @param except [Array<Symbol>] Exclude these fields
103
96
  # @return [RapiTapir::Types::Hash]
104
- # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
105
97
  def from_protobuf(proto_class, only: nil, except: nil)
106
- unless defined?(Google::Protobuf) && proto_class.respond_to?(:descriptor)
107
- raise ArgumentError, 'Protobuf not available or invalid protobuf class'
108
- end
98
+ raise ArgumentError, 'Protobuf not available or invalid protobuf class' unless defined?(Google::Protobuf) && proto_class.respond_to?(:descriptor)
109
99
 
110
100
  schema_hash = {}
111
101
  proto_class.descriptor.each do |field_descriptor|
@@ -121,12 +111,10 @@ module RapiTapir
121
111
 
122
112
  create_hash_type(schema_hash)
123
113
  end
124
- # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
125
114
 
126
115
  private
127
116
 
128
117
  # Convert JSON Schema field type to RapiTapir type
129
- # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
130
118
  def convert_json_schema_type(field_schema, required: true)
131
119
  base_type = case field_schema['type']
132
120
  when 'string'
@@ -163,7 +151,6 @@ module RapiTapir
163
151
 
164
152
  required ? base_type : create_optional_type(base_type)
165
153
  end
166
- # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity
167
154
 
168
155
  # Convert protobuf field descriptor to RapiTapir type
169
156
  def convert_protobuf_type(field_descriptor)
@@ -189,7 +176,6 @@ module RapiTapir
189
176
  end
190
177
 
191
178
  # Infer RapiTapir type from Ruby value
192
- # rubocop:disable Metrics/CyclomaticComplexity
193
179
  def infer_type_from_value(value)
194
180
  case value
195
181
  when ::Integer
@@ -212,7 +198,6 @@ module RapiTapir
212
198
  create_string_type
213
199
  end
214
200
  end
215
- # rubocop:enable Metrics/CyclomaticComplexity
216
201
 
217
202
  # Helper methods to create types without using convenience methods
218
203
  def create_string_type
@@ -260,6 +245,5 @@ module RapiTapir
260
245
  end
261
246
  end
262
247
  end
263
- # rubocop:enable Metrics/ModuleLength
264
248
  end
265
249
  end
@@ -42,9 +42,7 @@ module RapiTapir
42
42
  # Assume Unix timestamp
43
43
  ::Time.at(value).to_datetime
44
44
  else
45
- unless value.respond_to?(:to_datetime)
46
- raise CoercionError.new(value, 'DateTime', 'Value cannot be converted to DateTime')
47
- end
45
+ raise CoercionError.new(value, 'DateTime', 'Value cannot be converted to DateTime') unless value.respond_to?(:to_datetime)
48
46
 
49
47
  value.to_datetime
50
48
 
@@ -39,9 +39,7 @@ module RapiTapir
39
39
  def validate_minimum_constraints(float_value)
40
40
  errors = []
41
41
 
42
- if constraints[:minimum] && float_value < constraints[:minimum]
43
- errors << "Value #{float_value} is below minimum #{constraints[:minimum]}"
44
- end
42
+ errors << "Value #{float_value} is below minimum #{constraints[:minimum]}" if constraints[:minimum] && float_value < constraints[:minimum]
45
43
 
46
44
  if constraints[:exclusive_minimum] && float_value <= constraints[:exclusive_minimum]
47
45
  errors << "Value #{float_value} must be greater than #{constraints[:exclusive_minimum]}"
@@ -53,9 +51,7 @@ module RapiTapir
53
51
  def validate_maximum_constraints(float_value)
54
52
  errors = []
55
53
 
56
- if constraints[:maximum] && float_value > constraints[:maximum]
57
- errors << "Value #{float_value} exceeds maximum #{constraints[:maximum]}"
58
- end
54
+ errors << "Value #{float_value} exceeds maximum #{constraints[:maximum]}" if constraints[:maximum] && float_value > constraints[:maximum]
59
55
 
60
56
  if constraints[:exclusive_maximum] && float_value >= constraints[:exclusive_maximum]
61
57
  errors << "Value #{float_value} must be less than #{constraints[:exclusive_maximum]}"
@@ -9,7 +9,7 @@ module RapiTapir
9
9
  class Hash < Base
10
10
  attr_reader :field_types
11
11
 
12
- def initialize(field_types = {}, additional_properties: true, **options)
12
+ def initialize(field_types = {}, additional_properties: false, **options)
13
13
  @field_types = field_types.freeze
14
14
  super(
15
15
  additional_properties: additional_properties,
@@ -39,6 +39,16 @@ module RapiTapir
39
39
 
40
40
  field_types.each do |field_name, field_type|
41
41
  field_value = extract_field_value(value, field_name)
42
+
43
+ # Check for missing required fields
44
+ if field_value.nil? && !field_type.optional?
45
+ errors << "Required field '#{field_name}' is missing"
46
+ next
47
+ end
48
+
49
+ # Skip validation for optional missing fields
50
+ next if field_value.nil? && field_type.optional?
51
+
42
52
  field_result = field_type.validate(field_value)
43
53
  next if field_result[:valid]
44
54
 
@@ -82,6 +92,9 @@ module RapiTapir
82
92
  def coerce_hash_value(value)
83
93
  coerced = {}
84
94
 
95
+ # Check for unexpected fields if additional properties are not allowed
96
+ validate_no_unexpected_fields(value) unless constraints[:additional_properties]
97
+
85
98
  # Coerce defined fields
86
99
  coerce_defined_fields(value, coerced)
87
100
 
@@ -91,10 +104,33 @@ module RapiTapir
91
104
  coerced
92
105
  end
93
106
 
107
+ def validate_no_unexpected_fields(value)
108
+ expected_keys = field_types.keys.map { |k| [k, k.to_s, k.to_sym] }.flatten.uniq
109
+ unexpected_keys = value.keys - expected_keys
110
+ return if unexpected_keys.empty?
111
+
112
+ unexpected_list = unexpected_keys.map(&:inspect).join(', ')
113
+ raise CoercionError.new(value, 'Hash', "Unexpected fields in hash: #{unexpected_list}. Only these fields are allowed: #{field_types.keys.join(', ')}")
114
+ end
115
+
94
116
  def coerce_defined_fields(value, coerced)
95
117
  field_types.each do |field_name, field_type|
96
118
  field_value = find_field_value(value, field_name)
97
- coerced[field_name] = field_type.coerce(field_value) if field_value || !field_type.optional?
119
+
120
+ # Check for missing required fields
121
+ if field_value.nil? && !field_type.optional?
122
+ raise CoercionError.new(nil, field_type.class.name, "Required field '#{field_name}' is missing from hash")
123
+ end
124
+
125
+ # Only coerce if we have a value or field is optional
126
+ next unless field_value || !field_type.optional?
127
+
128
+ begin
129
+ coerced[field_name] = field_type.coerce(field_value)
130
+ rescue CoercionError => e
131
+ # Re-raise with field context
132
+ raise CoercionError.new(e.value, e.type, "Field '#{field_name}': #{e.reason}")
133
+ end
98
134
  end
99
135
  end
100
136
 
@@ -148,6 +184,8 @@ module RapiTapir
148
184
  schema[:additionalProperties] = constraints[:additional_properties]
149
185
  end
150
186
 
187
+ public
188
+
151
189
  def to_s
152
190
  if field_types.empty?
153
191
  'Hash'
@@ -46,9 +46,7 @@ module RapiTapir
46
46
  def validate_minimum_constraints(value)
47
47
  errors = []
48
48
 
49
- if constraints[:minimum] && value < constraints[:minimum]
50
- errors << "Value #{value} is below minimum #{constraints[:minimum]}"
51
- end
49
+ errors << "Value #{value} is below minimum #{constraints[:minimum]}" if constraints[:minimum] && value < constraints[:minimum]
52
50
 
53
51
  if constraints[:exclusive_minimum] && value <= constraints[:exclusive_minimum]
54
52
  errors << "Value #{value} must be greater than #{constraints[:exclusive_minimum]}"
@@ -60,9 +58,7 @@ module RapiTapir
60
58
  def validate_maximum_constraints(value)
61
59
  errors = []
62
60
 
63
- if constraints[:maximum] && value > constraints[:maximum]
64
- errors << "Value #{value} exceeds maximum #{constraints[:maximum]}"
65
- end
61
+ errors << "Value #{value} exceeds maximum #{constraints[:maximum]}" if constraints[:maximum] && value > constraints[:maximum]
66
62
 
67
63
  if constraints[:exclusive_maximum] && value >= constraints[:exclusive_maximum]
68
64
  errors << "Value #{value} must be less than #{constraints[:exclusive_maximum]}"
@@ -74,9 +70,7 @@ module RapiTapir
74
70
  def validate_multiple_constraint(value)
75
71
  errors = []
76
72
 
77
- if constraints[:multiple_of] && (value % constraints[:multiple_of]) != 0
78
- errors << "Value #{value} is not a multiple of #{constraints[:multiple_of]}"
79
- end
73
+ errors << "Value #{value} is not a multiple of #{constraints[:multiple_of]}" if constraints[:multiple_of] && (value % constraints[:multiple_of]) != 0
80
74
 
81
75
  errors
82
76
  end
@@ -103,9 +97,7 @@ module RapiTapir
103
97
  end
104
98
 
105
99
  def coerce_other_to_integer(value)
106
- unless value.respond_to?(:to_i)
107
- raise CoercionError.new(value, 'Integer', 'Value cannot be converted to integer')
108
- end
100
+ raise CoercionError.new(value, 'Integer', 'Value cannot be converted to integer') unless value.respond_to?(:to_i)
109
101
 
110
102
  value.to_i
111
103
  end
@@ -9,14 +9,14 @@ module RapiTapir
9
9
  class Object < Base
10
10
  attr_reader :fields
11
11
 
12
- def initialize(**options, &block)
12
+ def initialize(**options, &)
13
13
  @fields = {}
14
14
  super(**options)
15
15
 
16
16
  return unless block_given?
17
17
 
18
18
  builder = ObjectBuilder.new(self)
19
- builder.instance_eval(&block)
19
+ builder.instance_eval(&)
20
20
  end
21
21
 
22
22
  def field(name, type, required: true, **options)
@@ -118,6 +118,8 @@ module RapiTapir
118
118
  schema[:additionalProperties] = false # Objects are strict by default
119
119
  end
120
120
 
121
+ public
122
+
121
123
  def to_s
122
124
  if fields.empty?
123
125
  'Object'
@@ -127,6 +129,8 @@ module RapiTapir
127
129
  end
128
130
  end
129
131
 
132
+ private
133
+
130
134
  def extract_field_value(hash, field_name)
131
135
  # Try different key formats: symbol, string, and string version of symbol
132
136
  hash[field_name] || hash[field_name.to_s] || hash[field_name.to_sym]
@@ -124,12 +124,16 @@ module RapiTapir
124
124
  Hash.new(field_types, **options)
125
125
  end
126
126
 
127
+ def self.open_hash(field_types = {}, **options)
128
+ Hash.new(field_types, additional_properties: true, **options)
129
+ end
130
+
127
131
  def self.optional(type)
128
132
  Optional.new(type)
129
133
  end
130
134
 
131
- def self.object(&block)
132
- Object.new(&block)
135
+ def self.object(&)
136
+ Object.new(&)
133
137
  end
134
138
 
135
139
  # Auto-derivation convenience methods
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RapiTapir
4
- VERSION = '0.1.2'
4
+ VERSION = '2.1.0'
5
5
  end
data/lib/rapitapir.rb CHANGED
@@ -43,10 +43,12 @@ rescue LoadError
43
43
  # Sinatra not available
44
44
  end
45
45
 
46
+ # Rails integration (load unconditionally since Rails apps will define Rails)
46
47
  begin
47
- require_relative 'rapitapir/server/rails_adapter' if defined?(Rails)
48
- rescue LoadError
49
- # Rails not available
48
+ require_relative 'rapitapir/server/rails_integration'
49
+ rescue LoadError => e
50
+ # Rails integration files not available
51
+ warn "Rails integration not available: #{e.message}" if $DEBUG
50
52
  end
51
53
 
52
54
  # OpenAPI and client generation (optional)