@plune-ai/playwright 0.5.0 → 0.7.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.
package/dist/index.js CHANGED
@@ -1,25 +1,30 @@
1
1
  // src/index.ts
2
2
  import { readFileSync as readFileSync2 } from "fs";
3
+ import { resolve as resolve2 } from "path";
3
4
  import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
4
5
 
5
6
  // ../../dist/reporter-core.js
6
- import { createHash, randomUUID } from "crypto";
7
+ import { createHash as createHash2, randomUUID } from "crypto";
7
8
  import { promises as disk } from "fs";
8
9
  import { basename as basename2, extname } from "path";
9
10
  import { TextDecoder } from "util";
10
11
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
11
12
  import { homedir } from "os";
12
13
  import { dirname, join } from "path";
13
- import { request as httpRequest } from "http";
14
- import { request as httpsRequest } from "https";
14
+ import { createReadStream, openAsBlob } from "fs";
15
+ import { pipeline } from "stream";
16
+ import { Agent as HttpAgent, request as httpRequest } from "http";
17
+ import { Agent as HttpsAgent, request as httpsRequest } from "https";
15
18
  import * as path from "path";
16
19
  import { existsSync as existsSync2 } from "fs";
17
20
  import { homedir as homedir2 } from "os";
18
21
  import { dirname as dirname2, join as join2, posix, resolve } from "path";
19
22
  import { stripVTControlCharacters } from "util";
23
+ import { createHash } from "crypto";
24
+ import { createReadStream as createReadStream2 } from "fs";
20
25
  import * as fs from "fs";
21
26
  import * as path2 from "path";
22
- import { createHash as createHash2 } from "crypto";
27
+ import { createHash as createHash3 } from "crypto";
23
28
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
24
29
  function resolveApiUrl(explicit) {
25
30
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -39,20 +44,32 @@ function loadToken() {
39
44
  return null;
40
45
  }
41
46
  }
42
- var RETRY_DELAYS_MS = [300, 900];
47
+ var BACKOFF_BASE_MS = 300;
48
+ var BACKOFF_CAP_MS = 1e4;
49
+ var DEFAULT_RETRIES = 2;
50
+ var RETRY_AFTER_CAP_MS = 6e4;
51
+ function parseRetryAfter(raw, now = Date.now()) {
52
+ const text = raw?.trim();
53
+ if (text === void 0 || text === "") return null;
54
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : (Date.parse(text) - now) / 1e3;
55
+ if (!Number.isFinite(seconds)) return null;
56
+ return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
57
+ }
58
+ var POOLS = { "http:": new HttpAgent({ keepAlive: true }), "https:": new HttpsAgent({ keepAlive: true }) };
43
59
  var IDLE_MS = 3e5;
