nukadoko 0.1.0 → 0.3.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.
Files changed (159) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +417 -0
  3. data/README.ja.md +62 -7
  4. data/README.md +19 -5
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +294 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claim_sides.rb +469 -0
  15. data/lib/nukadoko/claims.rb +576 -37
  16. data/lib/nukadoko/cli.rb +814 -22
  17. data/lib/nukadoko/codes.json +947 -0
  18. data/lib/nukadoko/codes.rb +19 -0
  19. data/lib/nukadoko/command.rb +214 -12
  20. data/lib/nukadoko/criteria.rb +172 -0
  21. data/lib/nukadoko/definition.rb +33 -41
  22. data/lib/nukadoko/env_check.rb +88 -0
  23. data/lib/nukadoko/features.rb +80 -10
  24. data/lib/nukadoko/fixtures.rb +329 -11
  25. data/lib/nukadoko/http_recording.rb +68 -0
  26. data/lib/nukadoko/init.rb +129 -0
  27. data/lib/nukadoko/js_json.rb +274 -0
  28. data/lib/nukadoko/js_pattern.rb +531 -0
  29. data/lib/nukadoko/judge.rb +221 -0
  30. data/lib/nukadoko/judgment_file.rb +78 -0
  31. data/lib/nukadoko/judgments.rb +256 -0
  32. data/lib/nukadoko/literal.rb +129 -0
  33. data/lib/nukadoko/measured.rb +105 -0
  34. data/lib/nukadoko/order.rb +84 -0
  35. data/lib/nukadoko/parts.rb +43 -22
  36. data/lib/nukadoko/pattern.rb +73 -3
  37. data/lib/nukadoko/poll.rb +21 -8
  38. data/lib/nukadoko/program.rb +105 -17
  39. data/lib/nukadoko/project_files.rb +17 -0
  40. data/lib/nukadoko/project_fixtures.rb +17 -2
  41. data/lib/nukadoko/project_program.rb +119 -0
  42. data/lib/nukadoko/report_allure.rb +751 -0
  43. data/lib/nukadoko/report_messages.rb +167 -0
  44. data/lib/nukadoko/report_run.rb +169 -0
  45. data/lib/nukadoko/run.rb +898 -91
  46. data/lib/nukadoko/run_record.rb +535 -0
  47. data/lib/nukadoko/scaffold.rb +1015 -0
  48. data/lib/nukadoko/schema.rb +120 -21
  49. data/lib/nukadoko/secrets.rb +375 -0
  50. data/lib/nukadoko/selection.rb +163 -0
  51. data/lib/nukadoko/signature.rb +4 -1
  52. data/lib/nukadoko/skill.rb +36 -0
  53. data/lib/nukadoko/spaces.rb +28 -0
  54. data/lib/nukadoko/step.rb +68 -21
  55. data/lib/nukadoko/summary.rb +662 -0
  56. data/lib/nukadoko/table.rb +34 -2
  57. data/lib/nukadoko/text_fit.rb +179 -0
  58. data/lib/nukadoko/trace.rb +244 -0
  59. data/lib/nukadoko/trace_actions.rb +116 -0
  60. data/lib/nukadoko/tree_passes.rb +122 -0
  61. data/lib/nukadoko/verdict.rb +128 -0
  62. data/lib/nukadoko/version.rb +2 -1
  63. data/lib/nukadoko/vocabulary.rb +6 -0
  64. data/lib/nukadoko/walk.rb +305 -0
  65. data/lib/nukadoko/walk_files.rb +473 -0
  66. data/lib/nukadoko/walk_step.rb +149 -0
  67. data/lib/nukadoko.rb +60 -2
  68. data/llms.txt +297 -0
  69. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  70. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  71. data/sig/generated/nukadoko/base.rbs +142 -0
  72. data/sig/generated/nukadoko/check.rbs +255 -0
  73. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  74. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  75. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  76. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  77. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  78. data/sig/generated/nukadoko/claims.rbs +208 -0
  79. data/sig/generated/nukadoko/cli.rbs +182 -0
  80. data/sig/generated/nukadoko/codes.rbs +16 -0
  81. data/sig/generated/nukadoko/command.rbs +109 -0
  82. data/sig/generated/nukadoko/criteria.rbs +83 -0
  83. data/sig/generated/nukadoko/definition.rbs +30 -0
  84. data/sig/generated/nukadoko/env_check.rbs +34 -0
  85. data/sig/generated/nukadoko/features.rbs +101 -0
  86. data/sig/generated/nukadoko/fixtures.rbs +175 -0
  87. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  88. data/sig/generated/nukadoko/init.rbs +64 -0
  89. data/sig/generated/nukadoko/js_json.rbs +109 -0
  90. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  91. data/sig/generated/nukadoko/judge.rbs +64 -0
  92. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  93. data/sig/generated/nukadoko/judgments.rbs +120 -0
  94. data/sig/generated/nukadoko/literal.rbs +71 -0
  95. data/sig/generated/nukadoko/measured.rbs +42 -0
  96. data/sig/generated/nukadoko/order.rbs +54 -0
  97. data/sig/generated/nukadoko/parts.rbs +35 -0
  98. data/sig/generated/nukadoko/pattern.rbs +62 -0
  99. data/sig/generated/nukadoko/poll.rbs +41 -0
  100. data/sig/generated/nukadoko/program.rbs +101 -0
  101. data/sig/generated/nukadoko/project_files.rbs +19 -0
  102. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  103. data/sig/generated/nukadoko/project_program.rbs +55 -0
  104. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  105. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  106. data/sig/generated/nukadoko/report_run.rbs +102 -0
  107. data/sig/generated/nukadoko/run.rbs +264 -0
  108. data/sig/generated/nukadoko/run_record.rbs +175 -0
  109. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  110. data/sig/generated/nukadoko/schema.rbs +155 -0
  111. data/sig/generated/nukadoko/secrets.rbs +172 -0
  112. data/sig/generated/nukadoko/selection.rbs +73 -0
  113. data/sig/generated/nukadoko/signature.rbs +17 -0
  114. data/sig/generated/nukadoko/skill.rbs +20 -0
  115. data/sig/generated/nukadoko/spaces.rbs +31 -0
  116. data/sig/generated/nukadoko/step.rbs +115 -0
  117. data/sig/generated/nukadoko/summary.rbs +204 -0
  118. data/sig/generated/nukadoko/table.rbs +43 -0
  119. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  120. data/sig/generated/nukadoko/trace.rbs +127 -0
  121. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  122. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  123. data/sig/generated/nukadoko/verdict.rbs +56 -0
  124. data/sig/generated/nukadoko/version.rbs +5 -0
  125. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  126. data/sig/generated/nukadoko/walk.rbs +139 -0
  127. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  128. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  129. data/sig/generated/nukadoko.rbs +26 -0
  130. data/sig/nukadoko.rbs +5 -48
  131. data/skills/nukadoko/SKILL.md +120 -0
  132. data/skills/nukadoko/references/checking-steps.md +200 -0
  133. data/skills/nukadoko/references/diagnosing.md +200 -0
  134. data/skills/nukadoko/references/done.md +99 -0
  135. data/skills/nukadoko/references/evidence.md +124 -0
  136. data/skills/nukadoko/references/examples/cli.md +230 -0
  137. data/skills/nukadoko/references/examples/http-api.md +342 -0
  138. data/skills/nukadoko/references/examples/workflow.md +173 -0
  139. data/skills/nukadoko/references/exploring.md +184 -0
  140. data/skills/nukadoko/references/fixtures.md +198 -0
  141. data/skills/nukadoko/references/from-prose.md +51 -0
  142. data/skills/nukadoko/references/judgments.md +95 -0
  143. data/skills/nukadoko/references/maintenance.md +97 -0
  144. data/skills/nukadoko/references/merge-risk.md +74 -0
  145. data/skills/nukadoko/references/parts.md +152 -0
  146. data/skills/nukadoko/references/perturbed-worlds.md +109 -0
  147. data/skills/nukadoko/references/program.md +200 -0
  148. data/skills/nukadoko/references/reviewing.md +200 -0
  149. data/skills/nukadoko/references/running.md +200 -0
  150. data/skills/nukadoko/references/scenario-rules.md +188 -0
  151. data/skills/nukadoko/references/states.md +66 -0
  152. data/skills/nukadoko/references/step-files.md +200 -0
  153. data/skills/nukadoko/references/verdicts.md +200 -0
  154. data/skills/nukadoko/references/writing-steps.md +200 -0
  155. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  156. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  157. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  158. data/skills/nukadoko-verification/SKILL.md +263 -0
  159. metadata +133 -1
