@midscene/core 1.17.4 → 1.17.5

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 (86) hide show
  1. package/dist/es/agent/agent-report-manager.mjs +28 -5
  2. package/dist/es/agent/agent-report-manager.mjs.map +1 -1
  3. package/dist/es/agent/agent.mjs +2 -2
  4. package/dist/es/agent/agent.mjs.map +1 -1
  5. package/dist/es/agent/utils.mjs +1 -1
  6. package/dist/es/dump/html-utils.mjs +51 -68
  7. package/dist/es/dump/html-utils.mjs.map +1 -1
  8. package/dist/es/dump/report-artifact-publication.mjs +52 -0
  9. package/dist/es/dump/report-artifact-publication.mjs.map +1 -0
  10. package/dist/es/dump/report-artifact-store.mjs +2 -2
  11. package/dist/es/dump/report-artifact-store.mjs.map +1 -1
  12. package/dist/es/dump/report-artifact-writer.mjs +129 -0
  13. package/dist/es/dump/report-artifact-writer.mjs.map +1 -0
  14. package/dist/es/dump/report-session.mjs +229 -0
  15. package/dist/es/dump/report-session.mjs.map +1 -0
  16. package/dist/es/dump/test-report-images.mjs +68 -42
  17. package/dist/es/dump/test-report-images.mjs.map +1 -1
  18. package/dist/es/index.mjs +2 -2
  19. package/dist/es/index.mjs.map +1 -1
  20. package/dist/es/report-cli.mjs +38 -11
  21. package/dist/es/report-cli.mjs.map +1 -1
  22. package/dist/es/report-generator.mjs +2 -1
  23. package/dist/es/report-generator.mjs.map +1 -1
  24. package/dist/es/report-html-template.mjs +1 -1
  25. package/dist/es/report.mjs +152 -159
  26. package/dist/es/report.mjs.map +1 -1
  27. package/dist/es/test-run-report.mjs.map +1 -1
  28. package/dist/es/utils.mjs +1 -1
  29. package/dist/es/yaml/player.mjs +1 -1
  30. package/dist/es/yaml/player.mjs.map +1 -1
  31. package/dist/lib/agent/agent-report-manager.js +27 -4
  32. package/dist/lib/agent/agent-report-manager.js.map +1 -1
  33. package/dist/lib/agent/agent.js +2 -2
  34. package/dist/lib/agent/agent.js.map +1 -1
  35. package/dist/lib/agent/utils.js +1 -1
  36. package/dist/lib/dump/html-utils.js +59 -70
  37. package/dist/lib/dump/html-utils.js.map +1 -1
  38. package/dist/lib/dump/report-artifact-publication.js +89 -0
  39. package/dist/lib/dump/report-artifact-publication.js.map +1 -0
  40. package/dist/lib/dump/report-artifact-store.js +2 -2
  41. package/dist/lib/dump/report-artifact-store.js.map +1 -1
  42. package/dist/lib/dump/report-artifact-writer.js +163 -0
  43. package/dist/lib/dump/report-artifact-writer.js.map +1 -0
  44. package/dist/lib/dump/report-session.js +266 -0
  45. package/dist/lib/dump/report-session.js.map +1 -0
  46. package/dist/lib/dump/test-report-images.js +67 -41
  47. package/dist/lib/dump/test-report-images.js.map +1 -1
  48. package/dist/lib/index.js +3 -0
  49. package/dist/lib/index.js.map +1 -1
  50. package/dist/lib/report-cli.js +37 -10
  51. package/dist/lib/report-cli.js.map +1 -1
  52. package/dist/lib/report-generator.js +2 -1
  53. package/dist/lib/report-generator.js.map +1 -1
  54. package/dist/lib/report-html-template.js +1 -1
  55. package/dist/lib/report.js +152 -153
  56. package/dist/lib/report.js.map +1 -1
  57. package/dist/lib/test-run-report.js.map +1 -1
  58. package/dist/lib/utils.js +1 -1
  59. package/dist/lib/yaml/player.js +1 -1
  60. package/dist/lib/yaml/player.js.map +1 -1
  61. package/dist/types/agent/agent-report-manager.d.ts +4 -1
  62. package/dist/types/agent/agent-report-manager.d.ts.map +1 -1
  63. package/dist/types/agent/agent.d.ts +1 -1
  64. package/dist/types/agent/agent.d.ts.map +1 -1
  65. package/dist/types/dump/html-utils.d.ts +7 -1
  66. package/dist/types/dump/html-utils.d.ts.map +1 -1
  67. package/dist/types/dump/report-artifact-publication.d.ts +5 -0
  68. package/dist/types/dump/report-artifact-publication.d.ts.map +1 -0
  69. package/dist/types/dump/report-artifact-store.d.ts +1 -1
  70. package/dist/types/dump/report-artifact-store.d.ts.map +1 -1
  71. package/dist/types/dump/report-artifact-writer.d.ts +21 -0
  72. package/dist/types/dump/report-artifact-writer.d.ts.map +1 -0
  73. package/dist/types/dump/report-session.d.ts +48 -0
  74. package/dist/types/dump/report-session.d.ts.map +1 -0
  75. package/dist/types/dump/test-report-images.d.ts +5 -2
  76. package/dist/types/dump/test-report-images.d.ts.map +1 -1
  77. package/dist/types/index.d.ts +1 -1
  78. package/dist/types/index.d.ts.map +1 -1
  79. package/dist/types/report-cli.d.ts +2 -1
  80. package/dist/types/report-cli.d.ts.map +1 -1
  81. package/dist/types/report-generator.d.ts.map +1 -1
  82. package/dist/types/report.d.ts +11 -0
  83. package/dist/types/report.d.ts.map +1 -1
  84. package/dist/types/test-run-report.d.ts +2 -2
  85. package/dist/types/test-run-report.d.ts.map +1 -1
  86. package/package.json +2 -2
@@ -141,7 +141,7 @@ async function streamDumpScriptsAsync(filePath, visitor) {
141
141
  const tagEnd = content.indexOf('>');
142
142
  const type = content.slice(0, tagEnd).match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1];
143
143
  return 'midscene_web_dump' === type ? visitor({
144
- openTag: content.slice(0, tagEnd + 1),
144
+ openTag: `${String.fromCharCode(60)}script${content.slice(0, tagEnd + 1)}`,
145
145
  content: content.slice(tagEnd + 1)
146
146
  }) : false;
147
147
  });
@@ -366,78 +366,61 @@ function extractAllDumpScriptsSync(filePath) {
366
366
  });
367
367
  return results;
368
368
  }
