@plune-ai/playwright 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,24 +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";
10
+ import { TextDecoder } from "util";
9
11
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
10
12
  import { homedir } from "os";
11
13
  import { dirname, join } from "path";
12
- import { request as httpRequest } from "http";
13
- 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";
14
18
  import * as path from "path";
15
- import * as fs from "fs";
16
- import * as path2 from "path";
17
- import { createHash as createHash2 } from "crypto";
18
19
  import { existsSync as existsSync2 } from "fs";
19
20
  import { homedir as homedir2 } from "os";
20
- import { dirname as dirname3, join as join3, posix, resolve } from "path";
21
+ import { dirname as dirname2, join as join2, posix, resolve } from "path";
21
22
  import { stripVTControlCharacters } from "util";
23
+ import { createHash } from "crypto";
24
+ import { createReadStream as createReadStream2 } from "fs";
25
+ import * as fs from "fs";
26
+ import * as path2 from "path";
27
+ import { createHash as createHash3 } from "crypto";
22
28
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
23
29
  function resolveApiUrl(explicit) {
24
30
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -38,20 +44,32 @@ function loadToken() {
38
44
  return null;
39
45
  }
40
46
  }
41
- 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 }) };
42
59
  var IDLE_MS = 3e5;
43
60
  function nodeTransport(url, init, idleMs = IDLE_MS) {
44
- return new Promise((resolve2, reject) => {
61
+ return new Promise((resolve22, reject) => {
45
62
  const target = new URL(url);
46
63
  const send = target.protocol === "https:" ? httpsRequest : httpRequest;
47
- 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) => {
48
66
  const chunks = [];
49
67
  res.on("data", (chunk2) => chunks.push(chunk2));
50
68
  res.on("error", reject);
51
69
  res.on("end", () => {
52
70
  const status = res.statusCode ?? 0;
53
71
  const text = Buffer.concat(chunks).toString("utf8");
54
- resolve2({
72
+ resolve22({
55
73
  ok: status >= 200 && status <= 299,
56
74
  status,
57
75
  headers: {
@@ -69,20 +87,60 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
69
87
  req.end(init.body);
70
88
  });
71
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
+ };
72
122
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
73
123
  async function detailOf(res) {
74
124
  try {
75
125
  const body = await res.json();
76
- 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
+ };
77
133
  } catch {
78
- return "";
134
+ return { detail: "" };
79
135
  }
80
136
  }
81
- function retryAfterMs(res) {
82
- const raw = res.headers.get("retry-after");
83
- if (raw === null) return null;
84
- const seconds = Number(raw.trim());
85
- 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(", ");
86
144
  }
87
145
  function classify(status) {
88
146
  if (status === 401 || status === 403) return "auth";
@@ -94,15 +152,34 @@ function classify(status) {
94
152
  function createClient(opts) {
95
153
  const doFetch = opts.fetchImpl ?? nodeTransport;
96
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
+ }
97
172
  const base = opts.apiUrl.replace(/\/+$/, "");
98
173
  const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
99
- async function send(method, path3, payload) {
174
+ async function send(method, path3, payload, retries = DEFAULT_RETRIES) {
100
175
  let last = {
101
176
  kind: "unavailable",
102
177
  status: null,
103
178
  detail: "no attempt was made"
104
179
  };
105
- 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);
106
183
  let res;
107
184
  try {
108
185
  res = await doFetch(`${base}${path3}`, {
@@ -115,7 +192,8 @@ function createClient(opts) {
115
192
  });
116
193
  } catch (err) {
117
194
  last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
118
- 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);
119
197
  continue;
120
198
  }
121
199
  if (res.ok) {
@@ -126,23 +204,76 @@ function createClient(opts) {
126
204
  return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
127
205
  }
128
206
  }
129
- const detail = scrub(await detailOf(res));
207
+ const said = await detailOf(res);
130
208
  const kind = classify(res.status);
131
- 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 } : {} };
132
210
  if (kind !== "unavailable") break;
133
- if (attempt < RETRY_DELAYS_MS.length) {
134
- 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;
135
217
  }
218
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
219
+ mine = await backOff(attempt, said429);
136
220
  }
137
221
  return { ok: false, ...last };
138
222
  }
139
223
  return {
140
- post: (path3, body) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }),
141
- upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }),
142
- 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
+ }
143
260
  };
144
261
  }
145
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 };
146
277
  function value(env, name) {
147
278
  const raw = env[name]?.trim();
148
279
  return raw === void 0 || raw === "" ? void 0 : raw;
@@ -157,6 +288,14 @@ function count(env, name) {
157
288
  const n = Number(raw);
158
289
  return Number.isInteger(n) && n > 0 ? n : void 0;
159
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
+ }
160
299
  function list(env, name) {
161
300
  const raw = value(env, name);
162
301
  if (raw === void 0) return void 0;
@@ -169,11 +308,16 @@ function readEnv(env = process.env) {
169
308
  const apiUrl = value(env, "PLUNE_API_URL");
170
309
  const fallbackPath = value(env, "PLUNE_FALLBACK");
171
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);
172
315
  const title = value(env, "PLUNE_RUN_TITLE");
173
316
  const environment = value(env, "PLUNE_ENV");
174
317
  const labels = list(env, "PLUNE_LABELS");
175
318
  const offerDiscovered = flag(env, "PLUNE_CREATE");
176
319
  const full = flag(env, "PLUNE_FULL_RUN");
320
+ const { shard, error: shardError } = shardOf(env);
177
321
  return {
178
322
  config: {
179
323
  ...externalKey !== void 0 ? { externalKey } : {},
@@ -181,6 +325,8 @@ function readEnv(env = process.env) {
181
325
  ...apiUrl !== void 0 ? { apiUrl } : {},
182
326
  ...fallbackPath !== void 0 ? { fallbackPath } : {},
183
327
  ...batchSize !== void 0 ? { batchSize } : {},
328
+ ...uploadConcurrency !== void 0 ? { uploadConcurrency } : {},
329
+ ...uploadRetries !== void 0 ? { uploadRetries } : {},
184
330
  ...title !== void 0 ? { title } : {},
185
331
  ...environment !== void 0 ? { environment } : {},
186
332
  ...labels !== void 0 ? { labels } : {},
@@ -192,8 +338,14 @@ function readEnv(env = process.env) {
192
338
  // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
193
339
  // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
194
340
  // way this process must not be the one to call it finished.
195
- keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED"),
196
- 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
197
349
  };
198
350
  }
199
351
  function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cwd = process.cwd()) {
@@ -224,6 +376,157 @@ function ciCommit(reported, env = process.env) {
224
376
  ...branch !== void 0 ? { branch } : {}
225
377
  };
226
378
  }
379
+ function failureOf(attempt, home = homedir2()) {
380
+ const error = chosen(attempt);
381
+ const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
382
+ const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
383
+ const steps = chainOf(attempt.steps);
384
+ const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
385
+ const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && a.contentType !== METADATA_TYPE).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
386
+ const ciUrl = webLink(attempt.buildHref);
387
+ const failure = {
388
+ ...headline !== void 0 ? { headline } : {},
389
+ ...steps.length > 0 ? { steps } : {},
390
+ ...location !== void 0 ? { location } : {},
391
+ ...artifacts.length > 0 ? { artifacts } : {},
392
+ ...ciUrl !== void 0 ? { ciUrl } : {}
393
+ };
394
+ return Object.keys(failure).length === 0 ? void 0 : failure;
395
+ }
396
+ function repoRootOf(dir, stopAt) {
397
+ for (let here = resolve(dir); ; here = dirname2(here)) {
398
+ if (existsSync2(join2(here, ".git"))) return here;
399
+ if (here === stopAt || dirname2(here) === here) return void 0;
400
+ }
401
+ }
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) {
410
+ const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
411
+ return cut(machineless(text, attempt.repoRoot, home));
412
+ }
413
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
414
+ var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
415
+ var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
416
+ var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
417
+ function filesOf(attempt) {
418
+ return attempt.attachments.filter((a) => a.path !== void 0 || a.body !== void 0 && isTextType(a.contentType));
419
+ }
420
+ function machineless(raw, repoRoot, home) {
421
+ let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
422
+ const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
423
+ if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
424
+ const own = pathIn(home);
425
+ if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
426
+ if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
427
+ return text;
428
+ }
429
+ var PATH_START = "(?<![\\w.~%/\\\\-])";
430
+ var TEXT_LIMIT = 524288;
431
+ var HEADLINE_LIMIT = 8 * 1024;
432
+ var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
433
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
434
+ function pathIn(path3) {
435
+ const parts = path3.split(/[\\/]+/);
436
+ while (parts.length > 1 && parts.at(-1) === "") parts.pop();
437
+ if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
438
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
439
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
440
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
441
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
442
+ }
443
+ var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
444
+ function cut(text) {
445
+ if (jsonBytes(text) <= TEXT_LIMIT) return { text, omitted: 0 };
446
+ const lines = text.split("\n");
447
+ const size = lines.map((line) => jsonBytes(line) + 2);
448
+ const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
449
+ let used = 0;
450
+ let head = 0;
451
+ let tail = lines.length;
452
+ while (head < tail && used + size[head] <= budget / 2) used += size[head++];
453
+ while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
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 };
456
+ }
457
+ var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
458
+ var METADATA_TYPE = "application/plune.metadata+json";
459
+ var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
460
+ var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
461
+ var FRAME_MAX = 8192;
462
+ var firstLine = (text) => stripVTControlCharacters(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
463
+ function chosen({ status, errors }) {
464
+ if (status === "timedOut") {
465
+ const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
466
+ if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
467
+ }
468
+ return errors[0];
469
+ }
470
+ function chainOf(steps) {
471
+ const chain = [];
472
+ for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
473
+ chain.push(failed.title);
474
+ }
475
+ return chain;
476
+ }
477
+ function placeOf(error, testFile) {
478
+ const own = normal(testFile);
479
+ let first;
480
+ for (const line of stripVTControlCharacters(error.text).split("\n")) {
481
+ if (line.length > FRAME_MAX) continue;
482
+ const frame = FRAME.exec(line);
483
+ if (frame === null) continue;
484
+ const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
485
+ if (normal(place.file) === own) return place;
486
+ if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
487
+ }
488
+ return error.location ?? first;
489
+ }
490
+ function fileOf(raw) {
491
+ if (!raw.startsWith("file://")) return raw;
492
+ let path3 = raw.slice("file://".length);
493
+ try {
494
+ path3 = decodeURIComponent(path3);
495
+ } catch {
496
+ }
497
+ return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
498
+ }
499
+ var normal = (path3) => posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
500
+ function fromRoot(place, root) {
501
+ if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
502
+ const base = normal(root).replace(/\/+$/, "");
503
+ const file = normal(place.file);
504
+ if (!file.startsWith(`${base}/`)) return void 0;
505
+ const relative = file.slice(base.length + 1);
506
+ if (!REPO_RELATIVE.test(relative)) return void 0;
507
+ const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
508
+ return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
509
+ }
510
+ function webLink(href) {
511
+ return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
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
+ ]);
227
530
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
228
531
  function appendBatch(file, batch) {
229
532
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -241,7 +544,8 @@ function appendBatch(file, batch) {
241
544
  var RESOLVE_CHUNK = 500;
242
545
  var BATCH_MAX = 500;
243
546
  var DISCOVER_MAX = 500;
244
- var BATCH_DEFAULT = 100;
547
+ var BATCH_DEFAULT = 500;
548
+ var SEND_CONCURRENCY = 4;
245
549
  var EXPECTED_MAX = 1e4;
246
550
  var KEY_MAX = 1024;
247
551
  var TITLE_MAX = 300;
@@ -249,17 +553,20 @@ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
249
553
  var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
250
554
  var SCREENSHOT_BYTES = 2 * 1024 * 1024;
251
555
  var SCREENSHOTS_PER_RESULT = 20;
556
+ var TEXT_BYTES = 512 * 1024;
557
+ var TEXTS_PER_RESULT = 10;
558
+ var UTF8 = new TextDecoder("utf-8", { fatal: true });
252
559
  var TYPE_BY_EXTENSION = {
253
560
  ".png": "image/png",
254
561
  ".jpg": "image/jpeg",
255
562
  ".jpeg": "image/jpeg",
256
563
  ".webp": "image/webp"
257
564
  };
258
- var UPLOADS_AT_ONCE = 4;
565
+ var METADATA_TYPE2 = "application/plune.metadata+json";
259
566
  var NAME_MAX = 200;
260
567
  function nameOf(file) {
261
- const own = file.name.split(/[\\/]/).pop()?.trim() || basename2(file.path);
262
- const fileExt = extname(file.path);
568
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename2(file.path));
569
+ const fileExt = file.path === void 0 ? "" : extname(file.path);
263
570
  const ownExt = extname(own);
264
571
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
265
572
  const ext = typed ? ownExt : fileExt;
@@ -275,11 +582,60 @@ var SKIPPED = {
275
582
  type: "Plune takes PNG, JPEG and WebP",
276
583
  limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
277
584
  missing: "the file cannot be read on this machine",
278
- size: "Plune takes a file of at most 2 MB"
585
+ size: "Plune takes a file of at most 2 MB",
586
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
587
+ textSize: "Plune takes a text file of at most 512 KiB",
588
+ empty: "the file is empty",
589
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
590
+ encoding: "Plune takes UTF-8 text only",
591
+ noStorage: "no storage bucket is connected to this project"
279
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.";
594
+ var KINDS = {
595
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
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" }
599
+ };
600
+ function kindOf(type) {
601
+ if (type.startsWith("image/")) return "screenshot";
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 };
610
+ }
611
+ function textTypeOf(contentType, type) {
612
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
613
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
614
+ }
615
+ function textRefusal(bytes) {
616
+ if (bytes.length > TEXT_BYTES) return "textSize";
617
+ if (bytes.length === 0) return "empty";
618
+ if (bytes.includes(0)) return "binary";
619
+ try {
620
+ UTF8.decode(bytes);
621
+ } catch {
622
+ return "encoding";
623
+ }
624
+ return void 0;
625
+ }
626
+ function onDisk(result) {
627
+ if (!("files" in result) || result.files === void 0) return result;
628
+ const { files, ...rest } = result;
629
+ const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
630
+ return kept.length === 0 ? rest : { ...rest, files: kept };
631
+ }
632
+ function tally(counts, noun) {
633
+ if (counts.uploaded + counts.skipped + counts.failed === 0) return void 0;
634
+ return `${counts.uploaded} ${noun}(s) uploaded` + (counts.skipped > 0 ? `, ${counts.skipped} skipped` : "") + (counts.failed > 0 ? `, ${counts.failed} failed to upload` : "");
635
+ }
280
636
  function boundKey(key) {
281
637
  if (key.value.length <= KEY_MAX) return key;
282
- 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);
283
639
  let head = key.value.slice(0, KEY_MAX - digest.length - 1);
284
640
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
285
641
  return { ...key, value: `${head}#${digest}` };
@@ -327,6 +683,7 @@ function warnIfDropped(sent, run, log) {
327
683
  }
328
684
  async function startRun(passed, declared2) {
329
685
  const env = readEnv();
686
+ if (env.shardError !== void 0) throw new Error(env.shardError);
330
687
  const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
331
688
  const cfg = { ...env.config, ...stated };
332
689
  const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
@@ -337,9 +694,18 @@ async function startRun(passed, declared2) {
337
694
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
338
695
  const offerDiscovered = cfg.offerDiscovered ?? false;
339
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;
340
704
  const client = createClient({
341
705
  apiUrl: resolveApiUrl(cfg.apiUrl),
342
706
  token,
707
+ uploadRetries,
708
+ onRetry: () => void (retried += 1),
343
709
  ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
344
710
  });
345
711
  const stats = {
@@ -352,17 +718,29 @@ async function startRun(passed, declared2) {
352
718
  created: 0,
353
719
  unoffered: 0,
354
720
  deferred: 0,
355
- screenshots: { uploaded: 0, skipped: 0, failed: 0 }
721
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
722
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
723
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
356
724
  };
357
725
  const resolved = /* @__PURE__ */ new Map();
358
726
  let buffer = [];
359
727
  const discoveries = /* @__PURE__ */ new Map();
728
+ const held = /* @__PURE__ */ new Map();
729
+ let createdWithResult = 0;
730
+ let createdUndelivered = 0;
360
731
  let runId = null;
361
732
  let joined = false;
362
733
  let offline = token === "";
363
734
  let done = false;
364
735
  const shortened = /* @__PURE__ */ new Set();
365
736
  const skipsSaid = /* @__PURE__ */ new Set();
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();
366
744
  function bound(keys) {
367
745
  return keys.map((key) => {
368
746
  const fit = boundKey(key);
@@ -370,7 +748,7 @@ async function startRun(passed, declared2) {
370
748
  shortened.add(key.value);
371
749
  if (shortened.size === 1) {
372
750
  log(
373
- `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.`
374
752
  );
375
753
  }
376
754
  }
@@ -381,6 +759,7 @@ async function startRun(passed, declared2) {
381
759
  if (offline) {
382
760
  log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
383
761
  }
762
+ for (const warning of env.warnings) log(`plune: ${warning}`);
384
763
  if (env.ignored.length > 0) {
385
764
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
386
765
  }
@@ -390,7 +769,7 @@ async function startRun(passed, declared2) {
390
769
  externalKey,
391
770
  session: sessionMarker,
392
771
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
393
- results
772
+ results: results.map(onDisk)
394
773
  });
395
774
  stats.deferred += results.length;
396
775
  }
@@ -433,7 +812,7 @@ async function startRun(passed, declared2) {
433
812
  ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
434
813
  ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
435
814
  };
436
- const start = await client.post("/v1/runs", {
815
+ const request = {
437
816
  schemaVersion: 2,
438
817
  kind: cfg.kind ?? "automated",
439
818
  ...externalKey !== null ? { externalKey } : {},
@@ -444,7 +823,14 @@ async function startRun(passed, declared2) {
444
823
  // a person will miss, and a deployment older than the field must not be nagged on every run.
445
824
  title: defaultRunTitle(),
446
825
  ...described
447
- });
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
+ }
448
834
  if (start.ok && typeof start.body?.run?.id === "string") {
449
835
  runId = start.body.run.id;
450
836
  joined = start.status === 200;
@@ -477,6 +863,7 @@ async function startRun(passed, declared2) {
477
863
  specRef: result.specRef,
478
864
  rawStatus: result.rawStatus
479
865
  });
866
+ held.set(result.keys[0].value, result);
480
867
  }
481
868
  async function offer() {
482
869
  if (discoveries.size === 0 || offline || runId === null) return;
@@ -495,64 +882,453 @@ async function startRun(passed, declared2) {
495
882
  return;
496
883
  }
497
884
  stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
498
- 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
+ }
903
+ }
904
+ }
905
+ function skip(kind, name, why) {
906
+ countsOf(kind).skipped += 1;
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.`);
499
925
  }
500
926
  }
501
- function skip(name, why) {
502
- stats.screenshots.skipped += 1;
503
- if (skipsSaid.has(why)) return;
504
- skipsSaid.add(why);
505
- log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
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;
506
940
  }
507
- async function uploadOne(shot) {
941
+ async function uploadDirect(job, size) {
942
+ const { kind } = job;
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);
508
946
  let bytes;
509
- try {
510
- if ((await disk.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
511
- bytes = await disk.readFile(shot.path);
512
- } catch {
513
- return skip(shot.name, "missing");
947
+ if (job.body !== void 0) bytes = job.body;
948
+ else {
949
+ try {
950
+ bytes = await disk.readFile(job.path);
951
+ } catch {
952
+ return skip(kind, job.name, "missing");
953
+ }
514
954
  }
955
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
956
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
957
+ requests += 1;
515
958
  const out = await client.upload(
516
- `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
959
+ `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
517
960
  bytes,
518
- shot.type
961
+ job.type
962
+ );
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
+ })
519
1053
  );
520
- if (out.ok) {
521
- stats.screenshots.uploaded += 1;
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
+ }
522
1125
  return;
523
1126
  }
524
- stats.screenshots.failed += 1;
525
- if (stats.screenshots.failed === 1) {
526
- log(`plune: could not upload a screenshot (${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
+ }
527
1209
  }
528
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
+ });
1269
+ }
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
+ }
529
1280
  async function upload(items, filesByKey) {
530
1281
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
531
- const shots = [];
1282
+ const jobs = [];
532
1283
  for (const item of items) {
533
1284
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
534
- let room = SCREENSHOTS_PER_RESULT;
535
1285
  for (const file of filesByKey.get(item.resultKey) ?? []) {
536
- const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[extname(file.path).toLowerCase()];
537
- if (!type?.startsWith("image/")) continue;
1286
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[extname(file.path).toLowerCase()]);
1287
+ if (type === void 0 || type === METADATA_TYPE2) continue;
1288
+ const kind = kindOf(type);
1289
+ if (kind !== "text" && file.path === void 0) continue;
538
1290
  const name = nameOf(file);
539
- if (file.name.startsWith("_")) skip(name, "hidden");
540
- else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
541
- else if (room === 0) skip(name, "limit");
1291
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
542
1292
  else {
543
- room -= 1;
544
- shots.push({ id: item.id, name, type, path: file.path });
1293
+ jobs.push({
1294
+ id: item.id,
1295
+ kind,
1296
+ name,
1297
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
1298
+ ...file.body !== void 0 ? { body: file.body } : {},
1299
+ ...file.path !== void 0 ? { path: file.path } : {}
1300
+ });
545
1301
  }
546
1302
  }
547
1303
  }
548
- let next = 0;
549
- await Promise.all(
550
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
551
- while (next < shots.length) await uploadOne(shots[next++]);
552
- })
553
- );
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
+ }
554
1326
  }
