@plune-ai/playwright 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,76 @@ 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
+ var UPLOAD_CONCURRENCY = { min: 1, max: 32, default: 16 };
275
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
276
+ var IMPORT_TIMEOUT = { min: 0, max: 86400, default: 600 };
147
277
  function value(env, name) {
148
278
  const raw = env[name]?.trim();
149
279
  return raw === void 0 || raw === "" ? void 0 : raw;
@@ -158,6 +288,14 @@ function count(env, name) {
158
288
  const n = Number(raw);
159
289
  return Number.isInteger(n) && n > 0 ? n : void 0;
160
290
  }
291
+ function bounded(env, name, range, warnings) {
292
+ const raw = value(env, name);
293
+ if (raw === void 0) return void 0;
294
+ const n = Number(raw);
295
+ if (/^\d+$/.test(raw) && n >= range.min && n <= range.max) return n;
296
+ warnings.push(`${name}=${JSON.stringify(raw.slice(0, 40))} is not a whole number from ${range.min} to ${range.max} \u2014 using ${range.default}.`);
297
+ return void 0;
298
+ }
161
299
  function list(env, name) {
162
300
  const raw = value(env, name);
163
301
  if (raw === void 0) return void 0;
@@ -170,11 +308,16 @@ function readEnv(env = process.env) {
170
308
  const apiUrl = value(env, "PLUNE_API_URL");
171
309
  const fallbackPath = value(env, "PLUNE_FALLBACK");
172
310
  const batchSize = count(env, "PLUNE_BATCH_SIZE");
311
+ const warnings = [];
312
+ const uploadConcurrency = bounded(env, "PLUNE_UPLOAD_CONCURRENCY", UPLOAD_CONCURRENCY, warnings);
313
+ const uploadRetries = bounded(env, "PLUNE_UPLOAD_RETRIES", UPLOAD_RETRIES, warnings);
314
+ const importTimeout = bounded(env, "PLUNE_IMPORT_TIMEOUT", IMPORT_TIMEOUT, warnings);
173
315
  const title = value(env, "PLUNE_RUN_TITLE");
174
316
  const environment = value(env, "PLUNE_ENV");
175
317
  const labels = list(env, "PLUNE_LABELS");
176
318
  const offerDiscovered = flag(env, "PLUNE_CREATE");
177
319
  const full = flag(env, "PLUNE_FULL_RUN");
320
+ const { shard, error: shardError } = shardOf(env);
178
321
  return {
179
322
  config: {
180
323
  ...externalKey !== void 0 ? { externalKey } : {},
@@ -182,6 +325,8 @@ function readEnv(env = process.env) {
182
325
  ...apiUrl !== void 0 ? { apiUrl } : {},
183
326
  ...fallbackPath !== void 0 ? { fallbackPath } : {},
184
327
  ...batchSize !== void 0 ? { batchSize } : {},
328
+ ...uploadConcurrency !== void 0 ? { uploadConcurrency } : {},
329
+ ...uploadRetries !== void 0 ? { uploadRetries } : {},
185
330
  ...title !== void 0 ? { title } : {},
186
331
  ...environment !== void 0 ? { environment } : {},
187
332
  ...labels !== void 0 ? { labels } : {},
@@ -193,8 +338,14 @@ function readEnv(env = process.env) {
193
338
  // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
194
339
  // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
195
340
  // 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)
341
+ // `PLUNE_SHARD` implies it: the run is joined by the shared key and this process does not close it
342
+ // by itself; `leaveOpen` reports the shard instead.
343
+ keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED") || shard !== void 0 || shardError !== void 0,
344
+ ...shard !== void 0 ? { shard } : {},
345
+ ...shardError !== void 0 ? { shardError } : {},
346
+ ...importTimeout !== void 0 ? { importTimeout } : {},
347
+ ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0),
348
+ warnings
198
349
  };
199
350
  }
200
351
  function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cwd = process.cwd()) {
@@ -248,10 +399,18 @@ function repoRootOf(dir, stopAt) {
248
399
  if (here === stopAt || dirname2(here) === here) return void 0;
249
400
  }
250
401
  }
251
- function errorContextOf(attempt, home = homedir2()) {
402
+ function errorContextFields(attempt, home = homedir2()) {
403
+ const { text, omitted: omitted2 } = cutErrorContext(attempt, home);
404
+ return {
405
+ ...text !== "" ? { errorContext: text } : {},
406
+ ...omitted2 > 0 ? { errorContextOmitted: omitted2 } : {}
407
+ };
408
+ }
409
+ function cutErrorContext(attempt, home) {
252
410
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
253
411
  return cut(machineless(text, attempt.repoRoot, home));
254
412
  }
413
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
255
414
  var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
256
415
  var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
257
416
  var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
@@ -283,7 +442,7 @@ function pathIn(path3) {
283
442
  }
284
443
  var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
285
444
  function cut(text) {
286
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
445
+ if (jsonBytes(text) <= TEXT_LIMIT) return { text, omitted: 0 };
287
446
  const lines = text.split("\n");
288
447
  const size = lines.map((line) => jsonBytes(line) + 2);
289
448
  const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
@@ -292,7 +451,8 @@ function cut(text) {
292
451
  let tail = lines.length;
293
452
  while (head < tail && used + size[head] <= budget / 2) used += size[head++];
294
453
  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");
454
+ const kept = [...lines.slice(0, head), ...lines.slice(tail)].join("\n");
455
+ return { text: [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n"), omitted: text.length - kept.length };
296
456
  }
297
457
  var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
298
458
  var METADATA_TYPE = "application/plune.metadata+json";
@@ -350,6 +510,23 @@ function fromRoot(place, root) {
350
510
  function webLink(href) {
351
511
  return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
352
512
  }
513
+ var FILES_BATCH_MAX = 100;
514
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
515
+ var BATCH_PIPELINES = 2;
516
+ async function sha256File(path3) {
517
+ const hash = createHash("sha256");
518
+ for await (const part of createReadStream2(path3)) hash.update(part);
519
+ return hash.digest("hex");
520
+ }
521
+ var sha256Bytes = (bytes) => createHash("sha256").update(bytes).digest("hex");
522
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
523
+ "bucket_unreachable",
524
+ "not_connected",
525
+ "platform_not_configured",
526
+ "upload_expired",
527
+ "file_mismatch",
528
+ "file_missing"
529
+ ]);
353
530
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
354
531
  function appendBatch(file, batch) {
355
532
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -367,7 +544,8 @@ function appendBatch(file, batch) {
367
544
  var RESOLVE_CHUNK = 500;
368
545
  var BATCH_MAX = 500;
369
546
  var DISCOVER_MAX = 500;
370
- var BATCH_DEFAULT = 100;
547
+ var BATCH_DEFAULT = 500;
548
+ var SEND_CONCURRENCY = 4;
371
549
  var EXPECTED_MAX = 1e4;
372
550
  var KEY_MAX = 1024;
373
551
  var TITLE_MAX = 300;
@@ -384,7 +562,7 @@ var TYPE_BY_EXTENSION = {
384
562
  ".jpeg": "image/jpeg",
385
563
  ".webp": "image/webp"
386
564
  };
387
- var UPLOADS_AT_ONCE = 4;
565
+ var METADATA_TYPE2 = "application/plune.metadata+json";
388
566
  var NAME_MAX = 200;
389
567
  function nameOf(file) {
390
568
  const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename2(file.path));
@@ -409,15 +587,26 @@ var SKIPPED = {
409
587
  textSize: "Plune takes a text file of at most 512 KiB",
410
588
  empty: "the file is empty",
411
589
  binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
412
- encoding: "Plune takes UTF-8 text only"
590
+ encoding: "Plune takes UTF-8 text only",
591
+ noStorage: "no storage bucket is connected to this project"
413
592
  };
593
+ 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
594
  var KINDS = {
415
595
  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" }
596
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
597
+ // 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.
598
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
417
599
  };
418
600
  function kindOf(type) {
419
601
  if (type.startsWith("image/")) return "screenshot";
420
- return TEXT_TYPES.has(type) ? "text" : void 0;
602
+ return TEXT_TYPES.has(type) ? "text" : "file";
603
+ }
604
+ var codeOf = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
605
+ function linkOf(item) {
606
+ const link = item;
607
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
608
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
609
+ return { id: link.id, url: link.url, headers };
421
610
  }
422
611
  function textTypeOf(contentType, type) {
423
612
  const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
@@ -446,7 +635,7 @@ function tally(counts, noun) {
446
635
  }
447
636
  function boundKey(key) {
448
637
  if (key.value.length <= KEY_MAX) return key;
449
- const digest = createHash("sha256").update(key.value).digest("hex").slice(0, 16);
638
+ const digest = createHash2("sha256").update(key.value).digest("hex").slice(0, 16);
450
639
  let head = key.value.slice(0, KEY_MAX - digest.length - 1);
451
640
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
452
641
  return { ...key, value: `${head}#${digest}` };
@@ -494,6 +683,7 @@ function warnIfDropped(sent, run, log) {
494
683
  }
495
684
  async function startRun(passed, declared2) {
496
685
  const env = readEnv();
686
+ if (env.shardError !== void 0) throw new Error(env.shardError);
497
687
  const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
498
688
  const cfg = { ...env.config, ...stated };
499
689
  const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
@@ -504,9 +694,18 @@ async function startRun(passed, declared2) {
504
694
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
505
695
  const offerDiscovered = cfg.offerDiscovered ?? false;
506
696
  const token = cfg.token ?? loadToken() ?? "";
697
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
698
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
699
+ let retried = 0;
700
+ let uploadMs = 0;
701
+ let requests = 0;
702
+ let existed = 0;
703
+ let batchMissing = false;
507
704
  const client = createClient({
508
705
  apiUrl: resolveApiUrl(cfg.apiUrl),
509
706
  token,
707
+ uploadRetries,
708
+ onRetry: () => void (retried += 1),
510
709
  ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
511
710
  });
512
711
  const stats = {
@@ -520,18 +719,28 @@ async function startRun(passed, declared2) {
520
719
  unoffered: 0,
521
720
  deferred: 0,
522
721
  screenshots: { uploaded: 0, skipped: 0, failed: 0 },
523
- textFiles: { uploaded: 0, skipped: 0, failed: 0 }
722
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
723
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
524
724
  };
525
725
  const resolved = /* @__PURE__ */ new Map();
526
726
  let buffer = [];
527
727
  const discoveries = /* @__PURE__ */ new Map();
728
+ const held = /* @__PURE__ */ new Map();
729
+ let createdWithResult = 0;
730
+ let createdUndelivered = 0;
528
731
  let runId = null;
529
732
  let joined = false;
530
733
  let offline = token === "";
531
734
  let done = false;
532
735
  const shortened = /* @__PURE__ */ new Set();
533
736
  const skipsSaid = /* @__PURE__ */ new Set();
534
- const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
737
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
738
+ let bucketSeen = false;
739
+ let noStorage = 0;
740
+ let uploadsMissing = false;
741
+ const failedSaid = /* @__PURE__ */ new Set();
742
+ const codesSaid = /* @__PURE__ */ new Set();
743
+ const rooms = /* @__PURE__ */ new Map();
535
744
  function bound(keys) {
536
745
  return keys.map((key) => {
537
746
  const fit = boundKey(key);
@@ -539,7 +748,7 @@ async function startRun(passed, declared2) {
539
748
  shortened.add(key.value);
540
749
  if (shortened.size === 1) {
541
750
  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.`
751
+ `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
752
  );
544
753
  }
545
754
  }
@@ -550,6 +759,7 @@ async function startRun(passed, declared2) {
550
759
  if (offline) {
551
760
  log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
552
761
  }
762
+ for (const warning of env.warnings) log(`plune: ${warning}`);
553
763
  if (env.ignored.length > 0) {
554
764
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
555
765
  }
@@ -602,7 +812,7 @@ async function startRun(passed, declared2) {
602
812
  ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
603
813
  ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
604
814
  };
605
- const start = await client.post("/v1/runs", {
815
+ const request = {
606
816
  schemaVersion: 2,
607
817
  kind: cfg.kind ?? "automated",
608
818
  ...externalKey !== null ? { externalKey } : {},
@@ -613,7 +823,14 @@ async function startRun(passed, declared2) {
613
823
  // a person will miss, and a deployment older than the field must not be nagged on every run.
614
824
  title: defaultRunTitle(),
615
825
  ...described
616
- });
826
+ };
827
+ let start = await client.post("/v1/runs", request);
828
+ if (!start.ok && start.status === 413 && configuration !== void 0) {
829
+ log(
830
+ `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.`
831
+ );
832
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
833
+ }
617
834
  if (start.ok && typeof start.body?.run?.id === "string") {
618
835
  runId = start.body.run.id;
619
836
  joined = start.status === 200;
@@ -646,6 +863,7 @@ async function startRun(passed, declared2) {
646
863
  specRef: result.specRef,
647
864
  rawStatus: result.rawStatus
648
865
  });
866
+ held.set(result.keys[0].value, result);
649
867
  }
650
868
  async function offer() {
651
869
  if (discoveries.size === 0 || offline || runId === null) return;
@@ -664,24 +882,71 @@ async function startRun(passed, declared2) {
664
882
  return;
665
883
  }
666
884
  stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
667
- stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
885
+ const made = out.body.results.filter((r) => r?.outcome === "created");
886
+ stats.created += made.length;
887
+ const submissions = [];
888
+ const filesByKey = /* @__PURE__ */ new Map();
889
+ for (const r of made) {
890
+ const pending = typeof r.id === "string" && r.id !== "" ? held.get(r.key?.value) : void 0;
891
+ if (pending === void 0) continue;
892
+ held.delete(r.key.value);
893
+ const { keys: _keys, files, ...rest } = pending;
894
+ submissions.push({ ...rest, testCaseId: r.id });
895
+ if (files !== void 0) filesByKey.set(pending.resultKey, files);
896
+ }
897
+ if (submissions.length > 0) {
898
+ const before = stats.deferred;
899
+ await send(submissions, filesByKey);
900
+ createdWithResult += submissions.length;
901
+ createdUndelivered += stats.deferred - before;
902
+ }
668
903
  }
669
904
  }
670
905
  function skip(kind, name, why) {
671
906
  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]}.`);
907
+ if (why === "noStorage") noStorage += 1;
908
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
909
+ if (skipsSaid.has(said)) return;
910
+ skipsSaid.add(said);
911
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
912
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
913
+ }
914
+ function ask(job, size) {
915
+ requests += 1;
916
+ return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
917
+ files: [{ name: job.name, contentType: job.type, size }]
918
+ }, uploadRetries);
919
+ }
920
+ function failed(job, why) {
921
+ countsOf(job.kind).failed += 1;
922
+ if (!failedSaid.has(job.kind)) {
923
+ failedSaid.add(job.kind);
924
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
925
+ }
926
+ }
927
+ function failedToBucket(job, code) {
928
+ countsOf(job.kind).failed += 1;
929
+ if (codesSaid.has(code)) return;
930
+ codesSaid.add(code);
931
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
932
+ }
933
+ function refusedHere(job, size) {
934
+ if (job.kind === "screenshot") {
935
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
936
+ if (size > SCREENSHOT_BYTES) return "size";
937
+ }
938
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
939
+ return void 0;
675
940
  }
676
- async function uploadOne(job) {
941
+ async function uploadDirect(job, size) {
677
942
  const { kind } = job;
678
- const { label, bytes: ceiling, size } = KINDS[kind];
943
+ if (kind === "file") return skip(kind, job.name, "noStorage");
944
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
945
+ if (size > ceiling) return skip(kind, job.name, tooBig);
679
946
  let bytes;
680
947
  if (job.body !== void 0) bytes = job.body;
681
- else if (job.path === void 0) return skip(kind, job.name, "missing");
682
948
  else {
683
949
  try {
684
- if ((await disk.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
685
950
  bytes = await disk.readFile(job.path);
686
951
  } catch {
687
952
  return skip(kind, job.name, "missing");
@@ -689,37 +954,342 @@ async function startRun(passed, declared2) {
689
954
  }
690
955
  const refusal = kind === "text" ? textRefusal(bytes) : void 0;
691
956
  if (refusal !== void 0) return skip(kind, job.name, refusal);
957
+ requests += 1;
692
958
  const out = await client.upload(
693
959
  `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
694
960
  bytes,
695
961
  job.type
696
962
  );
697
- const counts = countsOf(kind);
698
- if (out.ok) {
699
- counts.uploaded += 1;
963
+ if (out.ok) countsOf(kind).uploaded += 1;
964
+ else failed(job, out.detail || out.kind);
965
+ }
966
+ async function uploadToBucket(job, size, first) {
967
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
968
+ let link = first;
969
+ for (let renewed = false; ; ) {
970
+ const put = await client.put(link.url, link.headers, source);
971
+ if (put.ok) break;
972
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
973
+ renewed = true;
974
+ const again = await ask(job, size);
975
+ if (!again.ok) return failedToBucket(job, codeOf(again));
976
+ const fresh = linkOf(again.body?.files?.[0]);
977
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
978
+ link = fresh;
979
+ }
980
+ requests += 1;
981
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
982
+ if (!done2.ok) return failedToBucket(job, codeOf(done2));
983
+ countsOf(job.kind).uploaded += 1;
984
+ }
985
+ let free = uploadsAtOnce;
986
+ const waiting = [];
987
+ async function gated(work) {
988
+ if (free === 0) await new Promise((resolve22) => waiting.push(resolve22));
989
+ else free -= 1;
990
+ try {
991
+ return await work();
992
+ } finally {
993
+ const next = waiting.shift();
994
+ if (next !== void 0) next();
995
+ else free += 1;
996
+ }
997
+ }
998
+ async function plan(job) {
999
+ const { kind } = job;
1000
+ let size;
1001
+ if (job.body !== void 0) size = job.body.length;
1002
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
1003
+ else {
1004
+ try {
1005
+ size = (await disk.stat(job.path)).size;
1006
+ } catch {
1007
+ return void skip(kind, job.name, "missing");
1008
+ }
1009
+ }
1010
+ if (size === 0) return void skip(kind, job.name, "empty");
1011
+ const direct = () => {
1012
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
1013
+ const roomKey = `${job.id}/${kind}`;
1014
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
1015
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
1016
+ rooms.set(roomKey, left - 1);
1017
+ return () => uploadDirect(job, size);
1018
+ };
1019
+ if (uploadsMissing) return direct();
1020
+ const out = await gated(() => ask(job, size));
1021
+ if (!out.ok) {
1022
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
1023
+ uploadsMissing = true;
1024
+ return direct();
1025
+ }
1026
+ if (out.code !== void 0) failedToBucket(job, out.code);
1027
+ else failed(job, out.detail || out.kind);
1028
+ return void 0;
1029
+ }
1030
+ const item = out.body?.files?.[0];
1031
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
1032
+ if (item?.direct === true) return direct();
1033
+ const link = linkOf(item);
1034
+ if (link === void 0) return void failed(job, "bad_answer");
1035
+ if (!bucketSeen) {
1036
+ bucketSeen = true;
1037
+ log(BUCKET_FOUND);
1038
+ }
1039
+ return () => uploadToBucket(job, size, link);
1040
+ }
1041
+ async function uploadEach(jobs) {
1042
+ const byResult = /* @__PURE__ */ new Map();
1043
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
1044
+ await Promise.all(
1045
+ [...byResult.values()].map(async (group) => {
1046
+ const work = [];
1047
+ for (const job of group) {
1048
+ const act = await plan(job);
1049
+ if (act !== void 0) work.push(gated(act));
1050
+ }
1051
+ await Promise.all(work);
1052
+ })
1053
+ );
1054
+ }
1055
+ async function measure(job) {
1056
+ let size;
1057
+ if (job.body !== void 0) size = job.body.length;
1058
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
1059
+ else {
1060
+ try {
1061
+ size = (await disk.stat(job.path)).size;
1062
+ } catch {
1063
+ return void skip(job.kind, job.name, "missing");
1064
+ }
1065
+ }
1066
+ if (size === 0) return void skip(job.kind, job.name, "empty");
1067
+ return size;
1068
+ }
1069
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
1070
+ function takeRoom(job) {
1071
+ if (job.kind === "file") {
1072
+ skip(job.kind, job.name, "noStorage");
1073
+ return false;
1074
+ }
1075
+ const roomKey = `${job.id}/${job.kind}`;
1076
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
1077
+ if (left === 0) {
1078
+ skip(job.kind, job.name, KINDS[job.kind].limit);
1079
+ return false;
1080
+ }
1081
+ rooms.set(roomKey, left - 1);
1082
+ return true;
1083
+ }
1084
+ function refusedItem(job, size, item) {
1085
+ const code = item.code ?? "refused";
1086
+ if (code === "duplicate") existed += 1;
1087
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
1088
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
1089
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
1090
+ else failed(job, code);
1091
+ }
1092
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
1093
+ async function batchOf(jobs) {
1094
+ if (batchMissing) return uploadEach(jobs);
1095
+ const sized = [];
1096
+ for (const job of jobs) {
1097
+ const size = await measure(job);
1098
+ if (size === void 0) continue;
1099
+ try {
1100
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
1101
+ } catch {
1102
+ skip(job.kind, job.name, "missing");
1103
+ }
1104
+ }
1105
+ if (sized.length === 0) return;
1106
+ const announced = await gated(() => {
1107
+ requests += 1;
1108
+ return client.post(
1109
+ "/v1/files/uploads-batch",
1110
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
1111
+ uploadRetries
1112
+ );
1113
+ });
1114
+ if (routeMissing(announced)) {
1115
+ batchMissing = true;
1116
+ return uploadEach(sized.map((s) => s.job));
1117
+ }
1118
+ const verdicts = announced.ok ? announced.body?.items : void 0;
1119
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
1120
+ for (const s of sized) {
1121
+ if (announced.ok) failed(s.job, "bad_answer");
1122
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
1123
+ else failed(s.job, announced.detail || announced.kind);
1124
+ }
700
1125
  return;
701
1126
  }
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.`);
1127
+ const puts = [];
1128
+ const directs = [];
1129
+ sized.forEach((s, i) => {
1130
+ const v = verdicts[i] ?? {};
1131
+ if (v.status === "exists") existed += 1;
1132
+ else if (v.status === "direct") {
1133
+ if (takeRoom(s.job)) directs.push(s);
1134
+ } else if (v.status === "upload") {
1135
+ const link = linkOf(v);
1136
+ if (link === void 0) return failed(s.job, "bad_answer");
1137
+ if (!bucketSeen) {
1138
+ bucketSeen = true;
1139
+ log(BUCKET_FOUND);
1140
+ }
1141
+ puts.push({ s, link });
1142
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
1143
+ else failed(s.job, "bad_answer");
1144
+ });
1145
+ const toComplete = [];
1146
+ await Promise.all(
1147
+ puts.map(
1148
+ ({ s, link: first }) => gated(async () => {
1149
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
1150
+ let link = first;
1151
+ for (let renewed = false; ; ) {
1152
+ const put = await client.put(link.url, link.headers, source);
1153
+ if (put.ok) break;
1154
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
1155
+ renewed = true;
1156
+ requests += 1;
1157
+ const again = await client.post(
1158
+ "/v1/files/uploads-batch",
1159
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
1160
+ uploadRetries
1161
+ );
1162
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
1163
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf(again));
1164
+ link = fresh;
1165
+ }
1166
+ toComplete.push({ job: s.job, id: link.id });
1167
+ })
1168
+ )
1169
+ );
1170
+ await complete(toComplete);
1171
+ await sendDirect(directs);
1172
+ }
1173
+ async function complete(items) {
1174
+ for (let round = 0; items.length > 0; round += 1) {
1175
+ const out = await gated(() => {
1176
+ requests += 1;
1177
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
1178
+ });
1179
+ if (routeMissing(out)) {
1180
+ await Promise.all(
1181
+ items.map(
1182
+ (i) => gated(async () => {
1183
+ requests += 1;
1184
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
1185
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
1186
+ else failedToBucket(i.job, codeOf(one));
1187
+ })
1188
+ )
1189
+ );
1190
+ return;
1191
+ }
1192
+ const verdicts = out.ok ? out.body?.items : void 0;
1193
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
1194
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf(out));
1195
+ return;
1196
+ }
1197
+ const again = [];
1198
+ items.forEach((i, at) => {
1199
+ const v = verdicts[at] ?? {};
1200
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
1201
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
1202
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1203
+ });
1204
+ items = again;
1205
+ if (items.length > 0) {
1206
+ retried += items.length;
1207
+ await itemPause(round);
1208
+ }
1209
+ }
1210
+ }
1211
+ async function sendDirect(items) {
1212
+ const groups = [];
1213
+ let bytes = 0;
1214
+ for (const item of items) {
1215
+ const group = groups[groups.length - 1];
1216
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
1217
+ groups.push([item]);
1218
+ bytes = item.size;
1219
+ } else {
1220
+ group.push(item);
1221
+ bytes += item.size;
1222
+ }
1223
+ }
1224
+ for (const group of groups) {
1225
+ const body = [];
1226
+ const sent = [];
1227
+ for (const { job, size } of group) {
1228
+ const { kind } = job;
1229
+ if (size > KINDS[kind].bytes) {
1230
+ skip(kind, job.name, KINDS[kind].size);
1231
+ continue;
1232
+ }
1233
+ let data;
1234
+ try {
1235
+ data = job.body ?? await disk.readFile(job.path);
1236
+ } catch {
1237
+ skip(kind, job.name, "missing");
1238
+ continue;
1239
+ }
1240
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
1241
+ if (refusal !== void 0) {
1242
+ skip(kind, job.name, refusal);
1243
+ continue;
1244
+ }
1245
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
1246
+ sent.push({ job, size });
1247
+ }
1248
+ if (body.length === 0) continue;
1249
+ const out = await gated(() => {
1250
+ requests += 1;
1251
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
1252
+ });
1253
+ if (routeMissing(out)) {
1254
+ batchMissing = true;
1255
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
1256
+ continue;
1257
+ }
1258
+ const verdicts = out.ok ? out.body?.items : void 0;
1259
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
1260
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
1261
+ continue;
1262
+ }
1263
+ sent.forEach(({ job }, i) => {
1264
+ const v = verdicts[i] ?? {};
1265
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
1266
+ else if (v.status === "exists") existed += 1;
1267
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1268
+ });
705
1269
  }
706
1270
  }
1271
+ async function uploadBatched(jobs) {
1272
+ const batches = chunk(jobs, FILES_BATCH_MAX);
1273
+ let next = 0;
1274
+ await Promise.all(
1275
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
1276
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
1277
+ })
1278
+ );
1279
+ }
707
1280
  async function upload(items, filesByKey) {
708
1281
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
709
1282
  const jobs = [];
710
1283
  for (const item of items) {
711
1284
  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
1285
  for (const file of filesByKey.get(item.resultKey) ?? []) {
714
1286
  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;
1287
+ if (type === void 0 || type === METADATA_TYPE2) continue;
1288
+ const kind = kindOf(type);
1289
+ if (kind !== "text" && file.path === void 0) continue;
717
1290
  const name = nameOf(file);
718
1291
  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
1292
  else {
722
- room[kind] -= 1;
723
1293
  jobs.push({
724
1294
  id: item.id,
725
1295
  kind,
@@ -731,14 +1301,34 @@ async function startRun(passed, declared2) {
731
1301
  }
732
1302
  }
733
1303
  }
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
- );
1304
+ const started = Date.now();
1305
+ if (batchMissing) await uploadEach(jobs);
1306
+ else await uploadBatched(jobs);
1307
+ uploadMs += Date.now() - started;
1308
+ }
1309
+ const sending = /* @__PURE__ */ new Set();
1310
+ let sendError;
1311
+ let answered = false;
1312
+ async function dispatch(work) {
1313
+ while (sending.size >= (answered ? SEND_CONCURRENCY : 1)) await Promise.race(sending);
1314
+ const task = work().catch((err) => {
1315
+ sendError ??= err;
1316
+ }).finally(() => sending.delete(task));
1317
+ sending.add(task);
1318
+ }
1319
+ async function settle() {
1320
+ while (sending.size > 0) await Promise.all([...sending]);
1321
+ if (sendError !== void 0) {
1322
+ const err = sendError;
1323
+ sendError = void 0;
1324
+ throw err;
1325
+ }
740
1326
  }
741
1327
  async function flush() {
1328
+ await flushBuffer();
1329
+ await settle();
1330
+ }
1331
+ async function flushBuffer() {
742
1332
  if (buffer.length === 0) return;
743
1333
  const pending = buffer;
744
1334
  buffer = [];
@@ -746,6 +1336,9 @@ async function startRun(passed, declared2) {
746
1336
  defer(pending);
747
1337
  return;
748
1338
  }
1339
+ await dispatch(() => deliver(pending));
1340
+ }
1341
+ async function deliver(pending) {
749
1342
  await resolveKeys(pending.flatMap((p) => p.keys));
750
1343
  const submissions = [];
751
1344
  const unanswered = [];
@@ -768,6 +1361,9 @@ async function startRun(passed, declared2) {
768
1361
  progress();
769
1362
  return;
770
1363
  }
1364
+ await send(submissions, filesByKey);
1365
+ }
1366
+ async function send(submissions, filesByKey) {
771
1367
  for (const part of packed(submissions)) {
772
1368
  if (offline) {
773
1369
  defer(part);
@@ -783,6 +1379,7 @@ async function startRun(passed, declared2) {
783
1379
  for (const k of told) stats[k] += counts[k];
784
1380
  progress();
785
1381
  await upload(out.ok ? out.body?.items : void 0, filesByKey);
1382
+ answered = true;
786
1383
  continue;
787
1384
  }
788
1385
  if (out.ok) {
@@ -811,17 +1408,40 @@ async function startRun(passed, declared2) {
811
1408
  if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
812
1409
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
813
1410
  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);
1411
+ if (stats.created > 0) {
1412
+ const recorded = createdWithResult === stats.created && createdUndelivered === 0;
1413
+ parts.push(`${stats.created} added as cases (trusted source)${recorded ? " and their results recorded" : ""}`);
1414
+ }
1415
+ const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1416
+ const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1417
+ if (bucketSeen) {
1418
+ const other = sum("skipped") - noStorage;
1419
+ parts.push(
1420
+ `${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` : "")
1421
+ );
1422
+ } else {
1423
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
1424
+ if (said !== void 0) parts.push(said);
1425
+ }
1426
+ const other = stats.otherFiles;
1427
+ if (other.skipped > 0) parts.push(`${other.skipped} file(s) not stored (no bucket connected)`);
1428
+ if (other.failed > 0) parts.push(`${other.failed} file(s) failed to upload`);
817
1429
  }
818
1430
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
819
1431
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1432
+ const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1433
+ const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1434
+ if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1435
+ log(
1436
+ `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)`
1437
+ );
1438
+ }
820
1439
  log(`plune: ${parts.join(" \xB7 ")}`);
821
1440
  if (stats.deferred > 0 && process.env["GITHUB_ACTIONS"] === "true") {
822
1441
  log(`::warning::${stats.deferred} result(s) were not delivered to Plune \u2014 see the reporting step's log.`);
823
1442
  }
824
1443
  }
1444
+ const shardLines = [];
825
1445
  return {
826
1446
  get runId() {
827
1447
  return runId;
@@ -834,40 +1454,73 @@ async function startRun(passed, declared2) {
834
1454
  },
835
1455
  async add(result) {
836
1456
  buffer.push({ ...result, keys: bound(result.keys) });
837
- if (buffer.length >= batchSize) await flush();
1457
+ if (buffer.length >= batchSize) await flushBuffer();
838
1458
  },
839
1459
  flush,
840
1460
  async finish(reason) {
841
- if (done) return;
1461
+ if (done) return void 0;
842
1462
  done = true;
843
1463
  await flush();
844
1464
  await offer();
1465
+ let frozen;
845
1466
  if (runId !== null && !offline) {
846
1467
  const out = await client.post(`/v1/runs/${runId}/events`, {
847
1468
  event: "finish",
848
1469
  ...reason !== void 0 ? { reason } : {}
849
1470
  });
850
1471
  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.`);
1472
+ else {
1473
+ frozen = out.body?.summary ?? void 0;
1474
+ if (typeof out.body?.detached === "number" && out.body.detached > 0) {
1475
+ log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1476
+ }
853
1477
  }
854
1478
  }
855
1479
  summarise();
1480
+ return frozen;
856
1481
  },
857
- async leaveOpen() {
858
- if (done) return;
1482
+ shardLines,
1483
+ async leaveOpen(opts) {
1484
+ if (done) return void 0;
859
1485
  done = true;
860
1486
  await flush();
861
1487
  await offer();
862
- if (runId !== null) {
1488
+ let frozen;
1489
+ const after = [];
1490
+ const shard = env.shard;
1491
+ let counted = false;
1492
+ let mismatch;
1493
+ if (runId !== null && shard !== void 0 && !offline) {
1494
+ const out = await client.post(`/v1/runs/${runId}/events`, { event: "finish", shardIndex: shard.index, shardsExpected: shard.total });
1495
+ if (out.ok && typeof out.body?.shardsReported === "number") {
1496
+ counted = true;
1497
+ frozen = out.body.summary ?? void 0;
1498
+ const n = out.body.shardsExpected ?? shard.total;
1499
+ if (out.body.run?.statusEvent === "finished") after.push("plune: run closed");
1500
+ after.push(`plune: shard ${shard.index} of ${shard.total} done \u2014 ${out.body.shardsReported} of ${n} shards reported`);
1501
+ } else if (out.ok || out.kind === "invalid") {
1502
+ log('plune: the platform does not support shard auto-close yet \u2014 the run is left open for "plune run finish".');
1503
+ } else if (out.code === "shards_mismatch") {
1504
+ mismatch = new Error(
1505
+ `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.`
1506
+ );
1507
+ } else {
1508
+ 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}".`);
1509
+ }
1510
+ }
1511
+ if (runId !== null && !counted) {
863
1512
  log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
864
1513
  }
865
1514
  summarise();
1515
+ shardLines.push(...after);
1516
+ if (opts?.holdShardLines !== true) for (const line of after) log(line);
1517
+ if (mismatch !== void 0) throw mismatch;
1518
+ return frozen;
866
1519
  }
867
1520
  };
868
1521
  }
869
1522
  function sha256(input) {
870
- return createHash2("sha256").update(input, "utf8").digest("hex");
1523
+ return createHash3("sha256").update(input, "utf8").digest("hex");
871
1524
  }
872
1525
  var RESULT_KEY_MAX = 200;
873
1526
  var HASH_CHARS = 32;
@@ -891,16 +1544,19 @@ function titlesOf(test) {
891
1544
  }
892
1545
  return titles;
893
1546
  }
1547
+ function pathTitleOf(test) {
1548
+ return [fileOf2(test), ...titlesOf(test)].join("#");
1549
+ }
894
1550
  function keysFor(test) {
895
1551
  return [
896
1552
  { kind: "playwright-id", value: test.id },
897
- { kind: "path-title", value: [fileOf2(test), ...titlesOf(test)].join("#") }
1553
+ { kind: "path-title", value: pathTitleOf(test) }
898
1554
  ];
899
1555
  }
900
- var METADATA_TYPE2 = "application/plune.metadata+json";
1556
+ var METADATA_TYPE3 = "application/plune.metadata+json";
901
1557
  var TOKEN = /@P([A-Za-z0-9_-]+)/;
902
1558
  function metadataOf(result) {
903
- const found = result.attachments.find((a) => a.contentType === METADATA_TYPE2);
1559
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
904
1560
  if (found === void 0) return void 0;
905
1561
  try {
906
1562
  const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync2(found.path, "utf8") : void 0;
@@ -909,12 +1565,32 @@ function metadataOf(result) {
909
1565
  return void 0;
910
1566
  }
911
1567
  }
912
- function statedIdOf(test, metadata) {
1568
+ function statedIdOf(test, metadata, mapped) {
913
1569
  const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
914
1570
  if (annotation !== void 0 && annotation !== "") return annotation;
915
1571
  const token = TOKEN.exec(test.title)?.[1];
916
1572
  if (token !== void 0) return token;
917
- return metadata?.id !== void 0 && metadata.id !== "" ? metadata.id : void 0;
1573
+ if (metadata?.id !== void 0 && metadata.id !== "") return metadata.id;
1574
+ return mapped;
1575
+ }
1576
+ function readIds(file) {
1577
+ let raw;
1578
+ try {
1579
+ raw = readFileSync2(file, "utf8");
1580
+ } catch {
1581
+ return {};
1582
+ }
1583
+ try {
1584
+ const parsed = JSON.parse(raw);
1585
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && Object.values(parsed).every((v) => typeof v === "string" && v !== ""))
1586
+ return parsed;
1587
+ } catch {
1588
+ }
1589
+ process.stderr.write(
1590
+ `plune: ${file} is not a JSON object of path-title to case id strings - ignored, tests resolve as if it were absent
1591
+ `
1592
+ );
1593
+ return {};
918
1594
  }
919
1595
  var NOT_FAILED = /* @__PURE__ */ new Set(["passed", "skipped"]);
920
1596
  function textOf(error) {
@@ -948,12 +1624,16 @@ function attemptOf(test, result, ctx) {
948
1624
  ...ctx.repoRoot !== void 0 ? { repoRoot: ctx.repoRoot } : {}
949
1625
  };
950
1626
  }
951
- function pendingFrom(test, result, ctx) {
1627
+ function pendingFrom(test, result, ctx, ids = {}) {
952
1628
  const metadata = metadataOf(result);
953
- const pluneId = statedIdOf(test, metadata);
1629
+ const pluneId = statedIdOf(
1630
+ test,
1631
+ metadata,
1632
+ Object.hasOwn(ids, pathTitleOf(test)) ? ids[pathTitleOf(test)] : void 0
1633
+ );
954
1634
  const expected = test.expectedStatus;
955
1635
  const attempt = attemptOf(test, result, ctx);
956
- const errorContext = errorContextOf(attempt);
1636
+ const errorContext = errorContextFields(attempt);
957
1637
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
958
1638
  const files = filesOf(attempt);
959
1639
  const startedAt = result.startTime;
@@ -983,7 +1663,7 @@ function pendingFrom(test, result, ctx) {
983
1663
  retry: result.retry,
984
1664
  worker: String(result.workerIndex)
985
1665
  },
986
- ...errorContext !== "" ? { errorContext } : {},
1666
+ ...errorContext,
987
1667
  ...failure !== void 0 ? { failure } : {},
988
1668
  // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
989
1669
  ...files.length > 0 ? { files } : {}
@@ -1001,6 +1681,8 @@ var PluneReporter = class {
1001
1681
  /** Kept whole: `metadata.ci` is written into it after `onConfigure`, so it is read at the run's opening. */
1002
1682
  config = null;
1003
1683
  context = {};
1684
+ /** The mapfile, read on the first result so a run that reports nothing never touches the disk. */
1685
+ ids = null;
1004
1686
  constructor(options = {}) {
1005
1687
  this.options = options;
1006
1688
  }
@@ -1053,7 +1735,10 @@ var PluneReporter = class {
1053
1735
  onTestEnd(test, result) {
1054
1736
  const session = this.open();
1055
1737
  this.chain = this.chain.then(async () => {
1056
- await (await session).add(pendingFrom(test, result, this.context));
1738
+ this.ids ??= readIds(
1739
+ resolve2(this.options.idsFile ?? process.env["PLUNE_IDS_FILE"] ?? "plune/ids.json")
1740
+ );
1741
+ await (await session).add(pendingFrom(test, result, this.context, this.ids));
1057
1742
  }).catch((err) => this.giveUp(err));
1058
1743
  }
1059
1744
  async onEnd(_result) {