@softprobe/e2e 0.0.0-stage → 0.2.1

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.
Files changed (54) hide show
  1. package/README.md +81 -2
  2. package/dist/bin/compile-session.d.ts +13 -0
  3. package/dist/bin/compile-session.d.ts.map +1 -0
  4. package/dist/bin/compile-session.js +187 -0
  5. package/dist/bin/compile-session.js.map +1 -0
  6. package/dist/fixtures.d.ts +29 -0
  7. package/dist/fixtures.d.ts.map +1 -0
  8. package/dist/fixtures.js +211 -0
  9. package/dist/fixtures.js.map +1 -0
  10. package/dist/index.d.ts +6 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +6 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/internal/arex-sink.d.ts +20 -0
  15. package/dist/internal/arex-sink.d.ts.map +1 -0
  16. package/dist/internal/arex-sink.js +223 -0
  17. package/dist/internal/arex-sink.js.map +1 -0
  18. package/dist/internal/blackbox-sink.d.ts +19 -0
  19. package/dist/internal/blackbox-sink.d.ts.map +1 -0
  20. package/dist/internal/blackbox-sink.js +607 -0
  21. package/dist/internal/blackbox-sink.js.map +1 -0
  22. package/dist/internal/config.d.ts +52 -0
  23. package/dist/internal/config.d.ts.map +1 -0
  24. package/dist/internal/config.js +319 -0
  25. package/dist/internal/config.js.map +1 -0
  26. package/dist/internal/correlator.d.ts +48 -0
  27. package/dist/internal/correlator.d.ts.map +1 -0
  28. package/dist/internal/correlator.js +268 -0
  29. package/dist/internal/correlator.js.map +1 -0
  30. package/dist/internal/poller.d.ts +29 -0
  31. package/dist/internal/poller.d.ts.map +1 -0
  32. package/dist/internal/poller.js +270 -0
  33. package/dist/internal/poller.js.map +1 -0
  34. package/dist/internal/reporter.d.ts +44 -0
  35. package/dist/internal/reporter.d.ts.map +1 -0
  36. package/dist/internal/reporter.js +249 -0
  37. package/dist/internal/reporter.js.map +1 -0
  38. package/dist/internal/sink-shared.d.ts +41 -0
  39. package/dist/internal/sink-shared.d.ts.map +1 -0
  40. package/dist/internal/sink-shared.js +98 -0
  41. package/dist/internal/sink-shared.js.map +1 -0
  42. package/dist/playwright.d.ts +60 -0
  43. package/dist/playwright.d.ts.map +1 -0
  44. package/dist/playwright.js +396 -0
  45. package/dist/playwright.js.map +1 -0
  46. package/dist/session-compiler.d.ts +304 -0
  47. package/dist/session-compiler.d.ts.map +1 -0
  48. package/dist/session-compiler.js +2277 -0
  49. package/dist/session-compiler.js.map +1 -0
  50. package/dist/types.d.ts +127 -0
  51. package/dist/types.d.ts.map +1 -0
  52. package/dist/types.js +58 -0
  53. package/dist/types.js.map +1 -0
  54. package/package.json +83 -4