555
1327
  async function flush() {
1328
+ await flushBuffer();
1329
+ await settle();
1330
+ }
1331
+ async function flushBuffer() {
556
1332
  if (buffer.length === 0) return;
557
1333
  const pending = buffer;
558
1334
  buffer = [];
@@ -560,6 +1336,9 @@ async function startRun(passed, declared2) {
560
1336
  defer(pending);
561
1337
  return;
562
1338
  }
1339
+ await dispatch(() => deliver(pending));
1340
+ }
1341
+ async function deliver(pending) {
563
1342
  await resolveKeys(pending.flatMap((p) => p.keys));
564
1343
  const submissions = [];
565
1344
  const unanswered = [];
@@ -582,6 +1361,9 @@ async function startRun(passed, declared2) {
582
1361
  progress();
583
1362
  return;
584
1363
  }
1364
+ await send(submissions, filesByKey);
1365
+ }
1366
+ async function send(submissions, filesByKey) {
585
1367
  for (const part of packed(submissions)) {
586
1368
  if (offline) {
587
1369
  defer(part);
@@ -597,6 +1379,7 @@ async function startRun(passed, declared2) {
597
1379
  for (const k of told) stats[k] += counts[k];
598
1380
  progress();
599
1381
  await upload(out.ok ? out.body?.items : void 0, filesByKey);
1382
+ answered = true;
600
1383
  continue;
601
1384
  }
602
1385
  if (out.ok) {
@@ -625,20 +1408,40 @@ async function startRun(passed, declared2) {
625
1408
  if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
626
1409
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
627
1410
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
628
- if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
629
- const shots = stats.screenshots;
630
- if (shots.uploaded + shots.skipped + shots.failed > 0) {
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;
631
1419
  parts.push(
632
- `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
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` : "")
633
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`);
634
1429
  }
635
1430
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
636
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
+ }
637
1439
  log(`plune: ${parts.join(" \xB7 ")}`);
638
1440
  if (stats.deferred > 0 && process.env["GITHUB_ACTIONS"] === "true") {
639
1441
  log(`::warning::${stats.deferred} result(s) were not delivered to Plune \u2014 see the reporting step's log.`);
640
1442
  }
641
1443
  }
1444
+ const shardLines = [];
642
1445
  return {
643
1446
  get runId() {
644
1447
  return runId;
@@ -651,40 +1454,73 @@ async function startRun(passed, declared2) {
651
1454
  },
652
1455
  async add(result) {
653
1456
  buffer.push({ ...result, keys: bound(result.keys) });
654
- if (buffer.length >= batchSize) await flush();
1457
+ if (buffer.length >= batchSize) await flushBuffer();
655
1458
  },
656
1459
  flush,
657
1460
  async finish(reason) {
658
- if (done) return;
1461
+ if (done) return void 0;
659
1462
  done = true;
660
1463
  await flush();
661
1464
  await offer();
1465
+ let frozen;
662
1466
  if (runId !== null && !offline) {
663
1467
  const out = await client.post(`/v1/runs/${runId}/events`, {
664
1468
  event: "finish",
665
1469
  ...reason !== void 0 ? { reason } : {}
666
1470
  });
667
1471
  if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
668
- else if (typeof out.body?.detached === "number" && out.body.detached > 0) {
669
- 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
+ }
670
1477
  }
671
1478
  }
672
1479
  summarise();
1480
+ return frozen;
673
1481
  },
674
- async leaveOpen() {
675
- if (done) return;
1482
+ shardLines,
1483
+ async leaveOpen(opts) {
1484
+ if (done) return void 0;
676
1485
  done = true;
677
1486
  await flush();
678
1487
  await offer();
679
- 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) {
680
1512
  log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
681
1513
  }
682
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;
683
1519
  }
684
1520
  };
685
1521
  }
686
1522
  function sha256(input) {
687
- return createHash2("sha256").update(input, "utf8").digest("hex");
1523
+ return createHash3("sha256").update(input, "utf8").digest("hex");
688
1524
  }
689
1525
  var RESULT_KEY_MAX = 200;
690
1526
  var HASH_CHARS = 32;
@@ -692,128 +1528,6 @@ function resultKey(testId, retry) {
692
1528
  const plain = `${testId}#${retry}`;
693
1529
  return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
694
1530
  }
695
- function failureOf(attempt, home = homedir2()) {
696
- const error = chosen(attempt);
697
- const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
698
- const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
699
- const steps = chainOf(attempt.steps);
700
- const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
701
- const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && a.contentType !== METADATA_TYPE).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
702
- const ciUrl = webLink(attempt.buildHref);
703
- const failure = {
704
- ...headline !== void 0 ? { headline } : {},
705
- ...steps.length > 0 ? { steps } : {},
706
- ...location !== void 0 ? { location } : {},
707
- ...artifacts.length > 0 ? { artifacts } : {},
708
- ...ciUrl !== void 0 ? { ciUrl } : {}
709
- };
710
- return Object.keys(failure).length === 0 ? void 0 : failure;
711
- }
712
- function repoRootOf(dir, stopAt) {
713
- for (let here = resolve(dir); ; here = dirname3(here)) {
714
- if (existsSync2(join3(here, ".git"))) return here;
715
- if (here === stopAt || dirname3(here) === here) return void 0;
716
- }
717
- }
718
- function errorContextOf(attempt, home = homedir2()) {
719
- const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
720
- return cut(machineless(text, attempt.repoRoot, home));
721
- }
722
- function filesOf(attempt) {
723
- return attempt.attachments.filter((a) => a.path !== void 0);
724
- }
725
- function machineless(raw, repoRoot, home) {
726
- let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
727
- const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
728
- if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
729
- const own = pathIn(home);
730
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
731
- if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
732
- return text;
733
- }
734
- var PATH_START = "(?<![\\w.~%/\\\\-])";
735
- var TEXT_LIMIT = 524288;
736
- var HEADLINE_LIMIT = 8 * 1024;
737
- var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
738
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
739
- function pathIn(path3) {
740
- const parts = path3.split(/[\\/]+/);
741
- while (parts.length > 1 && parts.at(-1) === "") parts.pop();
742
- if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
743
- const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
744
- const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
745
- const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
746
- return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
747
- }
748
- var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
749
- function cut(text) {
750
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
751
- const lines = text.split("\n");
752
- const size = lines.map((line) => jsonBytes(line) + 2);
753
- const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
754
- let used = 0;
755
- let head = 0;
756
- let tail = lines.length;
757
- while (head < tail && used + size[head] <= budget / 2) used += size[head++];
758
- while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
759
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
760
- }
761
- var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
762
- var METADATA_TYPE = "application/plune.metadata+json";
763
- var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
764
- var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
765
- var FRAME_MAX = 8192;
766
- var firstLine = (text) => stripVTControlCharacters(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
767
- function chosen({ status, errors }) {
768
- if (status === "timedOut") {
769
- const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
770
- if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
771
- }
772
- return errors[0];
773
- }
774
- function chainOf(steps) {
775
- const chain = [];
776
- for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
777
- chain.push(failed.title);
778
- }
779
- return chain;
780
- }
781
- function placeOf(error, testFile) {
782
- const own = normal(testFile);
783
- let first;
784
- for (const line of stripVTControlCharacters(error.text).split("\n")) {
785
- if (line.length > FRAME_MAX) continue;
786
- const frame = FRAME.exec(line);
787
- if (frame === null) continue;
788
- const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
789
- if (normal(place.file) === own) return place;
790
- if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
791
- }
792
- return error.location ?? first;
793
- }
794
- function fileOf(raw) {
795
- if (!raw.startsWith("file://")) return raw;
796
- let path3 = raw.slice("file://".length);
797
- try {
798
- path3 = decodeURIComponent(path3);
799
- } catch {
800
- }
801
- return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
802
- }
803
- var normal = (path3) => posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
804
- function fromRoot(place, root) {
805
- if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
806
- const base = normal(root).replace(/\/+$/, "");
807
- const file = normal(place.file);
808
- if (!file.startsWith(`${base}/`)) return void 0;
809
- const relative = file.slice(base.length + 1);
810
- if (!REPO_RELATIVE.test(relative)) return void 0;
811
- const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
812
- return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
813
- }
814
- function webLink(href) {
815
- return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
816
- }
817
1531
 
818
1532
  // src/index.ts
819
1533
  var SOURCE = "playwright";
@@ -830,16 +1544,19 @@ function titlesOf(test) {
830
1544
  }
831
1545
  return titles;
832
1546
  }
1547
+ function pathTitleOf(test) {
1548
+ return [fileOf2(test), ...titlesOf(test)].join("#");
1549
+ }
833
1550
  function keysFor(test) {
834
1551
  return [
835
1552
  { kind: "playwright-id", value: test.id },
836
- { kind: "path-title", value: [fileOf2(test), ...titlesOf(test)].join("#") }
1553
+ { kind: "path-title", value: pathTitleOf(test) }
837
1554
  ];
838
1555
  }
839
- var METADATA_TYPE2 = "application/plune.metadata+json";
1556
+ var METADATA_TYPE3 = "application/plune.metadata+json";
840
1557
  var TOKEN = /@P([A-Za-z0-9_-]+)/;
841
1558
  function metadataOf(result) {
842
- const found = result.attachments.find((a) => a.contentType === METADATA_TYPE2);
1559
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
843
1560
  if (found === void 0) return void 0;
844
1561
  try {
845
1562
  const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync2(found.path, "utf8") : void 0;
@@ -848,12 +1565,32 @@ function metadataOf(result) {
848
1565
  return void 0;
849
1566
  }
850
1567
  }
851
- function statedIdOf(test, metadata) {
1568
+ function statedIdOf(test, metadata, mapped) {
852
1569
  const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
853
1570
  if (annotation !== void 0 && annotation !== "") return annotation;
854
1571
  const token = TOKEN.exec(test.title)?.[1];
855
1572
  if (token !== void 0) return token;
856
- 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 {};
857
1594
  }
858
1595
  var NOT_FAILED = /* @__PURE__ */ new Set(["passed", "skipped"]);
859
1596
  function textOf(error) {
@@ -875,22 +1612,28 @@ function attemptOf(test, result, ctx) {
875
1612
  status: result.status,
876
1613
  errors: result.errors.map((e) => ({ text: textOf(e), ...e.location !== void 0 ? { location: e.location } : {} })),
877
1614
  steps: declared(result.steps ?? []),
878
- attachments: result.attachments.map(({ name, contentType, path: path3 }) => ({
1615
+ attachments: result.attachments.map(({ name, contentType, path: path3, body }) => ({
879
1616
  name,
880
1617
  contentType,
881
- ...path3 !== void 0 ? { path: path3 } : {}
1618
+ ...path3 !== void 0 ? { path: path3 } : {},
1619
+ // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
1620
+ ...body !== void 0 ? { body } : {}
882
1621
  })),
883
1622
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
884
1623
  testFile: test.location.file,
885
1624
  ...ctx.repoRoot !== void 0 ? { repoRoot: ctx.repoRoot } : {}
886
1625
  };
887
1626
  }
888
- function pendingFrom(test, result, ctx) {
1627
+ function pendingFrom(test, result, ctx, ids = {}) {
889
1628
  const metadata = metadataOf(result);
890
- 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
+ );
891
1634
  const expected = test.expectedStatus;
892
1635
  const attempt = attemptOf(test, result, ctx);
893
- const errorContext = errorContextOf(attempt);
1636
+ const errorContext = errorContextFields(attempt);
894
1637
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
895
1638
  const files = filesOf(attempt);
896
1639
  const startedAt = result.startTime;
@@ -920,9 +1663,9 @@ function pendingFrom(test, result, ctx) {
920
1663
  retry: result.retry,
921
1664
  worker: String(result.workerIndex)
922
1665
  },
923
- ...errorContext !== "" ? { errorContext } : {},
1666
+ ...errorContext,
924
1667
  ...failure !== void 0 ? { failure } : {},
925
- // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
1668
+ // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
926
1669
  ...files.length > 0 ? { files } : {}
927
1670
  };
928
1671
  }
@@ -938,6 +1681,8 @@ var PluneReporter = class {
938
1681
  /** Kept whole: `metadata.ci` is written into it after `onConfigure`, so it is read at the run's opening. */
939
1682
  config = null;
940
1683
  context = {};
1684
+ /** The mapfile, read on the first result so a run that reports nothing never touches the disk. */
1685
+ ids = null;
941
1686
  constructor(options = {}) {
942
1687
  this.options = options;
943
1688
  }
@@ -990,7 +1735,10 @@ var PluneReporter = class {
990
1735
  onTestEnd(test, result) {
991
1736
  const session = this.open();
992
1737
  this.chain = this.chain.then(async () => {
993
- 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));
994
1742
  }).catch((err) => this.giveUp(err));
995
1743
  }
996
1744
  async onEnd(_result) {