nukadoko 0.4.0 → 0.5.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,225 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "time"
5
+ require "timeout"
6
+
7
+ # The fixtures a step body uses to say where it went, to wait for a state
8
+ # that is not there yet, and to keep evidence only it can produce. The
9
+ # TypeScript engine gives the same three on ctx. Each one fills a list the
10
+ # engine writes into the step record, also when the step raises, because a
11
+ # failed step is the one whose record a reader opens.
12
+ module Nukadoko
13
+ # poll gave up: the budget ended before the block returned a value.
14
+ class PollTimeoutError < StandardError
15
+ attr_reader :timeout_ms #: Numeric
16
+ attr_reader :description #: String?
17
+
18
+ #: (Numeric, String?) -> void
19
+ def initialize(timeout_ms, description)
20
+ @timeout_ms = timeout_ms
21
+ @description = description
22
+ super("poll timed out after #{timeout_ms}ms#{" while waiting for #{description}" if description}")
23
+ end
24
+ end
25
+
26
+ # A timeout or interval that cannot be a budget. Raised before the first
27
+ # attempt, so it is not in the record: there is no attempt to count.
28
+ class InvalidPollOptionsError < ArgumentError; end
29
+
30
+ # An evidence name that would land outside the step's directory.
31
+ class InvalidEvidenceNameError < ArgumentError; end
32
+
33
+ # An evidence name the engine itself writes into the step's directory.
34
+ class ReservedEvidenceNameError < ArgumentError; end
35
+
36
+ # A pageAs name that cannot be part of a file name.
37
+ class InvalidContextNameError < ArgumentError; end
38
+
39
+ # A pageAs call that asks an open context for options it was not made with.
40
+ class ContextOptionsConflictError < ArgumentError; end
41
+
42
+ module Engine
43
+ #: () -> String
44
+ def self.now_iso = Time.now.utc.iso8601(3)
45
+
46
+ # `section.("label")` marks that the body reached a stage. It is a bare
47
+ # marker, not a block wrapper, so nesting and an early return need no
48
+ # meaning: the record answers where the body stopped.
49
+ class Sections
50
+ attr_reader :entries #: Array[Hash[Symbol, String]]
51
+
52
+ #: () -> void
53
+ def initialize
54
+ @entries = []
55
+ end
56
+
57
+ #: (String | Symbol) -> nil
58
+ def call(label)
59
+ @entries << { label: label.to_s, at: Engine.now_iso }
60
+ nil
61
+ end
62
+ end
63
+
64
+ # `poll.(description:, timeout:, interval:) { value or nil }` calls the
65
+ # block until it gives a value other than nil. The budget holds the
66
+ # attempt in flight too, so a value that arrives after it is not
67
+ # returned. Every finished call is kept, so the record tells a wait that
68
+ # did nothing from one that took seconds.
69
+ class Polls
70
+ DEFAULT_TIMEOUT_MS = 30_000
71
+ DEFAULT_INTERVAL_MS = 500
72
+ # The longest timer Node accepts, kept so both engines refuse the same values.
73
+ MAX_MS = 2_147_483_647
74
+
75
+ # An Exception, not a StandardError, so a block that rescues its own
76
+ # errors cannot swallow the end of its budget.
77
+ class AttemptOver < Exception; end
78
+
79
+ attr_reader :entries #: Array[Hash[Symbol, untyped]]
80
+
81
+ #: () -> void
82
+ def initialize
83
+ @entries = []
84
+ end
85
+
86
+ #: [T] (?description: String?, ?timeout: Numeric?, ?interval: Numeric?) { () -> T? } -> T
87
+ def call(description: nil, timeout: nil, interval: nil, &block)
88
+ raise ArgumentError, "poll needs a block that returns nil until the state exists" unless block
89
+
90
+ timeout_ms = timeout || DEFAULT_TIMEOUT_MS
91
+ seconds = budget(timeout_ms, "timeout")
92
+ pause = budget(interval || DEFAULT_INTERVAL_MS, "interval")
93
+ started = monotonic
94
+ at = Engine.now_iso
95
+ attempts = 0
96
+ outcome = "resolved"
97
+ over = lambda do
98
+ outcome = "timed_out"
99
+ raise PollTimeoutError.new(timeout_ms, description)
100
+ end
101
+ begin
102
+ loop do
103
+ left = seconds - (monotonic - started)
104
+ over.() unless left.positive?
105
+ attempts += 1
106
+ value = begin
107
+ Timeout.timeout(left, AttemptOver) { block.call } #: untyped
108
+ rescue AttemptOver
109
+ over.()
110
+ rescue StandardError
111
+ outcome = "failed"
112
+ raise
113
+ end
114
+ return value unless value.nil?
115
+
116
+ left = seconds - (monotonic - started)
117
+ over.() if left < pause
118
+ sleep(pause)
119
+ end
120
+ ensure
121
+ @entries << { description: description, at: at, attempts: attempts,
122
+ waited_ms: ((monotonic - started) * 1000).round, outcome: outcome }.compact
123
+ end
124
+ end
125
+
126
+ private
127
+
128
+ # The budget in seconds, from milliseconds.
129
+ #: (untyped, String) -> Float
130
+ def budget(value, option)
131
+ # A String or a Complex is not a number of milliseconds, so it reads as NaN.
132
+ number = value.is_a?(Numeric) && value.real? ? (_ = value).to_f : Float::NAN #: Float
133
+ return number / 1000 if number.finite? && number.positive? && number <= MAX_MS
134
+
135
+ raise InvalidPollOptionsError, "poll #{option} must be a finite number of milliseconds greater than 0 and " \
136
+ "at most #{MAX_MS} (got #{value.inspect})"
137
+ end
138
+
139
+ #: () -> Float
140
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
141
+ end
142
+
143
+ # `evidence.attach(name, body)` writes a file into the step's own
144
+ # directory, and `evidence.path(name)` gives a path there without
145
+ # writing. A name used twice keeps both files. A name that differs only
146
+ # by case counts as the same, since a case-insensitive volume would put
147
+ # the two on one file.
148
+ class Evidence
149
+ # The files and directories the engine writes into the same directory.
150
+ HARNESS = %w[record.json final.png trace.zip requests.zip http.jsonl mcp.jsonl websocket.jsonl
151
+ program-log.txt program-log-late.txt events.jsonl events-late.jsonl events-read.jsonl judged].freeze
152
+ PROCESS_FILE = /\Aprocess-[1-9][0-9]*\.((stdout|stderr|stdin)\.txt|json)\z/
153
+ NAMED_FILE = /\A(?:trace\.[a-z0-9][a-z0-9-]{0,63}\.zip|final\.[a-z0-9][a-z0-9-]{0,63}\.png)\z/
154
+ MAX_ATTACHMENTS = 100
155
+
156
+ #: (String, ?reserved: Array[String]) -> void
157
+ def initialize(dir, reserved: [])
158
+ @dir = dir
159
+ @reserved = reserved
160
+ @used = (HARNESS + reserved).to_h { [_1.downcase, true] }
161
+ @attached = []
162
+ @paths = []
163
+ end
164
+
165
+ #: (String | Symbol, String) -> nil
166
+ def attach(name, body)
167
+ file = allocate(name.to_s)
168
+ FileUtils.mkdir_p(@dir)
169
+ File.binwrite(File.join(@dir, file), body)
170
+ @attached << { name: name.to_s, file: file, at: Engine.now_iso }
171
+ nil
172
+ end
173
+
174
+ #: (String | Symbol) -> String
175
+ def path(name)
176
+ file = allocate(name.to_s)
177
+ FileUtils.mkdir_p(@dir)
178
+ @paths << { name: name.to_s, file: file }
179
+ File.join(@dir, file)
180
+ end
181
+
182
+ # What the step left: its attachments, and each path it wrote to, by
183
+ # time, at most MAX_ATTACHMENTS of them, with the whole count when
184
+ # there were more.
185
+ #: () -> [Array[Hash[Symbol, String]], Integer?]
186
+ def snapshot
187
+ written = @paths.filter_map do |entry|
188
+ full = File.join(@dir, entry[:file])
189
+ { **entry, at: File.mtime(full).utc.iso8601(3) } if File.exist?(full)
190
+ end
191
+ # Ruby's sort is not stable, and two files can share a millisecond.
192
+ all = (@attached + written).each_with_index.sort_by { |entry, index| [entry[:at], index] }.map(&:first)
193
+ [all.first(MAX_ATTACHMENTS), all.size > MAX_ATTACHMENTS ? all.size : nil]
194
+ end
195
+
196
+ private
197
+
198
+ #: (String) -> String
199
+ def allocate(name)
200
+ if name.empty? || %w[. ..].include?(name) || name.match?(%r{[/\\]})
201
+ raise InvalidEvidenceNameError, %(evidence name #{name.inspect} is not allowed: it must not contain "/" or "\\", ) +
202
+ %(and must not be ".", "..", or empty. Every attachment and path is written inside this step's own evidence directory.)
203
+ end
204
+ key = name.downcase
205
+ if (HARNESS + @reserved).any? { _1.downcase == key } || key.match?(PROCESS_FILE) || key.match?(NAMED_FILE)
206
+ raise ReservedEvidenceNameError, "evidence name #{name.inspect} is reserved for a file the engine writes itself " \
207
+ "(record.json, final.png, trace.zip, http.jsonl, the program's log lines, the trace.<name>.zip and " \
208
+ "final.<name>.png files of a pageAs context, and the process-<n> files of a run_command). " \
209
+ "A name that differs only by case is reserved too. Choose a different name."
210
+ end
211
+ unless @used.key?(key)
212
+ @used[key] = true
213
+ return name
214
+ end
215
+ dot = name.rindex(".")
216
+ stem, ext = dot&.positive? ? [name[0...dot].to_s, name[dot..].to_s] : [name, ""]
217
+ counter = 2
218
+ counter += 1 while @used.key?("#{stem}-#{counter}#{ext}".downcase)
219
+ candidate = "#{stem}-#{counter}#{ext}"
220
+ @used[candidate.downcase] = true
221
+ candidate
222
+ end
223
+ end
224
+ end
225
+ end
@@ -2,5 +2,5 @@
2
2
  # rbs_inline: enabled
3
3
 
4
4
  module Nukadoko
5
- VERSION = "0.4.0"
5
+ VERSION = "0.5.0"
6
6
  end
@@ -6,7 +6,7 @@
6
6
  # engine's vocabulary without opening a file.
7
7
  module Nukadoko
8
8
  module Vocabulary
9
- BROWSER = %i[page context pageAs].freeze
9
+ BROWSER = %i[page context pageAs page_as].freeze
10
10
 
11
11
  #: (singleton(Step), String) -> Hash[Symbol, untyped]
12
12
  def self.entry(step, project)
data/lib/nukadoko.rb CHANGED
@@ -4,6 +4,7 @@
4
4
  require "json"
5
5
  require_relative "nukadoko/version"
6
6
  require_relative "nukadoko/project_files"
7
+ require_relative "nukadoko/error_frames"
7
8
  require_relative "nukadoko/spaces"
8
9
  require_relative "nukadoko/js_pattern"
9
10
  require_relative "nukadoko/schema"
@@ -29,6 +30,7 @@ require_relative "nukadoko/claim_check_run"
29
30
  require_relative "nukadoko/check"
30
31
  require_relative "nukadoko/trace"
31
32
  require_relative "nukadoko/trace_actions"
33
+ require_relative "nukadoko/step_fixtures"
32
34
  require_relative "nukadoko/fixtures"
33
35
  require_relative "nukadoko/http_recording"
34
36
  require_relative "nukadoko/secrets"
data/llms.txt CHANGED
@@ -30,7 +30,8 @@ The `nukadoko` gem is a second engine that reads the same feature files and judg
30
30
  - `gem "nukadoko", group: :test` in the Gemfile, then `bundle exec nuka init`: it writes `nukadoko.config.rb`, `features/steps/`, the `.gitignore` entries, and a `scenarios` task in the Rakefile. Run every command as `bundle exec nuka`. It needs Ruby 3.4 or later.
31
31
  - A step is a class in `features/steps/<name>.rb` (`add_todo.rb` is `add-todo`): `class AddTodo < Nukadoko::Step` with `pattern`, `description`, `mutates`, `args { string :title, "what it is" }`, `returns { ... }`, `from title: [CreateTodo, :title]`, `parts [...]`, and `def run(request:, args:)`. Field kinds are `string`, `integer`, `number`, `boolean`, `enum`, `strings`, `table`, `object { ... }`, `unknown`, and `field :key, OtherStep.returns[:key]`; `null: true` allows nil.
32
32
  - A Then step has `claims [{ actual: "body", compare: "equal", expected: { from: "created" } }]` and `def observe(...)` in place of `run`, with `poll timeout_ms: 3000` when it waits.
33
- - The keyword arguments of `run` or `observe` name the fixtures, with `args:` only when the body reads them: `request`, `page`, `scratch` (`dir` and `copy`), `call`, and each `Nukadoko.fixture(:name) { |use| use.(value) }` in `nukadoko.config.rb`.
33
+ - The keyword arguments of `run` or `observe` name the fixtures, with `args:` only when the body reads them: the TypeScript names (`request`, `page`, `context`, `pageAs`, `env`, `requireEnv`, `baseURL`, `resultOf`, `call`, `section`, `poll`, `evidence`, `scratch`), and each `Nukadoko.fixture(:name) { |use| use.(value) }` in `nukadoko.config.rb`. `base_url`, `require_env`, `page_as`, and `result_of` are snake_case names of the same fixtures. A fixture TypeScript calls is a lambda: `page_as.("aki")`, `section.("paid")`, and `poll.(description: "the order") { value or nil }`. `skills/nukadoko/references/ruby.md` maps each TypeScript shape to its Ruby form.
34
+ - `page`, `context`, and `page_as` give playwright-ruby-client objects. Its `page.wait_for_url` takes a String or a Regexp (a Proc never matches), and `context.expect_page` raises ArgumentError: wait for a tab with `context.expect_event("page") { ... }`.
34
35
  - `Nukadoko.run_command(command, args, cwd:, env:, input:, timeout:, redact:)` runs a program and returns `{ exitCode:, signal:, stdout:, stderr: }`, kept in the step record. Its `env` is added to the runner's environment, and `timeout` is in seconds.
35
36
  - `Nukadoko.config(program: -> { { serve: { command: "... {port}", ready: "/up" }, environments: { ... } } })` holds the program under test, an environment's own env files under `envFiles:`. A `nukadoko.program.rb` of an earlier release is refused with `program-file-moved`.
36
37
  - `Nukadoko.config(envFiles: [".env"], secrets: { public: [...], redact: [...] })` loads env files and classifies their secrets as above.
@@ -14,8 +14,11 @@ module Nukadoko
14
14
  # no exit code to read. `input` (or `stdin`) is written to the program's
15
15
  # stdin. `redact` names secrets the step holds itself, which the record
16
16
  # writes as `{{secret.NAME}}` while the program still gets the real value.
17
- # : (String, ?Array[String], ?cwd: String, ?env: Hash[String | Symbol, String], ?input: String?, ?stdin: String?, ?timeout: Numeric?, ?redact: Hash[String | Symbol, String], ?files: bool) -> Hash[Symbol, untyped]
18
- def self.run_command: (String, ?Array[String], ?cwd: String, ?env: Hash[String | Symbol, String], ?input: String?, ?stdin: String?, ?timeout: Numeric?, ?redact: Hash[String | Symbol, String], ?files: bool) -> Hash[Symbol, untyped]
17
+ # `unbundled: true` runs the command with the environment from before
18
+ # Bundler set up nuka (no BUNDLE_GEMFILE, no -rbundler/setup in RUBYOPT),
19
+ # for a command in another Ruby project, which has a Gemfile of its own.
20
+ # : (String, ?Array[String], ?cwd: String, ?env: Hash[String | Symbol, String], ?input: String?, ?stdin: String?, ?timeout: Numeric?, ?redact: Hash[String | Symbol, String], ?files: bool, ?unbundled: bool) -> Hash[Symbol, untyped]
21
+ def self.run_command: (String, ?Array[String], ?cwd: String, ?env: Hash[String | Symbol, String], ?input: String?, ?stdin: String?, ?timeout: Numeric?, ?redact: Hash[String | Symbol, String], ?files: bool, ?unbundled: bool) -> Hash[Symbol, untyped]
19
22
 
20
23
  module Engine
21
24
  # The processes the running step started, kept per thread so a step
@@ -32,9 +35,15 @@ module Nukadoko
32
35
  # : () -> bool
33
36
  def self.groups?: () -> bool
34
37
 
38
+ # `env` on top of the environment Bundler found when it set up nuka:
39
+ # each variable Bundler added is unset and each one it changed is put
40
+ # back. Without Bundler loaded there is nothing to undo.
41
+ # : (Hash[String, String?]) -> Hash[String, String?]
42
+ def self.unbundled: (Hash[String, String?]) -> Hash[String, String?]
43
+
35
44
  # Runs the command to its close, its stdin closed after `input`.
36
- # : (Hash[String, String], Array[String], String, String?, Numeric?, group: bool) -> [String, String, Process::Status, bool?]
37
- def self.spawn: (Hash[String, String], Array[String], String, String?, Numeric?, group: bool) -> [ String, String, Process::Status, bool? ]
45
+ # : (Hash[String, String?], Array[String], String, String?, Numeric?, group: bool) -> [String, String, Process::Status, bool?]
46
+ def self.spawn: (Hash[String, String?], Array[String], String, String?, Numeric?, group: bool) -> [ String, String, Process::Status, bool? ]
38
47
 
39
48
  # `ended` when no process of the group still runs as the leader closed.
40
49
  # : (Integer) -> String
@@ -0,0 +1,24 @@
1
+ # Generated from lib/nukadoko/error_frames.rb with RBS::Inline
2
+
3
+ # Where a step's own code raised, as the project's own frames of the
4
+ # backtrace. A step record's error message says what went wrong but not
5
+ # where, so a reader had to call the step again outside nukadoko to find the
6
+ # line. The frames kept are the ones a reader can open and change: inside
7
+ # the project root, and outside the gem and any installed bundle, as the
8
+ # TypeScript engine leaves out node_modules.
9
+ module Nukadoko
10
+ module Engine
11
+ module ErrorFrames
12
+ # The first few frames are where the code was when it raised; the rest
13
+ # is the call chain a reader rarely needs.
14
+ MAX: ::Integer
15
+
16
+ GEM_ROOT: untyped
17
+
18
+ # Each frame as `path:line` relative to `root`, in backtrace order,
19
+ # without repeats.
20
+ # : (Exception, String) -> Array[String]
21
+ def self?.of: (Exception, String) -> Array[String]
22
+ end
23
+ end
24
+ end
@@ -31,8 +31,15 @@ module Nukadoko
31
31
  class Request
32
32
  attr_reader log: Array[Hash[Symbol, untyped]]
33
33
 
34
- # : (String) -> void
35
- def initialize: (String) -> void
34
+ # `base_url` is the world's URL, which a path joins onto; a project with
35
+ # no program has none. An absolute URL, http or https, goes where it
36
+ # names, so a step can call a third-party API and still have its
37
+ # requests recorded.
38
+ # : (String?) -> void
39
+ def initialize: (String?) -> void
40
+
41
+ # : (String) -> URI::Generic
42
+ def target: (String) -> URI::Generic
36
43
 
37
44
  BODY_TEXT: untyped
38
45
 
@@ -75,6 +82,9 @@ module Nukadoko
75
82
  # : (untyped, String, Float, ?caret: String?, ?bounded: bool) -> bool
76
83
  def masked_shot: (untyped, String, Float, ?caret: String?, ?bounded: bool) -> bool
77
84
 
85
+ # : () -> untyped
86
+ def launch: () -> untyped
87
+
78
88
  # : (String, Array[Hash[Symbol, untyped]]) -> [untyped, ^() -> void]
79
89
  def page_for: (String, Array[Hash[Symbol, untyped]]) -> [ untyped, ^() -> void ]
80
90
 
@@ -168,6 +178,32 @@ module Nukadoko
168
178
  # : (?String?) -> Array[Hash[Symbol, untyped]]
169
179
  def end_scenario: (?String?) -> Array[Hash[Symbol, untyped]]
170
180
 
181
+ CONTEXT_NAME: ::Regexp
182
+
183
+ # The page of a browser context of its own, named `name`, so a second
184
+ # person in the scenario has cookies and storage of their own. The
185
+ # context opens on the first call for the name in the scenario, with
186
+ # `options` over the world's base URL, and a later call gets the same
187
+ # page. Each step that calls it gets a trace chunk, trace.<name>.zip,
188
+ # and the page's requests go to the step's log with `as`.
189
+ # : (String, Hash[untyped, untyped]?, String, Array[Hash[Symbol, untyped]]) -> untyped
190
+ def page_as: (String, Hash[untyped, untyped]?, String, Array[Hash[Symbol, untyped]]) -> untyped
191
+
192
+ # Ends the step's chunk of each named context it reached, and names
193
+ # the files, in the order the contexts opened.
194
+ # : () -> Array[Hash[Symbol, String]]
195
+ def finish_named: () -> Array[Hash[Symbol, String]]
196
+
197
+ private
198
+
199
+ # : () -> Hash[String, Hash[Symbol, untyped]]
200
+ def named: () -> Hash[String, Hash[Symbol, untyped]]
201
+
202
+ # : () -> Hash[String, [String, untyped]]
203
+ def step_named: () -> Hash[String, [ String, untyped ]]
204
+
205
+ public
206
+
171
207
  # : () -> void
172
208
  def close: () -> void
173
209
  end
@@ -236,8 +236,8 @@ module Nukadoko
236
236
 
237
237
  # A project fixture is built the first time a step of its scope names
238
238
  # it, directly or through another fixture, and kept until the scope ends.
239
- # : (Symbol, World, Array[Symbol]) -> untyped
240
- def project_fixture: (Symbol, World, Array[Symbol]) -> untyped
239
+ # : (Symbol, World, Array[Symbol], ?(^(Symbol) -> untyped)?) -> untyped
240
+ def project_fixture: (Symbol, World, Array[Symbol], ?(^(Symbol) -> untyped)?) -> untyped
241
241
 
242
242
  # Each project fixture a step's bag touched, once, as the step record
243
243
  # lists it: built here with its setup time, or reused from its scope.
@@ -258,8 +258,29 @@ module Nukadoko
258
258
  # : (Environment) -> void
259
259
  def read_env: (Environment) -> void
260
260
 
261
- # : (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
262
- def build_fixtures: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped]) -> [ Hash[Symbol, untyped], (^() -> void)? ]
261
+ BUILTINS: untyped
262
+
263
+ # The snake_case spelling of each builtin a Ruby step may name instead,
264
+ # so a body passes RuboCop's naming cops. Both reach the same fixture.
265
+ ALIASES: untyped
266
+
267
+ # : (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped], Array[untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
268
+ def build_fixtures: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped], Array[untyped]) -> [ Hash[Symbol, untyped], (^() -> void)? ]
269
+
270
+ # requireEnv: the env fixture's value for a key, or a raise that names
271
+ # only the key. An empty value counts as missing, since a step that
272
+ # requires it is broken either way. Every name asked for is kept, in
273
+ # the order asked, whether the read found a value or not.
274
+ # : (World, Hash[Symbol, untyped]) -> ^(String | Symbol) -> String
275
+ def require_env: (World, Hash[Symbol, untyped]) -> ^(String | Symbol) -> String
276
+
277
+ # resultOf: the result an earlier step of the scenario last gave when
278
+ # it passed, or nil when it has not. A claim step takes an earlier
279
+ # value through `from` alone, so its record names where the value
280
+ # came from. A read that found a result names its step in `used`, as
281
+ # a from key does.
282
+ # : (singleton(Step), Array[untyped], Hash[Symbol, untyped]) -> ^(untyped) -> untyped
283
+ def result_of: (singleton(Step), Array[untyped], Hash[Symbol, untyped]) -> ^(untyped) -> untyped
263
284
 