@@ -0,0 +1,2277 @@
1
+ import { createHash } from "node:crypto";
2
+ import { AgentError } from "e2e";
3
+ import { z } from "zod";
4
+ import { parseBlackboxTracePayload } from "./internal/blackbox-sink.js";
5
+ import { formatAuthHeader, isJsonValue, parseJsonBodyValue, SinkHttpError, stripSpJsonPrefix, } from "./internal/sink-shared.js";
6
+ import { isSpanId, isTraceId, } from "./types.js";
7
+ export const UI_ACTION_SCHEMA_VERSION = "sp-ui-action-1";
8
+ export const E2E_TRACE_SCHEMA_VERSION = "trace-1";
9
+ export const E2E_REPLAY_POLICY_VERSION = "conservative/6";
10
+ export const E2E_ENGINE_SPI_VERSION = 1;
11
+ const capturedInputValueSchema = z.discriminatedUnion("kind", [
12
+ z.object({ kind: z.literal("literal"), value: z.string() }),
13
+ z.object({ kind: z.literal("secret"), slot: z.string().min(1) }),
14
+ z.object({ kind: z.literal("redacted"), length: z.number().int().nonnegative() }),
15
+ ]);
16
+ const modifierKeySchema = z.enum(["Alt", "Control", "Meta", "Shift"]);
17
+ const anchorStateSchema = z.enum(["checked", "expanded", "pressed", "selected"]);
18
+ export const semanticTargetSchema = z.object({
19
+ testId: z.string().optional(),
20
+ role: z.string().optional(),
21
+ name: z.string().optional(),
22
+ label: z.string().optional(),
23
+ placeholder: z.string().optional(),
24
+ text: z.string().optional(),
25
+ inputPurpose: z.string().optional(),
26
+ cssSelector: z.string().optional(),
27
+ within: z.string().optional(),
28
+ position: z
29
+ .object({
30
+ index: z.number().int().nonnegative(),
31
+ of: z.number().int().positive(),
32
+ })
33
+ .optional(),
34
+ rect: z
35
+ .object({
36
+ x: z.number(),
37
+ y: z.number(),
38
+ width: z.number(),
39
+ height: z.number(),
40
+ })
41
+ .optional(),
42
+ pointOffset: z
43
+ .object({
44
+ fx: z.number(),
45
+ fy: z.number(),
46
+ })
47
+ .optional(),
48
+ framePath: z.array(z.string()).optional(),
49
+ rrwebNodeId: z.number().int().nonnegative().optional(),
50
+ states: z.array(anchorStateSchema).optional(),
51
+ value: z.string().optional(),
52
+ });
53
+ export const causedHttpTraceSchema = z.object({
54
+ traceId: z.string().min(1),
55
+ spanId: z.string().optional(),
56
+ method: z.string().min(1),
57
+ url: z.string().min(1),
58
+ urlTemplate: z.string().optional(),
59
+ status: z.number().int().optional(),
60
+ });
61
+ export const semanticVerbSchema = z.discriminatedUnion("name", [
62
+ z.object({
63
+ name: z.literal("navigate"),
64
+ url: z.string().min(1),
65
+ trigger: z.enum(["load", "pushState", "popstate"]),
66
+ }),
67
+ z.object({
68
+ name: z.literal("click"),
69
+ target: semanticTargetSchema,
70
+ modifiers: z.array(modifierKeySchema).optional(),
71
+ point: z.object({ x: z.number(), y: z.number() }),
72
+ }),
73
+ z.object({
74
+ name: z.literal("dblclick"),
75
+ target: semanticTargetSchema,
76
+ modifiers: z.array(modifierKeySchema).optional(),
77
+ point: z.object({ x: z.number(), y: z.number() }),
78
+ }),
79
+ z.object({
80
+ name: z.literal("contextmenu"),
81
+ target: semanticTargetSchema,
82
+ modifiers: z.array(modifierKeySchema).optional(),
83
+ point: z.object({ x: z.number(), y: z.number() }),
84
+ }),
85
+ z.object({
86
+ name: z.literal("hover"),
87
+ target: semanticTargetSchema,
88
+ modifiers: z.array(modifierKeySchema).optional(),
89
+ point: z.object({ x: z.number(), y: z.number() }),
90
+ }),
91
+ z.object({
92
+ name: z.literal("fill"),
93
+ target: semanticTargetSchema,
94
+ value: capturedInputValueSchema,
95
+ replace: z.boolean(),
96
+ }),
97
+ z.object({
98
+ name: z.literal("select"),
99
+ target: semanticTargetSchema,
100
+ value: capturedInputValueSchema,
101
+ optionLabel: z.string().optional(),
102
+ }),
103
+ z.object({
104
+ name: z.literal("check"),
105
+ target: semanticTargetSchema,
106
+ checked: z.boolean(),
107
+ }),
108
+ z.object({
109
+ name: z.literal("press"),
110
+ target: semanticTargetSchema.optional(),
111
+ key: z.string().min(1),
112
+ modifiers: z.array(modifierKeySchema).optional(),
113
+ }),
114
+ z.object({
115
+ name: z.literal("upload"),
116
+ target: semanticTargetSchema,
117
+ fileNames: z.array(z.string()),
118
+ mimeTypes: z.array(z.string()),
119
+ }),
120
+ z.object({
121
+ name: z.literal("drag"),
122
+ source: semanticTargetSchema,
123
+ destination: semanticTargetSchema,
124
+ }),
125
+ z.object({
126
+ name: z.literal("scroll"),
127
+ target: semanticTargetSchema.optional(),
128
+ direction: z.enum(["up", "down", "left", "right"]),
129
+ times: z.number().int().positive(),
130
+ spansViewport: z.number(),
131
+ }),
132
+ z.object({
133
+ name: z.literal("dialog"),
134
+ dialogType: z.enum(["alert", "confirm", "prompt", "beforeunload"]),
135
+ accepted: z.boolean(),
136
+ promptText: capturedInputValueSchema.optional(),
137
+ }),
138
+ z.object({
139
+ name: z.literal("resize"),
140
+ viewport: z.object({
141
+ width: z.number().int().positive(),
142
+ height: z.number().int().positive(),
143
+ }),
144
+ }),
145
+ ]);
146
+ export const recordedSemanticActionSchema = z.object({
147
+ schemaVersion: z.literal(UI_ACTION_SCHEMA_VERSION),
148
+ actionIndex: z.number().int().nonnegative(),
149
+ timestampMs: z.number(),
150
+ startPath: z.string(),
151
+ endPath: z.string(),
152
+ viewport: z.object({
153
+ width: z.number().int().positive(),
154
+ height: z.number().int().positive(),
155
+ }),
156
+ verb: semanticVerbSchema,
157
+ causedTraces: z.array(causedHttpTraceSchema),
158
+ endAnchors: z.array(semanticTargetSchema),
159
+ goneAnchors: z.array(semanticTargetSchema),
160
+ settleMs: z.number().nonnegative(),
161
+ });
162
+ const rawKeyValueSchema = z.object({
163
+ key: z.string(),
164
+ value: z.unknown().optional(),
165
+ });
166
+ const rawAnyValueSchema = z.object({
167
+ stringValue: z.string().optional(),
168
+ intValue: z.union([z.string(), z.number()]).optional(),
169
+ doubleValue: z.number().optional(),
170
+ boolValue: z.boolean().optional(),
171
+ arrayValue: z.object({ values: z.array(z.unknown()).optional() }).optional(),
172
+ kvlistValue: z.object({ values: z.array(z.unknown()).optional() }).optional(),
173
+ });
174
+ const rawSpanObjectSchema = z.object({
175
+ traceId: z.unknown().optional(),
176
+ trace_id: z.unknown().optional(),
177
+ spanId: z.unknown().optional(),
178
+ span_id: z.unknown().optional(),
179
+ parentSpanId: z.unknown().optional(),
180
+ parent_span_id: z.unknown().optional(),
181
+ session_id: z.string().nullable().optional(),
182
+ name: z.string().optional(),
183
+ kind: z.unknown().optional(),
184
+ span_kind: z.unknown().optional(),
185
+ span_type: z.string().optional(),
186
+ observation_type: z.string().optional(),
187
+ service_name: z.string().nullable().optional(),
188
+ startTimeUnixNano: z.union([z.string(), z.number()]).optional(),
189
+ endTimeUnixNano: z.union([z.string(), z.number()]).optional(),
190
+ start_time: z.string().optional(),
191
+ end_time: z.string().nullable().optional(),
192
+ attributes: z.union([z.array(z.unknown()), z.record(z.string(), z.unknown())]).optional(),
193
+ resource_attributes: z
194
+ .union([z.array(z.unknown()), z.record(z.string(), z.unknown())])
195
+ .optional(),
196
+ events: z.array(z.unknown()).optional(),
197
+ });
198
+ const rawScopeSpansSchema = z.object({
199
+ spans: z.array(rawSpanObjectSchema).optional(),
200
+ });
201
+ const rawResourceSpansSchema = z.object({
202
+ resource: z
203
+ .object({
204
+ attributes: z.union([z.array(z.unknown()), z.record(z.string(), z.unknown())]).optional(),
205
+ })
206
+ .optional(),
207
+ scopeSpans: z.array(rawScopeSpansSchema).optional(),
208
+ instrumentationLibrarySpans: z.array(rawScopeSpansSchema).optional(),
209
+ });
210
+ const rawSessionInputEnvelopeSchema = z.object({
211
+ session_id: z.string().optional(),
212
+ sessionId: z.string().optional(),
213
+ spans: z.array(rawSpanObjectSchema).optional(),
214
+ observations: z.array(rawSpanObjectSchema).optional(),
215
+ resourceSpans: z.array(rawResourceSpansSchema).optional(),
216
+ batches: z.array(rawResourceSpansSchema).optional(),
217
+ trace: z
218
+ .object({
219
+ resourceSpans: z.array(rawResourceSpansSchema).optional(),
220
+ })
221
+ .optional(),
222
+ traces: z.record(z.string(), z.unknown()).optional(),
223
+ tracesByTraceId: z.record(z.string(), z.unknown()).optional(),
224
+ });
225
+ function decodeHexId(raw, byteLen) {
226
+ if (typeof raw !== "string")
227
+ return "";
228
+ const trimmed = raw.trim();
229
+ if (!trimmed)
230
+ return "";
231
+ if (trimmed.length === byteLen * 2 && /^[0-9a-fA-F]+$/.test(trimmed)) {
232
+ return trimmed.toLowerCase();
233
+ }
234
+ try {
235
+ const buf = Buffer.from(trimmed, "base64");
236
+ if (buf.length === byteLen)
237
+ return buf.toString("hex").toLowerCase();
238
+ }
239
+ catch { }
240
+ return "";
241
+ }
242
+ function stringifyAnyVal(raw) {
243
+ if (typeof raw === "string")
244
+ return raw;
245
+ if (typeof raw === "number" || typeof raw === "boolean")
246
+ return String(raw);
247
+ const parsed = rawAnyValueSchema.safeParse(raw);
248
+ if (!parsed.success) {
249
+ return isJsonValue(raw) ? JSON.stringify(raw) : "";
250
+ }
251
+ const v = parsed.data;
252
+ if (typeof v.stringValue === "string")
253
+ return v.stringValue;
254
+ if (typeof v.intValue === "string" || typeof v.intValue === "number")
255
+ return String(v.intValue);
256
+ if (typeof v.doubleValue === "number")
257
+ return String(v.doubleValue);
258
+ if (typeof v.boolValue === "boolean")
259
+ return String(v.boolValue);
260
+ if (Array.isArray(v.arrayValue?.values)) {
261
+ return JSON.stringify(v.arrayValue.values.map(stringifyAnyVal));
262
+ }
263
+ if (Array.isArray(v.kvlistValue?.values)) {
264
+ const out = {};
265
+ for (const item of v.kvlistValue.values) {
266
+ const kv = rawKeyValueSchema.safeParse(item);
267
+ if (kv.success)
268
+ out[kv.data.key] = stringifyAnyVal(kv.data.value);
269
+ }
270
+ return JSON.stringify(out);
271
+ }
272
+ return "";
273
+ }
274
+ function normalizeAttributes(raw) {
275
+ if (Array.isArray(raw)) {
276
+ const out = {};
277
+ for (const item of raw) {
278
+ const kv = rawKeyValueSchema.safeParse(item);
279
+ if (kv.success)
280
+ out[kv.data.key] = stringifyAnyVal(kv.data.value);
281
+ }
282
+ return out;
283
+ }
284
+ if (raw !== null && typeof raw === "object") {
285
+ const out = {};
286
+ for (const [k, v] of Object.entries(raw)) {
287
+ if (v !== undefined && v !== null)
288
+ out[k] = stringifyAnyVal(v);
289
+ }
290
+ return out;
291
+ }
292
+ return {};
293
+ }
294
+ function parseTimestampMs(nanoRaw, isoRaw) {
295
+ if (typeof nanoRaw === "number") {
296
+ if (Number.isFinite(nanoRaw) && nanoRaw > 0) {
297
+ return Math.trunc(nanoRaw / 1_000_000);
298
+ }
299
+ }
300
+ else if (typeof nanoRaw === "string") {
301
+ const trimmed = nanoRaw.trim();
302
+ if (/^\d+$/.test(trimmed)) {
303
+ try {
304
+ return Number(BigInt(trimmed) / 1000000n);
305
+ }
306
+ catch { }
307
+ }
308
+ else if (trimmed !== "") {
309
+ const parsedNum = Number(trimmed);
310
+ if (Number.isFinite(parsedNum) && parsedNum > 0) {
311
+ return Math.trunc(parsedNum / 1_000_000);
312
+ }
313
+ }
314
+ }
315
+ if (isoRaw) {
316
+ const parsed = Date.parse(isoRaw);
317
+ if (Number.isFinite(parsed))
318
+ return parsed;
319
+ }
320
+ return 0;
321
+ }
322
+ const TRIVIAL_RESPONSE_WORDS = new Set([
323
+ "true",
324
+ "false",
325
+ "null",
326
+ "ok",
327
+ "yes",
328
+ "no",
329
+ "idle",
330
+ "ready",
331
+ "done",
332
+ "error",
333
+ "success",
334
+ "pending",
335
+ "active",
336
+ "admin",
337
+ "user",
338
+ "member",
339
+ "usd",
340
+ "eur",
341
+ "gbp",
342
+ ]);
343
+ function isNonTrivialDynamicScalar(text) {
344
+ const trimmed = text.trim();
345
+ if (trimmed.length < 3 || trimmed.length > 120)
346
+ return false;
347
+ if (TRIVIAL_RESPONSE_WORDS.has(trimmed.toLowerCase()))
348
+ return false;
349
+ if (/\d/.test(trimmed))
350
+ return true;
351
+ return trimmed.length >= 6 && /[A-Za-z]/.test(trimmed) && /[A-Z0-9_-]/.test(trimmed);
352
+ }
353
+ function collectResponseJsonScalars(value, sink, depth = 0) {
354
+ if (value === undefined || value === null || depth > 8)
355
+ return;
356
+ if (typeof value === "string") {
357
+ if (isNonTrivialDynamicScalar(value)) {
358
+ sink.add(value.trim());
359
+ }
360
+ return;
361
+ }
362
+ if (typeof value === "number") {
363
+ const formatted = String(value);
364
+ if (formatted.length >= 3) {
365
+ sink.add(formatted);
366
+ }
367
+ if (!Number.isInteger(value)) {
368
+ const fixed2 = value.toFixed(2);
369
+ if (fixed2.length >= 4)
370
+ sink.add(fixed2);
371
+ }
372
+ return;
373
+ }
374
+ if (typeof value === "boolean")
375
+ return;
376
+ if (Array.isArray(value)) {
377
+ for (const item of value)
378
+ collectResponseJsonScalars(item, sink, depth + 1);
379
+ return;
380
+ }
381
+ for (const entry of Object.values(value)) {
382
+ collectResponseJsonScalars(entry, sink, depth + 1);
383
+ }
384
+ }
385
+ function escapeRegExpLiteral(value) {
386
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
387
+ }
388
+ function detectDynamicTextPattern(candidateText, priorScalarsByTrace) {
389
+ if (!candidateText || candidateText.trim().length < 4)
390
+ return undefined;
391
+ const matchedEntries = [];
392
+ for (const source of priorScalarsByTrace) {
393
+ for (const scalar of source.scalars) {
394
+ if (candidateText.length > scalar.length && candidateText.includes(scalar)) {
395
+ matchedEntries.push({ scalar, traceId: source.traceId });
396
+ }
397
+ }
398
+ }
399
+ if (matchedEntries.length === 0)
400
+ return undefined;
401
+ const uniqueScalars = [...new Set(matchedEntries.map((m) => m.scalar))].sort((a, b) => b.length - a.length);
402
+ const ranges = [];
403
+ for (const scalar of uniqueScalars) {
404
+ let fromIdx = 0;
405
+ while (fromIdx < candidateText.length) {
406
+ const found = candidateText.indexOf(scalar, fromIdx);
407
+ if (found === -1)
408
+ break;
409
+ const end = found + scalar.length;
410
+ const overlaps = ranges.some((r) => found < r.end && end > r.start);
411
+ if (!overlaps) {
412
+ ranges.push({ start: found, end, scalar });
413
+ }
414
+ fromIdx = end;
415
+ }
416
+ }
417
+ if (ranges.length === 0)
418
+ return undefined;
419
+ ranges.sort((a, b) => a.start - b.start);
420
+ let patternBody = "";
421
+ let cursor = 0;
422
+ for (const range of ranges) {
423
+ patternBody += escapeRegExpLiteral(candidateText.slice(cursor, range.start));
424
+ patternBody += ".*";
425
+ cursor = range.end;
426
+ }
427
+ patternBody += escapeRegExpLiteral(candidateText.slice(cursor));
428
+ return {
429
+ literal: candidateText,
430
+ patternSource: `^${patternBody}$`,
431
+ derivedFromTraceId: matchedEntries[0].traceId,
432
+ matchedScalars: ranges.map((r) => r.scalar),
433
+ };
434
+ }
435
+ const COLON_PARAM_SEGMENT_RE = /^:[A-Za-z_][A-Za-z0-9_]*$/;
436
+ const BRACE_PARAM_SEGMENT_RE = /^\{[^/}]+\}$/;
437
+ function extractRouteTemplatePathname(rawTemplate) {
438
+ const trimmed = rawTemplate.trim();
439
+ if (!trimmed)
440
+ return undefined;
441
+ let candidate = trimmed;
442
+ if (/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//.test(trimmed)) {
443
+ const schemeEnd = trimmed.indexOf("://") + 3;
444
+ const slashIdx = trimmed.indexOf("/", schemeEnd);
445
+ const queryOrHashIdx = trimmed.slice(schemeEnd).search(/[?#]/);
446
+ if (slashIdx >= 0 && (queryOrHashIdx === -1 || slashIdx < schemeEnd + queryOrHashIdx)) {
447
+ candidate = trimmed.slice(slashIdx);
448
+ }
449
+ else {
450
+ candidate = "/";
451
+ }
452
+ }
453
+ else if (!trimmed.startsWith("/")) {
454
+ const methodStripped = trimmed.replace(/^[A-Z]+\s+/, "").trim();
455
+ if (!methodStripped.startsWith("/"))
456
+ return undefined;
457
+ candidate = methodStripped;
458
+ }
459
+ const withoutHash = (candidate.split("#")[0] ?? "/").trim();
460
+ const withoutQuery = (withoutHash.split("?")[0] ?? "/").trim();
461
+ if (withoutQuery === "" || withoutQuery === "/")
462
+ return "/";
463
+ return `/${withoutQuery.replace(/^\/+|\/+$/g, "")}`;
464
+ }
465
+ function compileRouteTemplateRegexSource(rawTemplate) {
466
+ const pathname = extractRouteTemplatePathname(rawTemplate);
467
+ if (!pathname || pathname === "/")
468
+ return undefined;
469
+ const segments = pathname.slice(1).split("/");
470
+ let hasDynamicSegment = false;
471
+ const compiled = segments.map((seg) => {
472
+ if (seg === "**") {
473
+ hasDynamicSegment = true;
474
+ return ".*";
475
+ }
476
+ if (COLON_PARAM_SEGMENT_RE.test(seg) || BRACE_PARAM_SEGMENT_RE.test(seg)) {
477
+ hasDynamicSegment = true;
478
+ return "[^/]+";
479
+ }
480
+ if (seg.includes("*")) {
481
+ hasDynamicSegment = true;
482
+ let out = "";
483
+ for (const ch of seg) {
484
+ out += ch === "*" ? "[^/]*" : escapeRegExpLiteral(ch);
485
+ }
486
+ return out;
487
+ }
488
+ return escapeRegExpLiteral(seg);
489
+ });
490
+ if (!hasDynamicSegment)
491
+ return undefined;
492
+ return `^\\/${compiled.join("\\/")}\\/?$`;
493
+ }
494
+ function detectDynamicPathRegexSource(triggerPath, priorScalarsByTrace) {
495
+ if (!triggerPath || triggerPath === "/")
496
+ return undefined;
497
+ const normalized = `/${triggerPath.replace(/^\/+|\/+$/g, "")}`;
498
+ const allScalars = new Set();
499
+ for (const entry of priorScalarsByTrace) {
500
+ for (const s of entry.scalars) {
501
+ if (!s.includes("/"))
502
+ allScalars.add(s);
503
+ }
504
+ }
505
+ if (allScalars.size === 0)
506
+ return undefined;
507
+ const sortedScalars = [...allScalars].sort((a, b) => b.length - a.length);
508
+ let matchedAny = false;
509
+ const compiledSegments = normalized
510
+ .slice(1)
511
+ .split("/")
512
+ .map((segment) => {
513
+ if (!segment)
514
+ return "";
515
+ const exactMatch = sortedScalars.find((sc) => segment === sc);
516
+ if (exactMatch !== undefined) {
517
+ matchedAny = true;
518
+ return "[^/]+";
519
+ }
520
+ const subMatch = detectDynamicTextPattern(segment, [
521
+ { traceId: "path", scalars: allScalars },
522
+ ]);
523
+ if (subMatch) {
524
+ matchedAny = true;
525
+ return subMatch.patternSource
526
+ .replace(/^\^/, "")
527
+ .replace(/\$$/, "")
528
+ .replaceAll(".*", "[^/]+");
529
+ }
530
+ return escapeRegExpLiteral(segment);
531
+ });
532
+ if (!matchedAny)
533
+ return undefined;
534
+ return `^\\/${compiledSegments.join("\\/")}\\/?$`;
535
+ }
536
+ function resolveTriggerPathMatcher(triggerPath, urlTemplate, serverRoute, priorScalarsByTrace) {
537
+ for (const candidateTemplate of [urlTemplate, serverRoute]) {
538
+ if (!candidateTemplate)
539
+ continue;
540
+ const regexSource = compileRouteTemplateRegexSource(candidateTemplate);
541
+ if (regexSource && new RegExp(regexSource).test(triggerPath)) {
542
+ return { kind: "regex", patternSource: regexSource };
543
+ }
544
+ }
545
+ const dynamicScalarSource = detectDynamicPathRegexSource(triggerPath, priorScalarsByTrace);
546
+ if (dynamicScalarSource && new RegExp(dynamicScalarSource).test(triggerPath)) {
547
+ return { kind: "regex", patternSource: dynamicScalarSource };
548
+ }
549
+ return { kind: "exact", pathname: triggerPath };
550
+ }
551
+ function allocateDisambiguatedIdentifiers(slots, normalize) {
552
+ const uniqueSorted = [...new Set(slots)].sort(compareCodeUnits);
553
+ const used = new Set();
554
+ const mapping = new Map();
555
+ for (const slot of uniqueSorted) {
556
+ const rawBase = normalize(slot);
557
+ const base = rawBase.length > 0 ? rawBase : "slot";
558
+ let candidate = base;
559
+ let suffix = 2;
560
+ while (used.has(candidate)) {
561
+ candidate = `${base}_${suffix}`;
562
+ suffix += 1;
563
+ }
564
+ used.add(candidate);
565
+ mapping.set(slot, candidate);
566
+ }
567
+ return mapping;
568
+ }
569
+ function allocatePlaywrightSecretVars(slots) {
570
+ return allocateDisambiguatedIdentifiers(slots, (slot) => `secret_${slot.replace(/[^A-Za-z0-9_]/g, "_") || "slot"}`);
571
+ }
572
+ function allocateE2ESecretParamKeys(slots) {
573
+ return allocateDisambiguatedIdentifiers(slots, (slot) => slot.toLowerCase().replace(/[^a-z0-9_]/g, "_") || "secret");
574
+ }
575
+ function extractVerbPrimaryTarget(verb) {
576
+ switch (verb.name) {
577
+ case "click":
578
+ case "dblclick":
579
+ case "contextmenu":
580
+ case "hover":
581
+ case "fill":
582
+ case "select":
583
+ case "check":
584
+ case "upload":
585
+ return verb.target;
586
+ case "press":
587
+ case "scroll":
588
+ return verb.target;
589
+ case "drag":
590
+ return verb.source;
591
+ case "navigate":
592
+ case "dialog":
593
+ case "resize":
594
+ return undefined;
595
+ default: {
596
+ const _exhaustive = verb;
597
+ return _exhaustive;
598
+ }
599
+ }
600
+ }
601
+ function collectActionSecretSlots(verb, sink) {
602
+ if ((verb.name === "fill" || verb.name === "select") &&
603
+ verb.value.kind === "secret") {
604
+ sink.add(verb.value.slot);
605
+ }
606
+ if (verb.name === "dialog" && verb.promptText?.kind === "secret") {
607
+ sink.add(verb.promptText.slot);
608
+ }
609
+ }
610
+ export function extractSessionBundleFromSpans(rawInput, options = {}) {
611
+ const normalizedSpans = [];
612
+ let envelopeSessionId;
613
+ const extraTraces = {
614
+ ...(options.tracesByTraceId ?? {}),
615
+ };
616
+ const pushRaw = (item, resAttrs) => {
617
+ const attrs = normalizeAttributes(item.attributes);
618
+ const inlineResAttrs = normalizeAttributes(item.resource_attributes);
619
+ const combinedRes = { ...resAttrs, ...inlineResAttrs };
620
+ const traceHex = decodeHexId(item.traceId ?? item.trace_id, 16);
621
+ const spanHex = decodeHexId(item.spanId ?? item.span_id, 8);
622
+ const sessionId = item.session_id?.trim() ||
623
+ attrs["sp.session.id"]?.trim() ||
624
+ attrs["session.id"]?.trim() ||
625
+ undefined;
626
+ normalizedSpans.push({
627
+ raw: item,
628
+ traceId: isTraceId(traceHex) ? traceHex : null,
629
+ spanId: isSpanId(spanHex) ? spanHex : null,
630
+ sessionId,
631
+ name: item.name ?? "span",
632
+ startMs: parseTimestampMs(item.startTimeUnixNano, item.start_time),
633
+ attributes: attrs,
634
+ resourceAttributes: combinedRes,
635
+ });
636
+ };
637
+ if (Array.isArray(rawInput)) {
638
+ for (const entry of rawInput) {
639
+ const parsed = rawSpanObjectSchema.safeParse(entry);
640
+ if (parsed.success)
641
+ pushRaw(parsed.data, {});
642
+ }
643
+ }
644
+ else {
645
+ const envParsed = rawSessionInputEnvelopeSchema.safeParse(rawInput);
646
+ if (!envParsed.success) {
647
+ throw new Error(`Invalid session spans input: ${envParsed.error.issues.map((i) => i.message).join("; ")}`);
648
+ }
649
+ const data = envParsed.data;
650
+ envelopeSessionId = data.sessionId ?? data.session_id;
651
+ Object.assign(extraTraces, data.traces ?? {}, data.tracesByTraceId ?? {});
652
+ for (const rs of [
653
+ ...(data.trace?.resourceSpans ?? []),
654
+ ...(data.batches ?? []),
655
+ ...(data.resourceSpans ?? []),
656
+ ]) {
657
+ const resAttrs = normalizeAttributes(rs.resource?.attributes);
658
+ for (const scope of [
659
+ ...(rs.scopeSpans ?? []),
660
+ ...(rs.instrumentationLibrarySpans ?? []),
661
+ ]) {
662
+ for (const sp of scope.spans ?? []) {
663
+ pushRaw(sp, resAttrs);
664
+ }
665
+ }
666
+ }
667
+ for (const sp of [...(data.spans ?? []), ...(data.observations ?? [])]) {
668
+ pushRaw(sp, {});
669
+ }
670
+ }
671
+ const resolvedSessionId = options.sessionId?.trim() ||
672
+ envelopeSessionId?.trim() ||
673
+ normalizedSpans.find((s) => s.sessionId !== undefined)?.sessionId ||
674
+ "recorded-session";
675
+ const uiActionServiceNames = new Set();
676
+ const uiActionEntries = [];
677
+ const readSpanServiceName = (span) => span.raw.service_name?.trim() ||
678
+ span.resourceAttributes["service.name"]?.trim() ||
679
+ span.attributes["service.name"]?.trim() ||
680
+ span.attributes["service_name"]?.trim() ||
681
+ undefined;
682
+ for (const span of normalizedSpans) {
683
+ const isUiAction = span.name === "softprobe.ui.action" ||
684
+ span.attributes["sp.observation.type"] === "ui_action";
685
+ if (!isUiAction)
686
+ continue;
687
+ const svcName = readSpanServiceName(span);
688
+ if (svcName)
689
+ uiActionServiceNames.add(svcName);
690
+ const payloadRaw = span.attributes["sp.ui.action.payload"];
691
+ if (!payloadRaw) {
692
+ throw new Error(`softprobe.ui.action span ${span.spanId ?? "unknown"} is missing sp.ui.action.payload`);
693
+ }
694
+ let decodedJson;
695
+ try {
696
+ decodedJson = JSON.parse(stripSpJsonPrefix(payloadRaw));
697
+ }
698
+ catch (err) {
699
+ throw new Error(`Invalid JSON in sp.ui.action.payload on span ${span.spanId ?? "unknown"}: ${err instanceof Error ? err.message : String(err)}`);
700
+ }
701
+ const validated = recordedSemanticActionSchema.safeParse(decodedJson);
702
+ if (!validated.success) {
703
+ throw new Error(`Invalid sp-ui-action-1 payload on span ${span.spanId ?? "unknown"}: ${validated.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
704
+ }
705
+ const summary = span.attributes["sp.ui.action.summary"]?.trim() ||
706
+ validated.data.verb.name;
707
+ uiActionEntries.push({ action: validated.data, summary });
708
+ }
709
+ uiActionEntries.sort((a, b) => {
710
+ if (a.action.actionIndex !== b.action.actionIndex) {
711
+ return a.action.actionIndex - b.action.actionIndex;
712
+ }
713
+ return a.action.timestampMs - b.action.timestampMs;
714
+ });
715
+ const claimedTraceIds = new Set();
716
+ for (const entry of uiActionEntries) {
717
+ for (const ct of entry.action.causedTraces) {
718
+ claimedTraceIds.add(ct.traceId.trim().toLowerCase());
719
+ }
720
+ }
721
+ const candidateBrowserHttpSpans = normalizedSpans
722
+ .filter((span) => {
723
+ if (!span.traceId || claimedTraceIds.has(span.traceId) || span.startMs <= 0) {
724
+ return false;
725
+ }
726
+ const obsType = span.attributes["sp.observation.type"] ?? span.attributes["observation_type"];
727
+ if (span.name === "softprobe.ui.action" ||
728
+ span.name === "softprobe.web.recording" ||
729
+ span.name === "softprobe.http.body.capture" ||
730
+ obsType === "ui_action" ||
731
+ obsType === "recording" ||
732
+ obsType === "http_body") {
733
+ return false;
734
+ }
735
+ const parentHex = decodeHexId(span.raw.parentSpanId ?? span.raw.parent_span_id, 8);
736
+ if (isSpanId(parentHex))
737
+ return false;
738
+ const rawKind = span.raw.kind ?? span.raw.span_kind;
739
+ if (rawKind === 2 || rawKind === "SERVER" || rawKind === "SPAN_KIND_SERVER") {
740
+ return false;
741
+ }
742
+ const url = (span.attributes["url.full"] ?? span.attributes["http.url"] ?? "").trim();
743
+ if (!url)
744
+ return false;
745
+ const svcName = readSpanServiceName(span);
746
+ if (uiActionServiceNames.size > 0 && svcName && !uiActionServiceNames.has(svcName)) {
747
+ return false;
748
+ }
749
+ return true;
750
+ })
751
+ .sort((a, b) => a.startMs - b.startMs);
752
+ const eligibleActionIndices = uiActionEntries
753
+ .map((entry, idx) => entry.action.verb.name !== "resize" && entry.action.verb.name !== "dialog" ? idx : -1)
754
+ .filter((idx) => idx >= 0);
755
+ const inferredByActionIndex = new Map();
756
+ for (const httpSpan of candidateBrowserHttpSpans) {
757
+ if (!httpSpan.traceId || claimedTraceIds.has(httpSpan.traceId))
758
+ continue;
759
+ const url = (httpSpan.attributes["url.full"] ?? httpSpan.attributes["http.url"] ?? "").trim();
760
+ const method = (httpSpan.attributes["http.request.method"] ??
761
+ httpSpan.attributes["http.method"] ??
762
+ httpSpan.name)
763
+ .trim()
764
+ .toUpperCase();
765
+ if (!url || !method)
766
+ continue;
767
+ let chosenIdx = -1;
768
+ let prevPos = -1;
769
+ for (let p = 0; p < eligibleActionIndices.length; p += 1) {
770
+ const idx = eligibleActionIndices[p];
771
+ if (uiActionEntries[idx].action.timestampMs <= httpSpan.startMs) {
772
+ prevPos = p;
773
+ }
774
+ else {
775
+ break;
776
+ }
777
+ }
778
+ const nextPos = prevPos + 1;
779
+ if (nextPos < eligibleActionIndices.length) {
780
+ const nextIdx = eligibleActionIndices[nextPos];
781
+ const nextAction = uiActionEntries[nextIdx].action;
782
+ const prevSettled = prevPos < 0 ||
783
+ httpSpan.startMs >
784
+ uiActionEntries[eligibleActionIndices[prevPos]].action.timestampMs +
785
+ uiActionEntries[eligibleActionIndices[prevPos]].action.settleMs;
786
+ if (prevSettled && nextAction.timestampMs - httpSpan.startMs <= 50) {
787
+ chosenIdx = nextIdx;
788
+ }
789
+ }
790
+ if (chosenIdx < 0 && prevPos >= 0) {
791
+ const prevIdx = eligibleActionIndices[prevPos];
792
+ const prevAction = uiActionEntries[prevIdx].action;
793
+ if (httpSpan.startMs <= prevAction.timestampMs + Math.max(prevAction.settleMs, 15_000)) {
794
+ chosenIdx = prevIdx;
795
+ }
796
+ }
797
+ if (chosenIdx < 0)
798
+ continue;
799
+ const targetEntry = uiActionEntries[chosenIdx];
800
+ if (targetEntry.action.causedTraces.length > 0)
801
+ continue;
802
+ const rawStatus = httpSpan.attributes["http.response.status_code"] ?? httpSpan.attributes["http.status_code"];
803
+ const parsedStatus = rawStatus ? Number.parseInt(rawStatus, 10) : Number.NaN;
804
+ const urlTemplate = httpSpan.attributes["url.template"]?.trim() || undefined;
805
+ claimedTraceIds.add(httpSpan.traceId);
806
+ const list = inferredByActionIndex.get(chosenIdx) ?? [];
807
+ list.push({
808
+ traceId: httpSpan.traceId,
809
+ ...(httpSpan.spanId ? { spanId: httpSpan.spanId } : {}),
810
+ method,
811
+ url,
812
+ ...(urlTemplate ? { urlTemplate } : {}),
813
+ ...(Number.isInteger(parsedStatus) && parsedStatus >= 0 ? { status: parsedStatus } : {}),
814
+ });
815
+ inferredByActionIndex.set(chosenIdx, list);
816
+ }
817
+ for (const [idx, inferredTraces] of inferredByActionIndex.entries()) {
818
+ const entry = uiActionEntries[idx];
819
+ if (entry && inferredTraces.length > 0) {
820
+ entry.action = {
821
+ ...entry.action,
822
+ causedTraces: inferredTraces,
823
+ };
824
+ }
825
+ }
826
+ const rawSpansByTraceId = new Map();
827
+ const responseScalarsByTraceId = new Map();
828
+ for (const span of normalizedSpans) {
829
+ if (span.traceId) {
830
+ const bucket = rawSpansByTraceId.get(span.traceId) ?? [];
831
+ bucket.push({
832
+ ...span.raw,
833
+ resource_attributes: {
834
+ ...span.resourceAttributes,
835
+ ...(typeof span.raw.resource_attributes === "object" &&
836
+ span.raw.resource_attributes !== null &&
837
+ !Array.isArray(span.raw.resource_attributes)
838
+ ? span.raw.resource_attributes
839
+ : {}),
840
+ },
841
+ });
842
+ rawSpansByTraceId.set(span.traceId, bucket);
843
+ const rawResp = span.attributes["http.response.body.content"] ??
844
+ span.attributes["http.response.body"] ??
845
+ span.attributes["sp.http.response.body"];
846
+ if (rawResp) {
847
+ const parsedJson = parseJsonBodyValue(rawResp);
848
+ if (parsedJson !== undefined) {
849
+ const scalarSet = responseScalarsByTraceId.get(span.traceId) ?? new Set();
850
+ collectResponseJsonScalars(parsedJson, scalarSet);
851
+ if (scalarSet.size > 0) {
852
+ responseScalarsByTraceId.set(span.traceId, scalarSet);
853
+ }
854
+ }
855
+ }
856
+ }
857
+ }
858
+ let inferredOrigin = options.baseOrigin?.trim();
859
+ const secretSlots = new Set();
860
+ const priorTracesSeen = new Set();
861
+ let outboundAssertionCount = 0;
862
+ const steps = uiActionEntries.map((entry, idx) => {
863
+ const { action, summary } = entry;
864
+ collectActionSecretSlots(action.verb, secretSlots);
865
+ for (const span of normalizedSpans) {
866
+ if (span.traceId &&
867
+ span.startMs > 0 &&
868
+ span.startMs < action.timestampMs &&
869
+ !action.causedTraces.some((ct) => ct.traceId === span.traceId)) {
870
+ priorTracesSeen.add(span.traceId);
871
+ }
872
+ }
873
+ const priorScalarSources = [...priorTracesSeen]
874
+ .map((tid) => {
875
+ const scalars = responseScalarsByTraceId.get(tid);
876
+ return scalars ? { traceId: tid, scalars } : undefined;
877
+ })
878
+ .filter((x) => x !== undefined);
879
+ const target = extractVerbPrimaryTarget(action.verb);
880
+ const dynamicNamePattern = detectDynamicTextPattern(target?.name, priorScalarSources);
881
+ const dynamicTextPattern = detectDynamicTextPattern(target?.text, priorScalarSources);
882
+ const backendTraces = [];
883
+ for (const ct of action.causedTraces) {
884
+ priorTracesSeen.add(ct.traceId);
885
+ let triggerPath = ct.url;
886
+ try {
887
+ const parsedUrl = new URL(ct.url);
888
+ if (!inferredOrigin)
889
+ inferredOrigin = parsedUrl.origin;
890
+ triggerPath = parsedUrl.pathname || "/";
891
+ }
892
+ catch {
893
+ triggerPath = (ct.url.split("?")[0] ?? "/") || "/";
894
+ }
895
+ const traceIdLower = ct.traceId.trim().toLowerCase();
896
+ if (!isTraceId(traceIdLower))
897
+ continue;
898
+ let snapshot = extraTraces[traceIdLower] !== undefined
899
+ ? parseBlackboxTracePayload(traceIdLower, extraTraces[traceIdLower], options.explorerUrl)
900
+ : undefined;
901
+ if ((!snapshot || snapshot.state !== "ingested") && rawSpansByTraceId.has(traceIdLower)) {
902
+ snapshot = parseBlackboxTracePayload(traceIdLower, { spans: rawSpansByTraceId.get(traceIdLower) }, options.explorerUrl);
903
+ }
904
+ const outboundCalls = snapshot?.state === "ingested" ? snapshot.outboundHttp : [];
905
+ outboundAssertionCount += outboundCalls.length;
906
+ const serverRoute = snapshot?.state === "ingested" ? snapshot.serverEntry.routeOrPath : undefined;
907
+ const triggerPathMatcher = resolveTriggerPathMatcher(triggerPath, ct.urlTemplate, serverRoute, priorScalarSources);
908
+ backendTraces.push({
909
+ traceId: traceIdLower,
910
+ triggerMethod: ct.method.toUpperCase(),
911
+ triggerPath,
912
+ triggerPathMatcher,
913
+ triggerUrl: ct.url,
914
+ ...(ct.urlTemplate ? { urlTemplate: ct.urlTemplate } : {}),
915
+ ...(ct.status !== undefined ? { triggerStatus: ct.status } : {}),
916
+ ...(snapshot?.state === "ingested"
917
+ ? {
918
+ serverServiceName: snapshot.serverEntry.serviceName,
919
+ ...(serverRoute ? { serverRoute } : {}),
920
+ ...(snapshot.serverEntry.status !== undefined
921
+ ? { serverStatus: snapshot.serverEntry.status }
922
+ : {}),
923
+ }
924
+ : {}),
925
+ outboundCalls,
926
+ });
927
+ }
928
+ return {
929
+ stepIndex: idx,
930
+ action,
931
+ summary,
932
+ ...(dynamicNamePattern ? { dynamicNamePattern } : {}),
933
+ ...(dynamicTextPattern ? { dynamicTextPattern } : {}),
934
+ backendTraces,
935
+ };
936
+ });
937
+ return {
938
+ sessionId: resolvedSessionId,
939
+ ...(inferredOrigin ? { baseOrigin: inferredOrigin } : {}),
940
+ steps,
941
+ secretSlots: [...secretSlots].sort(),
942
+ outboundAssertionCount,
943
+ };
944
+ }
945
+ function buildSessionEndpointCandidates(rawEndpoint, sessionId, qs) {
946
+ const clean = rawEndpoint.trim().replace(/\/+$/, "");
947
+ const encodedId = encodeURIComponent(sessionId);
948
+ const suffix = qs ? `?${qs}` : "";
949
+ const withLimit = qs ? `?${qs}&limit=500` : "?limit=500";
950
+ const candidates = [];
951
+ const add = (url) => {
952
+ if (!candidates.includes(url))
953
+ candidates.push(url);
954
+ };
955
+ if (clean.endsWith("/api/thelake")) {
956
+ add(`${clean}/v1/llm/sessions/${encodedId}${withLimit}`);
957
+ add(`${clean}/v1/sessions/${encodedId}${withLimit}`);
958
+ add(`${clean}/v1/llm/sessions/${encodedId}/spans${suffix}`);
959
+ }
960
+ else {
961
+ add(`${clean}/api/thelake/v1/llm/sessions/${encodedId}${withLimit}`);
962
+ add(`${clean}/api/thelake/v1/sessions/${encodedId}${withLimit}`);
963
+ add(`${clean}/v1/sessions/${encodedId}${withLimit}`);
964
+ add(`${clean}/v1/llm/sessions/${encodedId}${withLimit}`);
965
+ add(`${clean}/api/thelake/v1/llm/sessions/${encodedId}/spans${suffix}`);
966
+ add(`${clean}/v1/llm/sessions/${encodedId}/spans${suffix}`);
967
+ }
968
+ return candidates;
969
+ }
970
+ function buildTraceEndpointCandidates(rawEndpoint, traceId) {
971
+ const clean = rawEndpoint.trim().replace(/\/+$/, "");
972
+ const encoded = encodeURIComponent(traceId);
973
+ const candidates = [];
974
+ const add = (url) => {
975
+ if (!candidates.includes(url))
976
+ candidates.push(url);
977
+ };
978
+ if (clean.endsWith("/api/thelake")) {
979
+ const explorerRoot = clean.slice(0, -"/api/thelake".length);
980
+ add(`${clean}/v1/traces/${encoded}`);
981
+ add(`${clean}/api/traces/${encoded}`);
982
+ add(`${explorerRoot}/api/traces/${encoded}`);
983
+ add(`${clean}/v1/llm/traces/${encoded}?limit=200`);
984
+ }
985
+ else {
986
+ add(`${clean}/api/thelake/v1/traces/${encoded}`);
987
+ add(`${clean}/api/thelake/api/traces/${encoded}`);
988
+ add(`${clean}/v1/traces/${encoded}`);
989
+ add(`${clean}/api/traces/${encoded}`);
990
+ add(`${clean}/v1/llm/traces/${encoded}?limit=200`);
991
+ add(`${clean}/api/thelake/v1/llm/traces/${encoded}?limit=200`);
992
+ }
993
+ return candidates;
994
+ }
995
+ // Explorer serves index.html with HTTP 200 on non-/api/ SPA routes, so skip HTML fallback responses while probing direct TheLake paths.
996
+ function isHtmlFallbackResponse(response) {
997
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
998
+ return contentType.includes("text/html");
999
+ }
1000
+ export async function fetchSessionSpansFromBlackbox(options) {
1001
+ const fetchFn = options.fetchImpl ?? fetch;
1002
+ const headers = {
1003
+ Accept: "application/json",
1004
+ ...formatAuthHeader(options.token),
1005
+ ...(options.workspaceId ? { "X-Workspace-Id": options.workspaceId } : {}),
1006
+ };
1007
+ const params = new URLSearchParams();
1008
+ if (options.from)
1009
+ params.set("from", options.from);
1010
+ if (options.to)
1011
+ params.set("to", options.to);
1012
+ const qs = params.toString();
1013
+ const candidates = buildSessionEndpointCandidates(options.endpoint, options.sessionId, qs);
1014
+ let rawSessionBody;
1015
+ let lastStatus = 404;
1016
+ let lastUrl = candidates[0] ?? options.endpoint;
1017
+ for (const url of candidates) {
1018
+ lastUrl = url;
1019
+ const response = await fetchFn(url, {
1020
+ method: "GET",
1021
+ headers,
1022
+ signal: options.signal,
1023
+ });
1024
+ if (response.status === 404 || isHtmlFallbackResponse(response)) {
1025
+ lastStatus = 404;
1026
+ continue;
1027
+ }
1028
+ if (!response.ok) {
1029
+ const snippet = (await response.text().catch(() => "")).slice(0, 240);
1030
+ throw new SinkHttpError(`Session lookup GET ${url} failed with HTTP ${response.status}${snippet ? ` (${snippet})` : ""}`, response.status, response.status >= 500 || response.status === 429);
1031
+ }
1032
+ rawSessionBody = await response.json();
1033
+ break;
1034
+ }
1035
+ if (rawSessionBody === undefined) {
1036
+ throw new SinkHttpError(`Session ${options.sessionId} not found at ${lastUrl} (HTTP ${lastStatus})`, lastStatus, false);
1037
+ }
1038
+ const spans = Array.isArray(rawSessionBody)
1039
+ ? rawSessionBody
1040
+ : typeof rawSessionBody === "object" && rawSessionBody !== null
1041
+ ? "spans" in rawSessionBody && Array.isArray(rawSessionBody.spans)
1042
+ ? rawSessionBody.spans
1043
+ : "observations" in rawSessionBody && Array.isArray(rawSessionBody.observations)
1044
+ ? rawSessionBody.observations
1045
+ : []
1046
+ : [];
1047
+ const preliminaryInput = spans.length > 0 ? { sessionId: options.sessionId, spans } : rawSessionBody;
1048
+ const preliminarBundle = extractSessionBundleFromSpans(preliminaryInput, {
1049
+ sessionId: options.sessionId,
1050
+ });
1051
+ const traceIds = new Set();
1052
+ for (const step of preliminarBundle.steps) {
1053
+ for (const ct of step.action.causedTraces) {
1054
+ const lower = ct.traceId.trim().toLowerCase();
1055
+ if (isTraceId(lower))
1056
+ traceIds.add(lower);
1057
+ }
1058
+ }
1059
+ const tracesByTraceId = {};
1060
+ const orderedTraceIds = [...traceIds];
1061
+ let preferredCandidateIndex = null;
1062
+ const fetchSingleTrace = async (traceId) => {
1063
+ const candidates = buildTraceEndpointCandidates(options.endpoint, traceId);
1064
+ const candidateIndices = candidates.map((_, idx) => idx);
1065
+ if (preferredCandidateIndex !== null &&
1066
+ preferredCandidateIndex >= 0 &&
1067
+ preferredCandidateIndex < candidateIndices.length) {
1068
+ candidateIndices.splice(preferredCandidateIndex, 1);
1069
+ candidateIndices.unshift(preferredCandidateIndex);
1070
+ }
1071
+ for (const idx of candidateIndices) {
1072
+ const traceUrl = candidates[idx];
1073
+ const resp = await fetchFn(traceUrl, {
1074
+ method: "GET",
1075
+ headers,
1076
+ signal: options.signal,
1077
+ }).catch(() => null);
1078
+ if (!resp || !resp.ok || isHtmlFallbackResponse(resp))
1079
+ continue;
1080
+ const body = await resp.json().catch(() => undefined);
1081
+ if (body !== undefined) {
1082
+ if (preferredCandidateIndex === null) {
1083
+ preferredCandidateIndex = idx;
1084
+ }
1085
+ tracesByTraceId[traceId] = body;
1086
+ return;
1087
+ }
1088
+ }
1089
+ };
1090
+ if (orderedTraceIds.length > 0) {
1091
+ await fetchSingleTrace(orderedTraceIds[0]);
1092
+ const remaining = orderedTraceIds.slice(1);
1093
+ const concurrency = Math.min(4, remaining.length);
1094
+ let cursor = 0;
1095
+ const workers = Array.from({ length: concurrency }, async () => {
1096
+ while (cursor < remaining.length) {
1097
+ const currentIdx = cursor;
1098
+ cursor += 1;
1099
+ const tid = remaining[currentIdx];
1100
+ if (tid !== undefined) {
1101
+ await fetchSingleTrace(tid);
1102
+ }
1103
+ }
1104
+ });
1105
+ await Promise.all(workers);
1106
+ }
1107
+ return {
1108
+ sessionId: options.sessionId,
1109
+ spans,
1110
+ tracesByTraceId,
1111
+ };
1112
+ }
1113
+ function sanitizeJsonForAssertion(value, depth = 0) {
1114
+ if (value === undefined || depth > 6)
1115
+ return undefined;
1116
+ if (value === null || typeof value === "boolean" || typeof value === "number") {
1117
+ return value;
1118
+ }
1119
+ if (typeof value === "string") {
1120
+ if (value.includes("[REDACTED]"))
1121
+ return undefined;
1122
+ return value;
1123
+ }
1124
+ if (Array.isArray(value)) {
1125
+ const mapped = value
1126
+ .map((item) => sanitizeJsonForAssertion(item, depth + 1))
1127
+ .filter((item) => item !== undefined);
1128
+ return mapped.length === value.length ? mapped : undefined;
1129
+ }
1130
+ const entries = [];
1131
+ for (const [k, v] of Object.entries(value)) {
1132
+ const clean = sanitizeJsonForAssertion(v, depth + 1);
1133
+ if (clean !== undefined) {
1134
+ entries.push([k, clean]);
1135
+ }
1136
+ }
1137
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
1138
+ }
1139
+ function isMintedTestId(testId) {
1140
+ return (/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.test(testId) ||
1141
+ testId
1142
+ .split(/[-_:./]+/)
1143
+ .some((part) => /^(?=(?:\D*\d){2})(?=.*[A-Za-z])[A-Za-z0-9]{10,}$/.test(part)));
1144
+ }
1145
+ function buildPlaywrightLocatorExpr(target, dynamicName, dynamicText) {
1146
+ const scopePrefix = target.within
1147
+ ? `page.locator("tr, li, article, [role='row'], [role='listitem'], [role='dialog'], [role='region'], fieldset, section").filter({ hasText: ${JSON.stringify(target.within)} }).first()`
1148
+ : "page";
1149
+ let expr;
1150
+ let usesTwinPosition = true;
1151
+ if (dynamicName && target.role) {
1152
+ expr = `${scopePrefix}.getByRole(${JSON.stringify(target.role)}, { name: new RegExp(${JSON.stringify(dynamicName.patternSource)}) })`;
1153
+ }
1154
+ else if (target.testId && !isMintedTestId(target.testId)) {
1155
+ expr = `${scopePrefix}.getByTestId(${JSON.stringify(target.testId)})`;
1156
+ }
1157
+ else if (target.role && target.name) {
1158
+ expr = `${scopePrefix}.getByRole(${JSON.stringify(target.role)}, { name: ${JSON.stringify(target.name)}, exact: true })`;
1159
+ }
1160
+ else if (target.label) {
1161
+ expr = `${scopePrefix}.getByLabel(${JSON.stringify(target.label)}, { exact: true })`;
1162
+ usesTwinPosition = false;
1163
+ }
1164
+ else if (target.placeholder) {
1165
+ expr = `${scopePrefix}.getByPlaceholder(${JSON.stringify(target.placeholder)}, { exact: true })`;
1166
+ }
1167
+ else if (dynamicText) {
1168
+ expr = `${scopePrefix}.getByText(new RegExp(${JSON.stringify(dynamicText.patternSource)}))`;
1169
+ }
1170
+ else if (target.text) {
1171
+ expr = `${scopePrefix}.getByText(${JSON.stringify(target.text)}, { exact: true })`;
1172
+ }
1173
+ else if (target.cssSelector) {
1174
+ expr = `page.locator(${JSON.stringify(target.cssSelector)})`;
1175
+ usesTwinPosition = false;
1176
+ }
1177
+ else if (target.role) {
1178
+ expr = `${scopePrefix}.getByRole(${JSON.stringify(target.role)})`;
1179
+ }
1180
+ else {
1181
+ expr = `page.locator("body")`;
1182
+ usesTwinPosition = false;
1183
+ }
1184
+ if (usesTwinPosition && target.position && target.position.of >= 2) {
1185
+ return `${expr}.nth(${target.position.index})`;
1186
+ }
1187
+ return expr;
1188
+ }
1189
+ const PLAYWRIGHT_CONTENT_NAMED_ROLES = new Set([
1190
+ "button",
1191
+ "cell",
1192
+ "checkbox",
1193
+ "columnheader",
1194
+ "gridcell",
1195
+ "heading",
1196
+ "link",
1197
+ "menuitem",
1198
+ "menuitemcheckbox",
1199
+ "menuitemradio",
1200
+ "option",
1201
+ "radio",
1202
+ "row",
1203
+ "rowheader",
1204
+ "switch",
1205
+ "tab",
1206
+ "tooltip",
1207
+ "treeitem",
1208
+ ]);
1209
+ function buildPlaywrightAnchorAssertionExpr(anchor) {
1210
+ const text = anchor.name ?? anchor.text;
1211
+ if (anchor.role &&
1212
+ text &&
1213
+ !anchor.label &&
1214
+ !PLAYWRIGHT_CONTENT_NAMED_ROLES.has(anchor.role)) {
1215
+ return `page.getByRole(${JSON.stringify(anchor.role)}).filter({ hasText: ${JSON.stringify(text)} }).first()`;
1216
+ }
1217
+ return buildPlaywrightLocatorExpr(anchor);
1218
+ }
1219
+ function selectVerifiableEndAnchors(anchors) {
1220
+ const priorityRoles = new Set(["alert", "alertdialog", "status", "heading", "dialog"]);
1221
+ return anchors
1222
+ .filter((anchor) => anchor.role !== undefined &&
1223
+ priorityRoles.has(anchor.role) &&
1224
+ (anchor.name !== undefined || anchor.text !== undefined))
1225
+ .slice(0, 2);
1226
+ }
1227
+ function formatOutboundUrlMatcherCode(rawUrl) {
1228
+ try {
1229
+ const parsed = new URL(rawUrl);
1230
+ return `new RegExp(${JSON.stringify(`${escapeRegExpLiteral(parsed.pathname)}$`)})`;
1231
+ }
1232
+ catch {
1233
+ return JSON.stringify(rawUrl);
1234
+ }
1235
+ }
1236
+ function formatTriggerPathMatcherCode(matcher) {
1237
+ switch (matcher.kind) {
1238
+ case "exact":
1239
+ return JSON.stringify(matcher.pathname);
1240
+ case "regex":
1241
+ return `new RegExp(${JSON.stringify(matcher.patternSource)})`;
1242
+ default: {
1243
+ const _exhaustive = matcher;
1244
+ return _exhaustive;
1245
+ }
1246
+ }
1247
+ }
1248
+ function triggerPathMatcherKey(method, matcher) {
1249
+ return matcher.kind === "exact"
1250
+ ? `${method}\u0000exact\u0000${matcher.pathname}`
1251
+ : `${method}\u0000regex\u0000${matcher.patternSource}`;
1252
+ }
1253
+ function formatWaitForResponsePredicateExpr(bt, occurrenceNumber) {
1254
+ const pathCheck = bt.triggerPathMatcher.kind === "exact"
1255
+ ? `new URL(res.url()).pathname === ${JSON.stringify(bt.triggerPathMatcher.pathname)}`
1256
+ : `new RegExp(${JSON.stringify(bt.triggerPathMatcher.patternSource)}).test(new URL(res.url()).pathname)`;
1257
+ const basePredicate = `(res) => res.request().method() === ${JSON.stringify(bt.triggerMethod)} && ${pathCheck}`;
1258
+ if (occurrenceNumber <= 1) {
1259
+ return basePredicate;
1260
+ }
1261
+ return `(() => { let seen = 0; return (res) => res.request().method() === ${JSON.stringify(bt.triggerMethod)} && ${pathCheck} && ++seen === ${occurrenceNumber}; })()`;
1262
+ }
1263
+ export function compileSessionToPlaywright(bundle, options = {}) {
1264
+ const testRelPath = (options.testFile ?? "tests/recorded-session.spec.ts")
1265
+ .replace(/\\/g, "/")
1266
+ .replace(/^\.\//, "");
1267
+ const defaultTargetUrl = options.targetUrl ?? bundle.baseOrigin ?? "http://127.0.0.1:3000";
1268
+ const initialPath = bundle.steps[0]?.action.startPath || "/";
1269
+ const lines = [
1270
+ `import { expect, test } from "@softprobe/e2e/playwright";`,
1271
+ ``,
1272
+ ];
1273
+ if (bundle.secretSlots.length > 0) {
1274
+ lines.push(`function requireSecret(envName: string, fallbackEnvName?: string): string {`, ` const value = process.env[envName] ?? (fallbackEnvName ? process.env[fallbackEnvName] : undefined);`, ` if (!value || value.trim() === "") {`, ` throw new Error(\`Missing required secret environment variable: \${envName}\`);`, ` }`, ` return value;`, `}`, ``);
1275
+ }
1276
+ lines.push(`test.describe("Recorded session replay", () => {`, ` test(${JSON.stringify(`replays session ${bundle.sessionId}`)}, async ({ page, trace }) => {`);
1277
+ const secretVarBySlot = allocatePlaywrightSecretVars(bundle.secretSlots);
1278
+ for (const slot of bundle.secretSlots) {
1279
+ const secretIdent = secretVarBySlot.get(slot);
1280
+ lines.push(` const ${secretIdent} = requireSecret(${JSON.stringify(`SP_SECRET_${slot}`)}, ${JSON.stringify(`E2E_SECRET_${slot}`)});`);
1281
+ }
1282
+ const firstVerb = bundle.steps[0]?.action.verb;
1283
+ if (!(firstVerb?.name === "navigate" && firstVerb.trigger === "load")) {
1284
+ lines.push(` await page.goto(${JSON.stringify(initialPath)});`);
1285
+ }
1286
+ const extraFixtureFiles = [];
1287
+ for (let i = 0; i < bundle.steps.length; i += 1) {
1288
+ const step = bundle.steps[i];
1289
+ const verb = step.action.verb;
1290
+ const nextStep = bundle.steps[i + 1];
1291
+ if (verb.name === "dialog") {
1292
+ continue;
1293
+ }
1294
+ if (nextStep?.action.verb.name === "dialog") {
1295
+ const dialogVerb = nextStep.action.verb;
1296
+ if (dialogVerb.accepted) {
1297
+ const promptArg = dialogVerb.promptText?.kind === "literal"
1298
+ ? JSON.stringify(dialogVerb.promptText.value)
1299
+ : dialogVerb.promptText?.kind === "secret"
1300
+ ? (secretVarBySlot.get(dialogVerb.promptText.slot) ??
1301
+ `secret_${dialogVerb.promptText.slot.replace(/[^A-Za-z0-9_]/g, "_")}`)
1302
+ : "";
1303
+ lines.push(` page.once("dialog", (dialog) => dialog.accept(${promptArg}));`);
1304
+ }
1305
+ else {
1306
+ lines.push(` page.once("dialog", (dialog) => dialog.dismiss());`);
1307
+ }
1308
+ }
1309
+ const emitActionLine = (actionStmt) => {
1310
+ if (step.backendTraces.length === 0) {
1311
+ lines.push(` ${actionStmt}`);
1312
+ return;
1313
+ }
1314
+ if (step.backendTraces.length === 1) {
1315
+ const singleTrigger = step.backendTraces[0];
1316
+ lines.push(` const responsePromise_${i} = page.waitForResponse(${formatWaitForResponsePredicateExpr(singleTrigger, 1)});`, ` ${actionStmt}`, ` await responsePromise_${i};`);
1317
+ return;
1318
+ }
1319
+ const occurrenceByKey = new Map();
1320
+ const waitExprs = step.backendTraces.map((bt) => {
1321
+ const key = triggerPathMatcherKey(bt.triggerMethod, bt.triggerPathMatcher);
1322
+ const occ = (occurrenceByKey.get(key) ?? 0) + 1;
1323
+ occurrenceByKey.set(key, occ);
1324
+ return ` page.waitForResponse(${formatWaitForResponsePredicateExpr(bt, occ)}),`;
1325
+ });
1326
+ lines.push(` const responsePromises_${i} = [`, ...waitExprs, ` ];`, ` ${actionStmt}`, ` await Promise.all(responsePromises_${i});`);
1327
+ };
1328
+ switch (verb.name) {
1329
+ case "navigate":
1330
+ emitActionLine(`await page.goto(${JSON.stringify(verb.url)});`);
1331
+ break;
1332
+ case "click": {
1333
+ const loc = buildPlaywrightLocatorExpr(verb.target, step.dynamicNamePattern, step.dynamicTextPattern);
1334
+ const modOpt = verb.modifiers && verb.modifiers.length > 0
1335
+ ? `{ modifiers: ${JSON.stringify(verb.modifiers)} }`
1336
+ : "";
1337
+ emitActionLine(`await ${loc}.click(${modOpt});`);
1338
+ break;
1339
+ }
1340
+ case "dblclick": {
1341
+ const loc = buildPlaywrightLocatorExpr(verb.target, step.dynamicNamePattern, step.dynamicTextPattern);
1342
+ emitActionLine(`await ${loc}.dblclick();`);
1343
+ break;
1344
+ }
1345
+ case "contextmenu": {
1346
+ const loc = buildPlaywrightLocatorExpr(verb.target, step.dynamicNamePattern, step.dynamicTextPattern);
1347
+ emitActionLine(`await ${loc}.click({ button: "right" });`);
1348
+ break;
1349
+ }
1350
+ case "hover": {
1351
+ const loc = buildPlaywrightLocatorExpr(verb.target, step.dynamicNamePattern, step.dynamicTextPattern);
1352
+ emitActionLine(`await ${loc}.hover();`);
1353
+ break;
1354
+ }
1355
+ case "fill": {
1356
+ const loc = buildPlaywrightLocatorExpr(verb.target);
1357
+ if (verb.value.kind === "literal") {
1358
+ emitActionLine(`await ${loc}.fill(${JSON.stringify(verb.value.value)});`);
1359
+ }
1360
+ else if (verb.value.kind === "secret") {
1361
+ const ident = secretVarBySlot.get(verb.value.slot) ??
1362
+ `secret_${verb.value.slot.replace(/[^A-Za-z0-9_]/g, "_")}`;
1363
+ emitActionLine(`await ${loc}.fill(${ident});`);
1364
+ }
1365
+ else {
1366
+ throw new Error(`Cannot compile redacted input at actionIndex=${step.action.actionIndex}; enable inputCapture: "secrets-only" when recording`);
1367
+ }
1368
+ break;
1369
+ }
1370
+ case "select": {
1371
+ const loc = buildPlaywrightLocatorExpr(verb.target);
1372
+ if (verb.value.kind === "literal") {
1373
+ emitActionLine(`await ${loc}.selectOption(${JSON.stringify(verb.value.value)});`);
1374
+ }
1375
+ else if (verb.value.kind === "secret") {
1376
+ const ident = secretVarBySlot.get(verb.value.slot) ??
1377
+ `secret_${verb.value.slot.replace(/[^A-Za-z0-9_]/g, "_")}`;
1378
+ emitActionLine(`await ${loc}.selectOption(${ident});`);
1379
+ }
1380
+ else if (verb.optionLabel) {
1381
+ emitActionLine(`await ${loc}.selectOption({ label: ${JSON.stringify(verb.optionLabel)} });`);
1382
+ }
1383
+ else {
1384
+ throw new Error(`Cannot compile redacted select at actionIndex=${step.action.actionIndex}; enable inputCapture: "secrets-only" when recording`);
1385
+ }
1386
+ break;
1387
+ }
1388
+ case "check": {
1389
+ const loc = buildPlaywrightLocatorExpr(verb.target);
1390
+ emitActionLine(`await ${loc}.${verb.checked ? "check" : "uncheck"}();`);
1391
+ break;
1392
+ }
1393
+ case "press": {
1394
+ const combo = verb.modifiers && verb.modifiers.length > 0
1395
+ ? `${verb.modifiers.join("+")}+${verb.key}`
1396
+ : verb.key;
1397
+ if (verb.target) {
1398
+ const loc = buildPlaywrightLocatorExpr(verb.target);
1399
+ emitActionLine(`await ${loc}.press(${JSON.stringify(combo)});`);
1400
+ }
1401
+ else {
1402
+ emitActionLine(`await page.keyboard.press(${JSON.stringify(combo)});`);
1403
+ }
1404
+ break;
1405
+ }
1406
+ case "upload": {
1407
+ const loc = buildPlaywrightLocatorExpr(verb.target);
1408
+ const relFiles = verb.fileNames.map((name) => {
1409
+ const safeName = name.replace(/[^A-Za-z0-9._-]/g, "_");
1410
+ const fixturePath = `fixtures/${safeName}`;
1411
+ if (!extraFixtureFiles.some((f) => f.relativePath === fixturePath)) {
1412
+ extraFixtureFiles.push({
1413
+ relativePath: fixturePath,
1414
+ content: "softprobe-upload-fixture\n",
1415
+ });
1416
+ }
1417
+ return fixturePath;
1418
+ });
1419
+ emitActionLine(`await ${loc}.setInputFiles(${JSON.stringify(relFiles)});`);
1420
+ break;
1421
+ }
1422
+ case "drag": {
1423
+ const src = buildPlaywrightLocatorExpr(verb.source);
1424
+ const dst = buildPlaywrightLocatorExpr(verb.destination);
1425
+ emitActionLine(`await ${src}.dragTo(${dst});`);
1426
+ break;
1427
+ }
1428
+ case "scroll": {
1429
+ const dy = verb.direction === "down" ? 400 * verb.times : verb.direction === "up" ? -400 * verb.times : 0;
1430
+ const dx = verb.direction === "right" ? 400 * verb.times : verb.direction === "left" ? -400 * verb.times : 0;
1431
+ emitActionLine(`await page.mouse.wheel(${dx}, ${dy});`);
1432
+ break;
1433
+ }
1434
+ case "resize":
1435
+ emitActionLine(`await page.setViewportSize({ width: ${verb.viewport.width}, height: ${verb.viewport.height} });`);
1436
+ break;
1437
+ }
1438
+ for (const anchor of selectVerifiableEndAnchors(step.action.endAnchors)) {
1439
+ const anchorLoc = buildPlaywrightAnchorAssertionExpr(anchor);
1440
+ lines.push(` await expect(${anchorLoc}).toBeVisible();`);
1441
+ }
1442
+ for (let tIdx = 0; tIdx < step.backendTraces.length; tIdx += 1) {
1443
+ const bt = step.backendTraces[tIdx];
1444
+ for (let cIdx = 0; cIdx < bt.outboundCalls.length; cIdx += 1) {
1445
+ const call = bt.outboundCalls[cIdx];
1446
+ const varName = `outbound_${i}_${tIdx}_${cIdx}`;
1447
+ lines.push(` const ${varName} = await trace.outboundHttp({`, ` triggeredBy: { method: ${JSON.stringify(bt.triggerMethod)}, path: ${formatTriggerPathMatcherCode(bt.triggerPathMatcher)} },`, ` method: ${JSON.stringify(call.method)},`, ` url: ${formatOutboundUrlMatcherCode(call.url)},`, ...(call.status > 0 ? [` status: ${call.status},`] : []), ` });`);
1448
+ if (call.status > 0) {
1449
+ lines.push(` expect(${varName}.status).toBe(${call.status});`);
1450
+ }
1451
+ const expectedJson = sanitizeJsonForAssertion(call.request.json);
1452
+ if (expectedJson !== undefined && typeof expectedJson === "object" && expectedJson !== null) {
1453
+ lines.push(` expect(${varName}.request.json).toMatchObject(${JSON.stringify(expectedJson)});`);
1454
+ }
1455
+ }
1456
+ }
1457
+ }
1458
+ lines.push(` });`, `});`, ``);
1459
+ const files = [
1460
+ ...extraFixtureFiles,
1461
+ {
1462
+ relativePath: testRelPath,
1463
+ content: lines.join("\n"),
1464
+ },
1465
+ ];
1466
+ if (options.includeConfig !== false) {
1467
+ const configLines = [
1468
+ `import { defineConfig } from "@playwright/test";`,
1469
+ `import type { SoftprobePlaywrightFixtures } from "@softprobe/e2e/playwright";`,
1470
+ ``,
1471
+ `export default defineConfig<SoftprobePlaywrightFixtures>({`,
1472
+ ` testDir: "./tests",`,
1473
+ ` fullyParallel: false,`,
1474
+ ` retries: 0,`,
1475
+ ` use: {`,
1476
+ ` baseURL: process.env.APP_URL ?? ${JSON.stringify(defaultTargetUrl)},`,
1477
+ ` headless: true,`,
1478
+ ...(options.sinkEndpoint || options.workspaceId || options.appId || options.store
1479
+ ? [
1480
+ ` softprobe: {`,
1481
+ ...(options.sinkEndpoint
1482
+ ? [` endpoint: process.env.SOFTPROBE_SINK_ENDPOINT ?? ${JSON.stringify(options.sinkEndpoint)},`]
1483
+ : []),
1484
+ ...(options.workspaceId
1485
+ ? [` workspaceId: process.env.SOFTPROBE_WORKSPACE_ID ?? ${JSON.stringify(options.workspaceId)},`]
1486
+ : []),
1487
+ ...(options.appId
1488
+ ? [` appId: process.env.SOFTPROBE_APP_ID ?? ${JSON.stringify(options.appId)},`]
1489
+ : []),
1490
+ ...(options.store
1491
+ ? [` store: ${JSON.stringify(options.store)},`]
1492
+ : []),
1493
+ ` },`,
1494
+ ]
1495
+ : []),
1496
+ ` },`,
1497
+ `});`,
1498
+ ``,
1499
+ ];
1500
+ files.push({
1501
+ relativePath: "playwright.config.ts",
1502
+ content: configLines.join("\n"),
1503
+ });
1504
+ }
1505
+ return {
1506
+ runner: "playwright",
1507
+ sessionId: bundle.sessionId,
1508
+ actionCount: bundle.steps.length,
1509
+ outboundAssertionCount: bundle.outboundAssertionCount,
1510
+ files,
1511
+ };
1512
+ }
1513
+ export function sha256Hex(input) {
1514
+ return createHash("sha256").update(input).digest("hex");
1515
+ }
1516
+ function compareCodeUnits(a, b) {
1517
+ if (a === b)
1518
+ return 0;
1519
+ return a < b ? -1 : 1;
1520
+ }
1521
+ export function canonicalJson(value) {
1522
+ if (value === null)
1523
+ return "null";
1524
+ switch (typeof value) {
1525
+ case "boolean":
1526
+ return value ? "true" : "false";
1527
+ case "number": {
1528
+ if (!Number.isFinite(value)) {
1529
+ throw new TypeError("Non-finite number in canonical JSON");
1530
+ }
1531
+ return JSON.stringify(value);
1532
+ }
1533
+ case "string":
1534
+ return JSON.stringify(value);
1535
+ case "object": {
1536
+ if (Array.isArray(value)) {
1537
+ return `[${value.map((item) => canonicalJson(item === undefined ? null : item)).join(",")}]`;
1538
+ }
1539
+ const entries = Object.entries(value)
1540
+ .filter(([, v]) => v !== undefined)
1541
+ .sort(([a], [b]) => compareCodeUnits(a, b));
1542
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
1543
+ }
1544
+ default:
1545
+ throw new TypeError(`Unsupported type in canonical JSON: ${typeof value}`);
1546
+ }
1547
+ }
1548
+ export function canonicalDigest(value) {
1549
+ return sha256Hex(canonicalJson(value));
1550
+ }
1551
+ export function encodeE2ETitle(title) {
1552
+ const normalized = title.normalize("NFC");
1553
+ const bytes = new TextEncoder().encode(normalized);
1554
+ let out = "";
1555
+ for (const byte of bytes) {
1556
+ const ch = String.fromCharCode(byte);
1557
+ if ((byte >= 0x41 && byte <= 0x5a) ||
1558
+ (byte >= 0x61 && byte <= 0x7a) ||
1559
+ (byte >= 0x30 && byte <= 0x39) ||
1560
+ ch === "-" ||
1561
+ ch === "." ||
1562
+ ch === "_" ||
1563
+ ch === "~") {
1564
+ out += ch;
1565
+ }
1566
+ else {
1567
+ out += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
1568
+ }
1569
+ }
1570
+ return out;
1571
+ }
1572
+ export function formatE2ETestId(relativeFile, titlePath) {
1573
+ const cleanFile = relativeFile.replace(/\\/g, "/").replace(/^\.\//, "");
1574
+ return `${cleanFile}::${titlePath.map(encodeE2ETitle).join("::")}`;
1575
+ }
1576
+ export function normalizeE2EInstruction(instruction) {
1577
+ return instruction.replace(/\r\n?/gu, "\n").normalize("NFC").trim();
1578
+ }
1579
+ // Match @e2e-dev/core 0.24.0 trace-1 cache key projection across appIdentity, testId, conservative/6 policy, and secret descriptors.
1580
+ export function buildE2ECacheKeyAndHash(input) {
1581
+ const projectedParams = {};
1582
+ const paramKeyBySlot = allocateE2ESecretParamKeys(input.secretSlots ?? []);
1583
+ for (const slot of [...new Set(input.secretSlots ?? [])].sort(compareCodeUnits)) {
1584
+ const paramKey = paramKeyBySlot.get(slot);
1585
+ projectedParams[paramKey] = {
1586
+ kind: "secret",
1587
+ name: slot,
1588
+ purpose: "generic-secret",
1589
+ };
1590
+ }
1591
+ const instrDigest = sha256Hex(normalizeE2EInstruction(input.instruction));
1592
+ const pDigest = canonicalDigest(projectedParams);
1593
+ const projectHash = sha256Hex(input.projectId);
1594
+ const appIdentityHash = canonicalDigest({
1595
+ identity: input.appIdentity,
1596
+ environment: input.appEnvironment,
1597
+ });
1598
+ const agentName = input.agentName ?? "default";
1599
+ const agentContextDigest = sha256Hex(input.agentContext ?? "");
1600
+ const fullKey = {
1601
+ specVersion: "0.1",
1602
+ cacheSchema: E2E_TRACE_SCHEMA_VERSION,
1603
+ project: projectHash,
1604
+ testId: input.testId,
1605
+ targetId: input.targetId,
1606
+ platform: "web",
1607
+ engineName: "web",
1608
+ engineSpiVersion: E2E_ENGINE_SPI_VERSION,
1609
+ kind: "act",
1610
+ callIndex: input.callIndex,
1611
+ instructionDigest: instrDigest,
1612
+ paramsDigest: pDigest,
1613
+ appIdentity: appIdentityHash,
1614
+ agent: agentName,
1615
+ agentContextDigest,
1616
+ policyVersion: E2E_REPLAY_POLICY_VERSION,
1617
+ };
1618
+ return {
1619
+ keyHash: canonicalDigest(fullKey),
1620
+ instructionDigest: instrDigest,
1621
+ paramsDigest: pDigest,
1622
+ projectedParams,
1623
+ keyedBy: {
1624
+ cacheSchema: E2E_TRACE_SCHEMA_VERSION,
1625
+ policyVersion: E2E_REPLAY_POLICY_VERSION,
1626
+ project: projectHash,
1627
+ platform: "web",
1628
+ engineName: "web",
1629
+ engineSpiVersion: E2E_ENGINE_SPI_VERSION,
1630
+ appIdentity: appIdentityHash,
1631
+ agentContextDigest,
1632
+ },
1633
+ };
1634
+ }
1635
+ const VALID_E2E_INPUT_PURPOSES = new Set(["password", "username", "one-time-code"]);
1636
+ const CONTENT_NAMED_ANCHOR_ROLES = new Set([
1637
+ "alert",
1638
+ "alertdialog",
1639
+ "status",
1640
+ "button",
1641
+ "link",
1642
+ "heading",
1643
+ "option",
1644
+ "tab",
1645
+ "menuitem",
1646
+ "checkbox",
1647
+ "radio",
1648
+ "switch",
1649
+ ]);
1650
+ function boundStr(value, max) {
1651
+ if (value === undefined)
1652
+ return undefined;
1653
+ const trimmed = value.replace(/\s+/g, " ").trim();
1654
+ if (trimmed === "")
1655
+ return undefined;
1656
+ return trimmed.length <= max ? trimmed : trimmed.slice(0, max);
1657
+ }
1658
+ function toE2ETargetDescriptor(target) {
1659
+ const role = boundStr(target.role, 300);
1660
+ const name = boundStr(target.name, 300);
1661
+ const rawText = boundStr(target.text, 300);
1662
+ const text = rawText !== undefined &&
1663
+ rawText !== name &&
1664
+ !(role !== undefined && CONTENT_NAMED_ANCHOR_ROLES.has(role) && name !== undefined)
1665
+ ? rawText
1666
+ : undefined;
1667
+ const testId = boundStr(target.testId, 300);
1668
+ const placeholder = boundStr(target.placeholder, 300);
1669
+ const selector = boundStr(target.cssSelector, 300);
1670
+ const inputPurpose = target.inputPurpose && VALID_E2E_INPUT_PURPOSES.has(target.inputPurpose)
1671
+ ? target.inputPurpose
1672
+ : undefined;
1673
+ const within = boundStr(target.within, 80);
1674
+ const hasIdentity = testId !== undefined ||
1675
+ name !== undefined ||
1676
+ text !== undefined ||
1677
+ placeholder !== undefined;
1678
+ const position = target.position &&
1679
+ target.position.of >= (hasIdentity ? 2 : 1) &&
1680
+ target.position.of <= 1000 &&
1681
+ target.position.index >= 0 &&
1682
+ target.position.index < target.position.of
1683
+ ? { index: target.position.index, of: target.position.of }
1684
+ : !hasIdentity && role !== undefined
1685
+ ? { index: 0, of: 1 }
1686
+ : undefined;
1687
+ const out = {
1688
+ ...(role !== undefined ? { role } : {}),
1689
+ ...(name !== undefined ? { name } : {}),
1690
+ ...(text !== undefined ? { text } : {}),
1691
+ ...(testId !== undefined ? { testId } : {}),
1692
+ ...(placeholder !== undefined ? { placeholder } : {}),
1693
+ ...(selector !== undefined ? { selector } : {}),
1694
+ ...(inputPurpose !== undefined ? { inputPurpose } : {}),
1695
+ ...(within !== undefined ? { within } : {}),
1696
+ ...(position !== undefined ? { position } : {}),
1697
+ };
1698
+ if (Object.keys(out).length === 0) {
1699
+ return { role: "button", position: { index: 0, of: 1 } };
1700
+ }
1701
+ return out;
1702
+ }
1703
+ function toE2EAnchorDescriptor(target) {
1704
+ const role = boundStr(target.role, 300);
1705
+ const name = boundStr(target.name, 300);
1706
+ const rawText = boundStr(target.text, 300);
1707
+ const text = rawText !== undefined &&
1708
+ rawText !== name &&
1709
+ !(role !== undefined && CONTENT_NAMED_ANCHOR_ROLES.has(role) && name !== undefined)
1710
+ ? rawText
1711
+ : undefined;
1712
+ const testId = boundStr(target.testId, 300);
1713
+ const placeholder = boundStr(target.placeholder, 300);
1714
+ const inputPurpose = target.inputPurpose && VALID_E2E_INPUT_PURPOSES.has(target.inputPurpose)
1715
+ ? target.inputPurpose
1716
+ : undefined;
1717
+ const value = inputPurpose === "password" || role === "checkbox" || role === "radio"
1718
+ ? undefined
1719
+ : boundStr(target.value, 300);
1720
+ const states = target.states && target.states.length > 0
1721
+ ? [...new Set(target.states)].sort()
1722
+ : undefined;
1723
+ if (testId === undefined &&
1724
+ name === undefined &&
1725
+ text === undefined &&
1726
+ placeholder === undefined) {
1727
+ return undefined;
1728
+ }
1729
+ return {
1730
+ ...(role !== undefined ? { role } : {}),
1731
+ ...(name !== undefined ? { name } : {}),
1732
+ ...(text !== undefined ? { text } : {}),
1733
+ ...(testId !== undefined ? { testId } : {}),
1734
+ ...(placeholder !== undefined ? { placeholder } : {}),
1735
+ ...(inputPurpose !== undefined ? { inputPurpose } : {}),
1736
+ ...(value !== undefined ? { value } : {}),
1737
+ ...(states !== undefined ? { states } : {}),
1738
+ };
1739
+ }
1740
+ function e2eAnchorKey(desc) {
1741
+ return JSON.stringify([
1742
+ desc.role ?? null,
1743
+ desc.name ?? null,
1744
+ desc.text ?? null,
1745
+ desc.testId ?? null,
1746
+ desc.placeholder ?? null,
1747
+ desc.inputPurpose ?? null,
1748
+ desc.value ?? null,
1749
+ desc.states ? desc.states.join(",") : "",
1750
+ ]);
1751
+ }
1752
+ function isE2EAnchorRelocatable(desc) {
1753
+ return (desc.testId !== undefined ||
1754
+ desc.name !== undefined ||
1755
+ desc.text !== undefined ||
1756
+ desc.placeholder !== undefined);
1757
+ }
1758
+ function convertSemanticStepToE2ERecordedAction(step, extraFixtureFiles) {
1759
+ const verb = step.action.verb;
1760
+ const summary = (step.summary || verb.name).slice(0, 300);
1761
+ switch (verb.name) {
1762
+ case "dialog":
1763
+ return null;
1764
+ case "navigate":
1765
+ return {
1766
+ name: "navigate",
1767
+ summary,
1768
+ url: verb.url,
1769
+ };
1770
+ case "click": {
1771
+ const target = toE2ETargetDescriptor(verb.target);
1772
+ const hasIdentity = target.testId !== undefined ||
1773
+ target.name !== undefined ||
1774
+ target.text !== undefined ||
1775
+ target.placeholder !== undefined;
1776
+ if (!hasIdentity && verb.point) {
1777
+ return {
1778
+ name: "tapAt",
1779
+ summary,
1780
+ point: { x: verb.point.x, y: verb.point.y },
1781
+ viewport: {
1782
+ width: step.action.viewport.width,
1783
+ height: step.action.viewport.height,
1784
+ },
1785
+ };
1786
+ }
1787
+ return {
1788
+ name: "tap",
1789
+ summary,
1790
+ target,
1791
+ ...(verb.modifiers && verb.modifiers.length > 0 ? { modifiers: [...verb.modifiers] } : {}),
1792
+ };
1793
+ }
1794
+ case "dblclick":
1795
+ return {
1796
+ name: "doubleTap",
1797
+ summary,
1798
+ target: toE2ETargetDescriptor(verb.target),
1799
+ ...(verb.modifiers && verb.modifiers.length > 0 ? { modifiers: [...verb.modifiers] } : {}),
1800
+ };
1801
+ case "contextmenu":
1802
+ return {
1803
+ name: "secondaryTap",
1804
+ summary,
1805
+ target: toE2ETargetDescriptor(verb.target),
1806
+ ...(verb.modifiers && verb.modifiers.length > 0 ? { modifiers: [...verb.modifiers] } : {}),
1807
+ };
1808
+ case "hover":
1809
+ return {
1810
+ name: "hover",
1811
+ summary,
1812
+ target: toE2ETargetDescriptor(verb.target),
1813
+ };
1814
+ case "fill": {
1815
+ const target = toE2ETargetDescriptor(verb.target);
1816
+ if (verb.value.kind === "secret") {
1817
+ return {
1818
+ name: "typeSecret",
1819
+ summary,
1820
+ target,
1821
+ secret: verb.value.slot,
1822
+ };
1823
+ }
1824
+ if (verb.value.kind === "literal") {
1825
+ return {
1826
+ name: "type",
1827
+ summary,
1828
+ target,
1829
+ value: verb.value.value,
1830
+ };
1831
+ }
1832
+ throw new Error(`Cannot compile redacted input at actionIndex=${step.action.actionIndex}; record with inputCapture: "secrets-only"`);
1833
+ }
1834
+ case "select": {
1835
+ const target = toE2ETargetDescriptor(verb.target);
1836
+ const val = verb.optionLabel ??
1837
+ (verb.value.kind === "literal" ? verb.value.value : undefined);
1838
+ if (!val) {
1839
+ throw new Error(`Cannot compile non-literal select at actionIndex=${step.action.actionIndex}`);
1840
+ }
1841
+ return {
1842
+ name: "select",
1843
+ summary,
1844
+ target,
1845
+ value: val,
1846
+ };
1847
+ }
1848
+ case "check":
1849
+ return {
1850
+ name: "check",
1851
+ summary,
1852
+ target: toE2ETargetDescriptor(verb.target),
1853
+ checked: verb.checked,
1854
+ };
1855
+ case "press": {
1856
+ const combo = verb.modifiers && verb.modifiers.length > 0
1857
+ ? `${verb.modifiers.join("+")}+${verb.key}`
1858
+ : verb.key;
1859
+ if (verb.target) {
1860
+ return {
1861
+ name: "press",
1862
+ summary,
1863
+ target: toE2ETargetDescriptor(verb.target),
1864
+ key: combo,
1865
+ };
1866
+ }
1867
+ return {
1868
+ name: "pressKey",
1869
+ summary,
1870
+ key: combo,
1871
+ };
1872
+ }
1873
+ case "upload": {
1874
+ const paths = verb.fileNames.map((name) => {
1875
+ const safeName = name.replace(/[^A-Za-z0-9._-]/g, "_");
1876
+ const fixturePath = `fixtures/${safeName}`;
1877
+ if (!extraFixtureFiles.some((f) => f.relativePath === fixturePath)) {
1878
+ extraFixtureFiles.push({
1879
+ relativePath: fixturePath,
1880
+ content: "softprobe-upload-fixture\n",
1881
+ });
1882
+ }
1883
+ return fixturePath;
1884
+ });
1885
+ return {
1886
+ name: "upload",
1887
+ summary,
1888
+ target: toE2ETargetDescriptor(verb.target),
1889
+ paths,
1890
+ };
1891
+ }
1892
+ case "drag":
1893
+ return {
1894
+ name: "drag",
1895
+ summary,
1896
+ target: toE2ETargetDescriptor(verb.source),
1897
+ destination: toE2ETargetDescriptor(verb.destination),
1898
+ };
1899
+ case "scroll":
1900
+ return {
1901
+ name: "scroll",
1902
+ summary,
1903
+ direction: verb.direction,
1904
+ ...(verb.target ? { target: toE2ETargetDescriptor(verb.target) } : {}),
1905
+ ...(verb.times >= 2 ? { times: verb.times } : {}),
1906
+ ...(verb.spansViewport >= 0 && verb.spansViewport <= 1
1907
+ ? { spans: verb.spansViewport }
1908
+ : {}),
1909
+ };
1910
+ case "resize":
1911
+ return {
1912
+ name: "resize",
1913
+ summary,
1914
+ size: {
1915
+ width: Math.min(7680, Math.max(200, verb.viewport.width)),
1916
+ height: Math.min(4320, Math.max(200, verb.viewport.height)),
1917
+ },
1918
+ };
1919
+ default: {
1920
+ const _exhaustive = verb;
1921
+ return _exhaustive;
1922
+ }
1923
+ }
1924
+ }
1925
+ function isPreparatoryStep(step) {
1926
+ if (step.backendTraces.length > 0)
1927
+ return false;
1928
+ if (step.action.startPath !== step.action.endPath)
1929
+ return false;
1930
+ switch (step.action.verb.name) {
1931
+ case "fill":
1932
+ case "select":
1933
+ case "check":
1934
+ case "upload":
1935
+ case "hover":
1936
+ case "scroll":
1937
+ case "resize":
1938
+ return true;
1939
+ case "press":
1940
+ return step.action.verb.key !== "Enter";
1941
+ default:
1942
+ return false;
1943
+ }
1944
+ }
1945
+ function foldGroupAnchors(steps) {
1946
+ const appeared = new Map();
1947
+ const vanished = new Map();
1948
+ for (const step of steps) {
1949
+ for (const rawGone of step.action.goneAnchors) {
1950
+ const desc = toE2EAnchorDescriptor(rawGone);
1951
+ if (!desc || !isE2EAnchorRelocatable(desc))
1952
+ continue;
1953
+ const key = e2eAnchorKey(desc);
1954
+ if (appeared.has(key)) {
1955
+ appeared.delete(key);
1956
+ }
1957
+ else if (!vanished.has(key)) {
1958
+ vanished.set(key, desc);
1959
+ }
1960
+ }
1961
+ for (const rawEnd of step.action.endAnchors) {
1962
+ const desc = toE2EAnchorDescriptor(rawEnd);
1963
+ if (!desc || !isE2EAnchorRelocatable(desc))
1964
+ continue;
1965
+ const key = e2eAnchorKey(desc);
1966
+ if (vanished.has(key)) {
1967
+ vanished.delete(key);
1968
+ }
1969
+ else {
1970
+ appeared.set(key, desc);
1971
+ }
1972
+ }
1973
+ }
1974
+ const orderAnchors = (items) => {
1975
+ const announcements = [];
1976
+ const rest = [];
1977
+ for (const item of items) {
1978
+ if (item.role === "alert" ||
1979
+ item.role === "alertdialog" ||
1980
+ item.role === "status") {
1981
+ announcements.push(item);
1982
+ }
1983
+ else {
1984
+ rest.push(item);
1985
+ }
1986
+ }
1987
+ return [...announcements, ...rest].slice(0, 8);
1988
+ };
1989
+ return {
1990
+ endAnchors: orderAnchors(appeared.values()),
1991
+ goneAnchors: orderAnchors(vanished.values()),
1992
+ };
1993
+ }
1994
+ function groupStepsForE2E(steps) {
1995
+ const nonLoadSteps = steps.filter((s, idx) => !(idx === 0 && s.action.verb.name === "navigate" && s.action.verb.trigger === "load"));
1996
+ if (nonLoadSteps.length === 0)
1997
+ return [];
1998
+ const rawGroups = [];
1999
+ let buffer = [];
2000
+ for (let i = 0; i < nonLoadSteps.length; i += 1) {
2001
+ const step = nonLoadSteps[i];
2002
+ if (step.action.verb.name === "dialog") {
2003
+ if (buffer.length > 0) {
2004
+ buffer.push(step);
2005
+ }
2006
+ else if (rawGroups.length > 0) {
2007
+ rawGroups[rawGroups.length - 1].push(step);
2008
+ }
2009
+ continue;
2010
+ }
2011
+ buffer.push(step);
2012
+ const nextNonDialog = nonLoadSteps
2013
+ .slice(i + 1)
2014
+ .find((cand) => cand.action.verb.name !== "dialog");
2015
+ if (!isPreparatoryStep(step) || !nextNonDialog) {
2016
+ while (i + 1 < nonLoadSteps.length && nonLoadSteps[i + 1]?.action.verb.name === "dialog") {
2017
+ i += 1;
2018
+ buffer.push(nonLoadSteps[i]);
2019
+ }
2020
+ rawGroups.push(buffer);
2021
+ buffer = [];
2022
+ }
2023
+ }
2024
+ if (buffer.length > 0) {
2025
+ rawGroups.push(buffer);
2026
+ }
2027
+ return rawGroups.map((groupSteps, gIdx) => {
2028
+ const first = groupSteps[0];
2029
+ const last = groupSteps[groupSteps.length - 1];
2030
+ const slots = new Set();
2031
+ const dialogs = [];
2032
+ const backendTraces = [];
2033
+ for (const s of groupSteps) {
2034
+ collectActionSecretSlots(s.action.verb, slots);
2035
+ if (s.action.verb.name === "dialog") {
2036
+ dialogs.push(s.action.verb);
2037
+ }
2038
+ backendTraces.push(...s.backendTraces);
2039
+ }
2040
+ const actionProseList = groupSteps
2041
+ .filter((s) => s.action.verb.name !== "dialog")
2042
+ .map((s) => s.summary);
2043
+ const joinedProse = actionProseList.join(", then ");
2044
+ const instruction = joinedProse.length <= 240
2045
+ ? `Step ${gIdx + 1}: ${joinedProse}`
2046
+ : `Step ${gIdx + 1}: ${joinedProse.slice(0, 237)}...`;
2047
+ const { endAnchors, goneAnchors } = foldGroupAnchors(groupSteps);
2048
+ const totalSettleMs = groupSteps.reduce((sum, s) => sum + s.action.settleMs, 0);
2049
+ return {
2050
+ steps: groupSteps,
2051
+ startPath: first.action.startPath || "/",
2052
+ endPath: last.action.endPath || first.action.startPath || "/",
2053
+ instruction,
2054
+ secretSlots: [...slots].sort(),
2055
+ dialogActions: dialogs,
2056
+ backendTraces,
2057
+ endAnchors,
2058
+ goneAnchors,
2059
+ rawEndTargets: last.action.endAnchors,
2060
+ settleMs: totalSettleMs,
2061
+ };
2062
+ });
2063
+ }
2064
+ function buildE2EScreenAssertionLine(group) {
2065
+ const candidates = selectVerifiableEndAnchors(group.rawEndTargets);
2066
+ const best = candidates[0];
2067
+ if (best && best.role && (best.name || best.text)) {
2068
+ const label = best.name ?? best.text;
2069
+ if (!best.label && !PLAYWRIGHT_CONTENT_NAMED_ROLES.has(best.role)) {
2070
+ return ` await expect(screen.getByRole(${JSON.stringify(best.role)})).toContainText(${JSON.stringify(label)});`;
2071
+ }
2072
+ return ` await expect(screen.getByRole(${JSON.stringify(best.role)}, ${JSON.stringify(label)})).toBeVisible();`;
2073
+ }
2074
+ const firstEnd = group.endAnchors[0];
2075
+ if (firstEnd?.role && firstEnd.name) {
2076
+ if (!PLAYWRIGHT_CONTENT_NAMED_ROLES.has(firstEnd.role)) {
2077
+ return ` await expect(screen.getByRole(${JSON.stringify(firstEnd.role)})).toContainText(${JSON.stringify(firstEnd.name)});`;
2078
+ }
2079
+ return ` await expect(screen.getByRole(${JSON.stringify(firstEnd.role)}, ${JSON.stringify(firstEnd.name)})).toBeVisible();`;
2080
+ }
2081
+ return ` await expect(app).toHaveURL(new RegExp(${JSON.stringify(escapeRegExpLiteral(group.endPath.split("?")[0] ?? "/"))}));`;
2082
+ }
2083
+ export function compileSessionToE2E(bundle, options = {}) {
2084
+ const projectId = options.projectId?.trim() || "softprobe-compiled-e2e";
2085
+ const targetName = options.targetName?.trim() || "web";
2086
+ const defaultTargetUrl = options.targetUrl ?? bundle.baseOrigin ?? "http://127.0.0.1:3000";
2087
+ const appIdentity = options.appIdentity?.trim() || "softprobe-recorded-app";
2088
+ const appEnvironment = options.appEnvironment ?? "test";
2089
+ const testRelPath = (options.testFile ?? "tests/recorded-session.e2e.ts")
2090
+ .replace(/\\/g, "/")
2091
+ .replace(/^\.\//, "");
2092
+ const createdAt = options.createdAt ?? new Date().toISOString();
2093
+ const suiteTitle = "Recorded session replay";
2094
+ const testTitle = `replays session ${bundle.sessionId}`;
2095
+ const fullTestId = formatE2ETestId(testRelPath, [suiteTitle, testTitle]);
2096
+ const groups = groupStepsForE2E(bundle.steps);
2097
+ const initialStartPath = groups[0]?.startPath ?? bundle.steps[0]?.action.startPath ?? "/";
2098
+ const extraFixtureFiles = [];
2099
+ const cacheFiles = [];
2100
+ const callCounts = new Map();
2101
+ const needsSecretsImport = bundle.secretSlots.length > 0;
2102
+ const needsBrowserFixture = groups.some((g) => g.dialogActions.length > 0);
2103
+ const testLines = [
2104
+ `import {`,
2105
+ ` describe,`,
2106
+ ` expect,`,
2107
+ ...(needsSecretsImport ? [` secrets,`] : []),
2108
+ ` test,`,
2109
+ `} from "@softprobe/e2e";`,
2110
+ ``,
2111
+ `describe(${JSON.stringify(suiteTitle)}, () => {`,
2112
+ ` test(${JSON.stringify(testTitle)}, async ({ app, agent, screen, trace${needsBrowserFixture ? ", browser" : ""} }) => {`,
2113
+ ` await app.open(${JSON.stringify(initialStartPath)});`,
2114
+ ];
2115
+ for (let gIdx = 0; gIdx < groups.length; gIdx += 1) {
2116
+ const group = groups[gIdx];
2117
+ const recordedActions = group.steps
2118
+ .map((s) => convertSemanticStepToE2ERecordedAction(s, extraFixtureFiles))
2119
+ .filter((item) => item !== null);
2120
+ if (recordedActions.length === 0)
2121
+ continue;
2122
+ const sigProbeKey = `${group.instruction}\u0000${group.secretSlots.join(",")}`;
2123
+ const callIndex = callCounts.get(sigProbeKey) ?? 0;
2124
+ callCounts.set(sigProbeKey, callIndex + 1);
2125
+ const keyInfo = buildE2ECacheKeyAndHash({
2126
+ projectId,
2127
+ testId: fullTestId,
2128
+ targetId: targetName,
2129
+ appIdentity,
2130
+ appEnvironment,
2131
+ instruction: group.instruction,
2132
+ secretSlots: group.secretSlots,
2133
+ callIndex,
2134
+ });
2135
+ const endWaitMs = Math.min(120_000, Math.max(10_000, Math.round(group.settleMs + 10_000)));
2136
+ const traceEntryDoc = {
2137
+ schemaVersion: E2E_TRACE_SCHEMA_VERSION,
2138
+ createdAt,
2139
+ payload: {
2140
+ actions: recordedActions,
2141
+ executor: {
2142
+ name: "softprobe-session-compiler",
2143
+ version: "0.1.0",
2144
+ },
2145
+ recordedFor: {
2146
+ testId: fullTestId,
2147
+ targetId: targetName,
2148
+ instructionDigest: keyInfo.instructionDigest,
2149
+ paramsDigest: keyInfo.paramsDigest,
2150
+ callIndex,
2151
+ agent: "default",
2152
+ },
2153
+ summary: group.instruction.slice(0, 300),
2154
+ startPath: group.startPath,
2155
+ endPath: group.endPath,
2156
+ ...(group.endAnchors.length > 0 ? { endAnchors: group.endAnchors } : {}),
2157
+ ...(group.goneAnchors.length > 0 ? { goneAnchors: group.goneAnchors } : {}),
2158
+ endWaitMs,
2159
+ keyedBy: keyInfo.keyedBy,
2160
+ },
2161
+ };
2162
+ cacheFiles.push({
2163
+ relativePath: `.e2e/cache/${keyInfo.keyHash}.json`,
2164
+ content: `${JSON.stringify(traceEntryDoc, null, 2)}\n`,
2165
+ });
2166
+ for (const dialogAction of group.dialogActions) {
2167
+ if (dialogAction.accepted) {
2168
+ const promptArg = dialogAction.promptText?.kind === "literal"
2169
+ ? JSON.stringify(dialogAction.promptText.value)
2170
+ : dialogAction.promptText?.kind === "secret"
2171
+ ? `secrets.get(${JSON.stringify(dialogAction.promptText.slot)})`
2172
+ : "";
2173
+ testLines.push(` browser.onDialog((dialog) => dialog.accept(${promptArg}));`);
2174
+ }
2175
+ else {
2176
+ testLines.push(` browser.onDialog((dialog) => dialog.dismiss());`);
2177
+ }
2178
+ }
2179
+ if (group.secretSlots.length > 0) {
2180
+ const paramKeyBySlot = allocateE2ESecretParamKeys(group.secretSlots);
2181
+ const paramEntries = group.secretSlots.map((slot) => {
2182
+ const paramKey = paramKeyBySlot.get(slot);
2183
+ return `${JSON.stringify(paramKey)}: secrets.get(${JSON.stringify(slot)})`;
2184
+ });
2185
+ testLines.push(` await agent.act(${JSON.stringify(group.instruction)}, {`, ` params: { ${paramEntries.join(", ")} },`, ` });`);
2186
+ }
2187
+ else {
2188
+ testLines.push(` await agent.act(${JSON.stringify(group.instruction)});`);
2189
+ }
2190
+ testLines.push(buildE2EScreenAssertionLine(group));
2191
+ for (let tIdx = 0; tIdx < group.backendTraces.length; tIdx += 1) {
2192
+ const bt = group.backendTraces[tIdx];
2193
+ for (let cIdx = 0; cIdx < bt.outboundCalls.length; cIdx += 1) {
2194
+ const call = bt.outboundCalls[cIdx];
2195
+ const varName = `outbound_${gIdx}_${tIdx}_${cIdx}`;
2196
+ testLines.push(` const ${varName} = await trace.outboundHttp({`, ` triggeredBy: { method: ${JSON.stringify(bt.triggerMethod)}, path: ${formatTriggerPathMatcherCode(bt.triggerPathMatcher)} },`, ` method: ${JSON.stringify(call.method)},`, ` url: ${formatOutboundUrlMatcherCode(call.url)},`, ...(call.status > 0 ? [` status: ${call.status},`] : []), ` });`);
2197
+ if (call.status > 0) {
2198
+ testLines.push(` expect(${varName}.status).toBe(${call.status});`);
2199
+ }
2200
+ const expectedJson = sanitizeJsonForAssertion(call.request.json);
2201
+ if (expectedJson !== undefined && typeof expectedJson === "object" && expectedJson !== null) {
2202
+ testLines.push(` expect(${varName}.request.json).toMatchObject(${JSON.stringify(expectedJson)});`);
2203
+ }
2204
+ }
2205
+ }
2206
+ }
2207
+ testLines.push(` });`, `});`, ``);
2208
+ const files = [
2209
+ ...extraFixtureFiles,
2210
+ {
2211
+ relativePath: testRelPath,
2212
+ content: testLines.join("\n"),
2213
+ },
2214
+ ];
2215
+ if (options.includeConfig !== false) {
2216
+ const configLines = [
2217
+ `import type { E2EConfig } from "e2e";`,
2218
+ `import { softprobeCachedAgent, softprobeReporter, softprobeWeb } from "@softprobe/e2e";`,
2219
+ ``,
2220
+ ];
2221
+ if (bundle.secretSlots.length > 0) {
2222
+ configLines.push(`function requireSecretEnv(primaryEnv: string, fallbackEnv: string): string {`, ` const value = process.env[primaryEnv] ?? process.env[fallbackEnv];`, ` if (!value || value.trim() === "") {`, ` throw new Error(\`Missing required secret environment variable: \${primaryEnv}\`);`, ` }`, ` return value;`, `}`, ``);
2223
+ }
2224
+ configLines.push(`export default {`, ` projectId: ${JSON.stringify(projectId)},`, ` workers: 1,`, ` retries: 0,`, ` tests: "tests/**/*.e2e.ts",`, ` cache: {`, ` dir: ".e2e/cache",`, ` mode: "read-write",`, ` },`, ` agents: {`, ` default: softprobeCachedAgent(),`, ` },`, ...(bundle.secretSlots.length > 0
2225
+ ? [
2226
+ ` secrets: {`,
2227
+ ...bundle.secretSlots.map((slot) => ` ${JSON.stringify(slot)}: () => requireSecretEnv(${JSON.stringify(`SP_SECRET_${slot}`)}, ${JSON.stringify(`E2E_SECRET_${slot}`)}),`),
2228
+ ` },`,
2229
+ ]
2230
+ : []), ` targets: [`, ` {`, ` name: ${JSON.stringify(targetName)},`, ` engine: softprobeWeb({`, ...(options.sinkEndpoint
2231
+ ? [` endpoint: process.env.SOFTPROBE_SINK_ENDPOINT ?? ${JSON.stringify(options.sinkEndpoint)},`]
2232
+ : []), ...(options.workspaceId
2233
+ ? [` workspaceId: process.env.SOFTPROBE_WORKSPACE_ID ?? ${JSON.stringify(options.workspaceId)},`]
2234
+ : []), ...(options.appId
2235
+ ? [` appId: process.env.SOFTPROBE_APP_ID ?? ${JSON.stringify(options.appId)},`]
2236
+ : []), ...(options.store
2237
+ ? [` store: ${JSON.stringify(options.store)},`]
2238
+ : []), ` }),`, ` app: {`, ` url: process.env.APP_URL ?? ${JSON.stringify(defaultTargetUrl)},`, ` identity: ${JSON.stringify(appIdentity)},`, ` environment: ${JSON.stringify(appEnvironment)},`, ` },`, ` },`, ` ],`, ` reporters: [softprobeReporter()],`, `} satisfies E2EConfig;`, ``);
2239
+ files.push({
2240
+ relativePath: "e2e.config.ts",
2241
+ content: configLines.join("\n"),
2242
+ });
2243
+ }
2244
+ return {
2245
+ runner: "e2e",
2246
+ sessionId: bundle.sessionId,
2247
+ projectId,
2248
+ targetName,
2249
+ appIdentity,
2250
+ testId: fullTestId,
2251
+ actionCount: bundle.steps.length,
2252
+ outboundAssertionCount: bundle.outboundAssertionCount,
2253
+ files,
2254
+ cacheFiles,
2255
+ };
2256
+ }
2257
+ // Satisfy e2e WorkerModels.preflight on zero-LLM cached replay while forwarding live models when recording new agent.act steps.
2258
+ export function softprobeCachedAgent(options = {}) {
2259
+ if (options.model !== undefined) {
2260
+ return {
2261
+ model: options.model,
2262
+ ...(options.judge !== undefined ? { judge: options.judge } : {}),
2263
+ ...(options.context !== undefined ? { context: options.context } : {}),
2264
+ };
2265
+ }
2266
+ return {
2267
+ ...(options.context !== undefined ? { context: options.context } : {}),
2268
+ executor: {
2269
+ name: "softprobe-session-replay",
2270
+ version: "0.1.0",
2271
+ async runStep(context) {
2272
+ throw new AgentError("MODEL_UNAVAILABLE", `No cached ActionTrace completed step ${JSON.stringify(context.step.instruction)} and no LLM model was passed to softprobeCachedAgent({ model }). Configure a model in e2e.config.ts to record new agent.act() steps.`);
2273
+ },
2274
+ },
2275
+ };
2276
+ }
2277
+ //# sourceMappingURL=session-compiler.js.map