openapi_components 0.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 22cf1d49b2868f8264758ffcd466461b999abd3a6138e852228086fbb10dbadd
4
+ data.tar.gz: 8d84dc30e4ef16d72752fe5f248884bd7c8508f85edba61586b122aef9768655
5
+ SHA512:
6
+ metadata.gz: 6799d7375dd7c7bb5df9b3df749f26b2b5919028596069d4421b1e8907de5f426c6d4553ac8a129acda40e9378c7c641d33ae2bc9485741a8e2733f28e8f50bd
7
+ data.tar.gz: 9ddc4730cd2045c1e54b841b60df884325ea1fcf618654b370f6426da2517bf8d17109a9c359d7a9788eacd66412955cd02d037bde4a0910de2357d560165407
data/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-09-02
4
+
5
+ - `OpenapiComponents::Loader` / `OpenapiComponents.load`: assemble an OpenAPI document from
6
+ `base.*` plus one file per component; YAML, JSON and Ruby sources; nested directories;
7
+ shared modules; collision detection across shared, local and inline components.
8
+ - Ruby component files evaluate against a context with a `ref(name, type = :schemas)` helper.
9
+ - `verify_refs` (default on) raises `BrokenReferenceError` for dangling internal `$ref`.
10
+ - `OpenapiComponents::Lint.broken_refs`, `.orphans`, `.load` for finished documents.
11
+ - Global `OpenapiComponents.configure` with per-call overrides.
12
+ - Requires Ruby >= 3.1.
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at cheerful.mf@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
6
+
7
+ gem "rake", "~> 13.0"
8
+ gem "rspec", "~> 3.13"
9
+ gem "rubocop", "~> 1.75"
10
+ gem "rubocop-rspec", "~> 3.5"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Mark Frost
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,184 @@
1
+ # openapi_components
2
+
3
+ One file per OpenAPI component, assembled into a document. Built for [rswag](https://github.com/rswag/rswag), works with anything that takes an OpenAPI document as Ruby data.
4
+
5
+ rswag generates `paths` from your request specs, but everything under `components` still has to be
6
+ handed to it as one big hash per document. Past a few dozen schemas that hash becomes a single
7
+ multi-thousand-line YAML file nobody wants to touch, and the enums inside it drift away from the
8
+ constants in your code.
9
+
10
+ `openapi_components` replaces that file with a directory tree:
11
+
12
+ ```
13
+ swagger/
14
+ ├── shared/
15
+ │ └── widgets/
16
+ │ └── schemas/
17
+ │ ├── Widget.yml
18
+ │ └── WidgetOptions.yml
19
+ └── settings/
20
+ ├── base.yml # info, servers, security — everything but components and paths
21
+ ├── schemas/
22
+ │ ├── Account.yml
23
+ │ ├── AccountKind.rb # a Ruby file: enums come from your code
24
+ │ └── nested/Address.json # nesting is free, only the file name matters
25
+ ├── parameters/
26
+ │ └── page.yml
27
+ ├── responses/
28
+ │ └── NotFound.yml
29
+ └── securitySchemes/
30
+ └── bearerAuth.yml
31
+ ```
32
+
33
+ Every file becomes one entry under `components/<directory>/<file name>`. Formats: `.yml`, `.yaml`,
34
+ `.json`, `.rb`. All nine OpenAPI 3.x component types are supported (`schemas`, `responses`,
35
+ `parameters`, `examples`, `requestBodies`, `headers`, `securitySchemes`, `links`, `callbacks`).
36
+
37
+ The gem has no runtime dependencies and does not depend on rswag itself: it produces a plain Hash,
38
+ so it works with anything that accepts an OpenAPI document as Ruby data.
39
+
40
+ ## Installation
41
+
42
+ ```ruby
43
+ group :development, :test do
44
+ gem "openapi_components"
45
+ end
46
+ ```
47
+
48
+ ## Usage with rswag
49
+
50
+ ```ruby
51
+ # spec/swagger_helper.rb
52
+ require "openapi_components"
53
+
54
+ OpenapiComponents.configure do |config|
55
+ config.root = Rails.root.join("swagger")
56
+ end
57
+
58
+ RSpec.configure do |config|
59
+ config.openapi_root = Rails.root.join("swagger-build").to_s
60
+ config.openapi_specs = {
61
+ "settings.yml" => OpenapiComponents.load(:settings, shared: %i[widgets periods]),
62
+ "reports.yml" => OpenapiComponents.load(:reports, shared: %i[widgets]),
63
+ "core.yml" => OpenapiComponents.load(:core)
64
+ }
65
+ config.openapi_format = :yaml
66
+ end
67
+ ```
68
+
69
+ `OpenapiComponents.load(name, **options)` is shorthand for `OpenapiComponents::Loader.new(name, **options).call`.
70
+ Keys in the returned hash are symbols, which is what rswag expects.
71
+
72
+ ### Base file
73
+
74
+ `<root>/<name>/base.{yml,yaml,json,rb}` is the document skeleton. Anything goes in it; `components`
75
+ may be omitted, `~`, or contain inline entries (those participate in collision detection like files do).
76
+
77
+ ### Shared modules
78
+
79
+ Components used by several documents live under `<root>/<shared_dir>/<module>/<componentType>/`
80
+ and are pulled in with `shared:`. Shared modules load first, so a document-local file with the same
81
+ name raises `NameAlreadyUsedError` instead of silently winning.
82
+
83
+ ### Ruby components
84
+
85
+ A `.rb` file is evaluated and its last expression is the component. Constants resolve from the top
86
+ level, so application code is right there:
87
+
88
+ ```ruby
89
+ # swagger/settings/schemas/AccountKind.rb
90
+ { type: "string", enum: Account::KINDS.keys }
91
+ ```
92
+
93
+ ```ruby
94
+ # swagger/settings/schemas/Accounts.rb
95
+ {
96
+ type: "array",
97
+ maxItems: Account::PAGE_SIZE,
98
+ items: ref("Account") # => { "$ref" => "#/components/schemas/Account" }
99
+ }
100
+ ```
101
+
102
+ `ref(name, type = :schemas)` is the only helper. Anything responding to `to_h` is accepted, so
103
+ a `Struct`, a `Data` instance, or the output of your favourite JSON Schema builder all work.
104
+
105
+ Because `.rb` and `.yml` files sit side by side, you can migrate one component at a time.
106
+
107
+ ### Reference verification
108
+
109
+ By default the loader raises `BrokenReferenceError` when a component points at
110
+ `#/components/...` that does not exist in the assembled document. Only internal pointers are
111
+ checked; external references (`other.yml#/...`) are ignored. Turn it off per document with
112
+ `verify_refs: false` or globally in the configuration.
113
+
114
+ ## Lint
115
+
116
+ `OpenapiComponents::Lint` works on the loader output and on finished files, for example what
117
+ `rake rswag:specs:swaggerize` writes. That matters for orphan detection: only the finished file
118
+ has the `paths` that make a component "used".
119
+
120
+ ```ruby
121
+ # spec/openapi_lint_spec.rb
122
+ RSpec.describe "OpenAPI documents" do
123
+ Dir[Rails.root.join("swagger-build/*.yml")].each do |file|
124
+ describe File.basename(file) do
125
+ let(:document) { OpenapiComponents::Lint.load(file) }
126
+
127
+ it "has no dangling $ref" do
128
+ expect(OpenapiComponents::Lint.broken_refs(document)).to be_empty
129
+ end
130
+
131
+ it "has no unreferenced components" do
132
+ expect(OpenapiComponents::Lint.orphans(document)).to be_empty
133
+ end
134
+ end
135
+ end
136
+ end
137
+ ```
138
+
139
+ * `broken_refs(document)` returns `Reference(target, location)` structs for every internal `$ref`
140
+ that resolves to nothing.
141
+ * `orphans(document)` returns `Orphan(type, name)` structs for components unreachable from anything
142
+ outside `components`. Reachability is transitive, so two unused schemas that reference each other
143
+ are both reported. `securitySchemes` are skipped because `security:` requirements name them
144
+ without `$ref`.
145
+ * `load(path)` reads a YAML document with symbolized keys.
146
+
147
+ Running the orphan check on a real project for the first time is usually revealing: with
148
+ `shared:` modules it is easy to pull a hundred schemas into a document that references six of them.
149
+
150
+ ## Configuration
151
+
152
+ | option | default | meaning |
153
+ |---------------------|------------|------------------------------------------------------------------|
154
+ | `root` | `"swagger"`| directory containing the document folders |
155
+ | `shared_dir` | `"shared"` | folder under `root` holding shared modules; cannot be a document |
156
+ | `permitted_classes` | `[Date]` | passed to `YAML.safe_load_file` for the `.yml` files |
157
+ | `verify_refs` | `true` | raise on dangling internal `$ref` after assembling |
158
+
159
+ Every option can be set globally through `OpenapiComponents.configure` or per document as a keyword
160
+ to `Loader.new` / `OpenapiComponents.load`.
161
+
162
+ ## Errors
163
+
164
+ All errors inherit from `OpenapiComponents::Error`.
165
+
166
+ | error | when |
167
+ |------------------------|------------------------------------------------------------------|
168
+ | `ReservedNameError` | the document name equals `shared_dir` |
169
+ | `MissingBaseError` | no `base.*` in the document folder |
170
+ | `AmbiguousBaseError` | more than one `base.*` |
171
+ | `NameAlreadyUsedError` | the same component name from two sources (file, shared, inline) |
172
+ | `InvalidSourceError` | a file did not produce a Hash |
173
+ | `BrokenReferenceError` | dangling internal `$ref` with `verify_refs` on |
174
+
175
+ ## Development
176
+
177
+ ```
178
+ bin/setup
179
+ bundle exec rake # rspec + rubocop
180
+ ```
181
+
182
+ ## License
183
+
184
+ MIT. See [LICENSE.txt](LICENSE.txt).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ class Configuration
5
+ attr_accessor :root, :shared_dir, :permitted_classes, :verify_refs
6
+
7
+ def initialize
8
+ @root = "swagger"
9
+ @shared_dir = "shared"
10
+ @permitted_classes = [Date]
11
+ @verify_refs = true
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ class Error < StandardError; end
5
+
6
+ class ReservedNameError < Error
7
+ def initialize(name)
8
+ super("`#{name}` is the shared directory and cannot be loaded as a document")
9
+ end
10
+ end
11
+
12
+ class MissingBaseError < Error
13
+ def initialize(dir)
14
+ super("No base.{yml,yaml,json,rb} found in #{dir}")
15
+ end
16
+ end
17
+
18
+ class AmbiguousBaseError < Error
19
+ def initialize(paths)
20
+ super("More than one base file found:\n #{paths.join("\n ")}")
21
+ end
22
+ end
23
+
24
+ class NameAlreadyUsedError < Error
25
+ def initialize(document:, type:, name:, first:, second:)
26
+ super("[#{document}] #{type}/#{name} is defined twice:\n #{first}\n #{second}")
27
+ end
28
+ end
29
+
30
+ class InvalidSourceError < Error
31
+ def initialize(path, value)
32
+ super("#{path} must evaluate to a Hash, got #{value.class}")
33
+ end
34
+ end
35
+
36
+ class UnsupportedFormatError < Error
37
+ def initialize(path)
38
+ super("#{path}: unsupported extension, expected one of #{Source::EXTENSIONS.join(", ")}")
39
+ end
40
+ end
41
+
42
+ class BrokenReferenceError < Error
43
+ def initialize(document, references)
44
+ list = references.map { |ref| " #{ref.target} (at #{ref.location})" }
45
+ super("[#{document}] unresolved $ref:\n#{list.join("\n")}")
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ module HashUtils
5
+ module_function
6
+
7
+ def deep_symbolize_keys(value)
8
+ case value
9
+ when Hash
10
+ value.to_h { |key, nested| [key.respond_to?(:to_sym) ? key.to_sym : key, deep_symbolize_keys(nested)] }
11
+ when Array
12
+ value.map { |item| deep_symbolize_keys(item) }
13
+ else
14
+ value
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ # Static checks over an assembled document. Works on the loader output as
5
+ # well as on a finished file (e.g. what `rswag:specs:swaggerize` wrote), so
6
+ # orphan detection can see the paths rswag adds later.
7
+ module Lint
8
+ Reference = Struct.new(:target, :location)
9
+ Orphan = Struct.new(:type, :name)
10
+
11
+ POINTER = %r{\A#/components/(?<type>[^/]+)/(?<name>[^/]+)\z}
12
+
13
+ # Security schemes are referenced by name through `security:` requirements,
14
+ # never through $ref, so reachability analysis cannot see them.
15
+ UNTRACKED_TYPES = %i[securitySchemes].freeze
16
+
17
+ module_function
18
+
19
+ def load(path, permitted_classes: [Date, Time])
20
+ HashUtils.deep_symbolize_keys(YAML.safe_load_file(path, permitted_classes: permitted_classes, aliases: true))
21
+ end
22
+
23
+ def broken_refs(document)
24
+ document = HashUtils.deep_symbolize_keys(document)
25
+ references(document).reject { |reference| resolve(document, reference.target) }
26
+ end
27
+
28
+ def orphans(document)
29
+ document = HashUtils.deep_symbolize_keys(document)
30
+ reachable = reachable_targets(document)
31
+
32
+ each_component(document).reject { |type, name| reachable.include?(pointer(type, name)) }
33
+ .map { |type, name| Orphan.new(type, name) }
34
+ end
35
+
36
+ def reachable_targets(document)
37
+ reachable = Set.new
38
+ queue = references(document.except(:components)).map(&:target)
39
+
40
+ until queue.empty?
41
+ target = queue.shift
42
+ next unless reachable.add?(target)
43
+
44
+ node = resolve(document, target)
45
+ queue.concat(references(node).map(&:target)) if node
46
+ end
47
+
48
+ reachable
49
+ end
50
+
51
+ def references(node, location = [], found = [])
52
+ children(node).each do |key, value|
53
+ if ref?(key, value)
54
+ found << Reference.new(value, location.join("/"))
55
+ else
56
+ references(value, location + [key], found)
57
+ end
58
+ end
59
+ found
60
+ end
61
+
62
+ def children(node)
63
+ case node
64
+ when Hash then node
65
+ when Array then node.each_with_index.map { |value, index| [index, value] }
66
+ else []
67
+ end
68
+ end
69
+
70
+ def ref?(key, value)
71
+ key == :$ref && value.is_a?(String) && value.start_with?("#/components/")
72
+ end
73
+
74
+ def resolve(document, target)
75
+ match = POINTER.match(target)
76
+ return unless match
77
+
78
+ document.dig(:components, match[:type].to_sym, match[:name].to_sym)
79
+ end
80
+
81
+ def pointer(type, name)
82
+ "#/components/#{type}/#{name}"
83
+ end
84
+
85
+ def each_component(document)
86
+ (document[:components] || {}).flat_map do |type, entries|
87
+ next [] if UNTRACKED_TYPES.include?(type) || !entries.is_a?(Hash)
88
+
89
+ entries.keys.map { |name| [type, name] }
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ # Assembles one OpenAPI document from a directory tree:
5
+ #
6
+ # <root>/<name>/base.{yml,json,rb} document skeleton (info, servers, security, ...)
7
+ # <root>/<name>/<componentType>/**/<Name>.* one component per file, keyed by the file name
8
+ # <root>/<shared_dir>/<module>/<componentType>/**/<Name>.* opt-in via `shared:`
9
+ #
10
+ # Shared modules load first, so a document-local file with the same name is
11
+ # reported as a collision rather than silently winning.
12
+ class Loader
13
+ attr_reader :name, :root, :shared, :shared_dir, :permitted_classes, :verify_refs
14
+
15
+ def initialize(name, shared: [], root: nil, shared_dir: nil, permitted_classes: nil, verify_refs: nil)
16
+ config = OpenapiComponents.configuration
17
+ @name = name.to_s
18
+ @shared = Array(shared).map(&:to_s)
19
+ @root = (root || config.root).to_s
20
+ @shared_dir = (shared_dir || config.shared_dir).to_s
21
+ @permitted_classes = permitted_classes || config.permitted_classes
22
+ @verify_refs = verify_refs.nil? ? config.verify_refs : verify_refs
23
+ end
24
+
25
+ def call
26
+ raise ReservedNameError, name if name == shared_dir
27
+
28
+ @sources = {}
29
+ document = base
30
+ document[:components] = components_of(document)
31
+ register_inline_components(document)
32
+
33
+ COMPONENT_TYPES.each { |type| component_paths(type).each { |path| add(document, type, path) } }
34
+
35
+ check_references(document) if verify_refs
36
+ document
37
+ end
38
+
39
+ private
40
+
41
+ def component_paths(type)
42
+ shared.flat_map { |mod| Source.glob(File.join(root, shared_dir, mod, type.to_s)) } +
43
+ Source.glob(File.join(root, name, type.to_s))
44
+ end
45
+
46
+ def base
47
+ candidates = Dir.glob(File.join(root, name, "base{#{Source::EXTENSIONS.join(",")}}"))
48
+ raise MissingBaseError, File.join(root, name) if candidates.empty?
49
+ raise AmbiguousBaseError, candidates if candidates.size > 1
50
+
51
+ Source.read(candidates.first, permitted_classes: permitted_classes)
52
+ end
53
+
54
+ def components_of(document)
55
+ components = document[:components]
56
+ components.is_a?(Hash) ? components : {}
57
+ end
58
+
59
+ def register_inline_components(document)
60
+ document[:components].each do |type, entries|
61
+ next unless entries.is_a?(Hash)
62
+
63
+ entries.each_key { |component_name| @sources[[type, component_name]] = "#{base_path} (inline)" }
64
+ end
65
+ end
66
+
67
+ def base_path
68
+ File.join(root, name, "base.*")
69
+ end
70
+
71
+ def add(document, type, path)
72
+ component_name = File.basename(path, File.extname(path)).to_sym
73
+ previous = @sources[[type, component_name]]
74
+ if previous
75
+ raise NameAlreadyUsedError.new(document: name, type: type, name: component_name, first: previous, second: path)
76
+ end
77
+
78
+ @sources[[type, component_name]] = path
79
+ (document[:components][type] ||= {})[component_name] = Source.read(path, permitted_classes: permitted_classes)
80
+ end
81
+
82
+ def check_references(document)
83
+ broken = Lint.broken_refs(document)
84
+ raise BrokenReferenceError.new(name, broken) unless broken.empty?
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ # The object a `.rb` component file is evaluated against. The file's last
5
+ # expression is the component; constants resolve from the top level, so
6
+ # application code (enums, limits, defaults) can be interpolated directly.
7
+ class RubyContext
8
+ def initialize(path)
9
+ @__path = path
10
+ end
11
+
12
+ def ref(name, type = :schemas)
13
+ { "$ref" => "#/components/#{type}/#{name}" }
14
+ end
15
+
16
+ def __evaluate
17
+ instance_eval(File.read(@__path), @__path, 1)
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ module Source
5
+ EXTENSIONS = %w[.yml .yaml .json .rb].freeze
6
+
7
+ module_function
8
+
9
+ def glob(dir)
10
+ Dir.glob(File.join(dir, "**", "*{#{EXTENSIONS.join(",")}}"))
11
+ end
12
+
13
+ def read(path, permitted_classes:)
14
+ value = case File.extname(path)
15
+ when ".yml", ".yaml" then YAML.safe_load_file(path, permitted_classes: permitted_classes, aliases: true)
16
+ when ".json" then JSON.parse(File.read(path))
17
+ when ".rb" then RubyContext.new(path).__evaluate
18
+ else raise UnsupportedFormatError, path
19
+ end
20
+
21
+ HashUtils.deep_symbolize_keys(coerce(path, value))
22
+ end
23
+
24
+ def coerce(path, value)
25
+ return value if value.is_a?(Hash)
26
+ return value.to_h if !value.nil? && !value.is_a?(Array) && value.respond_to?(:to_h)
27
+
28
+ raise InvalidSourceError.new(path, value)
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OpenapiComponents
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "json"
5
+ require "set"
6
+ require "yaml"
7
+
8
+ require_relative "openapi_components/version"
9
+ require_relative "openapi_components/errors"
10
+ require_relative "openapi_components/configuration"
11
+ require_relative "openapi_components/hash_utils"
12
+ require_relative "openapi_components/ruby_context"
13
+ require_relative "openapi_components/source"
14
+ require_relative "openapi_components/loader"
15
+ require_relative "openapi_components/lint"
16
+
17
+ module OpenapiComponents
18
+ # Every reusable object type OpenAPI 3.x allows under `components`.
19
+ COMPONENT_TYPES = %i[
20
+ schemas responses parameters examples requestBodies headers securitySchemes links callbacks
21
+ ].freeze
22
+
23
+ class << self
24
+ def configuration
25
+ @configuration ||= Configuration.new
26
+ end
27
+
28
+ def configure
29
+ yield configuration
30
+ end
31
+
32
+ def reset_configuration!
33
+ @configuration = Configuration.new
34
+ end
35
+
36
+ def load(name, **options)
37
+ Loader.new(name, **options).call
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/openapi_components/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "openapi_components"
7
+ spec.version = OpenapiComponents::VERSION
8
+ spec.authors = ["Mark Frost"]
9
+ spec.email = ["cheerful.mf@gmail.com"]
10
+
11
+ spec.summary = "One file per OpenAPI component, assembled into a document. Built for rswag, works with anything."
12
+ spec.description = <<~TEXT
13
+ Keep every OpenAPI component (schema, parameter, response, ...) in its own YAML, JSON or Ruby
14
+ file, share components between documents, and assemble the hash rswag's `config.openapi_specs`
15
+ (or any other OpenAPI consumer) expects. Ruby component files can reference application
16
+ constants, so enums and limits stay defined once. Ships a linter for dangling $ref pointers and
17
+ unreferenced components.
18
+ TEXT
19
+ spec.homepage = "https://github.com/frostmark/openapi_components"
20
+ spec.license = "MIT"
21
+ spec.required_ruby_version = ">= 3.1.0"
22
+
23
+ spec.metadata["source_code_uri"] = spec.homepage
24
+ spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
25
+ spec.metadata["rubygems_mfa_required"] = "true"
26
+
27
+ spec.files = Dir.chdir(__dir__) do
28
+ `git ls-files -z`.split("\x0").reject do |f|
29
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|spec)/|\.(?:git|github|rspec|rubocop))})
30
+ end
31
+ end
32
+ spec.require_paths = ["lib"]
33
+ end
metadata ADDED
@@ -0,0 +1,65 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: openapi_components
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mark Frost
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-09-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: |
13
+ Keep every OpenAPI component (schema, parameter, response, ...) in its own YAML, JSON or Ruby
14
+ file, share components between documents, and assemble the hash rswag's `config.openapi_specs`
15
+ (or any other OpenAPI consumer) expects. Ruby component files can reference application
16
+ constants, so enums and limits stay defined once. Ships a linter for dangling $ref pointers and
17
+ unreferenced components.
18
+ email:
19
+ - cheerful.mf@gmail.com
20
+ executables: []
21
+ extensions: []
22
+ extra_rdoc_files: []
23
+ files:
24
+ - CHANGELOG.md
25
+ - CODE_OF_CONDUCT.md
26
+ - Gemfile
27
+ - LICENSE.txt
28
+ - README.md
29
+ - Rakefile
30
+ - lib/openapi_components.rb
31
+ - lib/openapi_components/configuration.rb
32
+ - lib/openapi_components/errors.rb
33
+ - lib/openapi_components/hash_utils.rb
34
+ - lib/openapi_components/lint.rb
35
+ - lib/openapi_components/loader.rb
36
+ - lib/openapi_components/ruby_context.rb
37
+ - lib/openapi_components/source.rb
38
+ - lib/openapi_components/version.rb
39
+ - openapi_components.gemspec
40
+ homepage: https://github.com/frostmark/openapi_components
41
+ licenses:
42
+ - MIT
43
+ metadata:
44
+ source_code_uri: https://github.com/frostmark/openapi_components
45
+ changelog_uri: https://github.com/frostmark/openapi_components/blob/main/CHANGELOG.md
46
+ rubygems_mfa_required: 'true'
47
+ rdoc_options: []
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: 3.1.0
55
+ required_rubygems_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ requirements: []
61
+ rubygems_version: 3.6.2
62
+ specification_version: 4
63
+ summary: One file per OpenAPI component, assembled into a document. Built for rswag,
64
+ works with anything.
65
+ test_files: []