264
285
  # : (String) -> String
265
286
  def new_id: (String) -> String
@@ -4,8 +4,19 @@
4
4
  # a value must pass at run time, the RBS a Steep user checks the step body
5
5
  # against, and the Data class the body receives. A type is a symbol for a
6
6
  # scalar, `[:array, type]` for a list, or a nested Schema for an object.
7
+ # `[:checked, type, checks]` is an array item with bounds of its own.
8
+ #
9
+ # Each field method takes the options zod spells as methods: `null: true`
10
+ # (`.nullable()`), `optional: true` (`.optional()`: the key may be absent,
11
+ # and the body reads nil), `default:` (`.default(x)`: an absent key reads
12
+ # as the value), and bounds: `min:` and `max:` (a number's value, a
13
+ # string's length, an array's item count), `positive: true` (> 0) and
14
+ # `negative: true` (< 0).
7
15
  module Nukadoko
8
16
  class Schema
17
+ # The value of `default` when the field declares none.
18
+ NONE: untyped
19
+
9
20
  class Field < Data
10
21
  attr_reader name(): Symbol
11
22
 
@@ -13,14 +24,31 @@ module Nukadoko
13
24
 
14
25
  attr_reader description(): String?
15
26
 
16
- def self.new: (Symbol name, untyped type, String? description) -> instance
17
- | (name: Symbol, type: untyped, description: String?) -> instance
27
+ attr_reader optional(): bool
28
+
29
+ attr_reader default(): untyped
30
+
31
+ attr_reader checks(): Hash[Symbol, untyped]
18
32
 
