featurevisor-schemas 4.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.
@@ -0,0 +1,425 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Featurevisor
4
+ module Schemas
5
+ # A schema's handle, or a field's. Everything it does reads the current
6
+ # datafile when it is used, so one handle stays right for the life of an
7
+ # application, and handles are safe to share between threads.
8
+ class Handle
9
+ View = Struct.new(:values, :context, :start)
10
+ Check = Struct.new(:key, :message, :kind, :steps, :reads, :callable, :path)
11
+
12
+ # The schema's key, such as "signUp".
13
+ attr_reader :key
14
+ # The field's path in its schema, such as "address.city" or "items[].name", or empty for the schema.
15
+ attr_reader :path
16
+
17
+ def initialize(schemas, key, options = nil, steps = [], view = nil)
18
+ @schemas = schemas
19
+ @key = key
20
+ @options = options || {}
21
+ @form = Messages.form_messages(@options[:messages])
22
+ @steps = steps
23
+ @path = Paths.format_steps(steps)
24
+ @view = view
25
+ @mutex = Mutex.new
26
+ @handles = {}
27
+ @located = nil
28
+ @memo = nil
29
+ end
30
+
31
+ # Its own key in the object it sits in, such as "city", or empty for the schema itself.
32
+ def name
33
+ @steps.empty? ? "" : @steps.last.part
34
+ end
35
+
36
+ # Validates a value: hashes with string or symbol keys, arrays and
37
+ # primitives, or a Struct. Checks in code run in order, after the rules.
38
+ def validate(value, context: nil)
39
+ input = Values.plain(value)
40
+ # The rules run in the schema's evaluation, and checks in code after it.
41
+ run, located = evaluated(context) { |current| [current, apply_rules(input, current)] }
42
+ checks = located ? self.checks : []
43
+ return Result.new(value, run.issues.freeze) if checks.empty?
44
+
45
+ rule_issues = run.issues.dup
46
+ # In a view from the root, a field's checks see the whole input with the value in its place,
47
+ # as they would validating the schema, and the issues of the fields they read hold them back.
48
+ whole = root_view?
49
+ check_input = whole ? Views.place(@view.values, @steps, input) : input
50
+ read_issues = whole ? root_rule_issues(check_input, context) : rule_issues
51
+ info = CheckInfo.new(check_input, run.sources.info.context)
52
+ issues = rule_issues.dup
53
+ checks.each do |check|
54
+ # An issue in a field the check reads holds back every target, so it is looked for once.
55
+ next if check.reads.any? { |read| read_issues.any? { |issue| Paths.matches_steps?(issue.path, read) } }
56
+
57
+ expand(input, check.steps, [], []).each do |target_path, target|
58
+ next if rule_issues.any? { |issue| Paths.at_or_inside?(issue.path, target_path) }
59
+
60
+ code = begin
61
+ answer = check.callable.call(target, info)
62
+ passes = check.kind == :refine ? answer == true : found?(answer)
63
+ passes ? nil : (check.kind == :refine ? "refine" : "enum")
64
+ rescue StandardError => error
65
+ # A check that raises fails closed, and says why once per datafile.
66
+ store.check_failed(@key, check.key, check.path, error)
67
+ "refineError"
68
+ end
69
+ issues.concat(report_check(run, located, code, check, target_path)) if code
70
+ end
71
+ end
72
+ Result.new(value, issues.freeze)
73
+ end
74
+
75
+ def valid?(value, context: nil)
76
+ validate(value, context: context).valid?
77
+ end
78
+
79
+ # The value, or a ValidationError with the issues found.
80
+ def parse(value, context: nil)
81
+ result = validate(value, context: context)
82
+ raise ValidationError.new(@key, result.issues) unless result.valid?
83
+
84
+ value
85
+ end
86
+
87
+ # The handle for a field at a path, such as "address.city", "items[].name" or "labels.*".
88
+ def field(path)
89
+ handle(path) { Paths.parse(path) }
90
+ end
91
+
92
+ # The handle for one of an object's fields by its key, the same handle at
93
+ # gives when the key reads as itself, and its own for a key such as "a.b",
94
+ # "*" or "2024", which a path would read otherwise.
95
+ def child(key)
96
+ return field(key) if Paths.reads_as_key?(key)
97
+
98
+ handle("\u0000#{key}") { [Paths::Step.new(:key, key, nil)] }
99
+ end
100
+
101
+ # The same handle with an input, such as the values a form has so far: its
102
+ # members describe the rules with every mutation whose conditions match that
103
+ # input, and the context, applied at every depth.
104
+ def with_input(input, context: nil)
105
+ Handle.new(@schemas, @key, @options, @steps, View.new(Values.plain(input), context, @steps.length))
106
+ end
107
+
108
+ # The fields, relative to this handle, that its mutations' and issues' conditions read.
109
+ def reads
110
+ derive(:reads, []) { Views.reads_of(describe(nil)&.first, store) }
111
+ end
112
+
113
+ # Its annotations, over those of a schema its field references.
114
+ def annotations
115
+ derive(:annotations, {}) { |node| Derived.annotations(node, store) }
116
+ end
117
+
118
+ # The keys of an object's fields, in its order.
119
+ def field_keys
120
+ derive(:field_keys, []) { |node| Derived.field_keys(node, store) }
121
+ end
122
+
123
+ # An object's fields' handles, in its order, or none for any other value.
124
+ def fields
125
+ field_keys.map { |field| child(field) }
126
+ end
127
+
128
+ # The HTML validation attributes its rules imply, with required from the object it sits in.
129
+ def constraints
130
+ derive(:constraints, Constraints.new) { |node, required| Derived.constraints(node, required, store) }
131
+ end
132
+
133
+ # An object's fields' constraints by dot path, such as "address.city".
134
+ def field_constraints
135
+ derive(:field_constraints, {}) { |node| Derived.field_constraints(node, store) }
136
+ end
137
+
138
+ # The choices the field allows, in the order its rules list them, empty when it lists none.
139
+ def options
140
+ derive(:options, []) { |node| Derived.options(node, store) }
141
+ end
142
+
143
+ # An object's fields' choices by dot path, for the fields that list some.
144
+ def field_options
145
+ derive(:field_options, {}) { |node| Derived.field_options(node, store) }
146
+ end
147
+
148
+ # The schema's own choice for a value, or nil.
149
+ def option(value)
150
+ value = Values.plain(value)
151
+ options.find { |option| Values.same?(option.value, value) }
152
+ end
153
+
154
+ # What the rules say the field renders as, such as "text", "select" or "date-time", or nil for a oneOf of shapes.
155
+ def render_as
156
+ derive(:render_as, nil) { |node| Derived.render_as(node, store) }
157
+ end
158
+
159
+ # Whether an option source suggests choices for this field.
160
+ def searchable?
161
+ !source(:search).nil?
162
+ end
163
+
164
+ # Suggestions from the field's option source for a query, empty without a source that searches.
165
+ def search(query, context: nil)
166
+ source = source(:search)
167
+ return [] unless source
168
+
169
+ answer = source.search.call(query, CheckInfo.new(@view&.values, source_context(context)))
170
+ raise ArgumentError, "The search of option source #{source.key.inspect} must return a list" unless answer.is_a?(Array)
171
+
172
+ answer.map do |item|
173
+ item = Values.plain(item)
174
+ next SchemaOption.build(item, nil) unless item.is_a?(Hash)
175
+
176
+ # A hash without a value, such as { id, name }, would vanish from the list unseen.
177
+ raise ArgumentError, "The search of option source #{source.key.inspect} must return values, or hashes with a value" unless item.key?("value")
178
+
179
+ SchemaOption.build(item["value"], item)
180
+ end
181
+ end
182
+
183
+ # The choice for a value: the schema's own, or else the one the field's option source finds, or nil.
184
+ def lookup(value, context: nil)
185
+ own = option(value)
186
+ return own if own
187
+
188
+ source = source(:lookup)
189
+ return nil unless source
190
+
191
+ value = Values.plain(value)
192
+ answer = source.lookup.call(value, CheckInfo.new(@view&.values, source_context(context)))
193
+ return nil unless found?(answer)
194
+
195
+ answer = Values.plain(answer)
196
+ SchemaOption.build(value, answer.is_a?(Hash) ? answer : nil)
197
+ end
198
+
199
+ # Calls back when the datafile changes this handle's schema, until the returned lambda is called.
200
+ def subscribe(&listener)
201
+ version = store.version(@key)
202
+ @schemas.send(:listen) do
203
+ current = store.version(@key)
204
+ next if current == version
205
+
206
+ version = current
207
+ listener.call
208
+ end
209
+ end
210
+
211
+ def inspect
212
+ "#<Featurevisor::Schemas::Handle #{@key}#{@path.empty? ? "" : " at #{@path}"}>"
213
+ end
214
+
215
+ private
216
+
217
+ private :child, :field_keys
218
+
219
+ def store
220
+ @schemas.send(:store)
221
+ end
222
+
223
+ # Runs the block with a run in the schema's package evaluation, so modules see it and
224
+ # its conditions read the context they leave. A view's context comes first, with one
225
+ # given to the call merged over it.
226
+ def evaluated(given)
227
+ store.evaluate(@key, context_for(given)) do |context, match|
228
+ info = MessageInfo.new(-> { context })
229
+ yield Engine::Run.new(@key, Messages::Sources.new(@form, @schemas.send(:messages), info), @schemas.send(:translate), match)
230
+ end
231
+ end
232
+
233
+ # The context a call evaluates with: a view's, with one given to the call merged over it.
234
+ def context_for(given)
235
+ @view&.context ? @view.context.merge(given || {}) : given
236
+ end
237
+
238
+ # The context a source's function gets, evaluated as a validation is.
239
+ def source_context(given)
240
+ store.evaluate(@key, context_for(given)) { |context, _match| context }
241
+ end
242
+
243
+ # Where this handle's field sits in its schema, or nil when the datafile lacks
244
+ # it. In a view, the fields around it read the view's values, with the value
245
+ # being validated in the field's place. Its validator is the instance's, kept per node.
246
+ def field_for(value, run)
247
+ root = store.resolve(@key)
248
+ return nil unless root
249
+
250
+ node, validate = root
251
+ return [validate, node, Engine.lookup([], [])] if @steps.empty? && @view.nil?
252
+
253
+ if @view.nil?
254
+ # A field's place is kept until its schema changes, and its validator is the instance's.
255
+ version = store.version(@key)
256
+ cached = @mutex.synchronize { @located }
257
+ return [store.compile(cached[1]), cached[1], cached[2]] if cached && cached.first == version
258
+
259
+ field = Store.locate(store, node, @steps)
260
+ return nil unless field
261
+
262
+ cached = [version, field.node, Engine.lookup(field.mpath, field.scopes)]
263
+ @mutex.synchronize { @located = cached }
264
+ return [store.compile(field.node), field.node, cached[2]]
265
+ end
266
+ walk = Store::Walk.new(Views.place(@view.values, @steps[@view.start..], value), @view.start,
267
+ Views.adjuster(run.match, store))
268
+ field = Store.locate(store, node, @steps, [], [], walk)
269
+ field && [store.compile(field.node), field.node, Engine.lookup(field.mpath, field.scopes)]
270
+ end
271
+
272
+ def apply_rules(value, run)
273
+ located = field_for(value, run)
274
+ if located
275
+ located.first.call(value, run, Engine::Position.new([], located.last))
276
+ else
277
+ # A field the schema lacks is not a schema the datafile lacks.
278
+ store.report_missing(@key) unless store.entry(@key)
279
+ params = { schema: @key }
280
+ params[:field] = @path unless @steps.empty?
281
+ Engine.report(run, Engine::Position.new([], Engine.lookup([], [])), "schemaNotFound", params)
282
+ end
283
+ # Last, once mutations have named their issues.
284
+ Engine.translate(run)
285
+ located
286
+ end
287
+
288
+ def root_view?
289
+ !@steps.empty? && @view && @view.start.zero?
290
+ end
291
+
292
+ # Whether a source's step covers a handle's: [] every index, * every key.
293
+ def covers?(step, own)
294
+ case step.kind
295
+ when :items then %i[items index].include?(own.kind)
296
+ when :values then %i[values key].include?(own.kind)
297
+ when :key then own.kind == :key && own.key == step.key
298
+ else own.kind == :index && own.index == step.index
299
+ end
300
+ end
301
+
302
+ # The checks in code this handle runs, its sources' lookups first, then its refinements, its own or a field's share.
303
+ def checks
304
+ result = []
305
+ add = lambda do |key, message, kind, path, reads, callable|
306
+ owner_steps = Paths.parse(path)
307
+ parsed_reads = (reads || []).map { |read| Paths.parse(read) }
308
+ next result << Check.new(key, message, kind, owner_steps, parsed_reads, callable, path.to_s) if @steps.empty?
309
+ # A field's handle carries the checks at or inside it. One that reads other
310
+ # fields needs the whole input, which only a view from the schema's root holds.
311
+ next if (!parsed_reads.empty? && !root_view?) || owner_steps.length < @steps.length
312
+ next unless @steps.each_with_index.all? { |own, index| covers?(owner_steps[index], own) }
313
+
314
+ result << Check.new(key, message, kind, owner_steps[@steps.length..], parsed_reads, callable, path.to_s)
315
+ end
316
+ (@options[:option_sources] || []).each do |source|
317
+ add.call(source.key, source.message, :lookup, source.path, source.reads, source.lookup) if source.lookup
318
+ end
319
+ (@options[:refine] || []).each do |refinement|
320
+ add.call(refinement.key, refinement.message, :refine, refinement.path, refinement.reads, refinement.check)
321
+ end
322
+ result
323
+ end
324
+
325
+ # The concrete paths a check's steps reach in a value, with the value at each.
326
+ def expand(value, steps, path, found)
327
+ return found << [path, value] if steps.empty?
328
+
329
+ step = steps.first
330
+ rest = steps[1..]
331
+ case step.kind
332
+ when :items then value.each_with_index { |item, index| expand(item, rest, path + [index], found) } if value.is_a?(Array)
333
+ when :values then value.each { |key, item| expand(item, rest, path + [key], found) } if value.is_a?(Hash)
334
+ when :index then expand(value[step.index], rest, path + [step.index], found) if value.is_a?(Array) && step.index < value.length
335
+ else expand(value[step.key], rest, path + [step.key], found) if value.is_a?(Hash) && value.key?(step.key)
336
+ end
337
+ found
338
+ end
339
+
340
+ # Whether a lookup found a choice: anything but nil and false.
341
+ def found?(answer)
342
+ !answer.nil? && answer != false
343
+ end
344
+
345
+ def root_rule_issues(input, given)
346
+ root = store.resolve(@key)
347
+ return [] unless root
348
+
349
+ evaluated(given) do |run|
350
+ run.translate = nil
351
+ root.last.call(input, run, Engine::Position.new([], Engine.lookup([], [])))
352
+ run.issues
353
+ end
354
+ end
355
+
356
+ def report_check(run, located, code, check, path)
357
+ _validate, node, found = located
358
+ field = Store.locate(store, node, Paths.steps_of(path), found.mpath, found.scopes)
359
+ lookup = field ? Engine.lookup(field.mpath, field.scopes, Engine.title_of(field.node, store)) : Engine.lookup(found.mpath + path.map(&:to_s), found.scopes)
360
+ params = check.kind == :refine ? { refine: check.key } : { optionSource: check.key }
361
+ reporting = Engine::Run.new(run.schema, run.sources, run.translate, run.match)
362
+ Engine.report(reporting, Engine::Position.new(path, lookup), code, params, code == "refineError" ? nil : check.message)
363
+ Engine.translate(reporting)
364
+ reporting.issues
365
+ end
366
+
367
+ def source(function)
368
+ (@options[:option_sources] || []).find do |source|
369
+ next false unless source.public_send(function)
370
+
371
+ steps = Paths.parse(source.path)
372
+ exact = steps.length == @steps.length
373
+ holder = steps.length == @steps.length + 1 && steps[@steps.length].kind == :items
374
+ (exact || holder) && @steps.each_with_index.all? { |own, index| covers?(steps[index], own) }
375
+ end
376
+ end
377
+
378
+ def handle(id)
379
+ @mutex.synchronize do
380
+ @handles[id] ||= Handle.new(@schemas, @key, @options, @steps + yield, @view)
381
+ end
382
+ end
383
+
384
+ def describe(view)
385
+ root = store.resolve(@key)
386
+ return nil unless root
387
+
388
+ unless view
389
+ field = Store.locate(store, root.first, @steps)
390
+ return field && [field.node, field.required]
391
+ end
392
+ # A view's mutations match in the schema's evaluation, with the view's context.
393
+ store.evaluate(@key, view.context) do |_context, match|
394
+ adjust = Views.adjuster(match, store)
395
+ field = Store.locate(store, root.first, @steps, [], [], Store::Walk.new(view.values, view.start, adjust))
396
+ field && [Views.resolve_tree(field.node, field.value, adjust, store), field.required]
397
+ end
398
+ end
399
+
400
+ # What a member derives from the node, kept until the datafile changes. A view's is kept until the
401
+ # context or the sticky values change too, since its mutations' conditions read them.
402
+ def derive(kind, otherwise)
403
+ return otherwise unless store.entry(@key)
404
+
405
+ version = store.version(@key)
406
+ revision = store.api[:get_revision].call
407
+ context = @view && store.context_version
408
+ memo = nil
409
+ cached = @mutex.synchronize do
410
+ unless @memo && @memo[:version] == version && @memo[:revision] == revision && @memo[:context] == context
411
+ @memo = { version: version, revision: revision, context: context, made: {} }
412
+ end
413
+ memo = @memo
414
+ memo[:made].key?(kind) ? [memo[:made][kind]] : nil
415
+ end
416
+ return cached.first if cached
417
+
418
+ described = describe(@view)
419
+ made = yield(described&.first, described ? described.last : false)
420
+ @mutex.synchronize { memo[:made][kind] = made if @memo.equal?(memo) }
421
+ made
422
+ end
423
+ end
424
+ end
425
+ end