field_struct-json_schema 1.0.0.pre1

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: abbf12898d7fc2c1debea2c6a518f16a6dff51ce818985ea5c1b0df18521b6f0
4
+ data.tar.gz: 852f5f44de5d9f04ef425b3983afc59451f4988d4610f7fae82360d4a060e2b0
5
+ SHA512:
6
+ metadata.gz: 524476643bfdbc90a2289237f328130ecf7d4ff98dbad89d04c9a5f3bc49fb368add6c2dd4c4ceb4c5efbd56e9dba4723549603a0885f35bef90aea32413feb9
7
+ data.tar.gz: 35f179c0be40f39b52c5c5f9274d788b20cb68854d08f4ce3cc1757d02a346715f2ad7e508eca8745e88b5f074273da2d2f25025457a76914fbb3fdde43d9ab4
data/CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ### Changed
6
+
7
+ - `:big_decimal` maps to `number`, since field_struct's `to_json` now writes decimals as JSON numbers. A field
8
+ declared `json: :string` keeps the string form.
9
+
10
+ ### Added
11
+
12
+ - `generate(klass, freeze: true)` (and `to_json_schema(freeze: true)`) returns the cached schema itself, deep-frozen,
13
+ instead of a fresh copy, for callers that only read it.
14
+ - `generate(klass, decimals: :string)` describes every decimal as the string `as_json` writes, for callers that send
15
+ `as_json`. The default, `decimals: :to_json`, follows `to_json`.
16
+ - Requiring the adapter registers `json_schema:` with `FieldStruct.register_option`, so field_struct accepts the key and
17
+ refuses a value other than a Hash, `true` or `false` when the field is declared.
18
+ - `length:` maps to `minLength` and `maxLength` (an exclusive end gives one less, and `element:` options map inside
19
+ `items`). A `:binary` field gets only `maxLength`, since it counts bytes and JSON Schema counts characters.
20
+ - A required field declared `nullable: true` stays in `required` and also accepts `null`.
21
+ - `:hash, of:` maps to an object with the nullable value schema under `additionalProperties`.
22
+
23
+ ## 1.0.0.pre1
24
+
25
+ - First release: JSON Schema (draft 2020-12) generation for field_struct classes, `FieldStruct::JSONSchema.generate`, the opt-in
26
+ `Methods`, and `pattern_for`, the exact-or-nil Regexp to ECMA-262 translator with its ReDoS analysis, checked against Node.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adrian Madrid
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.md ADDED
@@ -0,0 +1,225 @@
1
+ # field_struct-json_schema
2
+
3
+ JSON Schema (draft 2020-12) for [field_struct](../../gems/field_struct) classes. It describes the JSON a struct writes
4
+ with `to_json` and reads with `from_json`, for API docs, validators in other languages, LLM tool parameters and
5
+ TypeScript generation. It also translates a Ruby `Regexp` into an ECMA-262 pattern that matches exactly the same strings,
6
+ or tells you it cannot.
7
+
8
+ It is not a validator, and its only runtime dependency is `field_struct`.
9
+
10
+ ## Install
11
+
12
+ ```ruby
13
+ gem 'field_struct-json_schema'
14
+ ```
15
+
16
+ ```ruby
17
+ require 'field_struct/json_schema'
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ ```ruby run
23
+ require 'field_struct/json_schema'
24
+
25
+ class Exhibit < FieldStruct::Base
26
+ required :name, :string
27
+ end
28
+
29
+ class Curator < FieldStruct::Base
30
+ include FieldStruct::JSONSchema::Methods # opt in to Curator.to_json_schema
31
+
32
+ required :given_name, :string
33
+ optional :access, :string, enum: %w[public staff], default: 'public'
34
+ optional :age, :integer, in: 0..150
35
+ optional :exhibits, :array, of: Exhibit
36
+ serialize :json, given_name: 'givenName'
37
+ end
38
+
39
+ schema = FieldStruct::JSONSchema.generate(Curator) # the same as Curator.to_json_schema
40
+ schema['title'] # => "Curator"
41
+ schema['required'] # => ["givenName"]
42
+ schema['properties']['age'] # => {"type"=>["integer", "null"], "minimum"=>0, "maximum"=>150}
43
+ schema['properties']['access']['default'] # => "public"
44
+ schema['$defs'].keys # => ["Exhibit"]
45
+ schema['properties']['exhibits']['items'] # => {"anyOf"=>[{"$ref"=>"#/$defs/Exhibit"}, {"type"=>"null"}]}
46
+ Curator.to_json_schema == schema # => true
47
+ ```
48
+
49
+ `generate` returns a fresh copy every time, so changing the result changes nothing else. `serialization:` picks the
50
+ `serialize` mapping whose names the schema uses (default `:json`, the one `to_json` writes).
51
+
52
+ ## What the schema says
53
+
54
+ The schema accepts exactly what a struct writes, for canonical JSON. A field is `required` in the schema when it is
55
+ required *and* has no default, because a default fills a missing key. An optional field also accepts `null`.
56
+
57
+ ```ruby run
58
+ class Dossier < FieldStruct::Base
59
+ required :label, :string
60
+ optional :alias_name, :string
61
+ optional :ratio, :float, in: 0.0...1.0
62
+ required :token, :string, sensitive: true, default: 'secret'
63
+ end
64
+
65
+ props = FieldStruct::JSONSchema.generate(Dossier)['properties']
66
+ props['label'] # => {"type"=>"string"}
67
+ props['alias_name'] # => {"type"=>["string", "null"]}
68
+ props['ratio'] # => {"type"=>["number", "null"], "minimum"=>0.0, "exclusiveMaximum"=>1.0}
69
+ props['token'] # => {"x-sensitive"=>true, "type"=>"string"}
70
+ FieldStruct::JSONSchema.generate(Dossier)['required'] # => ["label"]
71
+ ```
72
+
73
+ A sensitive field's default is left out of the published schema. A blank string counts as missing for the string types, so
74
+ an optional string with `enum:` or a `format:` also accepts a blank one:
75
+
76
+ ```ruby run
77
+ class Vase < FieldStruct::Base
78
+ optional :color, :string, enum: %w[red green]
79
+ end
80
+
81
+ color = FieldStruct::JSONSchema.generate(Vase)['properties']['color']
82
+ color['anyOf'][0] # => {"type"=>["string", "null"], "enum"=>["red", "green", nil]}
83
+ color['anyOf'][1] # => FieldStruct::JSONSchema::BLANK_STRING
84
+ ```
85
+
86
+ | Type | Schema |
87
+ |---|---|
88
+ | `:boolean` | `{"type":"boolean"}` |
89
+ | `:integer`, `:float` | `integer` / `number`, with `minimum`, `maximum` or `exclusiveMaximum` from `in:` (an Array becomes `enum`) |
90
+ | `:big_decimal` | `number`, as `to_json` writes it; a string matching `DECIMAL_PATTERN` for a field declared `json: :string`, or for every decimal under `generate(klass, decimals: :string)` |
91
+ | `:date`, `:time`, `:datetime` | a string with `format` `date` / `date-time` (only for the default or `:iso8601` format) |
92
+ | `:symbol` | a string, with `enum` when declared |
93
+ | `:string`, `:uuid`, `:url`, `:email`, `:binary` | a string; uuid is `format: uuid`, a Regexp `format:` becomes `pattern` |
94
+ | `:value` | `{}` |
95
+ | `:array`, unions, nested structs | `items`, `anyOf`, `$ref` into `$defs` |
96
+ | `:hash, of:` | `{"type":"object"}` with the value schema under `additionalProperties` |
97
+ | `length:` on a string type | `minLength` and `maxLength`; `:binary` counts bytes, so it gets `maxLength` only |
98
+ | `nullable: true` on a required field | stays in `required`, and its `type` also takes `"null"` |
99
+
100
+ The schema leaves out `in:` on dates, times and decimals, `max_items:`, `strict:`, `base:` and `round:`; the struct still
101
+ enforces them. Rules are never approximated.
102
+
103
+ ## Nested structs and recursion
104
+
105
+ A named nested struct is defined once under `$defs` and referenced; the root class is referenced as `#`. An anonymous
106
+ struct is inlined.
107
+
108
+ ```ruby run
109
+ class Node < FieldStruct::Base
110
+ required :value, :integer
111
+ optional :next_node, Node
112
+ end
113
+
114
+ tree = FieldStruct::JSONSchema.generate(Node)
115
+ tree['properties']['next_node'] # => {"anyOf"=>[{"$ref"=>"#"}, {"type"=>"null"}]}
116
+ tree.key?('$defs') # => false
117
+ ```
118
+
119
+ ## Overrides and custom types
120
+
121
+ A field's `json_schema:` option (a Hash, `true` or `false`) replaces the derived schema; a custom type can define a
122
+ `json_schema` method for the same purpose. Without either, a custom type is unconstrained and carries
123
+ `x-ruby-type`. Requiring the adapter registers `json_schema:` with `FieldStruct.register_option`, so require it before
124
+ the classes that use the option; any other value is refused when the field is declared.
125
+
126
+ ```ruby run
127
+ class Hosted < FieldStruct::Base
128
+ required :id, :string, json_schema: { 'type' => 'string', 'minLength' => 3 }
129
+ optional :extra, :value, json_schema: false
130
+ end
131
+
132
+ props = FieldStruct::JSONSchema.generate(Hosted)['properties']
133
+ props['id'] # => {"type"=>"string", "minLength"=>3}
134
+ props['extra'] # => {"anyOf"=>[{"not"=>{}}, {"type"=>"null"}]}
135
+ ```
136
+
137
+ A wrong override raises `ArgumentError` naming the class and field.
138
+
139
+ ## Regexps: `pattern_for`
140
+
141
+ `pattern_for(regexp)` returns an ECMA-262 pattern that matches the same strings under the `u` flag (what JSON Schema
142
+ validators use), or `nil`. It is exact or nil: when in doubt it returns nil, and the generator then writes the Ruby
143
+ source as an `x-ruby-pattern` annotation that no validator checks.
144
+
145
+ ```ruby run
146
+ FieldStruct::JSONSchema.pattern_for(/\A\d+\.\d+\z/) # => "^\\d+\\.\\d+$"
147
+ FieldStruct::JSONSchema.pattern_for(/\A[a-z]{2}\z/i) # => "^[a-zA-ZſK]{2}$"
148
+ FieldStruct::JSONSchema.pattern_for(/\Aa.c\z/) # => "^a[^\\n]c$"
149
+ FieldStruct::JSONSchema.pattern_for(/\bword\b/) # => nil
150
+ ```
151
+
152
+ What changes meaning between the engines is rewritten (`\A` and `\z` become `^` and `$`, `.` stops at a newline, `\s` is
153
+ the ASCII set, Ruby's `^` and `$` become lookarounds, `/i` is folded into character classes including the two extra
154
+ characters Ruby folds, U+017F and U+212A). What has no equivalent returns nil: `\p{..}`, backreferences, atomic and
155
+ possessive forms, `\b`, inline options, `x` and `m` flags, POSIX classes and the like.
156
+
157
+ A pattern a backtracking JavaScript engine could take exponential or high-polynomial time on is refused too, though Ruby
158
+ itself is safe:
159
+
160
+ ```ruby run
161
+ FieldStruct::JSONSchema.pattern_for(/\A(a+)+\z/) # => nil
162
+ FieldStruct::JSONSchema.pattern_for(/\A\d*\d*\d*x\z/) # => nil
163
+ FieldStruct::JSONSchema.pattern_for(/\A\d*\d*x\z/) # => "^\\d*\\d*x$"
164
+ FieldStruct::JSONSchema.pattern_for(/\A[^@\s]+@[^@\s]+\z/) # => "^[^@\\t\\n\\v\\f\\r ]+@[^@\\t\\n\\v\\f\\r ]+$"
165
+ ```
166
+
167
+ The check is conservative (a refusal may be unnecessary, an acceptance is never unsafe). In a struct, a `format:` Regexp
168
+ becomes `pattern` when translatable and `x-ruby-pattern` otherwise:
169
+
170
+ ```ruby run
171
+ class Tablet < FieldStruct::Base
172
+ required :code, :string, format: /\A[A-Z]{3}-\d{4}\z/
173
+ required :name, :string, format: /\A\p{L}+\z/
174
+ end
175
+
176
+ props = FieldStruct::JSONSchema.generate(Tablet)['properties']
177
+ props['code'] # => {"type"=>"string", "pattern"=>"^[A-Z]{3}-\\d{4}$"}
178
+ props['name'] # => {"type"=>"string", "x-ruby-pattern"=>"\\A\\p{L}+\\z"}
179
+ ```
180
+
181
+ The promise is checked against Node's RegExp on every supported Ruby (see Development).
182
+
183
+ ## Caching
184
+
185
+ `generate` builds once per class and serialization, and rebuilds when a class's fields, `serialize` mapping, name or
186
+ `unknown_attributes` change (not when an `enum:` Array or an override Hash is mutated in place: redeclare the field).
187
+ A schema that asked a custom type's `json_schema` hook is never cached. `FieldStruct::JSONSchema.clear_cache` empties
188
+ the cache, which holds classes alive: call it on code reload.
189
+
190
+ When you only read the schema (to validate with it, or to list it), `freeze: true` skips the copy and hands back the
191
+ cached schema itself. It's deep-frozen, so changing it raises `FrozenError`:
192
+
193
+ ```ruby run
194
+ shared = FieldStruct::JSONSchema.generate(Curator, freeze: true)
195
+ shared.frozen? # => true
196
+ shared.equal?(FieldStruct::JSONSchema.generate(Curator, freeze: true)) # => true
197
+ Curator.to_json_schema(freeze: true).equal?(shared) # => true
198
+ ```
199
+
200
+ A schema that asked a hook is still built for every call: `freeze: true` freezes it, but it's a new object each time.
201
+
202
+ ## Development
203
+
204
+ ```sh
205
+ bundle exec rake # specs + RuboCop
206
+ bundle exec rake release:check # also doctests, YARD, signature guards (sig/ is generated by Sord)
207
+ bundle exec rake differential # pattern_for against Node's RegExp (needs node)
208
+ bundle exec rake sigs:generate # after changing a YARD comment
209
+ ```
210
+
211
+ `spec/differential/` holds the corpus of about 1200 Regexps and a pool of sample strings. Ruby answers are computed on the
212
+ running Ruby, never stored. When a bug report shows a wrongly translated Regexp, add it to `corpus.json` with the strings
213
+ that disagree.
214
+
215
+ The type signatures are generated from the YARD comments by Sord. The internal files are excluded in `.yardopts`, so only
216
+ the public API is in `sig/`. Types of field_struct that the public API mentions (for example `FieldStruct::Base`) resolve
217
+ because `support/sord_gen.rb` feeds field_struct's own `sig/` to Sord's resolver.
218
+
219
+ ## License
220
+
221
+ MIT.
222
+
223
+ ## Docs
224
+
225
+ The guide on the docs site, with every example run in CI: https://gliders-rb.github.io/adapters/json-schema/
@@ -0,0 +1,195 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module JSONSchema
5
+ # Walks a struct class with +FieldStruct::Introspection+ and builds its schema (JS-B1..B17). One Builder builds
6
+ # one document and is thrown away.
7
+ class Builder
8
+ # What a build produced.
9
+ #
10
+ # @!attribute [r] schema
11
+ # @return [::Hash{::String=>::Object}] the document
12
+ # @!attribute [r] stamps
13
+ # @return [::Hash{::Class=>::Array<::Object>}] the stamp of every class the document covers
14
+ # @!attribute [r] hooked
15
+ # @return [::Boolean] whether a type's +json_schema+ hook was asked
16
+ Result = Struct.new(:schema, :stamps, :hooked)
17
+
18
+ # Where in the struct tree a field sits, for error messages: +Holder#inner.x+.
19
+ Spot = Struct.new(:prefix, :path) do
20
+ # @return [::String]
21
+ def label
22
+ "#{prefix}#{path.join('.')}"
23
+ end
24
+
25
+ # @param name [::Symbol]
26
+ # @return [Spot]
27
+ def down(name)
28
+ Spot.new(prefix, [*path, name])
29
+ end
30
+ end
31
+ private_constant :Spot
32
+
33
+ # @param root [::Class] a +FieldStruct::Base+ subclass
34
+ # @param serialization [::Symbol]
35
+ # @param decimals [::Symbol] +:to_json+, or +:string+ for every decimal as its +as_json+ String (JS-B24)
36
+ def initialize(root, serialization, decimals = :to_json)
37
+ @root = root
38
+ @serialization = serialization
39
+ @decimals = decimals
40
+ @stamps = {}
41
+ @hooked = false
42
+ @defs = {}
43
+ @inlining = [root]
44
+ end
45
+
46
+ # @return [Result]
47
+ def build
48
+ body = object_schema(@root, Spot.new("#{label_of(@root)}#", []))
49
+ head = { '$schema' => DRAFT }
50
+ head['title'] = @root.name if Introspection.named?(@root)
51
+ document = head.merge(body)
52
+ document['$defs'] = @defs unless @defs.empty?
53
+ Result.new(document, @stamps, @hooked)
54
+ end
55
+
56
+ private
57
+
58
+ def label_of(klass)
59
+ klass.name || klass.inspect
60
+ end
61
+
62
+ # The object schema of +klass+ without $schema/title.
63
+ def object_schema(klass, spot)
64
+ @stamps[klass] ||= Stamp.of(klass, @serialization)
65
+ properties = {}
66
+ required = []
67
+ Introspection.properties(klass, serialization: @serialization).each do |prop|
68
+ properties[prop.key] = property_schema(prop.field, prop.node, spot.down(prop.field.name))
69
+ required << prop.key if prop.field.required? && prop.field.default.nil?
70
+ end
71
+ schema = { 'type' => 'object', 'properties' => properties }
72
+ schema['required'] = required unless required.empty?
73
+ schema['additionalProperties'] = false if klass.unknown_attributes == :raise
74
+ schema
75
+ end
76
+
77
+ def property_schema(field, node, spot)
78
+ core = field_override(field, spot) || node_schema(node, spot)
79
+ core = Nullable.field(core, field.type_instance) if !field.required? || field.nullable?
80
+ annotations(field).merge(core)
81
+ end
82
+
83
+ def annotations(field)
84
+ notes = {}
85
+ notes['description'] = field.description if field.description
86
+ default = Defaults.for(field)
87
+ notes['default'] = default unless default.equal?(Defaults::NONE) || field.sensitive?
88
+ notes['x-sensitive'] = true if field.sensitive?
89
+ notes
90
+ end
91
+
92
+ # The field's own json_schema: option, or nil when it has none.
93
+ def field_override(field, spot)
94
+ value = field.options[:json_schema]
95
+ return nil if value.nil?
96
+
97
+ Override.normalize(value) ||
98
+ raise(::ArgumentError, "FieldStruct::JSONSchema.generate: the json_schema: option of #{spot.label} " \
99
+ "must be a Hash or a boolean, got #{value.inspect}")
100
+ end
101
+
102
+ # The type's json_schema hook, or nil when the type has none or the hook declines.
103
+ def hook_schema(type, spot)
104
+ return nil unless type.respond_to?(:json_schema)
105
+
106
+ @hooked = true
107
+ name = "#{type.class.name || type.class.inspect}#json_schema"
108
+ value = call_hook(type, name, spot)
109
+ return nil if value.nil?
110
+
111
+ Override.normalize(value) ||
112
+ raise(::ArgumentError, "FieldStruct::JSONSchema.generate: #{name} (for #{spot.label}) " \
113
+ "must be a Hash or a boolean, got #{value.inspect}")
114
+ end
115
+
116
+ def call_hook(type, name, spot)
117
+ type.json_schema
118
+ rescue ::StandardError => e
119
+ raise ::ArgumentError, "FieldStruct::JSONSchema.generate: #{name} raised #{e.class} (for #{spot.label}): #{e.message}"
120
+ end
121
+
122
+ def node_schema(node, spot)
123
+ hook_schema(node.type, spot) || plain_node_schema(node, spot)
124
+ end
125
+
126
+ def plain_node_schema(node, spot)
127
+ case node
128
+ when Introspection::ArrayNode then array_schema(node, spot)
129
+ when Introspection::MapNode then map_schema(node, spot)
130
+ when Introspection::UnionNode then union_schema(node, spot)
131
+ when Introspection::StructNode then struct_schema(node.klass, spot)
132
+ else Scalar.call(node.type, scalar_options(node))
133
+ end
134
+ end
135
+
136
+ # Under +decimals: :string+ a decimal is described as the String +as_json+ writes, whatever its +json:+.
137
+ def scalar_options(node)
138
+ options = node.options
139
+ return options unless @decimals == :string && node.type.is_a?(Types::BigDecimal)
140
+
141
+ options.merge(json: :string)
142
+ end
143
+
144
+ def array_schema(node, spot)
145
+ element = node.element
146
+ return { 'type' => 'array' } if element.nil?
147
+
148
+ { 'type' => 'array', 'items' => Nullable.call(node_schema(element, spot)) }
149
+ end
150
+
151
+ # A String-keyed map: the value schema, nullable, under additionalProperties (JS-B11a).
152
+ def map_schema(node, spot)
153
+ element = node.element
154
+ return { 'type' => 'object' } if element.nil?
155
+
156
+ { 'type' => 'object', 'additionalProperties' => Nullable.call(node_schema(element, spot)) }
157
+ end
158
+
159
+ def union_schema(node, spot)
160
+ members = node.members.map { |member| node_schema(member, spot) }.uniq
161
+ members.any?(&:empty?) ? {} : { 'anyOf' => members }
162
+ end
163
+
164
+ def struct_schema(klass, spot)
165
+ return { '$ref' => '#' } if klass.equal?(@root) && Introspection.named?(klass)
166
+ return definition_ref(klass) if Introspection.named?(klass)
167
+
168
+ inline_struct(klass, spot)
169
+ end
170
+
171
+ def definition_ref(klass)
172
+ name = klass.name
173
+ unless @defs.key?(name)
174
+ @defs[name] = nil
175
+ @defs[name] = { 'title' => name }.merge(object_schema(klass, Spot.new("#{name}#", [])))
176
+ end
177
+ { '$ref' => "#/$defs/#{name}" }
178
+ end
179
+
180
+ def inline_struct(klass, spot)
181
+ if @inlining.include?(klass)
182
+ raise ::ArgumentError, "FieldStruct::JSONSchema.generate(#{label_of(@root)}) cannot describe a recursive anonymous struct; " \
183
+ 'assign it to a constant'
184
+ end
185
+
186
+ @inlining.push(klass)
187
+ begin
188
+ object_schema(klass, spot)
189
+ ensure
190
+ @inlining.pop
191
+ end
192
+ end
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module JSONSchema
5
+ # The schema cache (JS-B40..B43): one entry per (class, serialization, decimals form), each valid while the stamps of every class
6
+ # it covers still match. A schema that asked a type hook is never stored (JS-I7).
7
+ class Cache
8
+ # A stored schema (deep-frozen) and the stamps it was built under.
9
+ Entry = Struct.new(:schema, :stamps) do
10
+ # @param serialization [::Symbol]
11
+ # @return [::Boolean]
12
+ def fresh?(serialization)
13
+ stamps.all? { |klass, stamp| stamp.current?(klass, serialization) }
14
+ end
15
+ end
16
+ private_constant :Entry
17
+
18
+ def initialize
19
+ @mutex = Mutex.new
20
+ @entries = {}
21
+ end
22
+
23
+ # @param klass [::Class]
24
+ # @param serialization [::Symbol]
25
+ # @param decimals [::Symbol] +:to_json+ or +:string+
26
+ # @param freeze [Boolean] return the deep-frozen schema itself instead of a fresh copy (JS-B44)
27
+ # @return [::Hash{::String=>::Object}]
28
+ def fetch(klass, serialization, decimals = :to_json, freeze: false)
29
+ key = [klass, serialization, decimals]
30
+ entry = @mutex.synchronize { @entries[key] }
31
+ return hand_out(entry.schema, freeze) if entry&.fresh?(serialization)
32
+
33
+ result = Builder.new(klass, serialization, decimals).build
34
+ frozen = Copy.deep(result.schema, freeze: true)
35
+ @mutex.synchronize { result.hooked ? @entries.delete(key) : @entries[key] = Entry.new(frozen, result.stamps) }
36
+ hand_out(frozen, freeze)
37
+ end
38
+
39
+ # @return [void]
40
+ def clear
41
+ @mutex.synchronize { @entries.clear }
42
+ end
43
+
44
+ private
45
+
46
+ def hand_out(frozen, freeze)
47
+ freeze ? frozen : Copy.fresh(frozen)
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module JSONSchema
5
+ # Deep copies of schema values: Hashes, Arrays and Strings are copied, everything else is shared (immutable).
6
+ module Copy
7
+ module_function
8
+
9
+ # @param value [::Object]
10
+ # @param freeze [::Boolean] whether the copy is frozen all the way down
11
+ # @return [::Object]
12
+ def deep(value, freeze: false)
13
+ copy = case value
14
+ when ::Hash then value.to_h { |key, item| [deep(key, freeze: freeze), deep(item, freeze: freeze)] }
15
+ when ::Array then value.map { |item| deep(item, freeze: freeze) }
16
+ when ::String then value.dup
17
+ else value
18
+ end
19
+ freeze ? copy.freeze : copy
20
+ end
21
+
22
+ # A fresh, mutable copy of a cached schema: every Hash, Array and String is new, everything else is shared
23
+ # (immutable). Hash keys are shared as well: a String key is frozen by the Hash that holds it, so nothing
24
+ # reachable through a key can be changed.
25
+ #
26
+ # @param value [::Object] JSON-shaped data
27
+ # @return [::Object]
28
+ def fresh(value)
29
+ case value
30
+ when ::Hash then value.transform_values { |item| fresh(item) }
31
+ when ::Array then value.map { |item| fresh(item) }
32
+ when ::String then value.dup
33
+ else value
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module JSONSchema
5
+ # Which field defaults are already what +to_json+ writes (JS-B5), decided without coercing.
6
+ module Defaults
7
+ NONE = Object.new.freeze
8
+ T = FieldStruct::Types
9
+ CHECKS = [
10
+ [T::Boolean, :boolean], [T::Integer, :integer], [T::Float, :float],
11
+ [T::Symbol, :symbol], [T::String, :string], [T::Value, :value]
12
+ ].freeze
13
+ private_constant :CHECKS
14
+
15
+ module_function
16
+
17
+ # @param field [FieldStruct::Field]
18
+ # @return [::Object] the JSON value of the default, or {NONE}
19
+ def for(field)
20
+ value = field.default
21
+ return NONE if value.nil?
22
+
23
+ _, check = CHECKS.find { |klass, _| field.type_instance.is_a?(klass) }
24
+ check ? send(check, value) : NONE
25
+ end
26
+
27
+ # @return [::Object]
28
+ def boolean(value) = [true, false].include?(value) ? value : NONE
29
+
30
+ # @return [::Object]
31
+ def integer(value) = value.is_a?(::Integer) ? value : NONE
32
+
33
+ # @return [::Object]
34
+ def symbol(value) = value.is_a?(::Symbol) ? value.to_s : NONE
35
+
36
+ # @return [::Object]
37
+ def string(value) = value.is_a?(::String) ? value : NONE
38
+
39
+ # @return [::Object]
40
+ def value(value) = json_value?(value) ? value : NONE
41
+
42
+ # An Integer becomes a Float; only a finite Float is kept.
43
+ #
44
+ # @return [::Object]
45
+ def float(value)
46
+ return value.to_f if value.is_a?(::Integer)
47
+
48
+ value.is_a?(::Float) && value.finite? ? value : NONE
49
+ end
50
+
51
+ # A JSON value: String, Integer, finite Float, true, false, nil, or an Array / String-keyed Hash of them.
52
+ #
53
+ # @param value [::Object]
54
+ # @return [::Boolean]
55
+ def json_value?(value)
56
+ case value
57
+ when nil, true, false, ::String, ::Integer then true
58
+ when ::Float then value.finite?
59
+ when ::Array then value.all? { |item| json_value?(item) }
60
+ when ::Hash then json_object?(value)
61
+ else false
62
+ end
63
+ end
64
+
65
+ # @param value [::Hash]
66
+ # @return [::Boolean]
67
+ def json_object?(value)
68
+ value.all? { |key, item| key.is_a?(::String) && json_value?(item) }
69
+ end
70
+ end
71
+ end
72
+ end