@@ -0,0 +1,751 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "digest"
5
+ require "fileutils"
6
+ require "json"
7
+ require "time"
8
+
9
+ # One run as Allure results, for `nuka report --format allure`, in the shape
10
+ # the TypeScript engine writes them (src/report/allure/): one test result
11
+ # per execution, with one step per line of the scenario, its hooks as
12
+ # fixtures in containers of their own, `categories.json`, and
13
+ # `environment.properties`. That engine writes through allure-js-commons;
14
+ # this one writes the same JSON itself, field for field, since Allure reads
15
+ # the files and nothing else.
16
+ #
17
+ # A file's name is derived from the run, the scenario execution, and its
18
+ # place in the render, never from a random id, so a second render of a run
19
+ # writes the same names and replaces what the first wrote. `historyId` and
20
+ # `testCaseId` use allure-js-commons' own formula (md5 of the full name, and
21
+ # of the parameters that are not excluded), so a result keeps the history
22
+ # the TypeScript engine's results of the same scenario built up.
23
+ #
24
+ # A failure stays as small as it can: an attachment that cannot be read
25
+ # costs that attachment, a step that cannot be mapped costs that step a
26
+ # broken entry, and a scenario that cannot be written costs its own result.
27
+ # Each is a problem the report names.
28
+ module Nukadoko
29
+ module Engine
30
+ module ReportAllure
31
+ # The kinds of a step's failure, in the order categories.json lists them.
32
+ CATEGORY_NAMES = {
33
+ "args_invalid" => "Contract: args failed the step's schema",
34
+ "result_invalid" => "Contract: result failed the step's schema",
35
+ "binding_invalid" => "Contract: the step's text couldn't bind",
36
+ "world_invalid" => "Contract: a World key's write failed its schema",
37
+ "timeout" => "Timeout",
38
+ "unsupported" => "Compat: unsupported step shape",
39
+ "claim_broken" => "Claim broken",
40
+ "unobserved" => "Claim step did not observe",
41
+ "claim_unjudged" => "Claim could not be judged",
42
+ "step_error" => "Step error"
43
+ }.freeze
44
+ # failed: the system under test broke the contract. broken: the
45
+ # contract layer did not reach a verdict.
46
+ FAILED_KINDS = %w[step_error result_invalid claim_broken].freeze
47
+ MEDIA_TYPE_BY_EXTENSION = { ".txt" => "text/plain", ".html" => "text/html", ".csv" => "text/csv", ".json" => "application/json",
48
+ ".xml" => "application/xml", ".png" => "image/png", ".jpg" => "image/jpeg", ".svg" => "image/svg+xml" }.freeze
49
+ # allure-js-commons' extension for a media type, for an attachment
50
+ # whose own name has none.
51
+ EXTENSION_BY_MEDIA_TYPE = { "application/json" => ".json", "application/octet-stream" => ".bin", "application/xml" => ".xml",
52
+ "application/zip" => ".zip", "application/vnd.allure.playwright-trace" => ".zip", "image/jpeg" => ".jpg",
53
+ "image/png" => ".png", "image/svg+xml" => ".svg", "text/csv" => ".csv", "text/html" => ".html",
54
+ "text/plain" => ".txt" }.freeze
55
+ TRACE = "application/vnd.allure.playwright-trace"
56
+ ALLURE_LABEL_TAG = /\A@allure\.label\.([^:=]+)[:=](.+)\z/
57
+ ALLURE_ID_TAG = /\A@allure\.id[:=](.+)\z/
58
+
59
+ # Writes the files of one render under names derived from the
60
+ # execution being written, and keeps one execution's files from
61
+ # landing half-written: they are kept in memory until `commit`.
62
+ class Writer
63
+ attr_reader :written #: Array[String]
64
+
65
+ #: (String) -> void
66
+ def initialize(dir)
67
+ @dir = dir
68
+ @written = []
69
+ @key = ""
70
+ @index = 0
71
+ @pending = []
72
+ end
73
+
74
+ #: (String) -> void
75
+ def begin(key)
76
+ @key = key
77
+ @index = 0
78
+ @pending = []
79
+ end
80
+
81
+ # The next name of the execution: the first 16 bytes of the SHA-256
82
+ # of the key and the place, with the version 8 and RFC 9562 variant
83
+ # bits set, as the TypeScript engine names it.
84
+ #: () -> String
85
+ def reserve
86
+ bytes = Digest::SHA256.digest("#{@key}\u0000#{@index}").bytes.first(16)
87
+ @index += 1
88
+ bytes[6] = (bytes[6] & 0x0f) | 0x80
89
+ bytes[8] = (bytes[8] & 0x3f) | 0x80
90
+ hex = bytes.pack("C*").unpack1("H*").to_s
91
+ "#{hex[0, 8]}-#{hex[8, 4]}-#{hex[12, 4]}-#{hex[16, 4]}-#{hex[20..]}"
92
+ end
93
+
94
+ #: (untyped) -> String
95
+ def name_of(_object) = reserve
96
+
97
+ #: (String) -> String
98
+ def attachment_name(extension) = "#{reserve}-attachment#{extension}"
99
+
100
+ #: (String, String, ?note: bool) -> void
101
+ def file(name, content, note: true)
102
+ if note
103
+ @pending << [name, content, nil]
104
+ else
105
+ atomic(File.join(@dir, name)) { File.write(_1, content) }
106
+ end
107
+ end
108
+
109
+ #: (String, String) -> void
110
+ def copy(name, source)
111
+ raise Errno::ENOENT, source unless File.file?(source)
112
+
113
+ @pending << [name, nil, source]
114
+ end
115
+
116
+ #: (Hash[Symbol, untyped]) -> void
117
+ def result(test)
118
+ @pending << ["#{test[:uuid]}-result.json", JSON.generate(test), nil]
119
+ end
120
+
121
+ #: (Hash[Symbol, untyped]) -> void
122
+ def container(group)
123
+ @pending << ["#{group[:uuid]}-container.json", JSON.generate(group), nil]
124
+ end
125
+
126
+ #: () -> void
127
+ def discard
128
+ @pending = []
129
+ end
130
+
131
+ #: () -> void
132
+ def commit
133
+ @pending.each do |name, content, source|
134
+ path = File.join(@dir, name)
135
+ atomic(path) { |temp| source ? link_or_copy(source, temp) : File.write(temp, content) }
136
+ @written << path
137
+ end
138
+ @pending = []
139
+ end
140
+
141
+ private
142
+
143
+ #: (String, String) -> void
144
+ def link_or_copy(source, temp)
145
+ File.link(source, temp)
146
+ rescue SystemCallError
147
+ FileUtils.cp(source, temp)
148
+ end
149
+
150
+ #: (String) { (String) -> void } -> void
151
+ def atomic(path)
152
+ temp = File.join(File.dirname(path), ".#{File.basename(path)}.tmp-#{Process.pid}-#{rand(36**6).to_s(36)}")
153
+ yield temp
154
+ File.rename(temp, path)
155
+ rescue StandardError
156
+ FileUtils.rm_f(temp) if temp
157
+ raise
158
+ end
159
+ end
160
+
161
+ module_function
162
+
163
+ #: (String) -> String
164
+ def status_for_kind(kind) = FAILED_KINDS.include?(kind) ? "failed" : "broken"
165
+
166
+ #: (String) -> String
167
+ def failure_marker(kind) = "[nukadoko.failure=#{kind}]"
168
+
169
+ #: () -> Array[Hash[Symbol, untyped]]
170
+ def categories
171
+ CATEGORY_NAMES.map do |kind, name|
172
+ { name: name, matchedStatuses: [status_for_kind(kind)], messageRegex: "#{Regexp.escape(failure_marker(kind))}[\\s\\S]*" }
173
+ end
174
+ end
175
+
176
+ # Writes every result of `run` into `dir`, and returns the files it
177
+ # wrote; what it left out goes to `warn`.
178
+ #: (ReportRun, String, ^(String) -> void) -> Array[String]
179
+ def write(run, dir, warn)
180
+ FileUtils.mkdir_p(dir)
181
+ writer = Writer.new(dir)
182
+ environments = run.document[:environments] || []
183
+ info = { "environment" => environments.map { _1[:name] }.join(", ") }
184
+ info["target_version"] = environments.first[:target_version] if environments.size == 1 && environments.first[:target_version]
185
+ begin
186
+ writer.file("categories.json", JSON.generate(categories), note: false)
187
+ writer.file("environment.properties", properties(info), note: false)
188
+ rescue StandardError => e
189
+ warn.("allure categories.json or environment.properties not written: #{e.message}")
190
+ end
191
+ run.scenarios.each do |scenario|
192
+ write_scenario(run, scenario, writer, warn)
193
+ rescue StandardError => e
194
+ writer.discard
195
+ warn.("allure: scenario #{scenario.json[:scenario_record_id]} was not written: #{e.message}")
196
+ end
197
+ writer.written
198
+ end
199
+
200
+ #: (ReportRun, ReportRun::Scenario, Writer, ^(String) -> void) -> void
201
+ def write_scenario(run, scenario, writer, warn)
202
+ record = scenario_record(run, scenario.json)
203
+ writer.begin("#{record[:run_id]}\u0000#{record[:scenario_record_id]}\u0000#{record[:environment]}")
204
+ attach = ->(target, attachment) { write_attachment(run, writer, target, attachment, warn) }
205
+ pickle = scenario.pickle
206
+ document = scenario.feature.document
207
+ posix = scenario.feature.path.tr("\\", "/")
208
+ steps = map_steps(record, scenario, document, pickle, warn)
209
+ mapped = map_scenario(record, document, pickle, posix, run.project_name, steps, scenario.verdict)
210
+ full_name = run.project_name ? "#{run.project_name}:#{posix}##{pickle["name"]}" : "#{posix}##{pickle["name"]}"
211
+ test = test_result(writer, mapped, full_name, title_path(run.project_name, posix, mapped[:feature_name]), attach)
212
+ writer.result(test)
213
+ start = ms(record[:started_at])
214
+ stop = ms(record[:finished_at])
215
+ fixtures = map_hooks(record, start, stop).map { |hook| fixture(hook, attach) }
216
+ fixtures.each do |type, value|
217
+ writer.container({ uuid: writer.name_of(Object.new), name: value[:name], children: [test[:uuid]],
218
+ befores: type == "before" ? [value] : [], afters: type == "after" ? [value] : [] })
219
+ end
220
+ writer.commit
221
+ end
222
+
223
+ # What the run directory says of one execution, in the shape the
224
+ # mapping reads: run.json's scenario entry, with its evidence under
225
+ # the run directory.
226
+ #: (ReportRun, Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
227
+ def scenario_record(run, json)
228
+ document = run.document
229
+ target = (document[:environments] || []).find { _1[:name] == json[:environment] }&.dig(:target_version)
230
+ in_run = ->(relative) { File.join("runs", document[:run_id].to_s, relative) }
231
+ evidence = json[:evidence] ? { **json[:evidence], dir: in_run.(json[:evidence][:dir].to_s) } : { dir: in_run.(File.join("scenarios", json[:scenario_record_id].to_s)), screenshots: [] }
232
+ { scenario_record_id: json[:scenario_record_id], run_id: document[:run_id], status: json[:status], stopped: json[:stopped],
233
+ environment: json[:environment], target_version: target, started_at: json[:started_at], finished_at: json[:finished_at],
234
+ steps: json[:steps], hooks: json[:hooks] || [], evidence: evidence }
235
+ end
236
+
237
+ #: (untyped) -> Integer
238
+ def ms(time) = (Time.iso8601(time.to_s).to_r * 1000).floor
239
+
240
+ #: (String?, String, String) -> Array[String]
241
+ def title_path(project, posix, feature_name)
242
+ dirs = posix.split("/")[0...-1] || []
243
+ path = feature_name.empty? ? dirs : [*dirs, feature_name]
244
+ project ? [project, *path] : path
245
+ end
246
+
247
+ # --- the files allure-js-commons would write ---
248
+
249
+ #: (Writer, Hash[Symbol, untyped], String, Array[String], ^(Hash[Symbol, untyped], Hash[Symbol, untyped]) -> void) -> Hash[Symbol, untyped]
250
+ def test_result(writer, mapped, full_name, title_path, attach)
251
+ test = { uuid: writer.reserve, name: mapped[:name], historyId: nil, status: mapped[:status], statusDetails: {}, stage: "pending",
252
+ steps: [], attachments: [], parameters: mapped[:parameters], labels: [{ name: "language", value: "ruby" },
253
+ { name: "framework", value: "nukadoko" },
254
+ *mapped[:labels], *environment_labels],
255
+ links: mapped[:links], start: mapped[:start], fullName: full_name, titlePath: title_path } #: Hash[Symbol, untyped]
256
+ test[:description] = mapped[:description] if mapped[:description]
257
+ test[:statusDetails] = { message: mapped[:message], **(mapped[:trace] ? { trace: mapped[:trace] } : {}) } if mapped[:message]
258
+ mapped[:attachments].each { attach.(test, _1) }
259
+ test[:steps] = mapped[:steps].map { |step| gwt_step(step, attach) }
260
+ test[:testCaseId] = Digest::MD5.hexdigest(full_name)
261
+ test[:historyId] = "#{test[:testCaseId]}:#{Digest::MD5.hexdigest(parameters_text(test[:parameters]))}"
262
+ test[:stop] = mapped[:stop]
263
+ test.delete(:description) unless test[:description]
264
+ test
265
+ end
266
+
267
+ # `ALLURE_LABEL_*` as the process rendering the report sees it: the
268
+ # person rendering chooses those, and the run recorded none.
269
+ #: () -> Array[Hash[Symbol, untyped]]
270
+ def environment_labels
271
+ ENV.filter_map { |key, value| (name = key.delete_prefix("ALLURE_LABEL_").strip) && key.start_with?("ALLURE_LABEL_") && !name.empty? ? { name: name, value: value } : nil }
272
+ end
273
+
274
+ # The parameters that join historyId, as allure-js-commons orders
275
+ # them: by name, then by value.
276
+ #: (Array[Hash[Symbol, untyped]]) -> String
277
+ def parameters_text(parameters)
278
+ parameters.reject { _1[:excluded] }.sort { |a, b| [collation(a[:name]), collation(a[:value])] <=> [collation(b[:name]), collation(b[:value])] }
279
+ .map { "#{_1[:name]}:#{_1[:value]}" }.join(",")
280
+ end
281
+
282
+ # A sort key near the Unicode collation JavaScript's localeCompare
283
+ # uses: punctuation before digits before letters, letters without
284
+ # case first and lowercase before uppercase on a tie.
285
+ #: (untyped) -> Array[untyped]
286
+ def collation(text)
287
+ primary = text.to_s.each_char.map do |char|
288
+ rank = if char.match?(/[[:alpha:]]/) then 3
289
+ elsif char.match?(/[[:digit:]]/) then 2
290
+ elsif char.match?(/[[:space:]]/) then 0
291
+ else 1
292
+ end
293
+ [rank, char.downcase]
294
+ end
295
+ [primary, text.to_s.swapcase]
296
+ end
297
+
298
+ #: (untyped, String, Integer?, Integer?, ?parameters: Array[Hash[Symbol, untyped]], ?message: String?) -> Hash[Symbol, untyped]
299
+ def step_result(name, status, start, stop, parameters: [], message: nil)
300
+ { status: status, statusDetails: message ? { message: message } : {}, stage: "finished", steps: [], attachments: [],
301
+ parameters: parameters, start: start, name: name, stop: stop }
302
+ end
303
+
304
+ #: (Hash[Symbol, untyped], ^(Hash[Symbol, untyped], Hash[Symbol, untyped]) -> void) -> Hash[Symbol, untyped]
305
+ def gwt_step(step, attach)
306
+ result = step_result(step[:name], step[:status], step[:start], step[:stop], parameters: step[:parameters], message: step[:message])
307
+ step[:attachments].each { attach.(result, _1) }
308
+ result[:steps] = child_steps(step[:child_steps])
309
+ result
310
+ end
311
+
312
+ #: (Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
313
+ def child_steps(children)
314
+ children.map do |child|
315
+ result = step_result(child[:name], child[:status], child[:start], child[:stop], parameters: child[:parameters] || [])
316
+ result[:steps] = child_steps(child[:child_steps] || [])
317
+ result
318
+ end
319
+ end
320
+
321
+ #: (Hash[Symbol, untyped], ^(Hash[Symbol, untyped], Hash[Symbol, untyped]) -> void) -> [untyped, Hash[Symbol, untyped]]
322
+ def fixture(hook, attach)
323
+ value = { status: hook[:status], statusDetails: hook[:message] ? { message: hook[:message] } : {}, stage: "finished", steps: [],
324
+ attachments: [], parameters: hook[:declared_parameters], start: hook[:start], name: hook[:name], stop: hook[:stop] }
325
+ hook[:attachments].each { attach.(value, _1) }
326
+ value[:steps] = child_steps(hook[:child_steps])
327
+ [hook[:type], value]
328
+ end
329
+
330
+ # An attachment that cannot be read, or whose path is refused, costs
331
+ # that attachment only.
332
+ #: (ReportRun, Writer, Hash[Symbol, untyped], Hash[Symbol, untyped], ^(String) -> void) -> void
333
+ def write_attachment(run, writer, target, attachment, warn)
334
+ if attachment[:path]
335
+ begin
336
+ source = run.resolve_recorded(attachment[:path])
337
+ rescue ArgumentError => e
338
+ return warn.("allure: could not attach #{attachment[:path]}: #{e.message}")
339
+ end
340
+ extension = File.extname(source)
341
+ name = writer.attachment_name(extension.empty? ? EXTENSION_BY_MEDIA_TYPE.fetch(attachment[:type], "") : extension)
342
+ begin
343
+ writer.copy(name, source)
344
+ rescue SystemCallError, IOError => e
345
+ return warn.("allure: could not attach #{attachment[:path]}: #{e.message}")
346
+ end
347
+ else
348
+ name = writer.attachment_name(attachment[:extension])
349
+ writer.file(name, attachment[:content])
350
+ end
351
+ target[:attachments] << { name: attachment[:name], source: name, type: attachment[:type] }
352
+ end
353
+
354
+ # A Java properties file, escaped as allure-js-commons escapes it.
355
+ #: (Hash[untyped, untyped]) -> String
356
+ def properties(info)
357
+ info.map { |key, value| "#{escape(key, true, separators: true)}=#{escape(value.to_s, false)}" }.join("\n")
358
+ end
359
+
360
+ #: (String, bool, ?separators: bool) -> String
361
+ def escape(text, key, separators: false)
362
+ leading = true
363
+ codes = text.encode("UTF-16BE").unpack("n*") #: Array[Integer]
364
+ codes.map do |code|
365
+ char = [code].pack("U")
366
+ leading &&= [9, 12, 32].include?(code) unless key
367
+ if separators && "=:".include?(char) && code < 128 then "\\#{char}"
368
+ elsif code > 31 && code < 127
369
+ char == " " && (key || leading) ? "\\ " : char == "\\" ? "\\\\" : char
370
+ elsif (named = { 9 => "\\t", 10 => "\\n", 12 => "\\f", 13 => "\\r" }[code]) then named
371
+ elsif code < 160 || code >= 256 then format("\\u%04x", code)
372
+ else char
373
+ end
374
+ end.join
375
+ end
376
+
377
+ # --- one execution, as the TypeScript engine maps it ---
378
+
379
+ #: (Hash[Symbol, untyped], ReportRun::Scenario, Hash[String, untyped], Hash[String, untyped], ^(String) -> void) -> Array[Hash[Symbol, untyped]]
380
+ def map_steps(record, scenario, document, pickle, warn)
381
+ mapped = [] #: Array[Hash[Symbol, untyped]]
382
+ record[:steps].each_with_index do |entry, index|
383
+ id = entry[:step_record_id]
384
+ step_record = id && scenario.step_records[id]
385
+ unreadable = id && scenario.step_records.key?(id) && step_record.nil?
386
+ previous = mapped.last&.dig(:step, :stop) || ms(record[:started_at])
387
+ begin
388
+ mapped << map_step(index, entry, step_record, unreadable, previous, document, pickle)
389
+ rescue StandardError => e
390
+ warn.("allure: step #{index} of scenario #{record[:scenario_record_id]} was not mapped: #{e.message}")
391
+ span = own_span(step_record)
392
+ mapped << { step: { name: entry[:text], status: "broken", message: e.message, start: span&.first || previous, stop: span&.last || previous,
393
+ attachments: [], parameters: [], child_steps: [] }, span: span, labels: [], links: [] }
394
+ end
395
+ end
396
+ mapped
397
+ end
398
+
399
+ #: (Hash[String, untyped]?) -> [Integer, Integer]?
400
+ def own_span(step_record) = step_record && [ms(step_record["started_at"]), ms(step_record["finished_at"])]
401
+
402
+ #: (Hash[String, untyped]) -> Array[Hash[String, untyped]]
403
+ def scenarios_of(document)
404
+ (document.dig("feature", "children") || []).flat_map do |child|
405
+ [child["scenario"], *(child.dig("rule", "children") || []).map { _1["scenario"] }].compact
406
+ end
407
+ end
408
+
409
+ #: (Hash[String, untyped]) -> Hash[String, Hash[String, untyped]]
410
+ def gherkin_steps(document)
411
+ (document.dig("feature", "children") || []).flat_map do |child|
412
+ [child, *(child.dig("rule", "children") || [])].flat_map { [*(_1.dig("background", "steps") || []), *(_1.dig("scenario", "steps") || [])] }
413
+ end.to_h { [_1["id"], _1] }
414
+ end
415
+
416
+ #: (Hash[String, untyped], Hash[String, untyped], Integer, String) -> String
417
+ def step_name(document, pickle, index, text)
418
+ id = pickle.dig("steps", index, "astNodeIds", 0)
419
+ keyword = id && gherkin_steps(document)[id]&.dig("keyword")
420
+ keyword ? "#{keyword}#{text}" : text
421
+ end
422
+
423
+ #: (Hash[String, untyped], Hash[String, untyped]) -> untyped
424
+ def example_row(document, pickle)
425
+ rows = scenarios_of(document).flat_map { |scenario| (scenario["examples"] || []).flat_map { |examples| (examples["tableBody"] || []).map { [_1["id"], [examples, _1]] } } }.to_h
426
+ pickle["astNodeIds"].to_a.lazy.map { rows[_1] }.find(&:itself)
427
+ end
428
+
429
+ #: (Array[Hash[String, untyped]]) -> String
430
+ def csv_row(cells) = cells.map { (value = _1["value"].to_s).match?(/[",\r\n]/) ? %("#{value.gsub('"', '""')}") : value }.join(",")
431
+
432
+ #: (String, String, String, String) -> Hash[Symbol, untyped]
433
+ def buffer(name, type, content, extension) = { name: name, type: type, content: content, extension: extension }
434
+
435
+ #: (String, String, String) -> Hash[Symbol, untyped]
436
+ def path_attachment(name, type, path) = { name: name, type: type, path: path }
437
+
438
+ #: (untyped, String) -> String
439
+ def join_relative(dir, file) = "#{dir.to_s.sub(%r{/+\z}, "")}/#{file}"
440
+
441
+ #: (String) -> String
442
+ def content_type(file) = (dot = file.rindex(".")) ? MEDIA_TYPE_BY_EXTENSION.fetch(file[dot..].to_s.downcase, "application/octet-stream") : "application/octet-stream"
443
+
444
+ # Attachments, log lines, links, labels, and parameters a step or a
445
+ # hook declared, the same shape either way.
446
+ #: (Hash[String, untyped]?, String?, Integer?) -> Hash[Symbol, untyped]
447
+ def map_declared(declared, dir, at)
448
+ return { attachments: [], child_steps: [], links: [], labels: [], parameters: [] } unless declared
449
+
450
+ { attachments: (declared["attachments"] || []).map { path_attachment("declared: #{_1}", content_type(_1), join_relative(dir, _1)) },
451
+ child_steps: (declared["logs"] || []).map { { name: _1, start: at, stop: at, status: "passed" } },
452
+ links: (declared["links"] || []).map { { url: _1["url"], name: _1["name"], type: _1["type"] }.compact },
453
+ labels: (declared["labels"] || []).map { { name: _1["name"], value: _1["value"] } },
454
+ parameters: (declared["parameters"] || []).map { { name: _1["name"], value: _1["value"] } } }
455
+ end
456
+
457
+ #: (Hash[Symbol, untyped], Hash[String, untyped]?, bool) -> Hash[Symbol, untyped]
458
+ def step_outcome(entry, step_record, unreadable)
459
+ if unreadable
460
+ return { status: "broken", message: "step record #{entry[:step_record_id]} could not be read; run.json records this step as #{entry[:status]}" }
461
+ end
462
+
463
+ case entry[:status]
464
+ when "passed" then { status: "passed" }
465
+ when "skipped" then { status: "skipped" }
466
+ # A vocabulary defect has no step record to carry a kind.
467
+ when "undefined", "ambiguous" then { status: "broken", message: entry.dig(:error, :message) }
468
+ else
469
+ if step_record && step_record["status"] == "failed"
470
+ kind = step_record.dig("error", "kind")
471
+ raw = step_record.dig("error", "message")
472
+ { status: status_for_kind(kind), message: "#{failure_marker(kind)} #{raw}", raw: raw, kind: kind }
473
+ else
474
+ { status: "failed", message: entry.dig(:error, :message) }
475
+ end
476
+ end
477
+ end
478
+
479
+ #: (Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
480
+ def hook_outcome(hook)
481
+ return { status: "passed" } if hook[:status] == "passed"
482
+ return { status: "broken" } unless hook[:error]
483
+
484
+ kind = hook[:error][:kind]
485
+ { status: status_for_kind(kind), message: "#{failure_marker(kind)} #{hook[:error][:message]}", raw: hook[:error][:message], kind: kind }
486
+ end
487
+
488
+ #: (Hash[String, untyped]) -> String
489
+ def action_name(action)
490
+ target = action["selector"] || action["url"]
491
+ if action["method"] == "expect" && action["expression"]
492
+ matcher = action["is_not"] == true ? "not #{action["expression"]}" : action["expression"]
493
+ return target ? "expect #{target} #{matcher}" : "expect #{matcher}"
494
+ end
495
+ target ? "#{action["method"]} #{target}" : action["method"]
496
+ end
497
+
498
+ # Sections, polls, and actions as one timeline in the order they
499
+ # began; on one instant, sections, then polls, then actions.
500
+ #: (Hash[String, untyped], Integer) -> Array[Hash[Symbol, untyped]]
501
+ def timeline(source, anchor)
502
+ entries = [] #: Array[[String, Hash[Symbol, untyped]]]
503
+ (source["sections"] || []).each { entries << [_1["at"], { name: _1["label"], start: ms(_1["at"]), stop: ms(_1["at"]), status: "passed" }] }
504
+ (source["polls"] || []).each do |poll|
505
+ start = ms(poll["at"])
506
+ status = { "resolved" => "passed", "timed_out" => "failed" }.fetch(poll["outcome"], "broken")
507
+ entries << [poll["at"], { name: "#{poll["description"] || "poll"} (#{poll["attempts"]} attempts)", start: start, stop: start + poll["waited_ms"].to_i, status: status }]
508
+ end
509
+ (source["actions"] || []).each do |action|
510
+ start = ms(action["at"])
511
+ entries << [action["at"], { name: action_name(action), start: start, stop: start + action["ms"].to_i, status: action["outcome"] == "failed" ? "failed" : "passed" }]
512
+ end
513
+ steps = entries.each_with_index.sort_by { |(at, _), index| [at, index] }.map { _1.first.last }
514
+ if (total = source.dig("truncated", "actions"))
515
+ last = steps.last&.dig(:stop) || anchor
516
+ steps << { name: "... #{total - (source["actions"] || []).size} more actions not shown", start: last, stop: last, status: "passed" }
517
+ end
518
+ steps
519
+ end
520
+
521
+ #: (Array[untyped]?, Integer?) -> String?
522
+ def page_event_count(entries, total)
523
+ return nil if entries.nil? || entries.empty?
524
+
525
+ total ? "#{entries.size} of #{total}" : entries.size.to_s
526
+ end
527
+
528
+ #: (Array[Hash[String, untyped]]?) -> Array[Hash[Symbol, untyped]]
529
+ def calls(entries)
530
+ (entries || []).map do |entry|
531
+ { name: entry["step"], start: ms(entry["started_at"]), stop: ms(entry["finished_at"]),
532
+ status: entry["error"] ? status_for_kind(entry.dig("error", "kind")) : "passed",
533
+ parameters: [{ name: "args", value: js_json(entry["args"]) }, *(entry.key?("result") ? [{ name: "result", value: js_json(entry["result"]) }] : [])],
534
+ child_steps: calls(entry["calls"]) }
535
+ end
536
+ end
537
+
538
+ #: (Hash[String, untyped]?) -> String
539
+ def channel(measured) = measured.nil? ? "none" : "#{measured["step_record_id"]} #{measured["channel"]}"
540
+
541
+ # A judged-as claim compared nothing: a judgment decides it outside
542
+ # the results, and skipped is the one status that claims neither.
543
+ #: (String) -> String
544
+ def claim_status(outcome)
545
+ { "for-judgment" => "skipped", "held" => "passed", "broken" => "failed" }.fetch(outcome, "broken")
546
+ end
547
+
548
+ #: (Hash[String, untyped]) -> Array[Hash[Symbol, untyped]]
549
+ def claim_parameters(claim)
550
+ parameters = [] #: Array[Hash[Symbol, untyped]]
551
+ parameters << { name: "actual", value: js_json(claim["actual"]) } if claim.key?("actual") && !claim["actual"].nil?
552
+ parameters << { name: "actual from", value: claim["actual_from"] }
553
+ parameters << { name: "expected", value: js_json(claim["expected"]) } if claim.key?("expected") && !claim["expected"].nil?
554
+ parameters << { name: "expected from", value: claim["expected_from"] } if claim.key?("expected_from")
555
+ return parameters if claim["outcome"] == "unobserved"
556
+
557
+ parameters << { name: "measured", value: channel(claim["measured"]) }
558
+ unless claim.key?("each")
559
+ parameters << { name: "expected measured", value: channel(claim["expected_measured"]) } if claim.key?("expected_measured")
560
+ return parameters
561
+ end
562
+ declared = [*(claim.dig("each", "where") || []).each_with_index.map { ["where[#{_2}]", _1] },
563
+ *(claim.dig("each", "claims") || []).each_with_index.map { ["claims[#{_2}]", _1] }]
564
+ declared.each { |name, entry| parameters << { name: "expected measured #{name}", value: channel(entry["expected_measured"]) } if entry.key?("expected_measured") }
565
+ parameters
566
+ end
567
+
568
+ #: (Array[Hash[String, untyped]]?, Integer) -> Array[Hash[Symbol, untyped]]
569
+ def map_claims(claims, at)
570
+ (claims || []).map do |claim|
571
+ { name: ClaimLine.line(JSON.parse(JSON.generate(claim), symbolize_names: true)), start: at, stop: at,
572
+ status: claim_status(claim["outcome"]), parameters: claim_parameters(claim) }
573
+ end
574
+ end
575
+
576
+ # JSON as JavaScript writes it: a whole-number float has no fraction.
577
+ #: (untyped) -> String
578
+ def js_json(value) = JSON.generate(js_value(value))
579
+
580
+ #: (untyped) -> untyped
581
+ def js_value(value)
582
+ case value
583
+ when Float then value.finite? && value == value.floor && value.abs < 1e21 ? value.to_i : value
584
+ when Array then value.map { js_value(_1) }
585
+ when Hash then value.transform_values { js_value(_1) }
586
+ else value
587
+ end
588
+ end
589
+
590
+ #: (Hash[String, untyped]?) -> Array[[String, String, String]]
591
+ def judged_view_attachments(view)
592
+ pages = view&.dig("pages") || []
593
+ pages.flat_map do |page|
594
+ which = pages.size == 1 ? "" : " (page #{page["page"]}#{page["as"].nil? ? "" : " of #{page["as"]}"})"
595
+ [*(page["screenshot"] ? [["judged view#{which}", page.dig("screenshot", "file"), "image/png"]] : []),
596
+ *(page["aria"] ? [["judged view ARIA#{which}", page.dig("aria", "file"), "text/plain"]] : [])]
597
+ end
598
+ end
599
+
600
+ #: (Integer, Hash[Symbol, untyped], Hash[String, untyped]?, bool, Integer, Hash[String, untyped], Hash[String, untyped]) -> Hash[Symbol, untyped]
601
+ def map_step(index, entry, step_record, unreadable, previous, document, pickle)
602
+ outcome = step_outcome(entry, step_record, unreadable)
603
+ span = own_span(step_record)
604
+ start, stop = span || [previous, previous]
605
+ attachments = [] #: Array[Hash[Symbol, untyped]]
606
+ argument = pickle.dig("steps", index, "argument")
607
+ rows = argument&.dig("dataTable", "rows")
608
+ attachments << buffer("Data table", "text/csv", "#{rows.map { csv_row(_1["cells"]) }.join("\n")}\n", ".csv") if rows && !rows.empty?
609
+ attachments << buffer("Doc string", "text/plain", argument.dig("docString", "content"), ".txt") if argument&.dig("docString")
610
+ parameters = [] #: Array[Hash[Symbol, untyped]]
611
+ declared = map_declared(nil, nil, nil)
612
+ children = [] #: Array[Hash[Symbol, untyped]]
613
+ if step_record
614
+ evidence = step_record["evidence"] || {}
615
+ dir = evidence["dir"]
616
+ mutates = step_record["mutates"]
617
+ parameters << { name: "step record id", value: step_record["step_record_id"] }
618
+ parameters << { name: "mutates (declared)", value: mutates.nil? ? "not declared" : mutates.to_s }
619
+ if (world = step_record["world"])
620
+ parameters << { name: "world reads (observed)", value: world["reads"].join(", ") }
621
+ parameters << { name: "world writes (observed)", value: world["writes"].join(", ") }
622
+ end
623
+ used = step_record["used"] || []
624
+ parameters << { name: "used step records", value: used.map { _1["step_record_id"] }.join(", ") } unless used.empty?
625
+ required = step_record["required_env"] || []
626
+ parameters << { name: "required env", value: required.join(", ") } unless required.empty?
627
+ if (events = step_record["page_events"])
628
+ { "console_errors" => "console errors (observed)", "page_errors" => "page errors (observed)", "failed_requests" => "failed requests (observed)" }.each do |key, name|
629
+ count = page_event_count(events[key], events.dig("truncated", key))
630
+ parameters << { name: name, value: count } if count
631
+ end
632
+ end
633
+ attachments << buffer("record.json", "application/json", JSON.pretty_generate(js_value(step_record)), ".json")
634
+ if step_record["status"] == "passed" && !step_record["result"].nil?
635
+ attachments << buffer("result", "application/json", JSON.pretty_generate(js_value(step_record["result"])), ".json")
636
+ end
637
+ { "http" => "http log", "mcp" => "mcp log", "websocket" => "websocket log" }.each do |key, name|
638
+ attachments << path_attachment(name, "text/plain", join_relative(dir, evidence[key])) if evidence[key]
639
+ end
640
+ attachments << path_attachment("trace", TRACE, join_relative(dir, evidence["trace"])) if evidence["trace"]
641
+ (evidence["named_traces"] || []).each { attachments << path_attachment("trace (#{_1["as"]})", TRACE, join_relative(dir, _1["file"])) }
642
+ (evidence["screenshots"] || []).each { attachments << path_attachment(_1["file"], "image/png", join_relative(dir, _1["file"])) }
643
+ judged_view_attachments(step_record["judged_view"]).each { |name, file, type| attachments << path_attachment(name, type, join_relative(dir, file)) }
644
+ (evidence["attachments"] || []).each { attachments << path_attachment(_1["name"], content_type(_1["file"]), join_relative(dir, _1["file"])) }
645
+ declared = map_declared(step_record["declared"], dir, start)
646
+ attachments.concat(declared[:attachments])
647
+ parameters.concat(declared[:parameters])
648
+ children = [*declared[:child_steps], *timeline(step_record, ms(step_record["started_at"])), *calls(step_record["calls"]),
649
+ *map_claims(step_record["claims"], stop)]
650
+ end
651
+ { step: { name: step_name(document, pickle, index, entry[:text]), status: outcome[:status], message: outcome[:message],
652
+ start: start, stop: stop, attachments: attachments, parameters: parameters, child_steps: children },
653
+ span: span, labels: declared[:labels], links: declared[:links],
654
+ failure: outcome[:kind] && outcome[:message] ? { kind: outcome[:kind], message: outcome[:message], raw: outcome[:raw] || outcome[:message] } : nil,
655
+ unreadable: unreadable ? true : nil }
656
+ end
657
+
658
+ # The first classified failure, a step's before a hook's.
659
+ #: (Array[Hash[Symbol, untyped]], Array[untyped]) -> Hash[Symbol, untyped]?
660
+ def first_failure(steps, hooks)
661
+ steps.each { return _1[:failure] if _1[:failure] }
662
+ hooks.each do |hook|
663
+ outcome = hook_outcome(hook)
664
+ return { kind: outcome[:kind], message: outcome[:message], raw: outcome[:raw] || outcome[:message] } if outcome[:kind] && outcome[:message]
665
+ end
666
+ nil
667
+ end
668
+
669
+ #: (Hash[String, untyped]) -> Array[Hash[Symbol, untyped]]
670
+ def tag_labels(pickle)
671
+ (pickle["tags"] || []).map do |tag|
672
+ name = tag["name"]
673
+ if (id = ALLURE_ID_TAG.match(name)) then { name: "ALLURE_ID", value: id[1] }
674
+ elsif (label = ALLURE_LABEL_TAG.match(name)) then { name: label[1], value: label[2] }
675
+ else { name: "tag", value: name }
676
+ end
677
+ end
678
+ end
679
+
680
+ #: (Hash[Symbol, untyped], Hash[String, untyped], Hash[String, untyped], String, String?, Array[Hash[Symbol, untyped]], Hash[Symbol, untyped]?) -> Hash[Symbol, untyped]
681
+ def map_scenario(record, document, pickle, posix, project, steps, verdict)
682
+ scenario = scenarios_of(document).find { pickle["astNodeIds"].to_a.include?(_1["id"]) }
683
+ feature_name = document.dig("feature", "name") || ""
684
+ start = ms(record[:started_at])
685
+ stop = ms(record[:finished_at])
686
+ failure = record[:status] == "failed" ? first_failure(steps, record[:hooks]) : nil
687
+ unreadable = steps.find { _1[:unreadable] }
688
+ row = example_row(document, pickle)
689
+ labels = [{ name: "feature", value: feature_name }, { name: "package", value: [*project, *posix.split("/")].join(".") }, *tag_labels(pickle),
690
+ { name: "env", value: record[:environment] }, *(verdict ? [{ name: "role", value: verdict[:role] }] : []),
691
+ *steps.flat_map { _1[:labels] }, *(failure ? [{ name: "nukadoko.failure", value: failure[:kind] }] : [])]
692
+ attachments = [] #: Array[Hash[Symbol, untyped]]
693
+ if row
694
+ examples = row.first
695
+ header = csv_row(examples.dig("tableHeader", "cells") || [])
696
+ body = (examples["tableBody"] || []).map { csv_row(_1["cells"]) }.join("\n")
697
+ attachments << buffer("Examples", "text/csv", "#{header}\n#{body}\n", ".csv") unless header.empty? && body.empty?
698
+ end
699
+ (record.dig(:evidence, :screenshots) || []).each { attachments << path_attachment(_1[:file], "image/png", join_relative(record[:evidence][:dir], _1[:file])) }
700
+ headers = row ? (row.first.dig("tableHeader", "cells") || []).map { _1["value"] } : []
701
+ examples = row ? row.last["cells"].each_with_index.map { |cell, index| { name: headers[index] || "arg#{index}", value: cell["value"] } } : []
702
+ context = [*(record[:target_version] ? [{ name: "target_version", value: record[:target_version], excluded: true }] : []),
703
+ *(verdict ? [{ name: "verdict", value: verdict[:verdict], excluded: true }] : [])]
704
+ identity = [{ name: "nukadoko.scenario.steps", value: pickle["steps"].map { _1["text"] }.join("\n"), mode: "hidden" },
705
+ { name: "environment", value: record[:environment] }]
706
+ description = [scenario&.dig("description"), document.dig("feature", "description")].map { _1.to_s.strip }.find { !_1.empty? }
707
+ stopped = record[:stopped]
708
+ message = failure&.dig(:message) ||
709
+ (if record[:status] == "passed" then unreadable&.dig(:step, :message)
710
+ elsif record[:status] == "stopped" && stopped
711
+ "the walk (nuka run --step) was stopped after step #{stopped[:after_step]} with nuka step stop, so the steps after it did not run"
712
+ end)
713
+ previous = start
714
+ placed_steps = steps.map do |outcome|
715
+ from, to = outcome[:span] || [previous, previous]
716
+ previous = to
717
+ { **outcome[:step], start: from, stop: to }
718
+ end
719
+ status = if record[:status] == "stopped" then "skipped"
720
+ elsif record[:status] == "passed" && unreadable then "broken"
721
+ else record[:status]
722
+ end
723
+ { name: verdict&.dig(:role) == "control" ? "#{pickle["name"]} (control)" : pickle["name"], feature_name: feature_name, description: description,
724
+ status: status, message: message, trace: failure&.dig(:raw), start: start, stop: stop, labels: labels,
725
+ links: steps.flat_map { _1[:links] }.uniq { [_1[:url], _1[:name], _1[:type]] }, parameters: [*examples, *context, *identity],
726
+ attachments: attachments, steps: placed_steps }
727
+ end
728
+
729
+ # A hook record holds no time of its own: a before hook sits at the
730
+ # scenario's start and an after hook at its end, both zero-width.
731
+ #: (Hash[Symbol, untyped], Integer, Integer) -> Array[Hash[Symbol, untyped]]
732
+ def map_hooks(record, start, stop)
733
+ record[:hooks].map do |hook|
734
+ hook = JSON.parse(JSON.generate(hook))
735
+ symbol = hook.transform_keys(&:to_sym)
736
+ symbol[:error] = symbol[:error]&.transform_keys(&:to_sym)
737
+ outcome = hook_outcome(symbol)
738
+ at = hook["type"] == "before" ? start : stop
739
+ declared = map_declared(hook["declared"], record[:evidence][:dir], at)
740
+ fallback = { "before" => "Before", "after" => "After" }.fetch(hook["type"]) { "AfterStep[#{hook["step_index"]}]" }
741
+ attachments = [*declared[:attachments]]
742
+ attachments << path_attachment("trace", TRACE, join_relative(record[:evidence][:dir], hook["trace"])) if hook["trace"]
743
+ (hook["named_traces"] || []).each { attachments << path_attachment("trace (#{_1["as"]})", TRACE, join_relative(record[:evidence][:dir], _1["file"])) }
744
+ { type: hook["type"] == "before" ? "before" : "after", name: hook["name"].to_s.empty? ? fallback : hook["name"], status: outcome[:status],
745
+ message: outcome[:message], start: at, stop: at, attachments: attachments,
746
+ child_steps: [*declared[:child_steps], *timeline(hook, at)], declared_parameters: declared[:parameters] }
747
+ end
748
+ end
749
+ end
750
+ end
751
+ end