@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.cjs CHANGED
@@ -34,25 +34,31 @@ __export(src_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(src_exports);
36
36
  var import_node_fs = require("fs");
37
+ var import_node_path = require("path");
37
38
  var import_node_util = require("util");
38
39
 
39
40
  // ../../dist/reporter-core.js
40
41
  var import_crypto = require("crypto");
41
42
  var import_fs = require("fs");
42
43
  var import_path = require("path");
44
+ var import_util = require("util");
43
45
  var import_fs2 = require("fs");
44
46
  var import_os = require("os");
45
47
  var import_path2 = require("path");
48
+ var import_fs3 = require("fs");
49
+ var import_stream = require("stream");
46
50
  var import_http = require("http");
47
51
  var import_https = require("https");
48
52
  var path = __toESM(require("path"), 1);
49
- var fs = __toESM(require("fs"), 1);
50
- var path2 = __toESM(require("path"), 1);
51
- var import_crypto2 = require("crypto");
52
- var import_fs3 = require("fs");
53
+ var import_fs4 = require("fs");
53
54
  var import_os2 = require("os");
54
55
  var import_path3 = require("path");
55
- var import_util = require("util");
56
+ var import_util2 = require("util");
57
+ var import_crypto2 = require("crypto");
58
+ var import_fs5 = require("fs");
59
+ var fs = __toESM(require("fs"), 1);
60
+ var path2 = __toESM(require("path"), 1);
61
+ var import_crypto3 = require("crypto");
56
62
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
57
63
  function resolveApiUrl(explicit) {
58
64
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -72,20 +78,32 @@ function loadToken() {
72
78
  return null;
73
79
  }
74
80
  }
75
- var RETRY_DELAYS_MS = [300, 900];
81
+ var BACKOFF_BASE_MS = 300;
82
+ var BACKOFF_CAP_MS = 1e4;
83
+ var DEFAULT_RETRIES = 2;
84
+ var RETRY_AFTER_CAP_MS = 6e4;
85
+ function parseRetryAfter(raw, now = Date.now()) {
86
+ const text = raw?.trim();
87
+ if (text === void 0 || text === "") return null;
88
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : (Date.parse(text) - now) / 1e3;
89
+ if (!Number.isFinite(seconds)) return null;
90
+ return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
91
+ }
92
+ var POOLS = { "http:": new import_http.Agent({ keepAlive: true }), "https:": new import_https.Agent({ keepAlive: true }) };
76
93
  var IDLE_MS = 3e5;
77
94
  function nodeTransport(url, init, idleMs = IDLE_MS) {
78
- return new Promise((resolve2, reject) => {
95
+ return new Promise((resolve22, reject) => {
79
96
  const target = new URL(url);
80
97
  const send = target.protocol === "https:" ? import_https.request : import_http.request;
81
- const req = send(target, { method: init.method, headers: init.headers }, (res) => {
98
+ const agent = POOLS[target.protocol === "https:" ? "https:" : "http:"];
99
+ const req = send(target, { method: init.method, headers: init.headers, agent }, (res) => {
82
100
  const chunks = [];
83
101
  res.on("data", (chunk2) => chunks.push(chunk2));
84
102
  res.on("error", reject);
85
103
  res.on("end", () => {
86
104
  const status = res.statusCode ?? 0;
87
105
  const text = Buffer.concat(chunks).toString("utf8");
88
- resolve2({
106
+ resolve22({
89
107
  ok: status >= 200 && status <= 299,
90
108
  status,
91
109
  headers: {
@@ -103,20 +121,60 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
103
121
  req.end(init.body);
104
122
  });
105
123
  }
124
+ var withoutLength = (headers) => Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-length"));
125
+ function nodePut(url, headers, source, idleMs) {
126
+ return new Promise((resolve22, reject) => {
127
+ const target = new URL(url);
128
+ const send = target.protocol === "https:" ? import_https.request : import_http.request;
129
+ const length = "body" in source ? source.body.length : source.size;
130
+ let answered;
131
+ const settle = (err) => answered !== void 0 ? resolve22(answered) : reject(err);
132
+ const req = send(
133
+ target,
134
+ { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
135
+ (res) => {
136
+ const retry = res.headers["retry-after"];
137
+ answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
138
+ res.on("error", settle);
139
+ res.on("close", () => {
140
+ resolve22(answered);
141
+ req.destroy();
142
+ });
143
+ res.resume();
144
+ }
145
+ );
146
+ req.setTimeout(idleMs, () => req.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
147
+ req.on("error", settle);
148
+ if ("body" in source) req.end(source.body);
149
+ else (0, import_stream.pipeline)((0, import_fs3.createReadStream)(source.path), req, (err) => err ? settle(err) : void 0);
150
+ });
151
+ }
152
+ var codeOfError = (err) => {
153
+ const code = err?.code;
154
+ return typeof code === "string" && /^[A-Z0-9_]{2,40}$/.test(code) ? code : "network";
155
+ };
106
156
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
107
157
  async function detailOf(res) {
108
158
  try {
109
159
  const body = await res.json();
110
- return typeof body.error === "string" ? body.error : "";
160
+ const q = body.quota;
161
+ return {
162
+ ...typeof body.shardsExpected === "number" && Number.isInteger(body.shardsExpected) ? { shardsExpected: body.shardsExpected } : {},
163
+ detail: typeof body.error === "string" ? body.error : "",
164
+ ...typeof q === "object" && q !== null && !Array.isArray(q) ? { quota: q } : {},
165
+ ...typeof body.code === "string" && /^[a-z0-9_]{1,60}$/.test(body.code) ? { code: body.code } : {}
166
+ };
111
167
  } catch {
112
- return "";
168
+ return { detail: "" };
113
169
  }
114
170
  }
115
- function retryAfterMs(res) {
116
- const raw = res.headers.get("retry-after");
117
- if (raw === null) return null;
118
- const seconds = Number(raw.trim());
119
- return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : null;
171
+ function describeQuota(q) {
172
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
173
+ const kind = typeof q["kind"] === "string" ? q["kind"].slice(0, 60) : "limit";
174
+ const [used, limit] = [num(q["used"]), num(q["limit"])];
175
+ const parts = [used !== void 0 && limit !== void 0 ? `${kind}: ${used} of ${limit} used` : kind];
176
+ if (typeof q["resetsAt"] === "string" && q["resetsAt"] !== "") parts.push(`resets ${q["resetsAt"].slice(0, 40)}`);
177
+ return parts.join(", ");
120
178
  }
121
179
  function classify(status) {
122
180
  if (status === 401 || status === 403) return "auth";
@@ -128,15 +186,34 @@ function classify(status) {
128
186
  function createClient(opts) {
129
187
  const doFetch = opts.fetchImpl ?? nodeTransport;
130
188
  const wait = opts.wait ?? sleep;
189
+ const uploadRetries = opts.uploadRetries === void 0 ? void 0 : Math.max(0, Math.floor(opts.uploadRetries));
190
+ const random = opts.random ?? Math.random;
191
+ const now = opts.now ?? Date.now;
192
+ let pausedUntil = 0;
193
+ const jittered = (ms) => Math.round(ms * (1 + random() * 0.5));
194
+ async function backOff(attempt, said) {
195
+ opts.onRetry?.();
196
+ const ms = jittered(said ?? Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_CAP_MS));
197
+ const until = now() + ms;
198
+ pausedUntil = Math.max(pausedUntil, until);
199
+ await wait(ms);
200
+ return until;
201
+ }
202
+ async function respectPause(mine) {
203
+ const left = pausedUntil - now();
204
+ if (pausedUntil > mine && left > 0) await wait(left + Math.round(random() * 250));
205
+ }
131
206
  const base = opts.apiUrl.replace(/\/+$/, "");
132
207
  const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
133
- async function send(method, path3, payload) {
208
+ async function send(method, path3, payload, retries = DEFAULT_RETRIES) {
134
209
  let last = {
135
210
  kind: "unavailable",
136
211
  status: null,
137
212
  detail: "no attempt was made"
138
213
  };
139
- for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {
214
+ let mine = 0;
215
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
216
+ await respectPause(mine);
140
217
  let res;
141
218
  try {
142
219
  res = await doFetch(`${base}${path3}`, {
@@ -149,7 +226,8 @@ function createClient(opts) {
149
226
  });
150
227
  } catch (err) {
151
228
  last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
152
- if (attempt < RETRY_DELAYS_MS.length) await wait(RETRY_DELAYS_MS[attempt]);
229
+ if (attempt >= Math.min(retries, DEFAULT_RETRIES)) break;
230
+ mine = await backOff(attempt, null);
153
231
  continue;
154
232
  }
155
233
  if (res.ok) {
@@ -160,23 +238,76 @@ function createClient(opts) {
160
238
  return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
161
239
  }
162
240
  }
163
- const detail = scrub(await detailOf(res));
241
+ const said = await detailOf(res);
164
242
  const kind = classify(res.status);
165
- last = { kind, status: res.status, detail };
243
+ last = { kind, status: res.status, detail: scrub(said.detail), ...said.code !== void 0 ? { code: said.code } : {}, ...said.shardsExpected !== void 0 ? { shardsExpected: said.shardsExpected } : {} };
166
244
  if (kind !== "unavailable") break;
167
- if (attempt < RETRY_DELAYS_MS.length) {
168
- await wait(retryAfterMs(res) ?? RETRY_DELAYS_MS[attempt]);
245
+ const said429 = parseRetryAfter(res.headers.get("retry-after"), now());
246
+ if (res.status === 429 && (said.quota !== void 0 || said429 === null)) {
247
+ last.kind = "invalid";
248
+ last.detail = `quota exceeded (${said.quota === void 0 ? "no Retry-After" : scrub(describeQuota(said.quota))})`;
249
+ if (said.detail) last.detail += ` \u2014 ${scrub(said.detail)}`;
250
+ break;
169
251
  }
252
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
253
+ mine = await backOff(attempt, said429);
170
254
  }
171
255
  return { ok: false, ...last };
172
256
  }
173
257
  return {
174
- post: (path3, body) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }),
175
- upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }),
176
- del: (path3) => send("DELETE", path3)
258
+ post: (path3, body, retries) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }, retries),
259
+ upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
260
+ del: (path3) => send("DELETE", path3),
261
+ get: (path3) => send("GET", path3),
262
+ async put(url, headers, source) {
263
+ const putRetries = uploadRetries ?? 3;
264
+ let last = { ok: false, status: null, code: "network" };
265
+ let mine = 0;
266
+ for (let attempt = 0; attempt <= putRetries; attempt += 1) {
267
+ await respectPause(mine);
268
+ try {
269
+ let status;
270
+ let retryAfter;
271
+ if (opts.fetchImpl === void 0) ({ status, retryAfter } = await nodePut(url, headers, source, IDLE_MS));
272
+ else {
273
+ const body = "body" in source ? source.body : await (0, import_fs3.openAsBlob)(source.path);
274
+ const res = await opts.fetchImpl(url, { method: "PUT", headers: withoutLength(headers), body });
275
+ await res.arrayBuffer().catch(() => void 0);
276
+ status = res.status;
277
+ retryAfter = res.headers.get("retry-after");
278
+ }
279
+ if (status >= 200 && status <= 299) return { ok: true };
280
+ last = { ok: false, status, code: `bucket_${status}` };
281
+ if (status < 500 && status !== 429) return last;
282
+ const said = parseRetryAfter(retryAfter, now());
283
+ if (attempt >= (said === null ? Math.min(putRetries, 3) : putRetries)) return last;
284
+ mine = await backOff(attempt, said);
285
+ continue;
286
+ } catch (err) {
287
+ last = { ok: false, status: null, code: codeOfError(err) };
288
+ }
289
+ if (attempt >= Math.min(putRetries, 3)) return last;
290
+ mine = await backOff(attempt, null);
291
+ }
292
+ return last;
293
+ }
177
294
  };
178
295
  }
179
296
  var UNSUPPORTED_VARS = ["PLUNE_GROUP"];
297
+ var SHARDS_MAX = 1e3;
298
+ function shardOf(env) {
299
+ const raw = value(env, "PLUNE_SHARD");
300
+ if (raw === void 0) return {};
301
+ const m = /^(\d{1,4})\/(\d{1,4})$/.exec(raw);
302
+ const [k, n] = m ? [Number(m[1]), Number(m[2])] : [0, 0];
303
+ if (k >= 1 && k <= n && n <= SHARDS_MAX) return { shard: { index: k, total: n } };
304
+ return {
305
+ 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.`
306
+ };
307
+ }
308
+ var UPLOAD_CONCURRENCY = { min: 1, max: 32, default: 16 };
309
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
310
+ var IMPORT_TIMEOUT = { min: 0, max: 86400, default: 600 };
180
311
  function value(env, name) {
181
312
  const raw = env[name]?.trim();
182
313
  return raw === void 0 || raw === "" ? void 0 : raw;
@@ -191,6 +322,14 @@ function count(env, name) {
191
322
  const n = Number(raw);
192
323
  return Number.isInteger(n) && n > 0 ? n : void 0;
193
324
  }
325
+ function bounded(env, name, range, warnings) {
326
+ const raw = value(env, name);
327
+ if (raw === void 0) return void 0;
328
+ const n = Number(raw);
329
+ if (/^\d+$/.test(raw) && n >= range.min && n <= range.max) return n;
330
+ warnings.push(`${name}=${JSON.stringify(raw.slice(0, 40))} is not a whole number from ${range.min} to ${range.max} \u2014 using ${range.default}.`);
331
+ return void 0;
332
+ }
194
333
  function list(env, name) {
195
334
  const raw = value(env, name);
196
335
  if (raw === void 0) return void 0;
@@ -203,11 +342,16 @@ function readEnv(env = process.env) {
203
342
  const apiUrl = value(env, "PLUNE_API_URL");
204
343
  const fallbackPath = value(env, "PLUNE_FALLBACK");
205
344
  const batchSize = count(env, "PLUNE_BATCH_SIZE");
345
+ const warnings = [];
346
+ const uploadConcurrency = bounded(env, "PLUNE_UPLOAD_CONCURRENCY", UPLOAD_CONCURRENCY, warnings);
347
+ const uploadRetries = bounded(env, "PLUNE_UPLOAD_RETRIES", UPLOAD_RETRIES, warnings);
348
+ const importTimeout = bounded(env, "PLUNE_IMPORT_TIMEOUT", IMPORT_TIMEOUT, warnings);
206
349
  const title = value(env, "PLUNE_RUN_TITLE");
207
350
  const environment = value(env, "PLUNE_ENV");
208
351
  const labels = list(env, "PLUNE_LABELS");
209
352
  const offerDiscovered = flag(env, "PLUNE_CREATE");
210
353
  const full = flag(env, "PLUNE_FULL_RUN");
354
+ const { shard, error: shardError } = shardOf(env);
211
355
  return {
212
356
  config: {
213
357
  ...externalKey !== void 0 ? { externalKey } : {},
@@ -215,6 +359,8 @@ function readEnv(env = process.env) {
215
359
  ...apiUrl !== void 0 ? { apiUrl } : {},
216
360
  ...fallbackPath !== void 0 ? { fallbackPath } : {},
217
361
  ...batchSize !== void 0 ? { batchSize } : {},
362
+ ...uploadConcurrency !== void 0 ? { uploadConcurrency } : {},
363
+ ...uploadRetries !== void 0 ? { uploadRetries } : {},
218
364
  ...title !== void 0 ? { title } : {},
219
365
  ...environment !== void 0 ? { environment } : {},
220
366
  ...labels !== void 0 ? { labels } : {},
@@ -226,8 +372,14 @@ function readEnv(env = process.env) {
226
372
  // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
227
373
  // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
228
374
  // way this process must not be the one to call it finished.
229
- keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED"),
230
- ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0)
375
+ // `PLUNE_SHARD` implies it: the run is joined by the shared key and this process does not close it
376
+ // by itself; `leaveOpen` reports the shard instead.
377
+ keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED") || shard !== void 0 || shardError !== void 0,
378
+ ...shard !== void 0 ? { shard } : {},
379
+ ...shardError !== void 0 ? { shardError } : {},
380
+ ...importTimeout !== void 0 ? { importTimeout } : {},
381
+ ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0),
382
+ warnings
231
383
  };
232
384
  }
233
385
  function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cwd = process.cwd()) {
@@ -258,6 +410,157 @@ function ciCommit(reported, env = process.env) {
258
410
  ...branch !== void 0 ? { branch } : {}
259
411
  };
260
412
  }
413
+ function failureOf(attempt, home = (0, import_os2.homedir)()) {
414
+ const error = chosen(attempt);
415
+ const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
416
+ const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
417
+ const steps = chainOf(attempt.steps);
418
+ const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
419
+ 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 !== "");
420
+ const ciUrl = webLink(attempt.buildHref);
421
+ const failure = {
422
+ ...headline !== void 0 ? { headline } : {},
423
+ ...steps.length > 0 ? { steps } : {},
424
+ ...location !== void 0 ? { location } : {},
425
+ ...artifacts.length > 0 ? { artifacts } : {},
426
+ ...ciUrl !== void 0 ? { ciUrl } : {}
427
+ };
428
+ return Object.keys(failure).length === 0 ? void 0 : failure;
429
+ }
430
+ function repoRootOf(dir, stopAt) {
431
+ for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
432
+ if ((0, import_fs4.existsSync)((0, import_path3.join)(here, ".git"))) return here;
433
+ if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
434
+ }
435
+ }
436
+ function errorContextFields(attempt, home = (0, import_os2.homedir)()) {
437
+ const { text, omitted: omitted2 } = cutErrorContext(attempt, home);
438
+ return {
439
+ ...text !== "" ? { errorContext: text } : {},
440
+ ...omitted2 > 0 ? { errorContextOmitted: omitted2 } : {}
441
+ };
442
+ }
443
+ function cutErrorContext(attempt, home) {
444
+ const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
445
+ return cut(machineless(text, attempt.repoRoot, home));
446
+ }
447
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
448
+ var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
449
+ var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
450
+ var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
451
+ function filesOf(attempt) {
452
+ return attempt.attachments.filter((a) => a.path !== void 0 || a.body !== void 0 && isTextType(a.contentType));
453
+ }
454
+ function machineless(raw, repoRoot, home) {
455
+ let text = (0, import_util2.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
456
+ const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
457
+ if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
458
+ const own = pathIn(home);
459
+ if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
460
+ if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
461
+ return text;
462
+ }
463
+ var PATH_START = "(?<![\\w.~%/\\\\-])";
464
+ var TEXT_LIMIT = 524288;
465
+ var HEADLINE_LIMIT = 8 * 1024;
466
+ var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
467
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
468
+ function pathIn(path3) {
469
+ const parts = path3.split(/[\\/]+/);
470
+ while (parts.length > 1 && parts.at(-1) === "") parts.pop();
471
+ if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
472
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
473
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
474
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
475
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
476
+ }
477
+ var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
478
+ function cut(text) {
479
+ if (jsonBytes(text) <= TEXT_LIMIT) return { text, omitted: 0 };
480
+ const lines = text.split("\n");
481
+ const size = lines.map((line) => jsonBytes(line) + 2);
482
+ const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
483
+ let used = 0;
484
+ let head = 0;
485
+ let tail = lines.length;
486
+ while (head < tail && used + size[head] <= budget / 2) used += size[head++];
487
+ while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
488
+ const kept = [...lines.slice(0, head), ...lines.slice(tail)].join("\n");
489
+ return { text: [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n"), omitted: text.length - kept.length };
490
+ }
491
+ var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
492
+ var METADATA_TYPE = "application/plune.metadata+json";
493
+ var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
494
+ var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
495
+ var FRAME_MAX = 8192;
496
+ var firstLine = (text) => (0, import_util2.stripVTControlCharacters)(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
497
+ function chosen({ status, errors }) {
498
+ if (status === "timedOut") {
499
+ const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
500
+ if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
501
+ }
502
+ return errors[0];
503
+ }
504
+ function chainOf(steps) {
505
+ const chain = [];
506
+ for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
507
+ chain.push(failed.title);
508
+ }
509
+ return chain;
510
+ }
511
+ function placeOf(error, testFile) {
512
+ const own = normal(testFile);
513
+ let first;
514
+ for (const line of (0, import_util2.stripVTControlCharacters)(error.text).split("\n")) {
515
+ if (line.length > FRAME_MAX) continue;
516
+ const frame = FRAME.exec(line);
517
+ if (frame === null) continue;
518
+ const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
519
+ if (normal(place.file) === own) return place;
520
+ if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
521
+ }
522
+ return error.location ?? first;
523
+ }
524
+ function fileOf(raw) {
525
+ if (!raw.startsWith("file://")) return raw;
526
+ let path3 = raw.slice("file://".length);
527
+ try {
528
+ path3 = decodeURIComponent(path3);
529
+ } catch {
530
+ }
531
+ return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
532
+ }
533
+ var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
534
+ function fromRoot(place, root) {
535
+ if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
536
+ const base = normal(root).replace(/\/+$/, "");
537
+ const file = normal(place.file);
538
+ if (!file.startsWith(`${base}/`)) return void 0;
539
+ const relative = file.slice(base.length + 1);
540
+ if (!REPO_RELATIVE.test(relative)) return void 0;
541
+ const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
542
+ return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
543
+ }
544
+ function webLink(href) {
545
+ return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
546
+ }
547
+ var FILES_BATCH_MAX = 100;
548
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
549
+ var BATCH_PIPELINES = 2;
550
+ async function sha256File(path3) {
551
+ const hash = (0, import_crypto2.createHash)("sha256");
552
+ for await (const part of (0, import_fs5.createReadStream)(path3)) hash.update(part);
553
+ return hash.digest("hex");
554
+ }
555
+ var sha256Bytes = (bytes) => (0, import_crypto2.createHash)("sha256").update(bytes).digest("hex");
556
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
557
+ "bucket_unreachable",
558
+ "not_connected",
559
+ "platform_not_configured",
560
+ "upload_expired",
561
+ "file_mismatch",
562
+ "file_missing"
563
+ ]);
261
564
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
262
565
  function appendBatch(file, batch) {
263
566
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -275,7 +578,8 @@ function appendBatch(file, batch) {
275
578
  var RESOLVE_CHUNK = 500;
276
579
  var BATCH_MAX = 500;
277
580
  var DISCOVER_MAX = 500;
278
- var BATCH_DEFAULT = 100;
581
+ var BATCH_DEFAULT = 500;
582
+ var SEND_CONCURRENCY = 4;
279
583
  var EXPECTED_MAX = 1e4;
280
584
  var KEY_MAX = 1024;
281
585
  var TITLE_MAX = 300;
@@ -283,17 +587,20 @@ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
283
587
  var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
284
588
  var SCREENSHOT_BYTES = 2 * 1024 * 1024;
285
589
  var SCREENSHOTS_PER_RESULT = 20;
590
+ var TEXT_BYTES = 512 * 1024;
591
+ var TEXTS_PER_RESULT = 10;
592
+ var UTF8 = new import_util.TextDecoder("utf-8", { fatal: true });
286
593
  var TYPE_BY_EXTENSION = {
287
594
  ".png": "image/png",
288
595
  ".jpg": "image/jpeg",
289
596
  ".jpeg": "image/jpeg",
290
597
  ".webp": "image/webp"
291
598
  };
292
- var UPLOADS_AT_ONCE = 4;
599
+ var METADATA_TYPE2 = "application/plune.metadata+json";
293
600
  var NAME_MAX = 200;
294
601
  function nameOf(file) {
295
- const own = file.name.split(/[\\/]/).pop()?.trim() || (0, import_path.basename)(file.path);
296
- const fileExt = (0, import_path.extname)(file.path);
602
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_path.basename)(file.path));
603
+ const fileExt = file.path === void 0 ? "" : (0, import_path.extname)(file.path);
297
604
  const ownExt = (0, import_path.extname)(own);
298
605
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
299
606
  const ext = typed ? ownExt : fileExt;
@@ -309,8 +616,57 @@ var SKIPPED = {
309
616
  type: "Plune takes PNG, JPEG and WebP",
310
617
  limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
311
618
  missing: "the file cannot be read on this machine",
312
- size: "Plune takes a file of at most 2 MB"
619
+ size: "Plune takes a file of at most 2 MB",
620
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
621
+ textSize: "Plune takes a text file of at most 512 KiB",
622
+ empty: "the file is empty",
623
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
624
+ encoding: "Plune takes UTF-8 text only",
625
+ noStorage: "no storage bucket is connected to this project"
313
626
  };
627
+ var BUCKET_FOUND = "plune: storage bucket found for this project \u2014 screenshots, text, trace and video go straight to it over short-lived links.";
628
+ var KINDS = {
629
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
630
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
631
+ // 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.
632
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
633
+ };
634
+ function kindOf(type) {
635
+ if (type.startsWith("image/")) return "screenshot";
636
+ return TEXT_TYPES.has(type) ? "text" : "file";
637
+ }
638
+ var codeOf = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
639
+ function linkOf(item) {
640
+ const link = item;
641
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
642
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
643
+ return { id: link.id, url: link.url, headers };
644
+ }
645
+ function textTypeOf(contentType, type) {
646
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
647
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
648
+ }
649
+ function textRefusal(bytes) {
650
+ if (bytes.length > TEXT_BYTES) return "textSize";
651
+ if (bytes.length === 0) return "empty";
652
+ if (bytes.includes(0)) return "binary";
653
+ try {
654
+ UTF8.decode(bytes);
655
+ } catch {
656
+ return "encoding";
657
+ }
658
+ return void 0;
659
+ }
660
+ function onDisk(result) {
661
+ if (!("files" in result) || result.files === void 0) return result;
662
+ const { files, ...rest } = result;
663
+ const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
664
+ return kept.length === 0 ? rest : { ...rest, files: kept };
665
+ }
666
+ function tally(counts, noun) {
667
+ if (counts.uploaded + counts.skipped + counts.failed === 0) return void 0;
668
+ return `${counts.uploaded} ${noun}(s) uploaded` + (counts.skipped > 0 ? `, ${counts.skipped} skipped` : "") + (counts.failed > 0 ? `, ${counts.failed} failed to upload` : "");
669
+ }
314
670
  function boundKey(key) {
315
671
  if (key.value.length <= KEY_MAX) return key;
316
672
  const digest = (0, import_crypto.createHash)("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -361,6 +717,7 @@ function warnIfDropped(sent, run, log) {
361
717
  }
362
718
  async function startRun(passed, declared2) {
363
719
  const env = readEnv();
720
+ if (env.shardError !== void 0) throw new Error(env.shardError);
364
721
  const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
365
722
  const cfg = { ...env.config, ...stated };
366
723
  const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
@@ -371,9 +728,18 @@ async function startRun(passed, declared2) {
371
728
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
372
729
  const offerDiscovered = cfg.offerDiscovered ?? false;
373
730
  const token = cfg.token ?? loadToken() ?? "";
731
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
732
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
733
+ let retried = 0;
734
+ let uploadMs = 0;
735
+ let requests = 0;
736
+ let existed = 0;
737
+ let batchMissing = false;
374
738
  const client = createClient({
375
739
  apiUrl: resolveApiUrl(cfg.apiUrl),
376
740
  token,
741
+ uploadRetries,
742
+ onRetry: () => void (retried += 1),
377
743
  ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
378
744
  });
379
745
  const stats = {
@@ -386,17 +752,29 @@ async function startRun(passed, declared2) {
386
752
  created: 0,
387
753
  unoffered: 0,
388
754
  deferred: 0,
389
- screenshots: { uploaded: 0, skipped: 0, failed: 0 }
755
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
756
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
757
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
390
758
  };
391
759
  const resolved = /* @__PURE__ */ new Map();
392
760
  let buffer = [];
393
761
  const discoveries = /* @__PURE__ */ new Map();
762
+ const held = /* @__PURE__ */ new Map();
763
+ let createdWithResult = 0;
764
+ let createdUndelivered = 0;
394
765
  let runId = null;
395
766
  let joined = false;
396
767
  let offline = token === "";
397
768
  let done = false;
398
769
  const shortened = /* @__PURE__ */ new Set();
399
770
  const skipsSaid = /* @__PURE__ */ new Set();
771
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
772
+ let bucketSeen = false;
773
+ let noStorage = 0;
774
+ let uploadsMissing = false;
775
+ const failedSaid = /* @__PURE__ */ new Set();
776
+ const codesSaid = /* @__PURE__ */ new Set();
777
+ const rooms = /* @__PURE__ */ new Map();
400
778
  function bound(keys) {
401
779
  return keys.map((key) => {
402
780
  const fit = boundKey(key);
@@ -404,7 +782,7 @@ async function startRun(passed, declared2) {
404
782
  shortened.add(key.value);
405
783
  if (shortened.size === 1) {
406
784
  log(
407
- `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.`
785
+ `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.`
408
786
  );
409
787
  }
410
788
  }
@@ -415,6 +793,7 @@ async function startRun(passed, declared2) {
415
793
  if (offline) {
416
794
  log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
417
795
  }
796
+ for (const warning of env.warnings) log(`plune: ${warning}`);
418
797
  if (env.ignored.length > 0) {
419
798
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
420
799
  }
@@ -424,7 +803,7 @@ async function startRun(passed, declared2) {
424
803
  externalKey,
425
804
  session: sessionMarker,
426
805
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
427
- results
806
+ results: results.map(onDisk)
428
807
  });
429
808
  stats.deferred += results.length;
430
809
  }
@@ -467,7 +846,7 @@ async function startRun(passed, declared2) {
467
846
  ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
468
847
  ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
469
848
  };
470
- const start = await client.post("/v1/runs", {
849
+ const request = {
471
850
  schemaVersion: 2,
472
851
  kind: cfg.kind ?? "automated",
473
852
  ...externalKey !== null ? { externalKey } : {},
@@ -478,7 +857,14 @@ async function startRun(passed, declared2) {
478
857
  // a person will miss, and a deployment older than the field must not be nagged on every run.
479
858
  title: defaultRunTitle(),
480
859
  ...described
481
- });
860
+ };
861
+ let start = await client.post("/v1/runs", request);
862
+ if (!start.ok && start.status === 413 && configuration !== void 0) {
863
+ log(
864
+ `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.`
865
+ );
866
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
867
+ }
482
868
  if (start.ok && typeof start.body?.run?.id === "string") {
483
869
  runId = start.body.run.id;
484
870
  joined = start.status === 200;
@@ -511,6 +897,7 @@ async function startRun(passed, declared2) {
511
897
  specRef: result.specRef,
512
898
  rawStatus: result.rawStatus
513
899
  });
900
+ held.set(result.keys[0].value, result);
514
901
  }
515
902
  async function offer() {
516
903
  if (discoveries.size === 0 || offline || runId === null) return;
@@ -529,64 +916,453 @@ async function startRun(passed, declared2) {
529
916
  return;
530
917
  }
531
918
  stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
532
- stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
919
+ const made = out.body.results.filter((r) => r?.outcome === "created");
920
+ stats.created += made.length;
921
+ const submissions = [];
922
+ const filesByKey = /* @__PURE__ */ new Map();
923
+ for (const r of made) {
924
+ const pending = typeof r.id === "string" && r.id !== "" ? held.get(r.key?.value) : void 0;
925
+ if (pending === void 0) continue;
926
+ held.delete(r.key.value);
927
+ const { keys: _keys, files, ...rest } = pending;
928
+ submissions.push({ ...rest, testCaseId: r.id });
929
+ if (files !== void 0) filesByKey.set(pending.resultKey, files);
930
+ }
931
+ if (submissions.length > 0) {
932
+ const before = stats.deferred;
933
+ await send(submissions, filesByKey);
934
+ createdWithResult += submissions.length;
935
+ createdUndelivered += stats.deferred - before;
936
+ }
937
+ }
938
+ }
939
+ function skip(kind, name, why) {
940
+ countsOf(kind).skipped += 1;
941
+ if (why === "noStorage") noStorage += 1;
942
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
943
+ if (skipsSaid.has(said)) return;
944
+ skipsSaid.add(said);
945
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
946
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
947
+ }
948
+ function ask(job, size) {
949
+ requests += 1;
950
+ return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
951
+ files: [{ name: job.name, contentType: job.type, size }]
952
+ }, uploadRetries);
953
+ }
954
+ function failed(job, why) {
955
+ countsOf(job.kind).failed += 1;
956
+ if (!failedSaid.has(job.kind)) {
957
+ failedSaid.add(job.kind);
958
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
533
959
  }
534
960
  }
535
- function skip(name, why) {
536
- stats.screenshots.skipped += 1;
537
- if (skipsSaid.has(why)) return;
538
- skipsSaid.add(why);
539
- log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
961
+ function failedToBucket(job, code) {
962
+ countsOf(job.kind).failed += 1;
963
+ if (codesSaid.has(code)) return;
964
+ codesSaid.add(code);
965
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
540
966
  }
541
- async function uploadOne(shot) {
967
+ function refusedHere(job, size) {
968
+ if (job.kind === "screenshot") {
969
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
970
+ if (size > SCREENSHOT_BYTES) return "size";
971
+ }
972
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
973
+ return void 0;
974
+ }
975
+ async function uploadDirect(job, size) {
976
+ const { kind } = job;
977
+ if (kind === "file") return skip(kind, job.name, "noStorage");
978
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
979
+ if (size > ceiling) return skip(kind, job.name, tooBig);
542
980
  let bytes;
543
- try {
544
- if ((await import_fs.promises.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
545
- bytes = await import_fs.promises.readFile(shot.path);
546
- } catch {
547
- return skip(shot.name, "missing");
981
+ if (job.body !== void 0) bytes = job.body;
982
+ else {
983
+ try {
984
+ bytes = await import_fs.promises.readFile(job.path);
985
+ } catch {
986
+ return skip(kind, job.name, "missing");
987
+ }
548
988
  }
989
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
990
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
991
+ requests += 1;
549
992
  const out = await client.upload(
550
- `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
993
+ `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
551
994
  bytes,
552
- shot.type
995
+ job.type
996
+ );
997
+ if (out.ok) countsOf(kind).uploaded += 1;
998
+ else failed(job, out.detail || out.kind);
999
+ }
1000
+ async function uploadToBucket(job, size, first) {
1001
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
1002
+ let link = first;
1003
+ for (let renewed = false; ; ) {
1004
+ const put = await client.put(link.url, link.headers, source);
1005
+ if (put.ok) break;
1006
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
1007
+ renewed = true;
1008
+ const again = await ask(job, size);
1009
+ if (!again.ok) return failedToBucket(job, codeOf(again));
1010
+ const fresh = linkOf(again.body?.files?.[0]);
1011
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
1012
+ link = fresh;
1013
+ }
1014
+ requests += 1;
1015
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1016
+ if (!done2.ok) return failedToBucket(job, codeOf(done2));
1017
+ countsOf(job.kind).uploaded += 1;
1018
+ }
1019
+ let free = uploadsAtOnce;
1020
+ const waiting = [];
1021
+ async function gated(work) {
1022
+ if (free === 0) await new Promise((resolve22) => waiting.push(resolve22));
1023
+ else free -= 1;
1024
+ try {
1025
+ return await work();
1026
+ } finally {
1027
+ const next = waiting.shift();
1028
+ if (next !== void 0) next();
1029
+ else free += 1;
1030
+ }
1031
+ }
1032
+ async function plan(job) {
1033
+ const { kind } = job;
1034
+ let size;
1035
+ if (job.body !== void 0) size = job.body.length;
1036
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
1037
+ else {
1038
+ try {
1039
+ size = (await import_fs.promises.stat(job.path)).size;
1040
+ } catch {
1041
+ return void skip(kind, job.name, "missing");
1042
+ }
1043
+ }
1044
+ if (size === 0) return void skip(kind, job.name, "empty");
1045
+ const direct = () => {
1046
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
1047
+ const roomKey = `${job.id}/${kind}`;
1048
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
1049
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
1050
+ rooms.set(roomKey, left - 1);
1051
+ return () => uploadDirect(job, size);
1052
+ };
1053
+ if (uploadsMissing) return direct();
1054
+ const out = await gated(() => ask(job, size));
1055
+ if (!out.ok) {
1056
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
1057
+ uploadsMissing = true;
1058
+ return direct();
1059
+ }
1060
+ if (out.code !== void 0) failedToBucket(job, out.code);
1061
+ else failed(job, out.detail || out.kind);
1062
+ return void 0;
1063
+ }
1064
+ const item = out.body?.files?.[0];
1065
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
1066
+ if (item?.direct === true) return direct();
1067
+ const link = linkOf(item);
1068
+ if (link === void 0) return void failed(job, "bad_answer");
1069
+ if (!bucketSeen) {
1070
+ bucketSeen = true;
1071
+ log(BUCKET_FOUND);
1072
+ }
1073
+ return () => uploadToBucket(job, size, link);
1074
+ }
1075
+ async function uploadEach(jobs) {
1076
+ const byResult = /* @__PURE__ */ new Map();
1077
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
1078
+ await Promise.all(
1079
+ [...byResult.values()].map(async (group) => {
1080
+ const work = [];
1081
+ for (const job of group) {
1082
+ const act = await plan(job);
1083
+ if (act !== void 0) work.push(gated(act));
1084
+ }
1085
+ await Promise.all(work);
1086
+ })
553
1087
  );
554
- if (out.ok) {
555
- stats.screenshots.uploaded += 1;
1088
+ }
1089
+ async function measure(job) {
1090
+ let size;
1091
+ if (job.body !== void 0) size = job.body.length;
1092
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
1093
+ else {
1094
+ try {
1095
+ size = (await import_fs.promises.stat(job.path)).size;
1096
+ } catch {
1097
+ return void skip(job.kind, job.name, "missing");
1098
+ }
1099
+ }
1100
+ if (size === 0) return void skip(job.kind, job.name, "empty");
1101
+ return size;
1102
+ }
1103
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
1104
+ function takeRoom(job) {
1105
+ if (job.kind === "file") {
1106
+ skip(job.kind, job.name, "noStorage");
1107
+ return false;
1108
+ }
1109
+ const roomKey = `${job.id}/${job.kind}`;
1110
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
1111
+ if (left === 0) {
1112
+ skip(job.kind, job.name, KINDS[job.kind].limit);
1113
+ return false;
1114
+ }
1115
+ rooms.set(roomKey, left - 1);
1116
+ return true;
1117
+ }
1118
+ function refusedItem(job, size, item) {
1119
+ const code = item.code ?? "refused";
1120
+ if (code === "duplicate") existed += 1;
1121
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
1122
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
1123
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
1124
+ else failed(job, code);
1125
+ }
1126
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
1127
+ async function batchOf(jobs) {
1128
+ if (batchMissing) return uploadEach(jobs);
1129
+ const sized = [];
1130
+ for (const job of jobs) {
1131
+ const size = await measure(job);
1132
+ if (size === void 0) continue;
1133
+ try {
1134
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
1135
+ } catch {
1136
+ skip(job.kind, job.name, "missing");
1137
+ }
1138
+ }
1139
+ if (sized.length === 0) return;
1140
+ const announced = await gated(() => {
1141
+ requests += 1;
1142
+ return client.post(
1143
+ "/v1/files/uploads-batch",
1144
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
1145
+ uploadRetries
1146
+ );
1147
+ });
1148
+ if (routeMissing(announced)) {
1149
+ batchMissing = true;
1150
+ return uploadEach(sized.map((s) => s.job));
1151
+ }
1152
+ const verdicts = announced.ok ? announced.body?.items : void 0;
1153
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
1154
+ for (const s of sized) {
1155
+ if (announced.ok) failed(s.job, "bad_answer");
1156
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
1157
+ else failed(s.job, announced.detail || announced.kind);
1158
+ }
556
1159
  return;
557
1160
  }
558
- stats.screenshots.failed += 1;
559
- if (stats.screenshots.failed === 1) {
560
- log(`plune: could not upload a screenshot (${out.detail || out.kind}) \u2014 its result is reported without it.`);
1161
+ const puts = [];
1162
+ const directs = [];
1163
+ sized.forEach((s, i) => {
1164
+ const v = verdicts[i] ?? {};
1165
+ if (v.status === "exists") existed += 1;
1166
+ else if (v.status === "direct") {
1167
+ if (takeRoom(s.job)) directs.push(s);
1168
+ } else if (v.status === "upload") {
1169
+ const link = linkOf(v);
1170
+ if (link === void 0) return failed(s.job, "bad_answer");
1171
+ if (!bucketSeen) {
1172
+ bucketSeen = true;
1173
+ log(BUCKET_FOUND);
1174
+ }
1175
+ puts.push({ s, link });
1176
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
1177
+ else failed(s.job, "bad_answer");
1178
+ });
1179
+ const toComplete = [];
1180
+ await Promise.all(
1181
+ puts.map(
1182
+ ({ s, link: first }) => gated(async () => {
1183
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
1184
+ let link = first;
1185
+ for (let renewed = false; ; ) {
1186
+ const put = await client.put(link.url, link.headers, source);
1187
+ if (put.ok) break;
1188
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
1189
+ renewed = true;
1190
+ requests += 1;
1191
+ const again = await client.post(
1192
+ "/v1/files/uploads-batch",
1193
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
1194
+ uploadRetries
1195
+ );
1196
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
1197
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf(again));
1198
+ link = fresh;
1199
+ }
1200
+ toComplete.push({ job: s.job, id: link.id });
1201
+ })
1202
+ )
1203
+ );
1204
+ await complete(toComplete);
1205
+ await sendDirect(directs);
1206
+ }
1207
+ async function complete(items) {
1208
+ for (let round = 0; items.length > 0; round += 1) {
1209
+ const out = await gated(() => {
1210
+ requests += 1;
1211
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
1212
+ });
1213
+ if (routeMissing(out)) {
1214
+ await Promise.all(
1215
+ items.map(
1216
+ (i) => gated(async () => {
1217
+ requests += 1;
1218
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
1219
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
1220
+ else failedToBucket(i.job, codeOf(one));
1221
+ })
1222
+ )
1223
+ );
1224
+ return;
1225
+ }
1226
+ const verdicts = out.ok ? out.body?.items : void 0;
1227
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
1228
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf(out));
1229
+ return;
1230
+ }
1231
+ const again = [];
1232
+ items.forEach((i, at) => {
1233
+ const v = verdicts[at] ?? {};
1234
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
1235
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
1236
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1237
+ });
1238
+ items = again;
1239
+ if (items.length > 0) {
1240
+ retried += items.length;
1241
+ await itemPause(round);
1242
+ }
1243
+ }
1244
+ }
1245
+ async function sendDirect(items) {
1246
+ const groups = [];
1247
+ let bytes = 0;
1248
+ for (const item of items) {
1249
+ const group = groups[groups.length - 1];
1250
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
1251
+ groups.push([item]);
1252
+ bytes = item.size;
1253
+ } else {
1254
+ group.push(item);
1255
+ bytes += item.size;
1256
+ }
1257
+ }
1258
+ for (const group of groups) {
1259
+ const body = [];
1260
+ const sent = [];
1261
+ for (const { job, size } of group) {
1262
+ const { kind } = job;
1263
+ if (size > KINDS[kind].bytes) {
1264
+ skip(kind, job.name, KINDS[kind].size);
1265
+ continue;
1266
+ }
1267
+ let data;
1268
+ try {
1269
+ data = job.body ?? await import_fs.promises.readFile(job.path);
1270
+ } catch {
1271
+ skip(kind, job.name, "missing");
1272
+ continue;
1273
+ }
1274
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
1275
+ if (refusal !== void 0) {
1276
+ skip(kind, job.name, refusal);
1277
+ continue;
1278
+ }
1279
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
1280
+ sent.push({ job, size });
1281
+ }
1282
+ if (body.length === 0) continue;
1283
+ const out = await gated(() => {
1284
+ requests += 1;
1285
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
1286
+ });
1287
+ if (routeMissing(out)) {
1288
+ batchMissing = true;
1289
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
1290
+ continue;
1291
+ }
1292
+ const verdicts = out.ok ? out.body?.items : void 0;
1293
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
1294
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
1295
+ continue;
1296
+ }
1297
+ sent.forEach(({ job }, i) => {
1298
+ const v = verdicts[i] ?? {};
1299
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
1300
+ else if (v.status === "exists") existed += 1;
1301
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1302
+ });
561
1303
  }
562
1304
  }
1305
+ async function uploadBatched(jobs) {
1306
+ const batches = chunk(jobs, FILES_BATCH_MAX);
1307
+ let next = 0;
1308
+ await Promise.all(
1309
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
1310
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
1311
+ })
1312
+ );
1313
+ }
563
1314
  async function upload(items, filesByKey) {
564
1315
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
565
- const shots = [];
1316
+ const jobs = [];
566
1317
  for (const item of items) {
567
1318
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
568
- let room = SCREENSHOTS_PER_RESULT;
569
1319
  for (const file of filesByKey.get(item.resultKey) ?? []) {
570
- const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()];
571
- if (!type?.startsWith("image/")) continue;
1320
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()]);
1321
+ if (type === void 0 || type === METADATA_TYPE2) continue;
1322
+ const kind = kindOf(type);
1323
+ if (kind !== "text" && file.path === void 0) continue;
572
1324
  const name = nameOf(file);
573
- if (file.name.startsWith("_")) skip(name, "hidden");
574
- else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
575
- else if (room === 0) skip(name, "limit");
1325
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
576
1326
  else {
577
- room -= 1;
578
- shots.push({ id: item.id, name, type, path: file.path });
1327
+ jobs.push({
1328
+ id: item.id,
1329
+ kind,
1330
+ name,
1331
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
1332
+ ...file.body !== void 0 ? { body: file.body } : {},
1333
+ ...file.path !== void 0 ? { path: file.path } : {}
1334
+ });
579
1335
  }
580
1336
  }
581
1337
  }
582
- let next = 0;
583
- await Promise.all(
584
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
585
- while (next < shots.length) await uploadOne(shots[next++]);
586
- })
587
- );
1338
+ const started = Date.now();
1339
+ if (batchMissing) await uploadEach(jobs);
1340
+ else await uploadBatched(jobs);
1341
+ uploadMs += Date.now() - started;
1342
+ }
1343
+ const sending = /* @__PURE__ */ new Set();
1344
+ let sendError;
1345
+ let answered = false;
1346
+ async function dispatch(work) {
1347
+ while (sending.size >= (answered ? SEND_CONCURRENCY : 1)) await Promise.race(sending);
1348
+ const task = work().catch((err) => {
1349
+ sendError ??= err;
1350
+ }).finally(() => sending.delete(task));
1351
+ sending.add(task);
1352
+ }
1353
+ async function settle() {
1354
+ while (sending.size > 0) await Promise.all([...sending]);
1355
+ if (sendError !== void 0) {
1356
+ const err = sendError;
1357
+ sendError = void 0;
1358
+ throw err;
1359
+ }
588
1360
  }
589
1361
  async function flush() {
1362
+ await flushBuffer();
1363
+ await settle();
1364
+ }
1365
+ async function flushBuffer() {
590
1366
  if (buffer.length === 0) return;
591
1367
  const pending = buffer;
592
1368
  buffer = [];
@@ -594,6 +1370,9 @@ async function startRun(passed, declared2) {
594
1370
  defer(pending);
595
1371
  return;
596
1372
  }
1373
+ await dispatch(() => deliver(pending));
1374
+ }
1375
+ async function deliver(pending) {
597
1376
  await resolveKeys(pending.flatMap((p) => p.keys));
598
1377
  const submissions = [];
599
1378
  const unanswered = [];
@@ -616,6 +1395,9 @@ async function startRun(passed, declared2) {
616
1395
  progress();
617
1396
  return;
618
1397
  }
1398
+ await send(submissions, filesByKey);
1399
+ }
1400
+ async function send(submissions, filesByKey) {
619
1401
  for (const part of packed(submissions)) {
620
1402
  if (offline) {
621
1403
  defer(part);
@@ -631,6 +1413,7 @@ async function startRun(passed, declared2) {
631
1413
  for (const k of told) stats[k] += counts[k];
632
1414
  progress();
633
1415
  await upload(out.ok ? out.body?.items : void 0, filesByKey);
1416
+ answered = true;
634
1417
  continue;
635
1418
  }
636
1419
  if (out.ok) {
@@ -659,20 +1442,40 @@ async function startRun(passed, declared2) {
659
1442
  if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
660
1443
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
661
1444
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
662
- if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
663
- const shots = stats.screenshots;
664
- if (shots.uploaded + shots.skipped + shots.failed > 0) {
1445
+ if (stats.created > 0) {
1446
+ const recorded = createdWithResult === stats.created && createdUndelivered === 0;
1447
+ parts.push(`${stats.created} added as cases (trusted source)${recorded ? " and their results recorded" : ""}`);
1448
+ }
1449
+ const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1450
+ const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1451
+ if (bucketSeen) {
1452
+ const other = sum("skipped") - noStorage;
665
1453
  parts.push(
666
- `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
1454
+ `${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` : "")
667
1455
  );
1456
+ } else {
1457
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
1458
+ if (said !== void 0) parts.push(said);
1459
+ }
1460
+ const other = stats.otherFiles;
1461
+ if (other.skipped > 0) parts.push(`${other.skipped} file(s) not stored (no bucket connected)`);
1462
+ if (other.failed > 0) parts.push(`${other.failed} file(s) failed to upload`);
668
1463
  }
669
1464
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
670
1465
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1466
+ const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1467
+ const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1468
+ if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1469
+ log(
1470
+ `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)`
1471
+ );
1472
+ }
671
1473
  log(`plune: ${parts.join(" \xB7 ")}`);
672
1474
  if (stats.deferred > 0 && process.env["GITHUB_ACTIONS"] === "true") {
673
1475
  log(`::warning::${stats.deferred} result(s) were not delivered to Plune \u2014 see the reporting step's log.`);
674
1476
  }
675
1477
  }
1478
+ const shardLines = [];
676
1479
  return {
677
1480
  get runId() {
678
1481
  return runId;
@@ -685,40 +1488,73 @@ async function startRun(passed, declared2) {
685
1488
  },
686
1489
  async add(result) {
687
1490
  buffer.push({ ...result, keys: bound(result.keys) });
688
- if (buffer.length >= batchSize) await flush();
1491
+ if (buffer.length >= batchSize) await flushBuffer();
689
1492
  },
690
1493
  flush,
691
1494
  async finish(reason) {
692
- if (done) return;
1495
+ if (done) return void 0;
693
1496
  done = true;
694
1497
  await flush();
695
1498
  await offer();
1499
+ let frozen;
696
1500
  if (runId !== null && !offline) {
697
1501
  const out = await client.post(`/v1/runs/${runId}/events`, {
698
1502
  event: "finish",
699
1503
  ...reason !== void 0 ? { reason } : {}
700
1504
  });
701
1505
  if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
702
- else if (typeof out.body?.detached === "number" && out.body.detached > 0) {
703
- log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1506
+ else {
1507
+ frozen = out.body?.summary ?? void 0;
1508
+ if (typeof out.body?.detached === "number" && out.body.detached > 0) {
1509
+ log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1510
+ }
704
1511
  }
705
1512
  }
706
1513
  summarise();
1514
+ return frozen;
707
1515
  },
708
- async leaveOpen() {
709
- if (done) return;
1516
+ shardLines,
1517
+ async leaveOpen(opts) {
1518
+ if (done) return void 0;
710
1519
  done = true;
711
1520
  await flush();
712
1521
  await offer();
713
- if (runId !== null) {
1522
+ let frozen;
1523
+ const after = [];
1524
+ const shard = env.shard;
1525
+ let counted = false;
1526
+ let mismatch;
1527
+ if (runId !== null && shard !== void 0 && !offline) {
1528
+ const out = await client.post(`/v1/runs/${runId}/events`, { event: "finish", shardIndex: shard.index, shardsExpected: shard.total });
1529
+ if (out.ok && typeof out.body?.shardsReported === "number") {
1530
+ counted = true;
1531
+ frozen = out.body.summary ?? void 0;
1532
+ const n = out.body.shardsExpected ?? shard.total;
1533
+ if (out.body.run?.statusEvent === "finished") after.push("plune: run closed");
1534
+ after.push(`plune: shard ${shard.index} of ${shard.total} done \u2014 ${out.body.shardsReported} of ${n} shards reported`);
1535
+ } else if (out.ok || out.kind === "invalid") {
1536
+ log('plune: the platform does not support shard auto-close yet \u2014 the run is left open for "plune run finish".');
1537
+ } else if (out.code === "shards_mismatch") {
1538
+ mismatch = new Error(
1539
+ `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.`
1540
+ );
1541
+ } else {
1542
+ 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}".`);
1543
+ }
1544
+ }
1545
+ if (runId !== null && !counted) {
714
1546
  log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
715
1547
  }
716
1548
  summarise();
1549
+ shardLines.push(...after);
1550
+ if (opts?.holdShardLines !== true) for (const line of after) log(line);
1551
+ if (mismatch !== void 0) throw mismatch;
1552
+ return frozen;
717
1553
  }
718
1554
  };
719
1555
  }
720
1556
  function sha256(input) {
721
- return (0, import_crypto2.createHash)("sha256").update(input, "utf8").digest("hex");
1557
+ return (0, import_crypto3.createHash)("sha256").update(input, "utf8").digest("hex");
722
1558
  }
723
1559
  var RESULT_KEY_MAX = 200;
724
1560
  var HASH_CHARS = 32;
@@ -726,128 +1562,6 @@ function resultKey(testId, retry) {
726
1562
  const plain = `${testId}#${retry}`;
727
1563
  return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
728
1564
  }
729
- function failureOf(attempt, home = (0, import_os2.homedir)()) {
730
- const error = chosen(attempt);
731
- const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
732
- const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
733
- const steps = chainOf(attempt.steps);
734
- const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
735
- 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 !== "");
736
- const ciUrl = webLink(attempt.buildHref);
737
- const failure = {
738
- ...headline !== void 0 ? { headline } : {},
739
- ...steps.length > 0 ? { steps } : {},
740
- ...location !== void 0 ? { location } : {},
741
- ...artifacts.length > 0 ? { artifacts } : {},
742
- ...ciUrl !== void 0 ? { ciUrl } : {}
743
- };
744
- return Object.keys(failure).length === 0 ? void 0 : failure;
745
- }
746
- function repoRootOf(dir, stopAt) {
747
- for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
748
- if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
749
- if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
750
- }
751
- }
752
- function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
753
- const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
754
- return cut(machineless(text, attempt.repoRoot, home));
755
- }
756
- function filesOf(attempt) {
757
- return attempt.attachments.filter((a) => a.path !== void 0);
758
- }
759
- function machineless(raw, repoRoot, home) {
760
- let text = (0, import_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
761
- const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
762
- if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
763
- const own = pathIn(home);
764
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
765
- if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
766
- return text;
767
- }
768
- var PATH_START = "(?<![\\w.~%/\\\\-])";
769
- var TEXT_LIMIT = 524288;
770
- var HEADLINE_LIMIT = 8 * 1024;
771
- var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
772
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
773
- function pathIn(path3) {
774
- const parts = path3.split(/[\\/]+/);
775
- while (parts.length > 1 && parts.at(-1) === "") parts.pop();
776
- if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
777
- const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
778
- const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
779
- const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
780
- return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
781
- }
782
- var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
783
- function cut(text) {
784
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
785
- const lines = text.split("\n");
786
- const size = lines.map((line) => jsonBytes(line) + 2);
787
- const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
788
- let used = 0;
789
- let head = 0;
790
- let tail = lines.length;
791
- while (head < tail && used + size[head] <= budget / 2) used += size[head++];
792
- while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
793
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
794
- }
795
- var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
796
- var METADATA_TYPE = "application/plune.metadata+json";
797
- var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
798
- var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
799
- var FRAME_MAX = 8192;
800
- var firstLine = (text) => (0, import_util.stripVTControlCharacters)(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
801
- function chosen({ status, errors }) {
802
- if (status === "timedOut") {
803
- const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
804
- if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
805
- }
806
- return errors[0];
807
- }
808
- function chainOf(steps) {
809
- const chain = [];
810
- for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
811
- chain.push(failed.title);
812
- }
813
- return chain;
814
- }
815
- function placeOf(error, testFile) {
816
- const own = normal(testFile);
817
- let first;
818
- for (const line of (0, import_util.stripVTControlCharacters)(error.text).split("\n")) {
819
- if (line.length > FRAME_MAX) continue;
820
- const frame = FRAME.exec(line);
821
- if (frame === null) continue;
822
- const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
823
- if (normal(place.file) === own) return place;
824
- if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
825
- }
826
- return error.location ?? first;
827
- }
828
- function fileOf(raw) {
829
- if (!raw.startsWith("file://")) return raw;
830
- let path3 = raw.slice("file://".length);
831
- try {
832
- path3 = decodeURIComponent(path3);
833
- } catch {
834
- }
835
- return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
836
- }
837
- var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
838
- function fromRoot(place, root) {
839
- if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
840
- const base = normal(root).replace(/\/+$/, "");
841
- const file = normal(place.file);
842
- if (!file.startsWith(`${base}/`)) return void 0;
843
- const relative = file.slice(base.length + 1);
844
- if (!REPO_RELATIVE.test(relative)) return void 0;
845
- const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
846
- return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
847
- }
848
- function webLink(href) {
849
- return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
850
- }
851
1565
 
852
1566
  // src/index.ts
853
1567
  var SOURCE = "playwright";
@@ -864,16 +1578,19 @@ function titlesOf(test) {
864
1578
  }
865
1579
  return titles;
866
1580
  }
1581
+ function pathTitleOf(test) {
1582
+ return [fileOf2(test), ...titlesOf(test)].join("#");
1583
+ }
867
1584
  function keysFor(test) {
868
1585
  return [
869
1586
  { kind: "playwright-id", value: test.id },
870
- { kind: "path-title", value: [fileOf2(test), ...titlesOf(test)].join("#") }
1587
+ { kind: "path-title", value: pathTitleOf(test) }
871
1588
  ];
872
1589
  }
873
- var METADATA_TYPE2 = "application/plune.metadata+json";
1590
+ var METADATA_TYPE3 = "application/plune.metadata+json";
874
1591
  var TOKEN = /@P([A-Za-z0-9_-]+)/;
875
1592
  function metadataOf(result) {
876
- const found = result.attachments.find((a) => a.contentType === METADATA_TYPE2);
1593
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
877
1594
  if (found === void 0) return void 0;
878
1595
  try {
879
1596
  const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? (0, import_node_fs.readFileSync)(found.path, "utf8") : void 0;
@@ -882,12 +1599,32 @@ function metadataOf(result) {
882
1599
  return void 0;
883
1600
  }
884
1601
  }
885
- function statedIdOf(test, metadata) {
1602
+ function statedIdOf(test, metadata, mapped) {
886
1603
  const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
887
1604
  if (annotation !== void 0 && annotation !== "") return annotation;
888
1605
  const token = TOKEN.exec(test.title)?.[1];
889
1606
  if (token !== void 0) return token;
890
- return metadata?.id !== void 0 && metadata.id !== "" ? metadata.id : void 0;
1607
+ if (metadata?.id !== void 0 && metadata.id !== "") return metadata.id;
1608
+ return mapped;
1609
+ }
1610
+ function readIds(file) {
1611
+ let raw;
1612
+ try {
1613
+ raw = (0, import_node_fs.readFileSync)(file, "utf8");
1614
+ } catch {
1615
+ return {};
1616
+ }
1617
+ try {
1618
+ const parsed = JSON.parse(raw);
1619
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && Object.values(parsed).every((v) => typeof v === "string" && v !== ""))
1620
+ return parsed;
1621
+ } catch {
1622
+ }
1623
+ process.stderr.write(
1624
+ `plune: ${file} is not a JSON object of path-title to case id strings - ignored, tests resolve as if it were absent
1625
+ `
1626
+ );
1627
+ return {};
891
1628
  }
892
1629
  var NOT_FAILED = /* @__PURE__ */ new Set(["passed", "skipped"]);
893
1630
  function textOf(error) {
@@ -909,22 +1646,28 @@ function attemptOf(test, result, ctx) {
909
1646
  status: result.status,
910
1647
  errors: result.errors.map((e) => ({ text: textOf(e), ...e.location !== void 0 ? { location: e.location } : {} })),
911
1648
  steps: declared(result.steps ?? []),
912
- attachments: result.attachments.map(({ name, contentType, path: path3 }) => ({
1649
+ attachments: result.attachments.map(({ name, contentType, path: path3, body }) => ({
913
1650
  name,
914
1651
  contentType,
915
- ...path3 !== void 0 ? { path: path3 } : {}
1652
+ ...path3 !== void 0 ? { path: path3 } : {},
1653
+ // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
1654
+ ...body !== void 0 ? { body } : {}
916
1655
  })),
917
1656
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
918
1657
  testFile: test.location.file,
919
1658
  ...ctx.repoRoot !== void 0 ? { repoRoot: ctx.repoRoot } : {}
920
1659
  };
921
1660
  }
922
- function pendingFrom(test, result, ctx) {
1661
+ function pendingFrom(test, result, ctx, ids = {}) {
923
1662
  const metadata = metadataOf(result);
924
- const pluneId = statedIdOf(test, metadata);
1663
+ const pluneId = statedIdOf(
1664
+ test,
1665
+ metadata,
1666
+ Object.hasOwn(ids, pathTitleOf(test)) ? ids[pathTitleOf(test)] : void 0
1667
+ );
925
1668
  const expected = test.expectedStatus;
926
1669
  const attempt = attemptOf(test, result, ctx);
927
- const errorContext = errorContextOf(attempt);
1670
+ const errorContext = errorContextFields(attempt);
928
1671
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
929
1672
  const files = filesOf(attempt);
930
1673
  const startedAt = result.startTime;
@@ -954,9 +1697,9 @@ function pendingFrom(test, result, ctx) {
954
1697
  retry: result.retry,
955
1698
  worker: String(result.workerIndex)
956
1699
  },
957
- ...errorContext !== "" ? { errorContext } : {},
1700
+ ...errorContext,
958
1701
  ...failure !== void 0 ? { failure } : {},
959
- // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
1702
+ // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
960
1703
  ...files.length > 0 ? { files } : {}
961
1704
  };
962
1705
  }
@@ -972,6 +1715,8 @@ var PluneReporter = class {
972
1715
  /** Kept whole: `metadata.ci` is written into it after `onConfigure`, so it is read at the run's opening. */
973
1716
  config = null;
974
1717
  context = {};
1718
+ /** The mapfile, read on the first result so a run that reports nothing never touches the disk. */
1719
+ ids = null;
975
1720
  constructor(options = {}) {
976
1721
  this.options = options;
977
1722
  }
@@ -1024,7 +1769,10 @@ var PluneReporter = class {
1024
1769
  onTestEnd(test, result) {
1025
1770
  const session = this.open();
1026
1771
  this.chain = this.chain.then(async () => {
1027
- await (await session).add(pendingFrom(test, result, this.context));
1772
+ this.ids ??= readIds(
1773
+ (0, import_node_path.resolve)(this.options.idsFile ?? process.env["PLUNE_IDS_FILE"] ?? "plune/ids.json")
1774
+ );
1775
+ await (await session).add(pendingFrom(test, result, this.context, this.ids));
1028
1776
  }).catch((err) => this.giveUp(err));
1029
1777
  }
1030
1778
  async onEnd(_result) {