369
- function streamDumpScriptsSync(filePath, onMatch) {
370
- const openTagPrefix = '<script type="midscene_web_dump"';
371
- const closeTag = htmlScriptCloseTag();
372
- const fd = (0, external_node_fs_.openSync)(filePath, 'r');
373
- const fileSize = (0, external_node_fs_.statSync)(filePath).size;
374
- const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);
375
- let position = 0;
376
- let leftover = '';
369
+ function streamDumpScriptsSync(filePath, visitor) {
370
+ streamScanTags(filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), (content)=>{
371
+ const end = content.indexOf('>');
372
+ const type = content.slice(0, end).match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1];
373
+ return 'midscene_web_dump' === type ? visitor({
374
+ openTag: `${String.fromCharCode(60)}script${content.slice(0, end + 1)}`,
375
+ content: content.slice(end + 1)
376
+ }) : false;
377
+ });
378
+ }
379
+ function inlineImageElement(content) {
380
+ const end = content.indexOf('>');
381
+ const attributes = content.slice(0, end);
382
+ const type = attributes.match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1];
383
+ const id = attributes.match(/(?:^|\s)data-id="([a-z0-9_-]{1,128})"/i)?.[1];
384
+ return 'midscene-image' === type && id ? {
385
+ id,
386
+ data: unescapeContent(content.slice(end + 1))
387
+ } : void 0;
388
+ }
389
+ function streamInlineReportImages(filePath, visit) {
390
+ streamScanTags(filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), (content)=>{
391
+ const image = inlineImageElement(content);
392
+ return image ? visit(image.id, image.data) : false;
393
+ });
394
+ }
395
+ async function* streamInlineReportImagesAsync(filePath) {
396
+ const open = `${String.fromCharCode(60)}script`;
397
+ const close = htmlScriptCloseTag();
398
+ let pending = '';
377
399
  let capturing = false;
378
- let currentContent = '';
379
- let currentOpenTag = '';
380
- try {
381
- while(position < fileSize){
382
- const bytesRead = (0, external_node_fs_.readSync)(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);
383
- const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);
384
- position += bytesRead;
385
- let searchStart = 0;
386
- while(searchStart < chunk.length)if (capturing) {
387
- const endIdx = chunk.indexOf(closeTag, searchStart);
388
- if (-1 !== endIdx) {
389
- currentContent += chunk.slice(searchStart, endIdx);
390
- const shouldStop = onMatch({
391
- openTag: currentOpenTag,
392
- content: currentContent.trim()
393
- });
394
- if (shouldStop) return;
395
- capturing = false;
396
- currentContent = '';
397
- currentOpenTag = '';
398
- searchStart = endIdx + closeTag.length;
399
- } else {
400
- currentContent += chunk.slice(searchStart, -closeTag.length);
401
- leftover = chunk.slice(-closeTag.length);
402
- break;
403
- }
404
- } else {
405
- const startIdx = chunk.indexOf(openTagPrefix, searchStart);
406
- if (-1 !== startIdx) {
407
- const tagEndIdx = chunk.indexOf('>', startIdx);
408
- if (-1 !== tagEndIdx) {
409
- capturing = true;
410
- currentOpenTag = chunk.slice(startIdx, tagEndIdx + 1);
411
- currentContent = chunk.slice(tagEndIdx + 1);
412
- const endIdx = currentContent.indexOf(closeTag);
413
- if (-1 !== endIdx) {
414
- const shouldStop = onMatch({
415
- openTag: currentOpenTag,
416
- content: currentContent.slice(0, endIdx).trim()
417
- });
418
- if (shouldStop) return;
419
- capturing = false;
420
- currentContent = '';
421
- currentOpenTag = '';
422
- searchStart = tagEndIdx + 1 + endIdx + closeTag.length;
423
- } else {
424
- leftover = currentContent.slice(-closeTag.length);
425
- currentContent = currentContent.slice(0, -closeTag.length);
426
- break;
427
- }
428
- } else {
429
- leftover = chunk.slice(startIdx);
430
- break;
431
- }
432
- } else {
433
- leftover = chunk.slice(-openTagPrefix.length);
400
+ for await (const chunk of (0, external_node_fs_.createReadStream)(filePath, {
401
+ encoding: 'utf8'
402
+ })){
403
+ pending += chunk;
404
+ while(true){
405
+ if (!capturing) {
406
+ const start = pending.indexOf(open);
407
+ if (start < 0) {
408
+ pending = pending.slice(-(open.length - 1));
434
409
  break;
435
410
  }
411
+ pending = pending.slice(start + open.length);
412
+ capturing = true;
436
413
  }
414
+ const end = pending.indexOf(close);
415
+ if (end < 0) break;
416
+ const content = pending.slice(0, end);
417
+ pending = pending.slice(end + close.length);
418
+ capturing = false;
419
+ const image = inlineImageElement(content);
420
+ if (image) yield image;
437
421
  }
438
- } finally{
439
- (0, external_node_fs_.closeSync)(fd);
440
422
  }
423
+ if (capturing) throw new Error(`Unterminated report script in ${filePath}`);
441
424
  }
442
425
  function parseImageScripts(html) {
443
426
  const imageMap = {};
@@ -492,6 +475,6 @@ function generateDumpScriptTag(json, attributes) {
492
475
  if (attributes && Object.keys(attributes).length > 0) attrString = ' ' + Object.entries(attributes).map(([k, v])=>k + '="' + encodeURIComponent(v) + '"').join(' ');
493
476
  return '<script type="midscene_web_dump"' + attrString + '>' + escapeContent(json) + closeTag;
494
477
  }
495
- export { DATA_SCREENSHOT_MODE_ATTR, STREAMING_CHUNK_SIZE, collectImageScriptIds, escapeContent, extractAllDumpScriptsSync, extractImageByIdSync, extractLastDumpScriptSync, extractReportArtifactPathAsync, extractReportArtifactPathSync, extractTestRunReportDumpSync, generateAgentReportComment, generateDumpScriptTag, generateImageScriptTag, generateReportArtifactScriptTag, generateTestRunReportScriptTag, getBaseUrlFixScript, parseDumpScript, parseDumpScriptAttributes, parseImageScripts, streamDumpScriptsAsync, streamDumpScriptsSync, streamImageScriptsToFile, streamScanTags, streamScanTagsAsync, unescapeContent };
478
+ export { DATA_SCREENSHOT_MODE_ATTR, STREAMING_CHUNK_SIZE, collectImageScriptIds, escapeContent, extractAllDumpScriptsSync, extractImageByIdSync, extractLastDumpScriptSync, extractReportArtifactPathAsync, extractReportArtifactPathSync, extractTestRunReportDumpSync, generateAgentReportComment, generateDumpScriptTag, generateImageScriptTag, generateReportArtifactScriptTag, generateTestRunReportScriptTag, getBaseUrlFixScript, parseDumpScript, parseDumpScriptAttributes, parseImageScripts, streamDumpScriptsAsync, streamDumpScriptsSync, streamImageScriptsToFile, streamInlineReportImages, streamInlineReportImagesAsync, streamScanTags, streamScanTagsAsync, unescapeContent };
496
479
 
497
480
  //# sourceMappingURL=html-utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dump/html-utils.mjs","sources":["../../../src/dump/html-utils.ts"],"sourcesContent":["import { closeSync, openSync, readSync, statSync } from 'node:fs';\nimport { open as openAsync } from 'node:fs/promises';\nimport { StringDecoder } from 'node:string_decoder';\nimport {\n REPORT_ARTIFACT_SCRIPT_TYPE,\n assertReportArtifactPath,\n} from '@midscene/shared/report-artifact';\nimport { antiEscapeScriptTag, escapeScriptTag } from '@midscene/shared/utils';\nimport {\n TEST_RUN_REPORT_SCRIPT_TYPE,\n type TestRunReportDump,\n} from '../test-run-report';\nimport type { AIUsageInfo, IReportActionDump, ModelBrief } from '../types';\n\nexport const escapeContent = escapeScriptTag;\nexport const unescapeContent = antiEscapeScriptTag;\n\nfunction cleanHtmlCommentValue(value: unknown): string {\n return String(value ?? 'N/A')\n .replace(/\\0/g, '')\n .replace(/--/g, '- -');\n}\n\nfunction formatModelBriefForAgent(brief: ModelBrief): string {\n const intent = brief.intent || 'default';\n const model = brief.name || 'unknown';\n const description = brief.modelDescription\n ? ` (${brief.modelDescription})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction hasUsageModelInfo(usage?: AIUsageInfo): usage is AIUsageInfo {\n return Boolean(\n usage &&\n (usage.model_name ||\n usage.response_model_name ||\n usage.model_description ||\n usage.intent),\n );\n}\n\nfunction formatUsageModelForAgent(source: string, usage: AIUsageInfo): string {\n const intent = usage.intent || source;\n const model = usage.model_name || usage.response_model_name || 'unknown';\n const description = usage.model_description\n ? ` (${usage.model_description})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction collectUsageModelsForAgent(report: IReportActionDump): string {\n const models = new Map<string, string>();\n const executions = Array.isArray(report.executions) ? report.executions : [];\n for (const execution of executions) {\n const tasks = Array.isArray(execution.tasks) ? execution.tasks : [];\n for (const task of tasks) {\n const taskWithUsage = task as {\n usage?: AIUsageInfo;\n searchAreaUsage?: AIUsageInfo;\n };\n const usages: Array<[string, AIUsageInfo | undefined]> = [\n ['main', taskWithUsage.usage],\n ['searchArea', taskWithUsage.searchAreaUsage],\n ];\n\n for (const [source, usage] of usages) {\n if (!hasUsageModelInfo(usage)) {\n continue;\n }\n const formatted = formatUsageModelForAgent(source, usage);\n models.set(formatted, formatted);\n }\n }\n }\n\n return Array.from(models.values()).join('; ');\n}\n\nexport function generateAgentReportComment(report: IReportActionDump): string {\n const executions = Array.isArray(report.executions) ? report.executions : [];\n const taskCount = executions.reduce(\n (sum, execution) =>\n sum + (Array.isArray(execution.tasks) ? execution.tasks.length : 0),\n 0,\n );\n const modelBriefs = report.modelBriefs?.length\n ? report.modelBriefs.map(formatModelBriefForAgent).join('; ')\n : collectUsageModelsForAgent(report) || 'No model metadata recorded';\n\n const lines = [\n 'For Agent Analysis:',\n `Report: ${cleanHtmlCommentValue(report.groupName)}`,\n `SDK: ${cleanHtmlCommentValue(report.sdkVersion)}`,\n `Device: ${cleanHtmlCommentValue(report.deviceType)}`,\n `Executions: ${executions.length}; Tasks: ${taskCount}`,\n `Models: ${cleanHtmlCommentValue(modelBriefs)}`,\n 'Structured report JSON is stored in script[type=\"midscene_web_dump\"] tags near this comment.',\n 'Screenshots are stored as script[type=\"midscene-image\"] tags or files referenced by screenshot refs.',\n 'For AI analysis, inspect each execution task for type, status, timing, param, output, usage, searchAreaUsage, recorder, and screenshot refs.',\n 'Use the Markdown export when available; it contains the same report context plus image links for agent review.',\n ];\n\n return `\\n<!--\\n${lines.join('\\n')}\\n-->\\n`;\n}\n\nfunction htmlScriptCloseTag(): string {\n // biome-ignore lint/style/useTemplate: keep this token runtime-built for inline report bundles\n return String.fromCharCode(60) + '/script>';\n}\n\n/** Directory reports declare their data entry separately from the Viewer. */\nexport function generateReportArtifactScriptTag(path: string): string {\n assertReportArtifactPath(path);\n return [\n String.fromCharCode(60),\n 'script type=\"',\n REPORT_ARTIFACT_SCRIPT_TYPE,\n '\">',\n JSON.stringify(path),\n htmlScriptCloseTag(),\n ].join('');\n}\n\nfunction reportArtifactPathExtractor(filePath: string) {\n let result: string | undefined;\n return {\n get path() {\n return result;\n },\n visit: (content: string) => {\n const tagEnd = content.indexOf('>');\n const type = content\n .slice(0, tagEnd)\n .match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n if (type !== REPORT_ARTIFACT_SCRIPT_TYPE) return false;\n if (result !== undefined)\n throw new Error(\n `Report contains multiple artifact entries: ${filePath}`,\n );\n const path: unknown = JSON.parse(\n unescapeContent(content.slice(tagEnd + 1)),\n );\n assertReportArtifactPath(path);\n result = path;\n return false;\n },\n };\n}\n\nexport function extractReportArtifactPathSync(\n filePath: string,\n): string | undefined {\n const extractor = reportArtifactPathExtractor(filePath);\n streamScanTags(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n extractor.visit,\n );\n return extractor.path;\n}\n\nexport async function extractReportArtifactPathAsync(\n filePath: string,\n): Promise<string | undefined> {\n const extractor = reportArtifactPathExtractor(filePath);\n await streamScanTagsAsync(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n extractor.visit,\n );\n return extractor.path;\n}\n\n/** Consume complete elements so dump-tag strings in the Viewer are never payloads. */\nexport async function streamDumpScriptsAsync(\n filePath: string,\n visitor: (dump: { openTag: string; content: string }) => boolean,\n): Promise<void> {\n await streamScanTagsAsync(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n (content) => {\n const tagEnd = content.indexOf('>');\n const type = content\n .slice(0, tagEnd)\n .match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n return type === 'midscene_web_dump'\n ? visitor({\n openTag: content.slice(0, tagEnd + 1),\n content: content.slice(tagEnd + 1),\n })\n : false;\n },\n );\n}\n\n/** Avoid raw close tokens: this writer itself is bundled into report HTML. */\nexport function generateTestRunReportScriptTag(\n dump: TestRunReportDump,\n): string {\n return [\n String.fromCharCode(60),\n 'script type=\"',\n TEST_RUN_REPORT_SCRIPT_TYPE,\n '\">\\n',\n escapeScriptTag(JSON.stringify(dump)),\n '\\n',\n htmlScriptCloseTag(),\n '\\n',\n ].join('');\n}\n\nexport function extractTestRunReportDumpSync(\n filePath: string,\n): TestRunReportDump | undefined {\n let result: TestRunReportDump | undefined;\n // Consume executable scripts as whole elements: the embedded viewer itself\n // contains report-writer source with data-tag strings that are not payloads.\n const openTag = `${String.fromCharCode(60)}script`;\n streamScanTags(filePath, openTag, htmlScriptCloseTag(), (content) => {\n const tagEnd = content.indexOf('>');\n const attributes = content.slice(0, tagEnd);\n const type = attributes.match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n if (type !== TEST_RUN_REPORT_SCRIPT_TYPE) return false;\n if (result)\n throw new Error(\n `Report contains multiple Midscene Test dumps: ${filePath}`,\n );\n const parsed = JSON.parse(unescapeContent(content.slice(tagEnd + 1)));\n if (\n parsed?.schemaVersion !== 1 ||\n parsed?.kind !== 'test-runner' ||\n !Array.isArray(parsed.projects)\n )\n throw new Error(`Invalid Midscene Test report dump: ${filePath}`);\n result = parsed;\n return false;\n });\n return result;\n}\n\n/** Chunk size for streaming file operations (64KB) */\nexport const STREAMING_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Callback for processing matched tags during streaming.\n * @param content - The content between open and close tags\n * @returns true to stop scanning, false to continue\n */\ntype TagMatchCallback = (content: string) => boolean;\n\nclass StreamingTagMatcher {\n private leftover = '';\n private capturing = false;\n private currentContent = '';\n\n constructor(\n private readonly openTag: string,\n private readonly closeTag: string,\n private readonly onMatch: TagMatchCallback,\n ) {}\n\n push(nextChunk: string): boolean {\n const chunk = this.leftover + nextChunk;\n this.leftover = '';\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!this.capturing) {\n const startIndex = chunk.indexOf(this.openTag, searchStart);\n if (startIndex === -1) {\n const retainedSuffixLength = Math.max(0, this.openTag.length - 1);\n this.leftover = retainedSuffixLength\n ? chunk.slice(-retainedSuffixLength)\n : '';\n return false;\n }\n this.capturing = true;\n searchStart = startIndex + this.openTag.length;\n }\n\n const endIndex = chunk.indexOf(this.closeTag, searchStart);\n if (endIndex !== -1) {\n this.currentContent += chunk.slice(searchStart, endIndex);\n if (this.onMatch(this.currentContent)) return true;\n this.capturing = false;\n this.currentContent = '';\n searchStart = endIndex + this.closeTag.length;\n continue;\n }\n\n const retainedSuffixLength = Math.max(0, this.closeTag.length - 1);\n const contentEnd = Math.max(\n searchStart,\n chunk.length - retainedSuffixLength,\n );\n this.currentContent += chunk.slice(searchStart, contentEnd);\n this.leftover = chunk.slice(contentEnd);\n return false;\n }\n\n return false;\n }\n}\n\n/**\n * Stream through a file and find tags matching the pattern.\n * Memory usage: O(chunk_size + tag_size), not O(file_size).\n *\n * @param filePath - Absolute path to the file\n * @param openTag - Opening tag to search for\n * @param closeTag - Closing tag\n * @param onMatch - Callback for each matched tag content\n */\nexport function streamScanTags(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): void {\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n let position = 0;\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n matcher.push(decoder.end());\n } finally {\n closeSync(fd);\n }\n}\n\n/** Asynchronously stream tags without blocking the Node.js event loop. */\nexport async function streamScanTagsAsync(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): Promise<void> {\n const handle = await openAsync(filePath, 'r');\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n let position = 0;\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n\n try {\n while (true) {\n const { bytesRead } = await handle.read(\n buffer,\n 0,\n STREAMING_CHUNK_SIZE,\n position,\n );\n if (bytesRead === 0) {\n matcher.push(decoder.end());\n return;\n }\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Synchronously extract a specific image's base64 data from an HTML file by its id.\n * Uses streaming to avoid loading the entire file into memory.\n *\n * @param htmlPath - Absolute path to the HTML file\n * @param imageId - The id of the image to extract\n * @returns The base64 data string, or null if not found\n */\nexport function extractImageByIdSync(\n htmlPath: string,\n imageId: string,\n): string | null {\n const targetTag = `<script type=\"midscene-image\" data-id=\"${imageId}\">`;\n const closeTag = htmlScriptCloseTag();\n\n let result: string | null = null;\n\n streamScanTags(htmlPath, targetTag, closeTag, (content) => {\n result = unescapeContent(content);\n return true; // Stop after first match\n });\n\n return result;\n}\n\n/**\n * Stream image script tags from source file directly to output file.\n * Memory usage: O(single_image_size), not O(all_images_size).\n *\n * @param srcFilePath - Source HTML file path\n * @param destFilePath - Destination file path to append to\n * @param writtenImageIds - IDs already written to the destination\n */\nexport function streamImageScriptsToFile(\n srcFilePath: string,\n destFilePath: string,\n writtenImageIds: Set<string> = new Set(),\n): void {\n const { appendFileSync } = require('node:fs');\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n streamScanTags(srcFilePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (!imageId || writtenImageIds.has(imageId)) {\n return false;\n }\n // Write complete tag immediately to destination, don't accumulate\n appendFileSync(destFilePath, `${openTag}${content}${closeTag}\\n`);\n writtenImageIds.add(imageId);\n return false; // Continue scanning for more tags\n });\n}\n\nfunction parseImageScriptId(contentAfterType: string): string | null {\n const match = /^ data-id=\"([a-z0-9_-]{1,128})\">/i.exec(contentAfterType);\n return match?.[1] ?? null;\n}\n\n/** Collect IDs of real inline image script tags without blocking on a large report. */\nexport async function collectImageScriptIds(\n filePath: string,\n): Promise<Set<string>> {\n const imageIds = new Set<string>();\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n await streamScanTagsAsync(filePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (imageId) imageIds.add(imageId);\n return false;\n });\n return imageIds;\n}\n\n/**\n * Extract the LAST dump script content from HTML file using streaming.\n * Memory usage: O(dump_size), not O(file_size).\n *\n * @param filePath - Absolute path to the HTML file\n * @returns The dump script content (trimmed), or empty string if not found\n */\nexport function extractLastDumpScriptSync(filePath: string): string {\n const openTagPrefix = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n let lastContent = '';\n\n // Custom streaming to handle the special case where open tag has variable attributes\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n\n let position = 0;\n let leftover = '';\n let capturing = false;\n let currentContent = '';\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);\n position += bytesRead;\n\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!capturing) {\n const startIdx = chunk.indexOf(openTagPrefix, searchStart);\n if (startIdx !== -1) {\n // Find the end of the opening tag (the '>' character)\n const tagEndIdx = chunk.indexOf('>', startIdx);\n if (tagEndIdx !== -1) {\n capturing = true;\n currentContent = chunk.slice(tagEndIdx + 1);\n const endIdx = currentContent.indexOf(closeTag);\n if (endIdx !== -1) {\n lastContent = currentContent.slice(0, endIdx).trim();\n capturing = false;\n currentContent = '';\n searchStart = tagEndIdx + 1 + endIdx + closeTag.length;\n } else {\n leftover = currentContent.slice(-closeTag.length);\n currentContent = currentContent.slice(0, -closeTag.length);\n break;\n }\n } else {\n leftover = chunk.slice(startIdx);\n break;\n }\n } else {\n leftover = chunk.slice(-openTagPrefix.length);\n break;\n }\n } else {\n const endIdx = chunk.indexOf(closeTag, searchStart);\n if (endIdx !== -1) {\n currentContent += chunk.slice(searchStart, endIdx);\n lastContent = currentContent.trim();\n capturing = false;\n currentContent = '';\n searchStart = endIdx + closeTag.length;\n } else {\n currentContent += chunk.slice(searchStart, -closeTag.length);\n leftover = chunk.slice(-closeTag.length);\n break;\n }\n }\n }\n }\n } finally {\n closeSync(fd);\n }\n\n return lastContent;\n}\n\n/**\n * Extract ALL dump script contents from an HTML file using streaming.\n * Each entry includes the full opening tag (for attribute extraction) and the content.\n *\n * @param filePath - Absolute path to the HTML file\n * @returns Array of { openTag, content } for each dump script found\n */\nexport function extractAllDumpScriptsSync(\n filePath: string,\n): { openTag: string; content: string }[] {\n const results: { openTag: string; content: string }[] = [];\n streamDumpScriptsSync(filePath, (dumpScript) => {\n results.push(dumpScript);\n return false;\n });\n return results;\n}\n\n/**\n * Stream ALL dump scripts from an HTML file.\n * Calls onMatch for each dump script and keeps memory bounded to a single\n * dump script payload instead of accumulating every dump in memory.\n *\n * @param filePath - Absolute path to the HTML file\n * @param onMatch - Callback for each dump script; return true to stop early\n */\nexport function streamDumpScriptsSync(\n filePath: string,\n onMatch: (dumpScript: { openTag: string; content: string }) => boolean,\n): void {\n const openTagPrefix = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n\n let position = 0;\n let leftover = '';\n let capturing = false;\n let currentContent = '';\n let currentOpenTag = '';\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);\n position += bytesRead;\n\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!capturing) {\n const startIdx = chunk.indexOf(openTagPrefix, searchStart);\n if (startIdx !== -1) {\n const tagEndIdx = chunk.indexOf('>', startIdx);\n if (tagEndIdx !== -1) {\n capturing = true;\n currentOpenTag = chunk.slice(startIdx, tagEndIdx + 1);\n currentContent = chunk.slice(tagEndIdx + 1);\n const endIdx = currentContent.indexOf(closeTag);\n if (endIdx !== -1) {\n const shouldStop = onMatch({\n openTag: currentOpenTag,\n content: currentContent.slice(0, endIdx).trim(),\n });\n if (shouldStop) return;\n capturing = false;\n currentContent = '';\n currentOpenTag = '';\n searchStart = tagEndIdx + 1 + endIdx + closeTag.length;\n } else {\n leftover = currentContent.slice(-closeTag.length);\n currentContent = currentContent.slice(0, -closeTag.length);\n break;\n }\n } else {\n leftover = chunk.slice(startIdx);\n break;\n }\n } else {\n leftover = chunk.slice(-openTagPrefix.length);\n break;\n }\n } else {\n const endIdx = chunk.indexOf(closeTag, searchStart);\n if (endIdx !== -1) {\n currentContent += chunk.slice(searchStart, endIdx);\n const shouldStop = onMatch({\n openTag: currentOpenTag,\n content: currentContent.trim(),\n });\n if (shouldStop) return;\n capturing = false;\n currentContent = '';\n currentOpenTag = '';\n searchStart = endIdx + closeTag.length;\n } else {\n currentContent += chunk.slice(searchStart, -closeTag.length);\n leftover = chunk.slice(-closeTag.length);\n break;\n }\n }\n }\n }\n } finally {\n closeSync(fd);\n }\n}\n\nexport function parseImageScripts(html: string): Record<string, string> {\n const imageMap: Record<string, string> = {};\n const regex =\n /<script type=\"midscene-image\" data-id=\"([^\"]+)\">([\\s\\S]*?)<\\/script>/g;\n\n for (const match of html.matchAll(regex)) {\n const [, id, content] = match;\n imageMap[id] = unescapeContent(content);\n }\n\n return imageMap;\n}\n\nexport function parseDumpScript(html: string): string {\n // Use string search instead of regex to avoid ReDoS vulnerability\n // Find the LAST dump script tag (template may contain similar patterns in bundled JS)\n const scriptOpenTag = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n // Find the last occurrence of the opening tag\n const lastOpenIndex = html.lastIndexOf(scriptOpenTag);\n if (lastOpenIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the end of the opening tag (the '>' character)\n const tagEndIndex = html.indexOf('>', lastOpenIndex);\n if (tagEndIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the closing tag after the opening tag\n const closeIndex = html.indexOf(closeTag, tagEndIndex);\n if (closeIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Extract content between opening and closing tags\n const content = html.substring(tagEndIndex + 1, closeIndex);\n return unescapeContent(content);\n}\n\nexport function parseDumpScriptAttributes(\n html: string,\n): Record<string, string> {\n const regex = /<script type=\"midscene_web_dump\"([^>]*)>/;\n const match = regex.exec(html);\n\n if (!match) {\n return {};\n }\n\n const attrString = match[1];\n const attributes: Record<string, string> = {};\n const attrRegex = /(\\w+)=\"([^\"]*)\"/g;\n\n for (const attrMatch of attrString.matchAll(attrRegex)) {\n const [, key, value] = attrMatch;\n if (key !== 'type') {\n attributes[key] = decodeURIComponent(value);\n }\n }\n\n return attributes;\n}\n\nexport function generateImageScriptTag(id: string, data: string): string {\n // Do not use template string here, will cause bundle error with <script\n const closeTag = htmlScriptCloseTag();\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene-image\" data-id=\"' +\n id +\n '\">' +\n escapeContent(data) +\n closeTag\n );\n}\n\n/**\n * Inline script that fixes relative URL resolution for directory-mode reports.\n *\n * Problem: when a static server (e.g. `npx serve`) serves `name/index.html`\n * at URL `/name` (without trailing slash), relative paths like\n * `./screenshots/xxx.png` resolve to `/screenshots/xxx.png` instead of\n * `/name/screenshots/xxx.png`.\n *\n * Fix: dynamically insert a <base> tag so relative URLs resolve correctly.\n */\n// Do not use template string here, will cause bundle error with <script\n//\n// The closing script tag is built at runtime so bundlers cannot inline the\n// token that would prematurely close the report template's inline app bundle.\n//\n// Do NOT replace this with a string constant, hex escape (\\x3c), or literal\n// string concatenation. Bundlers may optimise those forms back to the unsafe\n// token.\nlet _baseUrlFixScript: string;\nexport function getBaseUrlFixScript(): string {\n if (!_baseUrlFixScript) {\n const close = htmlScriptCloseTag();\n _baseUrlFixScript =\n // biome-ignore lint/style/useTemplate: see above\n '\\n<script>(function(){' +\n 'var p=window.location.pathname;' +\n 'if(p.endsWith(\"/\")||/\\\\.\\\\w+$/.test(p))return;' +\n 'var b=document.createElement(\"base\");' +\n 'b.href=p+\"/\";' +\n 'document.head.insertBefore(b,document.head.firstChild)' +\n '})()' +\n close +\n '\\n';\n }\n return _baseUrlFixScript;\n}\n\n/**\n * Dump-script attribute that records how the report file stores screenshots.\n * Written by the report generator and the merger, read back when deciding\n * whether a report is in directory mode. Kept here, next to dump-tag\n * generation, so the writer and reader share one source of truth.\n */\nexport const DATA_SCREENSHOT_MODE_ATTR = 'data-screenshot-mode';\n\nexport function generateDumpScriptTag(\n json: string,\n attributes?: Record<string, string | number | boolean>,\n): string {\n const closeTag = htmlScriptCloseTag();\n let attrString = '';\n if (attributes && Object.keys(attributes).length > 0) {\n // Do not use template string here, will cause bundle error with <script\n attrString =\n // biome-ignore lint/style/useTemplate: <explanation>\n ' ' +\n Object.entries(attributes)\n // biome-ignore lint/style/useTemplate: <explanation>\n .map(([k, v]) => k + '=\"' + encodeURIComponent(v) + '\"')\n .join(' ');\n }\n\n // Do not use template string here, will cause bundle error with <script\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene_web_dump\"' +\n attrString +\n '>' +\n escapeContent(json) +\n closeTag\n );\n}\n"],"names":["escapeContent","escapeScriptTag","unescapeContent","antiEscapeScriptTag","cleanHtmlCommentValue","value","String","formatModelBriefForAgent","brief","intent","model","description","hasUsageModelInfo","usage","Boolean","formatUsageModelForAgent","source","collectUsageModelsForAgent","report","models","Map","executions","Array","execution","tasks","task","taskWithUsage","usages","formatted","generateAgentReportComment","taskCount","sum","modelBriefs","lines","htmlScriptCloseTag","generateReportArtifactScriptTag","path","assertReportArtifactPath","REPORT_ARTIFACT_SCRIPT_TYPE","JSON","reportArtifactPathExtractor","filePath","result","content","tagEnd","type","undefined","Error","extractReportArtifactPathSync","extractor","streamScanTags","extractReportArtifactPathAsync","streamScanTagsAsync","streamDumpScriptsAsync","visitor","generateTestRunReportScriptTag","dump","TEST_RUN_REPORT_SCRIPT_TYPE","extractTestRunReportDumpSync","openTag","attributes","parsed","STREAMING_CHUNK_SIZE","StreamingTagMatcher","nextChunk","chunk","searchStart","startIndex","retainedSuffixLength","Math","endIndex","contentEnd","closeTag","onMatch","fd","openSync","fileSize","statSync","buffer","Buffer","decoder","StringDecoder","matcher","position","bytesRead","readSync","closeSync","handle","openAsync","extractImageByIdSync","htmlPath","imageId","targetTag","streamImageScriptsToFile","srcFilePath","destFilePath","writtenImageIds","Set","appendFileSync","require","parseImageScriptId","contentAfterType","match","collectImageScriptIds","imageIds","extractLastDumpScriptSync","openTagPrefix","lastContent","leftover","capturing","currentContent","endIdx","startIdx","tagEndIdx","extractAllDumpScriptsSync","results","streamDumpScriptsSync","dumpScript","currentOpenTag","shouldStop","parseImageScripts","html","imageMap","regex","id","parseDumpScript","scriptOpenTag","lastOpenIndex","tagEndIndex","closeIndex","parseDumpScriptAttributes","attrString","attrRegex","attrMatch","key","decodeURIComponent","generateImageScriptTag","data","_baseUrlFixScript","getBaseUrlFixScript","close","DATA_SCREENSHOT_MODE_ATTR","generateDumpScriptTag","json","Object","k","v","encodeURIComponent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcO,MAAMA,gBAAgBC;AACtB,MAAMC,kBAAkBC;AAE/B,SAASC,sBAAsBC,KAAc;IAC3C,OAAOC,OAAOD,SAAS,OACpB,OAAO,CAAC,OAAO,IACf,OAAO,CAAC,OAAO;AACpB;AAEA,SAASE,yBAAyBC,KAAiB;IACjD,MAAMC,SAASD,MAAM,MAAM,IAAI;IAC/B,MAAME,QAAQF,MAAM,IAAI,IAAI;IAC5B,MAAMG,cAAcH,MAAM,gBAAgB,GACtC,CAAC,EAAE,EAAEA,MAAM,gBAAgB,CAAC,CAAC,CAAC,GAC9B;IACJ,OAAO,GAAGC,OAAO,EAAE,EAAEC,QAAQC,aAAa;AAC5C;AAEA,SAASC,kBAAkBC,KAAmB;IAC5C,OAAOC,QACLD,SACGA,CAAAA,MAAM,UAAU,IACfA,MAAM,mBAAmB,IACzBA,MAAM,iBAAiB,IACvBA,MAAM,MAAK;AAEnB;AAEA,SAASE,yBAAyBC,MAAc,EAAEH,KAAkB;IAClE,MAAMJ,SAASI,MAAM,MAAM,IAAIG;IAC/B,MAAMN,QAAQG,MAAM,UAAU,IAAIA,MAAM,mBAAmB,IAAI;IAC/D,MAAMF,cAAcE,MAAM,iBAAiB,GACvC,CAAC,EAAE,EAAEA,MAAM,iBAAiB,CAAC,CAAC,CAAC,G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["import {\n closeSync,\n createReadStream,\n openSync,\n readSync,\n statSync,\n} from 'node:fs';\nimport { open as openAsync } from 'node:fs/promises';\nimport { StringDecoder } from 'node:string_decoder';\nimport {\n REPORT_ARTIFACT_SCRIPT_TYPE,\n assertReportArtifactPath,\n} from '@midscene/shared/report-artifact';\nimport { antiEscapeScriptTag, escapeScriptTag } from '@midscene/shared/utils';\nimport {\n TEST_RUN_REPORT_SCRIPT_TYPE,\n type TestRunReportDump,\n} from '../test-run-report';\nimport type { AIUsageInfo, IReportActionDump, ModelBrief } from '../types';\n\nexport const escapeContent = escapeScriptTag;\nexport const unescapeContent = antiEscapeScriptTag;\n\nfunction cleanHtmlCommentValue(value: unknown): string {\n return String(value ?? 'N/A')\n .replace(/\\0/g, '')\n .replace(/--/g, '- -');\n}\n\nfunction formatModelBriefForAgent(brief: ModelBrief): string {\n const intent = brief.intent || 'default';\n const model = brief.name || 'unknown';\n const description = brief.modelDescription\n ? ` (${brief.modelDescription})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction hasUsageModelInfo(usage?: AIUsageInfo): usage is AIUsageInfo {\n return Boolean(\n usage &&\n (usage.model_name ||\n usage.response_model_name ||\n usage.model_description ||\n usage.intent),\n );\n}\n\nfunction formatUsageModelForAgent(source: string, usage: AIUsageInfo): string {\n const intent = usage.intent || source;\n const model = usage.model_name || usage.response_model_name || 'unknown';\n const description = usage.model_description\n ? ` (${usage.model_description})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction collectUsageModelsForAgent(report: IReportActionDump): string {\n const models = new Map<string, string>();\n const executions = Array.isArray(report.executions) ? report.executions : [];\n for (const execution of executions) {\n const tasks = Array.isArray(execution.tasks) ? execution.tasks : [];\n for (const task of tasks) {\n const taskWithUsage = task as {\n usage?: AIUsageInfo;\n searchAreaUsage?: AIUsageInfo;\n };\n const usages: Array<[string, AIUsageInfo | undefined]> = [\n ['main', taskWithUsage.usage],\n ['searchArea', taskWithUsage.searchAreaUsage],\n ];\n\n for (const [source, usage] of usages) {\n if (!hasUsageModelInfo(usage)) {\n continue;\n }\n const formatted = formatUsageModelForAgent(source, usage);\n models.set(formatted, formatted);\n }\n }\n }\n\n return Array.from(models.values()).join('; ');\n}\n\nexport function generateAgentReportComment(report: IReportActionDump): string {\n const executions = Array.isArray(report.executions) ? report.executions : [];\n const taskCount = executions.reduce(\n (sum, execution) =>\n sum + (Array.isArray(execution.tasks) ? execution.tasks.length : 0),\n 0,\n );\n const modelBriefs = report.modelBriefs?.length\n ? report.modelBriefs.map(formatModelBriefForAgent).join('; ')\n : collectUsageModelsForAgent(report) || 'No model metadata recorded';\n\n const lines = [\n 'For Agent Analysis:',\n `Report: ${cleanHtmlCommentValue(report.groupName)}`,\n `SDK: ${cleanHtmlCommentValue(report.sdkVersion)}`,\n `Device: ${cleanHtmlCommentValue(report.deviceType)}`,\n `Executions: ${executions.length}; Tasks: ${taskCount}`,\n `Models: ${cleanHtmlCommentValue(modelBriefs)}`,\n 'Structured report JSON is stored in script[type=\"midscene_web_dump\"] tags near this comment.',\n 'Screenshots are stored as script[type=\"midscene-image\"] tags or files referenced by screenshot refs.',\n 'For AI analysis, inspect each execution task for type, status, timing, param, output, usage, searchAreaUsage, recorder, and screenshot refs.',\n 'Use the Markdown export when available; it contains the same report context plus image links for agent review.',\n ];\n\n return `\\n<!--\\n${lines.join('\\n')}\\n-->\\n`;\n}\n\nfunction htmlScriptCloseTag(): string {\n // biome-ignore lint/style/useTemplate: keep this token runtime-built for inline report bundles\n return String.fromCharCode(60) + '/script>';\n}\n\n/** Directory reports declare their data entry separately from the Viewer. */\nexport function generateReportArtifactScriptTag(path: string): string {\n assertReportArtifactPath(path);\n return [\n String.fromCharCode(60),\n 'script type=\"',\n REPORT_ARTIFACT_SCRIPT_TYPE,\n '\">',\n JSON.stringify(path),\n htmlScriptCloseTag(),\n ].join('');\n}\n\nfunction reportArtifactPathExtractor(filePath: string) {\n let result: string | undefined;\n return {\n get path() {\n return result;\n },\n visit: (content: string) => {\n const tagEnd = content.indexOf('>');\n const type = content\n .slice(0, tagEnd)\n .match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n if (type !== REPORT_ARTIFACT_SCRIPT_TYPE) return false;\n if (result !== undefined)\n throw new Error(\n `Report contains multiple artifact entries: ${filePath}`,\n );\n const path: unknown = JSON.parse(\n unescapeContent(content.slice(tagEnd + 1)),\n );\n assertReportArtifactPath(path);\n result = path;\n return false;\n },\n };\n}\n\nexport function extractReportArtifactPathSync(\n filePath: string,\n): string | undefined {\n const extractor = reportArtifactPathExtractor(filePath);\n streamScanTags(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n extractor.visit,\n );\n return extractor.path;\n}\n\nexport async function extractReportArtifactPathAsync(\n filePath: string,\n): Promise<string | undefined> {\n const extractor = reportArtifactPathExtractor(filePath);\n await streamScanTagsAsync(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n extractor.visit,\n );\n return extractor.path;\n}\n\n/** Consume complete elements so dump-tag strings in the Viewer are never payloads. */\nexport async function streamDumpScriptsAsync(\n filePath: string,\n visitor: (dump: { openTag: string; content: string }) => boolean,\n): Promise<void> {\n await streamScanTagsAsync(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n (content) => {\n const tagEnd = content.indexOf('>');\n const type = content\n .slice(0, tagEnd)\n .match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n return type === 'midscene_web_dump'\n ? visitor({\n openTag: `${String.fromCharCode(60)}script${content.slice(0, tagEnd + 1)}`,\n content: content.slice(tagEnd + 1),\n })\n : false;\n },\n );\n}\n\n/** Avoid raw close tokens: this writer itself is bundled into report HTML. */\nexport function generateTestRunReportScriptTag(\n dump: TestRunReportDump,\n): string {\n return [\n String.fromCharCode(60),\n 'script type=\"',\n TEST_RUN_REPORT_SCRIPT_TYPE,\n '\">\\n',\n escapeScriptTag(JSON.stringify(dump)),\n '\\n',\n htmlScriptCloseTag(),\n '\\n',\n ].join('');\n}\n\nexport function extractTestRunReportDumpSync(\n filePath: string,\n): TestRunReportDump | undefined {\n let result: TestRunReportDump | undefined;\n // Consume executable scripts as whole elements: the embedded viewer itself\n // contains report-writer source with data-tag strings that are not payloads.\n const openTag = `${String.fromCharCode(60)}script`;\n streamScanTags(filePath, openTag, htmlScriptCloseTag(), (content) => {\n const tagEnd = content.indexOf('>');\n const attributes = content.slice(0, tagEnd);\n const type = attributes.match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n if (type !== TEST_RUN_REPORT_SCRIPT_TYPE) return false;\n if (result)\n throw new Error(\n `Report contains multiple Midscene Test dumps: ${filePath}`,\n );\n const parsed = JSON.parse(unescapeContent(content.slice(tagEnd + 1)));\n if (\n parsed?.schemaVersion !== 1 ||\n parsed?.kind !== 'test-runner' ||\n !Array.isArray(parsed.projects)\n )\n throw new Error(`Invalid Midscene Test report dump: ${filePath}`);\n result = parsed;\n return false;\n });\n return result;\n}\n\n/** Chunk size for streaming file operations (64KB) */\nexport const STREAMING_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Callback for processing matched tags during streaming.\n * @param content - The content between open and close tags\n * @returns true to stop scanning, false to continue\n */\ntype TagMatchCallback = (content: string) => boolean;\n\nclass StreamingTagMatcher {\n private leftover = '';\n private capturing = false;\n private currentContent = '';\n\n constructor(\n private readonly openTag: string,\n private readonly closeTag: string,\n private readonly onMatch: TagMatchCallback,\n ) {}\n\n push(nextChunk: string): boolean {\n const chunk = this.leftover + nextChunk;\n this.leftover = '';\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!this.capturing) {\n const startIndex = chunk.indexOf(this.openTag, searchStart);\n if (startIndex === -1) {\n const retainedSuffixLength = Math.max(0, this.openTag.length - 1);\n this.leftover = retainedSuffixLength\n ? chunk.slice(-retainedSuffixLength)\n : '';\n return false;\n }\n this.capturing = true;\n searchStart = startIndex + this.openTag.length;\n }\n\n const endIndex = chunk.indexOf(this.closeTag, searchStart);\n if (endIndex !== -1) {\n this.currentContent += chunk.slice(searchStart, endIndex);\n if (this.onMatch(this.currentContent)) return true;\n this.capturing = false;\n this.currentContent = '';\n searchStart = endIndex + this.closeTag.length;\n continue;\n }\n\n const retainedSuffixLength = Math.max(0, this.closeTag.length - 1);\n const contentEnd = Math.max(\n searchStart,\n chunk.length - retainedSuffixLength,\n );\n this.currentContent += chunk.slice(searchStart, contentEnd);\n this.leftover = chunk.slice(contentEnd);\n return false;\n }\n\n return false;\n }\n}\n\n/**\n * Stream through a file and find tags matching the pattern.\n * Memory usage: O(chunk_size + tag_size), not O(file_size).\n *\n * @param filePath - Absolute path to the file\n * @param openTag - Opening tag to search for\n * @param closeTag - Closing tag\n * @param onMatch - Callback for each matched tag content\n */\nexport function streamScanTags(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): void {\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n let position = 0;\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n matcher.push(decoder.end());\n } finally {\n closeSync(fd);\n }\n}\n\n/** Asynchronously stream tags without blocking the Node.js event loop. */\nexport async function streamScanTagsAsync(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): Promise<void> {\n const handle = await openAsync(filePath, 'r');\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n let position = 0;\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n\n try {\n while (true) {\n const { bytesRead } = await handle.read(\n buffer,\n 0,\n STREAMING_CHUNK_SIZE,\n position,\n );\n if (bytesRead === 0) {\n matcher.push(decoder.end());\n return;\n }\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Synchronously extract a specific image's base64 data from an HTML file by its id.\n * Uses streaming to avoid loading the entire file into memory.\n *\n * @param htmlPath - Absolute path to the HTML file\n * @param imageId - The id of the image to extract\n * @returns The base64 data string, or null if not found\n */\nexport function extractImageByIdSync(\n htmlPath: string,\n imageId: string,\n): string | null {\n const targetTag = `<script type=\"midscene-image\" data-id=\"${imageId}\">`;\n const closeTag = htmlScriptCloseTag();\n\n let result: string | null = null;\n\n streamScanTags(htmlPath, targetTag, closeTag, (content) => {\n result = unescapeContent(content);\n return true; // Stop after first match\n });\n\n return result;\n}\n\n/**\n * Stream image script tags from source file directly to output file.\n * Memory usage: O(single_image_size), not O(all_images_size).\n *\n * @param srcFilePath - Source HTML file path\n * @param destFilePath - Destination file path to append to\n * @param writtenImageIds - IDs already written to the destination\n */\nexport function streamImageScriptsToFile(\n srcFilePath: string,\n destFilePath: string,\n writtenImageIds: Set<string> = new Set(),\n): void {\n const { appendFileSync } = require('node:fs');\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n streamScanTags(srcFilePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (!imageId || writtenImageIds.has(imageId)) {\n return false;\n }\n // Write complete tag immediately to destination, don't accumulate\n appendFileSync(destFilePath, `${openTag}${content}${closeTag}\\n`);\n writtenImageIds.add(imageId);\n return false; // Continue scanning for more tags\n });\n}\n\nfunction parseImageScriptId(contentAfterType: string): string | null {\n const match = /^ data-id=\"([a-z0-9_-]{1,128})\">/i.exec(contentAfterType);\n return match?.[1] ?? null;\n}\n\n/** Collect IDs of real inline image script tags without blocking on a large report. */\nexport async function collectImageScriptIds(\n filePath: string,\n): Promise<Set<string>> {\n const imageIds = new Set<string>();\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n await streamScanTagsAsync(filePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (imageId) imageIds.add(imageId);\n return false;\n });\n return imageIds;\n}\n\n/**\n * Extract the LAST dump script content from HTML file using streaming.\n * Memory usage: O(dump_size), not O(file_size).\n *\n * @param filePath - Absolute path to the HTML file\n * @returns The dump script content (trimmed), or empty string if not found\n */\nexport function extractLastDumpScriptSync(filePath: string): string {\n const openTagPrefix = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n let lastContent = '';\n\n // Custom streaming to handle the special case where open tag has variable attributes\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n\n let position = 0;\n let leftover = '';\n let capturing = false;\n let currentContent = '';\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);\n position += bytesRead;\n\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!capturing) {\n const startIdx = chunk.indexOf(openTagPrefix, searchStart);\n if (startIdx !== -1) {\n // Find the end of the opening tag (the '>' character)\n const tagEndIdx = chunk.indexOf('>', startIdx);\n if (tagEndIdx !== -1) {\n capturing = true;\n currentContent = chunk.slice(tagEndIdx + 1);\n const endIdx = currentContent.indexOf(closeTag);\n if (endIdx !== -1) {\n lastContent = currentContent.slice(0, endIdx).trim();\n capturing = false;\n currentContent = '';\n searchStart = tagEndIdx + 1 + endIdx + closeTag.length;\n } else {\n leftover = currentContent.slice(-closeTag.length);\n currentContent = currentContent.slice(0, -closeTag.length);\n break;\n }\n } else {\n leftover = chunk.slice(startIdx);\n break;\n }\n } else {\n leftover = chunk.slice(-openTagPrefix.length);\n break;\n }\n } else {\n const endIdx = chunk.indexOf(closeTag, searchStart);\n if (endIdx !== -1) {\n currentContent += chunk.slice(searchStart, endIdx);\n lastContent = currentContent.trim();\n capturing = false;\n currentContent = '';\n searchStart = endIdx + closeTag.length;\n } else {\n currentContent += chunk.slice(searchStart, -closeTag.length);\n leftover = chunk.slice(-closeTag.length);\n break;\n }\n }\n }\n }\n } finally {\n closeSync(fd);\n }\n\n return lastContent;\n}\n\n/**\n * Extract ALL dump script contents from an HTML file using streaming.\n * Each entry includes the full opening tag (for attribute extraction) and the content.\n *\n * @param filePath - Absolute path to the HTML file\n * @returns Array of { openTag, content } for each dump script found\n */\nexport function extractAllDumpScriptsSync(\n filePath: string,\n): { openTag: string; content: string }[] {\n const results: { openTag: string; content: string }[] = [];\n streamDumpScriptsSync(filePath, (dumpScript) => {\n results.push(dumpScript);\n return false;\n });\n return results;\n}\n\n/**\n * Stream ALL dump scripts from an HTML file.\n * Calls onMatch for each dump script and keeps memory bounded to a single\n * dump script payload instead of accumulating every dump in memory.\n *\n * @param filePath - Absolute path to the HTML file\n * @param onMatch - Callback for each dump script; return true to stop early\n */\nexport function streamDumpScriptsSync(\n filePath: string,\n visitor: (dump: { openTag: string; content: string }) => boolean,\n): void {\n streamScanTags(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n (content) => {\n const end = content.indexOf('>');\n const type = content\n .slice(0, end)\n .match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n return type === 'midscene_web_dump'\n ? visitor({\n openTag: `${String.fromCharCode(60)}script${content.slice(0, end + 1)}`,\n content: content.slice(end + 1),\n })\n : false;\n },\n );\n}\n\n/** Visit one inline image at a time; never retain all image bytes from a report. */\nfunction inlineImageElement(\n content: string,\n): { id: string; data: string } | undefined {\n const end = content.indexOf('>');\n const attributes = content.slice(0, end);\n const type = attributes.match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n const id = attributes.match(/(?:^|\\s)data-id=\"([a-z0-9_-]{1,128})\"/i)?.[1];\n return type === 'midscene-image' && id\n ? { id, data: unescapeContent(content.slice(end + 1)) }\n : undefined;\n}\n\nexport function streamInlineReportImages(\n filePath: string,\n visit: (id: string, data: string) => boolean,\n): void {\n streamScanTags(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n (content) => {\n const image = inlineImageElement(content);\n return image ? visit(image.id, image.data) : false;\n },\n );\n}\n\n/** Async backpressure keeps report import memory bounded to one image or Viewer script. */\nexport async function* streamInlineReportImagesAsync(\n filePath: string,\n): AsyncGenerator<{ id: string; data: string }> {\n const open = `${String.fromCharCode(60)}script`;\n const close = htmlScriptCloseTag();\n let pending = '';\n let capturing = false;\n for await (const chunk of createReadStream(filePath, { encoding: 'utf8' })) {\n pending += chunk;\n while (true) {\n if (!capturing) {\n const start = pending.indexOf(open);\n if (start < 0) {\n pending = pending.slice(-(open.length - 1));\n break;\n }\n pending = pending.slice(start + open.length);\n capturing = true;\n }\n const end = pending.indexOf(close);\n if (end < 0) break;\n const content = pending.slice(0, end);\n pending = pending.slice(end + close.length);\n capturing = false;\n const image = inlineImageElement(content);\n if (image) yield image;\n }\n }\n if (capturing) throw new Error(`Unterminated report script in ${filePath}`);\n}\n\nexport function parseImageScripts(html: string): Record<string, string> {\n const imageMap: Record<string, string> = {};\n const regex =\n /<script type=\"midscene-image\" data-id=\"([^\"]+)\">([\\s\\S]*?)<\\/script>/g;\n\n for (const match of html.matchAll(regex)) {\n const [, id, content] = match;\n imageMap[id] = unescapeContent(content);\n }\n\n return imageMap;\n}\n\nexport function parseDumpScript(html: string): string {\n // Use string search instead of regex to avoid ReDoS vulnerability\n // Find the LAST dump script tag (template may contain similar patterns in bundled JS)\n const scriptOpenTag = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n // Find the last occurrence of the opening tag\n const lastOpenIndex = html.lastIndexOf(scriptOpenTag);\n if (lastOpenIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the end of the opening tag (the '>' character)\n const tagEndIndex = html.indexOf('>', lastOpenIndex);\n if (tagEndIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the closing tag after the opening tag\n const closeIndex = html.indexOf(closeTag, tagEndIndex);\n if (closeIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Extract content between opening and closing tags\n const content = html.substring(tagEndIndex + 1, closeIndex);\n return unescapeContent(content);\n}\n\nexport function parseDumpScriptAttributes(\n html: string,\n): Record<string, string> {\n const regex = /<script type=\"midscene_web_dump\"([^>]*)>/;\n const match = regex.exec(html);\n\n if (!match) {\n return {};\n }\n\n const attrString = match[1];\n const attributes: Record<string, string> = {};\n const attrRegex = /(\\w+)=\"([^\"]*)\"/g;\n\n for (const attrMatch of attrString.matchAll(attrRegex)) {\n const [, key, value] = attrMatch;\n if (key !== 'type') {\n attributes[key] = decodeURIComponent(value);\n }\n }\n\n return attributes;\n}\n\nexport function generateImageScriptTag(id: string, data: string): string {\n // Do not use template string here, will cause bundle error with <script\n const closeTag = htmlScriptCloseTag();\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene-image\" data-id=\"' +\n id +\n '\">' +\n escapeContent(data) +\n closeTag\n );\n}\n\n/**\n * Inline script that fixes relative URL resolution for directory-mode reports.\n *\n * Problem: when a static server (e.g. `npx serve`) serves `name/index.html`\n * at URL `/name` (without trailing slash), relative paths like\n * `./screenshots/xxx.png` resolve to `/screenshots/xxx.png` instead of\n * `/name/screenshots/xxx.png`.\n *\n * Fix: dynamically insert a <base> tag so relative URLs resolve correctly.\n */\n// Do not use template string here, will cause bundle error with <script\n//\n// The closing script tag is built at runtime so bundlers cannot inline the\n// token that would prematurely close the report template's inline app bundle.\n//\n// Do NOT replace this with a string constant, hex escape (\\x3c), or literal\n// string concatenation. Bundlers may optimise those forms back to the unsafe\n// token.\nlet _baseUrlFixScript: string;\nexport function getBaseUrlFixScript(): string {\n if (!_baseUrlFixScript) {\n const close = htmlScriptCloseTag();\n _baseUrlFixScript =\n // biome-ignore lint/style/useTemplate: see above\n '\\n<script>(function(){' +\n 'var p=window.location.pathname;' +\n 'if(p.endsWith(\"/\")||/\\\\.\\\\w+$/.test(p))return;' +\n 'var b=document.createElement(\"base\");' +\n 'b.href=p+\"/\";' +\n 'document.head.insertBefore(b,document.head.firstChild)' +\n '})()' +\n close +\n '\\n';\n }\n return _baseUrlFixScript;\n}\n\n/**\n * Dump-script attribute that records how the report file stores screenshots.\n * Written by the report generator and the merger, read back when deciding\n * whether a report is in directory mode. Kept here, next to dump-tag\n * generation, so the writer and reader share one source of truth.\n */\nexport const DATA_SCREENSHOT_MODE_ATTR = 'data-screenshot-mode';\n\nexport function generateDumpScriptTag(\n json: string,\n attributes?: Record<string, string | number | boolean>,\n): string {\n const closeTag = htmlScriptCloseTag();\n let attrString = '';\n if (attributes && Object.keys(attributes).length > 0) {\n // Do not use template string here, will cause bundle error with <script\n attrString =\n // biome-ignore lint/style/useTemplate: <explanation>\n ' ' +\n Object.entries(attributes)\n // biome-ignore lint/style/useTemplate: <explanation>\n .map(([k, v]) => k + '=\"' + encodeURIComponent(v) + '\"')\n .join(' ');\n }\n\n // Do not use template string here, will cause bundle error with <script\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene_web_dump\"' +\n attrString +\n '>' +\n escapeContent(json) +\n closeTag\n );\n}\n"],"names":["escapeContent","escapeScriptTag","unescapeContent","antiEscapeScriptTag","cleanHtmlCommentValue","value","String","formatModelBriefForAgent","brief","intent","model","description","hasUsageModelInfo","usage","Boolean","formatUsageModelForAgent","source","collectUsageModelsForAgent","report","models","Map","executions","Array","execution","tasks","task","taskWithUsage","usages","formatted","generateAgentReportComment","taskCount","sum","modelBriefs","lines","htmlScriptCloseTag","generateReportArtifactScriptTag","path","assertReportArtifactPath","REPORT_ARTIFACT_SCRIPT_TYPE","JSON","reportArtifactPathExtractor","filePath","result","content","tagEnd","type","undefined","Error","extractReportArtifactPathSync","extractor","streamScanTags","extractReportArtifactPathAsync","streamScanTagsAsync","streamDumpScriptsAsync","visitor","generateTestRunReportScriptTag","dump","TEST_RUN_REPORT_SCRIPT_TYPE","extractTestRunReportDumpSync","openTag","attributes","parsed","STREAMING_CHUNK_SIZE","StreamingTagMatcher","nextChunk","chunk","searchStart","startIndex","retainedSuffixLength","Math","endIndex","contentEnd","closeTag","onMatch","fd","openSync","fileSize","statSync","buffer","Buffer","decoder","StringDecoder","matcher","position","bytesRead","readSync","closeSync","handle","openAsync","extractImageByIdSync","htmlPath","imageId","targetTag","streamImageScriptsToFile","srcFilePath","destFilePath","writtenImageIds","Set","appendFileSync","require","parseImageScriptId","contentAfterType","match","collectImageScriptIds","imageIds","extractLastDumpScriptSync","openTagPrefix","lastContent","leftover","capturing","currentContent","endIdx","startIdx","tagEndIdx","extractAllDumpScriptsSync","results","streamDumpScriptsSync","dumpScript","end","inlineImageElement","id","streamInlineReportImages","visit","image","streamInlineReportImagesAsync","open","close","pending","createReadStream","start","parseImageScripts","html","imageMap","regex","parseDumpScript","scriptOpenTag","lastOpenIndex","tagEndIndex","closeIndex","parseDumpScriptAttributes","attrString","attrRegex","attrMatch","key","decodeURIComponent","generateImageScriptTag","data","_baseUrlFixScript","getBaseUrlFixScript","DATA_SCREENSHOT_MODE_ATTR","generateDumpScriptTag","json","Object","k","v","encodeURIComponent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,MAAMA,gBAAgBC;AACtB,MAAMC,kBAAkBC;AAE/B,SAASC,sBAAsBC,KAAc;IAC3C,OAAOC,OAAOD,SAAS,OACpB,OAAO,CAAC,OAAO,IACf,OAAO,CAAC,OAAO;AACpB;AAEA,SAASE,yBAAyBC,KAAiB;IACjD,MAAMC,SAASD,MAAM,MAAM,IAAI;IAC/B,MAAME,QAAQF,MAAM,IAAI,IAAI;IAC5B,MAAMG,cAAcH,MAAM,gBAAgB,GACtC,CAAC,EAAE,EAAEA,MAAM,gBAAgB,CAAC,CAAC,CAAC,GAC9B;IACJ,OAAO,GAAGC,OAAO,EAAE,EAAEC,QAAQ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AAO,IAAI,CAAC5F,YAAY,MAAM,GAAG,GAEjDgF,aAEE,MACAY,OAAO,OAAO,CAAC5F,YAEZ,GAAG,CAAC,CAAC,CAAC6F,GAAGC,EAAE,GAAKD,IAAI,OAAOE,mBAAmBD,KAAK,KACnD,IAAI,CAAC;IAIZ,OAEE,qCACAd,aACA,MACA5I,cAAcuJ,QACd/E;AAEJ"}
@@ -0,0 +1,52 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, existsSync, linkSync, openSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { link as promises_link, rename, rm } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { withReportArtifactLock } from "./report-artifact-store.mjs";
6
+ function publicationLockName(destination) {
7
+ const id = createHash('sha256').update(resolve(destination)).digest('hex');
8
+ return `.report-publish-${id}.lock`;
9
+ }
10
+ function assertAvailable(destination, overwrite) {
11
+ if (!overwrite && existsSync(destination)) throw new Error(`Report artifact already exists: ${destination}`);
12
+ }
13
+ async function publishReportArtifact(prepared, destination, directory, overwrite = false) {
14
+ await withReportArtifactLock(dirname(destination), async ()=>{
15
+ assertAvailable(destination, overwrite);
16
+ if (directory) {
17
+ if (overwrite) await rm(destination, {
18
+ recursive: true,
19
+ force: true
20
+ });
21
+ await rename(prepared, destination);
22
+ } else if (overwrite) await rename(prepared, destination);
23
+ else await promises_link(prepared, destination);
24
+ }, 10000, publicationLockName(destination));
25
+ }
26
+ function publishReportArtifactSync(prepared, destination, directory, overwrite = false) {
27
+ const lockPath = join(dirname(destination), publicationLockName(destination));
28
+ const lock = openSync(lockPath, 'wx');
29
+ try {
30
+ writeFileSync(lock, JSON.stringify({
31
+ pid: process.pid
32
+ }));
33
+ assertAvailable(destination, overwrite);
34
+ if (directory) {
35
+ if (overwrite) rmSync(destination, {
36
+ recursive: true,
37
+ force: true
38
+ });
39
+ renameSync(prepared, destination);
40
+ } else if (overwrite) renameSync(prepared, destination);
41
+ else linkSync(prepared, destination);
42
+ } finally{
43
+ try {
44
+ closeSync(lock);
45
+ } finally{
46
+ unlinkSync(lockPath);
47
+ }
48
+ }
49
+ }
50
+ export { publishReportArtifact, publishReportArtifactSync };
51
+
52
+ //# sourceMappingURL=report-artifact-publication.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dump/report-artifact-publication.mjs","sources":["../../../src/dump/report-artifact-publication.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport {\n closeSync,\n existsSync,\n linkSync,\n openSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\nimport { link, rename, rm } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { withReportArtifactLock } from './report-artifact-store';\n\nfunction publicationLockName(destination: string): string {\n const id = createHash('sha256').update(resolve(destination)).digest('hex');\n return `.report-publish-${id}.lock`;\n}\n\nfunction assertAvailable(destination: string, overwrite: boolean): void {\n if (!overwrite && existsSync(destination))\n throw new Error(`Report artifact already exists: ${destination}`);\n}\n\n/** The prepared artifact and destination share a filesystem. Lock only the\n * final publication, and never remove the other format's sibling artifact. */\nexport async function publishReportArtifact(\n prepared: string,\n destination: string,\n directory: boolean,\n overwrite = false,\n): Promise<void> {\n await withReportArtifactLock(\n dirname(destination),\n async () => {\n assertAvailable(destination, overwrite);\n if (directory) {\n if (overwrite) await rm(destination, { recursive: true, force: true });\n await rename(prepared, destination);\n } else if (overwrite) {\n await rename(prepared, destination);\n } else {\n // Unlike rename, link cannot replace a file created after the check.\n await link(prepared, destination);\n }\n },\n 10_000,\n publicationLockName(destination),\n );\n}\n\nexport function publishReportArtifactSync(\n prepared: string,\n destination: string,\n directory: boolean,\n overwrite = false,\n): void {\n const lockPath = join(dirname(destination), publicationLockName(destination));\n // A synchronous caller must not block the event loop waiting for an async\n // publisher in this same process. A busy destination fails without changes.\n const lock = openSync(lockPath, 'wx');\n try {\n writeFileSync(lock, JSON.stringify({ pid: process.pid }));\n assertAvailable(destination, overwrite);\n if (directory) {\n if (overwrite) rmSync(destination, { recursive: true, force: true });\n renameSync(prepared, destination);\n } else if (overwrite) {\n renameSync(prepared, destination);\n } else {\n linkSync(prepared, destination);\n }\n } finally {\n try {\n closeSync(lock);\n } finally {\n unlinkSync(lockPath);\n }\n }\n}\n"],"names":["publicationLockName","destination","id","createHash","resolve","assertAvailable","overwrite","existsSync","Error","publishReportArtifact","prepared","directory","withReportArtifactLock","dirname","rm","rename","link","publishReportArtifactSync","lockPath","join","lock","openSync","writeFileSync","JSON","process","rmSync","renameSync","linkSync","closeSync","unlinkSync"],"mappings":";;;;;AAeA,SAASA,oBAAoBC,WAAmB;IAC9C,MAAMC,KAAKC,WAAW,UAAU,MAAM,CAACC,QAAQH,cAAc,MAAM,CAAC;IACpE,OAAO,CAAC,gBAAgB,EAAEC,GAAG,KAAK,CAAC;AACrC;AAEA,SAASG,gBAAgBJ,WAAmB,EAAEK,SAAkB;IAC9D,IAAI,CAACA,aAAaC,WAAWN,cAC3B,MAAM,IAAIO,MAAM,CAAC,gCAAgC,EAAEP,aAAa;AACpE;AAIO,eAAeQ,sBACpBC,QAAgB,EAChBT,WAAmB,EACnBU,SAAkB,EAClBL,YAAY,KAAK;IAEjB,MAAMM,uBACJC,QAAQZ,cACR;QACEI,gBAAgBJ,aAAaK;QAC7B,IAAIK,WAAW;YACb,IAAIL,WAAW,MAAMQ,GAAGb,aAAa;gBAAE,WAAW;gBAAM,OAAO;YAAK;YACpE,MAAMc,OAAOL,UAAUT;QACzB,OAAO,IAAIK,WACT,MAAMS,OAAOL,UAAUT;aAGvB,MAAMe,cAAKN,UAAUT;IAEzB,GACA,OACAD,oBAAoBC;AAExB;AAEO,SAASgB,0BACdP,QAAgB,EAChBT,WAAmB,EACnBU,SAAkB,EAClBL,YAAY,KAAK;IAEjB,MAAMY,WAAWC,KAAKN,QAAQZ,cAAcD,oBAAoBC;IAGhE,MAAMmB,OAAOC,SAASH,UAAU;IAChC,IAAI;QACFI,cAAcF,MAAMG,KAAK,SAAS,CAAC;YAAE,KAAKC,QAAQ,GAAG;QAAC;QACtDnB,gBAAgBJ,aAAaK;QAC7B,IAAIK,WAAW;YACb,IAAIL,WAAWmB,OAAOxB,aAAa;gBAAE,WAAW;gBAAM,OAAO;YAAK;YAClEyB,WAAWhB,UAAUT;QACvB,OAAO,IAAIK,WACToB,WAAWhB,UAAUT;aAErB0B,SAASjB,UAAUT;IAEvB,SAAU;QACR,IAAI;YACF2B,UAAUR;QACZ,SAAU;YACRS,WAAWX;QACb;IACF;AACF"}
@@ -26,8 +26,8 @@ async function writeReportArtifactFile(path, content) {
26
26
  });
27
27
  }
28
28
  }
29
- async function withReportArtifactLock(root, publish, timeoutMs = 10000) {
30
- const lockPath = external_node_path_resolve(root, '.report.json.lock');
29
+ async function withReportArtifactLock(root, publish, timeoutMs = 10000, lockFileName = '.report.json.lock') {
30
+ const lockPath = external_node_path_resolve(root, lockFileName);
31
31
  await mkdir(dirname(lockPath), {
32
32
  recursive: true
33
33
  });
@@ -1 +1 @@
1
- {"version":3,"file":"dump/report-artifact-store.mjs","sources":["../../../src/dump/report-artifact-store.ts"],"sourcesContent":["import {\n mkdir,\n open,\n readFile,\n rename,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n type ReportArtifactManifest,\n parseReportArtifactManifest,\n} from '@midscene/shared/report-artifact';\nimport { uuid } from '@midscene/shared/utils';\n\n/** Publish individual files atomically; readers never observe truncated JSON. */\nexport async function writeReportArtifactFile(\n path: string,\n content: string | Uint8Array,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temporary = `${path}.${uuid()}.tmp`;\n try {\n await writeFile(temporary, content, 'utf8');\n await rename(temporary, path);\n } finally {\n await unlink(temporary).catch((error) => {\n if (error.code !== 'ENOENT') throw error;\n });\n }\n}\n\n/** Serialize the entire read/merge/write transaction across Node processes. */\nexport async function withReportArtifactLock<T>(\n root: string,\n publish: () => Promise<T>,\n timeoutMs = 10_000,\n): Promise<T> {\n const lockPath = resolve(root, '.report.json.lock');\n await mkdir(dirname(lockPath), { recursive: true });\n const startedAt = Date.now();\n const acquire = async () => {\n while (true) {\n try {\n return await open(lockPath, 'wx');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n if (Date.now() - startedAt >= timeoutMs) {\n throw new Error(\n `Timed out waiting for report artifact lock ${lockPath}. Another publisher may still be running. If its owner crashed, remove the lock only after confirming that process has exited.`,\n { cause: error },\n );\n }\n await new Promise((resolve) =>\n setTimeout(resolve, 20 + Math.random() * 10),\n );\n }\n }\n };\n const lock = await acquire();\n try {\n await lock.writeFile(JSON.stringify({ pid: process.pid }));\n return await publish();\n } finally {\n // Never expire a live publisher's lock based on elapsed time: a slow\n // filesystem or paused process must not result in two simultaneous owners.\n await lock.close().finally(() => unlink(lockPath));\n }\n}\n\n/** Stores report data without rendering HTML or owning execution resources. */\nexport class ReportArtifactStore {\n private readonly executionPaths = new Map<string, string>();\n private nextExecution = 0;\n private readonly manifest: ReportArtifactManifest;\n private queue: Promise<void> = Promise.resolve();\n private hasPublished = false;\n private finalization?: Promise<void>;\n\n constructor(\n private readonly root: string,\n reportId: string,\n kind: 'agent' | 'test' = 'agent',\n private readonly reuseExistingReport = false,\n entry = 'index.html',\n ) {\n if (!/^[a-zA-Z0-9_-]{1,128}$/.test(reportId))\n throw new Error('Invalid report artifact ID');\n this.manifest = {\n schemaVersion: 1,\n kind,\n status: 'running',\n reportId,\n entry,\n groups: [{ id: reportId, status: 'running', attributes: {}, dumps: [] }],\n };\n }\n\n async writeExecution(\n key: string,\n serialized: string,\n attributes: Record<string, string>,\n ): Promise<void> {\n this.assertOpen();\n this.queue = this.queue.then(async () => {\n let path = this.executionPaths.get(key);\n if (!path) {\n path = `data/${this.manifest.reportId}/${++this.nextExecution}.json`;\n this.executionPaths.set(key, path);\n }\n await writeReportArtifactFile(join(this.root, path), serialized);\n const group = this.manifest.groups[0];\n group.attributes = attributes;\n if (!group.dumps.includes(path)) group.dumps.push(path);\n await this.publish();\n });\n await this.queue;\n }\n\n async writeRunner(serialized: string): Promise<void> {\n this.assertOpen();\n this.queue = this.queue.then(async () => {\n const path = `data/${this.manifest.reportId}/runner.json`;\n await writeReportArtifactFile(join(this.root, path), serialized);\n this.manifest.runner = path;\n await this.publish();\n });\n await this.queue;\n }\n\n async finalize(): Promise<void> {\n if (!this.finalization) {\n this.finalization = this.queue = this.queue.then(async () => {\n this.manifest.groups[0].status = 'complete';\n await this.publish();\n });\n }\n await this.finalization;\n }\n\n private assertOpen(): void {\n if (this.finalization)\n throw new Error('The report artifact stream has been finalized.');\n }\n\n private async publish(): Promise<void> {\n const path = resolve(this.root, 'report.json');\n await withReportArtifactLock(this.root, async () => {\n let manifest = this.manifest;\n if (this.reuseExistingReport || this.hasPublished) {\n const existing = await readFile(path, 'utf8').catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (existing !== undefined) {\n const previous = parseReportArtifactManifest(JSON.parse(existing));\n if (\n previous.kind !== manifest.kind ||\n previous.entry !== manifest.entry\n )\n throw new Error(\n 'Cannot combine reports with different kinds or entries',\n );\n manifest = {\n ...previous,\n groups: [\n ...new Map(\n [...previous.groups, ...manifest.groups].map((group) => [\n group.id,\n group,\n ]),\n ).values(),\n ],\n runner: manifest.runner ?? previous.runner,\n };\n }\n }\n manifest = {\n ...manifest,\n status: manifest.groups.every((group) => group.status === 'complete')\n ? 'complete'\n : 'running',\n };\n parseReportArtifactManifest(manifest);\n await writeReportArtifactFile(path, JSON.stringify(manifest));\n this.hasPublished = true;\n });\n }\n}\n"],"names":["writeReportArtifactFile","path","content","mkdir","dirname","temporary","uuid","writeFile","rename","unlink","error","withReportArtifactLock","root","publish","timeoutMs","lockPath","resolve","startedAt","Date","acquire","open","Error","Promise","setTimeout","Math","lock","JSON","process","ReportArtifactStore","key","serialized","attributes","join","group","manifest","existing","readFile","undefined","previous","parseReportArtifactManifest","Map","reportId","kind","reuseExistingReport","entry"],"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Q;YACnD,IAAI,CAAC,YAAY,GAAG;QACtB;IACF;IA5GA,YACmBtB,IAAY,EAC7B6B,QAAgB,EAChBC,OAAyB,OAAO,EACfC,sBAAsB,KAAK,EAC5CC,QAAQ,YAAY,CACpB;;;QAbF,uBAAiB,kBAAjB;QACA,uBAAQ,iBAAR;QACA,uBAAiB,YAAjB;QACA,uBAAQ,SAAR;QACA,uBAAQ,gBAAR;QACA,uBAAQ,gBAAR;aAGmBhC,IAAI,GAAJA;aAGA+B,mBAAmB,GAAnBA;aAXF,cAAc,GAAG,IAAIH;aAC9B,aAAa,GAAG;aAEhB,KAAK,GAAkBlB,QAAQ,OAAO;aACtC,YAAY,GAAG;QAUrB,IAAI,CAAC,yBAAyB,IAAI,CAACmB,WACjC,MAAM,IAAIpB,MAAM;QAClB,IAAI,CAAC,QAAQ,GAAG;YACd,eAAe;YACfqB;YACA,QAAQ;YACRD;YACAG;YACA,QAAQ;gBAAC;oBAAE,IAAIH;oBAAU,QAAQ;oBAAW,YAAY,CAAC;oBAAG,OAAO,EAAE;gBAAC;aAAE;QAC1E;IACF;AA4FF"}
1
+ {"version":3,"file":"dump/report-artifact-store.mjs","sources":["../../../src/dump/report-artifact-store.ts"],"sourcesContent":["import {\n mkdir,\n open,\n readFile,\n rename,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n type ReportArtifactManifest,\n parseReportArtifactManifest,\n} from '@midscene/shared/report-artifact';\nimport { uuid } from '@midscene/shared/utils';\n\n/** Publish individual files atomically; readers never observe truncated JSON. */\nexport async function writeReportArtifactFile(\n path: string,\n content: string | Uint8Array,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temporary = `${path}.${uuid()}.tmp`;\n try {\n await writeFile(temporary, content, 'utf8');\n await rename(temporary, path);\n } finally {\n await unlink(temporary).catch((error) => {\n if (error.code !== 'ENOENT') throw error;\n });\n }\n}\n\n/** Serialize the entire read/merge/write transaction across Node processes. */\nexport async function withReportArtifactLock<T>(\n root: string,\n publish: () => Promise<T>,\n timeoutMs = 10_000,\n lockFileName = '.report.json.lock',\n): Promise<T> {\n const lockPath = resolve(root, lockFileName);\n await mkdir(dirname(lockPath), { recursive: true });\n const startedAt = Date.now();\n const acquire = async () => {\n while (true) {\n try {\n return await open(lockPath, 'wx');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n if (Date.now() - startedAt >= timeoutMs) {\n throw new Error(\n `Timed out waiting for report artifact lock ${lockPath}. Another publisher may still be running. If its owner crashed, remove the lock only after confirming that process has exited.`,\n { cause: error },\n );\n }\n await new Promise((resolve) =>\n setTimeout(resolve, 20 + Math.random() * 10),\n );\n }\n }\n };\n const lock = await acquire();\n try {\n await lock.writeFile(JSON.stringify({ pid: process.pid }));\n return await publish();\n } finally {\n // Never expire a live publisher's lock based on elapsed time: a slow\n // filesystem or paused process must not result in two simultaneous owners.\n await lock.close().finally(() => unlink(lockPath));\n }\n}\n\n/** Stores report data without rendering HTML or owning execution resources. */\nexport class ReportArtifactStore {\n private readonly executionPaths = new Map<string, string>();\n private nextExecution = 0;\n private readonly manifest: ReportArtifactManifest;\n private queue: Promise<void> = Promise.resolve();\n private hasPublished = false;\n private finalization?: Promise<void>;\n\n constructor(\n private readonly root: string,\n reportId: string,\n kind: 'agent' | 'test' = 'agent',\n private readonly reuseExistingReport = false,\n entry = 'index.html',\n ) {\n if (!/^[a-zA-Z0-9_-]{1,128}$/.test(reportId))\n throw new Error('Invalid report artifact ID');\n this.manifest = {\n schemaVersion: 1,\n kind,\n status: 'running',\n reportId,\n entry,\n groups: [{ id: reportId, status: 'running', attributes: {}, dumps: [] }],\n };\n }\n\n async writeExecution(\n key: string,\n serialized: string,\n attributes: Record<string, string>,\n ): Promise<void> {\n this.assertOpen();\n this.queue = this.queue.then(async () => {\n let path = this.executionPaths.get(key);\n if (!path) {\n path = `data/${this.manifest.reportId}/${++this.nextExecution}.json`;\n this.executionPaths.set(key, path);\n }\n await writeReportArtifactFile(join(this.root, path), serialized);\n const group = this.manifest.groups[0];\n group.attributes = attributes;\n if (!group.dumps.includes(path)) group.dumps.push(path);\n await this.publish();\n });\n await this.queue;\n }\n\n async writeRunner(serialized: string): Promise<void> {\n this.assertOpen();\n this.queue = this.queue.then(async () => {\n const path = `data/${this.manifest.reportId}/runner.json`;\n await writeReportArtifactFile(join(this.root, path), serialized);\n this.manifest.runner = path;\n await this.publish();\n });\n await this.queue;\n }\n\n async finalize(): Promise<void> {\n if (!this.finalization) {\n this.finalization = this.queue = this.queue.then(async () => {\n this.manifest.groups[0].status = 'complete';\n await this.publish();\n });\n }\n await this.finalization;\n }\n\n private assertOpen(): void {\n if (this.finalization)\n throw new Error('The report artifact stream has been finalized.');\n }\n\n private async publish(): Promise<void> {\n const path = resolve(this.root, 'report.json');\n await withReportArtifactLock(this.root, async () => {\n let manifest = this.manifest;\n if (this.reuseExistingReport || this.hasPublished) {\n const existing = await readFile(path, 'utf8').catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (existing !== undefined) {\n const previous = parseReportArtifactManifest(JSON.parse(existing));\n if (\n previous.kind !== manifest.kind ||\n previous.entry !== manifest.entry\n )\n throw new Error(\n 'Cannot combine reports with different kinds or entries',\n );\n manifest = {\n ...previous,\n groups: [\n ...new Map(\n [...previous.groups, ...manifest.groups].map((group) => [\n group.id,\n group,\n ]),\n ).values(),\n ],\n runner: manifest.runner ?? previous.runner,\n };\n }\n }\n manifest = {\n ...manifest,\n status: manifest.groups.every((group) => group.status === 'complete')\n ? 'complete'\n : 'running',\n };\n parseReportArtifactManifest(manifest);\n await writeReportArtifactFile(path, JSON.stringify(manifest));\n this.hasPublished = true;\n });\n }\n}\n"],"names":["writeReportArtifactFile","path","content","mkdir","dirname","temporary","uuid","writeFile","rename","unlink","error","withReportArtifactLock","root","publish","timeoutMs","lockFileName","lockPath","resolve","startedAt","Date","acquire","open","Error","Promise","setTimeout","Math","lock","JSON","process","ReportArtifactStore","key","serialized","attributes","join","group","manifest","existing","readFile","undefined","previous","parseReportArtifactManifest","Map","reportId","kind","reuseExistingReport","entry"],"mappings":";;;;;;;;;;;;;;AAgBO,eAAeA,wBACpBC,IAAY,EACZC,OAA4B;IAE5B,MAAMC,MAAMC,QAAQH,OAAO;QAAE,WAAW;IAAK;IAC7C,MAAMI,YAAY,GAAGJ,KAAK,CAAC,EAAEK,OAAO,IAAI,CAAC;IACzC,IAAI;QACF,MAAMC,UAAUF,WAAWH,SAAS;QACpC,MAAMM,OAAOH,WAAWJ;IAC1B,SAAU;QACR,MAAMQ,OAAOJ,WAAW,KAAK,CAAC,CAACK;YAC7B,IAAIA,AAAe,aAAfA,MAAM,IAAI,EAAe,MAAMA;QACrC;IACF;AACF;AAGO,eAAeC,uBACpBC,IAAY,EACZC,OAAyB,EACzBC,YAAY,KAAM,EAClBC,eAAe,mBAAmB;IAElC,MAAMC,WAAWC,2BAAQL,MAAMG;IAC/B,MAAMZ,MAAMC,QAAQY,WAAW;QAAE,WAAW;IAAK;IACjD,MAAME,YAAYC,KAAK,GAAG;IAC1B,MAAMC,UAAU;QACd,MAAO,KACL,IAAI;YACF,OAAO,MAAMC,cAAKL,UAAU;QAC9B,EAAE,OAAON,OAAO;YACd,IAAKA,AAAyC,aAAzCA,MAAgC,IAAI,EAAe,MAAMA;YAC9D,IAAIS,KAAK,GAAG,KAAKD,aAAaJ,WAC5B,MAAM,IAAIQ,MACR,CAAC,2CAA2C,EAAEN,SAAS,8HAA8H,CAAC,EACtL;gBAAE,OAAON;YAAM;YAGnB,MAAM,IAAIa,QAAQ,CAACN,UACjBO,WAAWP,SAAS,KAAKQ,AAAgB,KAAhBA,KAAK,MAAM;QAExC;IAEJ;IACA,MAAMC,OAAO,MAAMN;IACnB,IAAI;QACF,MAAMM,KAAK,SAAS,CAACC,KAAK,SAAS,CAAC;YAAE,KAAKC,QAAQ,GAAG;QAAC;QACvD,OAAO,MAAMf;IACf,SAAU;QAGR,MAAMa,KAAK,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,AAAiB,eAAjBA,MAAM,MAAM,IACjD,aACA;YACN;YACAM,4BAA4BL;YAC5B,MAAMnC,wBAAwBC,MAAM0B,KAAK,SAAS,CAACQ;YACnD,IAAI,CAAC,YAAY,GAAG;QACtB;IACF;IA5GA,YACmBvB,IAAY,EAC7B8B,QAAgB,EAChBC,OAAyB,OAAO,EACfC,sBAAsB,KAAK,EAC5CC,QAAQ,YAAY,CACpB;;;QAbF,uBAAiB,kBAAjB;QACA,uBAAQ,iBAAR;QACA,uBAAiB,YAAjB;QACA,uBAAQ,SAAR;QACA,uBAAQ,gBAAR;QACA,uBAAQ,gBAAR;aAGmBjC,IAAI,GAAJA;aAGAgC,mBAAmB,GAAnBA;aAXF,cAAc,GAAG,IAAIH;aAC9B,aAAa,GAAG;aAEhB,KAAK,GAAkBlB,QAAQ,OAAO;aACtC,YAAY,GAAG;QAUrB,IAAI,CAAC,yBAAyB,IAAI,CAACmB,WACjC,MAAM,IAAIpB,MAAM;QAClB,IAAI,CAAC,QAAQ,GAAG;YACd,eAAe;YACfqB;YACA,QAAQ;YACRD;YACAG;YACA,QAAQ;gBAAC;oBAAE,IAAIH;oBAAU,QAAQ;oBAAW,YAAY,CAAC;oBAAG,OAAO,EAAE;gBAAC;aAAE;QAC1E;IACF;AA4FF"}
@@ -0,0 +1,129 @@
1
+ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { appendFile, mkdir, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { parseReportArtifactManifest } from "@midscene/shared/report-artifact";
5
+ import { uuid } from "@midscene/shared/utils";
6
+ import { getReportTpl, reportHTMLContent } from "../utils.mjs";
7
+ import { generateReportArtifactScriptTag, generateTestRunReportScriptTag, getBaseUrlFixScript } from "./html-utils.mjs";
8
+ import { writeReportArtifactFile } from "./report-artifact-store.mjs";
9
+ import { TestReportImages } from "./test-report-images.mjs";
10
+ function _define_property(obj, key, value) {
11
+ if (key in obj) Object.defineProperty(obj, key, {
12
+ value: value,
13
+ enumerable: true,
14
+ configurable: true,
15
+ writable: true
16
+ });
17
+ else obj[key] = value;
18
+ return obj;
19
+ }
20
+ class ReportArtifactWriter {
21
+ get template() {
22
+ const template = getReportTpl();
23
+ const end = template.lastIndexOf('</html>');
24
+ return (end < 0 ? template : template.slice(0, end)) + (this.external ? getBaseUrlFixScript() : '');
25
+ }
26
+ async initialize() {
27
+ await mkdir(dirname(this.entry), {
28
+ recursive: true
29
+ });
30
+ await writeFile(this.entry, this.template);
31
+ }
32
+ initializeSync() {
33
+ mkdirSync(dirname(this.entry), {
34
+ recursive: true
35
+ });
36
+ writeFileSync(this.entry, this.template);
37
+ }
38
+ group(id, attributes) {
39
+ if (this.manifest.groups.some((group)=>group.id === id)) throw new Error(`Duplicate report group: ${id}`);
40
+ const path = `data/group-${this.manifest.groups.length + 1}/1.json`;
41
+ this.manifest.groups.push({
42
+ id,
43
+ status: 'complete',
44
+ attributes: {
45
+ ...attributes,
46
+ 'data-screenshot-mode': 'directory'
47
+ },
48
+ dumps: [
49
+ path
50
+ ]
51
+ });
52
+ return join(dirname(this.entry), path);
53
+ }
54
+ inlineGroup(id, attributes, serialized) {
55
+ return reportHTMLContent({
56
+ dumpString: serialized,
57
+ attributes: {
58
+ ...attributes,
59
+ 'data-group-id': id,
60
+ 'data-screenshot-mode': 'inline',
61
+ 'data-report-kind': this.manifest.kind
62
+ }
63
+ }, void 0, void 0, false);
64
+ }
65
+ async addGroup(id, serialized, sourcePath, attributes, origins) {
66
+ const rewritten = await this.images.rewriteAsync(serialized, sourcePath, origins);
67
+ if (this.external) await writeReportArtifactFile(this.group(id, attributes), rewritten);
68
+ else await appendFile(this.entry, this.inlineGroup(id, attributes, rewritten));
69
+ }
70
+ addGroupSync(id, serialized, sourcePath, attributes, origins) {
71
+ const rewritten = this.images.rewriteSync(serialized, sourcePath, origins);
72
+ if (this.external) {
73
+ const file = this.group(id, attributes);
74
+ mkdirSync(dirname(file), {
75
+ recursive: true
76
+ });
77
+ writeFileSync(file, rewritten);
78
+ } else appendFileSync(this.entry, this.inlineGroup(id, attributes, rewritten));
79
+ }
80
+ footer(runner, comment) {
81
+ const data = this.external ? generateReportArtifactScriptTag('report.json') : runner ? generateTestRunReportScriptTag(runner) : '';
82
+ return `${data}${comment}\n</html>\n`;
83
+ }
84
+ async finish(runner, comment = '') {
85
+ if (this.external) {
86
+ if (runner) {
87
+ this.manifest.runner = 'data/runner.json';
88
+ await writeReportArtifactFile(join(dirname(this.entry), this.manifest.runner), JSON.stringify(runner));
89
+ }
90
+ parseReportArtifactManifest(this.manifest);
91
+ await writeReportArtifactFile(join(dirname(this.entry), 'report.json'), JSON.stringify(this.manifest));
92
+ }
93
+ await appendFile(this.entry, this.footer(runner, comment));
94
+ }
95
+ finishSync(runner, comment = '') {
96
+ if (this.external) {
97
+ if (runner) {
98
+ this.manifest.runner = 'data/runner.json';
99
+ mkdirSync(join(dirname(this.entry), 'data'), {
100
+ recursive: true
101
+ });
102
+ writeFileSync(join(dirname(this.entry), this.manifest.runner), JSON.stringify(runner));
103
+ }
104
+ parseReportArtifactManifest(this.manifest);
105
+ writeFileSync(join(dirname(this.entry), 'report.json'), JSON.stringify(this.manifest));
106
+ }
107
+ appendFileSync(this.entry, this.footer(runner, comment));
108
+ }
109
+ constructor(entry, external, kind, reportId = uuid()){
110
+ _define_property(this, "entry", void 0);
111
+ _define_property(this, "external", void 0);
112
+ _define_property(this, "manifest", void 0);
113
+ _define_property(this, "images", void 0);
114
+ this.entry = entry;
115
+ this.external = external;
116
+ this.manifest = {
117
+ schemaVersion: 1,
118
+ kind,
119
+ reportId,
120
+ entry: basename(entry),
121
+ status: 'complete',
122
+ groups: []
123
+ };
124
+ this.images = new TestReportImages(entry, external);
125
+ }
126
+ }
127
+ export { ReportArtifactWriter };
128
+
129
+ //# sourceMappingURL=report-artifact-writer.mjs.map