loadam 0.3.0 → 0.4.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/README.md +25 -5
- package/dist/bin.js +2482 -1145
- package/dist/bin.js.map +1 -1
- package/dist/index.js +2482 -1145
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -430,8 +430,8 @@ async function listSessions(outRoot) {
|
|
|
430
430
|
return [];
|
|
431
431
|
}
|
|
432
432
|
const metas = [];
|
|
433
|
-
for (const
|
|
434
|
-
const meta = await loadMeta(join(root,
|
|
433
|
+
for (const entry2 of entries) {
|
|
434
|
+
const meta = await loadMeta(join(root, entry2));
|
|
435
435
|
if (meta) metas.push(meta);
|
|
436
436
|
}
|
|
437
437
|
return metas.sort((a, b) => a.startedAt < b.startedAt ? 1 : -1);
|
|
@@ -685,7 +685,7 @@ function registerCompletionCommand(program) {
|
|
|
685
685
|
|
|
686
686
|
// src/commands/contract.ts
|
|
687
687
|
import { mkdir as mkdir2, readFile as readFile6, writeFile as writeFile2 } from "fs/promises";
|
|
688
|
-
import { dirname as dirname2, join as join3, resolve as
|
|
688
|
+
import { dirname as dirname2, join as join3, resolve as resolve6 } from "path";
|
|
689
689
|
|
|
690
690
|
// ../core/dist/index.js
|
|
691
691
|
import { z } from "zod";
|
|
@@ -760,6 +760,32 @@ var AuthProfile = z.discriminatedUnion("kind", [
|
|
|
760
760
|
id: z.string(),
|
|
761
761
|
kind: z.literal("custom"),
|
|
762
762
|
signerRef: z.string()
|
|
763
|
+
}),
|
|
764
|
+
/**
|
|
765
|
+
* A token (or session cookie) obtained by calling one of the API's own
|
|
766
|
+
* operations, e.g. POST /auth/login {email, password} → {token}.
|
|
767
|
+
* Detected from the spec or declared in loadam.config.json.
|
|
768
|
+
*/
|
|
769
|
+
z.object({
|
|
770
|
+
id: z.string(),
|
|
771
|
+
kind: z.literal("login"),
|
|
772
|
+
/** The operation that logs in. */
|
|
773
|
+
operationId: z.string(),
|
|
774
|
+
/** Request body. Values may hold `${ENV_VAR}` placeholders, filled in at runtime. */
|
|
775
|
+
body: z.record(z.string(), z.string()),
|
|
776
|
+
/** Dotted path to the token in the response ("token", "data.access_token"). Absent: cookie session. */
|
|
777
|
+
tokenPath: z.string().optional(),
|
|
778
|
+
/** Dotted path to a lifetime in seconds. Default: `expires_in`, then the JWT `exp` claim. */
|
|
779
|
+
expiresInPath: z.string().optional(),
|
|
780
|
+
/** Where the token goes on later requests. Default: `Authorization: Bearer {token}`. */
|
|
781
|
+
apply: z.object({
|
|
782
|
+
in: z.enum(["header", "query", "cookie"]),
|
|
783
|
+
name: z.string(),
|
|
784
|
+
format: z.string()
|
|
785
|
+
}).optional(),
|
|
786
|
+
/** The security scheme this login supplies credentials for. Absent: every gated op. */
|
|
787
|
+
scheme: z.string().optional(),
|
|
788
|
+
source: z.enum(["detected", "config"]).optional()
|
|
763
789
|
})
|
|
764
790
|
]);
|
|
765
791
|
var AuthRef = z.object({
|
|
@@ -826,7 +852,14 @@ var Operation = z.object({
|
|
|
826
852
|
cookieParams: z.array(Param).default([]),
|
|
827
853
|
body: RequestBody.optional(),
|
|
828
854
|
responses: z.array(ResponseDef).default([]),
|
|
855
|
+
/** Every scheme the operation mentions, flattened. Kept for compatibility; prefer securityRequirements. */
|
|
829
856
|
security: z.array(AuthRef).default([]),
|
|
857
|
+
/**
|
|
858
|
+
* OpenAPI's security requirement as written: any one inner list satisfies it,
|
|
859
|
+
* and every scheme in that list is needed. `[]` means the operation is public.
|
|
860
|
+
* Absent: the spec declares no security for it (top-level or per operation).
|
|
861
|
+
*/
|
|
862
|
+
securityRequirements: z.array(z.array(AuthRef)).optional(),
|
|
830
863
|
servers: z.array(Server).optional(),
|
|
831
864
|
// Inferred
|
|
832
865
|
resourceKind: z.string().optional(),
|
|
@@ -1101,6 +1134,7 @@ function extractOperations(doc) {
|
|
|
1101
1134
|
body: extractRequestBody(opObj.requestBody),
|
|
1102
1135
|
responses: extractResponses(opObj.responses ?? {}),
|
|
1103
1136
|
security: extractSecurityRefs(opObj.security ?? doc.security),
|
|
1137
|
+
securityRequirements: extractRequirements(opObj.security ?? doc.security),
|
|
1104
1138
|
safety,
|
|
1105
1139
|
idempotency: method === "GET" || method === "HEAD" ? "idempotent" : "unknown"
|
|
1106
1140
|
});
|
|
@@ -1154,9 +1188,16 @@ function extractResponses(responses) {
|
|
|
1154
1188
|
examples: media.example !== void 0 ? [media.example] : void 0
|
|
1155
1189
|
};
|
|
1156
1190
|
}
|
|
1191
|
+
const headers = Object.entries(resp.headers ?? {}).filter(([, h]) => !isRef(h)).map(([name, h]) => ({
|
|
1192
|
+
name,
|
|
1193
|
+
schema: schemaFromAny(h.schema ?? { type: "string" }),
|
|
1194
|
+
required: !!h.required,
|
|
1195
|
+
description: h.description
|
|
1196
|
+
}));
|
|
1157
1197
|
out.push({
|
|
1158
1198
|
status: numericStatus,
|
|
1159
1199
|
description: resp.description,
|
|
1200
|
+
headers: headers.length > 0 ? headers : void 0,
|
|
1160
1201
|
contentTypes: Object.keys(contentTypes).length > 0 ? contentTypes : void 0
|
|
1161
1202
|
});
|
|
1162
1203
|
}
|
|
@@ -1165,13 +1206,22 @@ function extractResponses(responses) {
|
|
|
1165
1206
|
function extractSecurityRefs(security) {
|
|
1166
1207
|
if (!security) return [];
|
|
1167
1208
|
const refs = [];
|
|
1168
|
-
for (const
|
|
1169
|
-
for (const [profileId, scopes] of Object.entries(
|
|
1209
|
+
for (const entry2 of security) {
|
|
1210
|
+
for (const [profileId, scopes] of Object.entries(entry2)) {
|
|
1170
1211
|
refs.push({ profileId, scopes: scopes.length > 0 ? scopes : void 0 });
|
|
1171
1212
|
}
|
|
1172
1213
|
}
|
|
1173
1214
|
return refs;
|
|
1174
1215
|
}
|
|
1216
|
+
function extractRequirements(security) {
|
|
1217
|
+
if (!security) return void 0;
|
|
1218
|
+
return security.map(
|
|
1219
|
+
(entry2) => Object.entries(entry2).map(([profileId, scopes]) => ({
|
|
1220
|
+
profileId,
|
|
1221
|
+
scopes: scopes.length > 0 ? scopes : void 0
|
|
1222
|
+
}))
|
|
1223
|
+
);
|
|
1224
|
+
}
|
|
1175
1225
|
function inferSafety(method) {
|
|
1176
1226
|
if (method === "GET" || method === "HEAD" || method === "OPTIONS") return "safe";
|
|
1177
1227
|
if (method === "DELETE") return "destructive";
|
|
@@ -1183,14 +1233,14 @@ function isRef(v) {
|
|
|
1183
1233
|
|
|
1184
1234
|
// ../graph/dist/index.js
|
|
1185
1235
|
function bodyProperties(ir, schema) {
|
|
1186
|
-
const
|
|
1236
|
+
const resolve22 = (s) => {
|
|
1187
1237
|
if (typeof s === "string") return ir.schemas[s]?.jsonSchema;
|
|
1188
1238
|
if (!s || typeof s !== "object") return void 0;
|
|
1189
1239
|
const js = "jsonSchema" in s ? s.jsonSchema : s;
|
|
1190
1240
|
if (js?.$ref) return ir.schemas[js.$ref]?.jsonSchema;
|
|
1191
1241
|
return js;
|
|
1192
1242
|
};
|
|
1193
|
-
return
|
|
1243
|
+
return resolve22(schema)?.properties ?? {};
|
|
1194
1244
|
}
|
|
1195
1245
|
function isScalar(p) {
|
|
1196
1246
|
if (p.$ref) return false;
|
|
@@ -1206,8 +1256,8 @@ function detectBodyRef(field, prop, kinds, ownKind) {
|
|
|
1206
1256
|
if (!isScalar(prop)) return void 0;
|
|
1207
1257
|
const m = field.match(/^([a-zA-Z][a-zA-Z0-9]*?)(Id|_id|ID|Uuid|_uuid|Ref|_ref)$/) ?? field.match(/^([a-zA-Z][a-zA-Z0-9_]*)$/);
|
|
1208
1258
|
if (m?.[1]) {
|
|
1209
|
-
const
|
|
1210
|
-
const kind = byLower.get(
|
|
1259
|
+
const candidate2 = m[1].replace(/_/g, "").toLowerCase();
|
|
1260
|
+
const kind = byLower.get(candidate2);
|
|
1211
1261
|
if (kind && kind !== ownKind) return { field, kind, via: "name" };
|
|
1212
1262
|
}
|
|
1213
1263
|
const text = `${prop.description ?? ""} ${prop.title ?? ""}`.toLowerCase();
|
|
@@ -1250,6 +1300,166 @@ function addBodyRef(op, ref, edges) {
|
|
|
1250
1300
|
});
|
|
1251
1301
|
}
|
|
1252
1302
|
}
|
|
1303
|
+
var PATH_RE = /(^|[^a-z])(log-?in|sign-?in|sessions?|auth|authenticate|tokens?)([^a-z]|$)/i;
|
|
1304
|
+
var ID_RE = /log-?in|sign-?in|authenticate|create_?session|(create|get|issue)_?token/i;
|
|
1305
|
+
var NOT_LOGIN_RE = /refresh|log-?out|sign-?out|register|sign-?up|reset|forgot|verify|otp|mfa|revoke/i;
|
|
1306
|
+
var PASSWORD_RE = /^(password|pass|passwd|pwd|secret)$/i;
|
|
1307
|
+
var USER_RE = /^(email|e_?mail|username|user_?name|user|login|identifier|phone)$/i;
|
|
1308
|
+
var TOKEN_FIELDS = [
|
|
1309
|
+
"access_token",
|
|
1310
|
+
"accessToken",
|
|
1311
|
+
"token",
|
|
1312
|
+
"jwt",
|
|
1313
|
+
"auth_token",
|
|
1314
|
+
"authToken",
|
|
1315
|
+
"session_token",
|
|
1316
|
+
"sessionToken",
|
|
1317
|
+
"id_token",
|
|
1318
|
+
"idToken"
|
|
1319
|
+
];
|
|
1320
|
+
var EXPIRES_FIELDS = ["expires_in", "expiresIn", "ttl"];
|
|
1321
|
+
var ENVELOPES = ["data", "result", "session", "auth", "tokens", "payload"];
|
|
1322
|
+
var LOGIN_ENV = { user: "API_USER", pass: "API_PASS" };
|
|
1323
|
+
function findLoginCandidates(ir) {
|
|
1324
|
+
const out = [];
|
|
1325
|
+
for (const op of ir.operations) {
|
|
1326
|
+
const c = candidate(ir, op);
|
|
1327
|
+
if (c) out.push(c);
|
|
1328
|
+
}
|
|
1329
|
+
return out;
|
|
1330
|
+
}
|
|
1331
|
+
function detectLogin(ir) {
|
|
1332
|
+
const candidates = findLoginCandidates(ir);
|
|
1333
|
+
if (ir.auth.some((p) => p.kind === "login")) return { candidates };
|
|
1334
|
+
if (candidates.length === 0) return { candidates };
|
|
1335
|
+
if (candidates.length > 1)
|
|
1336
|
+
return {
|
|
1337
|
+
candidates,
|
|
1338
|
+
reason: `${candidates.length} operations look like logins (${candidates.map((c2) => c2.operationId).join(", ")})`
|
|
1339
|
+
};
|
|
1340
|
+
const c = candidates[0];
|
|
1341
|
+
const target = schemeFor(ir, c);
|
|
1342
|
+
if (target === null)
|
|
1343
|
+
return {
|
|
1344
|
+
candidates,
|
|
1345
|
+
reason: "the spec has several security schemes, so it is unclear which one the token is for"
|
|
1346
|
+
};
|
|
1347
|
+
const added = {
|
|
1348
|
+
id: "login",
|
|
1349
|
+
kind: "login",
|
|
1350
|
+
operationId: c.operationId,
|
|
1351
|
+
body: c.body,
|
|
1352
|
+
tokenPath: c.tokenPath,
|
|
1353
|
+
expiresInPath: c.expiresInPath,
|
|
1354
|
+
scheme: target,
|
|
1355
|
+
source: "detected"
|
|
1356
|
+
};
|
|
1357
|
+
ir.auth.push(added);
|
|
1358
|
+
return { candidates, added };
|
|
1359
|
+
}
|
|
1360
|
+
function schemeFor(ir, c) {
|
|
1361
|
+
const profiles = ir.auth.filter((p) => p.kind !== "none");
|
|
1362
|
+
if (c.cookie) {
|
|
1363
|
+
const cookieKeys = profiles.filter((p) => p.kind === "apiKey" && p.in === "cookie");
|
|
1364
|
+
if (cookieKeys.length === 1) return cookieKeys[0].id;
|
|
1365
|
+
return profiles.length === 0 ? void 0 : cookieKeys.length === 0 ? void 0 : null;
|
|
1366
|
+
}
|
|
1367
|
+
const bearer = profiles.filter((p) => p.kind === "bearer");
|
|
1368
|
+
if (bearer.length === 1) return bearer[0].id;
|
|
1369
|
+
if (bearer.length > 1) return null;
|
|
1370
|
+
const keys = profiles.filter((p) => p.kind === "apiKey" && p.in !== "cookie");
|
|
1371
|
+
if (keys.length === 1) return keys[0].id;
|
|
1372
|
+
return profiles.length === 0 ? void 0 : null;
|
|
1373
|
+
}
|
|
1374
|
+
function candidate(ir, op) {
|
|
1375
|
+
if (op.method !== "POST") return null;
|
|
1376
|
+
const req = op.securityRequirements;
|
|
1377
|
+
if (req && req.length > 0 && !req.some((s) => s.length === 0)) return null;
|
|
1378
|
+
const named = PATH_RE.test(op.path) || ID_RE.test(op.id);
|
|
1379
|
+
if (!named || NOT_LOGIN_RE.test(op.path) || NOT_LOGIN_RE.test(op.id)) return null;
|
|
1380
|
+
const media = Object.entries(op.body?.contentTypes ?? {}).find(
|
|
1381
|
+
([ct]) => ct.includes("json") || ct.startsWith("application/x-www-form-urlencoded")
|
|
1382
|
+
);
|
|
1383
|
+
if (!media) return null;
|
|
1384
|
+
const reqSchema = resolve4(ir, media[1].schema);
|
|
1385
|
+
const props = properties(ir, reqSchema);
|
|
1386
|
+
const names = Object.keys(props);
|
|
1387
|
+
const pass = names.find((n) => PASSWORD_RE.test(n));
|
|
1388
|
+
const user = names.find((n) => USER_RE.test(n));
|
|
1389
|
+
if (!pass || !user) return null;
|
|
1390
|
+
const body = {
|
|
1391
|
+
[user]: `\${${LOGIN_ENV.user}}`,
|
|
1392
|
+
[pass]: `\${${LOGIN_ENV.pass}}`
|
|
1393
|
+
};
|
|
1394
|
+
for (const name of required(ir, reqSchema)) {
|
|
1395
|
+
if (name in body) continue;
|
|
1396
|
+
const p = resolve4(ir, props[name]);
|
|
1397
|
+
const v = p?.default ?? (p?.enum?.length === 1 ? p.enum[0] : void 0) ?? p?.example;
|
|
1398
|
+
if (v === void 0 || typeof v === "object") return null;
|
|
1399
|
+
body[name] = String(v);
|
|
1400
|
+
}
|
|
1401
|
+
for (const r of op.responses) {
|
|
1402
|
+
if (typeof r.status !== "number" || r.status < 200 || r.status >= 300) continue;
|
|
1403
|
+
const json = Object.entries(r.contentTypes ?? {}).find(([ct]) => ct.includes("json"));
|
|
1404
|
+
const found = json ? tokenIn(ir, resolve4(ir, json[1].schema)) : void 0;
|
|
1405
|
+
if (found)
|
|
1406
|
+
return {
|
|
1407
|
+
operationId: op.id,
|
|
1408
|
+
method: op.method,
|
|
1409
|
+
path: op.path,
|
|
1410
|
+
body,
|
|
1411
|
+
tokenPath: found.tokenPath,
|
|
1412
|
+
expiresInPath: found.expiresInPath,
|
|
1413
|
+
cookie: false
|
|
1414
|
+
};
|
|
1415
|
+
if (r.headers?.some((h) => h.name.toLowerCase() === "set-cookie"))
|
|
1416
|
+
return { operationId: op.id, method: op.method, path: op.path, body, cookie: true };
|
|
1417
|
+
}
|
|
1418
|
+
return null;
|
|
1419
|
+
}
|
|
1420
|
+
function tokenIn(ir, schema) {
|
|
1421
|
+
const at = (s, prefix) => {
|
|
1422
|
+
const props2 = properties(ir, s);
|
|
1423
|
+
const token = TOKEN_FIELDS.find((f) => f in props2 && isString(ir, props2[f]));
|
|
1424
|
+
if (!token) return void 0;
|
|
1425
|
+
const exp = EXPIRES_FIELDS.find((f) => f in props2);
|
|
1426
|
+
return {
|
|
1427
|
+
tokenPath: prefix + token,
|
|
1428
|
+
expiresInPath: exp ? prefix + exp : void 0
|
|
1429
|
+
};
|
|
1430
|
+
};
|
|
1431
|
+
const top = at(schema, "");
|
|
1432
|
+
if (top) return top;
|
|
1433
|
+
const props = properties(ir, schema);
|
|
1434
|
+
for (const env of ENVELOPES) {
|
|
1435
|
+
if (!(env in props)) continue;
|
|
1436
|
+
const inner = at(resolve4(ir, props[env]), `${env}.`);
|
|
1437
|
+
if (inner) return inner;
|
|
1438
|
+
}
|
|
1439
|
+
return void 0;
|
|
1440
|
+
}
|
|
1441
|
+
function isString(ir, p) {
|
|
1442
|
+
const r = resolve4(ir, p);
|
|
1443
|
+
if (!r || r.type === void 0) return true;
|
|
1444
|
+
return Array.isArray(r.type) ? r.type.includes("string") : r.type === "string";
|
|
1445
|
+
}
|
|
1446
|
+
function resolve4(ir, s, depth = 0) {
|
|
1447
|
+
if (s === void 0 || depth > 8) return void 0;
|
|
1448
|
+
if (typeof s === "string") return resolve4(ir, ir.schemas[s]?.jsonSchema, depth + 1);
|
|
1449
|
+
const js = "jsonSchema" in s ? s.jsonSchema : s;
|
|
1450
|
+
if (js?.$ref) return resolve4(ir, ir.schemas[js.$ref]?.jsonSchema, depth + 1);
|
|
1451
|
+
return js;
|
|
1452
|
+
}
|
|
1453
|
+
function properties(ir, s) {
|
|
1454
|
+
if (!s) return {};
|
|
1455
|
+
const own = { ...s.properties ?? {} };
|
|
1456
|
+
for (const part of s.allOf ?? []) Object.assign(own, properties(ir, resolve4(ir, part)));
|
|
1457
|
+
return own;
|
|
1458
|
+
}
|
|
1459
|
+
function required(ir, s) {
|
|
1460
|
+
if (!s) return [];
|
|
1461
|
+
return [...s.required ?? [], ...(s.allOf ?? []).flatMap((p) => required(ir, resolve4(ir, p)))];
|
|
1462
|
+
}
|
|
1253
1463
|
var IRREGULAR = {
|
|
1254
1464
|
people: "person",
|
|
1255
1465
|
children: "child",
|
|
@@ -1405,6 +1615,14 @@ function inferResourceGraph(ir) {
|
|
|
1405
1615
|
return true;
|
|
1406
1616
|
});
|
|
1407
1617
|
ir.resources = { kinds, edges: dedupedEdges };
|
|
1618
|
+
const login2 = detectLogin(ir);
|
|
1619
|
+
if (login2.candidates.length > 0) {
|
|
1620
|
+
ir.hints.login = {
|
|
1621
|
+
detected: login2.added?.operationId,
|
|
1622
|
+
candidates: login2.candidates.map((c) => c.operationId),
|
|
1623
|
+
reason: login2.reason
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1408
1626
|
return ir;
|
|
1409
1627
|
}
|
|
1410
1628
|
function classifyOperation(op, schemas, allPaths) {
|
|
@@ -1462,8 +1680,8 @@ function actionTarget(segments, allPaths) {
|
|
|
1462
1680
|
const prefixIsEndpoint = allPaths.has(prefix) || [...allPaths].some((p) => p.startsWith(`${prefix}/{`) && p.split("/").length === depth + 1);
|
|
1463
1681
|
if (!prefixIsEndpoint) return void 0;
|
|
1464
1682
|
if ([...allPaths].some((p) => p.startsWith(`${self}/`))) return void 0;
|
|
1465
|
-
const
|
|
1466
|
-
if (
|
|
1683
|
+
const plural2 = singularize(last).toLowerCase() !== last.toLowerCase();
|
|
1684
|
+
if (plural2 && !ACTION_VERB.test(last)) return void 0;
|
|
1467
1685
|
for (let i = segments.length - 2; i >= 0; i--) {
|
|
1468
1686
|
const s = segments[i];
|
|
1469
1687
|
if (!isParamSegment(s) && !isVersionSegment(s)) return s;
|
|
@@ -1664,6 +1882,7 @@ function applyConfig(ir, config) {
|
|
|
1664
1882
|
if (!kind) throw new ConfigError(`${where}: unknown resource "${name}". Known: ${known()}`);
|
|
1665
1883
|
return kind;
|
|
1666
1884
|
};
|
|
1885
|
+
if (config.auth?.login !== void 0) applyLogin(ir, config.auth.login);
|
|
1667
1886
|
for (const [name, override] of Object.entries(config.resources ?? {})) {
|
|
1668
1887
|
const kind = kindNamed(name, `resources.${name}`);
|
|
1669
1888
|
if (override.idField) {
|
|
@@ -1711,6 +1930,60 @@ function applyConfig(ir, config) {
|
|
|
1711
1930
|
}
|
|
1712
1931
|
return ir;
|
|
1713
1932
|
}
|
|
1933
|
+
function applyLogin(ir, login2) {
|
|
1934
|
+
ir.auth = ir.auth.filter((p) => p.kind !== "login");
|
|
1935
|
+
if (login2 === false) return;
|
|
1936
|
+
const where = "auth.login";
|
|
1937
|
+
if (!login2 || typeof login2 !== "object")
|
|
1938
|
+
throw new ConfigError(`${where}: expected an object or false`);
|
|
1939
|
+
if (typeof login2.operation !== "string" || !login2.operation)
|
|
1940
|
+
throw new ConfigError(`${where}.operation: expected an operationId or "METHOD /path"`);
|
|
1941
|
+
const m = login2.operation.match(/^([A-Za-z]+)\s+(\/\S*)$/);
|
|
1942
|
+
const op = m ? ir.operations.find((o) => o.method === m[1].toUpperCase() && o.path === m[2]) : ir.operations.find((o) => o.id === login2.operation);
|
|
1943
|
+
if (!op)
|
|
1944
|
+
throw new ConfigError(`${where}.operation: no operation "${login2.operation}" in the spec`);
|
|
1945
|
+
if (!login2.body || typeof login2.body !== "object" || Array.isArray(login2.body))
|
|
1946
|
+
throw new ConfigError(
|
|
1947
|
+
`${where}.body: expected an object of strings, e.g. {"password": "\${API_PASS}"}`
|
|
1948
|
+
);
|
|
1949
|
+
for (const [k, v] of Object.entries(login2.body))
|
|
1950
|
+
if (typeof v !== "string") throw new ConfigError(`${where}.body.${k}: expected a string`);
|
|
1951
|
+
const schemes = ir.auth.filter((p) => p.kind !== "none" && p.kind !== "login");
|
|
1952
|
+
if (login2.scheme !== void 0 && !schemes.some((p) => p.id === login2.scheme))
|
|
1953
|
+
throw new ConfigError(
|
|
1954
|
+
`${where}.scheme: no security scheme "${login2.scheme}". Known: ${schemes.map((p) => p.id).join(", ") || "none"}`
|
|
1955
|
+
);
|
|
1956
|
+
const scheme = login2.scheme ?? (schemes.filter((p) => p.kind === "bearer").length === 1 ? schemes.find((p) => p.kind === "bearer").id : schemes.length === 1 ? schemes[0].id : void 0);
|
|
1957
|
+
const profile = {
|
|
1958
|
+
id: "login",
|
|
1959
|
+
kind: "login",
|
|
1960
|
+
operationId: op.id,
|
|
1961
|
+
body: login2.body,
|
|
1962
|
+
tokenPath: login2.token,
|
|
1963
|
+
expiresInPath: login2.expiresIn,
|
|
1964
|
+
apply: login2.use !== void 0 ? parseUse(login2.use) : void 0,
|
|
1965
|
+
scheme,
|
|
1966
|
+
source: "config"
|
|
1967
|
+
};
|
|
1968
|
+
ir.auth.push(profile);
|
|
1969
|
+
}
|
|
1970
|
+
function parseUse(use) {
|
|
1971
|
+
const where = "auth.login.use";
|
|
1972
|
+
if (typeof use !== "string") throw new ConfigError(`${where}: expected a string`);
|
|
1973
|
+
const kv = use.match(/^(query|cookie)\s+([^=\s]+)=(.*)$/i);
|
|
1974
|
+
if (kv) {
|
|
1975
|
+
if (!kv[3].includes("{token}")) throw new ConfigError(`${where}: missing {token}`);
|
|
1976
|
+
return { in: kv[1].toLowerCase(), name: kv[2], format: kv[3] };
|
|
1977
|
+
}
|
|
1978
|
+
const header = use.match(/^([A-Za-z0-9-]+):\s*(.*)$/);
|
|
1979
|
+
if (header) {
|
|
1980
|
+
if (!header[2].includes("{token}")) throw new ConfigError(`${where}: missing {token}`);
|
|
1981
|
+
return { in: "header", name: header[1], format: header[2] };
|
|
1982
|
+
}
|
|
1983
|
+
throw new ConfigError(
|
|
1984
|
+
`${where}: expected "Header-Name: Bearer {token}", "query name={token}" or "cookie name={token}"`
|
|
1985
|
+
);
|
|
1986
|
+
}
|
|
1714
1987
|
|
|
1715
1988
|
// ../test-contract/dist/index.js
|
|
1716
1989
|
import { parse, stringify } from "yaml";
|
|
@@ -1806,8 +2079,8 @@ function successResponse(op) {
|
|
|
1806
2079
|
return op.responses.filter((r) => typeof r.status === "number" && r.status >= 200 && r.status < 300).sort((a, b) => a.status - b.status)[0];
|
|
1807
2080
|
}
|
|
1808
2081
|
function jsonMedia(res) {
|
|
1809
|
-
const
|
|
1810
|
-
return
|
|
2082
|
+
const entry2 = Object.entries(res.contentTypes ?? {}).find(([k]) => k.includes("json"));
|
|
2083
|
+
return entry2?.[1];
|
|
1811
2084
|
}
|
|
1812
2085
|
function esc(s) {
|
|
1813
2086
|
return s.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
@@ -1859,7 +2132,7 @@ ${stringify(doc, { aliasDuplicateObjects: false })}`;
|
|
|
1859
2132
|
[specFileName]: specOut,
|
|
1860
2133
|
"pyproject.toml": emitPyProject(ir),
|
|
1861
2134
|
"conftest.py": emitConftest(specFileName, envVars),
|
|
1862
|
-
"loadam_hooks.py": emitHooks(ir.auth, baseUrl),
|
|
2135
|
+
"loadam_hooks.py": emitHooks(ir.auth, baseUrl, ir.operations),
|
|
1863
2136
|
"schemathesis.toml": emitSchemathesisToml(ir),
|
|
1864
2137
|
"test_contract.py": emitContractTests(examples, linksAdded > 0),
|
|
1865
2138
|
"README.md": emitReadme(ir, specFileName),
|
|
@@ -1869,8 +2142,16 @@ ${stringify(doc, { aliasDuplicateObjects: false })}`;
|
|
|
1869
2142
|
}
|
|
1870
2143
|
function collectEnvVars(profiles) {
|
|
1871
2144
|
const out = /* @__PURE__ */ new Set();
|
|
2145
|
+
const backed = new Set(
|
|
2146
|
+
profiles.flatMap((p) => p.kind === "login" && p.scheme ? [p.scheme] : [])
|
|
2147
|
+
);
|
|
1872
2148
|
for (const p of profiles) {
|
|
2149
|
+
if (backed.has(p.id)) continue;
|
|
1873
2150
|
switch (p.kind) {
|
|
2151
|
+
case "login":
|
|
2152
|
+
for (const v of Object.values(p.body))
|
|
2153
|
+
for (const m of v.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)) out.add(m[1]);
|
|
2154
|
+
break;
|
|
1874
2155
|
case "bearer":
|
|
1875
2156
|
out.add(p.tokenEnv ?? "API_TOKEN");
|
|
1876
2157
|
break;
|
|
@@ -1969,7 +2250,7 @@ ${blocks.length ? `
|
|
|
1969
2250
|
# rejecting them is correct: skip the "schema-valid data rejected" check.
|
|
1970
2251
|
${blocks.join("")}` : ""}`;
|
|
1971
2252
|
}
|
|
1972
|
-
function emitHooks(profiles, baseUrl) {
|
|
2253
|
+
function emitHooks(profiles, baseUrl, ops) {
|
|
1973
2254
|
const head = `# AUTO-GENERATED by @loadam/test-contract
|
|
1974
2255
|
"""
|
|
1975
2256
|
Environment and auth for the contract suite. conftest.py imports this; the
|
|
@@ -1991,14 +2272,54 @@ BASE_URL = os.getenv("BASE_URL", ${JSON.stringify(baseUrl)})
|
|
|
1991
2272
|
# The spec declares no authentication.
|
|
1992
2273
|
`;
|
|
1993
2274
|
const usesOAuth = relevant.some((p) => p.kind === "oauth2_cc");
|
|
2275
|
+
const usesLogin = relevant.some((p) => p.kind === "login");
|
|
1994
2276
|
const lines = [
|
|
1995
2277
|
"def _credentials() -> dict:",
|
|
1996
2278
|
` """Headers / query / cookies from env vars, per the spec's security schemes."""`,
|
|
1997
2279
|
' out: dict = {"headers": {}, "query": {}, "cookies": {}}'
|
|
1998
2280
|
];
|
|
1999
2281
|
const env = (name) => `os.getenv(${JSON.stringify(name)})`;
|
|
2000
|
-
|
|
2282
|
+
const ordered = [
|
|
2283
|
+
...relevant.filter((p) => p.kind === "login"),
|
|
2284
|
+
...relevant.filter((p) => p.kind !== "login")
|
|
2285
|
+
];
|
|
2286
|
+
for (const p of ordered) {
|
|
2001
2287
|
switch (p.kind) {
|
|
2288
|
+
case "login": {
|
|
2289
|
+
const op = ops.find((o) => o.id === p.operationId);
|
|
2290
|
+
if (!op) break;
|
|
2291
|
+
const backed = p.scheme ? relevant.find((s) => s.id === p.scheme) : void 0;
|
|
2292
|
+
const staticEnv = backed?.kind === "bearer" ? backed.tokenEnv ?? "API_TOKEN" : backed?.kind === "apiKey" ? apiKeyEnv(backed) : void 0;
|
|
2293
|
+
const vars = [
|
|
2294
|
+
...new Set(
|
|
2295
|
+
Object.values(p.body).flatMap(
|
|
2296
|
+
(v) => [...v.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((m) => m[1])
|
|
2297
|
+
)
|
|
2298
|
+
)
|
|
2299
|
+
];
|
|
2300
|
+
const cond = [...staticEnv ? [`not ${env(staticEnv)}`] : [], ...vars.map((v) => env(v))];
|
|
2301
|
+
const body = `{${Object.entries(p.body).map(
|
|
2302
|
+
([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, '" + (os.getenv("$1") or "") + "')}`
|
|
2303
|
+
).join(", ")}}`;
|
|
2304
|
+
const form = Object.keys(op.body?.contentTypes ?? {})[0]?.startsWith(
|
|
2305
|
+
"application/x-www-form-urlencoded"
|
|
2306
|
+
);
|
|
2307
|
+
lines.push(` if ${cond.length ? cond.join(" and ") : "True"}:`);
|
|
2308
|
+
lines.push(
|
|
2309
|
+
` token = _login(${JSON.stringify(op.method)}, ${JSON.stringify(op.path)}, ${body}, ${p.tokenPath ? JSON.stringify(p.tokenPath) : "None"}, ${form ? "True" : "False"})`
|
|
2310
|
+
);
|
|
2311
|
+
if (!p.tokenPath) {
|
|
2312
|
+
lines.push(" if token:", ` out["cookies"].update(token)`);
|
|
2313
|
+
} else {
|
|
2314
|
+
const a = p.apply ?? (backed?.kind === "apiKey" ? { in: backed.in, name: backed.name, format: "{token}" } : { in: "header", name: "Authorization", format: "Bearer {token}" });
|
|
2315
|
+
const bucket = a.in === "header" ? "headers" : a.in === "query" ? "query" : "cookies";
|
|
2316
|
+
lines.push(
|
|
2317
|
+
" if token:",
|
|
2318
|
+
` out[${JSON.stringify(bucket)}][${JSON.stringify(a.name)}] = ${JSON.stringify(a.format)}.replace("{token}", token)`
|
|
2319
|
+
);
|
|
2320
|
+
}
|
|
2321
|
+
break;
|
|
2322
|
+
}
|
|
2002
2323
|
case "bearer": {
|
|
2003
2324
|
const e = p.tokenEnv ?? "API_TOKEN";
|
|
2004
2325
|
lines.push(` if ${env(e)}:`);
|
|
@@ -2053,18 +2374,82 @@ def _oauth_token(token_url: str, client_id: str, client_secret: str, scope: str)
|
|
|
2053
2374
|
except Exception as exc: # noqa: BLE001 \u2014 report, don't crash collection
|
|
2054
2375
|
print(f"loadam: OAuth2 token request to {url} failed: {exc}")
|
|
2055
2376
|
return None
|
|
2377
|
+
` : "";
|
|
2378
|
+
const login2 = usesLogin ? `
|
|
2379
|
+
|
|
2380
|
+
_LOGINS: dict = {}
|
|
2381
|
+
|
|
2382
|
+
|
|
2383
|
+
def _jwt_exp(token: str) -> float:
|
|
2384
|
+
"""Expiry (epoch seconds) from a JWT's exp claim; 0 when it isn't a JWT."""
|
|
2385
|
+
parts = token.split(".")
|
|
2386
|
+
if len(parts) != 3:
|
|
2387
|
+
return 0
|
|
2388
|
+
try:
|
|
2389
|
+
claims = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4)))
|
|
2390
|
+
return float(claims.get("exp") or 0)
|
|
2391
|
+
except Exception: # noqa: BLE001
|
|
2392
|
+
return 0
|
|
2393
|
+
|
|
2394
|
+
|
|
2395
|
+
def _login(method: str, path: str, body: dict, token_path, form: bool):
|
|
2396
|
+
"""Log in once, and again shortly before the token (or session) expires."""
|
|
2397
|
+
key = (method, path, json.dumps(body, sort_keys=True))
|
|
2398
|
+
cached = _LOGINS.get(key)
|
|
2399
|
+
if cached and (not cached[1] or time.time() < cached[1] - min(30, (cached[1] - cached[2]) * 0.1)):
|
|
2400
|
+
return cached[0]
|
|
2401
|
+
got = _login_call(method, path, body, token_path, form)
|
|
2402
|
+
if got is None:
|
|
2403
|
+
return None
|
|
2404
|
+
value, ttl = got
|
|
2405
|
+
now = time.time()
|
|
2406
|
+
exp = now + ttl if ttl else (_jwt_exp(value) if isinstance(value, str) else 0)
|
|
2407
|
+
_LOGINS[key] = (value, exp, now)
|
|
2408
|
+
return value
|
|
2409
|
+
|
|
2410
|
+
|
|
2411
|
+
def _login_call(method: str, path: str, body: dict, token_path, form: bool):
|
|
2412
|
+
"""Call the API's login operation: (token or session cookies, lifetime in seconds or 0)."""
|
|
2413
|
+
url = BASE_URL.rstrip("/") + path
|
|
2414
|
+
data = urlencode(body).encode() if form else json.dumps(body).encode()
|
|
2415
|
+
content_type = "application/x-www-form-urlencoded" if form else "application/json"
|
|
2416
|
+
req = urllib.request.Request(
|
|
2417
|
+
url, data=data, method=method, headers={"Content-Type": content_type, "Accept": "application/json"}
|
|
2418
|
+
)
|
|
2419
|
+
try:
|
|
2420
|
+
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
2421
|
+
if token_path is None:
|
|
2422
|
+
raw = resp.headers.get_all("Set-Cookie") or []
|
|
2423
|
+
pairs = [c.split(";")[0] for c in raw]
|
|
2424
|
+
ages = [int(m.group(1)) for c in raw for m in [re.search(r"max-age=(\\d+)", c, re.I)] if m]
|
|
2425
|
+
cookies = dict(p.split("=", 1) for p in pairs if "=" in p)
|
|
2426
|
+
return (cookies, min(ages) if ages else 0) if cookies else None
|
|
2427
|
+
payload = json.loads(resp.read().decode())
|
|
2428
|
+
found = payload
|
|
2429
|
+
for key in token_path.split("."):
|
|
2430
|
+
found = found.get(key) if isinstance(found, dict) else None
|
|
2431
|
+
if not isinstance(found, str) or not found:
|
|
2432
|
+
return None
|
|
2433
|
+
ttl = payload.get("expires_in") if isinstance(payload, dict) else None
|
|
2434
|
+
return found, int(ttl) if isinstance(ttl, (int, float)) else 0
|
|
2435
|
+
except Exception as exc: # noqa: BLE001 \u2014 report, don't crash collection
|
|
2436
|
+
print(f"loadam: login via {method} {path} failed: {exc}")
|
|
2437
|
+
return None
|
|
2056
2438
|
` : "";
|
|
2057
2439
|
const imports = [
|
|
2058
|
-
relevant.some((p) => p.kind === "basic") ? "import base64" : "",
|
|
2059
|
-
|
|
2440
|
+
relevant.some((p) => p.kind === "basic") || usesLogin ? "import base64" : "",
|
|
2441
|
+
usesLogin ? "import re\nimport time" : "",
|
|
2442
|
+
usesOAuth || usesLogin ? `import json
|
|
2443
|
+
import urllib.request
|
|
2444
|
+
from urllib.parse import urlencode${usesOAuth ? ", urljoin" : ""}` : ""
|
|
2060
2445
|
].filter(Boolean).join("\n");
|
|
2061
2446
|
return `${head}${imports ? `${imports}
|
|
2062
2447
|
` : ""}
|
|
2063
2448
|
|
|
2064
2449
|
${lines.join("\n")}
|
|
2065
|
-
${oauth}
|
|
2450
|
+
${oauth}${login2}
|
|
2066
2451
|
|
|
2067
|
-
@schemathesis.auth()
|
|
2452
|
+
@schemathesis.auth(${usesLogin ? "refresh_interval=None" : ""})
|
|
2068
2453
|
class LoadamAuth:
|
|
2069
2454
|
"""Applied to every generated request; the ignored_auth check strips it to verify enforcement."""
|
|
2070
2455
|
|
|
@@ -2203,10 +2588,10 @@ function slugify(s) {
|
|
|
2203
2588
|
// src/util/config.ts
|
|
2204
2589
|
import { existsSync } from "fs";
|
|
2205
2590
|
import { readFile as readFile4 } from "fs/promises";
|
|
2206
|
-
import { dirname, join as join2, resolve as
|
|
2591
|
+
import { dirname, join as join2, resolve as resolve5 } from "path";
|
|
2207
2592
|
var CONFIG_FILE = "loadam.config.json";
|
|
2208
2593
|
async function applyUserConfig(ir, specPath, explicit) {
|
|
2209
|
-
const candidates = explicit ? [
|
|
2594
|
+
const candidates = explicit ? [resolve5(explicit)] : [resolve5(CONFIG_FILE), join2(dirname(resolve5(specPath)), CONFIG_FILE)];
|
|
2210
2595
|
const path = candidates.find((p) => existsSync(p));
|
|
2211
2596
|
if (!path) {
|
|
2212
2597
|
if (explicit) throw new Error(`Config file not found: ${explicit}`);
|
|
@@ -2224,7 +2609,7 @@ async function applyUserConfig(ir, specPath, explicit) {
|
|
|
2224
2609
|
if (err instanceof ConfigError) throw new Error(`${path}: ${err.message}`);
|
|
2225
2610
|
throw err;
|
|
2226
2611
|
}
|
|
2227
|
-
return path;
|
|
2612
|
+
return { path, config };
|
|
2228
2613
|
}
|
|
2229
2614
|
var CONFIG_OPTION_HELP = `corrections for inferred resources/refs (default: ./${CONFIG_FILE} or one next to the spec)`;
|
|
2230
2615
|
|
|
@@ -2329,7 +2714,7 @@ function registerContractCommand(program) {
|
|
|
2329
2714
|
}
|
|
2330
2715
|
async function runContract(spec, opts) {
|
|
2331
2716
|
const out = makeOutput(!!opts.json);
|
|
2332
|
-
const specPath =
|
|
2717
|
+
const specPath = resolve6(spec);
|
|
2333
2718
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
2334
2719
|
const ir = await fromOpenApiFile(specPath);
|
|
2335
2720
|
inferResourceGraph(ir);
|
|
@@ -2342,10 +2727,10 @@ async function runContract(spec, opts) {
|
|
|
2342
2727
|
baseUrl: target,
|
|
2343
2728
|
examples: Number.isFinite(examples) ? examples : 25
|
|
2344
2729
|
});
|
|
2345
|
-
const outDir =
|
|
2730
|
+
const outDir = resolve6(opts.output);
|
|
2346
2731
|
await mkdir2(outDir, { recursive: true });
|
|
2347
2732
|
for (const [rel, contents] of Object.entries(result.files)) {
|
|
2348
|
-
const full =
|
|
2733
|
+
const full = resolve6(outDir, rel);
|
|
2349
2734
|
await mkdir2(dirname2(full), { recursive: true });
|
|
2350
2735
|
await writeFile2(full, contents, "utf8");
|
|
2351
2736
|
}
|
|
@@ -2354,7 +2739,7 @@ async function runContract(spec, opts) {
|
|
|
2354
2739
|
out.info(` ${ir.operations.length} operations to fuzz`);
|
|
2355
2740
|
const session = await createSession({
|
|
2356
2741
|
command: "contract",
|
|
2357
|
-
outRoot:
|
|
2742
|
+
outRoot: resolve6(outDir, ".."),
|
|
2358
2743
|
specPath,
|
|
2359
2744
|
specSource,
|
|
2360
2745
|
ir,
|
|
@@ -2451,7 +2836,7 @@ async function runContract(spec, opts) {
|
|
|
2451
2836
|
|
|
2452
2837
|
// src/commands/diff.ts
|
|
2453
2838
|
import { readFile as readFile7, writeFile as writeFile3 } from "fs/promises";
|
|
2454
|
-
import { resolve as
|
|
2839
|
+
import { resolve as resolve7 } from "path";
|
|
2455
2840
|
|
|
2456
2841
|
// ../test-drift/dist/index.js
|
|
2457
2842
|
import Ajv from "ajv";
|
|
@@ -2852,7 +3237,17 @@ async function resolveAuth(ir, env, baseUrl, fetchImpl = fetch) {
|
|
|
2852
3237
|
if (!v) out.missing.push(name);
|
|
2853
3238
|
return v;
|
|
2854
3239
|
};
|
|
3240
|
+
const loginFor = /* @__PURE__ */ new Map();
|
|
3241
|
+
for (const p of ir.auth) {
|
|
3242
|
+
if (p.kind !== "login") continue;
|
|
3243
|
+
const backed = p.scheme ? ir.auth.find((s) => s.id === p.scheme) : void 0;
|
|
3244
|
+
const staticEnv = backed?.kind === "bearer" ? backed.tokenEnv ?? "API_TOKEN" : backed?.kind === "apiKey" ? apiKeyEnv2(backed) : void 0;
|
|
3245
|
+
if (staticEnv && env[staticEnv]) continue;
|
|
3246
|
+
const ok = await login(ir, p, backed, env, baseUrl, fetchImpl, out);
|
|
3247
|
+
if (ok && p.scheme) loginFor.set(p.scheme, p.id);
|
|
3248
|
+
}
|
|
2855
3249
|
for (const p of ir.auth) {
|
|
3250
|
+
if (loginFor.has(p.id)) continue;
|
|
2856
3251
|
switch (p.kind) {
|
|
2857
3252
|
case "bearer": {
|
|
2858
3253
|
const token = need(p.tokenEnv ?? "API_TOKEN");
|
|
@@ -2914,6 +3309,74 @@ async function resolveAuth(ir, env, baseUrl, fetchImpl = fetch) {
|
|
|
2914
3309
|
}
|
|
2915
3310
|
return out;
|
|
2916
3311
|
}
|
|
3312
|
+
async function login(ir, p, backed, env, baseUrl, fetchImpl, out) {
|
|
3313
|
+
const op = ir.operations.find((o) => o.id === p.operationId);
|
|
3314
|
+
if (!op) return false;
|
|
3315
|
+
const body = {};
|
|
3316
|
+
let ready = true;
|
|
3317
|
+
for (const [k, v] of Object.entries(p.body)) {
|
|
3318
|
+
body[k] = v.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_m, name) => {
|
|
3319
|
+
const value = env[name];
|
|
3320
|
+
if (!value) {
|
|
3321
|
+
if (!out.missing.includes(name)) out.missing.push(name);
|
|
3322
|
+
ready = false;
|
|
3323
|
+
}
|
|
3324
|
+
return value ?? "";
|
|
3325
|
+
});
|
|
3326
|
+
}
|
|
3327
|
+
if (!ready) return false;
|
|
3328
|
+
const form = Object.keys(op.body?.contentTypes ?? {})[0]?.startsWith(
|
|
3329
|
+
"application/x-www-form-urlencoded"
|
|
3330
|
+
);
|
|
3331
|
+
const url = baseUrl.replace(/\/$/, "") + op.path;
|
|
3332
|
+
try {
|
|
3333
|
+
const resp = await fetchImpl(url, {
|
|
3334
|
+
method: op.method,
|
|
3335
|
+
headers: {
|
|
3336
|
+
"content-type": form ? "application/x-www-form-urlencoded" : "application/json",
|
|
3337
|
+
accept: "application/json"
|
|
3338
|
+
},
|
|
3339
|
+
body: form ? new URLSearchParams(body).toString() : JSON.stringify(body)
|
|
3340
|
+
});
|
|
3341
|
+
if (!resp.ok) {
|
|
3342
|
+
out.notes.push(`Login via ${op.method} ${op.path} failed (${resp.status}).`);
|
|
3343
|
+
return false;
|
|
3344
|
+
}
|
|
3345
|
+
if (!p.tokenPath) {
|
|
3346
|
+
const cookies = resp.headers.getSetCookie?.() ?? [];
|
|
3347
|
+
const pairs = cookies.map((c) => c.split(";")[0]).filter(Boolean);
|
|
3348
|
+
if (pairs.length === 0) {
|
|
3349
|
+
out.notes.push(`Login via ${op.method} ${op.path} set no cookie.`);
|
|
3350
|
+
return false;
|
|
3351
|
+
}
|
|
3352
|
+
const prev = out.headers.Cookie ? `${out.headers.Cookie}; ` : "";
|
|
3353
|
+
out.headers.Cookie = prev + pairs.join("; ");
|
|
3354
|
+
return true;
|
|
3355
|
+
}
|
|
3356
|
+
const json = await resp.json().catch(() => void 0);
|
|
3357
|
+
let token = json;
|
|
3358
|
+
for (const k of p.tokenPath.split(".")) {
|
|
3359
|
+
token = token && typeof token === "object" ? token[k] : void 0;
|
|
3360
|
+
}
|
|
3361
|
+
if (typeof token !== "string" || !token) {
|
|
3362
|
+
out.notes.push(`Login response has no token at "${p.tokenPath}".`);
|
|
3363
|
+
return false;
|
|
3364
|
+
}
|
|
3365
|
+
const apply2 = p.apply ?? (backed?.kind === "apiKey" ? { in: backed.in, name: backed.name, format: "{token}" } : { in: "header", name: "Authorization", format: "Bearer {token}" });
|
|
3366
|
+
const value = apply2.format.split("{token}").join(token);
|
|
3367
|
+
if (apply2.in === "query") out.query[apply2.name] = value;
|
|
3368
|
+
else if (apply2.in === "cookie") {
|
|
3369
|
+
const prev = out.headers.Cookie ? `${out.headers.Cookie}; ` : "";
|
|
3370
|
+
out.headers.Cookie = `${prev}${apply2.name}=${value}`;
|
|
3371
|
+
} else out.headers[apply2.name] = value;
|
|
3372
|
+
return true;
|
|
3373
|
+
} catch (err) {
|
|
3374
|
+
out.notes.push(
|
|
3375
|
+
`Login via ${op.method} ${op.path} failed: ${err instanceof Error ? err.message : String(err)}`
|
|
3376
|
+
);
|
|
3377
|
+
return false;
|
|
3378
|
+
}
|
|
3379
|
+
}
|
|
2917
3380
|
|
|
2918
3381
|
// src/commands/diff.ts
|
|
2919
3382
|
function registerDiffCommand(program) {
|
|
@@ -2928,7 +3391,7 @@ async function runDiff(spec, opts) {
|
|
|
2928
3391
|
if (!target) {
|
|
2929
3392
|
throw new Error("--target is required (or set LOADAM_TARGET env var)");
|
|
2930
3393
|
}
|
|
2931
|
-
const specPath =
|
|
3394
|
+
const specPath = resolve7(spec);
|
|
2932
3395
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
2933
3396
|
const specSource = await readFile7(specPath, "utf8");
|
|
2934
3397
|
const ir = await fromOpenApiFile(specPath);
|
|
@@ -2958,7 +3421,7 @@ async function runDiff(spec, opts) {
|
|
|
2958
3421
|
const counts = countBySeverity(findings);
|
|
2959
3422
|
const session = await createSession({
|
|
2960
3423
|
command: "diff",
|
|
2961
|
-
outRoot:
|
|
3424
|
+
outRoot: resolve7("./loadam-out"),
|
|
2962
3425
|
specPath,
|
|
2963
3426
|
specSource,
|
|
2964
3427
|
ir,
|
|
@@ -2988,7 +3451,7 @@ async function runDiff(spec, opts) {
|
|
|
2988
3451
|
);
|
|
2989
3452
|
if (!out.json) {
|
|
2990
3453
|
if (opts.output) {
|
|
2991
|
-
const outFile =
|
|
3454
|
+
const outFile = resolve7(opts.output);
|
|
2992
3455
|
await writeFile3(outFile, report, "utf8");
|
|
2993
3456
|
out.success(`Wrote drift report to ${outFile}`);
|
|
2994
3457
|
} else {
|
|
@@ -2999,7 +3462,7 @@ async function runDiff(spec, opts) {
|
|
|
2999
3462
|
);
|
|
3000
3463
|
out.info(` Session: ${session.id}`);
|
|
3001
3464
|
} else if (opts.output) {
|
|
3002
|
-
await writeFile3(
|
|
3465
|
+
await writeFile3(resolve7(opts.output), report, "utf8");
|
|
3003
3466
|
}
|
|
3004
3467
|
const failOn = opts.failOn ?? "error";
|
|
3005
3468
|
const failed = failOn === "error" && counts.error > 0 || failOn === "warning" && counts.error + counts.warning > 0;
|
|
@@ -3022,7 +3485,7 @@ async function runDiff(spec, opts) {
|
|
|
3022
3485
|
skipped: skipped.length,
|
|
3023
3486
|
findings: findings.length,
|
|
3024
3487
|
counts,
|
|
3025
|
-
reportPath: opts.output ?
|
|
3488
|
+
reportPath: opts.output ? resolve7(opts.output) : null,
|
|
3026
3489
|
failOn,
|
|
3027
3490
|
failed,
|
|
3028
3491
|
sessionId: session.id
|
|
@@ -3042,13 +3505,13 @@ function parseKvPairs(values, sep) {
|
|
|
3042
3505
|
}
|
|
3043
3506
|
|
|
3044
3507
|
// src/commands/history.ts
|
|
3045
|
-
import { resolve as
|
|
3508
|
+
import { resolve as resolve8 } from "path";
|
|
3046
3509
|
function registerHistoryCommand(program) {
|
|
3047
3510
|
program.command("history").description("List archived loadam sessions (newest first).").option("--root <dir>", "session archive root", "./loadam-out").option("--limit <n>", "show at most N sessions", "20").option("--command <cmd>", "filter by command (test|contract|diff)").option("--json", "emit a JSON array on stdout", false).action(withFriendlyErrors(runHistory));
|
|
3048
3511
|
}
|
|
3049
3512
|
async function runHistory(opts) {
|
|
3050
3513
|
const out = makeOutput(!!opts.json);
|
|
3051
|
-
const root =
|
|
3514
|
+
const root = resolve8(opts.root);
|
|
3052
3515
|
const limit = Number.parseInt(opts.limit ?? "20", 10);
|
|
3053
3516
|
const all = await listSessions(root);
|
|
3054
3517
|
const filtered = opts.command ? all.filter((s) => s.command === opts.command) : all;
|
|
@@ -3076,19 +3539,19 @@ async function runHistory(opts) {
|
|
|
3076
3539
|
|
|
3077
3540
|
// src/commands/init.ts
|
|
3078
3541
|
import { writeFile as writeFile4 } from "fs/promises";
|
|
3079
|
-
import { resolve as
|
|
3542
|
+
import { resolve as resolve9 } from "path";
|
|
3080
3543
|
function registerInitCommand(program) {
|
|
3081
3544
|
program.command("init").description("Parse a spec and emit loadam.ir.json with inferred resource graph").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <path>", "output path for IR JSON", "./loadam.ir.json").option("--no-tree", "skip printing the resource-graph tree").option("--config <path>", CONFIG_OPTION_HELP).option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runInit));
|
|
3082
3545
|
}
|
|
3083
3546
|
async function runInit(spec, opts) {
|
|
3084
3547
|
const out = makeOutput(!!opts.json);
|
|
3085
|
-
const specPath =
|
|
3548
|
+
const specPath = resolve9(spec);
|
|
3086
3549
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
3087
3550
|
const ir = await fromOpenApiFile(specPath);
|
|
3088
3551
|
inferResourceGraph(ir);
|
|
3089
3552
|
await applyUserConfig(ir, specPath, opts.config);
|
|
3090
3553
|
parseIR(ir);
|
|
3091
|
-
const outPath =
|
|
3554
|
+
const outPath = resolve9(opts.output);
|
|
3092
3555
|
await writeFile4(outPath, `${JSON.stringify(ir, null, 2)}
|
|
3093
3556
|
`, "utf8");
|
|
3094
3557
|
const stats = graphStats(ir.resources);
|
|
@@ -3114,7 +3577,7 @@ async function runInit(spec, opts) {
|
|
|
3114
3577
|
|
|
3115
3578
|
// src/commands/mcp.ts
|
|
3116
3579
|
import { mkdir as mkdir3, writeFile as writeFile5 } from "fs/promises";
|
|
3117
|
-
import { dirname as dirname3, resolve as
|
|
3580
|
+
import { dirname as dirname3, resolve as resolve10 } from "path";
|
|
3118
3581
|
|
|
3119
3582
|
// ../mcp/dist/index.js
|
|
3120
3583
|
function emitAuth(ir) {
|
|
@@ -3167,6 +3630,11 @@ function apply(p, headers, query, envVars, notes) {
|
|
|
3167
3630
|
case "custom":
|
|
3168
3631
|
notes.push(`Custom auth signer "${p.signerRef}" \u2014 wire manually.`);
|
|
3169
3632
|
return;
|
|
3633
|
+
case "login":
|
|
3634
|
+
notes.push(
|
|
3635
|
+
`Login profile "${p.id}" (${p.operationId}): the MCP server doesn't log in for you. Set the scheme's token env var instead.`
|
|
3636
|
+
);
|
|
3637
|
+
return;
|
|
3170
3638
|
}
|
|
3171
3639
|
}
|
|
3172
3640
|
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
@@ -3182,36 +3650,36 @@ function curateTools(ir, opts = {}) {
|
|
|
3182
3650
|
return tools;
|
|
3183
3651
|
}
|
|
3184
3652
|
function buildTool(ir, op) {
|
|
3185
|
-
const
|
|
3186
|
-
const
|
|
3653
|
+
const properties2 = {};
|
|
3654
|
+
const required2 = [];
|
|
3187
3655
|
for (const p of op.pathParams) {
|
|
3188
|
-
|
|
3189
|
-
|
|
3656
|
+
properties2[p.name] = annotate(resolveSchema2(ir, p.schema), p);
|
|
3657
|
+
required2.push(p.name);
|
|
3190
3658
|
}
|
|
3191
3659
|
for (const p of op.queryParams) {
|
|
3192
|
-
|
|
3193
|
-
if (p.required)
|
|
3660
|
+
properties2[p.name] = annotate(resolveSchema2(ir, p.schema), p);
|
|
3661
|
+
if (p.required) required2.push(p.name);
|
|
3194
3662
|
}
|
|
3195
3663
|
for (const p of op.headerParams) {
|
|
3196
3664
|
if (isAuthHeader(p.name)) continue;
|
|
3197
|
-
|
|
3198
|
-
if (p.required)
|
|
3665
|
+
properties2[p.name] = annotate(resolveSchema2(ir, p.schema), p);
|
|
3666
|
+
if (p.required) required2.push(p.name);
|
|
3199
3667
|
}
|
|
3200
3668
|
let hasBody = false;
|
|
3201
3669
|
if (op.body) {
|
|
3202
3670
|
const json = op.body.contentTypes["application/json"];
|
|
3203
3671
|
if (json) {
|
|
3204
|
-
|
|
3205
|
-
if (op.body.required)
|
|
3672
|
+
properties2.body = resolveSchema2(ir, json.schema);
|
|
3673
|
+
if (op.body.required) required2.push("body");
|
|
3206
3674
|
hasBody = true;
|
|
3207
3675
|
}
|
|
3208
3676
|
}
|
|
3209
3677
|
const inputSchema = {
|
|
3210
3678
|
type: "object",
|
|
3211
|
-
properties,
|
|
3679
|
+
properties: properties2,
|
|
3212
3680
|
additionalProperties: false
|
|
3213
3681
|
};
|
|
3214
|
-
if (
|
|
3682
|
+
if (required2.length > 0) inputSchema.required = required2;
|
|
3215
3683
|
return {
|
|
3216
3684
|
name: op.id,
|
|
3217
3685
|
description: buildDescription(op),
|
|
@@ -3649,7 +4117,7 @@ function registerMcpCommand(program) {
|
|
|
3649
4117
|
}
|
|
3650
4118
|
async function runMcp(spec, opts) {
|
|
3651
4119
|
const out = makeOutput(!!opts.json);
|
|
3652
|
-
const specPath =
|
|
4120
|
+
const specPath = resolve10(spec);
|
|
3653
4121
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
3654
4122
|
const ir = await fromOpenApiFile(specPath);
|
|
3655
4123
|
inferResourceGraph(ir);
|
|
@@ -3661,10 +4129,10 @@ async function runMcp(spec, opts) {
|
|
|
3661
4129
|
includeWrites: !!opts.writes,
|
|
3662
4130
|
exclude: opts.exclude
|
|
3663
4131
|
});
|
|
3664
|
-
const outDir =
|
|
4132
|
+
const outDir = resolve10(opts.output);
|
|
3665
4133
|
await mkdir3(outDir, { recursive: true });
|
|
3666
4134
|
for (const [rel, contents] of Object.entries(result.files)) {
|
|
3667
|
-
const full =
|
|
4135
|
+
const full = resolve10(outDir, rel);
|
|
3668
4136
|
await mkdir3(dirname3(full), { recursive: true });
|
|
3669
4137
|
await writeFile5(full, contents, "utf8");
|
|
3670
4138
|
}
|
|
@@ -3695,974 +4163,1375 @@ async function runMcp(spec, opts) {
|
|
|
3695
4163
|
// src/commands/report.ts
|
|
3696
4164
|
import { spawn as spawn2 } from "child_process";
|
|
3697
4165
|
import { readFile as readFile8, writeFile as writeFile6 } from "fs/promises";
|
|
3698
|
-
import { join as join4, resolve as
|
|
4166
|
+
import { join as join4, resolve as resolve11 } from "path";
|
|
3699
4167
|
|
|
3700
4168
|
// ../report/dist/index.js
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
|
|
3704
|
-
const dataPayload = {
|
|
3705
|
-
meta,
|
|
3706
|
-
k6Summaries: input.k6Summaries ?? null,
|
|
3707
|
-
contractFailures: input.contractFailures ?? null,
|
|
3708
|
-
operations: input.operations ?? null,
|
|
3709
|
-
loadamVersion
|
|
3710
|
-
};
|
|
3711
|
-
const hasEndpoints = (input.operations?.length ?? 0) > 0;
|
|
3712
|
-
const sideSections = [
|
|
3713
|
-
renderThresholds(meta),
|
|
3714
|
-
renderK6Section(input.k6Summaries, hasEndpoints),
|
|
3715
|
-
input.driftMarkdown ? renderDrift(input.driftMarkdown) : "",
|
|
3716
|
-
input.contractFailures && input.contractFailures.length > 0 ? renderContract(input.contractFailures) : "",
|
|
3717
|
-
renderRunDetails(meta)
|
|
3718
|
-
].filter((s) => s !== "").join("\n");
|
|
3719
|
-
const mainBlock = renderEndpoints(input.operations, input.k6Summaries);
|
|
3720
|
-
return [
|
|
3721
|
-
"<!doctype html>",
|
|
3722
|
-
`<html lang="en">`,
|
|
3723
|
-
"<head>",
|
|
3724
|
-
`<meta charset="utf-8" />`,
|
|
3725
|
-
`<meta name="viewport" content="width=device-width,initial-scale=1" />`,
|
|
3726
|
-
`<meta name="generator" content="loadam ${esc2(loadamVersion)}" />`,
|
|
3727
|
-
`<title>${esc2(reportTitle(meta))}</title>`,
|
|
3728
|
-
`<style>${STYLES}${dynamicTabStyles(input.k6Summaries)}${dynamicEndpointStyles(input.operations)}</style>`,
|
|
3729
|
-
"</head>",
|
|
3730
|
-
"<body>",
|
|
3731
|
-
renderHeader(meta, overall, input.k6Summaries),
|
|
3732
|
-
renderFailureReason(meta, overall, input.k6Summaries, input.contractFailures),
|
|
3733
|
-
renderSummary(meta, input.k6Summaries),
|
|
3734
|
-
// Two-column layout: endpoints fill the main column on the left, while
|
|
3735
|
-
// run-level data (thresholds, k6 results, drift, contract findings, run
|
|
3736
|
-
// details) lives in a sticky sidebar on the right so a reader never has
|
|
3737
|
-
// to scroll past a long endpoint list to see the overall numbers.
|
|
3738
|
-
mainBlock ? `<div class="page-grid"><div class="page-main">${mainBlock}</div><aside class="page-side">${sideSections}</aside></div>` : sideSections,
|
|
3739
|
-
renderFooter(meta, loadamVersion),
|
|
3740
|
-
`<script type="application/json" id="loadam-data">${escScript(JSON.stringify(dataPayload))}</script>`,
|
|
3741
|
-
DOWNLOAD_SCRIPT,
|
|
3742
|
-
"</body>",
|
|
3743
|
-
"</html>",
|
|
3744
|
-
""
|
|
3745
|
-
].join("\n");
|
|
4169
|
+
var INT = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });
|
|
4170
|
+
function esc2(s) {
|
|
4171
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
3746
4172
|
}
|
|
3747
|
-
function
|
|
3748
|
-
|
|
3749
|
-
const chipText = overall.detail ? `${overall.detail} \xB7 ${overall.label}` : overall.label;
|
|
3750
|
-
return `
|
|
3751
|
-
<div class="brand-row">
|
|
3752
|
-
<a class="brand" href="https://github.com/DesmondSanctity/loadam" target="_blank" rel="noopener" title="loadam on GitHub">
|
|
3753
|
-
<svg class="brand-mark" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
|
3754
|
-
<defs><linearGradient id="loadam-g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f59e0b"/><stop offset="1" stop-color="#ef4444"/></linearGradient></defs>
|
|
3755
|
-
<path d="M3 18 A 9 9 0 0 1 21 18" stroke="url(#loadam-g)" stroke-width="2.5" stroke-linecap="round"/>
|
|
3756
|
-
<path d="M12 18 L17 10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>
|
|
3757
|
-
<circle cx="12" cy="18" r="1.6" fill="currentColor"/>
|
|
3758
|
-
</svg>
|
|
3759
|
-
<span class="brand-name">load<span class="brand-name-am">am</span></span>
|
|
3760
|
-
</a>
|
|
3761
|
-
<span class="brand-tag">load tests & contract checks from OpenAPI</span>
|
|
3762
|
-
</div>
|
|
3763
|
-
<header class="hdr">
|
|
3764
|
-
<div class="hdr-left">
|
|
3765
|
-
<div class="cmd">${esc2(meta.command)}${modeLabel ? ` \xB7 ${esc2(modeLabel)}` : ""} <span class="status-chip ${overall.cls}">${esc2(chipText)}</span></div>
|
|
3766
|
-
<h1>${esc2(meta.spec.title ?? "Untitled API")}</h1>
|
|
3767
|
-
<div class="sub">${esc2(meta.spec.version ?? "")} \xB7 target <code>${esc2(meta.target ?? "\u2014")}</code></div>
|
|
3768
|
-
</div>
|
|
3769
|
-
<div class="hdr-right">
|
|
3770
|
-
<div class="when">${esc2(meta.startedAt)}</div>
|
|
3771
|
-
${typeof meta.durationMs === "number" ? `<div class="dur">${(meta.durationMs / 1e3).toFixed(2)}s</div>` : ""}
|
|
3772
|
-
<div class="actions">
|
|
3773
|
-
<button type="button" class="act" data-loadam-download="html" title="Download this HTML report">\u2B07 Report</button>
|
|
3774
|
-
<button type="button" class="act" data-loadam-download="json" title="Download raw run data as JSON">\u2B07 Data</button>
|
|
3775
|
-
<button type="button" class="act" data-loadam-print title="Print or save as PDF">\u2399 Print</button>
|
|
3776
|
-
</div>
|
|
3777
|
-
</div>
|
|
3778
|
-
</header>`;
|
|
4173
|
+
function escScript(s) {
|
|
4174
|
+
return s.replace(/<\/script/gi, "<\\/script");
|
|
3779
4175
|
}
|
|
3780
|
-
function
|
|
3781
|
-
|
|
3782
|
-
const labels = k6 ? Object.keys(k6) : [];
|
|
3783
|
-
if (labels.length > 0) return labels.join(" + ");
|
|
3784
|
-
const flagMode = meta.flags.mode;
|
|
3785
|
-
if (typeof flagMode === "string" && flagMode !== "skip") return flagMode;
|
|
3786
|
-
return "generated only";
|
|
3787
|
-
}
|
|
3788
|
-
function renderFailureReason(meta, overall, k6, contractFailures) {
|
|
3789
|
-
if (overall.cls === "ok" || overall.cls === "muted") return "";
|
|
3790
|
-
const reasons = [];
|
|
3791
|
-
const failedThresh = (meta.thresholds?.failed ?? []).filter((n) => !isSentinelThreshold(n));
|
|
3792
|
-
if (failedThresh.length > 0) {
|
|
3793
|
-
const PREVIEW = 3;
|
|
3794
|
-
const head = failedThresh.slice(0, PREVIEW).map((t) => `<code>${esc2(t)}</code>`).join(", ");
|
|
3795
|
-
const rest = failedThresh.slice(PREVIEW);
|
|
3796
|
-
const more = rest.length > 0 ? ` <details class="more"><summary>+${rest.length} more</summary>${rest.map((t) => `<code>${esc2(t)}</code>`).join(", ")}</details>` : "";
|
|
3797
|
-
reasons.push(
|
|
3798
|
-
`<strong>${failedThresh.length}</strong> threshold${failedThresh.length === 1 ? "" : "s"} failed: ${head}${more}`
|
|
3799
|
-
);
|
|
3800
|
-
}
|
|
3801
|
-
if (k6) {
|
|
3802
|
-
for (const [name, s] of Object.entries(k6)) {
|
|
3803
|
-
const checks = s.root_group?.checks;
|
|
3804
|
-
if (!checks) continue;
|
|
3805
|
-
const entries = Object.values(checks);
|
|
3806
|
-
const failed = entries.filter((c) => c.fails > 0);
|
|
3807
|
-
const totalChecks = entries.length;
|
|
3808
|
-
if (failed.length > 0) {
|
|
3809
|
-
reasons.push(
|
|
3810
|
-
`<strong>${name}</strong>: ${failed.length}/${totalChecks} operation check${failed.length === 1 ? "" : "s"} failed`
|
|
3811
|
-
);
|
|
3812
|
-
}
|
|
3813
|
-
}
|
|
3814
|
-
}
|
|
3815
|
-
if (contractFailures && contractFailures.length > 0) {
|
|
3816
|
-
reasons.push(
|
|
3817
|
-
`<strong>${contractFailures.length}</strong> contract test${contractFailures.length === 1 ? "" : "s"} failed`
|
|
3818
|
-
);
|
|
3819
|
-
}
|
|
3820
|
-
if (reasons.length === 0 && typeof meta.exitCode === "number" && meta.exitCode !== 0) {
|
|
3821
|
-
reasons.push(`Process exited with code <code>${meta.exitCode}</code>`);
|
|
3822
|
-
}
|
|
3823
|
-
if (reasons.length === 0) return "";
|
|
3824
|
-
const heading = overall.cls === "bad" ? "Why this failed" : "Issues to investigate";
|
|
3825
|
-
return `
|
|
3826
|
-
<section class="reason ${overall.cls}">
|
|
3827
|
-
<h2>${heading}</h2>
|
|
3828
|
-
<ul>${reasons.map((r) => `<li>${r}</li>`).join("")}</ul>
|
|
3829
|
-
</section>`;
|
|
4176
|
+
function slug(s) {
|
|
4177
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "x";
|
|
3830
4178
|
}
|
|
3831
|
-
function
|
|
3832
|
-
|
|
3833
|
-
if (meta.summary) {
|
|
3834
|
-
for (const [k, v] of Object.entries(meta.summary)) {
|
|
3835
|
-
cells.push({ label: k, value: String(v) });
|
|
3836
|
-
}
|
|
3837
|
-
}
|
|
3838
|
-
if (k6) {
|
|
3839
|
-
for (const [name, s] of Object.entries(k6)) {
|
|
3840
|
-
const dur = s.metrics?.http_req_duration?.values;
|
|
3841
|
-
if (dur && typeof dur["p(95)"] === "number") {
|
|
3842
|
-
cells.push({ label: `${name} p95`, value: `${dur["p(95)"].toFixed(0)} ms` });
|
|
3843
|
-
}
|
|
3844
|
-
const reqs = s.metrics?.http_reqs?.values;
|
|
3845
|
-
if (reqs && typeof reqs.count === "number") {
|
|
3846
|
-
cells.push({ label: `${name} reqs`, value: String(reqs.count) });
|
|
3847
|
-
}
|
|
3848
|
-
if (reqs && typeof reqs.rate === "number") {
|
|
3849
|
-
cells.push({ label: `${name} rps`, value: `${reqs.rate.toFixed(1)}/s` });
|
|
3850
|
-
}
|
|
3851
|
-
const failed = s.metrics?.http_req_failed?.values;
|
|
3852
|
-
if (failed && typeof failed.rate === "number") {
|
|
3853
|
-
cells.push({
|
|
3854
|
-
label: `${name} fail`,
|
|
3855
|
-
value: `${(failed.rate * 100).toFixed(2)}%`
|
|
3856
|
-
});
|
|
3857
|
-
}
|
|
3858
|
-
}
|
|
3859
|
-
}
|
|
3860
|
-
if (cells.length === 0) return "";
|
|
3861
|
-
return `
|
|
3862
|
-
<section class="cards">
|
|
3863
|
-
${cells.map(
|
|
3864
|
-
(c) => `<div class="card"><div class="card-v">${esc2(c.value)}</div><div class="card-l">${esc2(c.label)}</div></div>`
|
|
3865
|
-
).join("\n ")}
|
|
3866
|
-
</section>`;
|
|
4179
|
+
function isNum(n) {
|
|
4180
|
+
return typeof n === "number" && Number.isFinite(n);
|
|
3867
4181
|
}
|
|
3868
|
-
function
|
|
3869
|
-
|
|
3870
|
-
if (!t) return "";
|
|
3871
|
-
const failed = t.failed.filter((n) => !isSentinelThreshold(n));
|
|
3872
|
-
const passed = t.passed.filter((n) => !isSentinelThreshold(n));
|
|
3873
|
-
if (failed.length === 0 && passed.length === 0) return "";
|
|
3874
|
-
const PREVIEW = 4;
|
|
3875
|
-
const failedHead = failed.slice(0, PREVIEW);
|
|
3876
|
-
const failedRest = failed.slice(PREVIEW);
|
|
3877
|
-
const passedHead = passed.slice(0, PREVIEW);
|
|
3878
|
-
const passedRest = passed.slice(PREVIEW);
|
|
3879
|
-
const summary = [];
|
|
3880
|
-
if (failed.length > 0) summary.push(`<span class="bad">${failed.length} failed</span>`);
|
|
3881
|
-
if (passed.length > 0) summary.push(`<span class="ok">${passed.length} passed</span>`);
|
|
3882
|
-
return `
|
|
3883
|
-
<section>
|
|
3884
|
-
<h2>Thresholds <span class="muted">(${summary.join(" \xB7 ")})</span></h2>
|
|
3885
|
-
<ul class="thr">
|
|
3886
|
-
${failedHead.map((x) => `<li class="bad">\u2717 ${esc2(x)}</li>`).join("\n ")}
|
|
3887
|
-
${failedRest.length > 0 ? `<li class="thr-more"><details><summary>+${failedRest.length} more failed</summary><ul class="thr">${failedRest.map((x) => `<li class="bad">\u2717 ${esc2(x)}</li>`).join("")}</ul></details></li>` : ""}
|
|
3888
|
-
${passedHead.map((x) => `<li class="ok">\u2713 ${esc2(x)}</li>`).join("\n ")}
|
|
3889
|
-
${passedRest.length > 0 ? `<li class="thr-more"><details><summary>+${passedRest.length} more passed</summary><ul class="thr">${passedRest.map((x) => `<li class="ok">\u2713 ${esc2(x)}</li>`).join("")}</ul></details></li>` : ""}
|
|
3890
|
-
</ul>
|
|
3891
|
-
</section>`;
|
|
4182
|
+
function fmtInt(n) {
|
|
4183
|
+
return isNum(n) ? INT.format(n) : "\u2014";
|
|
3892
4184
|
}
|
|
3893
|
-
function
|
|
3894
|
-
if (!
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
3912
|
-
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
<div class="ep-group-h">${esc2(tag)}</div>
|
|
3934
|
-
${items}
|
|
3935
|
-
</div>`;
|
|
3936
|
-
}).join("\n ");
|
|
3937
|
-
const radios = ops.map((op, i) => {
|
|
3938
|
-
const id = opSlug(op);
|
|
3939
|
-
return `<input type="radio" name="loadam-endpoint" id="${esc2(id)}" class="ep-radio"${i === 0 ? " checked" : ""}>`;
|
|
3940
|
-
}).join("");
|
|
3941
|
-
const totals = ops.map((op) => endpointStatus(checkLookup.get(op.id) ?? []));
|
|
3942
|
-
const failedCount = totals.filter((t) => t.cls === "bad").length;
|
|
3943
|
-
const flakyCount = totals.filter((t) => t.cls === "warn").length;
|
|
3944
|
-
const passedCount = totals.filter((t) => t.cls === "ok").length;
|
|
3945
|
-
const noDataCount = totals.length - failedCount - flakyCount - passedCount;
|
|
3946
|
-
const parts = [`${ops.length} endpoint${ops.length === 1 ? "" : "s"}`];
|
|
3947
|
-
if (runs.length > 0) {
|
|
3948
|
-
parts.push(`${passedCount} passed`);
|
|
3949
|
-
if (flakyCount > 0) parts.push(`${flakyCount} flaky`);
|
|
3950
|
-
if (failedCount > 0) parts.push(`${failedCount} failed`);
|
|
3951
|
-
if (noDataCount > 0) parts.push(`${noDataCount} no data`);
|
|
3952
|
-
}
|
|
3953
|
-
const headline = parts.join(" \xB7 ");
|
|
3954
|
-
const filterRadios = [
|
|
3955
|
-
`<input type="radio" name="loadam-ep-filter" id="ep-filter-all" class="ep-filter-radio" checked>`,
|
|
3956
|
-
`<input type="radio" name="loadam-ep-filter" id="ep-filter-bad" class="ep-filter-radio">`,
|
|
3957
|
-
`<input type="radio" name="loadam-ep-filter" id="ep-filter-warn" class="ep-filter-radio">`,
|
|
3958
|
-
`<input type="radio" name="loadam-ep-filter" id="ep-filter-ok" class="ep-filter-radio">`
|
|
3959
|
-
].join("");
|
|
3960
|
-
const filterChips = `<div class="ep-filter">
|
|
3961
|
-
<label for="ep-filter-all" title="Show all endpoints">All ${ops.length}</label>
|
|
3962
|
-
<label for="ep-filter-bad" class="bad" title="Show failed endpoints only">Failed ${failedCount}</label>
|
|
3963
|
-
<label for="ep-filter-warn" class="warn" title="Show flaky endpoints only">Flaky ${flakyCount}</label>
|
|
3964
|
-
<label for="ep-filter-ok" class="ok" title="Show passed endpoints only">Passed ${passedCount}</label>
|
|
3965
|
-
</div>`;
|
|
3966
|
-
const panes = ops.map((op) => {
|
|
3967
|
-
const opChecks = checkLookup.get(op.id) ?? [];
|
|
3968
|
-
const status = endpointStatus(opChecks);
|
|
3969
|
-
const id = opSlug(op);
|
|
3970
|
-
const rateLabel = status.rate === null ? "" : ` <span class="ep-pill-rate">${esc2(fmtRate(status.rate))}</span>`;
|
|
3971
|
-
const pill = `<span class="ep-pill ${status.cls}">${esc2(status.label)}${rateLabel}</span>`;
|
|
3972
|
-
const runStrip = opChecks.map(({ run, check }) => {
|
|
3973
|
-
const total = check.passes + check.fails;
|
|
3974
|
-
const rate = total > 0 ? check.passes / total : 0;
|
|
3975
|
-
const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
|
|
3976
|
-
const pct = total > 0 ? fmtRate(rate) : "";
|
|
3977
|
-
return `<span class="ep-run ${cls}"><strong>${esc2(run)}</strong> ${check.passes}/${total} passed${pct ? ` \xB7 ${pct}` : ""}</span>`;
|
|
3978
|
-
}).join("");
|
|
3979
|
-
const checkRows = opChecks.map(({ run, check }) => {
|
|
3980
|
-
const total = check.passes + check.fails;
|
|
3981
|
-
const rate = total > 0 ? check.passes / total : 0;
|
|
3982
|
-
const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
|
|
3983
|
-
const pct = total > 0 ? ` <span class="muted">(${fmtRate(rate)})</span>` : "";
|
|
3984
|
-
return `<tr class="${cls}"><th>${esc2(run)}</th><td>${esc2(check.name)}</td><td>${check.passes}/${total} passed${pct}</td></tr>`;
|
|
3985
|
-
}).join("");
|
|
3986
|
-
const detail = checkRows ? `<table class="kv ep-detail"><thead><tr><th>run</th><th>check</th><th>result</th></tr></thead><tbody>${checkRows}</tbody></table>` : `<p class="hint">No k6 checks recorded for this operation.</p>`;
|
|
3987
|
-
const metricsBlock = renderOpMetricsBlock(opMetrics.get(op.id));
|
|
3988
|
-
const tags = (op.tags ?? []).map((t) => `<span class="ep-tag">${esc2(t)}</span>`).join("");
|
|
3989
|
-
return `<div class="ep-pane" data-ep="${esc2(id)}">
|
|
3990
|
-
<div class="ep-pane-h">
|
|
3991
|
-
<span class="ep-method ${esc2(op.method.toLowerCase())}">${esc2(op.method.toUpperCase())}</span>
|
|
3992
|
-
<span class="ep-path"><code>${esc2(op.path)}</code></span>
|
|
3993
|
-
${pill}
|
|
3994
|
-
</div>
|
|
3995
|
-
${op.summary ? `<p class="ep-pane-sum">${esc2(op.summary)}</p>` : ""}
|
|
3996
|
-
${tags ? `<div class="ep-tags">${tags}</div>` : ""}
|
|
3997
|
-
${runStrip ? `<div class="ep-runs">${runStrip}</div>` : ""}
|
|
3998
|
-
${metricsBlock}
|
|
3999
|
-
${detail}
|
|
4000
|
-
</div>`;
|
|
4001
|
-
}).join("\n ");
|
|
4002
|
-
return `
|
|
4003
|
-
<section class="endpoints">
|
|
4004
|
-
<h2>Endpoints <span class="muted">(${esc2(headline)})</span></h2>
|
|
4005
|
-
<p class="hint">Status uses pass-rate tiers: <span class="tier ok">passed \u2265 ${PASS_RATE_OK * 100}%</span> \xB7 <span class="tier warn">flaky ${PASS_RATE_WARN * 100}\u2013${PASS_RATE_OK * 100}%</span> \xB7 <span class="tier bad">failed < ${PASS_RATE_WARN * 100}%</span>.</p>
|
|
4006
|
-
<div class="ep-layout">
|
|
4007
|
-
${filterRadios}
|
|
4008
|
-
${radios}
|
|
4009
|
-
<aside class="ep-sidebar">
|
|
4010
|
-
${filterChips}
|
|
4011
|
-
${sidebar}
|
|
4012
|
-
</aside>
|
|
4013
|
-
<div class="ep-main">
|
|
4014
|
-
${panes}
|
|
4015
|
-
</div>
|
|
4016
|
-
</div>
|
|
4017
|
-
</section>`;
|
|
4185
|
+
function fmtMs(n) {
|
|
4186
|
+
if (!isNum(n)) return "\u2014";
|
|
4187
|
+
if (n >= 1e4) return `${(n / 1e3).toFixed(1)} s`;
|
|
4188
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(2)} s`;
|
|
4189
|
+
if (n >= 10 || n === 0) return `${Math.round(n)} ms`;
|
|
4190
|
+
if (n >= 1) return `${n.toFixed(1)} ms`;
|
|
4191
|
+
return `${n.toFixed(2)} ms`;
|
|
4192
|
+
}
|
|
4193
|
+
function fmtPerSec(n) {
|
|
4194
|
+
if (!isNum(n)) return "\u2014";
|
|
4195
|
+
return n >= 100 ? `${INT.format(n)}/s` : `${n.toFixed(1)}/s`;
|
|
4196
|
+
}
|
|
4197
|
+
function fmtPct(rate) {
|
|
4198
|
+
return isNum(rate) ? `${(rate * 100).toFixed(2)}%` : "\u2014";
|
|
4199
|
+
}
|
|
4200
|
+
function fmtPassRate(rate) {
|
|
4201
|
+
if (!isNum(rate)) return "";
|
|
4202
|
+
const pct = rate * 100;
|
|
4203
|
+
if (Number.isInteger(pct)) return `${pct}%`;
|
|
4204
|
+
if (pct > 99.9 && pct < 100) return ">99.9%";
|
|
4205
|
+
return `${pct.toFixed(1)}%`;
|
|
4206
|
+
}
|
|
4207
|
+
function fmtDuration(ms) {
|
|
4208
|
+
if (!isNum(ms)) return "\u2014";
|
|
4209
|
+
const s = ms / 1e3;
|
|
4210
|
+
if (s < 60) return `${s < 10 ? s.toFixed(1) : Math.round(s)} s`;
|
|
4211
|
+
const m = Math.floor(s / 60);
|
|
4212
|
+
const rest = Math.round(s - m * 60);
|
|
4213
|
+
return rest ? `${m} min ${rest} s` : `${m} min`;
|
|
4214
|
+
}
|
|
4215
|
+
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
4216
|
+
function fmtWhen(iso) {
|
|
4217
|
+
const d = new Date(iso);
|
|
4218
|
+
if (Number.isNaN(d.getTime())) return iso;
|
|
4219
|
+
const hh = String(d.getUTCHours()).padStart(2, "0");
|
|
4220
|
+
const mm = String(d.getUTCMinutes()).padStart(2, "0");
|
|
4221
|
+
return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}, ${hh}:${mm} UTC`;
|
|
4222
|
+
}
|
|
4223
|
+
function plural(n, one, many = `${one}s`) {
|
|
4224
|
+
return `${fmtInt(n)} ${n === 1 ? one : many}`;
|
|
4018
4225
|
}
|
|
4019
4226
|
var PASS_RATE_OK = 0.99;
|
|
4020
4227
|
var PASS_RATE_WARN = 0.95;
|
|
4021
|
-
|
|
4022
|
-
|
|
4228
|
+
var SENTINEL = /^(loadam_op_latency|loadam_op_status)/;
|
|
4229
|
+
function isSentinelThreshold(name) {
|
|
4230
|
+
return SENTINEL.test(name.replace(/^[a-zA-Z0-9_-]+:\s+/, ""));
|
|
4231
|
+
}
|
|
4232
|
+
function buildModel(meta, k6, ops, contractFailures) {
|
|
4233
|
+
const runs = Object.entries(k6 ?? {}).map(([name, s]) => runView(name, s));
|
|
4234
|
+
const primary = runs.find((r) => r.name === "load") ?? runs[0];
|
|
4235
|
+
const endpoints2 = endpointViews(ops ?? [], k6 ?? {});
|
|
4236
|
+
const fromRuns = runs.flatMap((r) => r.thresholds);
|
|
4237
|
+
const thresholds = fromRuns.length > 0 ? fromRuns : thresholdsFromMeta(meta);
|
|
4238
|
+
const overall = computeOverall(meta, runs, endpoints2, thresholds, contractFailures ?? []);
|
|
4239
|
+
return {
|
|
4240
|
+
meta,
|
|
4241
|
+
runs,
|
|
4242
|
+
primary,
|
|
4243
|
+
endpoints: endpoints2,
|
|
4244
|
+
thresholds,
|
|
4245
|
+
overall,
|
|
4246
|
+
contractFailures: contractFailures ?? []
|
|
4247
|
+
};
|
|
4248
|
+
}
|
|
4249
|
+
function runView(name, s) {
|
|
4250
|
+
const m = s.metrics ?? {};
|
|
4251
|
+
const v = (k) => m[k]?.values ?? {};
|
|
4252
|
+
const checks = Object.values(s.root_group?.checks ?? {});
|
|
4023
4253
|
let passes = 0;
|
|
4024
4254
|
let total = 0;
|
|
4025
|
-
for (const
|
|
4026
|
-
passes +=
|
|
4027
|
-
total +=
|
|
4028
|
-
}
|
|
4029
|
-
|
|
4030
|
-
const
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
if (rate === null) return "";
|
|
4037
|
-
const pct = rate * 100;
|
|
4038
|
-
return Number.isInteger(pct) ? `${pct}%` : `${pct.toFixed(1)}%`;
|
|
4039
|
-
}
|
|
4040
|
-
function computeOverall(meta, k6, ops) {
|
|
4041
|
-
const thresholdsFailed = (meta.thresholds?.failed ?? []).some((n) => !isSentinelThreshold(n));
|
|
4042
|
-
if (ops && ops.length > 0 && k6) {
|
|
4043
|
-
const lookup = /* @__PURE__ */ new Map();
|
|
4044
|
-
for (const op of ops) lookup.set(op.id, []);
|
|
4045
|
-
for (const summary of Object.values(k6)) {
|
|
4046
|
-
const checks = summary.root_group?.checks;
|
|
4047
|
-
if (!checks) continue;
|
|
4048
|
-
for (const c of Object.values(checks)) {
|
|
4049
|
-
const opId = c.name.split(/\s+/)[0];
|
|
4050
|
-
if (opId && lookup.has(opId)) lookup.get(opId)?.push(c);
|
|
4051
|
-
}
|
|
4052
|
-
}
|
|
4053
|
-
let okN = 0;
|
|
4054
|
-
let warnN = 0;
|
|
4055
|
-
let badN = 0;
|
|
4056
|
-
let withData = 0;
|
|
4057
|
-
for (const op of ops) {
|
|
4058
|
-
const opChecks = lookup.get(op.id) ?? [];
|
|
4059
|
-
const status = endpointStatus(opChecks.map((check) => ({ run: "", check })));
|
|
4060
|
-
if (status.cls === "ok") {
|
|
4061
|
-
okN++;
|
|
4062
|
-
withData++;
|
|
4063
|
-
} else if (status.cls === "warn") {
|
|
4064
|
-
warnN++;
|
|
4065
|
-
withData++;
|
|
4066
|
-
} else if (status.cls === "bad") {
|
|
4067
|
-
badN++;
|
|
4068
|
-
withData++;
|
|
4069
|
-
}
|
|
4255
|
+
for (const c of checks) {
|
|
4256
|
+
passes += c.passes;
|
|
4257
|
+
total += c.passes + c.fails;
|
|
4258
|
+
}
|
|
4259
|
+
const checkMetric = v("checks");
|
|
4260
|
+
const fromMetric = isNum(checkMetric.passes) && isNum(checkMetric.fails) ? { passes: checkMetric.passes, total: checkMetric.passes + checkMetric.fails } : void 0;
|
|
4261
|
+
const thresholds = [];
|
|
4262
|
+
for (const [metric, mm] of Object.entries(m)) {
|
|
4263
|
+
if (SENTINEL.test(metric) || !mm?.thresholds) continue;
|
|
4264
|
+
for (const [expr, t] of Object.entries(mm.thresholds)) {
|
|
4265
|
+
thresholds.push(parseThreshold(name, metric, expr, t.ok, mm.values, mm.type));
|
|
4070
4266
|
}
|
|
4071
|
-
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
|
|
4267
|
+
}
|
|
4268
|
+
const latency2 = m.http_req_duration?.values;
|
|
4269
|
+
return {
|
|
4270
|
+
name,
|
|
4271
|
+
slug: slug(name),
|
|
4272
|
+
requests: v("http_reqs").count,
|
|
4273
|
+
rps: v("http_reqs").rate,
|
|
4274
|
+
p95: latency2?.["p(95)"],
|
|
4275
|
+
errRate: v("http_req_failed").rate,
|
|
4276
|
+
checks: total > 0 ? { passes, total } : fromMetric,
|
|
4277
|
+
vus: v("vus_max").max ?? v("vus_max").value,
|
|
4278
|
+
iterations: v("iterations").count,
|
|
4279
|
+
latency: latency2 && Object.keys(latency2).length > 0 ? latency2 : void 0,
|
|
4280
|
+
renewals: v("loadam_auth_refreshes").count,
|
|
4281
|
+
rejected: v("loadam_auth_rejected").count,
|
|
4282
|
+
thresholds
|
|
4283
|
+
};
|
|
4284
|
+
}
|
|
4285
|
+
var EXPR = /^\s*([a-z]+(?:\(\d+(?:\.\d+)?\))?)\s*(<=|>=|==|!=|<|>)\s*(-?\d+(?:\.\d+)?)\s*$/i;
|
|
4286
|
+
function unitFor(metric, stat3, type) {
|
|
4287
|
+
if (stat3 === "rate" || type === "rate" || metric === "http_req_failed" || metric === "checks")
|
|
4288
|
+
return "pct";
|
|
4289
|
+
if (stat3 === "count") return "num";
|
|
4290
|
+
if (/duration|latency|waiting|blocked|connecting|sending|receiving/.test(metric)) return "ms";
|
|
4291
|
+
return "num";
|
|
4292
|
+
}
|
|
4293
|
+
function parseThreshold(run, metric, expr, ok, values, type) {
|
|
4294
|
+
const match = EXPR.exec(expr);
|
|
4295
|
+
if (!match) return { run, metric, expr, ok, unit: unitFor(metric, void 0, type) };
|
|
4296
|
+
const [, stat3 = "", op, limit] = match;
|
|
4297
|
+
const measured = values?.[stat3] ?? (stat3 === "value" ? values?.rate : void 0);
|
|
4298
|
+
return {
|
|
4299
|
+
run,
|
|
4300
|
+
metric,
|
|
4301
|
+
expr,
|
|
4302
|
+
ok,
|
|
4303
|
+
stat: stat3,
|
|
4304
|
+
op,
|
|
4305
|
+
limit: Number(limit),
|
|
4306
|
+
measured: isNum(measured) ? measured : void 0,
|
|
4307
|
+
unit: unitFor(metric, stat3, type)
|
|
4308
|
+
};
|
|
4309
|
+
}
|
|
4310
|
+
function thresholdsFromMeta(meta) {
|
|
4311
|
+
const out = [];
|
|
4312
|
+
const add = (line, ok) => {
|
|
4313
|
+
if (isSentinelThreshold(line)) return;
|
|
4314
|
+
const parts = line.split(/:\s+/);
|
|
4315
|
+
const [run, metric, expr] = parts.length >= 3 ? [parts[0] ?? "", parts[1] ?? "", parts.slice(2).join(": ")] : parts.length === 2 ? ["", parts[0] ?? "", parts[1] ?? ""] : ["", line, ""];
|
|
4316
|
+
out.push(parseThreshold(run, metric, expr, ok, void 0, void 0));
|
|
4317
|
+
};
|
|
4318
|
+
for (const t of meta.thresholds?.failed ?? []) add(t, false);
|
|
4319
|
+
for (const t of meta.thresholds?.passed ?? []) add(t, true);
|
|
4320
|
+
return out;
|
|
4321
|
+
}
|
|
4322
|
+
function endpointViews(ops, k6) {
|
|
4323
|
+
return ops.map((op) => {
|
|
4324
|
+
const checks = [];
|
|
4325
|
+
const runs = {};
|
|
4326
|
+
for (const [run, s] of Object.entries(k6)) {
|
|
4327
|
+
for (const c of Object.values(s.root_group?.checks ?? {})) {
|
|
4328
|
+
if (c.name.split(/\s+/)[0] === op.id)
|
|
4329
|
+
checks.push({ run, name: c.name, passes: c.passes, total: c.passes + c.fails });
|
|
4075
4330
|
}
|
|
4076
|
-
|
|
4077
|
-
if (badN === 0) return { cls: "warn", label: "flaky", detail };
|
|
4078
|
-
if (passingRate >= PASS_RATE_WARN) return { cls: "warn", label: "partial", detail };
|
|
4079
|
-
if (passingRate >= 0.5) return { cls: "warn", label: "partial", detail };
|
|
4080
|
-
return { cls: "bad", label: "failed", detail };
|
|
4331
|
+
runs[run] = opRunMetrics(op.id, s);
|
|
4081
4332
|
}
|
|
4082
|
-
}
|
|
4083
|
-
if (k6) {
|
|
4084
4333
|
let passes = 0;
|
|
4085
4334
|
let total = 0;
|
|
4086
|
-
for (const
|
|
4087
|
-
|
|
4088
|
-
|
|
4089
|
-
for (const c of Object.values(checks)) {
|
|
4090
|
-
passes += c.passes;
|
|
4091
|
-
total += c.passes + c.fails;
|
|
4092
|
-
}
|
|
4335
|
+
for (const c of checks) {
|
|
4336
|
+
passes += c.passes;
|
|
4337
|
+
total += c.total;
|
|
4093
4338
|
}
|
|
4094
|
-
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
|
|
4100
|
-
|
|
4101
|
-
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
const
|
|
4107
|
-
|
|
4108
|
-
const
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
}
|
|
4114
|
-
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
(k) => k.startsWith("loadam_op_latency{") && k.includes(`name:${op.id}`)
|
|
4124
|
-
);
|
|
4125
|
-
const p95 = latencyKey && typeof metrics[latencyKey]?.values?.["p(95)"] === "number" ? metrics[latencyKey].values["p(95)"] : null;
|
|
4126
|
-
const buckets = {};
|
|
4127
|
-
let total = 0;
|
|
4128
|
-
for (const [k, m] of Object.entries(metrics)) {
|
|
4129
|
-
if (!k.startsWith("loadam_op_status{") || !k.includes(`name:${op.id}`)) continue;
|
|
4130
|
-
const bucket = (k.match(/bucket:([0-9]xx)/) ?? [])[1];
|
|
4131
|
-
if (!bucket) continue;
|
|
4132
|
-
const count = typeof m.values?.count === "number" ? m.values.count : 0;
|
|
4133
|
-
if (count > 0) {
|
|
4134
|
-
buckets[bucket] = count;
|
|
4135
|
-
total += count;
|
|
4136
|
-
}
|
|
4137
|
-
}
|
|
4138
|
-
const entry = out.get(op.id);
|
|
4139
|
-
if (entry) {
|
|
4140
|
-
entry.perRun.set(runName, { p95, buckets, total });
|
|
4141
|
-
if (runName === "load" && p95 !== null) entry.p95 = p95;
|
|
4142
|
-
else if (entry.p95 === null && p95 !== null) entry.p95 = p95;
|
|
4339
|
+
const rate = total > 0 ? passes / total : null;
|
|
4340
|
+
const [tone, label] = tierFor(rate);
|
|
4341
|
+
return { op, slug: slug(`ep-${op.id}`), tone, label, rate, checks, runs };
|
|
4342
|
+
});
|
|
4343
|
+
}
|
|
4344
|
+
function tierFor(rate) {
|
|
4345
|
+
if (rate === null) return ["muted", "not run"];
|
|
4346
|
+
if (rate >= PASS_RATE_OK) return ["ok", "passed"];
|
|
4347
|
+
if (rate >= PASS_RATE_WARN) return ["warn", "flaky"];
|
|
4348
|
+
return ["bad", "failed"];
|
|
4349
|
+
}
|
|
4350
|
+
function opRunMetrics(opId, s) {
|
|
4351
|
+
const metrics = s.metrics ?? {};
|
|
4352
|
+
let p95 = null;
|
|
4353
|
+
const buckets = {};
|
|
4354
|
+
let total = 0;
|
|
4355
|
+
for (const [k, m] of Object.entries(metrics)) {
|
|
4356
|
+
if (!k.includes(`name:${opId}`)) continue;
|
|
4357
|
+
const tags = k.slice(k.indexOf("{") + 1, -1).split(",");
|
|
4358
|
+
if (!tags.includes(`name:${opId}`)) continue;
|
|
4359
|
+
if (k.startsWith("loadam_op_latency{")) {
|
|
4360
|
+
const v = m.values?.["p(95)"];
|
|
4361
|
+
if (isNum(v)) p95 = v;
|
|
4362
|
+
} else if (k.startsWith("loadam_op_status{")) {
|
|
4363
|
+
const bucket = /bucket:([0-9]xx)/.exec(k)?.[1];
|
|
4364
|
+
const count = m.values?.count;
|
|
4365
|
+
if (bucket && isNum(count) && count > 0) {
|
|
4366
|
+
buckets[bucket] = count;
|
|
4367
|
+
total += count;
|
|
4143
4368
|
}
|
|
4144
4369
|
}
|
|
4145
4370
|
}
|
|
4146
|
-
return
|
|
4147
|
-
}
|
|
4148
|
-
function isSentinelThreshold(name) {
|
|
4149
|
-
const stripped = name.replace(/^[a-zA-Z0-9_-]+:\s+/, "");
|
|
4150
|
-
return stripped.startsWith("loadam_op_latency") || stripped.startsWith("loadam_op_status");
|
|
4151
|
-
}
|
|
4152
|
-
var BUCKET_ORDER = ["1xx", "2xx", "3xx", "4xx", "5xx"];
|
|
4153
|
-
var BUCKET_CLASS = {
|
|
4154
|
-
"1xx": "muted",
|
|
4155
|
-
"2xx": "ok",
|
|
4156
|
-
"3xx": "ok",
|
|
4157
|
-
"4xx": "bad",
|
|
4158
|
-
"5xx": "bad"
|
|
4159
|
-
};
|
|
4160
|
-
function renderOpMetricsBlock(metrics) {
|
|
4161
|
-
if (!metrics || metrics.perRun.size === 0) return "";
|
|
4162
|
-
const rows = [];
|
|
4163
|
-
for (const [run, m] of metrics.perRun) {
|
|
4164
|
-
if (m.total === 0 && m.p95 === null) continue;
|
|
4165
|
-
const segments = BUCKET_ORDER.filter((b) => (m.buckets[b] ?? 0) > 0).map((b) => {
|
|
4166
|
-
const count = m.buckets[b] ?? 0;
|
|
4167
|
-
const pct = m.total > 0 ? count / m.total * 100 : 0;
|
|
4168
|
-
return `<span class="bkt ${BUCKET_CLASS[b]}" style="width:${pct.toFixed(2)}%" title="${b} \xB7 ${count} req \xB7 ${pct.toFixed(1)}%">${b} ${count}</span>`;
|
|
4169
|
-
}).join("");
|
|
4170
|
-
const p95 = m.p95 !== null ? `${Math.round(m.p95)}ms` : "\u2014";
|
|
4171
|
-
rows.push(`<tr>
|
|
4172
|
-
<th>${esc2(run)}</th>
|
|
4173
|
-
<td class="num">${m.total}</td>
|
|
4174
|
-
<td class="num">${esc2(p95)}</td>
|
|
4175
|
-
<td><div class="bkt-bar">${segments || `<span class="muted">no data</span>`}</div></td>
|
|
4176
|
-
</tr>`);
|
|
4177
|
-
}
|
|
4178
|
-
if (rows.length === 0) return "";
|
|
4179
|
-
return `<table class="kv ep-metrics">
|
|
4180
|
-
<thead><tr><th>run</th><th>requests</th><th>p95</th><th>status codes</th></tr></thead>
|
|
4181
|
-
<tbody>${rows.join("")}</tbody>
|
|
4182
|
-
</table>`;
|
|
4183
|
-
}
|
|
4184
|
-
function renderK6Section(k6, hasEndpoints) {
|
|
4185
|
-
if (!k6) return "";
|
|
4186
|
-
const entries = Object.entries(k6);
|
|
4187
|
-
if (entries.length === 0) return "";
|
|
4188
|
-
const blocks = entries.map(([name, summary]) => ({ name, html: renderK6Block(name, summary, hasEndpoints) })).filter((b) => b.html !== "");
|
|
4189
|
-
if (blocks.length === 0) return "";
|
|
4190
|
-
if (blocks.length === 1) {
|
|
4191
|
-
return `<section><h2>k6 results</h2>${blocks[0]?.html ?? ""}</section>`;
|
|
4192
|
-
}
|
|
4193
|
-
const tabs = blocks.map((b, i) => {
|
|
4194
|
-
const id = `loadam-tab-${slug(b.name)}`;
|
|
4195
|
-
return `
|
|
4196
|
-
<input type="radio" name="loadam-k6-tab" id="${esc2(id)}" class="tab-input"${i === 0 ? " checked" : ""}>`;
|
|
4197
|
-
}).join("");
|
|
4198
|
-
const labels = blocks.map((b) => {
|
|
4199
|
-
const id = `loadam-tab-${slug(b.name)}`;
|
|
4200
|
-
return `<label for="${esc2(id)}" class="tab-label">${esc2(b.name)}</label>`;
|
|
4201
|
-
}).join("");
|
|
4202
|
-
const panes = blocks.map((b) => `<div class="tab-pane" data-tab="${esc2(slug(b.name))}">${b.html}</div>`).join("");
|
|
4203
|
-
return `
|
|
4204
|
-
<section class="tabs">
|
|
4205
|
-
<h2>k6 results <span class="tab-hint">(${blocks.length} runs \u2014 click to switch)</span></h2>${tabs}
|
|
4206
|
-
<div class="tab-bar">${labels}</div>
|
|
4207
|
-
${panes}
|
|
4208
|
-
</section>`;
|
|
4209
|
-
}
|
|
4210
|
-
function renderK6Block(name, summary, hasEndpoints) {
|
|
4211
|
-
const metrics = summary.metrics ?? {};
|
|
4212
|
-
const dur = metrics.http_req_duration?.values;
|
|
4213
|
-
const reqs = metrics.http_reqs?.values;
|
|
4214
|
-
const failed = metrics.http_req_failed?.values;
|
|
4215
|
-
const headlineCells = [];
|
|
4216
|
-
if (dur && typeof dur["p(95)"] === "number")
|
|
4217
|
-
headlineCells.push({ label: "p95", value: fmtMs(dur["p(95)"]) });
|
|
4218
|
-
if (reqs && typeof reqs.count === "number")
|
|
4219
|
-
headlineCells.push({ label: "requests", value: String(reqs.count) });
|
|
4220
|
-
if (reqs && typeof reqs.rate === "number")
|
|
4221
|
-
headlineCells.push({ label: "rps", value: `${reqs.rate.toFixed(1)}/s` });
|
|
4222
|
-
if (failed && typeof failed.rate === "number")
|
|
4223
|
-
headlineCells.push({ label: "errors", value: `${(failed.rate * 100).toFixed(2)}%` });
|
|
4224
|
-
const headline = headlineCells.length > 0 ? `<div class="cards inner">${headlineCells.map(
|
|
4225
|
-
(c) => `<div class="card"><div class="card-v">${esc2(c.value)}</div><div class="card-l">${esc2(c.label)}</div></div>`
|
|
4226
|
-
).join("")}</div>` : "";
|
|
4227
|
-
const latency = dur ? `
|
|
4228
|
-
<h3>http_req_duration</h3>
|
|
4229
|
-
<table class="kv">
|
|
4230
|
-
<tbody>
|
|
4231
|
-
${[
|
|
4232
|
-
["min", fmtMs(dur.min)],
|
|
4233
|
-
["med", fmtMs(dur.med)],
|
|
4234
|
-
["avg", fmtMs(dur.avg)],
|
|
4235
|
-
["p(90)", fmtMs(dur["p(90)"])],
|
|
4236
|
-
["p(95)", fmtMs(dur["p(95)"])],
|
|
4237
|
-
["p(99)", fmtMs(dur["p(99)"])],
|
|
4238
|
-
["max", fmtMs(dur.max)]
|
|
4239
|
-
].map(([k, v]) => `<tr><th>${esc2(k)}</th><td>${esc2(v)}</td></tr>`).join("")}
|
|
4240
|
-
</tbody>
|
|
4241
|
-
</table>
|
|
4242
|
-
${renderPercentileBars(dur)}` : "";
|
|
4243
|
-
const checks = summary.root_group?.checks;
|
|
4244
|
-
const checkBlock = checks ? hasEndpoints ? renderChecksSummary(checks) : renderChecks(checks) : "";
|
|
4245
|
-
if (!headline && !latency && !checkBlock) return "";
|
|
4246
|
-
return `
|
|
4247
|
-
<div class="metric-block">
|
|
4248
|
-
${headline}
|
|
4249
|
-
${latency}
|
|
4250
|
-
${checkBlock}
|
|
4251
|
-
</div>`;
|
|
4252
|
-
}
|
|
4253
|
-
function renderChecksSummary(checks) {
|
|
4254
|
-
const entries = Object.values(checks);
|
|
4255
|
-
if (entries.length === 0) return "";
|
|
4256
|
-
let ok = 0;
|
|
4257
|
-
let warn = 0;
|
|
4258
|
-
let bad = 0;
|
|
4259
|
-
let totalPasses = 0;
|
|
4260
|
-
let totalInvocations = 0;
|
|
4261
|
-
for (const c of entries) {
|
|
4262
|
-
const t = c.passes + c.fails;
|
|
4263
|
-
totalPasses += c.passes;
|
|
4264
|
-
totalInvocations += t;
|
|
4265
|
-
const r = t > 0 ? c.passes / t : 0;
|
|
4266
|
-
if (r >= PASS_RATE_OK) ok++;
|
|
4267
|
-
else if (r >= PASS_RATE_WARN) warn++;
|
|
4268
|
-
else bad++;
|
|
4269
|
-
}
|
|
4270
|
-
const cls = bad > 0 ? "bad" : warn > 0 ? "warn" : "ok";
|
|
4271
|
-
const overallRate = totalInvocations > 0 ? totalPasses / totalInvocations : 0;
|
|
4272
|
-
const parts = [`<strong>${ok}</strong>/${entries.length} passed`];
|
|
4273
|
-
if (warn > 0) parts.push(`<span class="warn-text">${warn} flaky</span>`);
|
|
4274
|
-
if (bad > 0) parts.push(`<span class="bad-text">${bad} failed</span>`);
|
|
4275
|
-
return `
|
|
4276
|
-
<div class="chk-line"><span class="chk-tag ${cls}">checks</span> ${parts.join(" \xB7 ")} <span class="muted">\xB7 ${esc2(fmtRate(overallRate))} overall</span></div>`;
|
|
4277
|
-
}
|
|
4278
|
-
function renderChecks(checks) {
|
|
4279
|
-
const entries = Object.values(checks);
|
|
4280
|
-
if (entries.length === 0) return "";
|
|
4281
|
-
const failed = entries.filter((c) => c.fails > 0);
|
|
4282
|
-
const passed = entries.length - failed.length;
|
|
4283
|
-
const summaryLine = `${passed}/${entries.length} passed${failed.length > 0 ? ` \xB7 ${failed.length} failed` : ""}`;
|
|
4284
|
-
const row = (c, kind) => {
|
|
4285
|
-
const total = c.passes + c.fails;
|
|
4286
|
-
return `<tr class="${kind}"><th>${esc2(c.name)}</th><td><span class="chk-count">${c.passes}<span class="chk-sep">/</span>${total}</span> <span class="chk-word">passed</span></td></tr>`;
|
|
4287
|
-
};
|
|
4288
|
-
const failedRows = failed.map((c) => row(c, "bad")).join("");
|
|
4289
|
-
const passedRows = entries.filter((c) => c.fails === 0).map((c) => row(c, "ok")).join("");
|
|
4290
|
-
return `
|
|
4291
|
-
<h3>Per-operation checks <span class="muted">(${esc2(summaryLine)})</span></h3>
|
|
4292
|
-
<p class="hint">Each row shows <em>passed / invoked</em>: how many times this assertion held vs. how many times it ran (one invocation per request).</p>
|
|
4293
|
-
<table class="kv checks">
|
|
4294
|
-
<tbody>${failedRows}${passedRows}</tbody>
|
|
4295
|
-
</table>`;
|
|
4296
|
-
}
|
|
4297
|
-
function slug(s) {
|
|
4298
|
-
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "tab";
|
|
4371
|
+
return { p95, total, buckets };
|
|
4299
4372
|
}
|
|
4300
|
-
function
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
.
|
|
4306
|
-
.
|
|
4307
|
-
|
|
4373
|
+
function computeOverall(meta, runs, endpoints2, thresholds, contractFailures) {
|
|
4374
|
+
const failedThreshold = thresholds.some((t) => !t.ok);
|
|
4375
|
+
const exitBad = isNum(meta.exitCode) && meta.exitCode !== 0;
|
|
4376
|
+
const summary = meta.summary ?? {};
|
|
4377
|
+
if (meta.command === "diff") {
|
|
4378
|
+
if (Number(summary.error) > 0 || exitBad) return { tone: "bad", label: "drift found" };
|
|
4379
|
+
if (Number(summary.warning) > 0) return { tone: "warn", label: "warnings" };
|
|
4380
|
+
return { tone: "ok", label: "no drift" };
|
|
4381
|
+
}
|
|
4382
|
+
if (meta.command === "contract") {
|
|
4383
|
+
if (contractFailures.length > 0 || Number(summary.failed) > 0 || exitBad)
|
|
4384
|
+
return { tone: "bad", label: "failed" };
|
|
4385
|
+
if (!isNum(summary.tests)) return { tone: "muted", label: "not run" };
|
|
4386
|
+
return { tone: "ok", label: "passed" };
|
|
4387
|
+
}
|
|
4388
|
+
if (summary.authPreflight === "failed") return { tone: "bad", label: "auth failed" };
|
|
4389
|
+
const ran = endpoints2.filter((e) => e.tone !== "muted");
|
|
4390
|
+
if (failedThreshold || ran.some((e) => e.tone === "bad")) return { tone: "bad", label: "failed" };
|
|
4391
|
+
if (ran.some((e) => e.tone === "warn")) return { tone: "warn", label: "flaky" };
|
|
4392
|
+
if (ran.length > 0) return { tone: "ok", label: "passed" };
|
|
4393
|
+
let passes = 0;
|
|
4394
|
+
let total = 0;
|
|
4395
|
+
for (const r of runs) {
|
|
4396
|
+
passes += r.checks?.passes ?? 0;
|
|
4397
|
+
total += r.checks?.total ?? 0;
|
|
4398
|
+
}
|
|
4399
|
+
if (total > 0) {
|
|
4400
|
+
const [tone, label] = tierFor(passes / total);
|
|
4401
|
+
return { tone, label };
|
|
4402
|
+
}
|
|
4403
|
+
if (exitBad) return { tone: "bad", label: "failed" };
|
|
4404
|
+
if (runs.length === 0 && meta.command === "test" && !meta.thresholds)
|
|
4405
|
+
return { tone: "muted", label: "not run" };
|
|
4406
|
+
return { tone: "ok", label: "passed" };
|
|
4407
|
+
}
|
|
4408
|
+
var HEAD_SCRIPT = `<script>(function(){var r=document.documentElement;r.classList.add('js');try{var t=localStorage.getItem('loadam-theme');if(t==='light'||t==='dark')r.setAttribute('data-theme',t)}catch(e){}})();</script>`;
|
|
4409
|
+
var BODY_SCRIPT = `<script>(function(){
|
|
4410
|
+
var d=document,root=d.documentElement,report=d.querySelector('.report');
|
|
4411
|
+
function $$(s,el){return Array.prototype.slice.call((el||d).querySelectorAll(s))}
|
|
4412
|
+
|
|
4413
|
+
/* theme */
|
|
4414
|
+
var tt=d.querySelector('[data-theme-toggle]');
|
|
4415
|
+
if(tt)tt.addEventListener('click',function(){
|
|
4416
|
+
var cur=root.getAttribute('data-theme')||(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light');
|
|
4417
|
+
var next=cur==='dark'?'light':'dark';root.setAttribute('data-theme',next);
|
|
4418
|
+
try{localStorage.setItem('loadam-theme',next)}catch(e){}
|
|
4419
|
+
});
|
|
4420
|
+
|
|
4421
|
+
/* runs */
|
|
4422
|
+
function activeRun(){return report.getAttribute('data-active-run')||''}
|
|
4423
|
+
$$('[data-run-tab]').forEach(function(b){b.addEventListener('click',function(){
|
|
4424
|
+
report.setAttribute('data-active-run',b.getAttribute('data-run-tab'));
|
|
4425
|
+
$$('[data-run-tab]').forEach(function(x){x.setAttribute('aria-selected',String(x===b))});
|
|
4426
|
+
if(sortKey==='p95'||sortKey==='reqs')sortRows();
|
|
4427
|
+
})});
|
|
4428
|
+
|
|
4429
|
+
/* endpoints */
|
|
4430
|
+
var table=d.querySelector('.ep-table');
|
|
4431
|
+
var rows=table?$$('.ep-row',table):[];
|
|
4432
|
+
var filter='all',query='',sortKey='result',sortDir=1;
|
|
4433
|
+
rows.forEach(function(r){
|
|
4434
|
+
var det=r.nextElementSibling;if(det)det.hidden=true;
|
|
4435
|
+
function toggle(){var open=r.getAttribute('aria-expanded')!=='true';setOpen(r,open)}
|
|
4436
|
+
r.addEventListener('click',function(e){if(e.target.closest('a'))return;toggle()});
|
|
4437
|
+
r.addEventListener('keydown',function(e){if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle()}});
|
|
4438
|
+
});
|
|
4439
|
+
function setOpen(r,open){r.setAttribute('aria-expanded',String(open));var det=r.nextElementSibling;if(det)det.hidden=!open||r.hidden}
|
|
4440
|
+
var PAGE=10,page=0;
|
|
4441
|
+
var pager=d.querySelector('.pager'),info=pager&&pager.querySelector('.pager-info'),btns=pager&&pager.querySelector('.pager-btns');
|
|
4442
|
+
function matches(r){
|
|
4443
|
+
if(filter!=='all'&&r.getAttribute('data-state')!==filter)return false;
|
|
4444
|
+
if(!query)return true;
|
|
4445
|
+
var key=r.getAttribute('data-key'),terms=query.split(/\\s+/);
|
|
4446
|
+
for(var i=0;i<terms.length;i++)if(key.indexOf(terms[i])<0)return false;
|
|
4447
|
+
return true;
|
|
4308
4448
|
}
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
4328
|
-
|
|
4329
|
-
|
|
4330
|
-
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
|
|
4339
|
-
}
|
|
4340
|
-
function
|
|
4341
|
-
|
|
4342
|
-
<
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4449
|
+
/* Rows in their current (sorted) order that pass the filter and search. */
|
|
4450
|
+
function matching(){return table?$$('.ep-row',table).filter(matches):[]}
|
|
4451
|
+
function apply(){
|
|
4452
|
+
var list=matching(),pages=Math.max(1,Math.ceil(list.length/PAGE));
|
|
4453
|
+
if(page>=pages)page=pages-1;
|
|
4454
|
+
var from=page*PAGE,to=from+PAGE;
|
|
4455
|
+
rows.forEach(function(r){r.hidden=true});
|
|
4456
|
+
list.forEach(function(r,i){if(i>=from&&i<to)r.hidden=false});
|
|
4457
|
+
rows.forEach(function(r){setOpen(r,r.getAttribute('aria-expanded')==='true')});
|
|
4458
|
+
var empty=d.querySelector('.empty');if(empty)empty.hidden=list.length>0;
|
|
4459
|
+
renderPager(list.length,pages,from);
|
|
4460
|
+
}
|
|
4461
|
+
function renderPager(n,pages,from){
|
|
4462
|
+
if(!pager)return;
|
|
4463
|
+
var narrowed=filter!=='all'||!!query;
|
|
4464
|
+
pager.hidden=n===0||(pages<2&&!narrowed);
|
|
4465
|
+
info.textContent=pages>1?'Showing '+(from+1)+'\u2013'+Math.min(from+PAGE,n)+' of '+n+(narrowed?' matching':''):n+' of '+rows.length+' endpoints';
|
|
4466
|
+
btns.innerHTML='';
|
|
4467
|
+
if(pages<2)return;
|
|
4468
|
+
function btn(label,to,opts){
|
|
4469
|
+
var b=d.createElement('button');b.type='button';b.className='pg'+(opts&&opts.cur?' cur':'');b.textContent=label;
|
|
4470
|
+
if(opts&&opts.aria)b.setAttribute('aria-label',opts.aria);
|
|
4471
|
+
if(opts&&opts.cur)b.setAttribute('aria-current','page');
|
|
4472
|
+
b.disabled=to<0||to>=pages;
|
|
4473
|
+
b.addEventListener('click',function(){page=to;apply();var t=d.getElementById('endpoints');if(t&&t.getBoundingClientRect().top<0)t.scrollIntoView()});
|
|
4474
|
+
btns.appendChild(b);
|
|
4475
|
+
}
|
|
4476
|
+
function gap(){var s=d.createElement('span');s.className='pg-gap';s.textContent='\u2026';btns.appendChild(s)}
|
|
4477
|
+
btn('\u2039',page-1,{aria:'Previous page'});
|
|
4478
|
+
var shown={};[0,pages-1,page-1,page,page+1].forEach(function(p){if(p>=0&&p<pages)shown[p]=1});
|
|
4479
|
+
if(page<=2)[1,2,3].forEach(function(p){if(p<pages)shown[p]=1});
|
|
4480
|
+
if(page>=pages-3)[pages-2,pages-3,pages-4].forEach(function(p){if(p>=0)shown[p]=1});
|
|
4481
|
+
var last=-1;
|
|
4482
|
+
for(var p=0;p<pages;p++){if(!shown[p])continue;if(p>last+1)gap();btn(String(p+1),p,{cur:p===page,aria:'Page '+(p+1)});last=p}
|
|
4483
|
+
btn('\u203A',page+1,{aria:'Next page'});
|
|
4484
|
+
}
|
|
4485
|
+
/* Show a row wherever it is: clear what hides it and turn to its page. */
|
|
4486
|
+
function reveal(r){
|
|
4487
|
+
if(!matches(r)){
|
|
4488
|
+
filter='all';query='';if(search)search.value='';
|
|
4489
|
+
$$('[data-filter]').forEach(function(x){x.setAttribute('aria-pressed',String(x.getAttribute('data-filter')==='all'))});
|
|
4490
|
+
}
|
|
4491
|
+
var i=matching().indexOf(r);if(i>=0)page=Math.floor(i/PAGE);
|
|
4492
|
+
apply();setOpen(r,true);
|
|
4493
|
+
}
|
|
4494
|
+
$$('[data-filter]').forEach(function(b){b.addEventListener('click',function(){
|
|
4495
|
+
filter=b.getAttribute('data-filter');
|
|
4496
|
+
$$('[data-filter]').forEach(function(x){x.setAttribute('aria-pressed',String(x===b))});page=0;apply();
|
|
4497
|
+
})});
|
|
4498
|
+
var search=d.querySelector('[data-ep-search]');
|
|
4499
|
+
if(search){
|
|
4500
|
+
search.addEventListener('input',function(){query=search.value.trim().toLowerCase();page=0;apply()});
|
|
4501
|
+
search.addEventListener('keydown',function(e){if(e.key==='Escape'&&search.value){search.value='';query='';page=0;apply()}});
|
|
4502
|
+
}
|
|
4503
|
+
function firstRun(){var el=d.querySelector('[data-run]');return el?el.getAttribute('data-run'):''}
|
|
4504
|
+
function val(r,k){
|
|
4505
|
+
if(k==='path')return r.getAttribute('data-path');
|
|
4506
|
+
if(k==='result')return parseFloat(r.getAttribute('data-rank'))*10-parseFloat(r.getAttribute('data-rate'));
|
|
4507
|
+
var run=activeRun()||firstRun();var n=parseFloat(r.getAttribute('data-'+k+'-'+run));return isNaN(n)?-1:n;
|
|
4508
|
+
}
|
|
4509
|
+
function sortRows(){
|
|
4510
|
+
if(!table)return;var body=table.tBodies[0];
|
|
4511
|
+
var order=rows.map(function(r,i){return {r:r,i:i,v:val(r,sortKey)}});
|
|
4512
|
+
order.sort(function(a,b){
|
|
4513
|
+
if(typeof a.v==='string')return sortDir*a.v.localeCompare(b.v)||a.i-b.i;
|
|
4514
|
+
if(sortKey!=='result'&&(a.v<0||b.v<0))return (a.v<0)-(b.v<0)||a.i-b.i;
|
|
4515
|
+
return sortDir*(a.v-b.v)||a.i-b.i;
|
|
4516
|
+
});
|
|
4517
|
+
order.forEach(function(o){var det=o.r.nextElementSibling;body.appendChild(o.r);if(det)body.appendChild(det)});
|
|
4518
|
+
$$('th',table).forEach(function(th){var b=th.querySelector('[data-sort]');
|
|
4519
|
+
if(b&&b.getAttribute('data-sort')===sortKey)th.setAttribute('aria-sort',sortDir>0?'ascending':'descending');else th.removeAttribute('aria-sort')});
|
|
4520
|
+
var sel=d.querySelector('[data-ep-sort-select]');if(sel)sel.value=sortKey;
|
|
4521
|
+
page=0;apply();
|
|
4522
|
+
}
|
|
4523
|
+
var DEFAULT_DIR={path:1,result:1,p95:-1,reqs:-1};
|
|
4524
|
+
$$('[data-sort]').forEach(function(b){b.addEventListener('click',function(){
|
|
4525
|
+
var k=b.getAttribute('data-sort');sortDir=k===sortKey?-sortDir:DEFAULT_DIR[k];sortKey=k;sortRows();
|
|
4526
|
+
})});
|
|
4527
|
+
var sel=d.querySelector('[data-ep-sort-select]');
|
|
4528
|
+
if(sel)sel.addEventListener('change',function(){sortKey=sel.value;sortDir=DEFAULT_DIR[sortKey];sortRows()});
|
|
4529
|
+
if(table)sortRows();
|
|
4530
|
+
$$('[data-open-endpoint]').forEach(function(a){a.addEventListener('click',function(){
|
|
4531
|
+
var r=d.getElementById(a.getAttribute('data-open-endpoint'));if(r)reveal(r);
|
|
4532
|
+
})});
|
|
4533
|
+
function fromHash(){var r=location.hash&&d.getElementById(location.hash.slice(1));if(r&&r.classList&&r.classList.contains('ep-row')){reveal(r);r.scrollIntoView()}}
|
|
4534
|
+
addEventListener('hashchange',fromHash);fromHash();
|
|
4535
|
+
|
|
4536
|
+
/* tooltip */
|
|
4537
|
+
var tip=d.createElement('div');tip.className='tip';tip.hidden=true;tip.setAttribute('role','tooltip');d.body.appendChild(tip);
|
|
4538
|
+
d.addEventListener('mousemove',function(e){
|
|
4539
|
+
var t=e.target.closest&&e.target.closest('[data-tip]');
|
|
4540
|
+
if(!t){tip.hidden=true;return}
|
|
4541
|
+
tip.textContent=t.getAttribute('data-tip');tip.hidden=false;
|
|
4542
|
+
var x=Math.min(Math.max(e.clientX,tip.offsetWidth/2+8),innerWidth-tip.offsetWidth/2-8);
|
|
4543
|
+
tip.style.left=x+'px';tip.style.top=e.clientY+'px';
|
|
4544
|
+
});
|
|
4545
|
+
d.addEventListener('scroll',function(){tip.hidden=true},true);
|
|
4546
|
+
|
|
4547
|
+
/* downloads */
|
|
4548
|
+
var el=d.getElementById('loadam-data'),data={};
|
|
4549
|
+
try{data=JSON.parse(el.textContent||'{}')}catch(e){}
|
|
4550
|
+
var name=(data.meta&&data.meta.id)||'loadam-report';
|
|
4551
|
+
function dl(blob,filename){var u=URL.createObjectURL(blob),a=d.createElement('a');a.href=u;a.download=filename;d.body.appendChild(a);a.click();a.remove();setTimeout(function(){URL.revokeObjectURL(u)},1000)}
|
|
4552
|
+
var bH=d.querySelector('[data-loadam-download="html"]');
|
|
4553
|
+
if(bH)bH.addEventListener('click',function(){var c=root.cloneNode(true),t=c.querySelector('.tip');if(t)t.parentNode.removeChild(t);dl(new Blob(['<!doctype html>\\n'+c.outerHTML],{type:'text/html'}),name+'.html')});
|
|
4554
|
+
var bJ=d.querySelector('[data-loadam-download="json"]');
|
|
4555
|
+
if(bJ)bJ.addEventListener('click',function(){dl(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}),name+'.json')});
|
|
4556
|
+
var bP=d.querySelector('[data-loadam-print]');
|
|
4557
|
+
if(bP)bP.addEventListener('click',function(){window.print()});
|
|
4558
|
+
})();</script>`;
|
|
4559
|
+
var REPO = "https://github.com/DesmondSanctity/loadam";
|
|
4560
|
+
var MARK = `<svg class="mark" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" class="mark-bg"/><polyline points="4,23 10,23 12.5,19.5 15,23 18,9 21,23 28,23" fill="none" class="mark-line" stroke-width="2.5" stroke-linejoin="miter" stroke-miterlimit="10"/><rect x="15.5" y="2.5" width="5" height="5" fill="#C6FF3D"/></svg>`;
|
|
4561
|
+
function topBar() {
|
|
4562
|
+
return `<header class="top">
|
|
4563
|
+
<a class="brand" href="${REPO}" target="_blank" rel="noopener">${MARK}<span>loadam</span></a>
|
|
4564
|
+
<div class="top-actions js-only">
|
|
4565
|
+
<button type="button" class="btn" data-theme-toggle aria-label="Switch between light and dark">Theme</button>
|
|
4566
|
+
<button type="button" class="btn" data-loadam-download="html">Save report</button>
|
|
4567
|
+
<button type="button" class="btn" data-loadam-download="json">Raw data</button>
|
|
4568
|
+
<button type="button" class="btn" data-loadam-print>Print</button>
|
|
4569
|
+
</div>
|
|
4570
|
+
</header>`;
|
|
4346
4571
|
}
|
|
4347
|
-
function
|
|
4348
|
-
return
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4572
|
+
function kindLabel(meta, runs) {
|
|
4573
|
+
if (meta.command === "contract") return "Contract tests";
|
|
4574
|
+
if (meta.command === "diff") return "Drift check";
|
|
4575
|
+
const names = runs.map((r) => r.name);
|
|
4576
|
+
if (names.length > 0) {
|
|
4577
|
+
const words = names.map((n, i) => i === 0 ? n.charAt(0).toUpperCase() + n.slice(1) : n);
|
|
4578
|
+
return `${words.join(" + ")} test`;
|
|
4579
|
+
}
|
|
4580
|
+
const mode = meta.flags.mode;
|
|
4581
|
+
return typeof mode === "string" && mode !== "skip" ? `${mode} test` : "Test rig";
|
|
4582
|
+
}
|
|
4583
|
+
function verdict(model) {
|
|
4584
|
+
const { meta, overall, runs } = model;
|
|
4585
|
+
const facts = [["Started", fmtWhen(meta.startedAt)]];
|
|
4586
|
+
if (isNum(meta.durationMs)) facts.push(["Took", fmtDuration(meta.durationMs)]);
|
|
4587
|
+
const vus = model.primary?.vus;
|
|
4588
|
+
if (isNum(vus) && vus > 0) facts.push(["Virtual users", fmtInt(vus)]);
|
|
4589
|
+
if (isNum(meta.exitCode)) facts.push(["Exit code", String(meta.exitCode)]);
|
|
4590
|
+
const reasons = whyLines(model);
|
|
4591
|
+
return `<section class="verdict tone-${overall.tone}" aria-labelledby="title">
|
|
4592
|
+
<p class="eyebrow">${esc2(kindLabel(meta, runs))} <span class="dim">against</span> <code>${esc2(meta.target ?? "\u2014")}</code></p>
|
|
4593
|
+
<h1 id="title">${esc2(meta.spec.title ?? "Untitled API")}${meta.spec.version ? ` <span class="ver">${esc2(meta.spec.version)}</span>` : ""}</h1>
|
|
4594
|
+
<div class="verdict-row">
|
|
4595
|
+
<span class="status status-${overall.tone}">${esc2(overall.label.charAt(0).toUpperCase() + overall.label.slice(1))}</span>
|
|
4596
|
+
<p class="verdict-text">${verdictSentence(model)}</p>
|
|
4597
|
+
</div>
|
|
4598
|
+
${reasons.length > 0 ? `<div class="why"><h2 class="why-h">${overall.tone === "bad" ? "Why it failed" : "Worth a look"}</h2><ul>${reasons.map((r) => `<li>${r}</li>`).join("")}</ul></div>` : ""}
|
|
4599
|
+
<dl class="facts">${facts.map(([k, v]) => `<div><dt>${esc2(k)}</dt><dd>${esc2(v)}</dd></div>`).join("")}</dl>
|
|
4356
4600
|
</section>`;
|
|
4357
4601
|
}
|
|
4358
|
-
function
|
|
4359
|
-
const
|
|
4360
|
-
|
|
4361
|
-
)
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
${
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4602
|
+
function verdictSentence(model) {
|
|
4603
|
+
const { meta, endpoints: endpoints2, primary } = model;
|
|
4604
|
+
const s = meta.summary ?? {};
|
|
4605
|
+
if (meta.command === "diff") {
|
|
4606
|
+
const probed = Number(s.probed ?? 0);
|
|
4607
|
+
const findings = Number(s.findings ?? 0);
|
|
4608
|
+
if (findings === 0)
|
|
4609
|
+
return `The live API matches the spec on all ${plural(probed, "probed operation")}.`;
|
|
4610
|
+
const parts2 = [
|
|
4611
|
+
Number(s.error) > 0 ? plural(Number(s.error), "error") : "",
|
|
4612
|
+
Number(s.warning) > 0 ? plural(Number(s.warning), "warning") : "",
|
|
4613
|
+
Number(s.info) > 0 ? `${fmtInt(Number(s.info))} info` : ""
|
|
4614
|
+
].filter(Boolean);
|
|
4615
|
+
return `${plural(findings, "difference")} between the spec and the live API across ${plural(probed, "probed operation")}: ${parts2.join(", ")}.`;
|
|
4616
|
+
}
|
|
4617
|
+
if (meta.command === "contract") {
|
|
4618
|
+
if (isNum(s.tests)) {
|
|
4619
|
+
const failed = Number(s.failed ?? model.contractFailures.length);
|
|
4620
|
+
return failed > 0 ? `${fmtInt(failed)} of ${plural(s.tests, "test")} failed.` : `All ${plural(s.tests, "test")} passed${Number(s.skipped) > 0 ? `, ${fmtInt(Number(s.skipped))} skipped` : ""}.`;
|
|
4621
|
+
}
|
|
4622
|
+
const why = typeof s.skipped === "string" ? ` (${esc2(s.skipped)})` : "";
|
|
4623
|
+
return `The suite was generated but not run${why}.`;
|
|
4624
|
+
}
|
|
4625
|
+
if (s.authPreflight === "failed")
|
|
4626
|
+
return "The credentials were rejected before any load was sent, so nothing was measured.";
|
|
4627
|
+
if (!primary) {
|
|
4628
|
+
const why = typeof s.skipped === "string" ? ` (${esc2(s.skipped)})` : "";
|
|
4629
|
+
return `The rig was generated but not run${why}.`;
|
|
4630
|
+
}
|
|
4631
|
+
const ran = endpoints2.filter((e) => e.tone !== "muted");
|
|
4632
|
+
const notRun = endpoints2.length - ran.length;
|
|
4633
|
+
const bad = ran.filter((e) => e.tone === "bad").length;
|
|
4634
|
+
const warn = ran.filter((e) => e.tone === "warn").length;
|
|
4635
|
+
const parts = [];
|
|
4636
|
+
if (ran.length > 0) {
|
|
4637
|
+
if (bad === 0 && warn === 0)
|
|
4638
|
+
parts.push(`All ${plural(ran.length, "endpoint")} that ran passed.`);
|
|
4639
|
+
else {
|
|
4640
|
+
const bits = [bad ? `${fmtInt(bad)} failed` : "", warn ? `${fmtInt(warn)} flaky` : ""];
|
|
4641
|
+
parts.push(`${bits.filter(Boolean).join(" and ")} of ${plural(ran.length, "endpoint")}.`);
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
const nums = [];
|
|
4645
|
+
if (isNum(primary.requests))
|
|
4646
|
+
nums.push(
|
|
4647
|
+
`${plural(primary.requests, "request")}${isNum(primary.rps) ? ` at ${fmtPerSec(primary.rps)}` : ""}`
|
|
4648
|
+
);
|
|
4649
|
+
if (isNum(primary.p95)) nums.push(`p95 ${fmtMs(primary.p95)}`);
|
|
4650
|
+
if (isNum(primary.errRate)) nums.push(`${fmtPct(primary.errRate)} failed`);
|
|
4651
|
+
if (nums.length > 0)
|
|
4652
|
+
parts.push(
|
|
4653
|
+
`${model.runs.length > 1 ? `The ${esc2(primary.name)} run: ` : ""}${nums.join(", ")}.`
|
|
4654
|
+
);
|
|
4655
|
+
if (notRun > 0)
|
|
4656
|
+
parts.push(
|
|
4657
|
+
notRun === 1 ? "1 endpoint wasn't called." : `${fmtInt(notRun)} endpoints weren't called.`
|
|
4658
|
+
);
|
|
4659
|
+
return parts.join(" ") || "No requests were recorded.";
|
|
4380
4660
|
}
|
|
4381
|
-
function
|
|
4382
|
-
return
|
|
4383
|
-
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4661
|
+
function whyLines(model) {
|
|
4662
|
+
if (model.overall.tone === "ok" || model.overall.tone === "muted") return [];
|
|
4663
|
+
const out = [];
|
|
4664
|
+
const failed = model.thresholds.filter((t) => !t.ok);
|
|
4665
|
+
const multi = model.runs.length > 1;
|
|
4666
|
+
for (const t of failed.slice(0, 4)) {
|
|
4667
|
+
out.push(
|
|
4668
|
+
`${multi && t.run ? `<span class="dim">${esc2(t.run)}:</span> ` : ""}${esc2(metricName(t.metric))} ${thresholdSentence(t)}`
|
|
4669
|
+
);
|
|
4670
|
+
}
|
|
4671
|
+
if (failed.length > 4)
|
|
4672
|
+
out.push(`${fmtInt(failed.length - 4)} more thresholds failed (listed below).`);
|
|
4673
|
+
const badEps = [
|
|
4674
|
+
...model.endpoints.filter((e) => e.tone === "bad"),
|
|
4675
|
+
...model.endpoints.filter((e) => e.tone === "warn")
|
|
4676
|
+
];
|
|
4677
|
+
for (const e of badEps.slice(0, 3)) {
|
|
4678
|
+
out.push(
|
|
4679
|
+
`<a href="#${esc2(e.slug)}" data-open-endpoint="${esc2(e.slug)}"><span class="m">${esc2(e.op.method.toUpperCase())}</span> <code>${esc2(e.op.path)}</code></a> ${esc2(e.label)}: ${esc2(fmtPassRate(e.rate))} of checks passed`
|
|
4680
|
+
);
|
|
4681
|
+
}
|
|
4682
|
+
if (badEps.length > 3) out.push(`${fmtInt(badEps.length - 3)} more endpoints need a look.`);
|
|
4683
|
+
for (const r of model.runs) {
|
|
4684
|
+
if (isNum(r.rejected) && r.rejected > 0)
|
|
4685
|
+
out.push(
|
|
4686
|
+
`${multi ? `<span class="dim">${esc2(r.name)}:</span> ` : ""}${plural(r.rejected, "request")} rejected with 401 or 403 after a token renewal.`
|
|
4687
|
+
);
|
|
4688
|
+
}
|
|
4689
|
+
if (model.meta.command === "diff") {
|
|
4690
|
+
const errors = Number(model.meta.summary?.error ?? 0);
|
|
4691
|
+
const warnings = Number(model.meta.summary?.warning ?? 0);
|
|
4692
|
+
if (errors > 0)
|
|
4693
|
+
out.push(
|
|
4694
|
+
`${plural(errors, "error")}: the API answered in a way the spec doesn't allow (listed below).`
|
|
4695
|
+
);
|
|
4696
|
+
else if (warnings > 0)
|
|
4697
|
+
out.push(
|
|
4698
|
+
`${plural(warnings, "warning")}: responses that differ from the spec (listed below).`
|
|
4699
|
+
);
|
|
4700
|
+
}
|
|
4701
|
+
if (model.contractFailures.length > 0)
|
|
4702
|
+
out.push(`${plural(model.contractFailures.length, "contract test")} failed (listed below).`);
|
|
4703
|
+
if (model.meta.summary?.authPreflight === "failed")
|
|
4704
|
+
out.push("The auth check before the run failed. Check the credentials in your env vars.");
|
|
4705
|
+
if (out.length === 0 && isNum(model.meta.exitCode) && model.meta.exitCode !== 0)
|
|
4706
|
+
out.push(`The process exited with code <code>${model.meta.exitCode}</code>.`);
|
|
4707
|
+
return out;
|
|
4388
4708
|
}
|
|
4389
|
-
function
|
|
4390
|
-
|
|
4391
|
-
return
|
|
4709
|
+
function runSwitcher(model) {
|
|
4710
|
+
if (model.runs.length < 2) return "";
|
|
4711
|
+
return `<div class="runs js-only" role="tablist" aria-label="Run">
|
|
4712
|
+
${model.runs.map(
|
|
4713
|
+
(r) => `<button type="button" role="tab" class="run-tab" data-run-tab="${esc2(r.slug)}" aria-selected="${r === model.primary}">${esc2(r.name)}</button>`
|
|
4714
|
+
).join("")}
|
|
4715
|
+
</div>`;
|
|
4716
|
+
}
|
|
4717
|
+
var TILE_METRIC = {
|
|
4718
|
+
http_reqs: "Requests",
|
|
4719
|
+
http_req_duration: "p95 latency",
|
|
4720
|
+
http_req_failed: "Failed requests",
|
|
4721
|
+
checks: "Checks passed"
|
|
4722
|
+
};
|
|
4723
|
+
function tiles(model) {
|
|
4724
|
+
const { meta, runs } = model;
|
|
4725
|
+
if (runs.length > 0) {
|
|
4726
|
+
return runs.map((r) => {
|
|
4727
|
+
const list2 = [];
|
|
4728
|
+
const lim = (metric) => tileLimit(r, metric);
|
|
4729
|
+
if (isNum(r.requests))
|
|
4730
|
+
list2.push({ label: "Requests", value: fmtInt(r.requests), ...lim("http_reqs") });
|
|
4731
|
+
if (isNum(r.rps)) list2.push({ label: "Throughput", value: fmtPerSec(r.rps) });
|
|
4732
|
+
if (isNum(r.p95))
|
|
4733
|
+
list2.push({ label: "p95 latency", value: fmtMs(r.p95), ...lim("http_req_duration") });
|
|
4734
|
+
if (isNum(r.errRate))
|
|
4735
|
+
list2.push({
|
|
4736
|
+
label: "Failed requests",
|
|
4737
|
+
value: fmtPct(r.errRate),
|
|
4738
|
+
...lim("http_req_failed")
|
|
4739
|
+
});
|
|
4740
|
+
if (r.checks)
|
|
4741
|
+
list2.push({
|
|
4742
|
+
label: "Checks passed",
|
|
4743
|
+
value: fmtPassRate(r.checks.passes / r.checks.total) || "\u2014",
|
|
4744
|
+
sub: `${fmtInt(r.checks.passes)} of ${fmtInt(r.checks.total)}`,
|
|
4745
|
+
...lim("checks")
|
|
4746
|
+
});
|
|
4747
|
+
if (isNum(r.renewals) && r.renewals > 0)
|
|
4748
|
+
list2.push({
|
|
4749
|
+
label: "Token renewals",
|
|
4750
|
+
value: fmtInt(r.renewals),
|
|
4751
|
+
sub: "fetched before expiry or after a 401"
|
|
4752
|
+
});
|
|
4753
|
+
if (isNum(r.rejected) && r.rejected > 0)
|
|
4754
|
+
list2.push({
|
|
4755
|
+
label: "Auth rejected",
|
|
4756
|
+
value: fmtInt(r.rejected),
|
|
4757
|
+
sub: "401/403 after renewal",
|
|
4758
|
+
tone: "bad"
|
|
4759
|
+
});
|
|
4760
|
+
return tileGrid(list2, r.slug);
|
|
4761
|
+
}).join("");
|
|
4762
|
+
}
|
|
4763
|
+
const s = meta.summary ?? {};
|
|
4764
|
+
const list = [];
|
|
4765
|
+
if (meta.command === "contract") {
|
|
4766
|
+
for (const [k, label] of [
|
|
4767
|
+
["tests", "Tests"],
|
|
4768
|
+
["passed", "Passed"],
|
|
4769
|
+
["failed", "Failed"],
|
|
4770
|
+
["skipped", "Skipped"],
|
|
4771
|
+
["operations", "Operations"],
|
|
4772
|
+
["files", "Test files"]
|
|
4773
|
+
])
|
|
4774
|
+
if (isNum(s[k]))
|
|
4775
|
+
list.push({
|
|
4776
|
+
label,
|
|
4777
|
+
value: fmtInt(s[k]),
|
|
4778
|
+
tone: k === "failed" && Number(s[k]) > 0 ? "bad" : void 0
|
|
4779
|
+
});
|
|
4780
|
+
} else if (meta.command === "diff") {
|
|
4781
|
+
for (const [k, label] of [
|
|
4782
|
+
["probed", "Probed"],
|
|
4783
|
+
["findings", "Findings"],
|
|
4784
|
+
["error", "Errors"],
|
|
4785
|
+
["warning", "Warnings"],
|
|
4786
|
+
["info", "Info"],
|
|
4787
|
+
["skipped", "Skipped"]
|
|
4788
|
+
])
|
|
4789
|
+
if (isNum(s[k]))
|
|
4790
|
+
list.push({
|
|
4791
|
+
label,
|
|
4792
|
+
value: fmtInt(s[k]),
|
|
4793
|
+
tone: k === "error" && Number(s[k]) > 0 ? "bad" : void 0
|
|
4794
|
+
});
|
|
4795
|
+
} else {
|
|
4796
|
+
for (const [k, v] of Object.entries(s))
|
|
4797
|
+
if (isNum(v)) list.push({ label: humanize(k), value: fmtInt(v) });
|
|
4798
|
+
}
|
|
4799
|
+
return list.length > 0 ? tileGrid(list) : "";
|
|
4392
4800
|
}
|
|
4393
|
-
function
|
|
4394
|
-
|
|
4395
|
-
if (
|
|
4396
|
-
return
|
|
4801
|
+
function tileLimit(r, metric) {
|
|
4802
|
+
const t = r.thresholds.find((x) => x.metric === metric);
|
|
4803
|
+
if (!t) return {};
|
|
4804
|
+
return {
|
|
4805
|
+
sub: `${t.ok ? "within" : "over"} limit: ${ruleText(t)}`,
|
|
4806
|
+
tone: t.ok ? void 0 : "bad"
|
|
4807
|
+
};
|
|
4397
4808
|
}
|
|
4398
|
-
function
|
|
4399
|
-
|
|
4809
|
+
function tileGrid(list, run) {
|
|
4810
|
+
if (list.length === 0) return "";
|
|
4811
|
+
return `<div class="tiles"${run ? ` data-run="${esc2(run)}"` : ""}>${list.map(
|
|
4812
|
+
(t) => `<div class="tile${t.tone ? ` tile-${t.tone}` : ""}"><div class="tile-l">${esc2(t.label)}</div><div class="tile-v">${esc2(t.value)}</div>${t.sub ? `<div class="tile-s">${esc2(t.sub)}</div>` : ""}</div>`
|
|
4813
|
+
).join("")}</div>`;
|
|
4814
|
+
}
|
|
4815
|
+
var LADDER = [
|
|
4816
|
+
["min", "min"],
|
|
4817
|
+
["med", "median"],
|
|
4818
|
+
["p(90)", "p90"],
|
|
4819
|
+
["p(95)", "p95"],
|
|
4820
|
+
["p(99)", "p99"],
|
|
4821
|
+
["max", "max"]
|
|
4822
|
+
];
|
|
4823
|
+
function latency(model) {
|
|
4824
|
+
const blocks = model.runs.map((r) => latencyBlock(r)).filter(Boolean);
|
|
4825
|
+
if (blocks.length === 0) return "";
|
|
4826
|
+
return `<section class="panel" aria-labelledby="lat-h">
|
|
4827
|
+
<div class="panel-h"><h2 id="lat-h">Latency</h2><p class="panel-sub">How long requests took, across all endpoints.</p></div>
|
|
4828
|
+
${blocks.join("")}
|
|
4829
|
+
</section>`;
|
|
4400
4830
|
}
|
|
4401
|
-
function
|
|
4402
|
-
|
|
4831
|
+
function latencyBlock(r) {
|
|
4832
|
+
const d = r.latency;
|
|
4833
|
+
if (!d) return "";
|
|
4834
|
+
const rows = LADDER.filter(([k]) => isNum(d[k]));
|
|
4835
|
+
if (rows.length < 2) return "";
|
|
4836
|
+
const limitT = r.thresholds.find((t) => t.metric === "http_req_duration" && isNum(t.limit));
|
|
4837
|
+
const limit = limitT?.limit;
|
|
4838
|
+
const values = rows.map(([k]) => d[k]);
|
|
4839
|
+
const positive = values.filter((v) => v > 0);
|
|
4840
|
+
const hiRaw = Math.max(...values, limit ?? 0);
|
|
4841
|
+
const loRaw = positive.length ? Math.min(...positive) : 0;
|
|
4842
|
+
const log = loRaw > 0 && hiRaw / loRaw > 50;
|
|
4843
|
+
let lo = 0;
|
|
4844
|
+
let hi = hiRaw * 1.08;
|
|
4845
|
+
let pos;
|
|
4846
|
+
let ticks;
|
|
4847
|
+
if (log) {
|
|
4848
|
+
lo = 10 ** Math.floor(Math.log10(loRaw));
|
|
4849
|
+
hi = 10 ** Math.ceil(Math.log10(hiRaw * 1.0001));
|
|
4850
|
+
const span = Math.log10(hi) - Math.log10(lo);
|
|
4851
|
+
pos = (v) => v <= lo ? 0 : (Math.log10(v) - Math.log10(lo)) / span * 100;
|
|
4852
|
+
ticks = [];
|
|
4853
|
+
for (let t = lo; t <= hi * 1.0001; t *= 10) ticks.push(t);
|
|
4854
|
+
} else {
|
|
4855
|
+
const step = niceStep(hi / 4);
|
|
4856
|
+
hi = Math.ceil(hi / step) * step;
|
|
4857
|
+
pos = (v) => v / hi * 100;
|
|
4858
|
+
ticks = [];
|
|
4859
|
+
for (let t = 0; t <= hi + step / 2; t += step) ticks.push(t);
|
|
4860
|
+
}
|
|
4861
|
+
const clamp = (n) => Math.max(0, Math.min(100, n));
|
|
4862
|
+
const bars = rows.map(([k, label]) => {
|
|
4863
|
+
const v = d[k];
|
|
4864
|
+
const w = clamp(pos(v));
|
|
4865
|
+
const hot = k === "p(95)";
|
|
4866
|
+
return `<div class="lad-row${hot ? " hot" : ""}" data-tip="${esc2(label)}: ${esc2(fmtMs(v))}"><span class="lad-l">${esc2(label)}</span><span class="lad-track"><i style="width:${Math.max(w, 0.6).toFixed(2)}%"></i></span><span class="lad-v">${esc2(fmtMs(v))}</span></div>`;
|
|
4867
|
+
}).join("");
|
|
4868
|
+
const grid = ticks.map(
|
|
4869
|
+
(t) => `<span class="lad-tick" style="left:${clamp(pos(t)).toFixed(2)}%"><b>${esc2(fmtTick(t))}</b></span>`
|
|
4870
|
+
).join("");
|
|
4871
|
+
const limitLine = isNum(limit) ? `<span class="lad-limit${limitT?.ok ? "" : " over"}" style="left:${clamp(pos(limit)).toFixed(2)}%"><b>p95 limit ${esc2(fmtMs(limit))}</b></span>` : "";
|
|
4872
|
+
return `<div class="ladder" data-run="${esc2(r.slug)}">
|
|
4873
|
+
<div class="lad-plot">${bars}<div class="lad-overlay" aria-hidden="true">${grid}${limitLine}</div></div>
|
|
4874
|
+
<p class="note">${log ? "Log scale: each gridline is ten times the one before, so fast and slow requests fit on one chart. " : ""}${isNum(d.avg) ? `Average ${esc2(fmtMs(d.avg))}.` : ""}</p>
|
|
4875
|
+
</div>`;
|
|
4876
|
+
}
|
|
4877
|
+
function fmtTick(v) {
|
|
4878
|
+
if (v >= 1e3) return `${Number((v / 1e3).toPrecision(3))} s`;
|
|
4879
|
+
return `${Number(v.toPrecision(3))} ms`;
|
|
4880
|
+
}
|
|
4881
|
+
function niceStep(raw) {
|
|
4882
|
+
if (raw <= 0) return 1;
|
|
4883
|
+
const p = 10 ** Math.floor(Math.log10(raw));
|
|
4884
|
+
const n = raw / p;
|
|
4885
|
+
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p;
|
|
4886
|
+
}
|
|
4887
|
+
var TONE_RANK = { bad: 0, warn: 1, ok: 2, muted: 3 };
|
|
4888
|
+
var BUCKETS = ["2xx", "3xx", "4xx", "5xx", "1xx"];
|
|
4889
|
+
function endpoints(model) {
|
|
4890
|
+
const eps = model.endpoints;
|
|
4891
|
+
if (eps.length === 0) return "";
|
|
4892
|
+
const runs = model.runs;
|
|
4893
|
+
const counts = { bad: 0, warn: 0, ok: 0, muted: 0 };
|
|
4894
|
+
for (const e of eps) counts[e.tone]++;
|
|
4895
|
+
const sorted = eps.map((e, i) => ({ e, i })).sort((a, b) => TONE_RANK[a.e.tone] - TONE_RANK[b.e.tone] || a.i - b.i).map((x) => x.e);
|
|
4896
|
+
const maxP95 = {};
|
|
4897
|
+
const slowest = {};
|
|
4898
|
+
for (const r of runs) {
|
|
4899
|
+
let max = 0;
|
|
4900
|
+
for (const e of eps) {
|
|
4901
|
+
const p = e.runs[r.name]?.p95;
|
|
4902
|
+
if (isNum(p) && p > max) {
|
|
4903
|
+
max = p;
|
|
4904
|
+
slowest[r.name] = e.slug;
|
|
4905
|
+
}
|
|
4906
|
+
}
|
|
4907
|
+
maxP95[r.name] = max;
|
|
4908
|
+
}
|
|
4909
|
+
const sub = [
|
|
4910
|
+
plural(eps.length, "endpoint"),
|
|
4911
|
+
counts.ok ? `${fmtInt(counts.ok)} passed` : "",
|
|
4912
|
+
counts.warn ? `${fmtInt(counts.warn)} flaky` : "",
|
|
4913
|
+
counts.bad ? `${fmtInt(counts.bad)} failed` : "",
|
|
4914
|
+
counts.muted ? `${fmtInt(counts.muted)} not run` : ""
|
|
4915
|
+
].filter(Boolean).join(" \xB7 ");
|
|
4916
|
+
const chip = (key, label, n) => `<button type="button" class="chip" data-filter="${key}" aria-pressed="${key === "all"}"${n === 0 && key !== "all" ? " disabled" : ""}>${label} <span>${fmtInt(n)}</span></button>`;
|
|
4917
|
+
const rows = sorted.map((e) => endpointRow(e, runs, maxP95, slowest)).join("");
|
|
4918
|
+
const hasRuns = runs.length > 0;
|
|
4919
|
+
return `<section class="panel" id="endpoints" aria-labelledby="ep-h">
|
|
4920
|
+
<div class="panel-h"><h2 id="ep-h">Endpoints</h2><p class="panel-sub">${esc2(sub)}</p></div>
|
|
4921
|
+
<div class="toolbar js-only">
|
|
4922
|
+
<div class="chips" role="group" aria-label="Show">
|
|
4923
|
+
${chip("all", "All", eps.length)}${chip("bad", "Failed", counts.bad)}${chip("warn", "Flaky", counts.warn)}${chip("ok", "Passed", counts.ok)}${chip("muted", "Not run", counts.muted)}
|
|
4924
|
+
</div>
|
|
4925
|
+
<label class="search"><span class="sr">Find an endpoint</span><input type="search" placeholder="Search path, method or operation" data-ep-search autocomplete="off"></label>
|
|
4926
|
+
<label class="sort-m"><span class="sr">Sort by</span><select data-ep-sort-select>
|
|
4927
|
+
<option value="result">Sort: result</option><option value="p95">Sort: slowest</option><option value="reqs">Sort: most requests</option><option value="path">Sort: path</option>
|
|
4928
|
+
</select></label>
|
|
4929
|
+
</div>
|
|
4930
|
+
<div class="table-wrap">
|
|
4931
|
+
<table class="ep-table">
|
|
4932
|
+
<caption class="sr">Endpoints, ${esc2(sub)}. Select a row for its checks and status codes.</caption>
|
|
4933
|
+
<thead><tr>
|
|
4934
|
+
<th scope="col"><button type="button" data-sort="path">Endpoint</button></th>
|
|
4935
|
+
<th scope="col" aria-sort="ascending"><button type="button" data-sort="result">Result</button></th>
|
|
4936
|
+
${hasRuns ? `<th scope="col" class="num"><button type="button" data-sort="reqs">Requests</button></th>
|
|
4937
|
+
<th scope="col" class="c-p95h"><button type="button" data-sort="p95">p95</button></th>
|
|
4938
|
+
<th scope="col" class="c-codesh">Status codes</th>` : ""}
|
|
4939
|
+
<th scope="col" class="c-x"><span class="sr">Details</span></th>
|
|
4940
|
+
</tr></thead>
|
|
4941
|
+
<tbody>${rows}</tbody>
|
|
4942
|
+
</table>
|
|
4943
|
+
<p class="empty" hidden>No endpoints match. Clear the search or pick another filter.</p>
|
|
4944
|
+
</div>
|
|
4945
|
+
<nav class="pager js-only" aria-label="Endpoint pages" hidden><p class="pager-info" aria-live="polite"></p><div class="pager-btns"></div></nav>
|
|
4946
|
+
<p class="note">Passed means at least ${PASS_RATE_OK * 100}% of an endpoint's checks held, flaky ${PASS_RATE_WARN * 100}\u2013${PASS_RATE_OK * 100}%, failed below ${PASS_RATE_WARN * 100}%. Login and logout calls aren't part of the measured run.${hasRuns ? ` <span class="legend"><i class="b2"></i>2xx <i class="b3"></i>3xx <i class="b4"></i>4xx <i class="b5"></i>5xx</span>` : ""}</p>
|
|
4947
|
+
</section>`;
|
|
4403
4948
|
}
|
|
4949
|
+
function endpointRow(e, runs, maxP95, slowest) {
|
|
4950
|
+
const m = e.op.method.toUpperCase();
|
|
4951
|
+
const perRun = (fn) => runs.map((r) => `<span class="per" data-run="${esc2(r.slug)}">${fn(r)}</span>`).join("");
|
|
4952
|
+
const dataAttrs = runs.map((r) => {
|
|
4953
|
+
const x = e.runs[r.name];
|
|
4954
|
+
return ` data-reqs-${esc2(r.slug)}="${x?.total ?? 0}" data-p95-${esc2(r.slug)}="${isNum(x?.p95) ? x.p95 : -1}"`;
|
|
4955
|
+
}).join("");
|
|
4956
|
+
const cells = runs.length ? `<td class="num c-reqs" data-label="Requests">${perRun((r) => {
|
|
4957
|
+
const t = e.runs[r.name]?.total ?? 0;
|
|
4958
|
+
return t > 0 ? fmtInt(t) : `<span class="dim">\u2014</span>`;
|
|
4959
|
+
})}</td>
|
|
4960
|
+
<td class="c-p95" data-label="p95">${perRun((r) => {
|
|
4961
|
+
const p = e.runs[r.name]?.p95;
|
|
4962
|
+
if (!isNum(p)) return `<span class="dim">\u2014</span>`;
|
|
4963
|
+
const max = maxP95[r.name] || 1;
|
|
4964
|
+
const hot = slowest[r.name] === e.slug && runs.length > 0;
|
|
4965
|
+
return `<span class="p95${hot ? " hot" : ""}" data-tip="p95 ${esc2(fmtMs(p))}${hot ? " \xB7 slowest endpoint" : ""}"><span class="p95-v">${esc2(fmtMs(p))}</span><span class="p95-track"><i style="width:${Math.max(p / max * 100, 1).toFixed(2)}%"></i></span></span>`;
|
|
4966
|
+
})}</td>
|
|
4967
|
+
<td class="c-codes" data-label="Status codes">${perRun((r) => codeBar(e.runs[r.name]?.buckets ?? {}))}</td>` : "";
|
|
4968
|
+
return `<tr class="ep-row" id="${esc2(e.slug)}" data-state="${e.tone}" data-rank="${TONE_RANK[e.tone]}" data-rate="${isNum(e.rate) ? e.rate : -1}" data-key="${esc2(`${m} ${e.op.path} ${e.op.id} ${e.op.summary ?? ""}`.toLowerCase())}" data-path="${esc2(e.op.path)}"${dataAttrs} tabindex="0" aria-expanded="false" aria-controls="${esc2(e.slug)}-d">
|
|
4969
|
+
<td class="c-ep"><span class="m">${esc2(m)}</span><code class="path">${esc2(e.op.path)}</code>${e.op.summary ? `<span class="ep-sum">${esc2(e.op.summary)}</span>` : ""}</td>
|
|
4970
|
+
<td class="c-res" data-label="Result"><span class="pill pill-${e.tone}">${esc2(e.label)}</span>${isNum(e.rate) ? `<span class="rate">${esc2(fmtPassRate(e.rate))}</span>` : ""}</td>
|
|
4971
|
+
${cells}
|
|
4972
|
+
<td class="c-x" aria-hidden="true"><span class="chev"></span></td>
|
|
4973
|
+
</tr>
|
|
4974
|
+
<tr class="ep-detail" id="${esc2(e.slug)}-d"><td colspan="${runs.length ? 6 : 3}">${endpointDetail(e, runs)}</td></tr>`;
|
|
4975
|
+
}
|
|
4976
|
+
function codeBar(buckets) {
|
|
4977
|
+
const total = Object.values(buckets).reduce((a, b) => a + b, 0);
|
|
4978
|
+
if (total === 0) return `<span class="dim">\u2014</span>`;
|
|
4979
|
+
const segs = BUCKETS.filter((b) => (buckets[b] ?? 0) > 0).map((b) => {
|
|
4980
|
+
const n = buckets[b] ?? 0;
|
|
4981
|
+
const pct = n / total * 100;
|
|
4982
|
+
return `<i class="b${b[0]}" style="flex-grow:${pct.toFixed(3)}" data-tip="${b}: ${fmtInt(n)} (${pct < 0.1 ? "<0.1" : pct.toFixed(1)}%)"></i>`;
|
|
4983
|
+
}).join("");
|
|
4984
|
+
const share2 = ((buckets["2xx"] ?? 0) + (buckets["3xx"] ?? 0)) / total;
|
|
4985
|
+
return `<span class="codes" role="img" aria-label="${esc2(
|
|
4986
|
+
BUCKETS.filter((b) => buckets[b]).map((b) => `${b} ${fmtInt(buckets[b] ?? 0)}`).join(", ")
|
|
4987
|
+
)}">${segs}</span><span class="codes-n">${share2 >= 0.9995 ? "all 2xx/3xx" : `${fmtPassRate(share2) || "0%"} 2xx/3xx`}</span>`;
|
|
4988
|
+
}
|
|
4989
|
+
function endpointDetail(e, runs) {
|
|
4990
|
+
const blocks = [];
|
|
4991
|
+
if (e.checks.length > 0) {
|
|
4992
|
+
blocks.push(
|
|
4993
|
+
`<div class="d-block"><h3>Checks</h3><table class="mini"><thead><tr>${runs.length > 1 ? "<th>Run</th>" : ""}<th>Check</th><th class="num">Held</th><th class="num">Rate</th></tr></thead><tbody>${e.checks.map((c) => {
|
|
4994
|
+
const [tone] = tierFor(c.total > 0 ? c.passes / c.total : null);
|
|
4995
|
+
return `<tr>${runs.length > 1 ? `<td>${esc2(c.run)}</td>` : ""}<td><code>${esc2(c.name)}</code></td><td class="num">${fmtInt(c.passes)} / ${fmtInt(c.total)}</td><td class="num"><span class="dot dot-${tone}"></span>${esc2(fmtPassRate(c.total ? c.passes / c.total : null))}</td></tr>`;
|
|
4996
|
+
}).join("")}</tbody></table></div>`
|
|
4997
|
+
);
|
|
4998
|
+
} else {
|
|
4999
|
+
blocks.push(
|
|
5000
|
+
`<div class="d-block"><h3>Checks</h3><p class="dim">This endpoint wasn't called in the run. Logins, logouts and operations loadam couldn't build a request for are left out.</p></div>`
|
|
5001
|
+
);
|
|
5002
|
+
}
|
|
5003
|
+
const withCodes = runs.filter((r) => (e.runs[r.name]?.total ?? 0) > 0);
|
|
5004
|
+
if (withCodes.length > 0) {
|
|
5005
|
+
blocks.push(
|
|
5006
|
+
`<div class="d-block"><h3>Responses</h3><table class="mini"><thead><tr>${runs.length > 1 ? "<th>Run</th>" : ""}<th>Status</th><th class="num">Count</th><th class="num">Share</th></tr></thead><tbody>${withCodes.flatMap((r) => {
|
|
5007
|
+
const x = e.runs[r.name];
|
|
5008
|
+
if (!x) return [];
|
|
5009
|
+
return BUCKETS.filter((b) => (x.buckets[b] ?? 0) > 0).map(
|
|
5010
|
+
(b) => `<tr>${runs.length > 1 ? `<td>${esc2(r.name)}</td>` : ""}<td><i class="sw b${b[0]}"></i>${b}</td><td class="num">${fmtInt(x.buckets[b])}</td><td class="num">${((x.buckets[b] ?? 0) / x.total * 100).toFixed(1)}%</td></tr>`
|
|
5011
|
+
);
|
|
5012
|
+
}).join("")}${withCodes.map((r) => {
|
|
5013
|
+
const p = e.runs[r.name]?.p95;
|
|
5014
|
+
return isNum(p) ? `<tr class="sum">${runs.length > 1 ? `<td>${esc2(r.name)}</td>` : ""}<td>p95 latency</td><td class="num" colspan="2">${esc2(fmtMs(p))}</td></tr>` : "";
|
|
5015
|
+
}).join("")}</tbody></table></div>`
|
|
5016
|
+
);
|
|
5017
|
+
}
|
|
5018
|
+
const tags = (e.op.tags ?? []).map((t) => `<span class="tag">${esc2(t)}</span>`).join("");
|
|
5019
|
+
blocks.push(
|
|
5020
|
+
`<div class="d-block d-op"><h3>Operation</h3><p><code>${esc2(e.op.id)}</code></p>${tags ? `<p class="tags">${tags}</p>` : ""}</div>`
|
|
5021
|
+
);
|
|
5022
|
+
return `<div class="detail">${blocks.join("")}</div>`;
|
|
5023
|
+
}
|
|
5024
|
+
function thresholdsTable(model) {
|
|
5025
|
+
const onTiles = model.runs.length > 0 ? new Set(Object.keys(TILE_METRIC)) : /* @__PURE__ */ new Set();
|
|
5026
|
+
const list = model.thresholds.filter((t) => !onTiles.has(t.metric));
|
|
5027
|
+
if (list.length === 0) return "";
|
|
5028
|
+
const multi = new Set(list.map((t) => t.run)).size > 1;
|
|
5029
|
+
const failed = list.filter((t) => !t.ok).length;
|
|
5030
|
+
return `<section class="panel" aria-labelledby="thr-h">
|
|
5031
|
+
<div class="panel-h"><h2 id="thr-h">Thresholds</h2><p class="panel-sub">${failed ? `${fmtInt(failed)} of ${fmtInt(list.length)} failed` : `All ${fmtInt(list.length)} held`}</p></div>
|
|
5032
|
+
<div class="table-wrap"><table class="mini thr">
|
|
5033
|
+
<thead><tr>${multi ? "<th>Run</th>" : ""}<th>Metric</th><th>Limit</th><th class="num">Measured</th><th>Result</th></tr></thead>
|
|
5034
|
+
<tbody>${[...list].sort((a, b) => Number(a.ok) - Number(b.ok)).map(
|
|
5035
|
+
(t) => `<tr>${multi ? `<td>${esc2(t.run)}</td>` : ""}<td>${esc2(metricName(t.metric))}<br><code class="dim">${esc2(t.metric)}</code></td><td><code>${esc2(t.expr || "\u2014")}</code></td><td class="num">${isNum(t.measured) ? esc2(fmtUnit(t.measured, t.unit)) : "\u2014"}</td><td><span class="pill pill-${t.ok ? "ok" : "bad"}">${t.ok ? "held" : "failed"}</span></td></tr>`
|
|
5036
|
+
).join("")}</tbody>
|
|
5037
|
+
</table></div>
|
|
5038
|
+
</section>`;
|
|
5039
|
+
}
|
|
5040
|
+
var METRIC_NAMES = {
|
|
5041
|
+
http_req_duration: "Latency",
|
|
5042
|
+
http_req_failed: "Failed requests",
|
|
5043
|
+
http_reqs: "Requests",
|
|
5044
|
+
checks: "Checks",
|
|
5045
|
+
iteration_duration: "Iteration time",
|
|
5046
|
+
loadam_auth_rejected: "Auth rejections",
|
|
5047
|
+
loadam_auth_refreshes: "Token renewals"
|
|
5048
|
+
};
|
|
5049
|
+
function metricName(metric) {
|
|
5050
|
+
const base = metric.replace(/\{.*$/, "");
|
|
5051
|
+
return METRIC_NAMES[base] ?? humanize(base);
|
|
5052
|
+
}
|
|
5053
|
+
var STAT_NAMES = {
|
|
5054
|
+
"p(90)": "p90",
|
|
5055
|
+
"p(95)": "p95",
|
|
5056
|
+
"p(99)": "p99",
|
|
5057
|
+
med: "median"
|
|
5058
|
+
};
|
|
5059
|
+
function limitText(t) {
|
|
5060
|
+
const op = t.op === ">=" ? "\u2265" : t.op === "<=" ? "\u2264" : t.op === "!=" ? "\u2260" : t.op;
|
|
5061
|
+
return `${op} ${fmtUnit(t.limit ?? 0, t.unit)}`;
|
|
5062
|
+
}
|
|
5063
|
+
function statLabel(t) {
|
|
5064
|
+
if (!t.stat || t.unit === "pct") return "";
|
|
5065
|
+
return STAT_NAMES[t.stat] ?? t.stat;
|
|
5066
|
+
}
|
|
5067
|
+
function ruleText(t) {
|
|
5068
|
+
if (!t.stat || !isNum(t.limit)) return t.expr;
|
|
5069
|
+
const stat3 = statLabel(t);
|
|
5070
|
+
return `${stat3 ? `${stat3} ` : ""}${limitText(t)}`;
|
|
5071
|
+
}
|
|
5072
|
+
function thresholdSentence(t) {
|
|
5073
|
+
if (!t.stat || !isNum(t.limit)) return `failed its threshold <code>${esc2(t.expr)}</code>.`;
|
|
5074
|
+
const stat3 = statLabel(t);
|
|
5075
|
+
const lim = `<code>${esc2(limitText(t))}</code>`;
|
|
5076
|
+
if (!isNum(t.measured)) return `${stat3 ? `${esc2(stat3)} ` : ""}broke its limit of ${lim}.`;
|
|
5077
|
+
return `${stat3 ? `${esc2(stat3)} ` : ""}was ${esc2(fmtUnit(t.measured, t.unit))}; the limit is ${lim}.`;
|
|
5078
|
+
}
|
|
5079
|
+
function fmtUnit(n, unit) {
|
|
5080
|
+
if (unit === "ms") return fmtMs(n);
|
|
5081
|
+
if (unit === "pct") {
|
|
5082
|
+
const pct = n * 100;
|
|
5083
|
+
return Number.isInteger(pct) ? `${pct}%` : `${pct.toFixed(2)}%`;
|
|
5084
|
+
}
|
|
5085
|
+
return fmtInt(n);
|
|
5086
|
+
}
|
|
5087
|
+
function humanize(k) {
|
|
5088
|
+
const s = k.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_.]+/g, " ").trim().toLowerCase();
|
|
5089
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
5090
|
+
}
|
|
5091
|
+
function parseDrift(md) {
|
|
5092
|
+
const items = [];
|
|
5093
|
+
const skipped = [];
|
|
5094
|
+
const lines = md.split("\n");
|
|
5095
|
+
let cur = null;
|
|
5096
|
+
let inSkipped = false;
|
|
5097
|
+
let inCode = false;
|
|
5098
|
+
let code = [];
|
|
5099
|
+
for (const line of lines) {
|
|
5100
|
+
if (inCode) {
|
|
5101
|
+
if (line.startsWith("```")) {
|
|
5102
|
+
inCode = false;
|
|
5103
|
+
if (cur) cur.details = code.join("\n");
|
|
5104
|
+
code = [];
|
|
5105
|
+
} else code.push(line);
|
|
5106
|
+
continue;
|
|
5107
|
+
}
|
|
5108
|
+
const h = /^### `([A-Z]+) ([^`]+)` — (.+?) \((.+)\)\s*$/.exec(line);
|
|
5109
|
+
if (h) {
|
|
5110
|
+
const sev = /error/.test(h[4] ?? "") ? "error" : /warn/.test(h[4] ?? "") ? "warning" : "info";
|
|
5111
|
+
cur = { method: h[1] ?? "", path: h[2] ?? "", kind: h[3] ?? "", severity: sev, message: "" };
|
|
5112
|
+
items.push(cur);
|
|
5113
|
+
inSkipped = false;
|
|
5114
|
+
continue;
|
|
5115
|
+
}
|
|
5116
|
+
if (/^## Skipped/.test(line)) {
|
|
5117
|
+
inSkipped = true;
|
|
5118
|
+
cur = null;
|
|
5119
|
+
continue;
|
|
5120
|
+
}
|
|
5121
|
+
if (line.startsWith("```")) {
|
|
5122
|
+
inCode = true;
|
|
5123
|
+
continue;
|
|
5124
|
+
}
|
|
5125
|
+
if (inSkipped && line.startsWith("- ")) {
|
|
5126
|
+
skipped.push(line.slice(2));
|
|
5127
|
+
continue;
|
|
5128
|
+
}
|
|
5129
|
+
if (cur && line.trim() && !line.startsWith("#"))
|
|
5130
|
+
cur.message += (cur.message ? " " : "") + line.trim();
|
|
5131
|
+
}
|
|
5132
|
+
if (items.length === 0 && !/No drift detected/.test(md) && skipped.length === 0) return null;
|
|
5133
|
+
return { items, skipped };
|
|
5134
|
+
}
|
|
5135
|
+
function inlineMd(s) {
|
|
5136
|
+
return esc2(s).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
5137
|
+
}
|
|
5138
|
+
function drift(md) {
|
|
5139
|
+
if (!md) return "";
|
|
5140
|
+
const parsed = parseDrift(md);
|
|
5141
|
+
if (!parsed) {
|
|
5142
|
+
return `<section class="panel" aria-labelledby="drift-h"><div class="panel-h"><h2 id="drift-h">Drift findings</h2></div><pre class="raw">${esc2(md)}</pre></section>`;
|
|
5143
|
+
}
|
|
5144
|
+
const { items, skipped } = parsed;
|
|
5145
|
+
const order = { error: 0, warning: 1, info: 2 };
|
|
5146
|
+
const tone = { error: "bad", warning: "warn", info: "muted" };
|
|
5147
|
+
const list = items.sort((a, b) => order[a.severity] - order[b.severity]).map(
|
|
5148
|
+
(f) => `<li class="finding">
|
|
5149
|
+
<div class="finding-h"><span class="pill pill-${tone[f.severity]}">${f.severity}</span><span class="m">${esc2(f.method)}</span><code class="path">${esc2(f.path)}</code><span class="dim">${esc2(f.kind)}</span></div>
|
|
5150
|
+
<p>${inlineMd(f.message)}</p>
|
|
5151
|
+
${f.details ? `<details><summary>Details</summary><pre>${esc2(f.details)}</pre></details>` : ""}
|
|
5152
|
+
</li>`
|
|
5153
|
+
).join("");
|
|
5154
|
+
return `<section class="panel" aria-labelledby="drift-h">
|
|
5155
|
+
<div class="panel-h"><h2 id="drift-h">Drift findings</h2><p class="panel-sub">${items.length ? plural(items.length, "finding") : "None"}</p></div>
|
|
5156
|
+
${items.length ? `<ul class="findings">${list}</ul>` : `<p class="dim">The spec and the live API agree on every probed operation.</p>`}
|
|
5157
|
+
${skipped.length ? `<details class="skipped"><summary>${plural(skipped.length, "operation")} skipped</summary><ul>${skipped.map((s) => `<li>${inlineMd(s)}</li>`).join("")}</ul></details>` : ""}
|
|
5158
|
+
</section>`;
|
|
5159
|
+
}
|
|
5160
|
+
function contract(failures) {
|
|
5161
|
+
if (failures.length === 0) return "";
|
|
5162
|
+
return `<section class="panel" aria-labelledby="ct-h">
|
|
5163
|
+
<div class="panel-h"><h2 id="ct-h">Failed contract tests</h2><p class="panel-sub">${plural(failures.length, "test")}</p></div>
|
|
5164
|
+
<ul class="findings">${failures.map((f) => {
|
|
5165
|
+
const first = (f.message ?? "").split("\n").find((l) => l.trim()) ?? "";
|
|
5166
|
+
return `<li class="finding">
|
|
5167
|
+
<div class="finding-h"><span class="pill pill-bad">failed</span><code class="path">${esc2(f.test)}</code></div>
|
|
5168
|
+
${first ? `<p>${esc2(first.length > 220 ? `${first.slice(0, 220)}\u2026` : first)}</p>` : ""}
|
|
5169
|
+
${f.message && f.message.trim() !== first.trim() ? `<details><summary>Full output</summary><pre>${esc2(f.message)}</pre></details>` : ""}
|
|
5170
|
+
</li>`;
|
|
5171
|
+
}).join("")}</ul>
|
|
5172
|
+
</section>`;
|
|
5173
|
+
}
|
|
5174
|
+
function runDetails(meta) {
|
|
5175
|
+
const rows = [
|
|
5176
|
+
["Session", `<code>${esc2(meta.id)}</code>`],
|
|
5177
|
+
["Spec", `<code>${esc2(meta.spec.path)}</code>`],
|
|
5178
|
+
["Spec SHA-256", `<code>${esc2(meta.spec.sha256.slice(0, 16))}\u2026</code>`],
|
|
5179
|
+
["IR digest", `<code>${esc2(meta.irDigest.slice(0, 16))}\u2026</code>`],
|
|
5180
|
+
["Started", esc2(meta.startedAt)]
|
|
5181
|
+
];
|
|
5182
|
+
if (meta.endedAt) rows.push(["Ended", esc2(meta.endedAt)]);
|
|
5183
|
+
if (isNum(meta.exitCode)) rows.push(["Exit code", String(meta.exitCode)]);
|
|
5184
|
+
if (meta.envVars.length > 0)
|
|
5185
|
+
rows.push(["Env vars", meta.envVars.map((e) => `<code>${esc2(e)}</code>`).join(" ")]);
|
|
5186
|
+
for (const [k, v] of Object.entries(meta.flags))
|
|
5187
|
+
rows.push([
|
|
5188
|
+
`--${k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`,
|
|
5189
|
+
`<code>${esc2(String(v))}</code>`
|
|
5190
|
+
]);
|
|
5191
|
+
return `<details class="panel run-details">
|
|
5192
|
+
<summary><h2>Run details</h2><span class="panel-sub">Session, spec, flags and env var names</span></summary>
|
|
5193
|
+
<dl class="kv">${rows.map(([k, v]) => `<div><dt>${esc2(k)}</dt><dd>${v}</dd></div>`).join("")}</dl>
|
|
5194
|
+
</details>`;
|
|
5195
|
+
}
|
|
5196
|
+
function footer(meta, version) {
|
|
5197
|
+
return `<footer class="foot">Made by <a href="${REPO}" target="_blank" rel="noopener">loadam ${esc2(version)}</a> \xB7 session schema v${meta.schemaVersion} \xB7 IR <code>${esc2(meta.irDigest.slice(0, 12))}</code> \xB7 works offline</footer>`;
|
|
5198
|
+
}
|
|
5199
|
+
function runStyles(model) {
|
|
5200
|
+
if (model.runs.length < 2) return "";
|
|
5201
|
+
return model.runs.map(
|
|
5202
|
+
(r) => `.report[data-active-run="${r.slug}"] [data-run]:not([data-run="${r.slug}"]){display:none}`
|
|
5203
|
+
).join("\n");
|
|
5204
|
+
}
|
|
5205
|
+
var LIGHT = "--bg:#fff;--bg-2:#f4f4f2;--bg-3:#e9e9e6;--fg:#000;--fg-2:#4a4a4a;--fg-3:#767676;--line:#000;--line-soft:#dcdcd8;--ok-text:#3f6a00;--b2:#3a3a3a;--b3:#a3a39e;color-scheme:light;";
|
|
5206
|
+
var DARK = "--bg:#000;--bg-2:#0e0e0e;--bg-3:#1f1f1f;--fg:#fff;--fg-2:#b4b4b4;--fg-3:#8a8a8a;--line:#fff;--line-soft:#2a2a2a;--ok-text:#c6ff3d;--b2:#d0d0d0;--b3:#6a6a6a;color-scheme:dark;";
|
|
4404
5207
|
var STYLES = `
|
|
4405
|
-
:root{
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
|
|
4410
|
-
}
|
|
4411
|
-
|
|
4412
|
-
|
|
4413
|
-
|
|
4414
|
-
|
|
4415
|
-
|
|
4416
|
-
|
|
4417
|
-
|
|
4418
|
-
}
|
|
4419
|
-
|
|
4420
|
-
|
|
4421
|
-
|
|
4422
|
-
|
|
4423
|
-
|
|
4424
|
-
|
|
4425
|
-
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
.
|
|
4430
|
-
.
|
|
4431
|
-
.
|
|
4432
|
-
.
|
|
4433
|
-
.
|
|
4434
|
-
|
|
4435
|
-
|
|
4436
|
-
|
|
4437
|
-
.
|
|
4438
|
-
.
|
|
4439
|
-
|
|
4440
|
-
.
|
|
4441
|
-
.
|
|
4442
|
-
.status
|
|
4443
|
-
.status
|
|
4444
|
-
.status-
|
|
4445
|
-
.status-
|
|
4446
|
-
.
|
|
4447
|
-
.
|
|
4448
|
-
.
|
|
4449
|
-
.
|
|
4450
|
-
.
|
|
4451
|
-
.
|
|
4452
|
-
.
|
|
4453
|
-
.
|
|
4454
|
-
.
|
|
4455
|
-
.
|
|
4456
|
-
.
|
|
4457
|
-
|
|
4458
|
-
|
|
4459
|
-
|
|
4460
|
-
|
|
4461
|
-
.
|
|
4462
|
-
.
|
|
4463
|
-
.
|
|
4464
|
-
.
|
|
4465
|
-
|
|
4466
|
-
|
|
4467
|
-
.
|
|
4468
|
-
.
|
|
4469
|
-
.
|
|
4470
|
-
.
|
|
4471
|
-
.
|
|
4472
|
-
.
|
|
4473
|
-
.
|
|
4474
|
-
.
|
|
4475
|
-
|
|
4476
|
-
|
|
4477
|
-
.
|
|
4478
|
-
.
|
|
4479
|
-
.
|
|
4480
|
-
.
|
|
4481
|
-
.
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
.
|
|
4485
|
-
.
|
|
4486
|
-
.
|
|
4487
|
-
.
|
|
4488
|
-
.
|
|
4489
|
-
|
|
4490
|
-
|
|
4491
|
-
|
|
4492
|
-
|
|
4493
|
-
.
|
|
4494
|
-
.
|
|
4495
|
-
.
|
|
4496
|
-
.
|
|
4497
|
-
.
|
|
4498
|
-
.
|
|
4499
|
-
.
|
|
4500
|
-
.
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
.
|
|
4509
|
-
.
|
|
4510
|
-
.
|
|
4511
|
-
.
|
|
4512
|
-
.
|
|
4513
|
-
.
|
|
4514
|
-
.
|
|
4515
|
-
.
|
|
4516
|
-
.
|
|
4517
|
-
.
|
|
4518
|
-
.
|
|
4519
|
-
.
|
|
4520
|
-
.
|
|
4521
|
-
.
|
|
4522
|
-
.
|
|
4523
|
-
.
|
|
4524
|
-
.
|
|
4525
|
-
.
|
|
4526
|
-
.
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
}
|
|
4531
|
-
.
|
|
4532
|
-
.
|
|
4533
|
-
.
|
|
4534
|
-
.
|
|
4535
|
-
.
|
|
4536
|
-
.
|
|
4537
|
-
.
|
|
4538
|
-
.
|
|
4539
|
-
.
|
|
4540
|
-
.
|
|
4541
|
-
|
|
4542
|
-
.
|
|
4543
|
-
.
|
|
4544
|
-
.
|
|
4545
|
-
.
|
|
4546
|
-
.
|
|
4547
|
-
.
|
|
4548
|
-
.
|
|
4549
|
-
.
|
|
4550
|
-
.
|
|
4551
|
-
.
|
|
4552
|
-
.
|
|
4553
|
-
.
|
|
4554
|
-
.
|
|
4555
|
-
.ep-
|
|
4556
|
-
.ep-
|
|
4557
|
-
.
|
|
4558
|
-
.
|
|
4559
|
-
.
|
|
4560
|
-
.
|
|
4561
|
-
.
|
|
4562
|
-
.
|
|
4563
|
-
.
|
|
4564
|
-
.
|
|
4565
|
-
.
|
|
4566
|
-
.
|
|
4567
|
-
.
|
|
4568
|
-
.
|
|
4569
|
-
.
|
|
4570
|
-
.
|
|
4571
|
-
.
|
|
4572
|
-
.
|
|
4573
|
-
.
|
|
4574
|
-
.
|
|
4575
|
-
.
|
|
4576
|
-
.
|
|
4577
|
-
.
|
|
4578
|
-
.
|
|
4579
|
-
.
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
.
|
|
4583
|
-
.
|
|
4584
|
-
.
|
|
4585
|
-
.
|
|
4586
|
-
.
|
|
4587
|
-
.
|
|
4588
|
-
|
|
4589
|
-
.
|
|
4590
|
-
.
|
|
4591
|
-
.
|
|
4592
|
-
|
|
4593
|
-
|
|
4594
|
-
.
|
|
4595
|
-
.
|
|
4596
|
-
.
|
|
4597
|
-
.
|
|
4598
|
-
.
|
|
4599
|
-
.
|
|
4600
|
-
.
|
|
4601
|
-
.
|
|
4602
|
-
.
|
|
4603
|
-
|
|
4604
|
-
|
|
4605
|
-
.
|
|
4606
|
-
|
|
4607
|
-
|
|
4608
|
-
.
|
|
4609
|
-
.
|
|
4610
|
-
.
|
|
4611
|
-
|
|
4612
|
-
.
|
|
4613
|
-
.
|
|
4614
|
-
.
|
|
4615
|
-
.
|
|
4616
|
-
.
|
|
4617
|
-
.
|
|
4618
|
-
.
|
|
4619
|
-
|
|
4620
|
-
|
|
4621
|
-
|
|
4622
|
-
|
|
4623
|
-
.ep-
|
|
4624
|
-
.ep-
|
|
5208
|
+
:root{--lime:#c6ff3d;--ink:#0a0a0a;--warn:#ffb020;--fail:#ff4d2e;
|
|
5209
|
+
--sans:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
|
|
5210
|
+
--mono:ui-monospace,"SF Mono",Menlo,Monaco,Consolas,"Liberation Mono",monospace;${LIGHT}}
|
|
5211
|
+
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){${DARK}}}
|
|
5212
|
+
:root[data-theme="dark"]{${DARK}}
|
|
5213
|
+
*,*::before,*::after{box-sizing:border-box}
|
|
5214
|
+
html{-webkit-text-size-adjust:100%}
|
|
5215
|
+
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 var(--sans);-webkit-font-smoothing:antialiased}
|
|
5216
|
+
.report{max-width:1180px;margin:0 auto;padding:0 24px 64px}
|
|
5217
|
+
code,pre,.m,.mono{font-family:var(--mono)}
|
|
5218
|
+
code{font-size:.9em}
|
|
5219
|
+
a{color:inherit;text-decoration:underline;text-underline-offset:3px;text-decoration-thickness:1px}
|
|
5220
|
+
a:hover{text-decoration-thickness:2px}
|
|
5221
|
+
h1,h2,h3{margin:0;letter-spacing:-.01em}
|
|
5222
|
+
.dim{color:var(--fg-3)}
|
|
5223
|
+
.sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
|
|
5224
|
+
html:not(.js) .js-only{display:none!important}
|
|
5225
|
+
:focus-visible{outline:2px solid var(--fg);outline-offset:2px}
|
|
5226
|
+
button{font:inherit;color:inherit}
|
|
5227
|
+
|
|
5228
|
+
/* top bar */
|
|
5229
|
+
.top{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 0;border-bottom:1px solid var(--line)}
|
|
5230
|
+
.brand{display:inline-flex;align-items:center;gap:10px;font-weight:700;font-size:17px;letter-spacing:-.02em;text-decoration:none}
|
|
5231
|
+
.mark{width:24px;height:24px;display:block}
|
|
5232
|
+
.mark-bg{fill:var(--fg)}
|
|
5233
|
+
.mark-line{stroke:var(--bg)}
|
|
5234
|
+
.top-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}
|
|
5235
|
+
.btn{background:var(--bg);border:1px solid var(--line-soft);padding:6px 12px;font-size:13px;cursor:pointer}
|
|
5236
|
+
.btn:hover{border-color:var(--fg)}
|
|
5237
|
+
|
|
5238
|
+
/* verdict */
|
|
5239
|
+
.verdict{padding:44px 0 36px;border-bottom:1px solid var(--line-soft)}
|
|
5240
|
+
.eyebrow{margin:0 0 10px;font-size:13px;color:var(--fg-2)}
|
|
5241
|
+
.eyebrow code{color:var(--fg);word-break:break-all}
|
|
5242
|
+
h1{font-size:clamp(28px,4.4vw,44px);line-height:1.08;font-weight:750;letter-spacing:-.025em}
|
|
5243
|
+
.ver{font-size:.42em;font-weight:500;color:var(--fg-3);letter-spacing:0;vertical-align:middle;font-family:var(--mono)}
|
|
5244
|
+
.verdict-row{display:flex;align-items:flex-start;gap:18px;margin-top:22px}
|
|
5245
|
+
.status{flex:none;display:inline-flex;align-items:center;gap:8px;padding:7px 14px;font-weight:750;font-size:15px;line-height:1.3}
|
|
5246
|
+
.status::before{content:"";width:8px;height:8px;background:currentColor}
|
|
5247
|
+
.status-ok{background:var(--lime);color:var(--ink)}
|
|
5248
|
+
.status-warn{background:var(--warn);color:var(--ink)}
|
|
5249
|
+
.status-bad{background:var(--fail);color:var(--ink)}
|
|
5250
|
+
.status-muted{background:var(--bg-3);color:var(--fg)}
|
|
5251
|
+
.verdict-text{margin:2px 0 0;font-size:18px;line-height:1.5;color:var(--fg-2);max-width:68ch}
|
|
5252
|
+
.why{margin-top:24px;border-left:3px solid var(--fail);padding:2px 0 2px 18px}
|
|
5253
|
+
.tone-warn .why{border-left-color:var(--warn)}
|
|
5254
|
+
.why-h{font-size:13px;font-weight:700;margin-bottom:6px}
|
|
5255
|
+
.why ul{margin:0;padding:0;list-style:none}
|
|
5256
|
+
.why li{padding:3px 0;font-size:15px}
|
|
5257
|
+
.why .m{font-size:12px;font-weight:700;min-width:0;margin-right:2px}
|
|
5258
|
+
.facts{display:flex;flex-wrap:wrap;gap:8px 36px;margin:28px 0 0}
|
|
5259
|
+
.facts div{display:flex;flex-direction:column}
|
|
5260
|
+
.facts dt{font-size:12px;color:var(--fg-3)}
|
|
5261
|
+
.facts dd{margin:0;font-size:14px;font-variant-numeric:tabular-nums}
|
|
5262
|
+
|
|
5263
|
+
/* run tabs */
|
|
5264
|
+
.runs{display:inline-flex;border:1px solid var(--line);margin-top:32px}
|
|
5265
|
+
.run-tab{background:var(--bg);border:0;padding:8px 18px;font-size:14px;font-weight:600;cursor:pointer;text-transform:capitalize}
|
|
5266
|
+
.run-tab+.run-tab{border-left:1px solid var(--line)}
|
|
5267
|
+
.run-tab[aria-selected="true"]{background:var(--fg);color:var(--bg)}
|
|
5268
|
+
|
|
5269
|
+
/* tiles */
|
|
5270
|
+
.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:1px;background:var(--line-soft);border:1px solid var(--line-soft);margin-top:32px}
|
|
5271
|
+
.runs+.tiles,.runs~.tiles{margin-top:16px}
|
|
5272
|
+
.tile{background:var(--bg);padding:18px 20px 16px;min-width:0}
|
|
5273
|
+
.tile-l{font-size:13px;color:var(--fg-2)}
|
|
5274
|
+
.tile-v{font-size:30px;line-height:1.15;font-weight:650;letter-spacing:-.02em;font-variant-numeric:tabular-nums;margin-top:6px;overflow-wrap:anywhere}
|
|
5275
|
+
.tile-s{font-size:12px;color:var(--fg-3);margin-top:4px}
|
|
5276
|
+
.tile-bad{box-shadow:inset 0 3px 0 var(--fail)}
|
|
5277
|
+
.tile-bad .tile-s{color:var(--fg)}
|
|
5278
|
+
|
|
5279
|
+
/* panels */
|
|
5280
|
+
.panel{margin-top:56px}
|
|
5281
|
+
.panel-h{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 14px;margin-bottom:16px}
|
|
5282
|
+
.panel-h h2,.run-details summary h2{font-size:21px;font-weight:700}
|
|
5283
|
+
.panel-sub{margin:0;color:var(--fg-3);font-size:14px}
|
|
5284
|
+
.note{font-size:13px;color:var(--fg-3);margin:12px 0 0;line-height:1.6}
|
|
5285
|
+
|
|
5286
|
+
/* latency ladder */
|
|
5287
|
+
.lad-plot{position:relative;padding:4px 0 30px}
|
|
5288
|
+
.lad-row{display:grid;grid-template-columns:64px 1fr 88px;gap:12px;align-items:center;height:30px}
|
|
5289
|
+
.lad-l{font-size:13px;color:var(--fg-2)}
|
|
5290
|
+
.lad-track{position:relative;height:12px;z-index:1}
|
|
5291
|
+
.lad-track i{display:block;height:100%;background:var(--fg)}
|
|
5292
|
+
.lad-row.hot .lad-track i{background:var(--lime);box-shadow:inset 0 0 0 1px var(--ink)}
|
|
5293
|
+
.lad-row.hot .lad-l{color:var(--fg);font-weight:700}
|
|
5294
|
+
.lad-v{font:13px/1 var(--mono);text-align:right;font-variant-numeric:tabular-nums}
|
|
5295
|
+
.lad-row.hot .lad-v{font-weight:700}
|
|
5296
|
+
.lad-overlay{position:absolute;top:0;bottom:0;left:76px;right:100px;pointer-events:none}
|
|
5297
|
+
.lad-tick{position:absolute;top:0;bottom:22px;border-left:1px solid var(--line-soft)}
|
|
5298
|
+
.lad-tick b{position:absolute;bottom:-22px;transform:translateX(-50%);font:500 11px/1 var(--mono);color:var(--fg-3);white-space:nowrap}
|
|
5299
|
+
.lad-tick:first-child b{transform:none}
|
|
5300
|
+
.lad-limit{position:absolute;top:-6px;bottom:22px;border-left:2px dashed var(--fg);z-index:2}
|
|
5301
|
+
.lad-limit b{position:absolute;top:-16px;left:6px;font:600 11px/1 var(--mono);white-space:nowrap;background:var(--bg);padding:2px 4px}
|
|
5302
|
+
.lad-limit.over{border-left-color:var(--fail)}
|
|
5303
|
+
.ladder+.ladder{margin-top:28px}
|
|
5304
|
+
|
|
5305
|
+
/* endpoints */
|
|
5306
|
+
.toolbar{display:flex;flex-wrap:wrap;gap:12px;align-items:center;margin-bottom:12px}
|
|
5307
|
+
.chips{display:flex;flex-wrap:wrap;gap:6px}
|
|
5308
|
+
.chip{background:var(--bg);border:1px solid var(--line-soft);padding:5px 11px;font-size:13px;cursor:pointer}
|
|
5309
|
+
.chip span{color:var(--fg-3);font-variant-numeric:tabular-nums;margin-left:2px}
|
|
5310
|
+
.chip:hover:not(:disabled){border-color:var(--fg)}
|
|
5311
|
+
.chip[aria-pressed="true"]{background:var(--fg);color:var(--bg);border-color:var(--fg)}
|
|
5312
|
+
.chip[aria-pressed="true"] span{color:inherit;opacity:.7}
|
|
5313
|
+
.chip:disabled{opacity:.4;cursor:default}
|
|
5314
|
+
.search{flex:1 1 220px;max-width:340px;margin-left:auto}
|
|
5315
|
+
.search input,.sort-m select{width:100%;font:inherit;font-size:14px;padding:6px 10px;background:var(--bg);color:var(--fg);border:1px solid var(--line-soft);border-radius:0}
|
|
5316
|
+
.search input:focus,.sort-m select:focus{border-color:var(--fg);outline:none}
|
|
5317
|
+
.sort-m{display:none}
|
|
5318
|
+
.table-wrap{overflow-x:auto}
|
|
5319
|
+
.ep-table{width:100%;border-collapse:collapse;font-size:14px}
|
|
5320
|
+
.ep-table th{text-align:left;font-size:12px;font-weight:600;color:var(--fg-2);padding:0 12px 8px;border-bottom:1px solid var(--line);white-space:nowrap}
|
|
5321
|
+
.ep-table th.num{text-align:right}
|
|
5322
|
+
.ep-table th button{background:none;border:0;padding:0;font:inherit;color:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:4px}
|
|
5323
|
+
.ep-table th button:hover{color:var(--fg)}
|
|
5324
|
+
.ep-table th[aria-sort] button{color:var(--fg)}
|
|
5325
|
+
.ep-table th[aria-sort="ascending"] button::after{content:"\u2191"}
|
|
5326
|
+
.ep-table th[aria-sort="descending"] button::after{content:"\u2193"}
|
|
5327
|
+
.ep-table>tbody>tr>td{padding:12px;border-bottom:1px solid var(--line-soft);vertical-align:middle}
|
|
5328
|
+
.ep-row{cursor:pointer}
|
|
5329
|
+
.ep-row:hover,.ep-row[aria-expanded="true"]{background:var(--bg-2)}
|
|
5330
|
+
.ep-row[aria-expanded="true"]>td{border-bottom-color:transparent}
|
|
5331
|
+
.c-ep{min-width:220px}
|
|
5332
|
+
.m{display:inline-block;min-width:58px;font-size:11px;font-weight:700;letter-spacing:.03em}
|
|
5333
|
+
.path{font-size:14px;word-break:break-all}
|
|
5334
|
+
.ep-sum{display:block;font-size:12px;color:var(--fg-3);margin:2px 0 0 62px}
|
|
5335
|
+
.pill{display:inline-block;padding:2px 8px;font-size:11px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;white-space:nowrap}
|
|
5336
|
+
.pill-ok{background:var(--lime);color:var(--ink)}
|
|
5337
|
+
.pill-warn{background:var(--warn);color:var(--ink)}
|
|
5338
|
+
.pill-bad{background:var(--fail);color:var(--ink)}
|
|
5339
|
+
.pill-muted{background:var(--bg-3);color:var(--fg-2)}
|
|
5340
|
+
.rate{font:13px var(--mono);margin-left:8px;color:var(--fg-2);font-variant-numeric:tabular-nums}
|
|
5341
|
+
.c-res{white-space:nowrap}
|
|
5342
|
+
.num,.c-reqs{text-align:right;font-family:var(--mono);font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
5343
|
+
.p95{display:flex;align-items:center;gap:10px;min-width:180px}
|
|
5344
|
+
.p95-v{font:13px var(--mono);width:70px;text-align:right;flex:none;font-variant-numeric:tabular-nums}
|
|
5345
|
+
.p95-track{flex:1;height:10px;border:1px solid var(--line-soft);background:var(--bg)}
|
|
5346
|
+
.p95-track i{display:block;height:100%;background:var(--fg)}
|
|
5347
|
+
.p95.hot .p95-track i{background:var(--lime);box-shadow:inset 0 0 0 1px var(--ink)}
|
|
5348
|
+
.p95.hot .p95-v{font-weight:700}
|
|
5349
|
+
.c-codes .per{display:flex;align-items:center;gap:10px}
|
|
5350
|
+
.codes{display:flex;gap:2px;width:120px;height:10px;flex:none}
|
|
5351
|
+
.codes i{display:block;height:100%;min-width:3px;flex-basis:0}
|
|
5352
|
+
.b1{background:var(--bg-3)}.b2{background:var(--b2)}.b3{background:var(--b3)}.b4{background:var(--warn)}.b5{background:var(--fail)}
|
|
5353
|
+
.codes-n{font-size:12px;color:var(--fg-3);white-space:nowrap}
|
|
5354
|
+
.legend{display:inline-flex;gap:6px 12px;flex-wrap:wrap;align-items:center;margin-left:4px}
|
|
5355
|
+
.legend i,.sw{display:inline-block;width:10px;height:10px;margin-right:4px;vertical-align:-1px}
|
|
5356
|
+
.c-x{width:28px;text-align:center}
|
|
5357
|
+
.chev{display:inline-block;width:8px;height:8px;border-right:1.5px solid var(--fg-2);border-bottom:1.5px solid var(--fg-2);transform:rotate(45deg) translateY(-2px);transition:transform .15s}
|
|
5358
|
+
.ep-row[aria-expanded="true"] .chev{transform:rotate(225deg) translate(-2px,0)}
|
|
5359
|
+
.ep-detail>td{background:var(--bg-2);padding:4px 16px 20px 16px}
|
|
5360
|
+
.detail{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:20px 32px}
|
|
5361
|
+
.d-block h3{font-size:12px;font-weight:700;color:var(--fg-2);margin:12px 0 6px}
|
|
5362
|
+
.d-block p{margin:0;font-size:14px}
|
|
5363
|
+
.mini{width:100%;border-collapse:collapse;font-size:13px}
|
|
5364
|
+
.mini th{text-align:left;font-weight:600;color:var(--fg-3);font-size:12px;padding:6px 8px 6px 0;border-bottom:1px solid var(--line-soft)}
|
|
5365
|
+
.mini td{padding:6px 8px 6px 0;border-bottom:1px solid var(--line-soft);vertical-align:top}
|
|
5366
|
+
.mini th.num,.mini td.num{text-align:right}
|
|
5367
|
+
.mini tr.sum td{border-bottom:0;font-weight:600}
|
|
5368
|
+
.dot{display:inline-block;width:8px;height:8px;margin-right:6px}
|
|
5369
|
+
.dot-ok{background:var(--lime);box-shadow:inset 0 0 0 1px var(--ink)}.dot-warn{background:var(--warn)}.dot-bad{background:var(--fail)}.dot-muted{background:var(--bg-3)}
|
|
5370
|
+
.tags{margin-top:6px!important;display:flex;gap:6px;flex-wrap:wrap}
|
|
5371
|
+
.tag{font-size:12px;border:1px solid var(--line-soft);padding:1px 7px;color:var(--fg-2)}
|
|
5372
|
+
.pager{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px 16px;margin-top:14px}
|
|
5373
|
+
.pager[hidden]{display:none}
|
|
5374
|
+
.pager-info{margin:0;font-size:13px;color:var(--fg-2);font-variant-numeric:tabular-nums}
|
|
5375
|
+
.pager-btns{display:flex;align-items:center;gap:4px;flex-wrap:wrap}
|
|
5376
|
+
.pg{min-width:34px;height:32px;padding:0 8px;background:var(--bg);border:1px solid var(--line-soft);font-size:13px;font-variant-numeric:tabular-nums;cursor:pointer}
|
|
5377
|
+
.pg:hover:not(:disabled){border-color:var(--fg)}
|
|
5378
|
+
.pg.cur{background:var(--fg);color:var(--bg);border-color:var(--fg);cursor:default}
|
|
5379
|
+
.pg:disabled{opacity:.35;cursor:default}
|
|
5380
|
+
.pg-gap{padding:0 4px;color:var(--fg-3)}
|
|
5381
|
+
.empty{padding:24px 12px;color:var(--fg-3);margin:0}
|
|
5382
|
+
.thr td{vertical-align:middle}
|
|
5383
|
+
|
|
5384
|
+
/* findings */
|
|
5385
|
+
.findings{list-style:none;margin:0;padding:0}
|
|
5386
|
+
.finding{border:1px solid var(--line-soft);padding:14px 16px}
|
|
5387
|
+
.finding+.finding{border-top:0}
|
|
5388
|
+
.finding-h{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px}
|
|
5389
|
+
.finding p{margin:8px 0 0;color:var(--fg-2)}
|
|
5390
|
+
.finding details,.skipped{margin-top:10px}
|
|
5391
|
+
summary{cursor:pointer}
|
|
5392
|
+
.finding summary,.skipped summary{font-size:13px;color:var(--fg-2)}
|
|
5393
|
+
.finding pre,.raw{margin:8px 0 0;padding:12px 14px;background:var(--bg-2);border:1px solid var(--line-soft);font-size:12px;line-height:1.5;overflow-x:auto;white-space:pre-wrap;word-break:break-word}
|
|
5394
|
+
.skipped ul{margin:8px 0 0;padding-left:18px;font-size:14px;color:var(--fg-2)}
|
|
5395
|
+
|
|
5396
|
+
/* run details */
|
|
5397
|
+
.run-details summary{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 14px;list-style:none;padding:16px 0;border-top:1px solid var(--line-soft);border-bottom:1px solid var(--line-soft)}
|
|
5398
|
+
.run-details summary::-webkit-details-marker{display:none}
|
|
5399
|
+
.run-details summary::after{content:"+";margin-left:auto;font:400 22px/1 var(--mono)}
|
|
5400
|
+
.run-details[open] summary::after{content:"\u2212"}
|
|
5401
|
+
.kv{display:grid;grid-template-columns:minmax(120px,200px) 1fr;margin:0;font-size:14px}
|
|
5402
|
+
.kv div{display:contents}
|
|
5403
|
+
.kv dt{color:var(--fg-3);padding:8px 12px 8px 0;border-bottom:1px solid var(--line-soft)}
|
|
5404
|
+
.kv dd{margin:0;padding:8px 0;border-bottom:1px solid var(--line-soft);word-break:break-all}
|
|
5405
|
+
.foot{margin-top:56px;padding-top:16px;border-top:1px solid var(--line);font-size:13px;color:var(--fg-3)}
|
|
5406
|
+
|
|
5407
|
+
/* tooltip */
|
|
5408
|
+
.tip{position:fixed;z-index:20;pointer-events:none;background:var(--fg);color:var(--bg);font:12px/1.3 var(--mono);padding:5px 8px;white-space:nowrap;transform:translate(-50%,calc(-100% - 10px))}
|
|
5409
|
+
|
|
5410
|
+
@media (max-width:760px){
|
|
5411
|
+
.report{padding:0 16px 48px}
|
|
5412
|
+
.top-actions .btn:not([data-theme-toggle]):not([data-loadam-download="html"]){display:none}
|
|
5413
|
+
.verdict{padding:32px 0 28px}
|
|
5414
|
+
.verdict-row{flex-direction:column;gap:12px}
|
|
5415
|
+
.verdict-text{font-size:16px}
|
|
5416
|
+
.tiles{grid-template-columns:repeat(2,minmax(0,1fr))}
|
|
5417
|
+
.tile{padding:14px}
|
|
5418
|
+
.tile-v{font-size:24px}
|
|
5419
|
+
.lad-row{grid-template-columns:52px 1fr 72px;gap:8px}
|
|
5420
|
+
.lad-overlay{left:60px;right:80px}
|
|
5421
|
+
.lad-tick:nth-child(even):not(:last-of-type) b{display:none}
|
|
5422
|
+
.search{max-width:none;margin-left:0;flex-basis:100%}
|
|
5423
|
+
.sort-m{display:block;flex-basis:100%}
|
|
5424
|
+
.ep-table thead{display:none}
|
|
5425
|
+
.ep-table,.ep-table>tbody,.ep-table>tbody>tr,.ep-table>tbody>tr>td{display:block}
|
|
5426
|
+
.ep-table>tbody>tr.ep-row{display:grid;grid-template-columns:1fr auto;gap:8px 12px;padding:14px 4px;border-bottom:1px solid var(--line-soft)}
|
|
5427
|
+
.ep-table>tbody>tr>td{padding:0;border:0}
|
|
5428
|
+
.ep-row>td.c-ep{grid-column:1/2;min-width:0}
|
|
5429
|
+
.ep-row>td.c-x{grid-column:2;grid-row:1;align-self:start;padding-top:4px}
|
|
5430
|
+
.ep-row>td.c-res,.ep-row>td.c-reqs,.ep-row>td.c-p95,.ep-row>td.c-codes{grid-column:1/-1;display:flex;align-items:center;gap:12px;text-align:left}
|
|
5431
|
+
.ep-row>td.c-res::before,.ep-row>td.c-reqs::before,.ep-row>td.c-p95::before,.ep-row>td.c-codes::before{content:attr(data-label);font:12px var(--sans);color:var(--fg-3);width:84px;flex:none}
|
|
5432
|
+
.ep-row>td .per{flex:1;min-width:0}
|
|
5433
|
+
.p95{min-width:0}
|
|
5434
|
+
.p95-v{width:auto;text-align:left}
|
|
5435
|
+
.ep-sum{margin-left:0}
|
|
5436
|
+
.ep-detail>td{padding:4px 12px 16px}
|
|
5437
|
+
.kv{grid-template-columns:1fr}
|
|
5438
|
+
.kv dt{border-bottom:0;padding-bottom:0}
|
|
4625
5439
|
}
|
|
4626
5440
|
@media print{
|
|
4627
|
-
.actions{display:none}
|
|
4628
|
-
.
|
|
4629
|
-
.
|
|
4630
|
-
.ep-
|
|
5441
|
+
.top-actions,.toolbar,.runs,.tip,.c-x{display:none!important}
|
|
5442
|
+
.report{max-width:none;padding:0}
|
|
5443
|
+
.panel{break-inside:avoid-page}
|
|
5444
|
+
.ep-row{break-inside:avoid}
|
|
5445
|
+
.run-details>*:not(summary){display:block}
|
|
4631
5446
|
}
|
|
4632
|
-
|
|
5447
|
+
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
|
|
4633
5448
|
`;
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
|
|
5449
|
+
function normalizeSummary(summary) {
|
|
5450
|
+
if (!summary?.metrics) return summary;
|
|
5451
|
+
const metrics = {};
|
|
5452
|
+
for (const [name, m] of Object.entries(summary.metrics)) {
|
|
5453
|
+
if (!m || typeof m !== "object" || m.values) {
|
|
5454
|
+
metrics[name] = m;
|
|
5455
|
+
continue;
|
|
5456
|
+
}
|
|
5457
|
+
const flat = m;
|
|
5458
|
+
const values = {};
|
|
5459
|
+
for (const [k, v] of Object.entries(flat)) if (typeof v === "number") values[k] = v;
|
|
5460
|
+
const isRate = "passes" in flat && "fails" in flat && typeof flat.value === "number";
|
|
5461
|
+
if (isRate) values.rate = flat.value;
|
|
5462
|
+
const thresholds = {};
|
|
5463
|
+
for (const [expr, t] of Object.entries(flat.thresholds ?? {}))
|
|
5464
|
+
thresholds[expr] = typeof t === "boolean" ? { ok: !t } : t;
|
|
5465
|
+
metrics[name] = {
|
|
5466
|
+
type: isRate ? "rate" : void 0,
|
|
5467
|
+
values,
|
|
5468
|
+
thresholds: Object.keys(thresholds).length ? thresholds : void 0
|
|
5469
|
+
};
|
|
5470
|
+
}
|
|
5471
|
+
return { ...summary, metrics };
|
|
5472
|
+
}
|
|
5473
|
+
function renderReport(raw) {
|
|
5474
|
+
const k6Summaries = raw.k6Summaries ? Object.fromEntries(Object.entries(raw.k6Summaries).map(([k, v]) => [k, normalizeSummary(v)])) : void 0;
|
|
5475
|
+
const { meta, loadamVersion } = raw;
|
|
5476
|
+
const model = buildModel(meta, k6Summaries, raw.operations, raw.contractFailures);
|
|
5477
|
+
const dataPayload = {
|
|
5478
|
+
meta,
|
|
5479
|
+
k6Summaries: k6Summaries ?? null,
|
|
5480
|
+
contractFailures: raw.contractFailures ?? null,
|
|
5481
|
+
operations: raw.operations ?? null,
|
|
5482
|
+
loadamVersion
|
|
5483
|
+
};
|
|
5484
|
+
const body = [
|
|
5485
|
+
verdict(model),
|
|
5486
|
+
runSwitcher(model),
|
|
5487
|
+
tiles(model),
|
|
5488
|
+
latency(model),
|
|
5489
|
+
endpoints(model),
|
|
5490
|
+
thresholdsTable(model),
|
|
5491
|
+
drift(raw.driftMarkdown),
|
|
5492
|
+
contract(model.contractFailures),
|
|
5493
|
+
`<div class="panel">${runDetails(meta)}</div>`,
|
|
5494
|
+
footer(meta, loadamVersion)
|
|
5495
|
+
].filter(Boolean).join("\n");
|
|
5496
|
+
return [
|
|
5497
|
+
"<!doctype html>",
|
|
5498
|
+
`<html lang="en">`,
|
|
5499
|
+
"<head>",
|
|
5500
|
+
`<meta charset="utf-8">`,
|
|
5501
|
+
`<meta name="viewport" content="width=device-width,initial-scale=1">`,
|
|
5502
|
+
`<meta name="generator" content="loadam ${esc2(loadamVersion)}">`,
|
|
5503
|
+
`<meta name="color-scheme" content="light dark">`,
|
|
5504
|
+
`<title>${esc2(reportTitle(meta))}</title>`,
|
|
5505
|
+
HEAD_SCRIPT,
|
|
5506
|
+
`<style>${STYLES}${runStyles(model)}</style>`,
|
|
5507
|
+
"</head>",
|
|
5508
|
+
"<body>",
|
|
5509
|
+
`<div class="report"${model.primary && model.runs.length > 1 ? ` data-active-run="${esc2(model.primary.slug)}"` : ""}>`,
|
|
5510
|
+
topBar(),
|
|
5511
|
+
"<main>",
|
|
5512
|
+
body,
|
|
5513
|
+
"</main>",
|
|
5514
|
+
"</div>",
|
|
5515
|
+
`<script type="application/json" id="loadam-data">${escScript(JSON.stringify(dataPayload))}</script>`,
|
|
5516
|
+
BODY_SCRIPT,
|
|
5517
|
+
"</body>",
|
|
5518
|
+
"</html>",
|
|
5519
|
+
""
|
|
5520
|
+
].join("\n");
|
|
5521
|
+
}
|
|
5522
|
+
function reportTitle(meta) {
|
|
5523
|
+
const t = meta.spec.title ?? "loadam";
|
|
5524
|
+
return `${t} \xB7 ${meta.command} \xB7 ${meta.id}`;
|
|
4644
5525
|
}
|
|
4645
|
-
var bH=d.querySelector('[data-loadam-download="html"]');
|
|
4646
|
-
if(bH)bH.addEventListener('click',function(){
|
|
4647
|
-
var html='<!doctype html>\\n'+d.documentElement.outerHTML;
|
|
4648
|
-
dl(new Blob([html],{type:'text/html'}),name+'.html');
|
|
4649
|
-
});
|
|
4650
|
-
var bJ=d.querySelector('[data-loadam-download="json"]');
|
|
4651
|
-
if(bJ)bJ.addEventListener('click',function(){
|
|
4652
|
-
dl(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}),name+'.json');
|
|
4653
|
-
});
|
|
4654
|
-
var bP=d.querySelector('[data-loadam-print]');
|
|
4655
|
-
if(bP)bP.addEventListener('click',function(){window.print()});
|
|
4656
|
-
})();</script>`;
|
|
4657
5526
|
|
|
4658
5527
|
// src/commands/report.ts
|
|
4659
|
-
var VERSION = true ? "0.
|
|
5528
|
+
var VERSION = true ? "0.4.0" : "0.0.0";
|
|
4660
5529
|
function registerReportCommand(program) {
|
|
4661
5530
|
program.command("report").description("Render a self-contained HTML report for an archived session.").argument("[id]", 'session ID, prefix, or "latest" (default: latest)', "latest").option("--root <dir>", "session archive root", "./loadam-out").option("-o, --output <path>", "write to this path instead of <session>/report.html").option("--open", "open the report in your default browser after writing", false).option("--json", "emit a JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runReport));
|
|
4662
5531
|
}
|
|
4663
5532
|
async function runReport(id, opts) {
|
|
4664
5533
|
const out = makeOutput(!!opts.json);
|
|
4665
|
-
const root =
|
|
5534
|
+
const root = resolve11(opts.root);
|
|
4666
5535
|
const meta = await resolveSessionId(root, id);
|
|
4667
5536
|
const dir = join4(root, "sessions", meta.id);
|
|
4668
5537
|
const k6Summaries = {};
|
|
@@ -4711,7 +5580,7 @@ async function runReport(id, opts) {
|
|
|
4711
5580
|
operations,
|
|
4712
5581
|
loadamVersion: VERSION
|
|
4713
5582
|
});
|
|
4714
|
-
const outPath = opts.output ?
|
|
5583
|
+
const outPath = opts.output ? resolve11(opts.output) : join4(dir, "report.html");
|
|
4715
5584
|
await writeFile6(outPath, html, "utf8");
|
|
4716
5585
|
const sizeKb = Math.round(Buffer.byteLength(html, "utf8") / 1024);
|
|
4717
5586
|
if (!out.json) {
|
|
@@ -4746,7 +5615,7 @@ async function openInBrowser(path) {
|
|
|
4746
5615
|
|
|
4747
5616
|
// src/commands/show.ts
|
|
4748
5617
|
import { readFile as readFile9, readdir as readdir2 } from "fs/promises";
|
|
4749
|
-
import { join as join6, resolve as
|
|
5618
|
+
import { join as join6, resolve as resolve12 } from "path";
|
|
4750
5619
|
|
|
4751
5620
|
// src/util/k6.ts
|
|
4752
5621
|
import { spawn as spawn3 } from "child_process";
|
|
@@ -4758,10 +5627,10 @@ async function findK6Binary() {
|
|
|
4758
5627
|
for (const dir of path.split(delimiter)) {
|
|
4759
5628
|
if (!dir) continue;
|
|
4760
5629
|
for (const ext of exts) {
|
|
4761
|
-
const
|
|
5630
|
+
const candidate2 = join5(dir, `k6${ext}`);
|
|
4762
5631
|
try {
|
|
4763
|
-
await access(
|
|
4764
|
-
return
|
|
5632
|
+
await access(candidate2, constants.X_OK);
|
|
5633
|
+
return candidate2;
|
|
4765
5634
|
} catch {
|
|
4766
5635
|
}
|
|
4767
5636
|
}
|
|
@@ -4800,7 +5669,7 @@ async function digestK6Summary(path) {
|
|
|
4800
5669
|
try {
|
|
4801
5670
|
const { readFile: readFile12 } = await import("fs/promises");
|
|
4802
5671
|
const text = await readFile12(path, "utf8");
|
|
4803
|
-
const data = JSON.parse(text);
|
|
5672
|
+
const data = normalizeSummary(JSON.parse(text));
|
|
4804
5673
|
const passed = [];
|
|
4805
5674
|
const failed = [];
|
|
4806
5675
|
const metrics = {};
|
|
@@ -4832,7 +5701,7 @@ function registerShowCommand(program) {
|
|
|
4832
5701
|
}
|
|
4833
5702
|
async function runShow(id, opts) {
|
|
4834
5703
|
const out = makeOutput(!!opts.json);
|
|
4835
|
-
const root =
|
|
5704
|
+
const root = resolve12(opts.root);
|
|
4836
5705
|
const meta = await resolveSessionId(root, id);
|
|
4837
5706
|
const dir = join6(root, "sessions", meta.id);
|
|
4838
5707
|
if (out.json) {
|
|
@@ -4872,10 +5741,10 @@ async function runShow(id, opts) {
|
|
|
4872
5741
|
}
|
|
4873
5742
|
if (meta.command === "diff") {
|
|
4874
5743
|
try {
|
|
4875
|
-
const
|
|
5744
|
+
const drift2 = await readFile9(join6(dir, "drift.md"), "utf8");
|
|
4876
5745
|
out.info("");
|
|
4877
5746
|
out.info("\u2500\u2500\u2500\u2500 drift.md \u2500\u2500\u2500\u2500");
|
|
4878
|
-
process.stdout.write(
|
|
5747
|
+
process.stdout.write(drift2);
|
|
4879
5748
|
} catch {
|
|
4880
5749
|
}
|
|
4881
5750
|
}
|
|
@@ -4925,8 +5794,8 @@ async function runShow(id, opts) {
|
|
|
4925
5794
|
}
|
|
4926
5795
|
|
|
4927
5796
|
// src/commands/test.ts
|
|
4928
|
-
import { mkdir as mkdir4, readFile as readFile11, stat as stat2, writeFile as writeFile8 } from "fs/promises";
|
|
4929
|
-
import { dirname as dirname4, join as join7, resolve as
|
|
5797
|
+
import { copyFile, mkdir as mkdir4, readFile as readFile11, stat as stat2, writeFile as writeFile8 } from "fs/promises";
|
|
5798
|
+
import { dirname as dirname4, join as join7, resolve as resolve15 } from "path";
|
|
4930
5799
|
|
|
4931
5800
|
// ../data/dist/index.js
|
|
4932
5801
|
import { faker } from "@faker-js/faker";
|
|
@@ -5018,82 +5887,441 @@ function inferKindFromFieldName(field) {
|
|
|
5018
5887
|
const root = m[1];
|
|
5019
5888
|
return root.charAt(0).toUpperCase() + root.slice(1);
|
|
5020
5889
|
}
|
|
5021
|
-
function expandRefs(node,
|
|
5022
|
-
if (Array.isArray(node)) return node.map((n) => expandRefs(n,
|
|
5890
|
+
function expandRefs(node, resolve16, seen) {
|
|
5891
|
+
if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve16, seen));
|
|
5023
5892
|
if (!node || typeof node !== "object") return node;
|
|
5024
5893
|
const obj = node;
|
|
5025
5894
|
if (typeof obj.$ref === "string") {
|
|
5026
5895
|
if (seen.has(obj.$ref)) return {};
|
|
5027
|
-
const target =
|
|
5896
|
+
const target = resolve16(obj.$ref);
|
|
5028
5897
|
if (target === void 0) return obj;
|
|
5029
5898
|
const next = new Set(seen);
|
|
5030
5899
|
next.add(obj.$ref);
|
|
5031
|
-
return expandRefs(target,
|
|
5900
|
+
return expandRefs(target, resolve16, next);
|
|
5032
5901
|
}
|
|
5033
5902
|
const out = {};
|
|
5034
|
-
for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v,
|
|
5903
|
+
for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve16, seen);
|
|
5035
5904
|
return out;
|
|
5036
5905
|
}
|
|
5037
5906
|
|
|
5038
5907
|
// ../test-k6/dist/index.js
|
|
5908
|
+
var ENV_RE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
5909
|
+
function apiKeyEnv3(p) {
|
|
5910
|
+
return p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
|
|
5911
|
+
}
|
|
5039
5912
|
function emitAuth2(ir) {
|
|
5040
|
-
const headers = {};
|
|
5041
|
-
const query = {};
|
|
5042
5913
|
const envVars = /* @__PURE__ */ new Set();
|
|
5043
5914
|
const notes = [];
|
|
5044
|
-
|
|
5045
|
-
|
|
5915
|
+
const profiles = ir.auth.filter((p) => p.kind !== "none");
|
|
5916
|
+
const known = new Set(profiles.map((p) => p.id));
|
|
5917
|
+
const logins = profiles.filter((p) => p.kind === "login");
|
|
5918
|
+
const backing = /* @__PURE__ */ new Map();
|
|
5919
|
+
for (const l of logins) if (l.scheme && known.has(l.scheme)) backing.set(l.scheme, l);
|
|
5920
|
+
const globalLogins = logins.filter((l) => !l.scheme || !known.has(l.scheme)).map((l) => l.id);
|
|
5921
|
+
const opsById = new Map(ir.operations.map((o) => [o.id, o]));
|
|
5922
|
+
const entries = [];
|
|
5923
|
+
const fetchers = [];
|
|
5924
|
+
const renew = {};
|
|
5925
|
+
for (const l of logins) {
|
|
5926
|
+
const op = opsById.get(l.operationId);
|
|
5927
|
+
if (!op) {
|
|
5928
|
+
notes.push(`Login "${l.id}": operation "${l.operationId}" is not in the spec; skipped.`);
|
|
5929
|
+
continue;
|
|
5930
|
+
}
|
|
5931
|
+
for (const v of placeholders(l.body)) envVars.add(v);
|
|
5932
|
+
fetchers.push(emitLoginFetcher(l, op));
|
|
5933
|
+
renew[l.id] = l.id;
|
|
5934
|
+
const where = l.tokenPath ? `reads the token from \`${l.tokenPath}\`` : "keeps the session cookie";
|
|
5935
|
+
notes.push(
|
|
5936
|
+
`Login ("${l.id}"): each VU calls ${op.method} ${op.path} with ${[...placeholders(l.body)].map((v) => `\`${v}\``).join(", ") || "the configured body"}, ${where}, and logs in again when it expires or the API answers 401.`
|
|
5937
|
+
);
|
|
5046
5938
|
}
|
|
5047
|
-
|
|
5048
|
-
|
|
5049
|
-
|
|
5050
|
-
|
|
5051
|
-
|
|
5052
|
-
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
const env = p.tokenEnv ?? "API_TOKEN";
|
|
5060
|
-
headers.Authorization = `Bearer \${${env}}`;
|
|
5061
|
-
envVars.add(env);
|
|
5062
|
-
return;
|
|
5939
|
+
for (const p of profiles) {
|
|
5940
|
+
if (p.kind === "login") {
|
|
5941
|
+
if (!opsById.has(p.operationId)) continue;
|
|
5942
|
+
const fn = loginFn(p);
|
|
5943
|
+
entries.push(
|
|
5944
|
+
entry(
|
|
5945
|
+
p.id,
|
|
5946
|
+
readyFor(placeholders(p.body)),
|
|
5947
|
+
`if (!(${readyFor(placeholders(p.body))})) return; const t = __cached(${lit(p.id)}, ${fn}); if (t) ${applyToken(p, "t", p.apply)}`
|
|
5948
|
+
)
|
|
5949
|
+
);
|
|
5950
|
+
continue;
|
|
5063
5951
|
}
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
|
|
5067
|
-
|
|
5068
|
-
|
|
5069
|
-
|
|
5070
|
-
|
|
5952
|
+
const login2 = backing.get(p.id);
|
|
5953
|
+
const viaLogin = login2 && opsById.has(login2.operationId) ? login2 : void 0;
|
|
5954
|
+
switch (p.kind) {
|
|
5955
|
+
case "bearer": {
|
|
5956
|
+
const env = p.tokenEnv ?? "API_TOKEN";
|
|
5957
|
+
if (viaLogin) {
|
|
5958
|
+
renew[p.id] = viaLogin.id;
|
|
5959
|
+
notes.push(`\`${env}\` is optional: set it to use a fixed token instead of logging in.`);
|
|
5960
|
+
entries.push(
|
|
5961
|
+
entry(
|
|
5962
|
+
p.id,
|
|
5963
|
+
`!!__env(${lit(env)}) || (${readyFor(placeholders(viaLogin.body))})`,
|
|
5964
|
+
`const s = __env(${lit(env)}); if (s) { h['Authorization'] = 'Bearer ' + s; return; } if (!(${readyFor(placeholders(viaLogin.body))})) return; const t = __cached(${lit(viaLogin.id)}, ${loginFn(viaLogin)}); if (t) ${applyToken(viaLogin, "t", viaLogin.apply ?? { in: "header", name: "Authorization", format: "Bearer {token}" })}`
|
|
5965
|
+
)
|
|
5966
|
+
);
|
|
5967
|
+
} else {
|
|
5968
|
+
envVars.add(env);
|
|
5969
|
+
entries.push(
|
|
5970
|
+
entry(
|
|
5971
|
+
p.id,
|
|
5972
|
+
`!!__env(${lit(env)})`,
|
|
5973
|
+
`const t = __env(${lit(env)}); if (t) h['Authorization'] = 'Bearer ' + t;`
|
|
5974
|
+
)
|
|
5975
|
+
);
|
|
5976
|
+
}
|
|
5977
|
+
break;
|
|
5071
5978
|
}
|
|
5072
|
-
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5078
|
-
|
|
5079
|
-
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
|
|
5979
|
+
case "apiKey": {
|
|
5980
|
+
const env = apiKeyEnv3(p);
|
|
5981
|
+
const put = (v) => p.in === "header" ? `h[${lit(p.name)}] = ${v};` : p.in === "query" ? `q[${lit(p.name)}] = ${v};` : `__cookie(h, ${lit(p.name)}, ${v});`;
|
|
5982
|
+
if (viaLogin) {
|
|
5983
|
+
renew[p.id] = viaLogin.id;
|
|
5984
|
+
entries.push(
|
|
5985
|
+
entry(
|
|
5986
|
+
p.id,
|
|
5987
|
+
`!!__env(${lit(env)}) || (${readyFor(placeholders(viaLogin.body))})`,
|
|
5988
|
+
`const s = __env(${lit(env)}); if (s) { ${put("s")} return; } if (!(${readyFor(placeholders(viaLogin.body))})) return; const t = __cached(${lit(viaLogin.id)}, ${loginFn(viaLogin)}); if (t) ${applyToken(viaLogin, "t", viaLogin.apply ?? { in: p.in, name: p.name, format: "{token}" })}`
|
|
5989
|
+
)
|
|
5990
|
+
);
|
|
5991
|
+
} else {
|
|
5992
|
+
envVars.add(env);
|
|
5993
|
+
entries.push(
|
|
5994
|
+
entry(p.id, `!!__env(${lit(env)})`, `const v = __env(${lit(env)}); if (v) ${put("v")}`)
|
|
5995
|
+
);
|
|
5996
|
+
}
|
|
5997
|
+
break;
|
|
5998
|
+
}
|
|
5999
|
+
case "basic": {
|
|
6000
|
+
const u = p.userEnv ?? "API_USER";
|
|
6001
|
+
const pw = p.passEnv ?? "API_PASS";
|
|
6002
|
+
envVars.add(u);
|
|
6003
|
+
envVars.add(pw);
|
|
6004
|
+
entries.push(
|
|
6005
|
+
entry(
|
|
6006
|
+
p.id,
|
|
6007
|
+
`!!(__env(${lit(u)}) && __env(${lit(pw)}))`,
|
|
6008
|
+
`const u = __env(${lit(u)}); const pw = __env(${lit(pw)}); if (u && pw) h['Authorization'] = 'Basic ' + encoding.b64encode(u + ':' + pw);`
|
|
6009
|
+
)
|
|
6010
|
+
);
|
|
6011
|
+
break;
|
|
6012
|
+
}
|
|
6013
|
+
case "oauth2_cc": {
|
|
6014
|
+
envVars.add(p.clientIdEnv);
|
|
6015
|
+
envVars.add(p.clientSecretEnv);
|
|
6016
|
+
renew[p.id] = p.id;
|
|
6017
|
+
fetchers.push(emitOAuthFetcher(p));
|
|
6018
|
+
notes.push(
|
|
6019
|
+
`OAuth2 client credentials ("${p.id}"): each VU fetches a token from ${p.tokenUrl} using \`${p.clientIdEnv}\`/\`${p.clientSecretEnv}\`, and fetches a new one before it expires.`
|
|
6020
|
+
);
|
|
6021
|
+
entries.push(
|
|
6022
|
+
entry(
|
|
6023
|
+
p.id,
|
|
6024
|
+
`!!(__env(${lit(p.clientIdEnv)}) && __env(${lit(p.clientSecretEnv)}))`,
|
|
6025
|
+
`const t = __cached(${lit(p.id)}, ${oauthFn(p)}); if (t) h['Authorization'] = 'Bearer ' + t;`
|
|
6026
|
+
)
|
|
6027
|
+
);
|
|
6028
|
+
break;
|
|
6029
|
+
}
|
|
6030
|
+
case "custom":
|
|
6031
|
+
notes.push(`Custom auth signer "${p.signerRef}": wire it up by hand in config.js.`);
|
|
6032
|
+
entries.push(entry(p.id, "false", ""));
|
|
6033
|
+
break;
|
|
5083
6034
|
}
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5091
|
-
|
|
6035
|
+
}
|
|
6036
|
+
const loginOps = logins.map((l) => l.operationId).filter((id) => opsById.has(id));
|
|
6037
|
+
const loginOpSet = new Set(loginOps);
|
|
6038
|
+
const flat = profiles.filter((p) => p.kind !== "login").map((p) => p.id);
|
|
6039
|
+
const setsFor = (op) => {
|
|
6040
|
+
if (loginOpSet.has(op.id)) return [];
|
|
6041
|
+
const req = op.securityRequirements;
|
|
6042
|
+
if (req === void 0) {
|
|
6043
|
+
const all = [...flat, ...globalLogins];
|
|
6044
|
+
return all.length > 0 ? [all] : [];
|
|
6045
|
+
}
|
|
6046
|
+
if (req.length === 0) return [];
|
|
6047
|
+
const sets = req.map((set) => set.map((r) => r.profileId).filter((id) => known.has(id)));
|
|
6048
|
+
const authed = sets.filter((s) => s.length > 0).map((s) => [...s, ...globalLogins]);
|
|
6049
|
+
const anon = sets.filter((s) => s.length === 0);
|
|
6050
|
+
return [...authed, ...anon];
|
|
6051
|
+
};
|
|
6052
|
+
const defaultSets = (() => {
|
|
6053
|
+
const all = [...flat, ...globalLogins];
|
|
6054
|
+
return all.length > 0 ? [all] : [];
|
|
6055
|
+
})();
|
|
6056
|
+
const runtime = `
|
|
6057
|
+
// \u2500\u2500\u2500 auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
6058
|
+
// Credentials come from env vars, or from this VU's row of users.csv when the
|
|
6059
|
+
// rig has one (a header row of env var names, then one user per row).
|
|
6060
|
+
|
|
6061
|
+
const USERS = (function () {
|
|
6062
|
+
try {
|
|
6063
|
+
return new SharedArray('loadam-users', function () { return __csv(open('./users.csv')); });
|
|
6064
|
+
} catch (_) {
|
|
6065
|
+
return [];
|
|
6066
|
+
}
|
|
6067
|
+
})();
|
|
6068
|
+
|
|
6069
|
+
function __csv(text) {
|
|
6070
|
+
const lines = String(text).split(/\\r?\\n/).filter(function (l) { return l.trim() !== ''; });
|
|
6071
|
+
if (lines.length < 2) return [];
|
|
6072
|
+
const cells = function (l) { return l.split(',').map(function (c) { return c.trim().replace(/^"(.*)"$/, '$1'); }); };
|
|
6073
|
+
const head = cells(lines[0]);
|
|
6074
|
+
return lines.slice(1).map(function (l) {
|
|
6075
|
+
const row = {};
|
|
6076
|
+
const c = cells(l);
|
|
6077
|
+
for (let i = 0; i < head.length; i++) row[head[i]] = c[i] || '';
|
|
6078
|
+
return row;
|
|
6079
|
+
});
|
|
6080
|
+
}
|
|
6081
|
+
|
|
6082
|
+
export function userCount() {
|
|
6083
|
+
return USERS.length;
|
|
6084
|
+
}
|
|
6085
|
+
|
|
6086
|
+
function __env(name) {
|
|
6087
|
+
if (USERS.length > 0) {
|
|
6088
|
+
const row = USERS[(Math.max(__VU, 1) - 1) % USERS.length];
|
|
6089
|
+
if (row[name]) return row[name];
|
|
6090
|
+
}
|
|
6091
|
+
return (typeof __ENV !== 'undefined' && __ENV[name]) || '';
|
|
6092
|
+
}
|
|
6093
|
+
|
|
6094
|
+
function __get(obj, path) {
|
|
6095
|
+
let cur = obj;
|
|
6096
|
+
for (const k of String(path).split('.')) {
|
|
6097
|
+
if (cur === null || cur === undefined || typeof cur !== 'object') return undefined;
|
|
6098
|
+
cur = cur[k];
|
|
6099
|
+
}
|
|
6100
|
+
return cur;
|
|
6101
|
+
}
|
|
6102
|
+
|
|
6103
|
+
function __cookie(h, name, value) {
|
|
6104
|
+
h['Cookie'] = (h['Cookie'] ? h['Cookie'] + '; ' : '') + name + '=' + value;
|
|
6105
|
+
}
|
|
6106
|
+
|
|
6107
|
+
// Seconds until the first of a response's cookies expires (Max-Age or Expires). 0 = unknown.
|
|
6108
|
+
function __cookieTtl(res) {
|
|
6109
|
+
let ttl = 0;
|
|
6110
|
+
for (const n in res.cookies) {
|
|
6111
|
+
for (const c of res.cookies[n]) {
|
|
6112
|
+
let s = c.max_age > 0 ? c.max_age : 0;
|
|
6113
|
+
if (!s && c.expires) {
|
|
6114
|
+
const at = typeof c.expires === 'number' ? c.expires : Date.parse(c.expires);
|
|
6115
|
+
if (at > 0) s = Math.round((at - Date.now()) / 1000);
|
|
6116
|
+
}
|
|
6117
|
+
if (s > 0 && (!ttl || s < ttl)) ttl = s;
|
|
5092
6118
|
}
|
|
5093
|
-
case "custom":
|
|
5094
|
-
notes.push(`Custom auth signer "${p.signerRef}" \u2014 wire manually.`);
|
|
5095
|
-
return;
|
|
5096
6119
|
}
|
|
6120
|
+
return ttl;
|
|
6121
|
+
}
|
|
6122
|
+
|
|
6123
|
+
// Expiry from a JWT's exp claim, in ms. 0 when the token is not a JWT.
|
|
6124
|
+
function __jwtExp(token) {
|
|
6125
|
+
const parts = String(token).split('.');
|
|
6126
|
+
if (parts.length !== 3) return 0;
|
|
6127
|
+
try {
|
|
6128
|
+
const claims = JSON.parse(encoding.b64decode(parts[1], 'rawurl', 's'));
|
|
6129
|
+
return typeof claims.exp === 'number' ? claims.exp * 1000 : 0;
|
|
6130
|
+
} catch (_) {
|
|
6131
|
+
return 0;
|
|
6132
|
+
}
|
|
6133
|
+
}
|
|
6134
|
+
|
|
6135
|
+
// Absolute URL for an auth endpoint: relative ones resolve against BASE_URL.
|
|
6136
|
+
function __authUrl(u) {
|
|
6137
|
+
if (/^https?:/i.test(u)) return u;
|
|
6138
|
+
if (u.charAt(0) === '/') return BASE_URL.replace(/^(https?:\\/\\/[^/]+).*$/i, '$1') + u;
|
|
6139
|
+
return BASE_URL.replace(/\\/$/, '') + '/' + u;
|
|
6140
|
+
}
|
|
6141
|
+
|
|
6142
|
+
const authRefreshes = new Counter('loadam_auth_refreshes');
|
|
6143
|
+
const __tokens = {};
|
|
6144
|
+
|
|
6145
|
+
// A fetched credential, cached per VU and fetched again shortly before it expires.
|
|
6146
|
+
function __cached(id, fetchFn) {
|
|
6147
|
+
const now = Date.now();
|
|
6148
|
+
const c = __tokens[id];
|
|
6149
|
+
if (c && (!c.exp || now < c.exp - c.margin)) return c.token;
|
|
6150
|
+
const got = fetchFn();
|
|
6151
|
+
if (!got || !got.token) {
|
|
6152
|
+
// Don't fetch again on every request after a failure: wait a few seconds.
|
|
6153
|
+
__tokens[id] = { token: null, exp: now + 5000, margin: 0 };
|
|
6154
|
+
return null;
|
|
6155
|
+
}
|
|
6156
|
+
const exp = got.expiresIn > 0 ? now + got.expiresIn * 1000 : __jwtExp(got.token);
|
|
6157
|
+
if (c && c.token) authRefreshes.add(1);
|
|
6158
|
+
__tokens[id] = { token: got.token, exp: exp, margin: exp ? Math.min((exp - now) * 0.1, 30000) : 0 };
|
|
6159
|
+
return got.token;
|
|
6160
|
+
}
|
|
6161
|
+
${fetchers.join("")}
|
|
6162
|
+
const AUTH = {
|
|
6163
|
+
${entries.join(",\n")}
|
|
6164
|
+
};
|
|
6165
|
+
|
|
6166
|
+
// Profile id \u2192 the cached credential it uses, for profiles that can fetch a new one.
|
|
6167
|
+
const RENEW = ${JSON.stringify(renew)};
|
|
6168
|
+
|
|
6169
|
+
const DEFAULT_SETS = ${JSON.stringify(defaultSets)};
|
|
6170
|
+
|
|
6171
|
+
/**
|
|
6172
|
+
* Credentials for one request. \`sets\` is the operation's security: any one
|
|
6173
|
+
* set satisfies it, and every profile in that set is sent. The first set
|
|
6174
|
+
* whose credentials are all configured wins.
|
|
6175
|
+
*/
|
|
6176
|
+
export function authFor(sets) {
|
|
6177
|
+
const out = { headers: {}, query: {}, ids: [] };
|
|
6178
|
+
if (!sets || sets.length === 0) return out;
|
|
6179
|
+
let pick = sets[0];
|
|
6180
|
+
for (const s of sets) {
|
|
6181
|
+
if (s.every(function (id) { return AUTH[id] && AUTH[id].ready(); })) { pick = s; break; }
|
|
6182
|
+
}
|
|
6183
|
+
for (const id of pick) if (AUTH[id]) AUTH[id].apply(out.headers, out.query);
|
|
6184
|
+
out.ids = pick;
|
|
6185
|
+
return out;
|
|
6186
|
+
}
|
|
6187
|
+
|
|
6188
|
+
/** Forget cached tokens behind these profiles. True when there is something to fetch again. */
|
|
6189
|
+
export function renewAuth(ids) {
|
|
6190
|
+
let any = false;
|
|
6191
|
+
for (const id of ids || []) {
|
|
6192
|
+
const key = RENEW[id];
|
|
6193
|
+
if (!key) continue;
|
|
6194
|
+
if (__tokens[key]) __tokens[key].exp = 1;
|
|
6195
|
+
any = true;
|
|
6196
|
+
}
|
|
6197
|
+
return any;
|
|
6198
|
+
}
|
|
6199
|
+
|
|
6200
|
+
/** Logins that fail with the current credentials, as readable messages. */
|
|
6201
|
+
export function checkLogins() {
|
|
6202
|
+
const failed = [];
|
|
6203
|
+
${logins.filter((l) => opsById.has(l.operationId)).map(
|
|
6204
|
+
(l) => ` if (${readyFor(placeholders(l.body))} && !__cached(${lit(l.id)}, ${loginFn(l)})) failed.push(${lit(`login via ${opsById.get(l.operationId).method} ${opsById.get(l.operationId).path} failed`)});`
|
|
6205
|
+
).join("\n")}
|
|
6206
|
+
return failed;
|
|
6207
|
+
}
|
|
6208
|
+
|
|
6209
|
+
export function authHeaders() {
|
|
6210
|
+
return authFor(DEFAULT_SETS).headers;
|
|
6211
|
+
}
|
|
6212
|
+
|
|
6213
|
+
export function authQuery() {
|
|
6214
|
+
return authFor(DEFAULT_SETS).query;
|
|
6215
|
+
}
|
|
6216
|
+
`;
|
|
6217
|
+
return {
|
|
6218
|
+
envVars: [...envVars].sort(),
|
|
6219
|
+
notes,
|
|
6220
|
+
loginOps,
|
|
6221
|
+
renewable: Object.keys(renew).length > 0,
|
|
6222
|
+
runtime,
|
|
6223
|
+
setsFor
|
|
6224
|
+
};
|
|
6225
|
+
}
|
|
6226
|
+
function entry(id, ready, apply2) {
|
|
6227
|
+
return ` ${lit(id)}: {
|
|
6228
|
+
ready: function () { return ${ready}; },
|
|
6229
|
+
apply: function (h, q) { ${apply2} },
|
|
6230
|
+
}`;
|
|
6231
|
+
}
|
|
6232
|
+
function lit(s) {
|
|
6233
|
+
return JSON.stringify(s);
|
|
6234
|
+
}
|
|
6235
|
+
function placeholders(body) {
|
|
6236
|
+
const out = /* @__PURE__ */ new Set();
|
|
6237
|
+
for (const v of Object.values(body)) for (const m of v.matchAll(ENV_RE)) out.add(m[1]);
|
|
6238
|
+
return out;
|
|
6239
|
+
}
|
|
6240
|
+
function readyFor(vars) {
|
|
6241
|
+
return vars.size === 0 ? "true" : [...vars].map((v) => `!!__env(${lit(v)})`).join(" && ");
|
|
6242
|
+
}
|
|
6243
|
+
function template(value) {
|
|
6244
|
+
const parts = [];
|
|
6245
|
+
let last = 0;
|
|
6246
|
+
for (const m of value.matchAll(ENV_RE)) {
|
|
6247
|
+
if (m.index > last) parts.push(lit(value.slice(last, m.index)));
|
|
6248
|
+
parts.push(`__env(${lit(m[1])})`);
|
|
6249
|
+
last = m.index + m[0].length;
|
|
6250
|
+
}
|
|
6251
|
+
if (last < value.length) parts.push(lit(value.slice(last)));
|
|
6252
|
+
return parts.length === 0 ? "''" : parts.join(" + ");
|
|
6253
|
+
}
|
|
6254
|
+
function fnName(prefix, id) {
|
|
6255
|
+
return `${prefix}${id.replace(/[^A-Za-z0-9_]/g, "_")}`;
|
|
6256
|
+
}
|
|
6257
|
+
function loginFn(l) {
|
|
6258
|
+
return fnName("__login_", l.id);
|
|
6259
|
+
}
|
|
6260
|
+
function oauthFn(p) {
|
|
6261
|
+
return fnName("__oauth_", p.id);
|
|
6262
|
+
}
|
|
6263
|
+
function applyToken(l, v, apply2) {
|
|
6264
|
+
if (!l.tokenPath) return `h['Cookie'] = (h['Cookie'] ? h['Cookie'] + '; ' : '') + ${v};`;
|
|
6265
|
+
const a = apply2 ?? { in: "header", name: "Authorization", format: "Bearer {token}" };
|
|
6266
|
+
const value = a.format.split("{token}").map((s) => lit(s)).join(` + ${v} + `).replace(/^"" \+ /, "").replace(/ \+ ""$/, "");
|
|
6267
|
+
if (a.in === "query") return `q[${lit(a.name)}] = ${value};`;
|
|
6268
|
+
if (a.in === "cookie") return `__cookie(h, ${lit(a.name)}, ${value});`;
|
|
6269
|
+
return `h[${lit(a.name)}] = ${value};`;
|
|
6270
|
+
}
|
|
6271
|
+
function emitLoginFetcher(l, op) {
|
|
6272
|
+
const ct = Object.keys(op.body?.contentTypes ?? {})[0] ?? "application/json";
|
|
6273
|
+
const form = ct.startsWith("application/x-www-form-urlencoded");
|
|
6274
|
+
const fields = Object.entries(l.body).map(([k, v]) => `${lit(k)}: ${template(v)}`).join(", ");
|
|
6275
|
+
const method = op.method.toLowerCase() === "delete" ? "del" : op.method.toLowerCase();
|
|
6276
|
+
const payload = form ? "body" : "JSON.stringify(body)";
|
|
6277
|
+
const token = l.tokenPath ? `__get(b, ${lit(l.tokenPath)})` : "Object.keys(res.cookies).filter(function (n) { return res.cookies[n].length > 0; }).map(function (n) { return n + '=' + res.cookies[n][0].value; }).join('; ')";
|
|
6278
|
+
return `
|
|
6279
|
+
// Log in by calling ${op.method} ${op.path} (${op.id}).
|
|
6280
|
+
function ${loginFn(l)}() {
|
|
6281
|
+
const body = { ${fields} };
|
|
6282
|
+
const res = http.${method}(
|
|
6283
|
+
buildUrl(${lit(op.path)}, undefined, undefined, {}),
|
|
6284
|
+
${payload},
|
|
6285
|
+
{ headers: { 'Content-Type': ${lit(form ? "application/x-www-form-urlencoded" : "application/json")}, Accept: 'application/json' }, tags: { name: '__auth' } },
|
|
6286
|
+
);
|
|
6287
|
+
if (res.status < 200 || res.status >= 300) {
|
|
6288
|
+
console.warn('loadam: login via ${op.method} ${op.path} failed with ' + res.status);
|
|
6289
|
+
return null;
|
|
6290
|
+
}
|
|
6291
|
+
let b;
|
|
6292
|
+
try { b = res.json(); } catch (_) { b = undefined; }
|
|
6293
|
+
const token = ${token};
|
|
6294
|
+
if (!token) {
|
|
6295
|
+
console.warn('loadam: login response has ${l.tokenPath ? `no token at "${l.tokenPath}"` : "no cookies"}');
|
|
6296
|
+
return null;
|
|
6297
|
+
}
|
|
6298
|
+
return { token: String(token), expiresIn: ${l.tokenPath ? `Number(__get(b, ${lit(l.expiresInPath ?? "expires_in")})) || 0` : "__cookieTtl(res)"} };
|
|
6299
|
+
}
|
|
6300
|
+
`;
|
|
6301
|
+
}
|
|
6302
|
+
function emitOAuthFetcher(p) {
|
|
6303
|
+
const scope = p.scopes?.length ? ` + '&scope=' + encodeURIComponent(${lit(p.scopes.join(" "))})` : "";
|
|
6304
|
+
return `
|
|
6305
|
+
// OAuth2 client credentials token for "${p.id}". A relative tokenUrl resolves against BASE_URL.
|
|
6306
|
+
function ${oauthFn(p)}() {
|
|
6307
|
+
const id = __env(${lit(p.clientIdEnv)});
|
|
6308
|
+
const secret = __env(${lit(p.clientSecretEnv)});
|
|
6309
|
+
if (!id || !secret) return null;
|
|
6310
|
+
const url = __authUrl(${lit(p.tokenUrl)});
|
|
6311
|
+
const res = http.post(
|
|
6312
|
+
url,
|
|
6313
|
+
'grant_type=client_credentials&client_id=' + encodeURIComponent(id) + '&client_secret=' + encodeURIComponent(secret)${scope},
|
|
6314
|
+
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, tags: { name: '__auth' } },
|
|
6315
|
+
);
|
|
6316
|
+
let body = {};
|
|
6317
|
+
try { body = res.json(); } catch (_) { body = {}; }
|
|
6318
|
+
if (res.status >= 200 && res.status < 300 && body && body.access_token) {
|
|
6319
|
+
return { token: body.access_token, expiresIn: Number(body.expires_in) || 0 };
|
|
6320
|
+
}
|
|
6321
|
+
console.warn('loadam: OAuth2 token request to ' + url + ' failed with ' + res.status);
|
|
6322
|
+
return null;
|
|
6323
|
+
}
|
|
6324
|
+
`;
|
|
5097
6325
|
}
|
|
5098
6326
|
function sequenceForSmoke(ir) {
|
|
5099
6327
|
const opsById = new Map(ir.operations.map((o) => [o.id, o]));
|
|
@@ -5178,9 +6406,9 @@ function buildFixturePool(ir, opts = {}) {
|
|
|
5178
6406
|
fix.pathParams = generateParamPool(op.pathParams, size, seed + i, resolveRef2);
|
|
5179
6407
|
}
|
|
5180
6408
|
if (op.queryParams.length > 0) {
|
|
5181
|
-
const
|
|
5182
|
-
if (
|
|
5183
|
-
const columns = generateParamPool(
|
|
6409
|
+
const required2 = op.queryParams.filter((p) => p.required);
|
|
6410
|
+
if (required2.length > 0) {
|
|
6411
|
+
const columns = generateParamPool(required2, size, seed + i, resolveRef2);
|
|
5184
6412
|
fix.queryParams = Array.from(
|
|
5185
6413
|
{ length: size },
|
|
5186
6414
|
(_, row) => Object.fromEntries(Object.entries(columns).map(([name, values]) => [name, values[row]]))
|
|
@@ -5235,7 +6463,7 @@ function makeRefResolver(ir) {
|
|
|
5235
6463
|
return void 0;
|
|
5236
6464
|
};
|
|
5237
6465
|
}
|
|
5238
|
-
function
|
|
6466
|
+
function resolve13(ir, schema) {
|
|
5239
6467
|
if (typeof schema === "string") return ir.schemas[schema]?.jsonSchema;
|
|
5240
6468
|
if (!schema || typeof schema !== "object") return void 0;
|
|
5241
6469
|
const js = "jsonSchema" in schema ? schema.jsonSchema : schema;
|
|
@@ -5245,7 +6473,7 @@ function resolve12(ir, schema) {
|
|
|
5245
6473
|
function buildIdFields(ir) {
|
|
5246
6474
|
const out = {};
|
|
5247
6475
|
for (const kind of ir.resources.kinds) {
|
|
5248
|
-
const schema = kind.schemaId ?
|
|
6476
|
+
const schema = kind.schemaId ? resolve13(ir, kind.schemaId) : void 0;
|
|
5249
6477
|
const prop = schema?.properties?.[kind.idField];
|
|
5250
6478
|
out[kind.name] = { field: kind.idField, type: prop?.type };
|
|
5251
6479
|
}
|
|
@@ -5257,7 +6485,7 @@ function buildBodyRefs(ir) {
|
|
|
5257
6485
|
if (!op.body || !op.consumes?.length) continue;
|
|
5258
6486
|
const ct = pickContentType(op.body);
|
|
5259
6487
|
const media = ct ? op.body.contentTypes[ct] : void 0;
|
|
5260
|
-
const props = media ?
|
|
6488
|
+
const props = media ? resolve13(ir, media.schema)?.properties : void 0;
|
|
5261
6489
|
if (!props) continue;
|
|
5262
6490
|
const refs = {};
|
|
5263
6491
|
for (const c of op.consumes) {
|
|
@@ -5268,7 +6496,7 @@ function buildBodyRefs(ir) {
|
|
|
5268
6496
|
return out;
|
|
5269
6497
|
}
|
|
5270
6498
|
function binaryFields(ir, schema) {
|
|
5271
|
-
const props = schema ?
|
|
6499
|
+
const props = schema ? resolve13(ir, schema)?.properties : void 0;
|
|
5272
6500
|
if (!props) return [];
|
|
5273
6501
|
return Object.entries(props).filter(([, v]) => {
|
|
5274
6502
|
const f = v?.format;
|
|
@@ -5276,36 +6504,21 @@ function binaryFields(ir, schema) {
|
|
|
5276
6504
|
}).map(([k]) => k);
|
|
5277
6505
|
}
|
|
5278
6506
|
function emitConfigJs(ctx) {
|
|
5279
|
-
const { auth } = ctx;
|
|
5280
6507
|
const base = ctx.baseUrl;
|
|
5281
|
-
const headerEntries = Object.entries(auth.headers);
|
|
5282
|
-
const queryEntries = Object.entries(auth.query);
|
|
5283
|
-
const needsB64 = headerEntries.some(([, v]) => v.startsWith("__BASIC__:"));
|
|
5284
|
-
const oauth = ctx.ir.auth.filter((p) => p.kind === "oauth2_cc");
|
|
5285
|
-
const importLine = (needsB64 ? "import encoding from 'k6/encoding';\n" : "") + (oauth.length > 0 ? "import http from 'k6/http';\n" : "");
|
|
5286
|
-
const headersBody = headerEntries.length ? headerEntries.map(([k, v]) => ` ${buildHeaderLine2(k, v)}`).join("\n") : " // no auth headers";
|
|
5287
|
-
const queryBody = queryEntries.length ? queryEntries.map(([k, v]) => ` ${JSON.stringify(k)}: ${interpolate2(v)},`).join("\n") : "";
|
|
5288
6508
|
return `// AUTO-GENERATED by @loadam/test-k6
|
|
5289
|
-
|
|
6509
|
+
import http from 'k6/http';
|
|
6510
|
+
import encoding from 'k6/encoding';
|
|
6511
|
+
import { SharedArray } from 'k6/data';
|
|
6512
|
+
import { Counter } from 'k6/metrics';
|
|
6513
|
+
|
|
5290
6514
|
const BASE_URL = (typeof __ENV !== 'undefined' && __ENV.BASE_URL) || ${JSON.stringify(base)};
|
|
5291
6515
|
|
|
5292
6516
|
export function baseUrl() {
|
|
5293
6517
|
return BASE_URL;
|
|
5294
6518
|
}
|
|
5295
|
-
${
|
|
5296
|
-
|
|
5297
|
-
|
|
5298
|
-
${headersBody}
|
|
5299
|
-
return h;
|
|
5300
|
-
}
|
|
5301
|
-
|
|
5302
|
-
export function authQuery() {
|
|
5303
|
-
return {
|
|
5304
|
-
${queryBody}
|
|
5305
|
-
};
|
|
5306
|
-
}
|
|
5307
|
-
|
|
5308
|
-
export function buildUrl(path, pathParams, queryParams) {
|
|
6519
|
+
${ctx.auth.runtime}
|
|
6520
|
+
/** URL for a request. \`authQ\` is the query part of authFor(); omitted, the default credentials. */
|
|
6521
|
+
export function buildUrl(path, pathParams, queryParams, authQ) {
|
|
5309
6522
|
let p = path;
|
|
5310
6523
|
if (pathParams) {
|
|
5311
6524
|
for (const k in pathParams) {
|
|
@@ -5313,7 +6526,7 @@ export function buildUrl(path, pathParams, queryParams) {
|
|
|
5313
6526
|
p = p.split('{' + k + '}').join(encodeURIComponent(String(pathParams[k])));
|
|
5314
6527
|
}
|
|
5315
6528
|
}
|
|
5316
|
-
const aq = authQuery();
|
|
6529
|
+
const aq = authQ === undefined ? authQuery() : authQ;
|
|
5317
6530
|
const merged = Object.assign({}, queryParams || {}, aq);
|
|
5318
6531
|
const parts = [];
|
|
5319
6532
|
for (const k of Object.keys(merged)) {
|
|
@@ -5331,71 +6544,26 @@ export function buildUrl(path, pathParams, queryParams) {
|
|
|
5331
6544
|
}
|
|
5332
6545
|
`;
|
|
5333
6546
|
}
|
|
5334
|
-
function emitOAuthFetcher(p) {
|
|
5335
|
-
if (p.kind !== "oauth2_cc") return "";
|
|
5336
|
-
const fn = `__oauth_${p.id.replace(/[^A-Za-z0-9_]/g, "_")}`;
|
|
5337
|
-
const scope = p.scopes?.length ? `&scope=' + encodeURIComponent(${JSON.stringify(p.scopes.join(" "))}) + '` : "";
|
|
5338
|
-
return `
|
|
5339
|
-
let ${fn}_token = null;
|
|
5340
|
-
function ${fn}() {
|
|
5341
|
-
if (${fn}_token) return ${fn}_token;
|
|
5342
|
-
const id = __ENV.${p.clientIdEnv};
|
|
5343
|
-
const secret = __ENV.${p.clientSecretEnv};
|
|
5344
|
-
if (!id || !secret) return null;
|
|
5345
|
-
const tokenUrl = ${JSON.stringify(p.tokenUrl)};
|
|
5346
|
-
const url = /^https?:/i.test(tokenUrl)
|
|
5347
|
-
? tokenUrl
|
|
5348
|
-
: tokenUrl.charAt(0) === '/'
|
|
5349
|
-
? BASE_URL.replace(/^(https?:\\/\\/[^/]+).*$/i, '$1') + tokenUrl
|
|
5350
|
-
: BASE_URL.replace(/\\/$/, '') + '/' + tokenUrl;
|
|
5351
|
-
const res = http.post(
|
|
5352
|
-
url,
|
|
5353
|
-
'grant_type=client_credentials&client_id=' + encodeURIComponent(id) + '&client_secret=' + encodeURIComponent(secret) + '${scope}',
|
|
5354
|
-
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, tags: { name: '__oauth_token' } },
|
|
5355
|
-
);
|
|
5356
|
-
let body = {};
|
|
5357
|
-
try { body = res.json(); } catch (_) { body = {}; }
|
|
5358
|
-
if (res.status >= 200 && res.status < 300 && body && body.access_token) {
|
|
5359
|
-
${fn}_token = body.access_token;
|
|
5360
|
-
} else {
|
|
5361
|
-
console.warn('loadam: OAuth2 token request to ' + url + ' failed with ' + res.status);
|
|
5362
|
-
}
|
|
5363
|
-
return ${fn}_token;
|
|
5364
|
-
}
|
|
5365
|
-
`;
|
|
5366
|
-
}
|
|
5367
|
-
function buildHeaderLine2(name, value) {
|
|
5368
|
-
if (value.startsWith("__OAUTH2__:")) {
|
|
5369
|
-
const fn = `__oauth_${value.slice("__OAUTH2__:".length).replace(/[^A-Za-z0-9_]/g, "_")}`;
|
|
5370
|
-
return `{ const t = ${fn}(); if (t) { h[${JSON.stringify(name)}] = 'Bearer ' + t; } }`;
|
|
5371
|
-
}
|
|
5372
|
-
if (value.startsWith("__BASIC__:")) {
|
|
5373
|
-
const [, userEnv, passEnv] = value.split(":");
|
|
5374
|
-
return `if (__ENV.${userEnv} && __ENV.${passEnv}) { h.Authorization = 'Basic ' + encoding.b64encode(__ENV.${userEnv} + ':' + __ENV.${passEnv}); }`;
|
|
5375
|
-
}
|
|
5376
|
-
return `h[${JSON.stringify(name)}] = ${interpolate2(value)};`;
|
|
5377
|
-
}
|
|
5378
|
-
function interpolate2(value) {
|
|
5379
|
-
const replaced = value.replace(/\$\{([A-Z0-9_]+)\}/g, (_m, name) => `\${__ENV.${name} || ''}`);
|
|
5380
|
-
return `\`${replaced}\``;
|
|
5381
|
-
}
|
|
5382
6547
|
function emitFlowJs(ctx) {
|
|
5383
6548
|
const ops = ctx.sequencedOps;
|
|
5384
6549
|
const lines = [];
|
|
5385
6550
|
for (let i = 0; i < ops.length; i++) {
|
|
5386
6551
|
const op = ops[i];
|
|
5387
6552
|
if (!op) continue;
|
|
5388
|
-
lines.push(emitOpCall(ctx.ir, op));
|
|
6553
|
+
lines.push(emitOpCall(ctx.ir, op, ctx.auth.setsFor(op)));
|
|
5389
6554
|
}
|
|
5390
6555
|
return `// AUTO-GENERATED by @loadam/test-k6
|
|
5391
6556
|
import http from 'k6/http';
|
|
5392
6557
|
import { check } from 'k6';
|
|
6558
|
+
import exec from 'k6/execution';
|
|
5393
6559
|
import { Counter, Trend } from 'k6/metrics';
|
|
5394
6560
|
import { SharedArray } from 'k6/data';
|
|
5395
|
-
import {
|
|
6561
|
+
import { authFor, buildUrl, checkLogins, renewAuth } from './config.js';
|
|
5396
6562
|
|
|
5397
6563
|
const opLatency = new Trend('loadam_op_latency', true);
|
|
5398
6564
|
const opStatus = new Counter('loadam_op_status');
|
|
6565
|
+
// Authenticated requests the API still rejected (after one retry with fresh credentials).
|
|
6566
|
+
const authRejected = new Counter('loadam_auth_rejected');
|
|
5399
6567
|
|
|
5400
6568
|
function __statusBucket(s) {
|
|
5401
6569
|
if (s < 200) return '1xx';
|
|
@@ -5562,6 +6730,7 @@ function pickPathParam(opId, name, state, kind, idx) {
|
|
|
5562
6730
|
return undefined;
|
|
5563
6731
|
}
|
|
5564
6732
|
|
|
6733
|
+
${emitPreflight(ctx)}
|
|
5565
6734
|
/**
|
|
5566
6735
|
* Run one flow iteration. \`state\` collects ids by ResourceKind (created ones,
|
|
5567
6736
|
* plus ids seen in list responses under '~Kind') so later ops use real ids.
|
|
@@ -5573,8 +6742,8 @@ ${lines.join("\n")}
|
|
|
5573
6742
|
}
|
|
5574
6743
|
`;
|
|
5575
6744
|
}
|
|
5576
|
-
function emitOpCall(ir, op) {
|
|
5577
|
-
const headersExpr = "Object.assign({},
|
|
6745
|
+
function emitOpCall(ir, op, sets) {
|
|
6746
|
+
const headersExpr = "Object.assign({}, __a.headers)";
|
|
5578
6747
|
const opIdLit = JSON.stringify(op.id);
|
|
5579
6748
|
const pathParamLines = [];
|
|
5580
6749
|
let pathParamObj = "undefined";
|
|
@@ -5599,12 +6768,18 @@ function emitOpCall(ir, op) {
|
|
|
5599
6768
|
queryParamObj = `{ ${entries} }`;
|
|
5600
6769
|
}
|
|
5601
6770
|
const requestLine = emitRequestCall(ir, op, headersExpr, pathParamObj, queryParamObj);
|
|
6771
|
+
const send = sets.length > 0 ? ` const __sets = ${JSON.stringify(sets)};
|
|
6772
|
+
const __send = function (__a) { return ${requestLine}; };
|
|
6773
|
+
let resp = __send(authFor(__sets));
|
|
6774
|
+
if (resp.status === 401 && renewAuth(authFor(__sets).ids)) resp = __send(authFor(__sets));
|
|
6775
|
+
if (resp.status === 401 || resp.status === 403) authRejected.add(1, { name: ${opIdLit}, status: String(resp.status) });` : ` const __a = { headers: {}, query: {} };
|
|
6776
|
+
const resp = ${requestLine};`;
|
|
5602
6777
|
const kindLit = op.resourceKind ? JSON.stringify(op.resourceKind) : void 0;
|
|
5603
6778
|
const captureId = kindLit && op.resourceAction === "create" ? ` __captureCreated(state, ${kindLit}, resp);` : kindLit && op.resourceAction === "list" ? ` __captureListed(state, ${kindLit}, resp);` : "";
|
|
5604
6779
|
return ` // ${op.method} ${op.path} \u2014 ${op.id}
|
|
5605
6780
|
{
|
|
5606
6781
|
${pathParamLines.join("\n")}
|
|
5607
|
-
|
|
6782
|
+
${send}
|
|
5608
6783
|
check(resp, { ${JSON.stringify(`${op.id} 2xx-3xx`)}: (r) => r.status >= 200 && r.status < 400 });
|
|
5609
6784
|
opLatency.add(resp.timings.duration, { name: ${opIdLit} });
|
|
5610
6785
|
opStatus.add(1, { name: ${opIdLit}, bucket: __statusBucket(resp.status) });
|
|
@@ -5637,7 +6812,7 @@ function encodeBody(ir, op, headersExpr) {
|
|
|
5637
6812
|
return { bodyExpr: "'loadam test bytes'", headersWithCT: withCT };
|
|
5638
6813
|
}
|
|
5639
6814
|
function emitRequestCall(ir, op, headersExpr, pathParamObj, queryParamObj) {
|
|
5640
|
-
const url = `buildUrl(${JSON.stringify(op.path)}, ${pathParamObj}, ${queryParamObj})`;
|
|
6815
|
+
const url = `buildUrl(${JSON.stringify(op.path)}, ${pathParamObj}, ${queryParamObj}, __a.query)`;
|
|
5641
6816
|
const method = op.method.toLowerCase();
|
|
5642
6817
|
const hasBody = !!op.body;
|
|
5643
6818
|
const opIdLit = JSON.stringify(op.id);
|
|
@@ -5650,12 +6825,44 @@ function emitRequestCall(ir, op, headersExpr, pathParamObj, queryParamObj) {
|
|
|
5650
6825
|
}
|
|
5651
6826
|
return `http.${method}(${url}, ${bodyExpr}, { headers: ${headersWithCT}, tags: { name: ${opIdLit} } })`;
|
|
5652
6827
|
}
|
|
6828
|
+
function emitPreflight(ctx) {
|
|
6829
|
+
const probe = pickPreflightOp(ctx);
|
|
6830
|
+
const envList = ctx.auth.envVars.length ? ctx.auth.envVars.join(", ") : "your credentials";
|
|
6831
|
+
const probeCode = probe ? `
|
|
6832
|
+
const a = authFor(${JSON.stringify(probe.sets)});
|
|
6833
|
+
const res = http.get(buildUrl(${JSON.stringify(probe.op.path)}, undefined, undefined, a.query), { headers: a.headers, tags: { name: '__preflight' } });
|
|
6834
|
+
if (res.status === 401) {
|
|
6835
|
+
exec.test.abort('loadam: auth check failed: GET ${probe.op.path} returned 401. Check ${envList}.');
|
|
6836
|
+
}
|
|
6837
|
+
if (res.status === 403) {
|
|
6838
|
+
console.warn('loadam: auth check: GET ${probe.op.path} returned 403. The credentials work but may lack permissions.');
|
|
6839
|
+
}` : "";
|
|
6840
|
+
return `
|
|
6841
|
+
/** Abort before the test starts if the credentials are rejected. */
|
|
6842
|
+
export function preflight() {
|
|
6843
|
+
if (typeof __ENV !== 'undefined' && __ENV.LOADAM_PREFLIGHT === '0') return;
|
|
6844
|
+
const failed = checkLogins();
|
|
6845
|
+
if (failed.length > 0) {
|
|
6846
|
+
exec.test.abort('loadam: auth check failed: ' + failed.join('; ') + '. Check ${envList}.');
|
|
6847
|
+
}${probeCode}
|
|
6848
|
+
}
|
|
6849
|
+
`;
|
|
6850
|
+
}
|
|
6851
|
+
function pickPreflightOp(ctx) {
|
|
6852
|
+
const candidates = ctx.ir.operations.filter(
|
|
6853
|
+
(o) => o.method === "GET" && o.pathParams.length === 0 && !o.queryParams.some((p) => p.required) && !o.headerParams.some((p) => p.required)
|
|
6854
|
+
).map((op) => ({ op, sets: ctx.auth.setsFor(op) })).filter((c) => c.sets.length > 0 && c.sets[0].length > 0);
|
|
6855
|
+
candidates.sort(
|
|
6856
|
+
(a, b) => Number(b.op.resourceAction === "list") - Number(a.op.resourceAction === "list") || a.op.path.length - b.op.path.length
|
|
6857
|
+
);
|
|
6858
|
+
return candidates[0] ?? null;
|
|
6859
|
+
}
|
|
5653
6860
|
function safeIdent(s) {
|
|
5654
6861
|
return s.replace(/[^A-Za-z0-9_]/g, "_");
|
|
5655
6862
|
}
|
|
5656
6863
|
function emitSmokeJs(ctx) {
|
|
5657
6864
|
return `// AUTO-GENERATED by @loadam/test-k6 \u2014 smoke test
|
|
5658
|
-
import { runFlow } from './flow.js';
|
|
6865
|
+
import { preflight, runFlow } from './flow.js';
|
|
5659
6866
|
|
|
5660
6867
|
export const options = {
|
|
5661
6868
|
vus: 1,
|
|
@@ -5667,6 +6874,10 @@ export const options = {
|
|
|
5667
6874
|
${emitOpThresholds(ctx)} },
|
|
5668
6875
|
};
|
|
5669
6876
|
|
|
6877
|
+
export function setup() {
|
|
6878
|
+
preflight();
|
|
6879
|
+
}
|
|
6880
|
+
|
|
5670
6881
|
export default function () {
|
|
5671
6882
|
runFlow(0);
|
|
5672
6883
|
}
|
|
@@ -5674,7 +6885,7 @@ export default function () {
|
|
|
5674
6885
|
}
|
|
5675
6886
|
function emitLoadJs(ctx) {
|
|
5676
6887
|
return `// AUTO-GENERATED by @loadam/test-k6 \u2014 load test
|
|
5677
|
-
import { runFlow } from './flow.js';
|
|
6888
|
+
import { preflight, runFlow } from './flow.js';
|
|
5678
6889
|
|
|
5679
6890
|
export const options = {
|
|
5680
6891
|
stages: [
|
|
@@ -5689,6 +6900,10 @@ export const options = {
|
|
|
5689
6900
|
${emitOpThresholds(ctx)} },
|
|
5690
6901
|
};
|
|
5691
6902
|
|
|
6903
|
+
export function setup() {
|
|
6904
|
+
preflight();
|
|
6905
|
+
}
|
|
6906
|
+
|
|
5692
6907
|
export default function () {
|
|
5693
6908
|
runFlow(__ITER);
|
|
5694
6909
|
}
|
|
@@ -5738,6 +6953,20 @@ function emitEnvExample3(ctx) {
|
|
|
5738
6953
|
return `${lines.join("\n")}
|
|
5739
6954
|
`;
|
|
5740
6955
|
}
|
|
6956
|
+
function emitGitignore() {
|
|
6957
|
+
return ".env\nusers.csv\n";
|
|
6958
|
+
}
|
|
6959
|
+
function authSection(ctx) {
|
|
6960
|
+
if (ctx.auth.envVars.length === 0 && !ctx.auth.renewable) return "";
|
|
6961
|
+
return `
|
|
6962
|
+
## Credentials
|
|
6963
|
+
|
|
6964
|
+
- Each request sends only the credentials its operation's \`security\` asks for. Public operations send none.
|
|
6965
|
+
- Before any load, \`setup()\` checks that the credentials work and stops the test if they are rejected. Set \`LOADAM_PREFLIGHT=0\` to skip the check.${ctx.auth.renewable ? "\n- Tokens are fetched per VU, fetched again shortly before they expire, and once more if the API answers 401 (counted in `loadam_auth_refreshes`)." : ""}
|
|
6966
|
+
- To give each VU its own user, add a \`users.csv\` here: a header row of env var names (for example \`${ctx.auth.envVars.join(",") || "API_TOKEN"}\`), then one user per row. VU 1 gets row 1, and rows are reused when there are more VUs than users. It is git-ignored.
|
|
6967
|
+
${ctx.auth.loginOps.length ? `- Login operations (${ctx.auth.loginOps.join(", ")}) and logout operations are not part of the measured flow.
|
|
6968
|
+
` : ""}`;
|
|
6969
|
+
}
|
|
5741
6970
|
function emitReadme3(ctx) {
|
|
5742
6971
|
const opCount = ctx.sequencedOps.length;
|
|
5743
6972
|
const notes = ctx.auth.notes.length ? `
|
|
@@ -5768,8 +6997,8 @@ k6 run load.js
|
|
|
5768
6997
|
- \`load.js\` \u2014 same flow under ramping load with SLO thresholds.
|
|
5769
6998
|
- \`flow.js\` \u2014 shared per-iteration flow used by both scripts.
|
|
5770
6999
|
- \`fixtures.json\` \u2014 pre-generated request bodies and path-param values (k6 cannot run npm modules).
|
|
5771
|
-
- \`config.js\` \u2014 base URL +
|
|
5772
|
-
${notes}
|
|
7000
|
+
- \`config.js\` \u2014 base URL + credentials for each request.
|
|
7001
|
+
${authSection(ctx)}${notes}
|
|
5773
7002
|
## Regenerating
|
|
5774
7003
|
|
|
5775
7004
|
Re-run \`loadam test\` to refresh. Regenerating overwrites these files, so commit
|
|
@@ -5781,8 +7010,9 @@ function slugify3(s) {
|
|
|
5781
7010
|
}
|
|
5782
7011
|
function compileK6(ir, opts = {}) {
|
|
5783
7012
|
const baseUrl = opts.baseUrl ?? defaultBaseUrl(ir);
|
|
5784
|
-
const sequencedOps = sequenceForSmoke(ir);
|
|
5785
7013
|
const auth = emitAuth2(ir);
|
|
7014
|
+
const skip = new Set(auth.loginOps);
|
|
7015
|
+
const sequencedOps = sequenceForSmoke(ir).filter((op) => !skip.has(op.id) && !isLogout(op));
|
|
5786
7016
|
const fixtures = buildFixturePool(ir, {
|
|
5787
7017
|
size: opts.fixtureSize,
|
|
5788
7018
|
seed: opts.seed
|
|
@@ -5796,14 +7026,19 @@ function compileK6(ir, opts = {}) {
|
|
|
5796
7026
|
"fixtures.json": emitFixturesJson(fixtures.byOperationId),
|
|
5797
7027
|
"package.json": emitPackageJson2(ctx),
|
|
5798
7028
|
".env.example": emitEnvExample3(ctx),
|
|
5799
|
-
"README.md": emitReadme3(ctx)
|
|
7029
|
+
"README.md": emitReadme3(ctx),
|
|
7030
|
+
".gitignore": emitGitignore()
|
|
5800
7031
|
};
|
|
5801
7032
|
return { files, fixtures, auth, baseUrl };
|
|
5802
7033
|
}
|
|
7034
|
+
var LOGOUT = /log-?out|sign-?out/i;
|
|
7035
|
+
function isLogout(op) {
|
|
7036
|
+
return op.method !== "GET" && (LOGOUT.test(op.id) || LOGOUT.test(op.path));
|
|
7037
|
+
}
|
|
5803
7038
|
|
|
5804
7039
|
// src/util/interactive.ts
|
|
5805
7040
|
import { chmod, readFile as readFile10, writeFile as writeFile7 } from "fs/promises";
|
|
5806
|
-
import { resolve as
|
|
7041
|
+
import { resolve as resolve14 } from "path";
|
|
5807
7042
|
import { confirm, password, select } from "@inquirer/prompts";
|
|
5808
7043
|
function isInteractive(noInteractiveFlag) {
|
|
5809
7044
|
if (noInteractiveFlag) return false;
|
|
@@ -5840,7 +7075,7 @@ async function confirmContinue(message) {
|
|
|
5840
7075
|
return await confirm({ message, default: true });
|
|
5841
7076
|
}
|
|
5842
7077
|
async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
|
|
5843
|
-
const path =
|
|
7078
|
+
const path = resolve14(dir, ".env");
|
|
5844
7079
|
const existing = await readEnvFile(path);
|
|
5845
7080
|
const written = [];
|
|
5846
7081
|
const preserved = [];
|
|
@@ -5886,6 +7121,9 @@ async function readEnvFile(path) {
|
|
|
5886
7121
|
|
|
5887
7122
|
// src/commands/test.ts
|
|
5888
7123
|
var VALID_MODES = ["smoke", "load", "both", "skip"];
|
|
7124
|
+
var K6_ABORTED = 108;
|
|
7125
|
+
var LOAD_VUS = 10;
|
|
7126
|
+
var LOAD_SECONDS = 75;
|
|
5889
7127
|
function registerTestCommand(program) {
|
|
5890
7128
|
program.command("test").description("Compile an OpenAPI spec into a runnable k6 test rig (smoke + load).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <dir>", "output directory for the generated rig", "./loadam-out/k6").option(
|
|
5891
7129
|
"--target <url>",
|
|
@@ -5893,18 +7131,22 @@ function registerTestCommand(program) {
|
|
|
5893
7131
|
).option("--fixture-size <n>", "number of fixtures per slot", "10").option("--seed <n>", "deterministic seed for fixture generation", "1").option(
|
|
5894
7132
|
"--mode <mode>",
|
|
5895
7133
|
"run after generating: smoke | load | both | skip (default: prompt if interactive, skip otherwise)"
|
|
5896
|
-
).option("--no-interactive", "disable all prompts (CI mode)", false).option("--config <path>", CONFIG_OPTION_HELP).option(
|
|
7134
|
+
).option("--no-interactive", "disable all prompts (CI mode)", false).option("--config <path>", CONFIG_OPTION_HELP).option(
|
|
7135
|
+
"--users <csv>",
|
|
7136
|
+
"one user per VU: a CSV whose header row names env vars (e.g. API_USER,API_PASS)"
|
|
7137
|
+
).option("--no-preflight", "skip the auth check k6 runs before sending load").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runTest));
|
|
5897
7138
|
}
|
|
5898
7139
|
async function runTest(spec, opts) {
|
|
5899
7140
|
const out = makeOutput(!!opts.json);
|
|
5900
|
-
const specPath =
|
|
7141
|
+
const specPath = resolve15(spec);
|
|
5901
7142
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
5902
7143
|
const specSource = await readFile11(specPath, "utf8");
|
|
5903
7144
|
const ir = await fromOpenApiFile(specPath);
|
|
5904
7145
|
inferResourceGraph(ir);
|
|
5905
|
-
await applyUserConfig(ir, specPath, opts.config);
|
|
7146
|
+
const loaded = await applyUserConfig(ir, specPath, opts.config);
|
|
5906
7147
|
parseIR(ir);
|
|
5907
7148
|
out.success(`Parsed ${ir.operations.length} operation${ir.operations.length === 1 ? "" : "s"}`);
|
|
7149
|
+
reportLogin(ir, out);
|
|
5908
7150
|
const fixtureSize = Number.parseInt(opts.fixtureSize ?? "10", 10);
|
|
5909
7151
|
const seed = Number.parseInt(opts.seed ?? "1", 10);
|
|
5910
7152
|
const target = resolveTarget(opts.target);
|
|
@@ -5916,13 +7158,21 @@ async function runTest(spec, opts) {
|
|
|
5916
7158
|
fixtureSize: Number.isFinite(fixtureSize) ? fixtureSize : 10,
|
|
5917
7159
|
seed: Number.isFinite(seed) ? seed : 1
|
|
5918
7160
|
});
|
|
5919
|
-
const outDir =
|
|
7161
|
+
const outDir = resolve15(opts.output);
|
|
5920
7162
|
await mkdir4(outDir, { recursive: true });
|
|
5921
7163
|
for (const [rel, contents] of Object.entries(result.files)) {
|
|
5922
|
-
const full =
|
|
7164
|
+
const full = resolve15(outDir, rel);
|
|
5923
7165
|
await mkdir4(dirname4(full), { recursive: true });
|
|
5924
7166
|
await writeFile8(full, contents, "utf8");
|
|
5925
7167
|
}
|
|
7168
|
+
const usersSrc = opts.users !== void 0 ? resolve15(opts.users) : loaded?.config.auth?.users ? resolve15(dirname4(loaded.path), loaded.config.auth.users) : void 0;
|
|
7169
|
+
let users = 0;
|
|
7170
|
+
if (usersSrc) {
|
|
7171
|
+
users = await installUsers(usersSrc, outDir);
|
|
7172
|
+
out.info(
|
|
7173
|
+
` Users: ${users} from ${usersSrc}${users < LOAD_VUS ? ` (load.js peaks at ${LOAD_VUS} VUs, so some VUs share a user)` : ""}`
|
|
7174
|
+
);
|
|
7175
|
+
}
|
|
5926
7176
|
const fileCount = Object.keys(result.files).length;
|
|
5927
7177
|
const fixtureCount = Object.keys(result.fixtures.byOperationId).length;
|
|
5928
7178
|
out.success(`Wrote ${fileCount} files to ${outDir}`);
|
|
@@ -5983,7 +7233,14 @@ async function runTest(spec, opts) {
|
|
|
5983
7233
|
});
|
|
5984
7234
|
if (!out.json) out.info(` Session: ${session.id}`);
|
|
5985
7235
|
if (mode !== "skip") {
|
|
5986
|
-
runResult = await maybeRunWithSession({
|
|
7236
|
+
runResult = await maybeRunWithSession({
|
|
7237
|
+
mode,
|
|
7238
|
+
cwd: outDir,
|
|
7239
|
+
out,
|
|
7240
|
+
session,
|
|
7241
|
+
interactive,
|
|
7242
|
+
preflight: opts.preflight !== false
|
|
7243
|
+
});
|
|
5987
7244
|
} else if (!interactive && !out.json) {
|
|
5988
7245
|
out.step("");
|
|
5989
7246
|
out.step("Next steps:");
|
|
@@ -6016,11 +7273,71 @@ async function runTest(spec, opts) {
|
|
|
6016
7273
|
sessionId: session.id
|
|
6017
7274
|
});
|
|
6018
7275
|
if (runResult) {
|
|
6019
|
-
if (runResult.smokeExit
|
|
7276
|
+
if (runResult.smokeExit === K6_ABORTED || runResult.loadExit === K6_ABORTED) {
|
|
7277
|
+
process.exitCode = 2;
|
|
7278
|
+
} else if (runResult.smokeExit && runResult.smokeExit !== 0 || runResult.loadExit && runResult.loadExit !== 0) {
|
|
6020
7279
|
process.exitCode = 1;
|
|
6021
7280
|
}
|
|
6022
7281
|
}
|
|
6023
7282
|
}
|
|
7283
|
+
function reportLogin(ir, out) {
|
|
7284
|
+
const login2 = ir.auth.find((p) => p.kind === "login");
|
|
7285
|
+
if (login2) {
|
|
7286
|
+
const op = ir.operations.find((o) => o.id === login2.operationId);
|
|
7287
|
+
const how = login2.source === "config" ? "from loadam.config.json" : "detected in the spec";
|
|
7288
|
+
out.info(
|
|
7289
|
+
` Login: each VU logs in via ${op ? `${op.method} ${op.path}` : login2.operationId} (${how}) and renews its token.`
|
|
7290
|
+
);
|
|
7291
|
+
return;
|
|
7292
|
+
}
|
|
7293
|
+
const hint = ir.hints.login;
|
|
7294
|
+
if (!hint?.candidates?.length) return;
|
|
7295
|
+
out.info(
|
|
7296
|
+
` Possible login operation(s): ${hint.candidates.join(", ")}, not used: ${hint.reason}.`
|
|
7297
|
+
);
|
|
7298
|
+
out.info(
|
|
7299
|
+
` To log in for tokens, add to loadam.config.json: { "auth": { "login": { "operation": "${hint.candidates[0]}", "body": { "email": "\${API_USER}", "password": "\${API_PASS}" }, "token": "token" } } }`
|
|
7300
|
+
);
|
|
7301
|
+
}
|
|
7302
|
+
async function installUsers(src, outDir) {
|
|
7303
|
+
let text;
|
|
7304
|
+
try {
|
|
7305
|
+
text = await readFile11(src, "utf8");
|
|
7306
|
+
} catch {
|
|
7307
|
+
throw new Error(`--users: cannot read ${src}`);
|
|
7308
|
+
}
|
|
7309
|
+
const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");
|
|
7310
|
+
if (lines.length < 2)
|
|
7311
|
+
throw new Error(`--users: ${src} needs a header row of env var names and at least one user`);
|
|
7312
|
+
const header = lines[0].split(",").map((h) => h.trim());
|
|
7313
|
+
const bad = header.find((h) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(h));
|
|
7314
|
+
if (bad !== void 0)
|
|
7315
|
+
throw new Error(`--users: header "${bad}" is not an env var name (e.g. API_USER,API_PASS)`);
|
|
7316
|
+
await copyFile(src, join7(outDir, "users.csv"));
|
|
7317
|
+
return lines.length - 1;
|
|
7318
|
+
}
|
|
7319
|
+
function jwtSecondsLeft(token, now = Date.now()) {
|
|
7320
|
+
const parts = token.split(".");
|
|
7321
|
+
if (parts.length !== 3) return void 0;
|
|
7322
|
+
try {
|
|
7323
|
+
const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
7324
|
+
return typeof claims.exp === "number" ? Math.round(claims.exp - now / 1e3) : void 0;
|
|
7325
|
+
} catch {
|
|
7326
|
+
return void 0;
|
|
7327
|
+
}
|
|
7328
|
+
}
|
|
7329
|
+
function warnExpiringTokens(env, mode, out) {
|
|
7330
|
+
if (out.json) return;
|
|
7331
|
+
const needed = mode === "smoke" ? 30 : LOAD_SECONDS + 30;
|
|
7332
|
+
for (const [name, value] of Object.entries(env)) {
|
|
7333
|
+
if (!value || !/TOKEN|JWT|KEY/i.test(name)) continue;
|
|
7334
|
+
const left = jwtSecondsLeft(value);
|
|
7335
|
+
if (left === void 0 || left >= needed) continue;
|
|
7336
|
+
out.info(
|
|
7337
|
+
left <= 0 ? ` ${name} is a JWT that has already expired. Requests using it will get 401s.` : ` ${name} is a JWT that expires in ${left}s, before the run ends. Use a login in loadam.config.json ("auth.login") so loadam can renew it.`
|
|
7338
|
+
);
|
|
7339
|
+
}
|
|
7340
|
+
}
|
|
6024
7341
|
function parseModeFlag(raw) {
|
|
6025
7342
|
if (!raw) return null;
|
|
6026
7343
|
if (!VALID_MODES.includes(raw)) {
|
|
@@ -6029,7 +7346,7 @@ function parseModeFlag(raw) {
|
|
|
6029
7346
|
return raw;
|
|
6030
7347
|
}
|
|
6031
7348
|
function getSessionRoot(outDir) {
|
|
6032
|
-
return
|
|
7349
|
+
return resolve15(outDir, "..");
|
|
6033
7350
|
}
|
|
6034
7351
|
async function fileExists(p) {
|
|
6035
7352
|
try {
|
|
@@ -6040,7 +7357,7 @@ async function fileExists(p) {
|
|
|
6040
7357
|
}
|
|
6041
7358
|
}
|
|
6042
7359
|
async function maybeRunWithSession(input) {
|
|
6043
|
-
const { mode, cwd, out, session, interactive } = input;
|
|
7360
|
+
const { mode, cwd, out, session, interactive, preflight } = input;
|
|
6044
7361
|
if (mode === "skip") return { mode };
|
|
6045
7362
|
const bin = await findK6Binary();
|
|
6046
7363
|
if (!bin) {
|
|
@@ -6059,7 +7376,25 @@ async function maybeRunWithSession(input) {
|
|
|
6059
7376
|
const allFailed = [];
|
|
6060
7377
|
const summary = {};
|
|
6061
7378
|
const env = envForRun(await readEnvFile(join7(cwd, ".env")));
|
|
7379
|
+
if (!preflight) env.LOADAM_PREFLIGHT = "0";
|
|
6062
7380
|
const stdout = out.json ? "stderr" : "inherit";
|
|
7381
|
+
warnExpiringTokens({ ...process.env, ...env }, mode, out);
|
|
7382
|
+
const aborted = async (exit) => {
|
|
7383
|
+
if (exit !== K6_ABORTED) return false;
|
|
7384
|
+
summary.authPreflight = "failed";
|
|
7385
|
+
if (!out.json) {
|
|
7386
|
+
out.step("");
|
|
7387
|
+
out.info(
|
|
7388
|
+
"The auth check failed before any load was sent (see the k6 message above). Fix the credentials, or pass --no-preflight to skip the check."
|
|
7389
|
+
);
|
|
7390
|
+
}
|
|
7391
|
+
await session.finalize({
|
|
7392
|
+
exitCode: 2,
|
|
7393
|
+
thresholds: { passed: allPassed, failed: allFailed },
|
|
7394
|
+
summary
|
|
7395
|
+
});
|
|
7396
|
+
return true;
|
|
7397
|
+
};
|
|
6063
7398
|
if (mode === "smoke" || mode === "both") {
|
|
6064
7399
|
if (!out.json) {
|
|
6065
7400
|
out.step("");
|
|
@@ -6067,6 +7402,7 @@ async function maybeRunWithSession(input) {
|
|
|
6067
7402
|
}
|
|
6068
7403
|
const summaryPath = join7(session.dir, "k6-smoke-summary.json");
|
|
6069
7404
|
result.smokeExit = await runK6({ cwd, script: "smoke.js", summaryPath, env, stdout });
|
|
7405
|
+
if (await aborted(result.smokeExit)) return result;
|
|
6070
7406
|
if (await fileExists(summaryPath)) session.registerArtefact("k6-smoke-summary.json");
|
|
6071
7407
|
const digest = await digestK6Summary(summaryPath);
|
|
6072
7408
|
if (digest) {
|
|
@@ -6098,6 +7434,7 @@ async function maybeRunWithSession(input) {
|
|
|
6098
7434
|
}
|
|
6099
7435
|
const summaryPath = join7(session.dir, "k6-load-summary.json");
|
|
6100
7436
|
result.loadExit = await runK6({ cwd, script: "load.js", summaryPath, env, stdout });
|
|
7437
|
+
if (await aborted(result.loadExit)) return result;
|
|
6101
7438
|
if (await fileExists(summaryPath)) session.registerArtefact("k6-load-summary.json");
|
|
6102
7439
|
const digest = await digestK6Summary(summaryPath);
|
|
6103
7440
|
if (digest) {
|
|
@@ -6211,7 +7548,7 @@ ${dim}${TAGLINE}${reset}
|
|
|
6211
7548
|
}
|
|
6212
7549
|
|
|
6213
7550
|
// src/program.ts
|
|
6214
|
-
var VERSION2 = true ? "0.
|
|
7551
|
+
var VERSION2 = true ? "0.4.0" : "0.0.0";
|
|
6215
7552
|
function buildProgram() {
|
|
6216
7553
|
const program = new Command();
|
|
6217
7554
|
program.name("loadam").description(
|