19
- def self.members: () -> [ :name, :type, :description ]
33
+ def self.new: (Symbol name, untyped type, String? description, bool optional, untyped default, Hash[Symbol, untyped] checks) -> instance
34
+ | (name: Symbol, type: untyped, description: String?, optional: bool, default: untyped, checks: Hash[Symbol, untyped]) -> instance
20
35
 
21
- def members: () -> [ :name, :type, :description ]
36
+ def self.members: () -> [ :name, :type, :description, :optional, :default, :checks ]
37
+
38
+ def members: () -> [ :name, :type, :description, :optional, :default, :checks ]
22
39
  end
23
40
 
41
+ class Field
42
+ # An absent key passes: the field is optional or has a default.
43
+ # : () -> bool
44
+ def absent_ok?: () -> bool
45
+
46
+ # : () -> bool
47
+ def default?: () -> bool
48
+ end
49
+
50
+ CHECKS: untyped
51
+
24
52
  # : () ?{ () [self: Schema] -> void } -> Schema
25
53
  def self.build: () ?{ () [self: Schema] -> void } -> Schema
26
54
 
@@ -29,33 +57,45 @@ module Nukadoko
29
57
  # : (?Array[Field]) -> void
30
58
  def initialize: (?Array[Field]) -> void
31
59
 
