@flakiness/sdk 0.95.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.
@@ -0,0 +1,413 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/cmd-convert.ts
4
+ import fs3 from "fs/promises";
5
+ import path2 from "path";
6
+
7
+ // src/junit.ts
8
+ import { FlakinessReport as FK } from "@flakiness/report";
9
+ import { parseXml, XmlElement, XmlText } from "@rgrove/parse-xml";
10
+ import assert2 from "assert";
11
+ import fs2 from "fs";
12
+ import path from "path";
13
+
14
+ // src/utils.ts
15
+ import assert from "assert";
16
+ import { spawnSync } from "child_process";
17
+ import crypto from "crypto";
18
+ import fs from "fs";
19
+ import http from "http";
20
+ import https from "https";
21
+ import util from "util";
22
+ import zlib from "zlib";
23
+ var gzipAsync = util.promisify(zlib.gzip);
24
+ var gunzipAsync = util.promisify(zlib.gunzip);
25
+ var gunzipSync = zlib.gunzipSync;
26
+ var brotliCompressAsync = util.promisify(zlib.brotliCompress);
27
+ var brotliCompressSync = zlib.brotliCompressSync;
28
+ function sha1File(filePath) {
29
+ return new Promise((resolve, reject) => {
30
+ const hash = crypto.createHash("sha1");
31
+ const stream = fs.createReadStream(filePath);
32
+ stream.on("data", (chunk) => {
33
+ hash.update(chunk);
34
+ });
35
+ stream.on("end", () => {
36
+ resolve(hash.digest("hex"));
37
+ });
38
+ stream.on("error", (err) => {
39
+ reject(err);
40
+ });
41
+ });
42
+ }
43
+ function sha1Buffer(data) {
44
+ const hash = crypto.createHash("sha1");
45
+ hash.update(data);
46
+ return hash.digest("hex");
47
+ }
48
+ async function retryWithBackoff(job, backoff = []) {
49
+ for (const timeout of backoff) {
50
+ try {
51
+ return await job();
52
+ } catch (e) {
53
+ if (e instanceof AggregateError)
54
+ console.error(`[flakiness.io err]`, e.errors[0].message);
55
+ else if (e instanceof Error)
56
+ console.error(`[flakiness.io err]`, e.message);
57
+ else
58
+ console.error(`[flakiness.io err]`, e);
59
+ await new Promise((x) => setTimeout(x, timeout));
60
+ }
61
+ }
62
+ return await job();
63
+ }
64
+ var httpUtils;
65
+ ((httpUtils2) => {
66
+ function createRequest({ url, method = "get", headers = {} }) {
67
+ let resolve;
68
+ let reject;
69
+ const responseDataPromise = new Promise((a, b) => {
70
+ resolve = a;
71
+ reject = b;
72
+ });
73
+ const protocol = url.startsWith("https") ? https : http;
74
+ const request = protocol.request(url, { method, headers }, (res) => {
75
+ const chunks = [];
76
+ res.on("data", (chunk) => chunks.push(chunk));
77
+ res.on("end", () => {
78
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300)
79
+ resolve(Buffer.concat(chunks));
80
+ else
81
+ reject(new Error(`Request to ${url} failed with ${res.statusCode}`));
82
+ });
83
+ res.on("error", (error) => reject(error));
84
+ });
85
+ request.on("error", reject);
86
+ return { request, responseDataPromise };
87
+ }
88
+ httpUtils2.createRequest = createRequest;
89
+ async function getBuffer(url, backoff) {
90
+ return await retryWithBackoff(async () => {
91
+ const { request, responseDataPromise } = createRequest({ url });
92
+ request.end();
93
+ return await responseDataPromise;
94
+ }, backoff);
95
+ }
96
+ httpUtils2.getBuffer = getBuffer;
97
+ async function getText(url, backoff) {
98
+ const buffer = await getBuffer(url, backoff);
99
+ return buffer.toString("utf-8");
100
+ }
101
+ httpUtils2.getText = getText;
102
+ async function getJSON(url) {
103
+ return JSON.parse(await getText(url));
104
+ }
105
+ httpUtils2.getJSON = getJSON;
106
+ async function postText(url, text, backoff) {
107
+ const headers = {
108
+ "Content-Type": "application/json",
109
+ "Content-Length": Buffer.byteLength(text) + ""
110
+ };
111
+ return await retryWithBackoff(async () => {
112
+ const { request, responseDataPromise } = createRequest({ url, headers, method: "post" });
113
+ request.write(text);
114
+ request.end();
115
+ return await responseDataPromise;
116
+ }, backoff);
117
+ }
118
+ httpUtils2.postText = postText;
119
+ async function postJSON(url, json, backoff) {
120
+ const buffer = await postText(url, JSON.stringify(json), backoff);
121
+ return JSON.parse(buffer.toString("utf-8"));
122
+ }
123
+ httpUtils2.postJSON = postJSON;
124
+ })(httpUtils || (httpUtils = {}));
125
+ var ansiRegex = new RegExp("[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", "g");
126
+ function shell(command, args, options) {
127
+ try {
128
+ const result = spawnSync(command, args, { encoding: "utf-8", ...options });
129
+ if (result.status !== 0) {
130
+ console.log(result);
131
+ console.log(options);
132
+ return void 0;
133
+ }
134
+ return result.stdout.trim();
135
+ } catch (e) {
136
+ console.log(e);
137
+ return void 0;
138
+ }
139
+ }
140
+ function gitCommitInfo(gitRepo) {
141
+ const sha = shell(`git`, ["rev-parse", "HEAD"], {
142
+ cwd: gitRepo,
143
+ encoding: "utf-8"
144
+ });
145
+ assert(sha, `FAILED: git rev-parse HEAD @ ${gitRepo}`);
146
+ return sha.trim();
147
+ }
148
+ var IS_WIN32_PATH = new RegExp("^[a-zA-Z]:\\\\", "i");
149
+ var IS_ALMOST_POSIX_PATH = new RegExp("^[a-zA-Z]:/", "i");
150
+
151
+ // src/junit.ts
152
+ function getProperties(element) {
153
+ const propertiesNodes = element.children.filter((node) => node instanceof XmlElement).filter((node) => node.name === "properties");
154
+ if (!propertiesNodes.length)
155
+ return [];
156
+ const result = [];
157
+ for (const propertiesNode of propertiesNodes) {
158
+ const properties = propertiesNode.children.filter((node) => node instanceof XmlElement).filter((node) => node.name === "property");
159
+ for (const property of properties) {
160
+ const name = property.attributes["name"];
161
+ const innerText = property.children.find((node) => node instanceof XmlText);
162
+ const value = property.attributes["value"] ?? innerText?.text ?? "";
163
+ result.push([name, value]);
164
+ }
165
+ }
166
+ return result;
167
+ }
168
+ function extractErrors(testcase) {
169
+ const xmlErrors = testcase.children.filter((e) => e instanceof XmlElement).filter((element) => element.name === "error" || element.name === "failure");
170
+ if (!xmlErrors.length)
171
+ return void 0;
172
+ const errors = [];
173
+ for (const xmlErr of xmlErrors) {
174
+ const message = [xmlErr.attributes["type"], xmlErr.attributes["message"]].filter((x) => !!x).join(" ");
175
+ const xmlStackNodes = xmlErr.children.filter((child) => child instanceof XmlText);
176
+ const stack = xmlStackNodes ? xmlStackNodes.map((node) => node.text).join("\n") : void 0;
177
+ errors.push({
178
+ message,
179
+ stack
180
+ });
181
+ }
182
+ return errors;
183
+ }
184
+ function extractStdout(testcase, stdio) {
185
+ const xmlStdio = testcase.children.filter((e) => e instanceof XmlElement).filter((element) => element.name === stdio);
186
+ if (!xmlStdio.length)
187
+ return void 0;
188
+ return xmlStdio.map((node) => node.children.filter((node2) => node2 instanceof XmlText)).flat().map((txtNode) => ({
189
+ text: txtNode.text
190
+ }));
191
+ }
192
+ async function parseAttachment(value) {
193
+ let absolutePath = path.resolve(process.cwd(), value);
194
+ if (fs2.existsSync(absolutePath)) {
195
+ const id = await sha1File(absolutePath);
196
+ return {
197
+ contentType: "image/png",
198
+ path: absolutePath,
199
+ id
200
+ };
201
+ }
202
+ return {
203
+ contentType: "text/plain",
204
+ id: sha1Buffer(value),
205
+ body: Buffer.from(value)
206
+ };
207
+ }
208
+ async function traverseJUnitReport(context, node) {
209
+ const element = node;
210
+ if (!(element instanceof XmlElement))
211
+ return;
212
+ let { currentEnv, currentEnvIndex, currentSuite, report, currentTimeMs, attachments } = context;
213
+ if (element.attributes["timestamp"])
214
+ currentTimeMs = new Date(element.attributes["timestamp"]).getTime();
215
+ if (element.name === "testsuite") {
216
+ const file = element.attributes["file"];
217
+ const line = parseInt(element.attributes["line"], 10);
218
+ const name = element.attributes["name"];
219
+ const newSuite = {
220
+ title: name ?? file,
221
+ location: file && !isNaN(line) ? {
222
+ file,
223
+ line,
224
+ column: 1
225
+ } : FK.NO_LOCATION,
226
+ type: name ? "suite" : file ? "file" : "anonymous suite",
227
+ suites: [],
228
+ tests: []
229
+ };
230
+ if (currentSuite) {
231
+ currentSuite.suites ??= [];
232
+ currentSuite.suites.push(newSuite);
233
+ } else {
234
+ report.suites.push(newSuite);
235
+ }
236
+ currentSuite = newSuite;
237
+ const userSuppliedData = getProperties(element);
238
+ if (userSuppliedData.length) {
239
+ currentEnv = structuredClone(currentEnv);
240
+ currentEnv.userSuppliedData ??= {};
241
+ for (const [key, value] of userSuppliedData)
242
+ currentEnv.userSuppliedData[key] = value;
243
+ currentEnvIndex = report.environments.push(currentEnv) - 1;
244
+ }
245
+ } else if (element.name === "testcase") {
246
+ assert2(currentSuite);
247
+ const file = element.attributes["file"];
248
+ const name = element.attributes["name"];
249
+ const line = parseInt(element.attributes["line"], 10);
250
+ const timeMs = parseFloat(element.attributes["time"]) * 1e3;
251
+ const startTimestamp = currentTimeMs;
252
+ const duration = timeMs;
253
+ currentTimeMs += timeMs;
254
+ const annotations = [];
255
+ const attachments2 = [];
256
+ for (const [key, value] of getProperties(element)) {
257
+ if (key.toLowerCase().startsWith("attachment")) {
258
+ if (context.ignoreAttachments)
259
+ continue;
260
+ const attachment = await parseAttachment(value);
261
+ context.attachments.set(attachment.id, attachment);
262
+ attachments2.push({
263
+ id: attachment.id,
264
+ contentType: attachment.contentType,
265
+ //TODO: better default names for attachments?
266
+ name: attachment.path ? path.basename(attachment.path) : `attachment`
267
+ });
268
+ } else {
269
+ annotations.push({
270
+ type: key,
271
+ description: value.length ? value : void 0
272
+ });
273
+ }
274
+ }
275
+ const childElements = element.children.filter((child) => child instanceof XmlElement);
276
+ const xmlSkippedAnnotation = childElements.find((child) => child.name === "skipped");
277
+ if (xmlSkippedAnnotation)
278
+ annotations.push({ type: "skipped", description: xmlSkippedAnnotation.attributes["message"] });
279
+ const expectedStatus = xmlSkippedAnnotation ? "skipped" : "passed";
280
+ const errors = extractErrors(element);
281
+ const test = {
282
+ title: name,
283
+ location: file && !isNaN(line) ? {
284
+ file,
285
+ line,
286
+ column: 1
287
+ } : FK.NO_LOCATION,
288
+ attempts: [{
289
+ environmentIdx: currentEnvIndex,
290
+ expectedStatus,
291
+ annotations,
292
+ attachments: attachments2,
293
+ startTimestamp,
294
+ duration,
295
+ status: xmlSkippedAnnotation ? "skipped" : errors ? "failed" : "passed",
296
+ errors,
297
+ stdout: extractStdout(element, "system-out"),
298
+ stderr: extractStdout(element, "system-err")
299
+ }]
300
+ };
301
+ currentSuite.tests ??= [];
302
+ currentSuite.tests.push(test);
303
+ }
304
+ context = { ...context, currentEnv, currentEnvIndex, currentSuite, currentTimeMs };
305
+ for (const child of element.children)
306
+ await traverseJUnitReport(context, child);
307
+ }
308
+ async function parseJUnit(xmls, options) {
309
+ const report = {
310
+ category: "junit",
311
+ commitId: options.commitId,
312
+ duration: options.runDuration,
313
+ startTimestamp: options.runStartTimestamp,
314
+ url: options.runUrl,
315
+ environments: [options.defaultEnv],
316
+ suites: [],
317
+ unattributedErrors: []
318
+ };
319
+ const context = {
320
+ currentEnv: options.defaultEnv,
321
+ currentEnvIndex: 0,
322
+ currentTimeMs: 0,
323
+ report,
324
+ currentSuite: void 0,
325
+ attachments: /* @__PURE__ */ new Map(),
326
+ ignoreAttachments: !!options.ignoreAttachments
327
+ };
328
+ for (const xml of xmls) {
329
+ const doc = parseXml(xml);
330
+ for (const element of doc.children)
331
+ await traverseJUnitReport(context, element);
332
+ }
333
+ return {
334
+ report: FK.dedupeSuitesTestsEnvironments(report),
335
+ attachments: Array.from(context.attachments.values())
336
+ };
337
+ }
338
+
339
+ // src/cli/cmd-convert.ts
340
+ async function cmdConvert(junitPath, options) {
341
+ const fullPath = path2.resolve(junitPath);
342
+ if (!await fs3.access(fullPath, fs3.constants.F_OK).then(() => true).catch(() => false)) {
343
+ console.error(`Error: path ${fullPath} is not accessible`);
344
+ process.exit(1);
345
+ }
346
+ const stat = await fs3.stat(fullPath);
347
+ let xmlContents = [];
348
+ if (stat.isFile()) {
349
+ const xmlContent = await fs3.readFile(fullPath, "utf-8");
350
+ xmlContents.push(xmlContent);
351
+ } else if (stat.isDirectory()) {
352
+ const xmlFiles = await findXmlFiles(fullPath);
353
+ if (xmlFiles.length === 0) {
354
+ console.error(`Error: No XML files found in directory ${fullPath}`);
355
+ process.exit(1);
356
+ }
357
+ console.log(`Found ${xmlFiles.length} XML files`);
358
+ for (const xmlFile of xmlFiles) {
359
+ const xmlContent = await fs3.readFile(xmlFile, "utf-8");
360
+ xmlContents.push(xmlContent);
361
+ }
362
+ } else {
363
+ console.error(`Error: ${fullPath} is neither a file nor a directory`);
364
+ process.exit(1);
365
+ }
366
+ let commitId;
367
+ if (options.commitId) {
368
+ commitId = options.commitId;
369
+ } else {
370
+ try {
371
+ commitId = gitCommitInfo(process.cwd());
372
+ } catch (e) {
373
+ console.error("Failed to get git commit info. Please provide --commit-id option.");
374
+ process.exit(1);
375
+ }
376
+ }
377
+ const { report, attachments } = await parseJUnit(xmlContents, {
378
+ commitId,
379
+ defaultEnv: { name: options.envName },
380
+ runStartTimestamp: Date.now(),
381
+ runDuration: 0
382
+ });
383
+ await fs3.writeFile("fkreport.json", JSON.stringify(report, null, 2));
384
+ console.log("\u2713 Saved report to fkreport.json");
385
+ if (attachments.length > 0) {
386
+ await fs3.mkdir("fkattachments", { recursive: true });
387
+ for (const attachment of attachments) {
388
+ if (attachment.path) {
389
+ const destPath = path2.join("fkattachments", attachment.id);
390
+ await fs3.copyFile(attachment.path, destPath);
391
+ } else if (attachment.body) {
392
+ const destPath = path2.join("fkattachments", attachment.id);
393
+ await fs3.writeFile(destPath, attachment.body);
394
+ }
395
+ }
396
+ console.log(`\u2713 Saved ${attachments.length} attachments to fkattachments/`);
397
+ }
398
+ }
399
+ async function findXmlFiles(dir, result = []) {
400
+ const entries = await fs3.readdir(dir, { withFileTypes: true });
401
+ for (const entry of entries) {
402
+ const fullPath = path2.join(dir, entry.name);
403
+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".xml"))
404
+ result.push(fullPath);
405
+ else if (entry.isDirectory())
406
+ await findXmlFiles(fullPath, result);
407
+ }
408
+ return result;
409
+ }
410
+ export {
411
+ cmdConvert
412
+ };
413
+ //# sourceMappingURL=cmd-convert.js.map