@plune-ai/playwright 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -34,6 +34,7 @@ __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
@@ -44,16 +45,20 @@ var import_util = require("util");
44
45
  var import_fs2 = require("fs");
45
46
  var import_os = require("os");
46
47
  var import_path2 = require("path");
48
+ var import_fs3 = require("fs");
49
+ var import_stream = require("stream");
47
50
  var import_http = require("http");
48
51
  var import_https = require("https");
49
52
  var path = __toESM(require("path"), 1);
50
- var import_fs3 = require("fs");
53
+ var import_fs4 = require("fs");
51
54
  var import_os2 = require("os");
52
55
  var import_path3 = require("path");
53
56
  var import_util2 = require("util");
57
+ var import_crypto2 = require("crypto");
58
+ var import_fs5 = require("fs");
54
59
  var fs = __toESM(require("fs"), 1);
55
60
  var path2 = __toESM(require("path"), 1);
56
- var import_crypto2 = require("crypto");
61
+ var import_crypto3 = require("crypto");
57
62
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
58
63
  function resolveApiUrl(explicit) {
59
64
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -73,20 +78,32 @@ function loadToken() {
73
78
  return null;
74
79
  }
75
80
  }
76
- 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 }) };
77
93
  var IDLE_MS = 3e5;
78
94
  function nodeTransport(url, init, idleMs = IDLE_MS) {
79
- return new Promise((resolve2, reject) => {
95
+ return new Promise((resolve22, reject) => {
80
96
  const target = new URL(url);
81
97
  const send = target.protocol === "https:" ? import_https.request : import_http.request;
82
- 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) => {
83
100
  const chunks = [];
84
101
  res.on("data", (chunk2) => chunks.push(chunk2));
85
102
  res.on("error", reject);
86
103
  res.on("end", () => {
87
104
  const status = res.statusCode ?? 0;
88
105
  const text = Buffer.concat(chunks).toString("utf8");
89
- resolve2({
106
+ resolve22({
90
107
  ok: status >= 200 && status <= 299,
91
108
  status,
92
109
  headers: {
@@ -104,20 +121,60 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
104
121
  req.end(init.body);
105
122
  });
106
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
+ };
107
156
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
108
157
  async function detailOf(res) {
109
158
  try {
110
159
  const body = await res.json();
111
- 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
+ };
112
167
  } catch {
113
- return "";
168
+ return { detail: "" };
114
169
  }
115
170
  }
116
- function retryAfterMs(res) {
117
- const raw = res.headers.get("retry-after");
118
- if (raw === null) return null;
119
- const seconds = Number(raw.trim());
120
- 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(", ");
121
178
  }
122
179
  function classify(status) {
123
180
  if (status === 401 || status === 403) return "auth";
@@ -129,15 +186,34 @@ function classify(status) {
129
186
  function createClient(opts) {
130
187
  const doFetch = opts.fetchImpl ?? nodeTransport;
131
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
+ }
132
206
  const base = opts.apiUrl.replace(/\/+$/, "");
133
207
  const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
134
- async function send(method, path3, payload) {
208
+ async function send(method, path3, payload, retries = DEFAULT_RETRIES) {
135
209
  let last = {
136
210
  kind: "unavailable",
137
211
  status: null,
138
212
  detail: "no attempt was made"
139
213
  };
140
- 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);
141
217
  let res;
142
218
  try {
143
219
  res = await doFetch(`${base}${path3}`, {
@@ -150,7 +226,8 @@ function createClient(opts) {
150
226
  });
151
227
  } catch (err) {
152
228
  last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
153
- 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);
154
231
  continue;
155
232
  }
156
233
  if (res.ok) {
@@ -161,23 +238,95 @@ function createClient(opts) {
161
238
  return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
162
239
  }
163
240
  }
164
- const detail = scrub(await detailOf(res));
241
+ const said = await detailOf(res);
165
242
  const kind = classify(res.status);
166
- 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 } : {} };
167
244
  if (kind !== "unavailable") break;
168
- if (attempt < RETRY_DELAYS_MS.length) {
169
- 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;
170
251
  }
252
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
253
+ mine = await backOff(attempt, said429);
171
254
  }
172
255
  return { ok: false, ...last };
173
256
  }
174
257
  return {
175
- post: (path3, body) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }),
176
- upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }),
177
- 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
+ }
178
294
  };
179
295
  }
180
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
+ function configurationOf(env) {
309
+ const raw = value(env, "PLUNE_CONFIGURATION");
310
+ if (raw === void 0) return {};
311
+ const pairs = [];
312
+ for (const pair of raw.split(";").map((s) => s.trim()).filter((s) => s !== "")) {
313
+ const at = pair.indexOf("=");
314
+ const name = at < 0 ? "" : pair.slice(0, at).trim();
315
+ const label = at < 0 ? "" : pair.slice(at + 1).trim();
316
+ const twice = pairs.find(([seen]) => seen.toLowerCase() === name.toLowerCase());
317
+ const why = at < 0 ? 'has no "="' : name === "" ? "has no group name" : label === "" ? "has no value" : twice !== void 0 ? `names the group ${JSON.stringify(twice[0])} a second time` : void 0;
318
+ if (why !== void 0) {
319
+ return {
320
+ error: `PLUNE_CONFIGURATION: ${JSON.stringify(pair.slice(0, 40))} ${why} - write it as "Group=Value;Group=Value" (for example "Browser=Chrome;Operating system=Windows") - nothing was sent.`
321
+ };
322
+ }
323
+ pairs.push([name, label]);
324
+ }
325
+ return pairs.length === 0 ? {} : { configuration: Object.fromEntries(pairs) };
326
+ }
327
+ var UPLOAD_CONCURRENCY = { min: 1, max: 32, default: 16 };
328
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
329
+ var IMPORT_TIMEOUT = { min: 0, max: 86400, default: 600 };
181
330
  function value(env, name) {
182
331
  const raw = env[name]?.trim();
183
332
  return raw === void 0 || raw === "" ? void 0 : raw;
@@ -192,6 +341,14 @@ function count(env, name) {
192
341
  const n = Number(raw);
193
342
  return Number.isInteger(n) && n > 0 ? n : void 0;
194
343
  }
344
+ function bounded(env, name, range, warnings) {
345
+ const raw = value(env, name);
346
+ if (raw === void 0) return void 0;
347
+ const n = Number(raw);
348
+ if (/^\d+$/.test(raw) && n >= range.min && n <= range.max) return n;
349
+ warnings.push(`${name}=${JSON.stringify(raw.slice(0, 40))} is not a whole number from ${range.min} to ${range.max} \u2014 using ${range.default}.`);
350
+ return void 0;
351
+ }
195
352
  function list(env, name) {
196
353
  const raw = value(env, name);
197
354
  if (raw === void 0) return void 0;
@@ -204,11 +361,17 @@ function readEnv(env = process.env) {
204
361
  const apiUrl = value(env, "PLUNE_API_URL");
205
362
  const fallbackPath = value(env, "PLUNE_FALLBACK");
206
363
  const batchSize = count(env, "PLUNE_BATCH_SIZE");
364
+ const warnings = [];
365
+ const uploadConcurrency = bounded(env, "PLUNE_UPLOAD_CONCURRENCY", UPLOAD_CONCURRENCY, warnings);
366
+ const uploadRetries = bounded(env, "PLUNE_UPLOAD_RETRIES", UPLOAD_RETRIES, warnings);
367
+ const importTimeout = bounded(env, "PLUNE_IMPORT_TIMEOUT", IMPORT_TIMEOUT, warnings);
207
368
  const title = value(env, "PLUNE_RUN_TITLE");
208
369
  const environment = value(env, "PLUNE_ENV");
209
370
  const labels = list(env, "PLUNE_LABELS");
210
371
  const offerDiscovered = flag(env, "PLUNE_CREATE");
211
372
  const full = flag(env, "PLUNE_FULL_RUN");
373
+ const { shard, error: shardError } = shardOf(env);
374
+ const { configuration, error: configurationError } = configurationOf(env);
212
375
  return {
213
376
  config: {
214
377
  ...externalKey !== void 0 ? { externalKey } : {},
@@ -216,9 +379,12 @@ function readEnv(env = process.env) {
216
379
  ...apiUrl !== void 0 ? { apiUrl } : {},
217
380
  ...fallbackPath !== void 0 ? { fallbackPath } : {},
218
381
  ...batchSize !== void 0 ? { batchSize } : {},
382
+ ...uploadConcurrency !== void 0 ? { uploadConcurrency } : {},
383
+ ...uploadRetries !== void 0 ? { uploadRetries } : {},
219
384
  ...title !== void 0 ? { title } : {},
220
385
  ...environment !== void 0 ? { environment } : {},
221
386
  ...labels !== void 0 ? { labels } : {},
387
+ ...configuration !== void 0 ? { configuration } : {},
222
388
  // Only when set: `false` here would outrank a config file that asked for it, and an unset
223
389
  // variable is not an instruction.
224
390
  ...offerDiscovered ? { offerDiscovered } : {},
@@ -227,8 +393,15 @@ function readEnv(env = process.env) {
227
393
  // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
228
394
  // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
229
395
  // way this process must not be the one to call it finished.
230
- keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED"),
231
- ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0)
396
+ // `PLUNE_SHARD` implies it: the run is joined by the shared key and this process does not close it
397
+ // by itself; `leaveOpen` reports the shard instead.
398
+ keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED") || shard !== void 0 || shardError !== void 0,
399
+ ...shard !== void 0 ? { shard } : {},
400
+ ...shardError !== void 0 ? { shardError } : {},
401
+ ...configurationError !== void 0 ? { configurationError } : {},
402
+ ...importTimeout !== void 0 ? { importTimeout } : {},
403
+ ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0),
404
+ warnings
232
405
  };
233
406
  }
234
407
  function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cwd = process.cwd()) {
@@ -278,14 +451,22 @@ function failureOf(attempt, home = (0, import_os2.homedir)()) {
278
451
  }
279
452
  function repoRootOf(dir, stopAt) {
280
453
  for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
281
- if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
454
+ if ((0, import_fs4.existsSync)((0, import_path3.join)(here, ".git"))) return here;
282
455
  if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
283
456
  }
284
457
  }
285
- function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
458
+ function errorContextFields(attempt, home = (0, import_os2.homedir)()) {
459
+ const { text, omitted: omitted2 } = cutErrorContext(attempt, home);
460
+ return {
461
+ ...text !== "" ? { errorContext: text } : {},
462
+ ...omitted2 > 0 ? { errorContextOmitted: omitted2 } : {}
463
+ };
464
+ }
465
+ function cutErrorContext(attempt, home) {
286
466
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
287
467
  return cut(machineless(text, attempt.repoRoot, home));
288
468
  }
469
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
289
470
  var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
290
471
  var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
291
472
  var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
@@ -317,7 +498,7 @@ function pathIn(path3) {
317
498
  }
318
499
  var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
319
500
  function cut(text) {
320
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
501
+ if (jsonBytes(text) <= TEXT_LIMIT) return { text, omitted: 0 };
321
502
  const lines = text.split("\n");
322
503
  const size = lines.map((line) => jsonBytes(line) + 2);
323
504
  const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
@@ -326,7 +507,8 @@ function cut(text) {
326
507
  let tail = lines.length;
327
508
  while (head < tail && used + size[head] <= budget / 2) used += size[head++];
328
509
  while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
329
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
510
+ const kept = [...lines.slice(0, head), ...lines.slice(tail)].join("\n");
511
+ return { text: [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n"), omitted: text.length - kept.length };
330
512
  }
331
513
  var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
332
514
  var METADATA_TYPE = "application/plune.metadata+json";
@@ -384,6 +566,23 @@ function fromRoot(place, root) {
384
566
  function webLink(href) {
385
567
  return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
386
568
  }
569
+ var FILES_BATCH_MAX = 100;
570
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
571
+ var BATCH_PIPELINES = 2;
572
+ async function sha256File(path3) {
573
+ const hash = (0, import_crypto2.createHash)("sha256");
574
+ for await (const part of (0, import_fs5.createReadStream)(path3)) hash.update(part);
575
+ return hash.digest("hex");
576
+ }
577
+ var sha256Bytes = (bytes) => (0, import_crypto2.createHash)("sha256").update(bytes).digest("hex");
578
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
579
+ "bucket_unreachable",
580
+ "not_connected",
581
+ "platform_not_configured",
582
+ "upload_expired",
583
+ "file_mismatch",
584
+ "file_missing"
585
+ ]);
387
586
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
388
587
  function appendBatch(file, batch) {
389
588
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -393,6 +592,7 @@ function appendBatch(file, batch) {
393
592
  externalKey: batch.externalKey,
394
593
  ...batch.session !== void 0 ? { session: batch.session } : {},
395
594
  ...batch.meta !== void 0 ? { meta: batch.meta } : {},
595
+ ...batch.configuration !== void 0 ? { configuration: batch.configuration } : {},
396
596
  results: batch.results
397
597
  };
398
598
  fs.appendFileSync(file, `${JSON.stringify(line)}
@@ -401,7 +601,8 @@ function appendBatch(file, batch) {
401
601
  var RESOLVE_CHUNK = 500;
402
602
  var BATCH_MAX = 500;
403
603
  var DISCOVER_MAX = 500;
404
- var BATCH_DEFAULT = 100;
604
+ var BATCH_DEFAULT = 500;
605
+ var SEND_CONCURRENCY = 4;
405
606
  var EXPECTED_MAX = 1e4;
406
607
  var KEY_MAX = 1024;
407
608
  var TITLE_MAX = 300;
@@ -418,7 +619,7 @@ var TYPE_BY_EXTENSION = {
418
619
  ".jpeg": "image/jpeg",
419
620
  ".webp": "image/webp"
420
621
  };
421
- var UPLOADS_AT_ONCE = 4;
622
+ var METADATA_TYPE2 = "application/plune.metadata+json";
422
623
  var NAME_MAX = 200;
423
624
  function nameOf(file) {
424
625
  const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_path.basename)(file.path));
@@ -443,15 +644,26 @@ var SKIPPED = {
443
644
  textSize: "Plune takes a text file of at most 512 KiB",
444
645
  empty: "the file is empty",
445
646
  binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
446
- encoding: "Plune takes UTF-8 text only"
647
+ encoding: "Plune takes UTF-8 text only",
648
+ noStorage: "no storage bucket is connected to this project"
447
649
  };
650
+ var BUCKET_FOUND = "plune: storage bucket found for this project \u2014 screenshots, text, trace and video go straight to it over short-lived links.";
448
651
  var KINDS = {
449
652
  screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
450
- text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" }
653
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
654
+ // 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.
655
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
451
656
  };
452
657
  function kindOf(type) {
453
658
  if (type.startsWith("image/")) return "screenshot";
454
- return TEXT_TYPES.has(type) ? "text" : void 0;
659
+ return TEXT_TYPES.has(type) ? "text" : "file";
660
+ }
661
+ var codeOf = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
662
+ function linkOf(item) {
663
+ const link = item;
664
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
665
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
666
+ return { id: link.id, url: link.url, headers };
455
667
  }
456
668
  function textTypeOf(contentType, type) {
457
669
  const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
@@ -528,8 +740,11 @@ function warnIfDropped(sent, run, log) {
528
740
  }
529
741
  async function startRun(passed, declared2) {
530
742
  const env = readEnv();
743
+ if (env.shardError !== void 0) throw new Error(env.shardError);
744
+ if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
531
745
  const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
532
746
  const cfg = { ...env.config, ...stated };
747
+ const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
533
748
  const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
534
749
  `));
535
750
  const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
@@ -538,9 +753,18 @@ async function startRun(passed, declared2) {
538
753
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
539
754
  const offerDiscovered = cfg.offerDiscovered ?? false;
540
755
  const token = cfg.token ?? loadToken() ?? "";
756
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
757
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
758
+ let retried = 0;
759
+ let uploadMs = 0;
760
+ let requests = 0;
761
+ let existed = 0;
762
+ let batchMissing = false;
541
763
  const client = createClient({
542
764
  apiUrl: resolveApiUrl(cfg.apiUrl),
543
765
  token,
766
+ uploadRetries,
767
+ onRetry: () => void (retried += 1),
544
768
  ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
545
769
  });
546
770
  const stats = {
@@ -554,18 +778,28 @@ async function startRun(passed, declared2) {
554
778
  unoffered: 0,
555
779
  deferred: 0,
556
780
  screenshots: { uploaded: 0, skipped: 0, failed: 0 },
557
- textFiles: { uploaded: 0, skipped: 0, failed: 0 }
781
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
782
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
558
783
  };
559
784
  const resolved = /* @__PURE__ */ new Map();
560
785
  let buffer = [];
561
786
  const discoveries = /* @__PURE__ */ new Map();
787
+ const held = /* @__PURE__ */ new Map();
788
+ let createdWithResult = 0;
789
+ let createdUndelivered = 0;
562
790
  let runId = null;
563
791
  let joined = false;
564
792
  let offline = token === "";
565
793
  let done = false;
566
794
  const shortened = /* @__PURE__ */ new Set();
567
795
  const skipsSaid = /* @__PURE__ */ new Set();
568
- const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
796
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
797
+ let bucketSeen = false;
798
+ let noStorage = 0;
799
+ let uploadsMissing = false;
800
+ const failedSaid = /* @__PURE__ */ new Set();
801
+ const codesSaid = /* @__PURE__ */ new Set();
802
+ const rooms = /* @__PURE__ */ new Map();
569
803
  function bound(keys) {
570
804
  return keys.map((key) => {
571
805
  const fit = boundKey(key);
@@ -573,7 +807,7 @@ async function startRun(passed, declared2) {
573
807
  shortened.add(key.value);
574
808
  if (shortened.size === 1) {
575
809
  log(
576
- `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.`
810
+ `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.`
577
811
  );
578
812
  }
579
813
  }
@@ -584,6 +818,7 @@ async function startRun(passed, declared2) {
584
818
  if (offline) {
585
819
  log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
586
820
  }
821
+ for (const warning of env.warnings) log(`plune: ${warning}`);
587
822
  if (env.ignored.length > 0) {
588
823
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
589
824
  }
@@ -593,6 +828,7 @@ async function startRun(passed, declared2) {
593
828
  externalKey,
594
829
  session: sessionMarker,
595
830
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
831
+ ...configuration !== void 0 ? { configuration } : {},
596
832
  results: results.map(onDisk)
597
833
  });
598
834
  stats.deferred += results.length;
@@ -617,7 +853,7 @@ async function startRun(passed, declared2) {
617
853
  if (!offline) {
618
854
  if (expected !== void 0) await resolveKeys(expected.flat());
619
855
  const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
620
- const configuration = stated2.length === 0 ? void 0 : {
856
+ const configuration2 = stated2.length === 0 ? void 0 : {
621
857
  expected: stated2.flatMap((keys) => {
622
858
  const hit = keys.map((k) => resolved.get(k.value)).find((v) => typeof v === "string");
623
859
  if (typeof hit === "string") return [{ testCaseId: hit }];
@@ -636,18 +872,25 @@ async function startRun(passed, declared2) {
636
872
  ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
637
873
  ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
638
874
  };
639
- const start = await client.post("/v1/runs", {
875
+ const request = {
640
876
  schemaVersion: 2,
641
877
  kind: cfg.kind ?? "automated",
642
878
  ...externalKey !== null ? { externalKey } : {},
643
879
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
644
- ...configuration !== void 0 ? { configuration } : {},
880
+ ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
645
881
  // Named even when nobody named it — the list has to read without opening a row. Only what
646
882
  // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
647
883
  // a person will miss, and a deployment older than the field must not be nagged on every run.
648
884
  title: defaultRunTitle(),
649
885
  ...described
650
- });
886
+ };
887
+ let start = await client.post("/v1/runs", request);
888
+ if (!start.ok && start.status === 413 && configuration2 !== void 0) {
889
+ log(
890
+ `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.`
891
+ );
892
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
893
+ }
651
894
  if (start.ok && typeof start.body?.run?.id === "string") {
652
895
  runId = start.body.run.id;
653
896
  joined = start.status === 200;
@@ -680,6 +923,7 @@ async function startRun(passed, declared2) {
680
923
  specRef: result.specRef,
681
924
  rawStatus: result.rawStatus
682
925
  });
926
+ held.set(result.keys[0].value, result);
683
927
  }
684
928
  async function offer() {
685
929
  if (discoveries.size === 0 || offline || runId === null) return;
@@ -698,24 +942,71 @@ async function startRun(passed, declared2) {
698
942
  return;
699
943
  }
700
944
  stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
701
- stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
945
+ const made = out.body.results.filter((r) => r?.outcome === "created");
946
+ stats.created += made.length;
947
+ const submissions = [];
948
+ const filesByKey = /* @__PURE__ */ new Map();
949
+ for (const r of made) {
950
+ const pending = typeof r.id === "string" && r.id !== "" ? held.get(r.key?.value) : void 0;
951
+ if (pending === void 0) continue;
952
+ held.delete(r.key.value);
953
+ const { keys: _keys, files, ...rest } = pending;
954
+ submissions.push({ ...rest, testCaseId: r.id });
955
+ if (files !== void 0) filesByKey.set(pending.resultKey, files);
956
+ }
957
+ if (submissions.length > 0) {
958
+ const before = stats.deferred;
959
+ await send(submissions, filesByKey);
960
+ createdWithResult += submissions.length;
961
+ createdUndelivered += stats.deferred - before;
962
+ }
702
963
  }
703
964
  }
704
965
  function skip(kind, name, why) {
705
966
  countsOf(kind).skipped += 1;
706
- if (skipsSaid.has(`${kind}/${why}`)) return;
707
- skipsSaid.add(`${kind}/${why}`);
708
- log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
967
+ if (why === "noStorage") noStorage += 1;
968
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
969
+ if (skipsSaid.has(said)) return;
970
+ skipsSaid.add(said);
971
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
972
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
973
+ }
974
+ function ask(job, size) {
975
+ requests += 1;
976
+ return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
977
+ files: [{ name: job.name, contentType: job.type, size }]
978
+ }, uploadRetries);
979
+ }
980
+ function failed(job, why) {
981
+ countsOf(job.kind).failed += 1;
982
+ if (!failedSaid.has(job.kind)) {
983
+ failedSaid.add(job.kind);
984
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
985
+ }
986
+ }
987
+ function failedToBucket(job, code) {
988
+ countsOf(job.kind).failed += 1;
989
+ if (codesSaid.has(code)) return;
990
+ codesSaid.add(code);
991
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
992
+ }
993
+ function refusedHere(job, size) {
994
+ if (job.kind === "screenshot") {
995
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
996
+ if (size > SCREENSHOT_BYTES) return "size";
997
+ }
998
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
999
+ return void 0;
709
1000
  }
710
- async function uploadOne(job) {
1001
+ async function uploadDirect(job, size) {
711
1002
  const { kind } = job;
712
- const { label, bytes: ceiling, size } = KINDS[kind];
1003
+ if (kind === "file") return skip(kind, job.name, "noStorage");
1004
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
1005
+ if (size > ceiling) return skip(kind, job.name, tooBig);
713
1006
  let bytes;
714
1007
  if (job.body !== void 0) bytes = job.body;
715
- else if (job.path === void 0) return skip(kind, job.name, "missing");
716
1008
  else {
717
1009
  try {
718
- if ((await import_fs.promises.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
719
1010
  bytes = await import_fs.promises.readFile(job.path);
720
1011
  } catch {
721
1012
  return skip(kind, job.name, "missing");
@@ -723,37 +1014,342 @@ async function startRun(passed, declared2) {
723
1014
  }
724
1015
  const refusal = kind === "text" ? textRefusal(bytes) : void 0;
725
1016
  if (refusal !== void 0) return skip(kind, job.name, refusal);
1017
+ requests += 1;
726
1018
  const out = await client.upload(
727
1019
  `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
728
1020
  bytes,
729
1021
  job.type
730
1022
  );
731
- const counts = countsOf(kind);
732
- if (out.ok) {
733
- counts.uploaded += 1;
1023
+ if (out.ok) countsOf(kind).uploaded += 1;
1024
+ else failed(job, out.detail || out.kind);
1025
+ }
1026
+ async function uploadToBucket(job, size, first) {
1027
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
1028
+ let link = first;
1029
+ for (let renewed = false; ; ) {
1030
+ const put = await client.put(link.url, link.headers, source);
1031
+ if (put.ok) break;
1032
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
1033
+ renewed = true;
1034
+ const again = await ask(job, size);
1035
+ if (!again.ok) return failedToBucket(job, codeOf(again));
1036
+ const fresh = linkOf(again.body?.files?.[0]);
1037
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
1038
+ link = fresh;
1039
+ }
1040
+ requests += 1;
1041
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1042
+ if (!done2.ok) return failedToBucket(job, codeOf(done2));
1043
+ countsOf(job.kind).uploaded += 1;
1044
+ }
1045
+ let free = uploadsAtOnce;
1046
+ const waiting = [];
1047
+ async function gated(work) {
1048
+ if (free === 0) await new Promise((resolve22) => waiting.push(resolve22));
1049
+ else free -= 1;
1050
+ try {
1051
+ return await work();
1052
+ } finally {
1053
+ const next = waiting.shift();
1054
+ if (next !== void 0) next();
1055
+ else free += 1;
1056
+ }
1057
+ }
1058
+ async function plan(job) {
1059
+ const { kind } = job;
1060
+ let size;
1061
+ if (job.body !== void 0) size = job.body.length;
1062
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
1063
+ else {
1064
+ try {
1065
+ size = (await import_fs.promises.stat(job.path)).size;
1066
+ } catch {
1067
+ return void skip(kind, job.name, "missing");
1068
+ }
1069
+ }
1070
+ if (size === 0) return void skip(kind, job.name, "empty");
1071
+ const direct = () => {
1072
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
1073
+ const roomKey = `${job.id}/${kind}`;
1074
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
1075
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
1076
+ rooms.set(roomKey, left - 1);
1077
+ return () => uploadDirect(job, size);
1078
+ };
1079
+ if (uploadsMissing) return direct();
1080
+ const out = await gated(() => ask(job, size));
1081
+ if (!out.ok) {
1082
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
1083
+ uploadsMissing = true;
1084
+ return direct();
1085
+ }
1086
+ if (out.code !== void 0) failedToBucket(job, out.code);
1087
+ else failed(job, out.detail || out.kind);
1088
+ return void 0;
1089
+ }
1090
+ const item = out.body?.files?.[0];
1091
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
1092
+ if (item?.direct === true) return direct();
1093
+ const link = linkOf(item);
1094
+ if (link === void 0) return void failed(job, "bad_answer");
1095
+ if (!bucketSeen) {
1096
+ bucketSeen = true;
1097
+ log(BUCKET_FOUND);
1098
+ }
1099
+ return () => uploadToBucket(job, size, link);
1100
+ }
1101
+ async function uploadEach(jobs) {
1102
+ const byResult = /* @__PURE__ */ new Map();
1103
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
1104
+ await Promise.all(
1105
+ [...byResult.values()].map(async (group) => {
1106
+ const work = [];
1107
+ for (const job of group) {
1108
+ const act = await plan(job);
1109
+ if (act !== void 0) work.push(gated(act));
1110
+ }
1111
+ await Promise.all(work);
1112
+ })
1113
+ );
1114
+ }
1115
+ async function measure(job) {
1116
+ let size;
1117
+ if (job.body !== void 0) size = job.body.length;
1118
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
1119
+ else {
1120
+ try {
1121
+ size = (await import_fs.promises.stat(job.path)).size;
1122
+ } catch {
1123
+ return void skip(job.kind, job.name, "missing");
1124
+ }
1125
+ }
1126
+ if (size === 0) return void skip(job.kind, job.name, "empty");
1127
+ return size;
1128
+ }
1129
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
1130
+ function takeRoom(job) {
1131
+ if (job.kind === "file") {
1132
+ skip(job.kind, job.name, "noStorage");
1133
+ return false;
1134
+ }
1135
+ const roomKey = `${job.id}/${job.kind}`;
1136
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
1137
+ if (left === 0) {
1138
+ skip(job.kind, job.name, KINDS[job.kind].limit);
1139
+ return false;
1140
+ }
1141
+ rooms.set(roomKey, left - 1);
1142
+ return true;
1143
+ }
1144
+ function refusedItem(job, size, item) {
1145
+ const code = item.code ?? "refused";
1146
+ if (code === "duplicate") existed += 1;
1147
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
1148
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
1149
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
1150
+ else failed(job, code);
1151
+ }
1152
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
1153
+ async function batchOf(jobs) {
1154
+ if (batchMissing) return uploadEach(jobs);
1155
+ const sized = [];
1156
+ for (const job of jobs) {
1157
+ const size = await measure(job);
1158
+ if (size === void 0) continue;
1159
+ try {
1160
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
1161
+ } catch {
1162
+ skip(job.kind, job.name, "missing");
1163
+ }
1164
+ }
1165
+ if (sized.length === 0) return;
1166
+ const announced = await gated(() => {
1167
+ requests += 1;
1168
+ return client.post(
1169
+ "/v1/files/uploads-batch",
1170
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
1171
+ uploadRetries
1172
+ );
1173
+ });
1174
+ if (routeMissing(announced)) {
1175
+ batchMissing = true;
1176
+ return uploadEach(sized.map((s) => s.job));
1177
+ }
1178
+ const verdicts = announced.ok ? announced.body?.items : void 0;
1179
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
1180
+ for (const s of sized) {
1181
+ if (announced.ok) failed(s.job, "bad_answer");
1182
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
1183
+ else failed(s.job, announced.detail || announced.kind);
1184
+ }
734
1185
  return;
735
1186
  }
736
- counts.failed += 1;
737
- if (counts.failed === 1) {
738
- log(`plune: could not upload a ${label} (${out.detail || out.kind}) \u2014 its result is reported without it.`);
1187
+ const puts = [];
1188
+ const directs = [];
1189
+ sized.forEach((s, i) => {
1190
+ const v = verdicts[i] ?? {};
1191
+ if (v.status === "exists") existed += 1;
1192
+ else if (v.status === "direct") {
1193
+ if (takeRoom(s.job)) directs.push(s);
1194
+ } else if (v.status === "upload") {
1195
+ const link = linkOf(v);
1196
+ if (link === void 0) return failed(s.job, "bad_answer");
1197
+ if (!bucketSeen) {
1198
+ bucketSeen = true;
1199
+ log(BUCKET_FOUND);
1200
+ }
1201
+ puts.push({ s, link });
1202
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
1203
+ else failed(s.job, "bad_answer");
1204
+ });
1205
+ const toComplete = [];
1206
+ await Promise.all(
1207
+ puts.map(
1208
+ ({ s, link: first }) => gated(async () => {
1209
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
1210
+ let link = first;
1211
+ for (let renewed = false; ; ) {
1212
+ const put = await client.put(link.url, link.headers, source);
1213
+ if (put.ok) break;
1214
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
1215
+ renewed = true;
1216
+ requests += 1;
1217
+ const again = await client.post(
1218
+ "/v1/files/uploads-batch",
1219
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
1220
+ uploadRetries
1221
+ );
1222
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
1223
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf(again));
1224
+ link = fresh;
1225
+ }
1226
+ toComplete.push({ job: s.job, id: link.id });
1227
+ })
1228
+ )
1229
+ );
1230
+ await complete(toComplete);
1231
+ await sendDirect(directs);
1232
+ }
1233
+ async function complete(items) {
1234
+ for (let round = 0; items.length > 0; round += 1) {
1235
+ const out = await gated(() => {
1236
+ requests += 1;
1237
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
1238
+ });
1239
+ if (routeMissing(out)) {
1240
+ await Promise.all(
1241
+ items.map(
1242
+ (i) => gated(async () => {
1243
+ requests += 1;
1244
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
1245
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
1246
+ else failedToBucket(i.job, codeOf(one));
1247
+ })
1248
+ )
1249
+ );
1250
+ return;
1251
+ }
1252
+ const verdicts = out.ok ? out.body?.items : void 0;
1253
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
1254
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf(out));
1255
+ return;
1256
+ }
1257
+ const again = [];
1258
+ items.forEach((i, at) => {
1259
+ const v = verdicts[at] ?? {};
1260
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
1261
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
1262
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1263
+ });
1264
+ items = again;
1265
+ if (items.length > 0) {
1266
+ retried += items.length;
1267
+ await itemPause(round);
1268
+ }
1269
+ }
1270
+ }
1271
+ async function sendDirect(items) {
1272
+ const groups = [];
1273
+ let bytes = 0;
1274
+ for (const item of items) {
1275
+ const group = groups[groups.length - 1];
1276
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
1277
+ groups.push([item]);
1278
+ bytes = item.size;
1279
+ } else {
1280
+ group.push(item);
1281
+ bytes += item.size;
1282
+ }
1283
+ }
1284
+ for (const group of groups) {
1285
+ const body = [];
1286
+ const sent = [];
1287
+ for (const { job, size } of group) {
1288
+ const { kind } = job;
1289
+ if (size > KINDS[kind].bytes) {
1290
+ skip(kind, job.name, KINDS[kind].size);
1291
+ continue;
1292
+ }
1293
+ let data;
1294
+ try {
1295
+ data = job.body ?? await import_fs.promises.readFile(job.path);
1296
+ } catch {
1297
+ skip(kind, job.name, "missing");
1298
+ continue;
1299
+ }
1300
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
1301
+ if (refusal !== void 0) {
1302
+ skip(kind, job.name, refusal);
1303
+ continue;
1304
+ }
1305
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
1306
+ sent.push({ job, size });
1307
+ }
1308
+ if (body.length === 0) continue;
1309
+ const out = await gated(() => {
1310
+ requests += 1;
1311
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
1312
+ });
1313
+ if (routeMissing(out)) {
1314
+ batchMissing = true;
1315
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
1316
+ continue;
1317
+ }
1318
+ const verdicts = out.ok ? out.body?.items : void 0;
1319
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
1320
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
1321
+ continue;
1322
+ }
1323
+ sent.forEach(({ job }, i) => {
1324
+ const v = verdicts[i] ?? {};
1325
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
1326
+ else if (v.status === "exists") existed += 1;
1327
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1328
+ });
739
1329
  }
740
1330
  }
1331
+ async function uploadBatched(jobs) {
1332
+ const batches = chunk(jobs, FILES_BATCH_MAX);
1333
+ let next = 0;
1334
+ await Promise.all(
1335
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
1336
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
1337
+ })
1338
+ );
1339
+ }
741
1340
  async function upload(items, filesByKey) {
742
1341
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
743
1342
  const jobs = [];
744
1343
  for (const item of items) {
745
1344
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
746
- const room = { screenshot: KINDS.screenshot.room, text: KINDS.text.room };
747
1345
  for (const file of filesByKey.get(item.resultKey) ?? []) {
748
1346
  const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()]);
749
- const kind = type === void 0 ? void 0 : kindOf(type);
750
- if (type === void 0 || kind === void 0 || kind === "screenshot" && file.path === void 0) continue;
1347
+ if (type === void 0 || type === METADATA_TYPE2) continue;
1348
+ const kind = kindOf(type);
1349
+ if (kind !== "text" && file.path === void 0) continue;
751
1350
  const name = nameOf(file);
752
1351
  if (file.name.startsWith("_")) skip(kind, name, "hidden");
753
- else if (kind === "screenshot" && !SCREENSHOT_TYPES.has(type)) skip(kind, name, "type");
754
- else if (room[kind] === 0) skip(kind, name, KINDS[kind].limit);
755
1352
  else {
756
- room[kind] -= 1;
757
1353
  jobs.push({
758
1354
  id: item.id,
759
1355
  kind,
@@ -765,14 +1361,34 @@ async function startRun(passed, declared2) {
765
1361
  }
766
1362
  }
767
1363
  }
768
- let next = 0;
769
- await Promise.all(
770
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, jobs.length) }, async () => {
771
- while (next < jobs.length) await uploadOne(jobs[next++]);
772
- })
773
- );
1364
+ const started = Date.now();
1365
+ if (batchMissing) await uploadEach(jobs);
1366
+ else await uploadBatched(jobs);
1367
+ uploadMs += Date.now() - started;
1368
+ }
1369
+ const sending = /* @__PURE__ */ new Set();
1370
+ let sendError;
1371
+ let answered = false;
1372
+ async function dispatch(work) {
1373
+ while (sending.size >= (answered ? SEND_CONCURRENCY : 1)) await Promise.race(sending);
1374
+ const task = work().catch((err) => {
1375
+ sendError ??= err;
1376
+ }).finally(() => sending.delete(task));
1377
+ sending.add(task);
1378
+ }
1379
+ async function settle() {
1380
+ while (sending.size > 0) await Promise.all([...sending]);
1381
+ if (sendError !== void 0) {
1382
+ const err = sendError;
1383
+ sendError = void 0;
1384
+ throw err;
1385
+ }
774
1386
  }
775
1387
  async function flush() {
1388
+ await flushBuffer();
1389
+ await settle();
1390
+ }
1391
+ async function flushBuffer() {
776
1392
  if (buffer.length === 0) return;
777
1393
  const pending = buffer;
778
1394
  buffer = [];
@@ -780,6 +1396,9 @@ async function startRun(passed, declared2) {
780
1396
  defer(pending);
781
1397
  return;
782
1398
  }
1399
+ await dispatch(() => deliver(pending));
1400
+ }
1401
+ async function deliver(pending) {
783
1402
  await resolveKeys(pending.flatMap((p) => p.keys));
784
1403
  const submissions = [];
785
1404
  const unanswered = [];
@@ -802,6 +1421,9 @@ async function startRun(passed, declared2) {
802
1421
  progress();
803
1422
  return;
804
1423
  }
1424
+ await send(submissions, filesByKey);
1425
+ }
1426
+ async function send(submissions, filesByKey) {
805
1427
  for (const part of packed(submissions)) {
806
1428
  if (offline) {
807
1429
  defer(part);
@@ -809,7 +1431,8 @@ async function startRun(passed, declared2) {
809
1431
  }
810
1432
  const out = await client.post(
811
1433
  `/v1/runs/${runId}/results`,
812
- { results: part }
1434
+ // The job's combination on every batch (plune-ai/plune#1251); a refusal of it is a 422 said below as it came.
1435
+ { results: part, ...configuration !== void 0 ? { configuration } : {} }
813
1436
  );
814
1437
  const counts = out.ok ? out.body?.counts : void 0;
815
1438
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
@@ -817,6 +1440,7 @@ async function startRun(passed, declared2) {
817
1440
  for (const k of told) stats[k] += counts[k];
818
1441
  progress();
819
1442
  await upload(out.ok ? out.body?.items : void 0, filesByKey);
1443
+ answered = true;
820
1444
  continue;
821
1445
  }
822
1446
  if (out.ok) {
@@ -845,17 +1469,40 @@ async function startRun(passed, declared2) {
845
1469
  if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
846
1470
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
847
1471
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
848
- if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
849
- for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
850
- if (said !== void 0) parts.push(said);
1472
+ if (stats.created > 0) {
1473
+ const recorded = createdWithResult === stats.created && createdUndelivered === 0;
1474
+ parts.push(`${stats.created} added as cases (trusted source)${recorded ? " and their results recorded" : ""}`);
1475
+ }
1476
+ const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1477
+ const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1478
+ if (bucketSeen) {
1479
+ const other = sum("skipped") - noStorage;
1480
+ parts.push(
1481
+ `${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` : "")
1482
+ );
1483
+ } else {
1484
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
1485
+ if (said !== void 0) parts.push(said);
1486
+ }
1487
+ const other = stats.otherFiles;
1488
+ if (other.skipped > 0) parts.push(`${other.skipped} file(s) not stored (no bucket connected)`);
1489
+ if (other.failed > 0) parts.push(`${other.failed} file(s) failed to upload`);
851
1490
  }
852
1491
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
853
1492
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1493
+ const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1494
+ const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1495
+ if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1496
+ log(
1497
+ `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)`
1498
+ );
1499
+ }
854
1500
  log(`plune: ${parts.join(" \xB7 ")}`);
855
1501
  if (stats.deferred > 0 && process.env["GITHUB_ACTIONS"] === "true") {
856
1502
  log(`::warning::${stats.deferred} result(s) were not delivered to Plune \u2014 see the reporting step's log.`);
857
1503
  }
858
1504
  }
1505
+ const shardLines = [];
859
1506
  return {
860
1507
  get runId() {
861
1508
  return runId;
@@ -868,40 +1515,73 @@ async function startRun(passed, declared2) {
868
1515
  },
869
1516
  async add(result) {
870
1517
  buffer.push({ ...result, keys: bound(result.keys) });
871
- if (buffer.length >= batchSize) await flush();
1518
+ if (buffer.length >= batchSize) await flushBuffer();
872
1519
  },
873
1520
  flush,
874
1521
  async finish(reason) {
875
- if (done) return;
1522
+ if (done) return void 0;
876
1523
  done = true;
877
1524
  await flush();
878
1525
  await offer();
1526
+ let frozen;
879
1527
  if (runId !== null && !offline) {
880
1528
  const out = await client.post(`/v1/runs/${runId}/events`, {
881
1529
  event: "finish",
882
1530
  ...reason !== void 0 ? { reason } : {}
883
1531
  });
884
1532
  if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
885
- else if (typeof out.body?.detached === "number" && out.body.detached > 0) {
886
- log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1533
+ else {
1534
+ frozen = out.body?.summary ?? void 0;
1535
+ if (typeof out.body?.detached === "number" && out.body.detached > 0) {
1536
+ log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1537
+ }
887
1538
  }
888
1539
  }
889
1540
  summarise();
1541
+ return frozen;
890
1542
  },
891
- async leaveOpen() {
892
- if (done) return;
1543
+ shardLines,
1544
+ async leaveOpen(opts) {
1545
+ if (done) return void 0;
893
1546
  done = true;
894
1547
  await flush();
895
1548
  await offer();
896
- if (runId !== null) {
1549
+ let frozen;
1550
+ const after = [];
1551
+ const shard = env.shard;
1552
+ let counted = false;
1553
+ let mismatch;
1554
+ if (runId !== null && shard !== void 0 && !offline) {
1555
+ const out = await client.post(`/v1/runs/${runId}/events`, { event: "finish", shardIndex: shard.index, shardsExpected: shard.total });
1556
+ if (out.ok && typeof out.body?.shardsReported === "number") {
1557
+ counted = true;
1558
+ frozen = out.body.summary ?? void 0;
1559
+ const n = out.body.shardsExpected ?? shard.total;
1560
+ if (out.body.run?.statusEvent === "finished") after.push("plune: run closed");
1561
+ after.push(`plune: shard ${shard.index} of ${shard.total} done \u2014 ${out.body.shardsReported} of ${n} shards reported`);
1562
+ } else if (out.ok || out.kind === "invalid") {
1563
+ log('plune: the platform does not support shard auto-close yet \u2014 the run is left open for "plune run finish".');
1564
+ } else if (out.code === "shards_mismatch") {
1565
+ mismatch = new Error(
1566
+ `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.`
1567
+ );
1568
+ } else {
1569
+ 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}".`);
1570
+ }
1571
+ }
1572
+ if (runId !== null && !counted) {
897
1573
  log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
898
1574
  }
899
1575
  summarise();
1576
+ shardLines.push(...after);
1577
+ if (opts?.holdShardLines !== true) for (const line of after) log(line);
1578
+ if (mismatch !== void 0) throw mismatch;
1579
+ return frozen;
900
1580
  }
901
1581
  };
902
1582
  }
903
1583
  function sha256(input) {
904
- return (0, import_crypto2.createHash)("sha256").update(input, "utf8").digest("hex");
1584
+ return (0, import_crypto3.createHash)("sha256").update(input, "utf8").digest("hex");
905
1585
  }
906
1586
  var RESULT_KEY_MAX = 200;
907
1587
  var HASH_CHARS = 32;
@@ -925,16 +1605,19 @@ function titlesOf(test) {
925
1605
  }
926
1606
  return titles;
927
1607
  }
1608
+ function pathTitleOf(test) {
1609
+ return [fileOf2(test), ...titlesOf(test)].join("#");
1610
+ }
928
1611
  function keysFor(test) {
929
1612
  return [
930
1613
  { kind: "playwright-id", value: test.id },
931
- { kind: "path-title", value: [fileOf2(test), ...titlesOf(test)].join("#") }
1614
+ { kind: "path-title", value: pathTitleOf(test) }
932
1615
  ];
933
1616
  }
934
- var METADATA_TYPE2 = "application/plune.metadata+json";
1617
+ var METADATA_TYPE3 = "application/plune.metadata+json";
935
1618
  var TOKEN = /@P([A-Za-z0-9_-]+)/;
936
1619
  function metadataOf(result) {
937
- const found = result.attachments.find((a) => a.contentType === METADATA_TYPE2);
1620
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
938
1621
  if (found === void 0) return void 0;
939
1622
  try {
940
1623
  const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? (0, import_node_fs.readFileSync)(found.path, "utf8") : void 0;
@@ -943,12 +1626,32 @@ function metadataOf(result) {
943
1626
  return void 0;
944
1627
  }
945
1628
  }
946
- function statedIdOf(test, metadata) {
1629
+ function statedIdOf(test, metadata, mapped) {
947
1630
  const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
948
1631
  if (annotation !== void 0 && annotation !== "") return annotation;
949
1632
  const token = TOKEN.exec(test.title)?.[1];
950
1633
  if (token !== void 0) return token;
951
- return metadata?.id !== void 0 && metadata.id !== "" ? metadata.id : void 0;
1634
+ if (metadata?.id !== void 0 && metadata.id !== "") return metadata.id;
1635
+ return mapped;
1636
+ }
1637
+ function readIds(file) {
1638
+ let raw;
1639
+ try {
1640
+ raw = (0, import_node_fs.readFileSync)(file, "utf8");
1641
+ } catch {
1642
+ return {};
1643
+ }
1644
+ try {
1645
+ const parsed = JSON.parse(raw);
1646
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && Object.values(parsed).every((v) => typeof v === "string" && v !== ""))
1647
+ return parsed;
1648
+ } catch {
1649
+ }
1650
+ process.stderr.write(
1651
+ `plune: ${file} is not a JSON object of path-title to case id strings - ignored, tests resolve as if it were absent
1652
+ `
1653
+ );
1654
+ return {};
952
1655
  }
953
1656
  var NOT_FAILED = /* @__PURE__ */ new Set(["passed", "skipped"]);
954
1657
  function textOf(error) {
@@ -982,12 +1685,16 @@ function attemptOf(test, result, ctx) {
982
1685
  ...ctx.repoRoot !== void 0 ? { repoRoot: ctx.repoRoot } : {}
983
1686
  };
984
1687
  }
985
- function pendingFrom(test, result, ctx) {
1688
+ function pendingFrom(test, result, ctx, ids = {}) {
986
1689
  const metadata = metadataOf(result);
987
- const pluneId = statedIdOf(test, metadata);
1690
+ const pluneId = statedIdOf(
1691
+ test,
1692
+ metadata,
1693
+ Object.hasOwn(ids, pathTitleOf(test)) ? ids[pathTitleOf(test)] : void 0
1694
+ );
988
1695
  const expected = test.expectedStatus;
989
1696
  const attempt = attemptOf(test, result, ctx);
990
- const errorContext = errorContextOf(attempt);
1697
+ const errorContext = errorContextFields(attempt);
991
1698
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
992
1699
  const files = filesOf(attempt);
993
1700
  const startedAt = result.startTime;
@@ -1017,7 +1724,7 @@ function pendingFrom(test, result, ctx) {
1017
1724
  retry: result.retry,
1018
1725
  worker: String(result.workerIndex)
1019
1726
  },
1020
- ...errorContext !== "" ? { errorContext } : {},
1727
+ ...errorContext,
1021
1728
  ...failure !== void 0 ? { failure } : {},
1022
1729
  // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
1023
1730
  ...files.length > 0 ? { files } : {}
@@ -1035,6 +1742,8 @@ var PluneReporter = class {
1035
1742
  /** Kept whole: `metadata.ci` is written into it after `onConfigure`, so it is read at the run's opening. */
1036
1743
  config = null;
1037
1744
  context = {};
1745
+ /** The mapfile, read on the first result so a run that reports nothing never touches the disk. */
1746
+ ids = null;
1038
1747
  constructor(options = {}) {
1039
1748
  this.options = options;
1040
1749
  }
@@ -1087,7 +1796,10 @@ var PluneReporter = class {
1087
1796
  onTestEnd(test, result) {
1088
1797
  const session = this.open();
1089
1798
  this.chain = this.chain.then(async () => {
1090
- await (await session).add(pendingFrom(test, result, this.context));
1799
+ this.ids ??= readIds(
1800
+ (0, import_node_path.resolve)(this.options.idsFile ?? process.env["PLUNE_IDS_FILE"] ?? "plune/ids.json")
1801
+ );
1802
+ await (await session).add(pendingFrom(test, result, this.context, this.ids));
1091
1803
  }).catch((err) => this.giveUp(err));
1092
1804
  }
1093
1805
  async onEnd(_result) {