32
- # `null: true` lets the value be nil as well, as zod's `.nullable()` does.
33
- # : (Symbol, ?String?, ?null: bool) -> void
34
- def string: (Symbol, ?String?, ?null: bool) -> void
60
+ # : (Symbol, ?String?, **untyped) -> void
61
+ def string: (Symbol, ?String?, **untyped) -> void
62
+
63
+ # : (Symbol, ?String?, **untyped) -> void
64
+ def boolean: (Symbol, ?String?, **untyped) -> void
35
65
 
36
- # : (Symbol, ?String?, ?null: bool) -> void
37
- def boolean: (Symbol, ?String?, ?null: bool) -> void
66
+ # : (Symbol, ?String?, **untyped) -> void
67
+ def integer: (Symbol, ?String?, **untyped) -> void
38
68
 
39
- # : (Symbol, ?String?, ?null: bool) -> void
40
- def integer: (Symbol, ?String?, ?null: bool) -> void
69
+ # : (Symbol, ?String?, **untyped) -> void
70
+ def number: (Symbol, ?String?, **untyped) -> void
41
71
 
42
- # : (Symbol, ?String?, ?null: bool) -> void
43
- def number: (Symbol, ?String?, ?null: bool) -> void
72
+ # : (Symbol, ?String?, **untyped) -> void
73
+ def unknown: (Symbol, ?String?, **untyped) -> void
44
74
 
