schema_splint 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: b09e788cd65bc717b05d80faa99f7a91a8b9d32cf64d00ede64f3994f15981e8
4
+ data.tar.gz: fd9f228ecdad3efee4abfdd6af77e28e3cc29b431cee00c320d3bb255a93660d
5
+ SHA512:
6
+ metadata.gz: 0e0a59cd701c17e249b7d25c84efd24dc3f9c5ff7c1ae4fd23505c9816b771fa98605bf81e9599cb710dac04766c85399b0ab4aad836c2e57346d71e957460d8
7
+ data.tar.gz: ca41ba98e180a335470186746786993b420f0e66a767018479a01ad47c12972024f62040b3889c90cff25581d2a7925cd54d64281174ed68d7a4a9d25f26e766
data/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-12-06
4
+
5
+ First release. schema_splint lays an OpenAPI document over existing Ruby code as RBS, and writes no Ruby.
6
+
7
+ - `schema-splint rbs --spec OPENAPI --module NAME --out FILE` writes, for each schema, an interface with a snake_case reader per field and one `[]` overload per key (as a string or a symbol), and a record with the wire's string keys. Each 2xx JSON body of an operation gets an alias such as `get_order_200`. `--check` writes nothing and fails when the file is stale.
8
+ - Optional keys are `?`, nullable values are `T?`, enums are literal unions, and formats stay `String`.
9
+ - `SchemaSplint::Conform#problems` and `#check!` hold a value to the same RBS at runtime and report each break with its JSON path. String keys, symbol keys, and `with_indifferent_access` hashes are read, and keys the type does not name are ignored. `schema-splint conform --sig DIR --type NAME JSON_FILE...` does the same from the command line.
10
+ - Ruby 3.3 or later.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 meganemura
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.ja.md ADDED
@@ -0,0 +1,28 @@
1
+ # schema_splint
2
+
3
+ schema_splint は、OpenAPI の定義を、今ある Ruby のコードに RBS として被せます。
4
+ Ruby のコードは書きません。
5
+
6
+ ほかのサービスを呼ぶコードは、今のままにしておけます。
7
+ `with_indifferent_access` の Hash を `method_missing` で何でも読めるようにしたモデルも、そのままで構いません。
8
+ schema_splint は spec を RBS に書き出し、同じ RBS ファイルを両側から検査します。
9
+
10
+ - **コードの側**: Steep が、すべての読み取りを spec に照らします。spec に無い名前やキー、nil かもしれない値、型の違う使い方をエラーにします。
11
+ - **データの側**: `SchemaSplint::Conform` が、テストの偽データ、記録した返事、本番の返事を、実行時に同じ RBS に照らします。違いは JSON のパス付きで出します。
12
+
13
+ ## 入れ方
14
+
15
+ `gem install schema_splint` で入れるか、Gemfile の development グループに `gem "schema_splint"` を足します。
16
+ Ruby 3.3 以上で動きます。
17
+ コードの側の検査には Steep が要ります。
18
+
19
+ ## 使い方
20
+
21
+ 1. `schema-splint rbs --spec shop.openapi.yaml --module Shop::Contract --out sig/shop_contract.rbs` で、スキーマごとに interface とレコード型を書き出します。
22
+ 2. 今のコードに足す RBS は、クライアントが返すものの型だけです(例: `def self.order: (String id) -> Contract::_Order`)。
23
+ 3. Steep が、spec が約束していない読み取りを全部エラーにします。
24
+ 4. `SchemaSplint::Conform` や `schema-splint conform` で、データを同じ RBS に照らします。
25
+
26
+ interface は、クラスではなくメソッドで型を見ます。
27
+ そのため、今のモデルのクラスは変えずに済み、そのクラス用の RBS も要りません。
28
+ `--check` を付けて CI で動かすと、spec が変わったときに気づけます。
data/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # schema_splint
2
+
3
+ schema_splint lays an OpenAPI document over existing Ruby code as RBS. It writes no Ruby.
4
+
5
+ The code that calls another service stays as it is, including a model that answers any name through `method_missing` over a `with_indifferent_access` hash. schema_splint writes the spec as RBS, and the same RBS file is checked from both sides:
6
+
7
+ - **The code side.** Steep holds every read to the spec: a name or a key the spec does not have, a value that may be nil, a value used as the wrong type.
8
+ - **The data side.** `SchemaSplint::Conform` holds a value (a test fixture, a recorded response, a live response) to the same RBS at runtime, and reports each break with its JSON path.
9
+
10
+ ## Install
11
+
12
+ ```
13
+ gem install schema_splint
14
+ ```
15
+
16
+ Or add `gem "schema_splint"` to the Gemfile's development group. It needs Ruby 3.3 or later, and the code side needs Steep.
17
+
18
+ ## Write the contract
19
+
20
+ ```
21
+ schema-splint rbs --spec shop.openapi.yaml --module Shop::Contract --out sig/shop_contract.rbs
22
+ ```
23
+
24
+ For each schema it writes an interface and a record:
25
+
26
+ ```rbs
27
+ interface _Order
28
+ def status: () -> ("pending" | "paid" | "shipped" | "canceled")
29
+ def payment: () -> _Payment
30
+ def shipped_at: () -> String?
31
+ def []: ("status" | :status) -> ("pending" | "paid" | "shipped" | "canceled")
32
+ | ("payment" | :payment) -> _Payment
33
+ | ("shippedAt" | :shippedAt) -> String?
34
+ # ...
35
+ end
36
+ type order = { "status" => ("pending" | ...), "payment" => payment, "shippedAt" => String?, ?"deliveryDate" => String, ... }
37
+ ```
38
+
39
+ - The **interface** types an object: a model or a hash with indifferent access. Steep checks an interface by its methods, whatever the class, so the existing model class needs no change and no RBS of its own. It has a reader per field (snake_case) and one `[]` overload per key, as a string or a symbol.
40
+ - The **record** types a plain `JSON.parse` hash, with the wire's own string keys.
41
+ - Optional keys are `?`, nullable values are `T?`, enums are literal unions. Formats stay `String`: a date-time is a string on the wire.
42
+ - An alias per success body of each operation, such as `get_order_200`, names the record of that response.
43
+
44
+ Run it again with `--check` in CI. It writes nothing and fails when the file is stale, so a spec change reaches the code through a reviewed diff, and Steep then shows every place it breaks.
45
+
46
+ ## Lay it over the code
47
+
48
+ Say what the client returns. This is the only RBS the existing code needs:
49
+
50
+ ```rbs
51
+ module Shop
52
+ def self.order: (String id) -> Contract::_Order
53
+ end
54
+ ```
55
+
56
+ Steep then reports each read that the contract does not promise:
57
+
58
+ ```ruby
59
+ order = Shop.order("ord_1")
60
+ order.payment.amount + 1 # ok
61
+ order[:payment][:currency].upcase # ok
62
+ order.delivery_date.upcase # error: (String | nil) does not have method upcase
63
+ order.legacy_flag # error: _Order does not have method legacy_flag
64
+ order[:legacyFlag] # error: no overload of [] takes :legacyFlag
65
+ order.payment.amount.upcase # error: Integer does not have method upcase
66
+ ```
67
+
68
+ ## Hold the data to it
69
+
70
+ ```ruby
71
+ contract = SchemaSplint::Conform.new("sig")
72
+ contract.problems(body, "Shop::Contract::order")
73
+ # => [$.payment.amount expected Integer, got "1200", $.status expected "pending" | "paid" | ..., got "lost"]
74
+ contract.check!(body, "Shop::Contract::order") # raises SchemaSplint::Conform::Broken
75
+ ```
76
+
77
+ String keys, symbol keys, and `with_indifferent_access` hashes are all read. Keys the type does not name are ignored. Call it in the client, in tests, or on recorded responses:
78
+
79
+ ```
80
+ schema-splint conform --sig sig --type Shop::Contract::order spec/fixtures/shop/*.json
81
+ ```
82
+
83
+ [Japanese](README.ja.md)
data/exe/schema-splint ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../lib/schema_splint/cli"
5
+ exit SchemaSplint::CLI.run(ARGV)
@@ -0,0 +1,98 @@
1
+ # rbs_inline: enabled
2
+ # frozen_string_literal: true
3
+
4
+ require "fileutils"
5
+ require "json"
6
+ require_relative "../schema_splint"
7
+
8
+ module SchemaSplint
9
+ # The schema_splint command. `rbs` writes the contract as RBS (or, with --check,
10
+ # fails when the written file is stale); `conform` holds JSON files to it.
11
+ module CLI
12
+ USAGE = <<~TEXT
13
+ usage: schema-splint rbs --spec OPENAPI --module NAME --out FILE [--check]
14
+ schema-splint conform --sig DIR --type NAME JSON_FILE...
15
+ TEXT
16
+
17
+ # @rbs argv: Array[String]
18
+ # @rbs out: IO
19
+ # @rbs err: IO
20
+ # @rbs return: Integer
21
+ def self.run(argv, out: $stdout, err: $stderr)
22
+ command, *args = argv
23
+ case command
24
+ when "rbs" then rbs(args, out:, err:)
25
+ when "conform" then conform(args, out:, err:)
26
+ else
27
+ err.puts USAGE
28
+ 2
29
+ end
30
+ end
31
+
32
+ # Writes the spec as RBS. With --check it writes nothing and fails when
33
+ # the file differs, so a spec change reaches Steep through a reviewed diff.
34
+ # @rbs args: Array[String]
35
+ # @rbs out: IO
36
+ # @rbs err: IO
37
+ # @rbs return: Integer
38
+ def self.rbs(args, out:, err:)
39
+ check = !args.delete("--check").nil?
40
+ options = args.each_slice(2).to_h
41
+ spec, module_name, path = options.values_at("--spec", "--module", "--out")
42
+ unless spec && module_name && path && options.size == 3
43
+ err.puts USAGE
44
+ return 2
45
+ end
46
+
47
+ text = Contract.new(Spec.load(spec), module_name).to_rbs
48
+ return 0 if File.exist?(path) && File.read(path) == text
49
+ if check
50
+ err.puts "stale: #{path}; run schema-splint rbs"
51
+ return 1
52
+ end
53
+
54
+ FileUtils.mkdir_p(File.dirname(path))
55
+ File.write(path, text)
56
+ out.puts "wrote #{path}"
57
+ 0
58
+ rescue Error => e
59
+ err.puts e.message
60
+ 1
61
+ end
62
+
63
+ # Checks JSON files (fixtures, recorded responses) against an RBS type.
64
+ # @rbs args: Array[String]
65
+ # @rbs out: IO
66
+ # @rbs err: IO
67
+ # @rbs return: Integer
68
+ def self.conform(args, out:, err:)
69
+ sigs = [] #: Array[String]
70
+ type = nil #: String?
71
+ files = [] #: Array[String]
72
+ until args.empty?
73
+ arg = args.shift.to_s
74
+ case arg
75
+ when "--sig" then sigs << args.shift.to_s
76
+ when "--type" then type = args.shift
77
+ else files << arg
78
+ end
79
+ end
80
+ if sigs.empty? || type.nil? || files.empty?
81
+ err.puts USAGE
82
+ return 2
83
+ end
84
+
85
+ require_relative "conform"
86
+ checker = Conform.new(*sigs)
87
+ broken = files.count do |file|
88
+ problems = checker.problems(JSON.parse(File.read(file)), type)
89
+ problems.each { out.puts "#{file}: #{_1}" }
90
+ !problems.empty?
91
+ end
92
+ broken.zero? ? 0 : 1
93
+ rescue Error, JSON::ParserError => e
94
+ err.puts e.message
95
+ 1
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,158 @@
1
+ # rbs_inline: enabled
2
+ # frozen_string_literal: true
3
+
4
+ require "rbs"
5
+
6
+ module SchemaSplint
7
+ # Holds a value from the wire against a type in RBS files, at runtime: the
8
+ # data side of the contract that Steep checks on the code side. It reports
9
+ # every place the value breaks the type, with its JSON path, so a fixture,
10
+ # a recorded response, or a live response in the shadow can be fixed or
11
+ # reported without guessing.
12
+ #
13
+ # Keys the type does not name are ignored, as a tolerant reader would.
14
+ class Conform
15
+ # One place a value breaks the type: its JSON path, the type it should
16
+ # have, and what it holds.
17
+ Problem = Data.define(
18
+ :path, #: String
19
+ :expected, #: String
20
+ :actual #: String
21
+ )
22
+
23
+ class Problem
24
+ #: () -> String
25
+ def to_s = "#{path} expected #{expected.gsub(/(?<![\w:])::/, "")}, got #{actual}"
26
+ end
27
+
28
+ # The value broke the contract.
29
+ class Broken < StandardError
30
+ attr_reader :problems #: Array[Problem]
31
+
32
+ # @rbs type: String
33
+ # @rbs problems: Array[Problem]
34
+ def initialize(type, problems)
35
+ @problems = problems
36
+ super(["does not conform to #{type}:", *problems.map { " #{_1}" }].join("\n"))
37
+ end
38
+ end
39
+
40
+ # @rbs signatures: Array[String]
41
+ def initialize(*signatures)
42
+ loader = RBS::EnvironmentLoader.new
43
+ signatures.each { loader.add(path: Pathname(_1)) }
44
+ @env = RBS::Environment.from_loader(loader).resolve_type_names
45
+ end
46
+
47
+ # @rbs value: untyped
48
+ # @rbs type: String
49
+ # @rbs return: Array[Problem]
50
+ def problems(value, type)
51
+ found = [] #: Array[Problem]
52
+ check(value, RBS::Parser.parse_type(type.start_with?("::") ? type : "::#{type}"), "$", found)
53
+ found
54
+ end
55
+
56
+ # @rbs value: untyped
57
+ # @rbs type: String
58
+ def check!(value, type)
59
+ found = problems(value, type)
60
+ raise Broken.new(type, found) unless found.empty?
61
+
62
+ value
63
+ end
64
+
65
+ private
66
+
67
+ # @rbs value: untyped
68
+ # @rbs type: untyped
69
+ # @rbs path: String
70
+ # @rbs found: Array[Problem]
71
+ def check(value, type, path, found)
72
+ case type
73
+ when RBS::Types::Alias
74
+ decl = @env.type_alias_decls[type.name] or raise Error, "no type #{type.name} in the signatures"
75
+ check(value, decl.decl.type, path, found)
76
+ when RBS::Types::Optional
77
+ check(value, type.type, path, found) unless value.nil?
78
+ when RBS::Types::Union
79
+ return if type.types.any? { problems_of(value, _1, path).empty? }
80
+
81
+ found << Problem.new(path:, expected: type.to_s, actual: describe(value))
82
+ when RBS::Types::Record then record(value, type, path, found)
83
+ when RBS::Types::Literal
84
+ found << Problem.new(path:, expected: type.to_s, actual: describe(value)) unless value == type.literal
85
+ when RBS::Types::Bases::Bool
86
+ found << Problem.new(path:, expected: "bool", actual: describe(value)) unless value == true || value == false
87
+ when RBS::Types::Bases::Nil
88
+ found << Problem.new(path:, expected: "nil", actual: describe(value)) unless value.nil?
89
+ when RBS::Types::Bases::Any, RBS::Types::Bases::Top then nil
90
+ when RBS::Types::ClassInstance then instance(value, type, path, found)
91
+ else raise Error, "schema_splint does not check #{type} yet"
92
+ end
93
+ end
94
+
95
+ # @rbs value: untyped
96
+ # @rbs type: RBS::Types::Record
97
+ # @rbs path: String
98
+ # @rbs found: Array[Problem]
99
+ def record(value, type, path, found)
100
+ return found << Problem.new(path:, expected: "an object", actual: describe(value)) unless value.is_a?(Hash)
101
+
102
+ fields = type.fields.transform_values { [_1, true] }.merge(type.optional_fields.transform_values { [_1, false] })
103
+ fields.each do |key, (field, required)|
104
+ at = "#{path}.#{key}"
105
+ present, item = lookup(value, key)
106
+ if present
107
+ check(item, field, at, found)
108
+ elsif required
109
+ found << Problem.new(path: at, expected: field.to_s, actual: "nothing (the key is missing)")
110
+ end
111
+ end
112
+ end
113
+
114
+ # A body may come with string keys (JSON.parse), symbol keys
115
+ # (symbolize_names), or either (with_indifferent_access).
116
+ # @rbs hash: Hash[untyped, untyped]
117
+ # @rbs key: untyped
118
+ # @rbs return: [bool, untyped]
119
+ def lookup(hash, key)
120
+ [key, key.to_s, key.to_s.to_sym].uniq.each { return [true, hash[_1]] if hash.key?(_1) }
121
+ [false, nil]
122
+ end
123
+
124
+ # @rbs value: untyped
125
+ # @rbs type: RBS::Types::ClassInstance
126
+ # @rbs path: String
127
+ # @rbs found: Array[Problem]
128
+ def instance(value, type, path, found)
129
+ klass = Object.const_get(type.name.to_s)
130
+ return found << Problem.new(path:, expected: type.to_s, actual: describe(value)) unless value.is_a?(klass)
131
+
132
+ if value.is_a?(Array) && type.args.size == 1
133
+ value.each_with_index { |item, index| check(item, type.args.first, "#{path}[#{index}]", found) }
134
+ elsif value.is_a?(Hash) && type.args.size == 2
135
+ value.each { |key, item| check(item, type.args.last, "#{path}.#{key}", found) }
136
+ end
137
+ end
138
+
139
+ # @rbs value: untyped
140
+ # @rbs type: untyped
141
+ # @rbs path: String
142
+ def problems_of(value, type, path)
143
+ found = [] #: Array[Problem]
144
+ check(value, type, path, found)
145
+ found
146
+ end
147
+
148
+ # @rbs value: untyped
149
+ def describe(value)
150
+ case value
151
+ when nil then "nil"
152
+ when String then value.length > 40 ? "a String" : value.inspect
153
+ when Integer, Float, true, false then "#{value.inspect} (#{value.class})"
154
+ else "a #{value.class}"
155
+ end
156
+ end
157
+ end
158
+ end
@@ -0,0 +1,205 @@
1
+ # rbs_inline: enabled
2
+ # frozen_string_literal: true
3
+
4
+ module SchemaSplint
5
+ # Writes an OpenAPI document as RBS: one type alias per schema, as records
6
+ # with the wire's own string keys, plus one alias per operation's success
7
+ # body. That RBS file is the contract in Ruby's terms. Steep holds the
8
+ # application's code to it, and Conform holds data (test fixtures, recorded
9
+ # responses, live responses in the shadow) to the very same file, so the two
10
+ # sides are checked against one thing.
11
+ #
12
+ # Formats stay strings (a date-time is a String on the wire); turning them
13
+ # into Time is the application's translation, not the contract's.
14
+ class Contract
15
+ # @rbs spec: Spec
16
+ # @rbs module_name: String
17
+ def initialize(spec, module_name)
18
+ @spec = spec
19
+ @module_name = module_name
20
+ @refused = [] #: Array[String]
21
+ end
22
+
23
+ # The name an alias gets: OrderPage -> order_page.
24
+ # @rbs name: String
25
+ def self.alias_name(name)
26
+ snake = SchemaSplint.snake(name.gsub(/[^A-Za-z0-9_]/, "_"))
27
+ snake.match?(/\A[a-z_]/) ? snake : "t_#{snake}"
28
+ end
29
+
30
+ # The interface name for a schema: Order -> _Order.
31
+ # @rbs name: String
32
+ def self.interface_name(name)
33
+ "_" + name.gsub(/[^A-Za-z0-9]+/, "_").sub(/\A./, &:upcase)
34
+ end
35
+
36
+ #: () -> String
37
+ def to_rbs
38
+ lines = ["# Written by schema_splint from #{File.basename(@spec.path)}. Do not edit; change the spec and run it again.", ""]
39
+ body = [] #: Array[String]
40
+ @spec.schema_names.each do |name|
41
+ schema = @spec.schema(name) || {}
42
+ body << "type #{Contract.alias_name(name)} = #{type_of(schema)}"
43
+ body.concat(interface(name, @spec.deref(schema))) if object_schema?(@spec.deref(schema))
44
+ end
45
+ body << "" unless body.empty?
46
+ @spec.operation_ids.each do |id|
47
+ op = @spec.operation(id) or next
48
+ (op.operation["responses"] || {}).each do |status, response|
49
+ next unless status.to_s.match?(/\A2(\d\d|XX)\z/)
50
+
51
+ content = @spec.deref(response)["content"] || {}
52
+ media = content.keys.find { _1 == "application/json" || _1.end_with?("+json") }
53
+ schema = media && content.dig(media, "schema")
54
+ next unless schema
55
+
56
+ body << "# #{op.verb.upcase} #{op.template} #{status}"
57
+ body << "type #{Contract.alias_name(id)}_#{status.to_s.downcase} = #{type_of(schema)}"
58
+ end
59
+ end
60
+ nest = @module_name.split("::")
61
+ opening = nest.each_with_index.map { |n, i| "#{" " * i}module #{n}" }
62
+ closing = nest.each_index.reverse_each.map { "#{" " * _1}end" }
63
+ inner = body.map { _1.empty? ? "" : "#{" " * nest.size}#{_1}" }
64
+ (lines + opening + inner + closing).join("\n") + "\n"
65
+ end
66
+
67
+ private
68
+
69
+ # Object-like values (a model built on method_missing, a hash with
70
+ # indifferent access) are typed by an interface, not a record: Steep holds
71
+ # a value to an interface by its methods, whatever its class, so the
72
+ # existing class needs no change and no RBS of its own. A reader per field
73
+ # and one `[]` overload per key, string or symbol, mean a name or a key the
74
+ # spec does not have is a type error.
75
+ # @rbs name: String
76
+ # @rbs schema: Hash[String, untyped]
77
+ # @rbs return: Array[String]
78
+ def interface(name, schema)
79
+ required = Array(schema["required"])
80
+ fields = (schema["properties"] || {}).map do |key, property|
81
+ type = with_objects { type_of(property) }
82
+ type = optional(type) unless required.include?(key)
83
+ [key, type]
84
+ end
85
+ readers = fields.filter_map do |key, type|
86
+ reader = SchemaSplint.snake(key)
87
+ next unless reader.match?(/\A[a-z_][a-z0-9_]*\z/) && !TAKEN_READERS.include?(reader)
88
+
89
+ " def #{reader}: () -> #{type}"
90
+ end
91
+ keys = fields.map.with_index do |(key, type), index|
92
+ symbol = key.match?(/\A[A-Za-z_]\w*\z/) ? ":#{key}" : ":#{key.inspect}"
93
+ "#{index.zero? ? " def []: " : " | "}(#{key.inspect} | #{symbol}) -> #{type}"
94
+ end
95
+ ["interface #{Contract.interface_name(name)}", *readers, *keys, "end"]
96
+ end
97
+
98
+ # Names every object already answers; a field with one of these names is
99
+ # reached through `[]` only.
100
+ TAKEN_READERS = %w[class hash method send object_id display freeze dup clone then tap inspect to_s].freeze
101
+
102
+ # @rbs schema: Hash[String, untyped]
103
+ def object_schema?(schema) = schema["type"] == "object" || (schema["type"].nil? && schema.key?("properties"))
104
+
105
+ # @rbs &block: () -> String
106
+ def with_objects
107
+ @objects = true
108
+ yield
109
+ ensure
110
+ @objects = false
111
+ end
112
+
113
+ # @rbs type: String
114
+ def optional(type)
115
+ return type if type == "untyped" || type.end_with?("?")
116
+
117
+ type.match?(/\A[\w:]+\z/) || (type.start_with?("(") && type.end_with?(")")) ? "#{type}?" : "(#{type})?"
118
+ end
119
+
120
+ # @rbs node: Hash[String, untyped]
121
+ def type_of(node)
122
+ if (ref = node["$ref"])
123
+ raise Error, "#{@spec.path}: $ref #{ref} is not a local schema" unless ref.start_with?("#/components/schemas/")
124
+
125
+ name = ref.split("/").last
126
+ return nullable(Contract.interface_name(name), node) if @objects && object_schema?(@spec.deref(node))
127
+
128
+ return nullable(Contract.alias_name(name), node)
129
+ end
130
+
131
+ if (parts = node["allOf"])
132
+ return "untyped" if @objects
133
+
134
+ merged = parts.map { @spec.deref(_1) }
135
+ return nullable(record(merged.flat_map { (_1["properties"] || {}).to_a }.to_h, merged.flat_map { Array(_1["required"]) }), node)
136
+ end
137
+ if (parts = node["oneOf"] || node["anyOf"])
138
+ return nullable(union(parts.map { type_of(_1) }), node)
139
+ end
140
+
141
+ types = Array(node["type"])
142
+ null = types.include?("null")
143
+ types -= ["null"]
144
+ if (values = node["enum"])
145
+ literals = values.compact.map { _1.is_a?(String) ? _1.inspect : _1.to_s }
146
+ return nullable(union(literals), node, force: values.include?(nil) || null)
147
+ end
148
+
149
+ kinds = types.map do |type|
150
+ case type
151
+ when "string" then "String"
152
+ when "integer" then "Integer"
153
+ when "number" then "(Float | Integer)"
154
+ when "boolean" then "bool"
155
+ when "array" then "Array[#{type_of(node["items"] || {})}]"
156
+ when "object" then object(node)
157
+ else "untyped"
158
+ end
159
+ end
160
+ kinds = [object(node)] if kinds.empty? && (node["properties"] || node["additionalProperties"])
161
+ kinds = ["untyped"] if kinds.empty?
162
+ nullable(union(kinds), node, force: null)
163
+ end
164
+
165
+ # Inside an interface an object without a name has no interface to be,
166
+ # so it is untyped rather than a record its class could not satisfy.
167
+ # @rbs node: Hash[String, untyped]
168
+ def object(node)
169
+ return "untyped" if @objects
170
+
171
+ properties = node["properties"] || {}
172
+ extra = node["additionalProperties"]
173
+ return record(properties, Array(node["required"])) unless properties.empty?
174
+ return "Hash[String, #{type_of(extra)}]" if extra.is_a?(Hash) && !extra.empty?
175
+
176
+ "Hash[String, untyped]"
177
+ end
178
+
179
+ # @rbs properties: Hash[String, Hash[String, untyped]]
180
+ # @rbs required: Array[String]
181
+ def record(properties, required)
182
+ return "Hash[String, untyped]" if properties.empty?
183
+
184
+ fields = properties.map { |key, schema| "#{"?" unless required.include?(key)}#{key.inspect} => #{type_of(schema)}" }
185
+ "{ #{fields.join(", ")} }"
186
+ end
187
+
188
+ # @rbs types: Array[String]
189
+ def union(types)
190
+ types = types.uniq
191
+ types.size == 1 ? types.first.to_s : "(#{types.join(" | ")})"
192
+ end
193
+
194
+ # @rbs type: String
195
+ # @rbs node: Hash[String, untyped]
196
+ # @rbs force: untyped
197
+ def nullable(type, node, force: false)
198
+ return type unless force || node["nullable"] == true
199
+ return type if type == "untyped" || type.end_with?("?")
200
+
201
+ simple = type.match?(/\A[\w:]+\z/) || type.start_with?("(") && type.end_with?(")")
202
+ simple ? "#{type}?" : "(#{type})?"
203
+ end
204
+ end
205
+ end
@@ -0,0 +1,79 @@
1
+ # rbs_inline: enabled
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require "yaml"
6
+
7
+ module SchemaSplint
8
+ # Reads one OpenAPI document and answers questions about its schemas and
9
+ # operations. It resolves only local references (`#/components/...`): a
10
+ # reference into another file is refused, because guessing what that file
11
+ # holds would let the generated types drift from the real contract.
12
+ class Spec
13
+ attr_reader :path #: String
14
+
15
+ # @rbs path: String
16
+ def self.load(path)
17
+ text = File.read(path)
18
+ doc = path.end_with?(".json") ? JSON.parse(text) : YAML.safe_load(text, aliases: false)
19
+ raise Error, "#{path}: not an OpenAPI document" unless doc.is_a?(Hash) && doc["openapi"]
20
+
21
+ new(path, doc)
22
+ end
23
+
24
+ # @rbs path: String
25
+ # @rbs doc: Hash[String, untyped]
26
+ def initialize(path, doc)
27
+ @path = path
28
+ @doc = doc
29
+ end
30
+
31
+ # @rbs name: String
32
+ # @rbs return: Hash[String, untyped]?
33
+ def schema(name)
34
+ @doc.dig("components", "schemas", name)
35
+ end
36
+
37
+ #: () -> Array[String]
38
+ def schema_names
39
+ (@doc.dig("components", "schemas") || {}).keys
40
+ end
41
+
42
+ # @rbs id: String
43
+ # @rbs return: Operation?
44
+ def operation(id)
45
+ (@doc["paths"] || {}).each do |template, item|
46
+ item.each do |verb, op|
47
+ next unless op.is_a?(Hash) && op["operationId"] == id
48
+
49
+ params = Array(item["parameters"]) + Array(op["parameters"])
50
+ return Operation.new(id:, verb: verb.to_sym, template:, parameters: params.map { deref(_1) }, operation: op)
51
+ end
52
+ end
53
+ nil
54
+ end
55
+
56
+ #: () -> Array[String]
57
+ def operation_ids
58
+ (@doc["paths"] || {}).flat_map { |_, item| item.values.filter_map { _1["operationId"] if _1.is_a?(Hash) } }
59
+ end
60
+
61
+ # Follows `$ref` until a real object is reached.
62
+ # @rbs node: Hash[String, untyped]
63
+ # @rbs return: Hash[String, untyped]
64
+ def deref(node)
65
+ seen = [] #: Array[String]
66
+ while (ref = node["$ref"])
67
+ raise Error, "#{path}: $ref #{ref} points outside this document; bundle the spec first" unless ref.start_with?("#/")
68
+ raise Error, "#{path}: $ref cycle at #{ref}" if seen.include?(ref)
69
+
70
+ seen << ref
71
+ node = @doc.dig(*ref.delete_prefix("#/").split("/").map { _1.gsub("~1", "/").gsub("~0", "~") }) or
72
+ raise Error, "#{path}: $ref #{ref} points at nothing"
73
+ end
74
+ node
75
+ end
76
+
77
+ Operation = Data.define(:id, :verb, :template, :parameters, :operation)
78
+ end
79
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaSplint
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,18 @@
1
+ # rbs_inline: enabled
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "schema_splint/version"
5
+ require_relative "schema_splint/spec"
6
+ require_relative "schema_splint/contract"
7
+
8
+ # Lays an OpenAPI document over existing Ruby code as RBS, without writing any
9
+ # Ruby: Steep holds the code to the contract, and Conform holds the data to it.
10
+ module SchemaSplint
11
+ class Error < StandardError; end
12
+
13
+ # The Ruby name a spec name gets: shippedAt -> shipped_at.
14
+ # @rbs key: String
15
+ def self.snake(key)
16
+ key.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z\d])([A-Z])/, '\1_\2').tr("-", "_").downcase
17
+ end
18
+ end
@@ -0,0 +1,30 @@
1
+ # Generated from lib/schema_splint/cli.rb with RBS::Inline
2
+
3
+ module SchemaSplint
4
+ # The schema_splint command. `rbs` writes the contract as RBS (or, with --check,
5
+ # fails when the written file is stale); `conform` holds JSON files to it.
6
+ module CLI
7
+ USAGE: ::String
8
+
9
+ # @rbs argv: Array[String]
10
+ # @rbs out: IO
11
+ # @rbs err: IO
12
+ # @rbs return: Integer
13
+ def self.run: (Array[String] argv, ?out: untyped, ?err: IO) -> Integer
14
+
15
+ # Writes the spec as RBS. With --check it writes nothing and fails when
16
+ # the file differs, so a spec change reaches Steep through a reviewed diff.
17
+ # @rbs args: Array[String]
18
+ # @rbs out: IO
19
+ # @rbs err: IO
20
+ # @rbs return: Integer
21
+ def self.rbs: (Array[String] args, out: untyped, err: IO) -> Integer
22
+
23
+ # Checks JSON files (fixtures, recorded responses) against an RBS type.
24
+ # @rbs args: Array[String]
25
+ # @rbs out: IO
26
+ # @rbs err: IO
27
+ # @rbs return: Integer
28
+ def self.conform: (Array[String] args, out: untyped, err: IO) -> Integer
29
+ end
30
+ end
@@ -0,0 +1,90 @@
1
+ # Generated from lib/schema_splint/conform.rb with RBS::Inline
2
+
3
+ module SchemaSplint
4
+ # Holds a value from the wire against a type in RBS files, at runtime: the
5
+ # data side of the contract that Steep checks on the code side. It reports
6
+ # every place the value breaks the type, with its JSON path, so a fixture,
7
+ # a recorded response, or a live response in the shadow can be fixed or
8
+ # reported without guessing.
9
+ #
10
+ # Keys the type does not name are ignored, as a tolerant reader would.
11
+ class Conform
12
+ # One place a value breaks the type: its JSON path, the type it should
13
+ # have, and what it holds.
14
+ class Problem < Data
15
+ attr_reader path(): String
16
+
17
+ attr_reader expected(): String
18
+
19
+ attr_reader actual(): String
20
+
21
+ def self.new: (String path, String expected, String actual) -> instance
22
+ | (path: String, expected: String, actual: String) -> instance
23
+
24
+ def self.members: () -> [ :path, :expected, :actual ]
25
+
26
+ def members: () -> [ :path, :expected, :actual ]
27
+ end
28
+
29
+ class Problem
30
+ # : () -> String
31
+ def to_s: () -> String
32
+ end
33
+
34
+ # The value broke the contract.
35
+ class Broken < StandardError
36
+ attr_reader problems: Array[Problem]
37
+
38
+ # @rbs type: String
39
+ # @rbs problems: Array[Problem]
40
+ def initialize: (String type, Array[Problem] problems) -> untyped
41
+ end
42
+
43
+ # @rbs signatures: Array[String]
44
+ def initialize: (*untyped signatures) -> untyped
45
+
46
+ # @rbs value: untyped
47
+ # @rbs type: String
48
+ # @rbs return: Array[Problem]
49
+ def problems: (untyped value, String type) -> Array[Problem]
50
+
51
+ # @rbs value: untyped
52
+ # @rbs type: String
53
+ def check!: (untyped value, String type) -> untyped
54
+
55
+ private
56
+
57
+ # @rbs value: untyped
58
+ # @rbs type: untyped
59
+ # @rbs path: String
60
+ # @rbs found: Array[Problem]
61
+ def check: (untyped value, untyped type, String path, Array[Problem] found) -> untyped
62
+
63
+ # @rbs value: untyped
64
+ # @rbs type: RBS::Types::Record
65
+ # @rbs path: String
66
+ # @rbs found: Array[Problem]
67
+ def record: (untyped value, RBS::Types::Record type, String path, Array[Problem] found) -> untyped
68
+
69
+ # A body may come with string keys (JSON.parse), symbol keys
70
+ # (symbolize_names), or either (with_indifferent_access).
71
+ # @rbs hash: Hash[untyped, untyped]
72
+ # @rbs key: untyped
73
+ # @rbs return: [bool, untyped]
74
+ def lookup: (Hash[untyped, untyped] hash, untyped key) -> [ bool, untyped ]
75
+
76
+ # @rbs value: untyped
77
+ # @rbs type: RBS::Types::ClassInstance
78
+ # @rbs path: String
79
+ # @rbs found: Array[Problem]
80
+ def instance: (untyped value, RBS::Types::ClassInstance type, String path, Array[Problem] found) -> untyped
81
+
82
+ # @rbs value: untyped
83
+ # @rbs type: untyped
84
+ # @rbs path: String
85
+ def problems_of: (untyped value, untyped type, String path) -> untyped
86
+
87
+ # @rbs value: untyped
88
+ def describe: (untyped value) -> untyped
89
+ end
90
+ end
@@ -0,0 +1,75 @@
1
+ # Generated from lib/schema_splint/contract.rb with RBS::Inline
2
+
3
+ module SchemaSplint
4
+ # Writes an OpenAPI document as RBS: one type alias per schema, as records
5
+ # with the wire's own string keys, plus one alias per operation's success
6
+ # body. That RBS file is the contract in Ruby's terms. Steep holds the
7
+ # application's code to it, and Conform holds data (test fixtures, recorded
8
+ # responses, live responses in the shadow) to the very same file, so the two
9
+ # sides are checked against one thing.
10
+ #
11
+ # Formats stay strings (a date-time is a String on the wire); turning them
12
+ # into Time is the application's translation, not the contract's.
13
+ class Contract
14
+ # @rbs spec: Spec
15
+ # @rbs module_name: String
16
+ def initialize: (Spec spec, String module_name) -> untyped
17
+
18
+ # The name an alias gets: OrderPage -> order_page.
19
+ # @rbs name: String
20
+ def self.alias_name: (String name) -> untyped
21
+
22
+ # The interface name for a schema: Order -> _Order.
23
+ # @rbs name: String
24
+ def self.interface_name: (String name) -> untyped
25
+
26
+ # : () -> String
27
+ def to_rbs: () -> String
28
+
29
+ private
30
+
31
+ # Object-like values (a model built on method_missing, a hash with
32
+ # indifferent access) are typed by an interface, not a record: Steep holds
33
+ # a value to an interface by its methods, whatever its class, so the
34
+ # existing class needs no change and no RBS of its own. A reader per field
35
+ # and one `[]` overload per key, string or symbol, mean a name or a key the
36
+ # spec does not have is a type error.
37
+ # @rbs name: String
38
+ # @rbs schema: Hash[String, untyped]
39
+ # @rbs return: Array[String]
40
+ def interface: (String name, Hash[String, untyped] schema) -> Array[String]
41
+
42
+ # Names every object already answers; a field with one of these names is
43
+ # reached through `[]` only.
44
+ TAKEN_READERS: untyped
45
+
46
+ # @rbs schema: Hash[String, untyped]
47
+ def object_schema?: (Hash[String, untyped] schema) -> untyped
48
+
49
+ # @rbs &block: () -> String
50
+ def with_objects: () { () -> String } -> untyped
51
+
52
+ # @rbs type: String
53
+ def optional: (String type) -> untyped
54
+
55
+ # @rbs node: Hash[String, untyped]
56
+ def type_of: (Hash[String, untyped] node) -> untyped
57
+
58
+ # Inside an interface an object without a name has no interface to be,
59
+ # so it is untyped rather than a record its class could not satisfy.
60
+ # @rbs node: Hash[String, untyped]
61
+ def object: (Hash[String, untyped] node) -> untyped
62
+
63
+ # @rbs properties: Hash[String, Hash[String, untyped]]
64
+ # @rbs required: Array[String]
65
+ def record: (Hash[String, Hash[String, untyped]] properties, Array[String] required) -> untyped
66
+
67
+ # @rbs types: Array[String]
68
+ def union: (Array[String] types) -> untyped
69
+
70
+ # @rbs type: String
71
+ # @rbs node: Hash[String, untyped]
72
+ # @rbs force: untyped
73
+ def nullable: (String type, Hash[String, untyped] node, ?force: untyped) -> untyped
74
+ end
75
+ end
@@ -0,0 +1,56 @@
1
+ # Generated from lib/schema_splint/spec.rb with RBS::Inline
2
+
3
+ module SchemaSplint
4
+ # Reads one OpenAPI document and answers questions about its schemas and
5
+ # operations. It resolves only local references (`#/components/...`): a
6
+ # reference into another file is refused, because guessing what that file
7
+ # holds would let the generated types drift from the real contract.
8
+ class Spec
9
+ attr_reader path: String
10
+
11
+ # @rbs path: String
12
+ def self.load: (String path) -> untyped
13
+
14
+ # @rbs path: String
15
+ # @rbs doc: Hash[String, untyped]
16
+ def initialize: (String path, Hash[String, untyped] doc) -> untyped
17
+
18
+ # @rbs name: String
19
+ # @rbs return: Hash[String, untyped]?
20
+ def schema: (String name) -> Hash[String, untyped]?
21
+
22
+ # : () -> Array[String]
23
+ def schema_names: () -> Array[String]
24
+
25
+ # @rbs id: String
26
+ # @rbs return: Operation?
27
+ def operation: (String id) -> Operation?
28
+
29
+ # : () -> Array[String]
30
+ def operation_ids: () -> Array[String]
31
+
32
+ # Follows `$ref` until a real object is reached.
33
+ # @rbs node: Hash[String, untyped]
34
+ # @rbs return: Hash[String, untyped]
35
+ def deref: (Hash[String, untyped] node) -> Hash[String, untyped]
36
+
37
+ class Operation < Data
38
+ attr_reader id(): untyped
39
+
40
+ attr_reader verb(): untyped
41
+
42
+ attr_reader template(): untyped
43
+
44
+ attr_reader parameters(): untyped
45
+
46
+ attr_reader operation(): untyped
47
+
48
+ def self.new: (untyped id, untyped verb, untyped template, untyped parameters, untyped operation) -> instance
49
+ | (id: untyped, verb: untyped, template: untyped, parameters: untyped, operation: untyped) -> instance
50
+
51
+ def self.members: () -> [ :id, :verb, :template, :parameters, :operation ]
52
+
53
+ def members: () -> [ :id, :verb, :template, :parameters, :operation ]
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,12 @@
1
+ # Generated from lib/schema_splint.rb with RBS::Inline
2
+
3
+ # Lays an OpenAPI document over existing Ruby code as RBS, without writing any
4
+ # Ruby: Steep holds the code to the contract, and Conform holds the data to it.
5
+ module SchemaSplint
6
+ class Error < StandardError
7
+ end
8
+
9
+ # The Ruby name a spec name gets: shippedAt -> shipped_at.
10
+ # @rbs key: String
11
+ def self.snake: (String key) -> untyped
12
+ end
data/sig/version.rbs ADDED
@@ -0,0 +1,4 @@
1
+ # version.rb carries no rbs-inline comments: a change to it starts a release.
2
+ module SchemaSplint
3
+ VERSION: String
4
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: schema_splint
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - meganemura
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rbs
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '3.6'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '5'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '3.6'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '5'
32
+ executables:
33
+ - schema-splint
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - CHANGELOG.md
38
+ - LICENSE
39
+ - README.ja.md
40
+ - README.md
41
+ - exe/schema-splint
42
+ - lib/schema_splint.rb
43
+ - lib/schema_splint/cli.rb
44
+ - lib/schema_splint/conform.rb
45
+ - lib/schema_splint/contract.rb
46
+ - lib/schema_splint/spec.rb
47
+ - lib/schema_splint/version.rb
48
+ - sig/generated/schema_splint.rbs
49
+ - sig/generated/schema_splint/cli.rbs
50
+ - sig/generated/schema_splint/conform.rbs
51
+ - sig/generated/schema_splint/contract.rbs
52
+ - sig/generated/schema_splint/spec.rbs
53
+ - sig/version.rbs
54
+ homepage: https://github.com/meganemura/schema_splint
55
+ licenses:
56
+ - MIT
57
+ metadata:
58
+ source_code_uri: https://github.com/meganemura/schema_splint
59
+ changelog_uri: https://github.com/meganemura/schema_splint/blob/main/CHANGELOG.md
60
+ bug_tracker_uri: https://github.com/meganemura/schema_splint/issues
61
+ rubygems_mfa_required: 'true'
62
+ rdoc_options: []
63
+ require_paths:
64
+ - lib
65
+ required_ruby_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 3.3.0
70
+ required_rubygems_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ requirements: []
76
+ rubygems_version: 4.0.16
77
+ specification_version: 4
78
+ summary: Lay an OpenAPI document over existing Ruby code as RBS, so Steep holds the
79
+ code to it and Conform holds the data to it.
80
+ test_files: []