nukadoko 0.4.0 → 0.6.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 +4 -4
- data/CHANGELOG.md +78 -0
- data/README.ja.md +12 -2
- data/README.md +10 -3
- data/lib/nukadoko/check.rb +15 -4
- data/lib/nukadoko/cli.rb +10 -4
- data/lib/nukadoko/command.rb +22 -4
- data/lib/nukadoko/error_frames.rb +44 -0
- data/lib/nukadoko/features.rb +3 -1
- data/lib/nukadoko/fixtures.rb +108 -7
- data/lib/nukadoko/judgment_file.rb +21 -0
- data/lib/nukadoko/judgments.rb +30 -0
- data/lib/nukadoko/run.rb +126 -27
- data/lib/nukadoko/run_record.rb +9 -5
- data/lib/nukadoko/schema.rb +165 -37
- data/lib/nukadoko/step_fixtures.rb +225 -0
- data/lib/nukadoko/summary.rb +4 -1
- data/lib/nukadoko/verdict.rb +18 -1
- data/lib/nukadoko/version.rb +1 -1
- data/lib/nukadoko/vocabulary.rb +1 -1
- data/lib/nukadoko.rb +2 -0
- data/llms.txt +3 -2
- data/sig/generated/nukadoko/command.rbs +13 -4
- data/sig/generated/nukadoko/error_frames.rbs +24 -0
- data/sig/generated/nukadoko/fixtures.rbs +38 -2
- data/sig/generated/nukadoko/judgment_file.rbs +6 -0
- data/sig/generated/nukadoko/judgments.rbs +10 -0
- data/sig/generated/nukadoko/run.rbs +25 -4
- data/sig/generated/nukadoko/schema.rbs +91 -27
- data/sig/generated/nukadoko/step_fixtures.rbs +129 -0
- data/sig/generated/nukadoko/verdict.rbs +8 -0
- data/skills/nukadoko/SKILL.md +1 -1
- data/skills/nukadoko/references/done.md +22 -0
- data/skills/nukadoko/references/judgments.md +6 -0
- data/skills/nukadoko/references/ruby.md +80 -0
- metadata +6 -1
data/lib/nukadoko/judgments.rb
CHANGED
|
@@ -184,6 +184,36 @@ module Nukadoko
|
|
|
184
184
|
end
|
|
185
185
|
end
|
|
186
186
|
|
|
187
|
+
# Under --base, each judgment a read cites gains `in_base`: true when
|
|
188
|
+
# the base's file already held that very judgment (the same claim,
|
|
189
|
+
# value, verdict, judge, reason, and time), false when the change
|
|
190
|
+
# brought it. A change cannot be trusted to judge its own output any
|
|
191
|
+
# more than to rewrite its own Thens, and the old world covers only
|
|
192
|
+
# the Thens. `base_entries_of` answers nil for a feature whose base
|
|
193
|
+
# file could not be read, and its reads stay unmarked.
|
|
194
|
+
#: (Array[Hash[Symbol, untyped]], ^(String) -> Array[Hash[Symbol, untyped]]?) -> Array[Hash[Symbol, untyped]]
|
|
195
|
+
def with_base_judgments(rows, base_entries_of)
|
|
196
|
+
rows.map do |row|
|
|
197
|
+
judgment = row[:judgment]
|
|
198
|
+
next row unless judgment && judgment[:reads].any? { _1[:judgment] }
|
|
199
|
+
|
|
200
|
+
entries = base_entries_of.(row[:feature])
|
|
201
|
+
next row unless entries
|
|
202
|
+
|
|
203
|
+
reads = judgment[:reads].map do |read|
|
|
204
|
+
cited = read[:judgment]
|
|
205
|
+
next read unless cited
|
|
206
|
+
|
|
207
|
+
held = entries.any? do |entry|
|
|
208
|
+
entry[:criterion] == row[:name] && entry[:then] == read[:step] && entry[:claim] == read[:claim] &&
|
|
209
|
+
%i[value_digest verdict by because at].all? { entry[_1] == cited[_1] }
|
|
210
|
+
end
|
|
211
|
+
{ **read, judgment: { **cited, in_base: held } }
|
|
212
|
+
end
|
|
213
|
+
{ **row, judgment: { **judgment, reads: reads } }
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
|
|
187
217
|
#: (Array[Hash[Symbol, untyped]]) -> bool
|
|
188
218
|
def open?(rows) = rows.any? { _1[:judgment] && _1[:judgment][:state] != "judged" }
|
|
189
219
|
|
data/lib/nukadoko/run.rb
CHANGED
|
@@ -360,6 +360,14 @@ module Nukadoko
|
|
|
360
360
|
if @base && changed.nil?
|
|
361
361
|
warnings << { severity: "warning", code: "judgments-not-compared", message: "the judgment files were not compared with the base: git did not answer" }
|
|
362
362
|
end
|
|
363
|
+
# And per row, which judgment the change brought: a row that stands
|
|
364
|
+
# on a judgment the change made of its own output.
|
|
365
|
+
if (base = @base) && changed
|
|
366
|
+
at_base = {} #: Hash[String, Array[Hash[Symbol, untyped]]?]
|
|
367
|
+
rows = Judgments.with_base_judgments(rows, lambda do |feature|
|
|
368
|
+
at_base.fetch(feature) { at_base[feature] = JudgmentFile.at_commit(@project, base.commit, feature)&.dig(:entries) }
|
|
369
|
+
end)
|
|
370
|
+
end
|
|
363
371
|
judged += Judgments.findings(rows, @id) + problems
|
|
364
372
|
{ run_id: @id, run_dir: File.join(".nukadoko/runs", @id), started_at: @started_at, finished_at: now, commit: @commit,
|
|
365
373
|
environments: @environments.map { environment_entry(_1) }, worlds: @world_entries, order: @order,
|
|
@@ -718,20 +726,22 @@ module Nukadoko
|
|
|
718
726
|
@browser&.step = { step_record_id: record[:step_record_id], step: record[:step], line: at_line }
|
|
719
727
|
@browser&.begin_step
|
|
720
728
|
Trace.within(boundary) do
|
|
721
|
-
fixtures, finish = build_fixtures(step, dir, log, world, record)
|
|
729
|
+
fixtures, finish = build_fixtures(step, dir, log, world, record, results)
|
|
722
730
|
HttpRecording.collect(log) do
|
|
723
731
|
Processes.collect(processes) { RedactedOutput.around(secrets) { body(step, fixtures, args, [then_line, at_line], record, results, origins, texts) } }
|
|
724
732
|
end
|
|
725
733
|
end
|
|
726
|
-
record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && fixtures[:page] && record[:observation] != "unobserved"
|
|
734
|
+
record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && (fixtures[:page] || fixtures[:context]) && record[:observation] != "unobserved"
|
|
727
735
|
record[:status] ||= "passed"
|
|
728
736
|
rescue StandardError => e
|
|
729
737
|
record.merge!(status: "failed", outcome: :broke, error: e.message)
|
|
730
738
|
record[:error_kind] ||= "step_error"
|
|
739
|
+
record[:error_at] = ErrorFrames.of(e, @project).map { redact(_1) } if record[:error_kind] == "step_error"
|
|
731
740
|
ensure
|
|
732
741
|
@browser&.step = nil
|
|
733
742
|
finish&.call
|
|
734
|
-
log.concat(
|
|
743
|
+
log.concat(@request_log.log) if @request_log
|
|
744
|
+
@request_log = nil
|
|
735
745
|
# A world at a URL has a log nukadoko does not read.
|
|
736
746
|
record[:program_log] = @program_log&.slice(dir, boundary) if boundary
|
|
737
747
|
record[:finished_at] = Time.now.utc.iso8601(3)
|
|
@@ -753,6 +763,17 @@ module Nukadoko
|
|
|
753
763
|
record[:scratch] = made if made.any?
|
|
754
764
|
end
|
|
755
765
|
record[:calls] = fixtures[:call].calls if fixtures[:call]&.calls&.any?
|
|
766
|
+
# The step's own marks, waits, and files, as plain values for the record.
|
|
767
|
+
sections = record.delete(:section_log)&.entries
|
|
768
|
+
record[:sections] = sections if sections&.any?
|
|
769
|
+
polls = record.delete(:poll_log)&.entries
|
|
770
|
+
record[:polls] = polls if polls&.any?
|
|
771
|
+
if (evidence = record.delete(:evidence_log))
|
|
772
|
+
attachments, total = evidence.snapshot
|
|
773
|
+
record[:attachments] = attachments if attachments.any?
|
|
774
|
+
record[:attachments_total] = total if total
|
|
775
|
+
end
|
|
776
|
+
record.delete(:required_env) if record[:required_env] && record[:required_env].empty?
|
|
756
777
|
# A page's own traffic is in http.jsonl and the trace, not counted as the step's.
|
|
757
778
|
record[:http_count] = log.count { _1[:via] != "page" }
|
|
758
779
|
File.write(File.join(dir, "http.jsonl"), "#{log.map { JSON.generate(secrets.redact(_1)) }.join("\n")}\n") if log.any?
|
|
@@ -809,7 +830,7 @@ module Nukadoko
|
|
|
809
830
|
received: observes ? step.inputs.fields.map { _1.name.to_s } : [], transformed: transformed_fills(step, origins))
|
|
810
831
|
end
|
|
811
832
|
# A reading with a page open is timed, so the record can say what the page had received by then.
|
|
812
|
-
read = (plain = read; -> { @browser.reading(&plain) }) if own[:page]
|
|
833
|
+
read = (plain = read; -> { @browser.reading(&plain) }) if own[:page] || own[:context]
|
|
813
834
|
observed = begin
|
|
814
835
|
step.poll ? Poll.new(step.poll, step.claims, args, sides).call(record, &read) : read.()
|
|
815
836
|
rescue StandardError => e
|
|
@@ -915,6 +936,8 @@ module Nukadoko
|
|
|
915
936
|
used = []
|
|
916
937
|
step.from.each do |key, sources|
|
|
917
938
|
cls, value, at_line, record_id = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
|
|
939
|
+
# An optional key stays absent when no producer ran, as zod leaves it.
|
|
940
|
+
next if !cls && step.args[key]&.absent_ok?
|
|
918
941
|
unless cls
|
|
919
942
|
record[:error_kind] = "binding_invalid"
|
|
920
943
|
raise ArgumentError, %(no earlier step in this scenario gave "#{key}")
|
|
@@ -927,7 +950,7 @@ module Nukadoko
|
|
|
927
950
|
used << { step: cls.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
|
|
928
951
|
end
|
|
929
952
|
record[:used] = used
|
|
930
|
-
open = step.args.
|
|
953
|
+
open = step.args.required_names - args.keys
|
|
931
954
|
attachment = line.table || line.doc_string
|
|
932
955
|
if attachment && open.any?
|
|
933
956
|
args[open.first] = attachment
|
|
@@ -943,7 +966,7 @@ module Nukadoko
|
|
|
943
966
|
# for the one key it fills.
|
|
944
967
|
#: (singleton(Step), Hash[String, untyped], PickleStep) -> Hash[String, String]
|
|
945
968
|
def attachment_texts(step, captures, line)
|
|
946
|
-
open = step.args.
|
|
969
|
+
open = step.args.required_names - captures.keys - step.from.keys
|
|
947
970
|
return {} if open.empty?
|
|
948
971
|
return { open.first => line.doc_string } if line.doc_string
|
|
949
972
|
return { open.first => line.table.map { |row| "| #{row.join(" | ")} |" }.join("\n") } if line.table
|
|
@@ -956,17 +979,20 @@ module Nukadoko
|
|
|
956
979
|
|
|
957
980
|
# A project fixture is built the first time a step of its scope names
|
|
958
981
|
# it, directly or through another fixture, and kept until the scope ends.
|
|
959
|
-
#: (Symbol, World, Array[Symbol]) -> untyped
|
|
960
|
-
def project_fixture(name, world, chain)
|
|
982
|
+
#: (Symbol, World, Array[Symbol], ?(^(Symbol) -> untyped)?) -> untyped
|
|
983
|
+
def project_fixture(name, world, chain, builtin = nil)
|
|
961
984
|
fixture = Nukadoko.project_fixtures[name] or raise ArgumentError, "the Ruby engine has no fixture #{name} yet"
|
|
962
985
|
raise ArgumentError, "fixtures depend on each other in a cycle: #{[*chain, name].join(" -> ")}" if chain.include?(name)
|
|
963
986
|
|
|
964
987
|
cache = fixture.scope == :process ? @process_fixtures : @scenario_fixtures
|
|
988
|
+
# A fixture that names itself wraps the builtin of that name, as a
|
|
989
|
+
# page override in the TypeScript config does, so it is no cycle.
|
|
965
990
|
deps = fixture.dependencies.to_h do |dep|
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
991
|
+
if BUILTINS.include?(dep) && (dep == name || !Nukadoko.project_fixtures.key?(dep))
|
|
992
|
+
raise ArgumentError, %(fixture "#{name}" names "#{dep}", which only a step's own fixtures can give) unless builtin
|
|
993
|
+
|
|
994
|
+
[dep, builtin.(dep)]
|
|
995
|
+
else [dep, project_fixture(dep, world, [*chain, name], builtin)]
|
|
970
996
|
end
|
|
971
997
|
end
|
|
972
998
|
return cache[name].tap { note_fixture(name, fixture.scope, nil, nil) } if cache.key?(name)
|
|
@@ -1013,29 +1039,102 @@ module Nukadoko
|
|
|
1013
1039
|
raise Refusal.new("env-file-unreadable", e.message)
|
|
1014
1040
|
end
|
|
1015
1041
|
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1042
|
+
BUILTINS = %i[request baseURL env requireEnv scratch page context pageAs section poll evidence resultOf
|
|
1043
|
+
base_url require_env page_as result_of].freeze
|
|
1044
|
+
|
|
1045
|
+
# The snake_case spelling of each builtin a Ruby step may name instead,
|
|
1046
|
+
# so a body passes RuboCop's naming cops. Both reach the same fixture.
|
|
1047
|
+
ALIASES = { base_url: :baseURL, require_env: :requireEnv, page_as: :pageAs, result_of: :resultOf }.freeze
|
|
1048
|
+
|
|
1049
|
+
#: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped], Array[untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
|
|
1050
|
+
def build_fixtures(step, dir, log, world, record, results)
|
|
1051
|
+
finishes = [] #: Array[^() -> void]
|
|
1019
1052
|
@fixture_usage = []
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1053
|
+
built = {} #: Hash[Symbol, untyped]
|
|
1054
|
+
builtin = lambda do |name|
|
|
1055
|
+
name = ALIASES.fetch(name, name)
|
|
1056
|
+
next built[name] if built.key?(name)
|
|
1057
|
+
|
|
1058
|
+
built[name] =
|
|
1059
|
+
case name
|
|
1060
|
+
when :request then Request.new(world.base_url)
|
|
1061
|
+
when :baseURL then world.base_url
|
|
1062
|
+
when :env then step_env(world)
|
|
1063
|
+
when :requireEnv then require_env(world, record)
|
|
1064
|
+
when :scratch then @scratch
|
|
1065
|
+
when :page
|
|
1066
|
+
page, finish = @browser.page_for(dir, log)
|
|
1067
|
+
finishes << finish
|
|
1068
|
+
page
|
|
1069
|
+
when :context then builtin.(:page).context
|
|
1070
|
+
when :pageAs
|
|
1071
|
+
finishes << lambda do
|
|
1072
|
+
traces = @browser.finish_named
|
|
1073
|
+
record[:named_traces] = traces if traces.any?
|
|
1074
|
+
end
|
|
1075
|
+
->(as, options = nil) { @browser.page_as(as, options, dir, log) }
|
|
1076
|
+
when :section then (record[:section_log] = Sections.new)
|
|
1077
|
+
when :poll then (record[:poll_log] = Polls.new)
|
|
1078
|
+
when :evidence then (record[:evidence_log] = Evidence.new(dir))
|
|
1079
|
+
when :resultOf then result_of(step, results, record)
|
|
1080
|
+
end
|
|
1032
1081
|
end
|
|
1082
|
+
# A project fixture of a builtin's name replaces it for the step.
|
|
1083
|
+
fixtures = {} #: Hash[Symbol, untyped]
|
|
1084
|
+
(step.bag - [:call]).each do |name|
|
|
1085
|
+
fixtures[name] = Nukadoko.project_fixtures.key?(name) || !BUILTINS.include?(name) ? project_fixture(name, world, [], builtin) : builtin.(name)
|
|
1086
|
+
end
|
|
1087
|
+
# Requests a wrapped request fixture sends are the builtin's, so the record keeps them.
|
|
1088
|
+
@request_log = built[:request]
|
|
1033
1089
|
fixtures[:call] = Caller.new(step, fixtures) if step.fixtures.include?(:call)
|
|
1034
1090
|
record[:fixtures] = @fixture_usage if @fixture_usage.any?
|
|
1035
1091
|
@fixture_usage = nil
|
|
1092
|
+
finish = finishes.empty? ? nil : -> { finishes.reverse_each(&:call) }
|
|
1036
1093
|
[fixtures, finish]
|
|
1037
1094
|
end
|
|
1038
1095
|
|
|
1096
|
+
# requireEnv: the env fixture's value for a key, or a raise that names
|
|
1097
|
+
# only the key. An empty value counts as missing, since a step that
|
|
1098
|
+
# requires it is broken either way. Every name asked for is kept, in
|
|
1099
|
+
# the order asked, whether the read found a value or not.
|
|
1100
|
+
#: (World, Hash[Symbol, untyped]) -> ^(String | Symbol) -> String
|
|
1101
|
+
def require_env(world, record)
|
|
1102
|
+
asked = record[:required_env] = [] #: Array[String]
|
|
1103
|
+
lambda do |key|
|
|
1104
|
+
key = key.to_s
|
|
1105
|
+
asked << key unless asked.include?(key)
|
|
1106
|
+
value = step_env(world)[key]
|
|
1107
|
+
raise %(requireEnv("#{key}") found no value: set "#{key}" in one of the environment's env files, or in the world's env) if value.nil? || value.empty?
|
|
1108
|
+
|
|
1109
|
+
value
|
|
1110
|
+
end
|
|
1111
|
+
end
|
|
1112
|
+
|
|
1113
|
+
# resultOf: the result an earlier step of the scenario last gave when
|
|
1114
|
+
# it passed, or nil when it has not. A claim step takes an earlier
|
|
1115
|
+
# value through `from` alone, so its record names where the value
|
|
1116
|
+
# came from. A read that found a result names its step in `used`, as
|
|
1117
|
+
# a from key does.
|
|
1118
|
+
#: (singleton(Step), Array[untyped], Hash[Symbol, untyped]) -> ^(untyped) -> untyped
|
|
1119
|
+
def result_of(step, results, record)
|
|
1120
|
+
lambda do |source|
|
|
1121
|
+
unless source.is_a?(Class) && source < Step && @steps.include?(source)
|
|
1122
|
+
raise ArgumentError, "resultOf(#{source.inspect}): that is not a step this project registered, so no step record could hold its result"
|
|
1123
|
+
end
|
|
1124
|
+
if step.claims
|
|
1125
|
+
raise ArgumentError, %(Step "#{step.step_name}" declares claims, so it takes an earlier step's value through "from" alone, ) +
|
|
1126
|
+
%(which names where the value came from; resultOf(#{source.step_name}) is not available in a claim step.)
|
|
1127
|
+
end
|
|
1128
|
+
|
|
1129
|
+
_, value, _, record_id = results.reverse_each.find { |cls, *| cls == source }
|
|
1130
|
+
next nil unless value
|
|
1131
|
+
|
|
1132
|
+
used = (record[:used] ||= []) #: Array[Hash[Symbol, untyped]]
|
|
1133
|
+
used << { step: source.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
|
|
1134
|
+
(schema = source.returns) ? schema.load(value) : value
|
|
1135
|
+
end
|
|
1136
|
+
end
|
|
1137
|
+
|
|
1039
1138
|
#: (String) -> String
|
|
1040
1139
|
def new_id(kind) = "#{kind}-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}"
|
|
1041
1140
|
|
data/lib/nukadoko/run_record.rb
CHANGED
|
@@ -25,7 +25,7 @@ module Nukadoko
|
|
|
25
25
|
def step_file(record, environment:, world_name:, run_id:, scenario_record_id:, evidence_dir:)
|
|
26
26
|
passed = record[:status] == "passed"
|
|
27
27
|
outcome = if passed then { result: record[:result] || {}, returns_dropped: record[:returns_dropped] }.compact
|
|
28
|
-
else { error: { message: record[:error], kind: record[:error_kind] } }
|
|
28
|
+
else { error: { message: record[:error], kind: record[:error_kind], **(record[:error_at]&.any? ? { at: record[:error_at] } : {}) } }
|
|
29
29
|
end
|
|
30
30
|
processes = record[:processes]
|
|
31
31
|
used = (record[:used] || []).map do |entry|
|
|
@@ -35,12 +35,16 @@ module Nukadoko
|
|
|
35
35
|
args: record[:args] || {}, **(record[:args_origin]&.any? ? { args_origin: record[:args_origin] } : {}),
|
|
36
36
|
**outcome, status: record[:status], environment: environment, world_name: world_name,
|
|
37
37
|
scenario_record_id: scenario_record_id, run_id: run_id, started_at: record[:started_at], finished_at: record[:finished_at],
|
|
38
|
-
evidence: { dir: evidence_dir, screenshots: [], **(record[:
|
|
39
|
-
**(record[:
|
|
38
|
+
evidence: { dir: evidence_dir, screenshots: [], **(record[:attachments] ? { attachments: record[:attachments] } : {}),
|
|
39
|
+
**(record[:scratch] ? { scratch: record[:scratch] } : {}),
|
|
40
|
+
**(record[:http_file] ? { http: "http.jsonl" } : {}), **(record[:trace] ? { trace: record[:trace] } : {}),
|
|
41
|
+
**(record[:named_traces] ? { named_traces: record[:named_traces] } : {}) },
|
|
40
42
|
observed: { processes: processes&.any? ? processes : nil, http: record[:http_count].to_i.positive? ? record[:http_count] : nil,
|
|
41
43
|
files: record[:files], unmeasured: [], **(record.key?(:program_log) ? { program_log: record[:program_log] } : {}) },
|
|
42
|
-
mutates: record[:mutates], **(used.any? ? { used: used } : {}), **(record[:
|
|
43
|
-
**(record[:
|
|
44
|
+
mutates: record[:mutates], **(used.any? ? { used: used } : {}), **(record[:sections] ? { sections: record[:sections] } : {}),
|
|
45
|
+
**(record[:calls] ? { calls: record[:calls] } : {}), **(record[:polls] ? { polls: record[:polls] } : {}),
|
|
46
|
+
**(record[:required_env] ? { required_env: record[:required_env] } : {}),
|
|
47
|
+
**(record[:actions] ? { actions: record[:actions] } : {}), **(record[:actions_truncated] || record[:attachments_total] ? { truncated: { actions: record[:actions_truncated], evidence: record[:attachments_total] }.compact } : {}),
|
|
44
48
|
**(record[:fixtures] ? { fixtures: record[:fixtures] } : {}),
|
|
45
49
|
**(record[:claim_records] ? { claims: record[:claim_records], observation: record[:observation] || "observed", **poll_fields(record), **page_fields(record) } : {}) }
|
|
46
50
|
end
|
data/lib/nukadoko/schema.rb
CHANGED
|
@@ -5,14 +5,39 @@
|
|
|
5
5
|
# a value must pass at run time, the RBS a Steep user checks the step body
|
|
6
6
|
# against, and the Data class the body receives. A type is a symbol for a
|
|
7
7
|
# scalar, `[:array, type]` for a list, or a nested Schema for an object.
|
|
8
|
+
# `[:checked, type, checks]` is an array item with bounds of its own.
|
|
9
|
+
#
|
|
10
|
+
# Each field method takes the options zod spells as methods: `null: true`
|
|
11
|
+
# (`.nullable()`), `optional: true` (`.optional()`: the key may be absent,
|
|
12
|
+
# and the body reads nil), `default:` (`.default(x)`: an absent key reads
|
|
13
|
+
# as the value), and bounds: `min:` and `max:` (a number's value, a
|
|
14
|
+
# string's length, an array's item count), `positive: true` (> 0) and
|
|
15
|
+
# `negative: true` (< 0).
|
|
8
16
|
module Nukadoko
|
|
9
17
|
class Schema
|
|
18
|
+
# The value of `default` when the field declares none.
|
|
19
|
+
NONE = Object.new.freeze
|
|
20
|
+
|
|
10
21
|
Field = Data.define(
|
|
11
22
|
:name, #: Symbol
|
|
12
23
|
:type, #: untyped
|
|
13
24
|
:description, #: String?
|
|
25
|
+
:optional, #: bool
|
|
26
|
+
:default, #: untyped
|
|
27
|
+
:checks, #: Hash[Symbol, untyped]
|
|
14
28
|
)
|
|
15
29
|
|
|
30
|
+
class Field
|
|
31
|
+
# An absent key passes: the field is optional or has a default.
|
|
32
|
+
#: () -> bool
|
|
33
|
+
def absent_ok? = optional || default?
|
|
34
|
+
|
|
35
|
+
#: () -> bool
|
|
36
|
+
def default? = !NONE.equal?(default)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
CHECKS = %i[min max positive negative].freeze
|
|
40
|
+
|
|
16
41
|
#: () ?{ () [self: Schema] -> void } -> Schema
|
|
17
42
|
def self.build(&block)
|
|
18
43
|
schema = new
|
|
@@ -27,34 +52,56 @@ module Nukadoko
|
|
|
27
52
|
@fields = fields
|
|
28
53
|
end
|
|
29
54
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
55
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
56
|
+
def string(name, description = nil, **options) = add(name, :string, description, **options)
|
|
57
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
58
|
+
def boolean(name, description = nil, **options) = add(name, :boolean, description, **options)
|
|
59
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
60
|
+
def integer(name, description = nil, **options) = add(name, :integer, description, **options)
|
|
61
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
62
|
+
def number(name, description = nil, **options) = add(name, :number, description, **options)
|
|
63
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
64
|
+
def unknown(name, description = nil, **options) = add(name, :unknown, description, **options)
|
|
65
|
+
#: (Symbol, Array[String | Symbol], ?String?, **untyped) -> void
|
|
66
|
+
def enum(name, values, description = nil, **options) = add(name, [:enum, values.map(&:to_s)], description, **options)
|
|
67
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
68
|
+
def strings(name, description = nil, **options) = array(name, description, of: :string, **options)
|
|
69
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
70
|
+
def numbers(name, description = nil, **options) = array(name, description, of: :number, **options)
|
|
71
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
72
|
+
def integers(name, description = nil, **options) = array(name, description, of: :integer, **options)
|
|
73
|
+
#: (Symbol, ?String?, **untyped) -> void
|
|
74
|
+
def table(name, description = nil, **options) = add(name, [:array, [:array, :string]], description, **options)
|
|
75
|
+
#: (Symbol, ?String?, **untyped) { () [self: Schema] -> void } -> void
|
|
76
|
+
def object(name, description = nil, **options, &block) = add(name, Schema.build(&block), description, **options)
|
|
77
|
+
|
|
78
|
+
# A list: of objects the block declares (`array :todos do string :id end`),
|
|
79
|
+
# or of `of:` (:string, :number, :integer, :boolean, or a Schema).
|
|
80
|
+
# `each:` holds bounds every item meets (`each: { positive: true }`);
|
|
81
|
+
# `min:` and `max:` bound the item count.
|
|
82
|
+
#: (Symbol, ?String?, ?of: untyped, ?each: Hash[Symbol, untyped], **untyped) ?{ () [self: Schema] -> void } -> void
|
|
83
|
+
def array(name, description = nil, of: nil, each: {}, **options, &block)
|
|
84
|
+
item = block ? Schema.build(&block) : of
|
|
85
|
+
raise ArgumentError, "array :#{name} needs of: or a block that declares its items" if item.nil?
|
|
86
|
+
|
|
87
|
+
unknown = each.keys - CHECKS
|
|
88
|
+
raise ArgumentError, "array :#{name} each: takes #{CHECKS.join(", ")}, not #{unknown.join(", ")}" if unknown.any?
|
|
89
|
+
|
|
90
|
+
add(name, [:array, each.empty? ? item : [:checked, item, each]], description, **options)
|
|
91
|
+
end
|
|
49
92
|
|
|
50
93
|
# Reuses a field another step declared, so two contracts that must agree
|
|
51
94
|
# on one shape are written once: `field :created, AnItemExists.returns[:body]`.
|
|
52
95
|
#: (Symbol, Field, ?String?) -> void
|
|
53
|
-
def field(name, other, description = nil) =
|
|
96
|
+
def field(name, other, description = nil) = fields << other.with(name: name.to_sym, description: description || other.description)
|
|
54
97
|
|
|
55
98
|
#: (Symbol | String) -> Field?
|
|
56
99
|
def [](name) = fields.find { _1.name == name.to_sym }
|
|
57
100
|
|
|
101
|
+
# The keys a value must hold: neither optional nor defaulted.
|
|
102
|
+
#: () -> Array[String]
|
|
103
|
+
def required_names = fields.reject { _1.absent_ok? }.map { _1.name.to_s }
|
|
104
|
+
|
|
58
105
|
#: (Array[String]) -> Schema
|
|
59
106
|
def without(names) = Schema.new(fields.reject { names.include?(_1.name.to_s) })
|
|
60
107
|
|
|
@@ -65,7 +112,7 @@ module Nukadoko
|
|
|
65
112
|
|
|
66
113
|
#: (Hash[String, untyped]) -> untyped
|
|
67
114
|
def load(hash)
|
|
68
|
-
data_class.new(**fields.to_h { [
|
|
115
|
+
data_class.new(**fields.to_h { |field| [field.name, hash.fetch(field.name.to_s) { field.default? ? field.default : (field.optional ? nil : hash.fetch(field.name.to_s)) }] })
|
|
69
116
|
end
|
|
70
117
|
|
|
71
118
|
# Every way `value` departs from the schema, as `path: problem` lines in
|
|
@@ -80,8 +127,10 @@ module Nukadoko
|
|
|
80
127
|
hash = value.transform_keys(&:to_s)
|
|
81
128
|
found = fields.flat_map do |field|
|
|
82
129
|
key = join(path, field.name)
|
|
83
|
-
if hash.key?(field.name.to_s)
|
|
84
|
-
|
|
130
|
+
if hash.key?(field.name.to_s)
|
|
131
|
+
found = Schema.type_problems(field.type, hash[field.name.to_s], key)
|
|
132
|
+
found.empty? ? Schema.check_problems(field.checks, hash[field.name.to_s], key) : found
|
|
133
|
+
elsif field.type == :unknown || field.absent_ok? then []
|
|
85
134
|
else Schema.type_problems(field.type, MISSING, key)
|
|
86
135
|
end
|
|
87
136
|
end
|
|
@@ -96,7 +145,15 @@ module Nukadoko
|
|
|
96
145
|
#: (Hash[untyped, untyped]) -> Hash[String, untyped]
|
|
97
146
|
def strip(value)
|
|
98
147
|
hash = value.transform_keys(&:to_s)
|
|
99
|
-
|
|
148
|
+
kept = {} #: Hash[String, untyped]
|
|
149
|
+
fields.each do |field|
|
|
150
|
+
key = field.name.to_s
|
|
151
|
+
if hash.key?(key) then kept[key] = Schema.strip_type(field.type, hash[key])
|
|
152
|
+
elsif field.default? then kept[key] = field.default
|
|
153
|
+
elsif !field.optional then kept[key] = nil
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
kept
|
|
100
157
|
end
|
|
101
158
|
|
|
102
159
|
#: (untyped, untyped) -> untyped
|
|
@@ -104,6 +161,7 @@ module Nukadoko
|
|
|
104
161
|
case type
|
|
105
162
|
in [:nullable, inner] then value.nil? ? nil : strip_type(inner, value)
|
|
106
163
|
in [:array, item] then value.map { strip_type(item, _1) }
|
|
164
|
+
in [:checked, inner, _] then strip_type(inner, value)
|
|
107
165
|
in Schema then type.strip(value)
|
|
108
166
|
else value
|
|
109
167
|
end
|
|
@@ -136,6 +194,7 @@ module Nukadoko
|
|
|
136
194
|
case type
|
|
137
195
|
in [:nullable, inner] then value.nil? ? [] : drops_type(inner, value, at)
|
|
138
196
|
in [:array, item] then value.is_a?(Array) ? value.each_with_index.flat_map { drops_type(item, _1, [*at, _2.to_s]) } : []
|
|
197
|
+
in [:checked, inner, _] then drops_type(inner, value, at)
|
|
139
198
|
in Schema then type.drops(value, at)
|
|
140
199
|
else []
|
|
141
200
|
end
|
|
@@ -146,6 +205,7 @@ module Nukadoko
|
|
|
146
205
|
case type
|
|
147
206
|
in [:nullable, inner] then value.nil? ? [] : dropped_type(inner, value, path)
|
|
148
207
|
in [:array, item] then value.each_with_index.flat_map { dropped_type(item, _1, "#{path}[#{_2}]") }
|
|
208
|
+
in [:checked, inner, _] then dropped_type(inner, value, path)
|
|
149
209
|
in Schema then type.dropped(value, path)
|
|
150
210
|
else []
|
|
151
211
|
end
|
|
@@ -189,11 +249,39 @@ module Nukadoko
|
|
|
189
249
|
return ["#{path}: #{invalid("array", value)}"] unless value.is_a?(Array)
|
|
190
250
|
|
|
191
251
|
return value.each_with_index.flat_map { |v, i| type_problems(item, v, "#{path}.#{i}") }
|
|
252
|
+
in [:checked, inner, checks]
|
|
253
|
+
found = type_problems(inner, value, path)
|
|
254
|
+
return found.empty? ? check_problems(checks, value, path) : found
|
|
192
255
|
in Schema then return value.is_a?(Hash) ? type.problems(value, path) : ["#{path}: #{invalid("object", value)}"]
|
|
193
256
|
end
|
|
194
257
|
problem ? ["#{path}: #{problem}"] : []
|
|
195
258
|
end
|
|
196
259
|
|
|
260
|
+
# A bound zod reports in its own words, once the type passed: a number's
|
|
261
|
+
# value, a string's length in UTF-16 units, an array's item count.
|
|
262
|
+
#: (Hash[Symbol, untyped], untyped, String) -> Array[String]
|
|
263
|
+
def self.check_problems(checks, value, path)
|
|
264
|
+
return [] if checks.empty? || value.nil?
|
|
265
|
+
|
|
266
|
+
size, what, unit = case value
|
|
267
|
+
when String then [value.encode("UTF-16LE").bytesize / 2, "string", " characters"]
|
|
268
|
+
when Array then [value.size, "array", " items"]
|
|
269
|
+
when Numeric then [value, "number", ""]
|
|
270
|
+
else return []
|
|
271
|
+
end
|
|
272
|
+
relation = what == "number" ? "be" : "have"
|
|
273
|
+
bounds = [] #: Array[String]
|
|
274
|
+
bounds << "Too small: expected #{what} to #{relation} >0#{unit}" if checks[:positive] && size <= 0
|
|
275
|
+
bounds << "Too small: expected #{what} to #{relation} >=#{js(checks[:min])}#{unit}" if checks.key?(:min) && size < checks[:min]
|
|
276
|
+
bounds << "Too big: expected #{what} to #{relation} <0#{unit}" if checks[:negative] && size >= 0
|
|
277
|
+
bounds << "Too big: expected #{what} to #{relation} <=#{js(checks[:max])}#{unit}" if checks.key?(:max) && size > checks[:max]
|
|
278
|
+
bounds.map { "#{path}: #{_1}" }
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
# A number as JavaScript prints it: 2.0 is 2.
|
|
282
|
+
#: (Numeric) -> String
|
|
283
|
+
def self.js(number) = number.is_a?(Float) && number == number.floor && number.finite? ? number.to_i.to_s : number.to_s
|
|
284
|
+
|
|
197
285
|
# zod's int: a finite whole number within Number.MAX_SAFE_INTEGER.
|
|
198
286
|
#: (untyped) -> String?
|
|
199
287
|
def self.integer_problem(value)
|
|
@@ -209,32 +297,66 @@ module Nukadoko
|
|
|
209
297
|
# side (`returns`), where zod drops the keys it does not declare.
|
|
210
298
|
#: (?root: bool, ?output: bool) -> Hash[Symbol, untyped]
|
|
211
299
|
def json_schema(root: true, output: false)
|
|
212
|
-
|
|
213
|
-
|
|
300
|
+
properties = fields.to_h do |field|
|
|
301
|
+
type = Schema.json_type(field.type, output, field.checks)
|
|
302
|
+
type = { default: field.default, **type } if field.default?
|
|
303
|
+
[field.name, type.merge(field.description ? { description: field.description } : {})]
|
|
304
|
+
end
|
|
305
|
+
schema = { type: "object", properties: properties } #: Hash[Symbol, untyped]
|
|
306
|
+
# zod's output side always holds a defaulted key; the input may leave it out.
|
|
307
|
+
required = fields.reject { _1.optional || (_1.default? && !output) }.map(&:name)
|
|
308
|
+
schema[:required] = required if required.any?
|
|
214
309
|
return { "$schema": "https://json-schema.org/draft/2020-12/schema", **schema, additionalProperties: false } if root
|
|
215
310
|
|
|
216
311
|
output ? schema.merge(additionalProperties: false) : schema
|
|
217
312
|
end
|
|
218
313
|
|
|
219
|
-
|
|
220
|
-
|
|
314
|
+
# As z.toJSONSchema writes it, bounds included and in its key order.
|
|
315
|
+
#: (untyped, ?bool, ?Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
|
|
316
|
+
def self.json_type(type, output = false, checks = {})
|
|
221
317
|
case type
|
|
222
|
-
in :string then { type: "string" }
|
|
318
|
+
in :string then { type: "string", **length_bounds(checks, :minLength, :maxLength) }
|
|
223
319
|
in :boolean then { type: "boolean" }
|
|
224
|
-
in :integer
|
|
225
|
-
|
|
320
|
+
in :integer
|
|
321
|
+
{ type: "integer", **number_bounds(checks, -SAFE, SAFE) }
|
|
322
|
+
in :number then { type: "number", **number_bounds(checks, nil, nil) }
|
|
226
323
|
in :unknown then {}
|
|
227
|
-
in [:nullable, inner] then { anyOf: [json_type(inner, output), { type: "null" }] }
|
|
324
|
+
in [:nullable, inner] then { anyOf: [json_type(inner, output, checks), { type: "null" }] }
|
|
228
325
|
in [:enum, values] then { type: "string", enum: values }
|
|
229
|
-
in [:array, item] then { type: "array", items: json_type(item, output) }
|
|
326
|
+
in [:array, item] then { **length_bounds(checks, :minItems, :maxItems), type: "array", items: json_type(item, output) }
|
|
327
|
+
in [:checked, inner, own] then json_type(inner, output, own)
|
|
230
328
|
in Schema then type.json_schema(root: false, output: output)
|
|
231
329
|
end
|
|
232
330
|
end
|
|
233
331
|
|
|
332
|
+
#: (Hash[Symbol, untyped], Integer?, Integer?) -> Hash[Symbol, untyped]
|
|
333
|
+
def self.number_bounds(checks, floor, ceiling)
|
|
334
|
+
low = if checks[:positive] then { exclusiveMinimum: 0 }
|
|
335
|
+
elsif checks.key?(:min) then { minimum: checks[:min] }
|
|
336
|
+
elsif floor then { minimum: floor }
|
|
337
|
+
else {}
|
|
338
|
+
end
|
|
339
|
+
high = if checks[:negative] then { exclusiveMaximum: 0 }
|
|
340
|
+
elsif checks.key?(:max) then { maximum: checks[:max] }
|
|
341
|
+
elsif ceiling then { maximum: ceiling }
|
|
342
|
+
else {}
|
|
343
|
+
end
|
|
344
|
+
{ **low, **high }
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
#: (Hash[Symbol, untyped], Symbol, Symbol) -> Hash[Symbol, untyped]
|
|
348
|
+
def self.length_bounds(checks, low, high)
|
|
349
|
+
{ **(checks.key?(:min) ? { low => checks[:min] } : {}), **(checks.key?(:max) ? { high => checks[:max] } : {}) }
|
|
350
|
+
end
|
|
351
|
+
|
|
234
352
|
#: () -> Array[String]
|
|
235
|
-
def rbs_fields = fields.map { "attr_reader #{_1.name}: #{Schema.
|
|
353
|
+
def rbs_fields = fields.map { "attr_reader #{_1.name}: #{Schema.rbs_field(_1)}" }
|
|
236
354
|
#: () -> String
|
|
237
|
-
def rbs_record = "{ #{fields.map { "#{_1.name}: #{Schema.
|
|
355
|
+
def rbs_record = "{ #{fields.map { "#{_1.name}: #{Schema.rbs_field(_1)}" }.join(", ")} }"
|
|
356
|
+
|
|
357
|
+
# An optional key reads as nil when it is absent.
|
|
358
|
+
#: (Field) -> String
|
|
359
|
+
def self.rbs_field(field) = field.optional && !field.default? ? "(#{rbs_type(field.type)})?" : rbs_type(field.type)
|
|
238
360
|
|
|
239
361
|
#: (untyped) -> String
|
|
240
362
|
def self.rbs_type(type)
|
|
@@ -247,14 +369,20 @@ module Nukadoko
|
|
|
247
369
|
in [:nullable, inner] then "(#{rbs_type(inner)})?"
|
|
248
370
|
in [:enum, values] then values.map(&:inspect).join(" | ")
|
|
249
371
|
in [:array, item] then "Array[#{rbs_type(item)}]"
|
|
372
|
+
in [:checked, inner, _] then rbs_type(inner)
|
|
250
373
|
in Schema then type.fields.empty? ? "Hash[Symbol, untyped]" : type.rbs_record
|
|
251
374
|
end
|
|
252
375
|
end
|
|
253
376
|
|
|
254
377
|
private
|
|
255
378
|
|
|
256
|
-
#: (Symbol, untyped, String?, ?bool) -> void
|
|
257
|
-
def add(name, type, description, null
|
|
379
|
+
#: (Symbol, untyped, String?, ?null: bool, ?optional: bool, ?default: untyped, **untyped) -> void
|
|
380
|
+
def add(name, type, description, null: false, optional: false, default: NONE, **checks)
|
|
381
|
+
unknown = checks.keys - CHECKS
|
|
382
|
+
raise ArgumentError, ":#{name} takes null:, optional:, default:, #{CHECKS.map { "#{_1}:" }.join(", ")}, not #{unknown.map { "#{_1}:" }.join(", ")}" if unknown.any?
|
|
383
|
+
|
|
384
|
+
fields << Field.new(name: name.to_sym, type: null ? [:nullable, type] : type, description: description, optional: optional, default: default, checks: checks)
|
|
385
|
+
end
|
|
258
386
|
#: (String?, Symbol | String) -> String
|
|
259
387
|
def join(path, name) = path ? "#{path}.#{name}" : name.to_s
|
|
260
388
|
end
|