45
- # : (Symbol, ?String?) -> void
46
- def unknown: (Symbol, ?String?) -> void
75
+ # : (Symbol, Array[String | Symbol], ?String?, **untyped) -> void
76
+ def enum: (Symbol, Array[String | Symbol], ?String?, **untyped) -> void
47
77
 
48
- # : (Symbol, Array[String | Symbol], ?String?, ?null: bool) -> void
49
- def enum: (Symbol, Array[String | Symbol], ?String?, ?null: bool) -> void
78
+ # : (Symbol, ?String?, **untyped) -> void
79
+ def strings: (Symbol, ?String?, **untyped) -> void
50
80
 
51
- # : (Symbol, ?String?, ?null: bool) -> void
52
- def strings: (Symbol, ?String?, ?null: bool) -> void
81
+ # : (Symbol, ?String?, **untyped) -> void
82
+ def numbers: (Symbol, ?String?, **untyped) -> void
53
83
 
54
- # : (Symbol, ?String?, ?null: bool) -> void
55
- def table: (Symbol, ?String?, ?null: bool) -> void
84
+ # : (Symbol, ?String?, **untyped) -> void
85
+ def integers: (Symbol, ?String?, **untyped) -> void
56
86
 
57
- # : (Symbol, ?String?, ?null: bool) { () [self: Schema] -> void } -> void
58
- def object: (Symbol, ?String?, ?null: bool) { () [self: Schema] -> void } -> void
87
+ # : (Symbol, ?String?, **untyped) -> void
88
+ def table: (Symbol, ?String?, **untyped) -> void
89
+
90
+ # : (Symbol, ?String?, **untyped) { () [self: Schema] -> void } -> void
91
+ def object: (Symbol, ?String?, **untyped) { () [self: Schema] -> void } -> void
92
+
93
+ # A list: of objects the block declares (`array :todos do string :id end`),
94
+ # or of `of:` (:string, :number, :integer, :boolean, or a Schema).
95
+ # `each:` holds bounds every item meets (`each: { positive: true }`);
96
+ # `min:` and `max:` bound the item count.
97
+ # : (Symbol, ?String?, ?of: untyped, ?each: Hash[Symbol, untyped], **untyped) ?{ () [self: Schema] -> void } -> void
98
+ def array: (Symbol, ?String?, ?of: untyped, ?each: Hash[Symbol, untyped], **untyped) ?{ () [self: Schema] -> void } -> void
59
99
 