44
60
  function nodeTransport(url, init, idleMs = IDLE_MS) {
45
- return new Promise((resolve2, reject) => {
61
+ return new Promise((resolve22, reject) => {
46
62
  const target = new URL(url);
47
63
  const send = target.protocol === "https:" ? httpsRequest : httpRequest;
48
- const req = send(target, { method: init.method, headers: init.headers }, (res) => {
64
+ const agent = POOLS[target.protocol === "https:" ? "https:" : "http:"];
65
+ const req = send(target, { method: init.method, headers: init.headers, agent }, (res) => {
49
66
  const chunks = [];
50
67
  res.on("data", (chunk2) => chunks.push(chunk2));
51
68
  res.on("error", reject);
52
69
  res.on("end", () => {
53
70
  const status = res.statusCode ?? 0;
54
71
  const text = Buffer.concat(chunks).toString("utf8");
55
- resolve2({
72
+ resolve22({
56
73
  ok: status >= 200 && status <= 299,
57
74
  status,
58
75
  headers: {
@@ -70,20 +87,60 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
70
87
  req.end(init.body);
71
88
  });
72
89
  }
90
+ var withoutLength = (headers) => Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-length"));
91
+ function nodePut(url, headers, source, idleMs) {
92
+ return new Promise((resolve22, reject) => {
93
+ const target = new URL(url);
94
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
95
+ const length = "body" in source ? source.body.length : source.size;
96
+ let answered;
97
+ const settle = (err) => answered !== void 0 ? resolve22(answered) : reject(err);
98
+ const req = send(
99
+ target,
100
+ { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
101
+ (res) => {
102
+ const retry = res.headers["retry-after"];
103
+ answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
104
+ res.on("error", settle);
105
+ res.on("close", () => {
106
+ resolve22(answered);
107
+ req.destroy();
108
+ });
109
+ res.resume();
110
+ }
111
+ );
112
+ req.setTimeout(idleMs, () => req.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
113
+ req.on("error", settle);
114
+ if ("body" in source) req.end(source.body);
115
+ else pipeline(createReadStream(source.path), req, (err) => err ? settle(err) : void 0);
116
+ });
117
+ }
118
+ var codeOfError = (err) => {
119
+ const code = err?.code;
120
+ return typeof code === "string" && /^[A-Z0-9_]{2,40}$/.test(code) ? code : "network";
121
+ };
73
122
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
74
123
  async function detailOf(res) {
75
124
  try {
76
125
  const body = await res.json();
77
- return typeof body.error === "string" ? body.error : "";
126
+ const q = body.quota;
127
+ return {
128
+ ...typeof body.shardsExpected === "number" && Number.isInteger(body.shardsExpected) ? { shardsExpected: body.shardsExpected } : {},
129
+ detail: typeof body.error === "string" ? body.error : "",
130
+ ...typeof q === "object" && q !== null && !Array.isArray(q) ? { quota: q } : {},
131
+ ...typeof body.code === "string" && /^[a-z0-9_]{1,60}$/.test(body.code) ? { code: body.code } : {}
132
+ };
78
133
  } catch {
79
- return "";
134
+ return { detail: "" };
80
135
  }
81
136
  }
82
- function retryAfterMs(res) {
83
- const raw = res.headers.get("retry-after");
84
- if (raw === null) return null;
85
- const seconds = Number(raw.trim());
86
- return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : null;
137
+ function describeQuota(q) {
138
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
139
+ const kind = typeof q["kind"] === "string" ? q["kind"].slice(0, 60) : "limit";
140
+ const [used, limit] = [num(q["used"]), num(q["limit"])];
141
+ const parts = [used !== void 0 && limit !== void 0 ? `${kind}: ${used} of ${limit} used` : kind];
142
+ if (typeof q["resetsAt"] === "string" && q["resetsAt"] !== "") parts.push(`resets ${q["resetsAt"].slice(0, 40)}`);
143
+ return parts.join(", ");
87
144
  }
88
145
  function classify(status) {
89
146
  if (status === 401 || status === 403) return "auth";
@@ -95,15 +152,34 @@ function classify(status) {
95
152
  function createClient(opts) {
96
153
  const doFetch = opts.fetchImpl ?? nodeTransport;
97
154
  const wait = opts.wait ?? sleep;
155
+ const uploadRetries = opts.uploadRetries === void 0 ? void 0 : Math.max(0, Math.floor(opts.uploadRetries));
156
+ const random = opts.random ?? Math.random;
157
+ const now = opts.now ?? Date.now;
158
+ let pausedUntil = 0;
159
+ const jittered = (ms) => Math.round(ms * (1 + random() * 0.5));
160
+ async function backOff(attempt, said) {
161
+ opts.onRetry?.();
162
+ const ms = jittered(said ?? Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_CAP_MS));
163
+ const until = now() + ms;
164
+ pausedUntil = Math.max(pausedUntil, until);
165
+ await wait(ms);
166
+ return until;
167
+ }
168
+ async function respectPause(mine) {
169
+ const left = pausedUntil - now();
170
+ if (pausedUntil > mine && left > 0) await wait(left + Math.round(random() * 250));
171
+ }
98
172
  const base = opts.apiUrl.replace(/\/+$/, "");
99
173
  const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
100
- async function send(method, path3, payload) {
174
+ async function send(method, path3, payload, retries = DEFAULT_RETRIES) {
101
175
  let last = {
102
176
  kind: "unavailable",
103
177
  status: null,
104
178
  detail: "no attempt was made"
105
179
  };
106
- for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {
180
+ let mine = 0;
181
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
182
+ await respectPause(mine);
107
183
  let res;
108
184
  try {
109
185
  res = await doFetch(`${base}${path3}`, {
@@ -116,7 +192,8 @@ function createClient(opts) {
116
192
  });
117
193
  } catch (err) {
118
194
  last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
119
- if (attempt < RETRY_DELAYS_MS.length) await wait(RETRY_DELAYS_MS[attempt]);
195
+ if (attempt >= Math.min(retries, DEFAULT_RETRIES)) break;
196
+ mine = await backOff(attempt, null);
120
197
  continue;
121
198
  }
122
199
  if (res.ok) {
@@ -127,23 +204,95 @@ function createClient(opts) {
127
204
  return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
128
205
  }
129
206
  }
130
- const detail = scrub(await detailOf(res));
207
+ const said = await detailOf(res);
131
208
  const kind = classify(res.status);
132
- last = { kind, status: res.status, detail };
209
+ last = { kind, status: res.status, detail: scrub(said.detail), ...said.code !== void 0 ? { code: said.code } : {}, ...said.shardsExpected !== void 0 ? { shardsExpected: said.shardsExpected } : {} };
133
210
  if (kind !== "unavailable") break;
134
- if (attempt < RETRY_DELAYS_MS.length) {
135
- await wait(retryAfterMs(res) ?? RETRY_DELAYS_MS[attempt]);
211
+ const said429 = parseRetryAfter(res.headers.get("retry-after"), now());
212
+ if (res.status === 429 && (said.quota !== void 0 || said429 === null)) {
213
+ last.kind = "invalid";
214
+ last.detail = `quota exceeded (${said.quota === void 0 ? "no Retry-After" : scrub(describeQuota(said.quota))})`;
215
+ if (said.detail) last.detail += ` \u2014 ${scrub(said.detail)}`;
216
+ break;
136
217
  }
218
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
219
+ mine = await backOff(attempt, said429);
137
220
  }
138
221
  return { ok: false, ...last };
139
222
  }
140
223
  return {
141
- post: (path3, body) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }),
142
- upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }),
143
- del: (path3) => send("DELETE", path3)
224
+ post: (path3, body, retries) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }, retries),
225
+ upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
226
+ del: (path3) => send("DELETE", path3),
227
+ get: (path3) => send("GET", path3),
228
+ async put(url, headers, source) {
229
+ const putRetries = uploadRetries ?? 3;
230
+ let last = { ok: false, status: null, code: "network" };
231
+ let mine = 0;
232
+ for (let attempt = 0; attempt <= putRetries; attempt += 1) {
233
+ await respectPause(mine);
234
+ try {
235
+ let status;
236
+ let retryAfter;
237
+ if (opts.fetchImpl === void 0) ({ status, retryAfter } = await nodePut(url, headers, source, IDLE_MS));
238
+ else {
239
+ const body = "body" in source ? source.body : await openAsBlob(source.path);
240
+ const res = await opts.fetchImpl(url, { method: "PUT", headers: withoutLength(headers), body });
241
+ await res.arrayBuffer().catch(() => void 0);
242
+ status = res.status;
243
+ retryAfter = res.headers.get("retry-after");
244
+ }
245
+ if (status >= 200 && status <= 299) return { ok: true };
246
+ last = { ok: false, status, code: `bucket_${status}` };
247
+ if (status < 500 && status !== 429) return last;
248
+ const said = parseRetryAfter(retryAfter, now());
249
+ if (attempt >= (said === null ? Math.min(putRetries, 3) : putRetries)) return last;
250
+ mine = await backOff(attempt, said);
251
+ continue;
252
+ } catch (err) {
253
+ last = { ok: false, status: null, code: codeOfError(err) };
254
+ }
255
+ if (attempt >= Math.min(putRetries, 3)) return last;
256
+ mine = await backOff(attempt, null);
257
+ }
258
+ return last;
259
+ }
144
260
  };
145
261
  }
146
262
  var UNSUPPORTED_VARS = ["PLUNE_GROUP"];
263
+ var SHARDS_MAX = 1e3;
264
+ function shardOf(env) {
265
+ const raw = value(env, "PLUNE_SHARD");
266
+ if (raw === void 0) return {};
267
+ const m = /^(\d{1,4})\/(\d{1,4})$/.exec(raw);
268
+ const [k, n] = m ? [Number(m[1]), Number(m[2])] : [0, 0];
269
+ if (k >= 1 && k <= n && n <= SHARDS_MAX) return { shard: { index: k, total: n } };
270
+ return {
271
+ error: `PLUNE_SHARD=${JSON.stringify(raw.slice(0, 40))} is not "k/N" with 1 <= k <= N <= ${SHARDS_MAX} (for example 2/4) - nothing was sent.`
272
+ };
273
+ }
274
+ function configurationOf(env) {
275
+ const raw = value(env, "PLUNE_CONFIGURATION");
276
+ if (raw === void 0) return {};
277
+ const pairs = [];
278
+ for (const pair of raw.split(";").map((s) => s.trim()).filter((s) => s !== "")) {
279
+ const at = pair.indexOf("=");
280
+ const name = at < 0 ? "" : pair.slice(0, at).trim();
281
+ const label = at < 0 ? "" : pair.slice(at + 1).trim();
282
+ const twice = pairs.find(([seen]) => seen.toLowerCase() === name.toLowerCase());
283
+ const why = at < 0 ? 'has no "="' : name === "" ? "has no group name" : label === "" ? "has no value" : twice !== void 0 ? `names the group ${JSON.stringify(twice[0])} a second time` : void 0;
284
+ if (why !== void 0) {
285
+ return {
286
+ error: `PLUNE_CONFIGURATION: ${JSON.stringify(pair.slice(0, 40))} ${why} - write it as "Group=Value;Group=Value" (for example "Browser=Chrome;Operating system=Windows") - nothing was sent.`
287
+ };
288
+ }
289
+ pairs.push([name, label]);
290
+ }
291
+ return pairs.length === 0 ? {} : { configuration: Object.fromEntries(pairs) };
292
+ }
293
+ var UPLOAD_CONCURRENCY = { min: 1, max: 32, default: 16 };
294
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
295
+ var IMPORT_TIMEOUT = { min: 0, max: 86400, default: 600 };
147
296
  function value(env, name) {
148
297
  const raw = env[name]?.trim();
149
298
  return raw === void 0 || raw === "" ? void 0 : raw;
@@ -158,6 +307,14 @@ function count(env, name) {
158
307
  const n = Number(raw);
159
308
  return Number.isInteger(n) && n > 0 ? n : void 0;
160
309
  }
310
+ function bounded(env, name, range, warnings) {
311
+ const raw = value(env, name);
312
+ if (raw === void 0) return void 0;
313
+ const n = Number(raw);
314
+ if (/^\d+$/.test(raw) && n >= range.min && n <= range.max) return n;
315
+ warnings.push(`${name}=${JSON.stringify(raw.slice(0, 40))} is not a whole number from ${range.min} to ${range.max} \u2014 using ${range.default}.`);
316
+ return void 0;
317
+ }
161
318
  function list(env, name) {
162
319
  const raw = value(env, name);
163
320
  if (raw === void 0) return void 0;
@@ -170,11 +327,17 @@ function readEnv(env = process.env) {
170
327
  const apiUrl = value(env, "PLUNE_API_URL");
171
328
  const fallbackPath = value(env, "PLUNE_FALLBACK");
172
329
  const batchSize = count(env, "PLUNE_BATCH_SIZE");
330
+ const warnings = [];
331
+ const uploadConcurrency = bounded(env, "PLUNE_UPLOAD_CONCURRENCY", UPLOAD_CONCURRENCY, warnings);
332
+ const uploadRetries = bounded(env, "PLUNE_UPLOAD_RETRIES", UPLOAD_RETRIES, warnings);
333
+ const importTimeout = bounded(env, "PLUNE_IMPORT_TIMEOUT", IMPORT_TIMEOUT, warnings);
173
334
  const title = value(env, "PLUNE_RUN_TITLE");
174
335
  const environment = value(env, "PLUNE_ENV");
175
336
  const labels = list(env, "PLUNE_LABELS");
176
337
  const offerDiscovered = flag(env, "PLUNE_CREATE");
177
338
  const full = flag(env, "PLUNE_FULL_RUN");
339
+ const { shard, error: shardError } = shardOf(env);
340
+ const { configuration, error: configurationError } = configurationOf(env);
178
341
  return {
179
342
  config: {
180
343
  ...externalKey !== void 0 ? { externalKey } : {},
@@ -182,9 +345,12 @@ function readEnv(env = process.env) {
182
345
  ...apiUrl !== void 0 ? { apiUrl } : {},
183
346
  ...fallbackPath !== void 0 ? { fallbackPath } : {},
184
347
  ...batchSize !== void 0 ? { batchSize } : {},
348
+ ...uploadConcurrency !== void 0 ? { uploadConcurrency } : {},
349
+ ...uploadRetries !== void 0 ? { uploadRetries } : {},
185
350
  ...title !== void 0 ? { title } : {},
186
351
  ...environment !== void 0 ? { environment } : {},
187
352
  ...labels !== void 0 ? { labels } : {},
353
+ ...configuration !== void 0 ? { configuration } : {},
188
354
  // Only when set: `false` here would outrank a config file that asked for it, and an unset
189
355
  // variable is not an instruction.
190
356
  ...offerDiscovered ? { offerDiscovered } : {},
@@ -193,8 +359,15 @@ function readEnv(env = process.env) {
193
359
  // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
194
360
  // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
195
361
  // way this process must not be the one to call it finished.
196
- keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED"),
197
- ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0)
362
+ // `PLUNE_SHARD` implies it: the run is joined by the shared key and this process does not close it
363
+ // by itself; `leaveOpen` reports the shard instead.
364
+ keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED") || shard !== void 0 || shardError !== void 0,
365
+ ...shard !== void 0 ? { shard } : {},
366
+ ...shardError !== void 0 ? { shardError } : {},
367
+ ...configurationError !== void 0 ? { configurationError } : {},
368
+ ...importTimeout !== void 0 ? { importTimeout } : {},
369
+ ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0),
370
+ warnings
198
371
  };
199
372
  }
200
373
  function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cwd = process.cwd()) {
@@ -248,10 +421,18 @@ function repoRootOf(dir, stopAt) {
248
421
  if (here === stopAt || dirname2(here) === here) return void 0;
249
422
  }
250
423
  }
251
- function errorContextOf(attempt, home = homedir2()) {
424
+ function errorContextFields(attempt, home = homedir2()) {
425
+ const { text, omitted: omitted2 } = cutErrorContext(attempt, home);
426
+ return {
427
+ ...text !== "" ? { errorContext: text } : {},
428
+ ...omitted2 > 0 ? { errorContextOmitted: omitted2 } : {}
429
+ };
430
+ }
431
+ function cutErrorContext(attempt, home) {
252
432
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
253
433
  return cut(machineless(text, attempt.repoRoot, home));
254
434
  }
435
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
255
436
  var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
256
437
  var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
257
438
  var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
@@ -283,7 +464,7 @@ function pathIn(path3) {
283
464
  }
284
465
  var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
285
466
  function cut(text) {
286
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
467
+ if (jsonBytes(text) <= TEXT_LIMIT) return { text, omitted: 0 };
287
468
  const lines = text.split("\n");
288
469
  const size = lines.map((line) => jsonBytes(line) + 2);
289
470
  const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
@@ -292,7 +473,8 @@ function cut(text) {
292
473
  let tail = lines.length;
293
474
  while (head < tail && used + size[head] <= budget / 2) used += size[head++];
294
475
  while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
295
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
476
+ const kept = [...lines.slice(0, head), ...lines.slice(tail)].join("\n");
477
+ return { text: [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n"), omitted: text.length - kept.length };
296
478
  }
297
479
  var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
298
480
  var METADATA_TYPE = "application/plune.metadata+json";
@@ -350,6 +532,23 @@ function fromRoot(place, root) {
350
532
  function webLink(href) {
351
533
  return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
352
534
  }
535
+ var FILES_BATCH_MAX = 100;
536
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
537
+ var BATCH_PIPELINES = 2;
538
+ async function sha256File(path3) {
539
+ const hash = createHash("sha256");
540
+ for await (const part of createReadStream2(path3)) hash.update(part);
541
+ return hash.digest("hex");
542
+ }
543
+ var sha256Bytes = (bytes) => createHash("sha256").update(bytes).digest("hex");
544
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
545
+ "bucket_unreachable",
546
+ "not_connected",
547
+ "platform_not_configured",
548
+ "upload_expired",
549
+ "file_mismatch",
550
+ "file_missing"
551
+ ]);
353
552
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
354
553
  function appendBatch(file, batch) {
355
554
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -359,6 +558,7 @@ function appendBatch(file, batch) {
359
558
  externalKey: batch.externalKey,
360
559
  ...batch.session !== void 0 ? { session: batch.session } : {},
361
560
  ...batch.meta !== void 0 ? { meta: batch.meta } : {},
561
+ ...batch.configuration !== void 0 ? { configuration: batch.configuration } : {},
362
562
  results: batch.results
363
563
  };
364
564
  fs.appendFileSync(file, `${JSON.stringify(line)}
@@ -367,7 +567,8 @@ function appendBatch(file, batch) {
367
567
  var RESOLVE_CHUNK = 500;
368
568
  var BATCH_MAX = 500;
369
569
  var DISCOVER_MAX = 500;
370
- var BATCH_DEFAULT = 100;
570
+ var BATCH_DEFAULT = 500;
571
+ var SEND_CONCURRENCY = 4;
371
572
  var EXPECTED_MAX = 1e4;
372
573
  var KEY_MAX = 1024;
373
574
  var TITLE_MAX = 300;
@@ -384,7 +585,7 @@ var TYPE_BY_EXTENSION = {
384
585
  ".jpeg": "image/jpeg",
385
586
  ".webp": "image/webp"
386
587
  };
387
- var UPLOADS_AT_ONCE = 4;
588
+ var METADATA_TYPE2 = "application/plune.metadata+json";
388
589
  var NAME_MAX = 200;
389
590
  function nameOf(file) {
390
591
  const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename2(file.path));
@@ -409,15 +610,26 @@ var SKIPPED = {
409
610
  textSize: "Plune takes a text file of at most 512 KiB",
410
611
  empty: "the file is empty",
411
612
  binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
412
- encoding: "Plune takes UTF-8 text only"
613
+ encoding: "Plune takes UTF-8 text only",
614
+ noStorage: "no storage bucket is connected to this project"
413
615
  };
616
+ var BUCKET_FOUND = "plune: storage bucket found for this project \u2014 screenshots, text, trace and video go straight to it over short-lived links.";
414
617
  var KINDS = {
415
618
  screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
416
- text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" }
619
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
620
+ // Only the label is used: a file of this kind has no home in the database, so no ceiling of its own is known here.
621
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
417
622
  };
418
623
  function kindOf(type) {
419
624
  if (type.startsWith("image/")) return "screenshot";
420
- return TEXT_TYPES.has(type) ? "text" : void 0;
625
+ return TEXT_TYPES.has(type) ? "text" : "file";
626
+ }
627
+ var codeOf = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
628
+ function linkOf(item) {
629
+ const link = item;
630
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
631
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
632
+ return { id: link.id, url: link.url, headers };
421
633
  }
422
634
  function textTypeOf(contentType, type) {
423
635
  const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
@@ -446,7 +658,7 @@ function tally(counts, noun) {
446
658
  }
447
659
  function boundKey(key) {
448
660
  if (key.value.length <= KEY_MAX) return key;
449
- const digest = createHash("sha256").update(key.value).digest("hex").slice(0, 16);
661
+ const digest = createHash2("sha256").update(key.value).digest("hex").slice(0, 16);
450
662
  let head = key.value.slice(0, KEY_MAX - digest.length - 1);
451
663
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
452
664
  return { ...key, value: `${head}#${digest}` };
@@ -494,8 +706,11 @@ function warnIfDropped(sent, run, log) {
494
706
  }
495
707
  async function startRun(passed, declared2) {
496
708
  const env = readEnv();
709
+ if (env.shardError !== void 0) throw new Error(env.shardError);
710
+ if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
497
711
  const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
498
712
  const cfg = { ...env.config, ...stated };
713
+ const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
499
714
  const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
500
715
  `));
501
716
  const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
@@ -504,9 +719,18 @@ async function startRun(passed, declared2) {
504
719
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
505
720
  const offerDiscovered = cfg.offerDiscovered ?? false;
506
721
  const token = cfg.token ?? loadToken() ?? "";
722
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
723
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
724
+ let retried = 0;
725
+ let uploadMs = 0;
726
+ let requests = 0;
727
+ let existed = 0;
728
+ let batchMissing = false;
507
729
  const client = createClient({
508
730
  apiUrl: resolveApiUrl(cfg.apiUrl),
509
731
  token,
732
+ uploadRetries,
733
+ onRetry: () => void (retried += 1),
510
734
  ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
511
735
  });
512
736
  const stats = {
@@ -520,18 +744,28 @@ async function startRun(passed, declared2) {
520
744
  unoffered: 0,
521
745
  deferred: 0,
522
746
  screenshots: { uploaded: 0, skipped: 0, failed: 0 },
523
- textFiles: { uploaded: 0, skipped: 0, failed: 0 }
747
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
748
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
524
749
  };
525
750
  const resolved = /* @__PURE__ */ new Map();
526
751
  let buffer = [];
527
752
  const discoveries = /* @__PURE__ */ new Map();
753
+ const held = /* @__PURE__ */ new Map();
754
+ let createdWithResult = 0;
755
+ let createdUndelivered = 0;
528
756
  let runId = null;
529
757
  let joined = false;
530
758
  let offline = token === "";
531
759
  let done = false;
532
760
  const shortened = /* @__PURE__ */ new Set();
533
761
  const skipsSaid = /* @__PURE__ */ new Set();
534
- const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
762
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
763
+ let bucketSeen = false;
764
+ let noStorage = 0;
765
+ let uploadsMissing = false;
766
+ const failedSaid = /* @__PURE__ */ new Set();
767
+ const codesSaid = /* @__PURE__ */ new Set();
768
+ const rooms = /* @__PURE__ */ new Map();
535
769
  function bound(keys) {
536
770
  return keys.map((key) => {
537
771
  const fit = boundKey(key);
@@ -539,7 +773,7 @@ async function startRun(passed, declared2) {
539
773
  shortened.add(key.value);
540
774
  if (shortened.size === 1) {
541
775
  log(
542
- `plune: a test name longer than ${KEY_MAX} characters was shortened to fit its key \u2014 "${key.value.slice(0, 80)}\u2026". Give the test a shorter name; until then this is its identity.`
776
+ `plune: a test name longer than ${KEY_MAX} characters was shortened to fit its key \u2014 ${JSON.stringify(printable(key.value.slice(0, 80)))}\u2026 Give the test a shorter name; until then this is its identity.`
543
777
  );
544
778
  }
545
779
  }
@@ -550,6 +784,7 @@ async function startRun(passed, declared2) {
550
784
  if (offline) {
551
785
  log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
552
786
  }
787
+ for (const warning of env.warnings) log(`plune: ${warning}`);
553
788
  if (env.ignored.length > 0) {
554
789
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
555
790
  }
@@ -559,6 +794,7 @@ async function startRun(passed, declared2) {
559
794
  externalKey,
560
795
  session: sessionMarker,
561
796
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
797
+ ...configuration !== void 0 ? { configuration } : {},
562
798
  results: results.map(onDisk)
563
799
  });
564
800
  stats.deferred += results.length;
@@ -583,7 +819,7 @@ async function startRun(passed, declared2) {
583
819
  if (!offline) {
584
820
  if (expected !== void 0) await resolveKeys(expected.flat());
585
821
  const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
586
- const configuration = stated2.length === 0 ? void 0 : {
822
+ const configuration2 = stated2.length === 0 ? void 0 : {
587
823
  expected: stated2.flatMap((keys) => {
588
824
  const hit = keys.map((k) => resolved.get(k.value)).find((v) => typeof v === "string");
589
825
  if (typeof hit === "string") return [{ testCaseId: hit }];
@@ -602,18 +838,25 @@ async function startRun(passed, declared2) {
602
838
  ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
603
839
  ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
604
840
  };
605
- const start = await client.post("/v1/runs", {
841
+ const request = {
606
842
  schemaVersion: 2,
607
843
  kind: cfg.kind ?? "automated",
608
844
  ...externalKey !== null ? { externalKey } : {},
609
845
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
610
- ...configuration !== void 0 ? { configuration } : {},
846
+ ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
611
847
  // Named even when nobody named it — the list has to read without opening a row. Only what
612
848
  // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
613
849
  // a person will miss, and a deployment older than the field must not be nagged on every run.
614
850
  title: defaultRunTitle(),
615
851
  ...described
616
- });
852
+ };
853
+ let start = await client.post("/v1/runs", request);
854
+ if (!start.ok && start.status === 413 && configuration2 !== void 0) {
855
+ log(
856
+ `plune: the platform refused the run's list of expected tests as too large (${start.detail || start.kind}) \u2014 starting without it: the results still land, but this run counts no tests that did not run, and claims no full run.`
857
+ );
858
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
859
+ }
617
860
  if (start.ok && typeof start.body?.run?.id === "string") {
618
861
  runId = start.body.run.id;
619
862
  joined = start.status === 200;
@@ -646,6 +889,7 @@ async function startRun(passed, declared2) {
646
889
  specRef: result.specRef,
647
890
  rawStatus: result.rawStatus
648
891
  });
892
+ held.set(result.keys[0].value, result);
649
893
  }
650
894
  async function offer() {
651
895
  if (discoveries.size === 0 || offline || runId === null) return;
@@ -664,24 +908,71 @@ async function startRun(passed, declared2) {
664
908
  return;
665
909
  }
666
910
  stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
667
- stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
911
+ const made = out.body.results.filter((r) => r?.outcome === "created");
912
+ stats.created += made.length;
913
+ const submissions = [];
914
+ const filesByKey = /* @__PURE__ */ new Map();
915
+ for (const r of made) {
916
+ const pending = typeof r.id === "string" && r.id !== "" ? held.get(r.key?.value) : void 0;
917
+ if (pending === void 0) continue;
918
+ held.delete(r.key.value);
919
+ const { keys: _keys, files, ...rest } = pending;
920
+ submissions.push({ ...rest, testCaseId: r.id });
921
+ if (files !== void 0) filesByKey.set(pending.resultKey, files);
922
+ }
923
+ if (submissions.length > 0) {
924
+ const before = stats.deferred;
925
+ await send(submissions, filesByKey);
926
+ createdWithResult += submissions.length;
927
+ createdUndelivered += stats.deferred - before;
928
+ }
668
929
  }
669
930
  }
670
931
  function skip(kind, name, why) {
671
932
  countsOf(kind).skipped += 1;
672
- if (skipsSaid.has(`${kind}/${why}`)) return;
673
- skipsSaid.add(`${kind}/${why}`);
674
- log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
933
+ if (why === "noStorage") noStorage += 1;
934
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
935
+ if (skipsSaid.has(said)) return;
936
+ skipsSaid.add(said);
937
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
938
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
939
+ }
940
+ function ask(job, size) {
941
+ requests += 1;
942
+ return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
943
+ files: [{ name: job.name, contentType: job.type, size }]
944
+ }, uploadRetries);
945
+ }
946
+ function failed(job, why) {
947
+ countsOf(job.kind).failed += 1;
948
+ if (!failedSaid.has(job.kind)) {
949
+ failedSaid.add(job.kind);
950
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
951
+ }
675
952
  }
676
- async function uploadOne(job) {
953
+ function failedToBucket(job, code) {
954
+ countsOf(job.kind).failed += 1;
955
+ if (codesSaid.has(code)) return;
956
+ codesSaid.add(code);
957
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
958
+ }
959
+ function refusedHere(job, size) {
960
+ if (job.kind === "screenshot") {
961
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
962
+ if (size > SCREENSHOT_BYTES) return "size";
963
+ }
964
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
965
+ return void 0;
966
+ }
967
+ async function uploadDirect(job, size) {
677
968
  const { kind } = job;
678
- const { label, bytes: ceiling, size } = KINDS[kind];
969
+ if (kind === "file") return skip(kind, job.name, "noStorage");
970
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
971
+ if (size > ceiling) return skip(kind, job.name, tooBig);
679
972
  let bytes;
680
973
  if (job.body !== void 0) bytes = job.body;
681
- else if (job.path === void 0) return skip(kind, job.name, "missing");
682
974
  else {
683
975
  try {
684
- if ((await disk.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
685
976
  bytes = await disk.readFile(job.path);
686
977
  } catch {
687
978
  return skip(kind, job.name, "missing");
@@ -689,37 +980,342 @@ async function startRun(passed, declared2) {
689
980
  }
690
981
  const refusal = kind === "text" ? textRefusal(bytes) : void 0;
691
982
  if (refusal !== void 0) return skip(kind, job.name, refusal);
983
+ requests += 1;
692
984
  const out = await client.upload(
693
985
  `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
694
986
  bytes,
695
987
  job.type
696
988
  );
697
- const counts = countsOf(kind);
698
- if (out.ok) {
699
- counts.uploaded += 1;
989
+ if (out.ok) countsOf(kind).uploaded += 1;
990
+ else failed(job, out.detail || out.kind);
991
+ }
992
+ async function uploadToBucket(job, size, first) {
993
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
994
+ let link = first;
995
+ for (let renewed = false; ; ) {
996
+ const put = await client.put(link.url, link.headers, source);
997
+ if (put.ok) break;
998
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
999
+ renewed = true;
1000
+ const again = await ask(job, size);
1001
+ if (!again.ok) return failedToBucket(job, codeOf(again));
1002
+ const fresh = linkOf(again.body?.files?.[0]);
1003
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
1004
+ link = fresh;
1005
+ }
1006
+ requests += 1;
1007
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1008
+ if (!done2.ok) return failedToBucket(job, codeOf(done2));
1009
+ countsOf(job.kind).uploaded += 1;
1010
+ }
1011
+ let free = uploadsAtOnce;
1012
+ const waiting = [];
1013
+ async function gated(work) {
1014
+ if (free === 0) await new Promise((resolve22) => waiting.push(resolve22));
1015
+ else free -= 1;
1016
+ try {
1017
+ return await work();
1018
+ } finally {
1019
+ const next = waiting.shift();
1020
+ if (next !== void 0) next();
1021
+ else free += 1;
1022
+ }
1023
+ }
1024
+ async function plan(job) {
1025
+ const { kind } = job;
1026
+ let size;
1027
+ if (job.body !== void 0) size = job.body.length;
1028
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
1029
+ else {
1030
+ try {
1031
+ size = (await disk.stat(job.path)).size;
1032
+ } catch {
1033
+ return void skip(kind, job.name, "missing");
1034
+ }
1035
+ }
1036
+ if (size === 0) return void skip(kind, job.name, "empty");
1037
+ const direct = () => {
1038
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
1039
+ const roomKey = `${job.id}/${kind}`;
1040
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
1041
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
1042
+ rooms.set(roomKey, left - 1);
1043
+ return () => uploadDirect(job, size);
1044
+ };
1045
+ if (uploadsMissing) return direct();
1046
+ const out = await gated(() => ask(job, size));
1047
+ if (!out.ok) {
1048
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
1049
+ uploadsMissing = true;
1050
+ return direct();
1051
+ }
1052
+ if (out.code !== void 0) failedToBucket(job, out.code);
1053
+ else failed(job, out.detail || out.kind);
1054
+ return void 0;
1055
+ }
1056
+ const item = out.body?.files?.[0];
1057
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
1058
+ if (item?.direct === true) return direct();
1059
+ const link = linkOf(item);
1060
+ if (link === void 0) return void failed(job, "bad_answer");
1061
+ if (!bucketSeen) {
1062
+ bucketSeen = true;
1063
+ log(BUCKET_FOUND);
1064
+ }
1065
+ return () => uploadToBucket(job, size, link);
1066
+ }
1067
+ async function uploadEach(jobs) {
1068
+ const byResult = /* @__PURE__ */ new Map();
1069
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
1070
+ await Promise.all(
1071
+ [...byResult.values()].map(async (group) => {
1072
+ const work = [];
1073
+ for (const job of group) {
1074
+ const act = await plan(job);
1075
+ if (act !== void 0) work.push(gated(act));
1076
+ }
1077
+ await Promise.all(work);
1078
+ })
1079
+ );
1080
+ }
1081
+ async function measure(job) {
1082
+ let size;
1083
+ if (job.body !== void 0) size = job.body.length;
1084
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
1085
+ else {
1086
+ try {
1087
+ size = (await disk.stat(job.path)).size;
1088
+ } catch {
1089
+ return void skip(job.kind, job.name, "missing");
1090
+ }
1091
+ }
1092
+ if (size === 0) return void skip(job.kind, job.name, "empty");
1093
+ return size;
1094
+ }
1095
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
1096
+ function takeRoom(job) {
1097
+ if (job.kind === "file") {
1098
+ skip(job.kind, job.name, "noStorage");
1099
+ return false;
1100
+ }
1101
+ const roomKey = `${job.id}/${job.kind}`;
1102
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
1103
+ if (left === 0) {
1104
+ skip(job.kind, job.name, KINDS[job.kind].limit);
1105
+ return false;
1106
+ }
1107
+ rooms.set(roomKey, left - 1);
1108
+ return true;
1109
+ }
1110
+ function refusedItem(job, size, item) {
1111
+ const code = item.code ?? "refused";
1112
+ if (code === "duplicate") existed += 1;
1113
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
1114
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
1115
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
1116
+ else failed(job, code);
1117
+ }
1118
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
1119
+ async function batchOf(jobs) {
1120
+ if (batchMissing) return uploadEach(jobs);
1121
+ const sized = [];
1122
+ for (const job of jobs) {
1123
+ const size = await measure(job);
1124
+ if (size === void 0) continue;
1125
+ try {
1126
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
1127
+ } catch {
1128
+ skip(job.kind, job.name, "missing");
1129
+ }
1130
+ }
1131
+ if (sized.length === 0) return;
1132
+ const announced = await gated(() => {
1133
+ requests += 1;
1134
+ return client.post(
1135
+ "/v1/files/uploads-batch",
1136
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
1137
+ uploadRetries
1138
+ );
1139
+ });
1140
+ if (routeMissing(announced)) {
1141
+ batchMissing = true;
1142
+ return uploadEach(sized.map((s) => s.job));
1143
+ }
1144
+ const verdicts = announced.ok ? announced.body?.items : void 0;
1145
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
1146
+ for (const s of sized) {
1147
+ if (announced.ok) failed(s.job, "bad_answer");
1148
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
1149
+ else failed(s.job, announced.detail || announced.kind);
1150
+ }
700
1151
  return;
701
1152
  }
702
- counts.failed += 1;
703
- if (counts.failed === 1) {
704
- log(`plune: could not upload a ${label} (${out.detail || out.kind}) \u2014 its result is reported without it.`);
1153
+ const puts = [];
1154
+ const directs = [];
1155
+ sized.forEach((s, i) => {
1156
+ const v = verdicts[i] ?? {};
1157
+ if (v.status === "exists") existed += 1;
1158
+ else if (v.status === "direct") {
1159
+ if (takeRoom(s.job)) directs.push(s);
1160
+ } else if (v.status === "upload") {
1161
+ const link = linkOf(v);
1162
+ if (link === void 0) return failed(s.job, "bad_answer");
1163
+ if (!bucketSeen) {
1164
+ bucketSeen = true;
1165
+ log(BUCKET_FOUND);
1166
+ }
1167
+ puts.push({ s, link });
1168
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
1169
+ else failed(s.job, "bad_answer");
1170
+ });
1171
+ const toComplete = [];
1172
+ await Promise.all(
1173
+ puts.map(
1174
+ ({ s, link: first }) => gated(async () => {
1175
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
1176
+ let link = first;
1177
+ for (let renewed = false; ; ) {
1178
+ const put = await client.put(link.url, link.headers, source);
1179
+ if (put.ok) break;
1180
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
1181
+ renewed = true;
1182
+ requests += 1;
1183
+ const again = await client.post(
1184
+ "/v1/files/uploads-batch",
1185
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
1186
+ uploadRetries
1187
+ );
1188
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
1189
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf(again));
1190
+ link = fresh;
1191
+ }
1192
+ toComplete.push({ job: s.job, id: link.id });
1193
+ })
1194
+ )
1195
+ );
1196
+ await complete(toComplete);
1197
+ await sendDirect(directs);
1198
+ }
1199
+ async function complete(items) {
1200
+ for (let round = 0; items.length > 0; round += 1) {
1201
+ const out = await gated(() => {
1202
+ requests += 1;
1203
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
1204
+ });
1205
+ if (routeMissing(out)) {
1206
+ await Promise.all(
1207
+ items.map(
1208
+ (i) => gated(async () => {
1209
+ requests += 1;
1210
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
1211
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
1212
+ else failedToBucket(i.job, codeOf(one));
1213
+ })
1214
+ )
1215
+ );
1216
+ return;
1217
+ }
1218
+ const verdicts = out.ok ? out.body?.items : void 0;
1219
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
1220
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf(out));
1221
+ return;
1222
+ }
1223
+ const again = [];
1224
+ items.forEach((i, at) => {
1225
+ const v = verdicts[at] ?? {};
1226
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
1227
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
1228
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1229
+ });
1230
+ items = again;
1231
+ if (items.length > 0) {
1232
+ retried += items.length;
1233
+ await itemPause(round);
1234
+ }
1235
+ }
1236
+ }
1237
+ async function sendDirect(items) {
1238
+ const groups = [];
1239
+ let bytes = 0;
1240
+ for (const item of items) {
1241
+ const group = groups[groups.length - 1];
1242
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
1243
+ groups.push([item]);
1244
+ bytes = item.size;
1245
+ } else {
1246
+ group.push(item);
1247
+ bytes += item.size;
1248
+ }
1249
+ }
1250
+ for (const group of groups) {
1251
+ const body = [];
1252
+ const sent = [];
1253
+ for (const { job, size } of group) {
1254
+ const { kind } = job;
1255
+ if (size > KINDS[kind].bytes) {
1256
+ skip(kind, job.name, KINDS[kind].size);
1257
+ continue;
1258
+ }
1259
+ let data;
1260
+ try {
1261
+ data = job.body ?? await disk.readFile(job.path);
1262
+ } catch {
1263
+ skip(kind, job.name, "missing");
1264
+ continue;
1265
+ }
1266
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
1267
+ if (refusal !== void 0) {
1268
+ skip(kind, job.name, refusal);
1269
+ continue;
1270
+ }
1271
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
1272
+ sent.push({ job, size });
1273
+ }
1274
+ if (body.length === 0) continue;
1275
+ const out = await gated(() => {
1276
+ requests += 1;
1277
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
1278
+ });
1279
+ if (routeMissing(out)) {
1280
+ batchMissing = true;
1281
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
1282
+ continue;
1283
+ }
1284
+ const verdicts = out.ok ? out.body?.items : void 0;
1285
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
1286
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
1287
+ continue;
1288
+ }
1289
+ sent.forEach(({ job }, i) => {
1290
+ const v = verdicts[i] ?? {};
1291
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
1292
+ else if (v.status === "exists") existed += 1;
1293
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1294
+ });
705
1295
  }
706
1296
  }
1297
+ async function uploadBatched(jobs) {
1298
+ const batches = chunk(jobs, FILES_BATCH_MAX);
1299
+ let next = 0;
1300
+ await Promise.all(
1301
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
1302
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
1303
+ })
1304
+ );
1305
+ }
707
1306
  async function upload(items, filesByKey) {
708
1307
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
709
1308
  const jobs = [];
710
1309
  for (const item of items) {
711
1310
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
712
- const room = { screenshot: KINDS.screenshot.room, text: KINDS.text.room };
713
1311
  for (const file of filesByKey.get(item.resultKey) ?? []) {
714
1312
  const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[extname(file.path).toLowerCase()]);
715
- const kind = type === void 0 ? void 0 : kindOf(type);
716
- if (type === void 0 || kind === void 0 || kind === "screenshot" && file.path === void 0) continue;
1313
+ if (type === void 0 || type === METADATA_TYPE2) continue;
1314
+ const kind = kindOf(type);
1315
+ if (kind !== "text" && file.path === void 0) continue;
717
1316
  const name = nameOf(file);
718
1317
  if (file.name.startsWith("_")) skip(kind, name, "hidden");
719
- else if (kind === "screenshot" && !SCREENSHOT_TYPES.has(type)) skip(kind, name, "type");
720
- else if (room[kind] === 0) skip(kind, name, KINDS[kind].limit);
721
1318
  else {
722
- room[kind] -= 1;
723
1319
  jobs.push({
724
1320
  id: item.id,
725
1321
  kind,
@@ -731,14 +1327,34 @@ async function startRun(passed, declared2) {
731
1327
  }
732
1328
  }
733
1329
  }
734
- let next = 0;
735
- await Promise.all(
736
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, jobs.length) }, async () => {
737
- while (next < jobs.length) await uploadOne(jobs[next++]);
738
- })
739
- );
1330
+ const started = Date.now();
1331
+ if (batchMissing) await uploadEach(jobs);
1332
+ else await uploadBatched(jobs);
1333
+ uploadMs += Date.now() - started;
1334
+ }
1335
+ const sending = /* @__PURE__ */ new Set();
1336
+ let sendError;
1337
+ let answered = false;
1338
+ async function dispatch(work) {
1339
+ while (sending.size >= (answered ? SEND_CONCURRENCY : 1)) await Promise.race(sending);
1340
+ const task = work().catch((err) => {
1341
+ sendError ??= err;
1342
+ }).finally(() => sending.delete(task));
1343
+ sending.add(task);
1344
+ }
1345
+ async function settle() {
1346
+ while (sending.size > 0) await Promise.all([...sending]);
1347
+ if (sendError !== void 0) {
1348
+ const err = sendError;
1349
+ sendError = void 0;
1350
+ throw err;
1351
+ }
740
1352
  }
741
1353
  async function flush() {
1354
+ await flushBuffer();
1355
+ await settle();
1356
+ }
1357
+ async function flushBuffer() {
742
1358
  if (buffer.length === 0) return;
743
1359
  const pending = buffer;
744
1360
  buffer = [];
@@ -746,6 +1362,9 @@ async function startRun(passed, declared2) {
746
1362
  defer(pending);
747
1363
  return;
748
1364
  }
1365
+ await dispatch(() => deliver(pending));
1366
+ }
1367
+ async function deliver(pending) {
749
1368
  await resolveKeys(pending.flatMap((p) => p.keys));
750
1369
  const submissions = [];
751
1370
  const unanswered = [];
@@ -768,6 +1387,9 @@ async function startRun(passed, declared2) {
768
1387
  progress();
769
1388
  return;
770
1389
  }
1390
+ await send(submissions, filesByKey);
1391
+ }
1392
+ async function send(submissions, filesByKey) {
771
1393
  for (const part of packed(submissions)) {
772
1394
  if (offline) {
773
1395
  defer(part);
@@ -775,7 +1397,8 @@ async function startRun(passed, declared2) {
775
1397
  }
776
1398
  const out = await client.post(
777
1399
  `/v1/runs/${runId}/results`,
778
- { results: part }
1400
+ // The job's combination on every batch (plune-ai/plune#1251); a refusal of it is a 422 said below as it came.
1401
+ { results: part, ...configuration !== void 0 ? { configuration } : {} }
779
1402
  );
780
1403
  const counts = out.ok ? out.body?.counts : void 0;
781
1404
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
@@ -783,6 +1406,7 @@ async function startRun(passed, declared2) {
783
1406
  for (const k of told) stats[k] += counts[k];
784
1407
  progress();
785
1408
  await upload(out.ok ? out.body?.items : void 0, filesByKey);
1409
+ answered = true;
786
1410
  continue;
787
1411
  }
788
1412
  if (out.ok) {
@@ -811,17 +1435,40 @@ async function startRun(passed, declared2) {
811
1435
  if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
812
1436
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
813
1437
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
814
- if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
815
- for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
816
- if (said !== void 0) parts.push(said);
1438
+ if (stats.created > 0) {
1439
+ const recorded = createdWithResult === stats.created && createdUndelivered === 0;
1440
+ parts.push(`${stats.created} added as cases (trusted source)${recorded ? " and their results recorded" : ""}`);
1441
+ }
1442
+ const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1443
+ const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1444
+ if (bucketSeen) {
1445
+ const other = sum("skipped") - noStorage;
1446
+ parts.push(
1447
+ `${sum("uploaded")} file(s) uploaded to your bucket` + (noStorage > 0 ? `, ${noStorage} skipped (no bucket connected)` : "") + (other > 0 ? `, ${other} skipped` : "") + (sum("failed") > 0 ? `, ${sum("failed")} failed to upload` : "")
1448
+ );
1449
+ } else {
1450
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
1451
+ if (said !== void 0) parts.push(said);
1452
+ }
1453
+ const other = stats.otherFiles;
1454
+ if (other.skipped > 0) parts.push(`${other.skipped} file(s) not stored (no bucket connected)`);
1455
+ if (other.failed > 0) parts.push(`${other.failed} file(s) failed to upload`);
817
1456
  }
818
1457
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
819
1458
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1459
+ const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1460
+ const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1461
+ if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1462
+ log(
1463
+ `plune: files \u2014 ${total("uploaded")} uploaded, ${total("skipped")} skipped, ${existed} already there (skipped), ${retried} retried, ${total("failed")} dropped, in ${(uploadMs / 1e3).toFixed(1)} s (${uploadsAtOnce} at once, ${requests} request(s) to Plune)`
1464
+ );
1465
+ }
820
1466
  log(`plune: ${parts.join(" \xB7 ")}`);
821
1467
  if (stats.deferred > 0 && process.env["GITHUB_ACTIONS"] === "true") {
822
1468
  log(`::warning::${stats.deferred} result(s) were not delivered to Plune \u2014 see the reporting step's log.`);
823
1469
  }
824
1470
  }
1471
+ const shardLines = [];
825
1472
  return {
826
1473
  get runId() {
827
1474
  return runId;
@@ -834,40 +1481,73 @@ async function startRun(passed, declared2) {
834
1481
  },
835
1482
  async add(result) {
836
1483
  buffer.push({ ...result, keys: bound(result.keys) });
837
- if (buffer.length >= batchSize) await flush();
1484
+ if (buffer.length >= batchSize) await flushBuffer();
838
1485
  },
839
1486
  flush,
840
1487
  async finish(reason) {
841
- if (done) return;
1488
+ if (done) return void 0;
842
1489
  done = true;
843
1490
  await flush();
844
1491
  await offer();
1492
+ let frozen;
845
1493
  if (runId !== null && !offline) {
846
1494
  const out = await client.post(`/v1/runs/${runId}/events`, {
847
1495
  event: "finish",
848
1496
  ...reason !== void 0 ? { reason } : {}
849
1497
  });
850
1498
  if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
851
- else if (typeof out.body?.detached === "number" && out.body.detached > 0) {
852
- log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1499
+ else {
1500
+ frozen = out.body?.summary ?? void 0;
1501
+ if (typeof out.body?.detached === "number" && out.body.detached > 0) {
1502
+ log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1503
+ }
853
1504
  }
854
1505
  }
855
1506
  summarise();
1507
+ return frozen;
856
1508
  },
857
- async leaveOpen() {
858
- if (done) return;
1509
+ shardLines,
1510
+ async leaveOpen(opts) {
1511
+ if (done) return void 0;
859
1512
  done = true;
860
1513
  await flush();
861
1514
  await offer();
862
- if (runId !== null) {
1515
+ let frozen;
1516
+ const after = [];
1517
+ const shard = env.shard;
1518
+ let counted = false;
1519
+ let mismatch;
1520
+ if (runId !== null && shard !== void 0 && !offline) {
1521
+ const out = await client.post(`/v1/runs/${runId}/events`, { event: "finish", shardIndex: shard.index, shardsExpected: shard.total });
1522
+ if (out.ok && typeof out.body?.shardsReported === "number") {
1523
+ counted = true;
1524
+ frozen = out.body.summary ?? void 0;
1525
+ const n = out.body.shardsExpected ?? shard.total;
1526
+ if (out.body.run?.statusEvent === "finished") after.push("plune: run closed");
1527
+ after.push(`plune: shard ${shard.index} of ${shard.total} done \u2014 ${out.body.shardsReported} of ${n} shards reported`);
1528
+ } else if (out.ok || out.kind === "invalid") {
1529
+ log('plune: the platform does not support shard auto-close yet \u2014 the run is left open for "plune run finish".');
1530
+ } else if (out.code === "shards_mismatch") {
1531
+ mismatch = new Error(
1532
+ `PLUNE_SHARD=${shard.index}/${shard.total} says ${shard.total} shards, but run ${runId} already expects ${out.shardsExpected ?? "a different number of"} \u2014 every shard of one run must use the same N. The results are uploaded; the run is left open.`
1533
+ );
1534
+ } else {
1535
+ log(`plune: could not report shard ${shard.index} of ${shard.total} to run ${runId} (${out.detail || out.kind}) \u2014 the results are uploaded; close the run with "plune run finish ${runId}".`);
1536
+ }
1537
+ }
1538
+ if (runId !== null && !counted) {
863
1539
  log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
864
1540
  }
865
1541
  summarise();
1542
+ shardLines.push(...after);
1543
+ if (opts?.holdShardLines !== true) for (const line of after) log(line);
1544
+ if (mismatch !== void 0) throw mismatch;
1545
+ return frozen;
866
1546
  }
867
1547
  };
868
1548
  }
869
1549
  function sha256(input) {
870
- return createHash2("sha256").update(input, "utf8").digest("hex");
1550
+ return createHash3("sha256").update(input, "utf8").digest("hex");
871
1551
  }
872
1552
  var RESULT_KEY_MAX = 200;
873
1553
  var HASH_CHARS = 32;
@@ -891,16 +1571,19 @@ function titlesOf(test) {
891
1571
  }
892
1572
  return titles;
893
1573
  }
1574
+ function pathTitleOf(test) {
1575
+ return [fileOf2(test), ...titlesOf(test)].join("#");
1576
+ }
894
1577
  function keysFor(test) {
895
1578
  return [
896
1579
  { kind: "playwright-id", value: test.id },
897
- { kind: "path-title", value: [fileOf2(test), ...titlesOf(test)].join("#") }
1580
+ { kind: "path-title", value: pathTitleOf(test) }
898
1581
  ];
899
1582
  }
900
- var METADATA_TYPE2 = "application/plune.metadata+json";
1583
+ var METADATA_TYPE3 = "application/plune.metadata+json";
901
1584
  var TOKEN = /@P([A-Za-z0-9_-]+)/;
902
1585
  function metadataOf(result) {
903
- const found = result.attachments.find((a) => a.contentType === METADATA_TYPE2);
1586
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
904
1587
  if (found === void 0) return void 0;
905
1588
  try {
906
1589
  const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync2(found.path, "utf8") : void 0;
@@ -909,12 +1592,32 @@ function metadataOf(result) {
909
1592
  return void 0;
910
1593
  }
911
1594
  }
912
- function statedIdOf(test, metadata) {
1595
+ function statedIdOf(test, metadata, mapped) {
913
1596
  const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
914
1597
  if (annotation !== void 0 && annotation !== "") return annotation;
915
1598
  const token = TOKEN.exec(test.title)?.[1];
916
1599
  if (token !== void 0) return token;
917
- return metadata?.id !== void 0 && metadata.id !== "" ? metadata.id : void 0;
1600
+ if (metadata?.id !== void 0 && metadata.id !== "") return metadata.id;
1601
+ return mapped;
1602
+ }
1603
+ function readIds(file) {
1604
+ let raw;
1605
+ try {
1606
+ raw = readFileSync2(file, "utf8");
1607
+ } catch {
1608
+ return {};
1609
+ }
1610
+ try {
1611
+ const parsed = JSON.parse(raw);
1612
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && Object.values(parsed).every((v) => typeof v === "string" && v !== ""))
1613
+ return parsed;
1614
+ } catch {
1615
+ }
1616
+ process.stderr.write(
1617
+ `plune: ${file} is not a JSON object of path-title to case id strings - ignored, tests resolve as if it were absent
1618
+ `
1619
+ );
1620
+ return {};
918
1621
  }
919
1622
  var NOT_FAILED = /* @__PURE__ */ new Set(["passed", "skipped"]);
920
1623
  function textOf(error) {
@@ -948,12 +1651,16 @@ function attemptOf(test, result, ctx) {
948
1651
  ...ctx.repoRoot !== void 0 ? { repoRoot: ctx.repoRoot } : {}
949
1652
  };
950
1653
  }
951
- function pendingFrom(test, result, ctx) {
1654
+ function pendingFrom(test, result, ctx, ids = {}) {
952
1655
  const metadata = metadataOf(result);
953
- const pluneId = statedIdOf(test, metadata);
1656
+ const pluneId = statedIdOf(
1657
+ test,
1658
+ metadata,
1659
+ Object.hasOwn(ids, pathTitleOf(test)) ? ids[pathTitleOf(test)] : void 0
1660
+ );
954
1661
  const expected = test.expectedStatus;
955
1662
  const attempt = attemptOf(test, result, ctx);
956
- const errorContext = errorContextOf(attempt);
1663
+ const errorContext = errorContextFields(attempt);
957
1664
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
958
1665
  const files = filesOf(attempt);
959
1666
  const startedAt = result.startTime;
@@ -983,7 +1690,7 @@ function pendingFrom(test, result, ctx) {
983
1690
  retry: result.retry,
984
1691
  worker: String(result.workerIndex)
985
1692
  },
986
- ...errorContext !== "" ? { errorContext } : {},
1693
+ ...errorContext,
987
1694
  ...failure !== void 0 ? { failure } : {},
988
1695
  // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
989
1696
  ...files.length > 0 ? { files } : {}
@@ -1001,6 +1708,8 @@ var PluneReporter = class {
1001
1708
  /** Kept whole: `metadata.ci` is written into it after `onConfigure`, so it is read at the run's opening. */
1002
1709
  config = null;
1003
1710
  context = {};
1711
+ /** The mapfile, read on the first result so a run that reports nothing never touches the disk. */
1712
+ ids = null;
1004
1713
  constructor(options = {}) {
1005
1714
  this.options = options;
1006
1715
  }
@@ -1053,7 +1762,10 @@ var PluneReporter = class {
1053
1762
  onTestEnd(test, result) {
1054
1763
  const session = this.open();
1055
1764
  this.chain = this.chain.then(async () => {
1056
- await (await session).add(pendingFrom(test, result, this.context));
1765
+ this.ids ??= readIds(
1766
+ resolve2(this.options.idsFile ?? process.env["PLUNE_IDS_FILE"] ?? "plune/ids.json")
1767
+ );
1768
+ await (await session).add(pendingFrom(test, result, this.context, this.ids));
1057
1769
  }).catch((err) => this.giveUp(err));
1058
1770
  }
1059
1771
  async onEnd(_result) {