60
100
  # Reuses a field another step declared, so two contracts that must agree
61
101
  # on one shape are written once: `field :created, AnItemExists.returns[:body]`.
@@ -65,6 +105,10 @@ module Nukadoko
65
105
  # : (Symbol | String) -> Field?
66
106
  def []: (Symbol | String) -> Field?
67
107
 
108
+ # The keys a value must hold: neither optional nor defaulted.
109
+ # : () -> Array[String]
110
+ def required_names: () -> Array[String]
111
+
68
112
  # : (Array[String]) -> Schema
69
113
  def without: (Array[String]) -> Schema
70
114
 
@@ -122,6 +166,15 @@ module Nukadoko
122
166
  # : (untyped, untyped, String) -> Array[String]
123
167
  def self.type_problems: (untyped, untyped, String) -> Array[String]
124
168
 
169
+ # A bound zod reports in its own words, once the type passed: a number's
170
+ # value, a string's length in UTF-16 units, an array's item count.
171
+ # : (Hash[Symbol, untyped], untyped, String) -> Array[String]
172
+ def self.check_problems: (Hash[Symbol, untyped], untyped, String) -> Array[String]
173
+
174
+ # A number as JavaScript prints it: 2.0 is 2.
175
+ # : (Numeric) -> String
176
+ def self.js: (Numeric) -> String
177
+
125
178
  # zod's int: a finite whole number within Number.MAX_SAFE_INTEGER.
126
179
  # : (untyped) -> String?
127
180
  def self.integer_problem: (untyped) -> String?
@@ -132,8 +185,15 @@ module Nukadoko
132
185
  # : (?root: bool, ?output: bool) -> Hash[Symbol, untyped]
133
186
  def json_schema: (?root: bool, ?output: bool) -> Hash[Symbol, untyped]
134
187
 
135
- # : (untyped, ?bool) -> Hash[Symbol, untyped]
136
- def self.json_type: (untyped, ?bool) -> Hash[Symbol, untyped]
188
+ # As z.toJSONSchema writes it, bounds included and in its key order.
189
+ # : (untyped, ?bool, ?Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
190
+ def self.json_type: (untyped, ?bool, ?Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
191
+
192
+ # : (Hash[Symbol, untyped], Integer?, Integer?) -> Hash[Symbol, untyped]
193
+ def self.number_bounds: (Hash[Symbol, untyped], Integer?, Integer?) -> Hash[Symbol, untyped]
194
+
195
+ # : (Hash[Symbol, untyped], Symbol, Symbol) -> Hash[Symbol, untyped]
196
+ def self.length_bounds: (Hash[Symbol, untyped], Symbol, Symbol) -> Hash[Symbol, untyped]
137
197
 
138
198
  # : () -> Array[String]
139
199
  def rbs_fields: () -> Array[String]
@@ -141,13 +201,17 @@ module Nukadoko
141
201
  # : () -> String
142
202
  def rbs_record: () -> String
143
203
 
204
+ # An optional key reads as nil when it is absent.
205
+ # : (Field) -> String
206
+ def self.rbs_field: (Field) -> String
207
+
144
208
  # : (untyped) -> String
145
209
  def self.rbs_type: (untyped) -> String
146
210
 
147
211
  private
148
212
 
149
- # : (Symbol, untyped, String?, ?bool) -> void
150
- def add: (Symbol, untyped, String?, ?bool) -> void
213
+ # : (Symbol, untyped, String?, ?null: bool, ?optional: bool, ?default: untyped, **untyped) -> void
214
+ def add: (Symbol, untyped, String?, ?null: bool, ?optional: bool, ?default: untyped, **untyped) -> void
151
215
 
152
216
  # : (String?, Symbol | String) -> String
153
217
  def join: (String?, Symbol | String) -> String