@midscene/core 1.17.3-beta-20261029072240.0 → 1.17.3

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 (69) hide show
  1. package/dist/es/agent/task-builder.mjs +1 -2
  2. package/dist/es/agent/task-builder.mjs.map +1 -1
  3. package/dist/es/agent/utils.mjs +1 -1
  4. package/dist/es/dump/execution-recorder.mjs +70 -0
  5. package/dist/es/dump/execution-recorder.mjs.map +1 -0
  6. package/dist/es/dump/html-utils.mjs +51 -1
  7. package/dist/es/dump/html-utils.mjs.map +1 -1
  8. package/dist/es/dump/report-artifact-reader.mjs +85 -0
  9. package/dist/es/dump/report-artifact-reader.mjs.map +1 -0
  10. package/dist/es/dump/report-artifact-store.mjs +164 -0
  11. package/dist/es/dump/report-artifact-store.mjs.map +1 -0
  12. package/dist/es/dump/screenshot-store.mjs +40 -15
  13. package/dist/es/dump/screenshot-store.mjs.map +1 -1
  14. package/dist/es/dump/test-report-images.mjs +120 -0
  15. package/dist/es/dump/test-report-images.mjs.map +1 -0
  16. package/dist/es/report-cli.mjs +8 -7
  17. package/dist/es/report-cli.mjs.map +1 -1
  18. package/dist/es/report-generator.mjs +56 -47
  19. package/dist/es/report-generator.mjs.map +1 -1
  20. package/dist/es/report-html-template.mjs +1 -1
  21. package/dist/es/report.mjs +29 -55
  22. package/dist/es/report.mjs.map +1 -1
  23. package/dist/es/test-run-report.mjs.map +1 -1
  24. package/dist/es/utils.mjs +1 -1
  25. package/dist/lib/agent/task-builder.js +1 -2
  26. package/dist/lib/agent/task-builder.js.map +1 -1
  27. package/dist/lib/agent/utils.js +1 -1
  28. package/dist/lib/dump/execution-recorder.js +104 -0
  29. package/dist/lib/dump/execution-recorder.js.map +1 -0
  30. package/dist/lib/dump/html-utils.js +67 -5
  31. package/dist/lib/dump/html-utils.js.map +1 -1
  32. package/dist/lib/dump/report-artifact-reader.js +134 -0
  33. package/dist/lib/dump/report-artifact-reader.js.map +1 -0
  34. package/dist/lib/dump/report-artifact-store.js +204 -0
  35. package/dist/lib/dump/report-artifact-store.js.map +1 -0
  36. package/dist/lib/dump/screenshot-store.js +42 -14
  37. package/dist/lib/dump/screenshot-store.js.map +1 -1
  38. package/dist/lib/dump/test-report-images.js +154 -0
  39. package/dist/lib/dump/test-report-images.js.map +1 -0
  40. package/dist/lib/report-cli.js +8 -7
  41. package/dist/lib/report-cli.js.map +1 -1
  42. package/dist/lib/report-generator.js +54 -45
  43. package/dist/lib/report-generator.js.map +1 -1
  44. package/dist/lib/report-html-template.js +1 -1
  45. package/dist/lib/report.js +54 -56
  46. package/dist/lib/report.js.map +1 -1
  47. package/dist/lib/test-run-report.js.map +1 -1
  48. package/dist/lib/utils.js +1 -1
  49. package/dist/types/agent/task-builder.d.ts.map +1 -1
  50. package/dist/types/dump/execution-recorder.d.ts +23 -0
  51. package/dist/types/dump/execution-recorder.d.ts.map +1 -0
  52. package/dist/types/dump/html-utils.d.ts +9 -0
  53. package/dist/types/dump/html-utils.d.ts.map +1 -1
  54. package/dist/types/dump/report-artifact-reader.d.ts +19 -0
  55. package/dist/types/dump/report-artifact-reader.d.ts.map +1 -0
  56. package/dist/types/dump/report-artifact-store.d.ts +22 -0
  57. package/dist/types/dump/report-artifact-store.d.ts.map +1 -0
  58. package/dist/types/dump/screenshot-store.d.ts +6 -0
  59. package/dist/types/dump/screenshot-store.d.ts.map +1 -1
  60. package/dist/types/dump/test-report-images.d.ts +14 -0
  61. package/dist/types/dump/test-report-images.d.ts.map +1 -0
  62. package/dist/types/report-cli.d.ts.map +1 -1
  63. package/dist/types/report-generator.d.ts +4 -3
  64. package/dist/types/report-generator.d.ts.map +1 -1
  65. package/dist/types/report.d.ts +3 -0
  66. package/dist/types/report.d.ts.map +1 -1
  67. package/dist/types/test-run-report.d.ts +2 -0
  68. package/dist/types/test-run-report.d.ts.map +1 -1
  69. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"dump/html-utils.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/dump/html-utils.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { closeSync, openSync, readSync, statSync } from 'node:fs';\nimport { open as openAsync } from 'node:fs/promises';\nimport { StringDecoder } from 'node:string_decoder';\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/** 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":["__webpack_require__","definition","key","Object","obj","prop","Symbol","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","generateTestRunReportScriptTag","dump","TEST_RUN_REPORT_SCRIPT_TYPE","JSON","extractTestRunReportDumpSync","filePath","result","openTag","streamScanTags","content","tagEnd","attributes","type","Error","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","streamScanTagsAsync","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","decodeURIComponent","generateImageScriptTag","data","_baseUrlFixScript","getBaseUrlFixScript","close","DATA_SCREENSHOT_MODE_ATTR","generateDumpScriptTag","json","k","v","encodeURIComponent"],"mappings":";;;;;;;;;;;;;;;;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAA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BACdT,IAAY;QAEZ,MAAME,QAAQ;QACd,MAAMrB,QAAQqB,MAAM,IAAI,CAACF;QAEzB,IAAI,CAACnB,OACH,OAAO,CAAC;QAGV,MAAM6B,aAAa7B,KAAK,CAAC,EAAE;QAC3B,MAAM7C,aAAqC,CAAC;QAC5C,MAAM2E,YAAY;QAElB,KAAK,MAAMC,aAAaF,WAAW,QAAQ,CAACC,WAAY;YACtD,MAAM,GAAG9H,KAAKU,MAAM,GAAGqH;YACvB,IAAI/H,AAAQ,WAARA,KACFmD,UAAU,CAACnD,IAAI,GAAGgI,mBAAmBtH;QAEzC;QAEA,OAAOyC;IACT;IAEO,SAAS8E,uBAAuBX,EAAU,EAAEY,IAAY;QAE7D,MAAMjE,WAAW1B;QACjB,OAEE,4CACA+E,KACA,OACAjH,cAAc6H,QACdjE;IAEJ;IAoBA,IAAIkE;IACG,SAASC;QACd,IAAI,CAACD,mBAAmB;YACtB,MAAME,QAAQ9F;YACd4F,oBAEE,oNAOAE,QACA;QACJ;QACA,OAAOF;IACT;IAQO,MAAMG,4BAA4B;IAElC,SAASC,sBACdC,IAAY,EACZrF,UAAsD;QAEtD,MAAMc,WAAW1B;QACjB,IAAIsF,aAAa;QACjB,IAAI1E,cAAclD,OAAO,IAAI,CAACkD,YAAY,MAAM,GAAG,GAEjD0E,aAEE,MACA5H,OAAO,OAAO,CAACkD,YAEZ,GAAG,CAAC,CAAC,CAACsF,GAAGC,EAAE,GAAKD,IAAI,OAAOE,mBAAmBD,KAAK,KACnD,IAAI,CAAC;QAIZ,OAEE,qCACAb,aACA,MACAxH,cAAcmI,QACdvE;IAEJ"}
1
+ {"version":3,"file":"dump/html-utils.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/dump/html-utils.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","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":["__webpack_require__","definition","key","Object","obj","prop","Symbol","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","decodeURIComponent","generateImageScriptTag","data","_baseUrlFixScript","getBaseUrlFixScript","close","DATA_SCREENSHOT_MODE_ATTR","generateDumpScriptTag","json","k","v","encodeURIComponent"],"mappings":";;;;;;;;;;;;;;;;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG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AAO,OAAO,CAACgE,YAEZ,GAAG,CAAC,CAAC,CAACmF,GAAGC,EAAE,GAAKD,IAAI,OAAOE,mBAAmBD,KAAK,KACnD,IAAI,CAAC;QAIZ,OAEE,qCACAb,aACA,MACAnI,cAAc8I,QACdtE;IAEJ"}
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ readReportArtifactManifestAsync: ()=>readReportArtifactManifestAsync,
28
+ readReportDumpScripts: ()=>readReportDumpScripts,
29
+ streamReportDumpScripts: ()=>streamReportDumpScripts,
30
+ readReportRunnerDump: ()=>readReportRunnerDump,
31
+ readReportArtifactManifest: ()=>readReportArtifactManifest,
32
+ readReportActionDump: ()=>readReportActionDump
33
+ });
34
+ const external_node_fs_namespaceObject = require("node:fs");
35
+ const promises_namespaceObject = require("node:fs/promises");
36
+ const external_node_path_namespaceObject = require("node:path");
37
+ const report_artifact_namespaceObject = require("@midscene/shared/report-artifact");
38
+ const utils_namespaceObject = require("@midscene/shared/utils");
39
+ const external_html_utils_js_namespaceObject = require("./html-utils.js");
40
+ async function readReportArtifactManifestAsync(reportPath) {
41
+ const manifestPath = (0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(reportPath), 'report.json');
42
+ const exists = await (0, promises_namespaceObject.stat)(manifestPath).then(()=>true).catch((error)=>{
43
+ if ('ENOENT' === error.code) return false;
44
+ throw error;
45
+ });
46
+ if (!exists) return;
47
+ const entry = await (0, external_html_utils_js_namespaceObject.extractReportArtifactPathAsync)(reportPath);
48
+ if (!entry) return;
49
+ const manifest = (0, report_artifact_namespaceObject.parseReportArtifactManifest)(JSON.parse(await (0, promises_namespaceObject.readFile)((0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(reportPath), entry), 'utf8')));
50
+ if (manifest.entry !== (0, external_node_path_namespaceObject.basename)(reportPath)) throw new Error('Report entry does not match its artifact manifest');
51
+ return manifest;
52
+ }
53
+ async function readReportActionDump(reportPath) {
54
+ let base;
55
+ const executions = new Map();
56
+ let anonymous = 0;
57
+ const collect = (content)=>{
58
+ const parsed = JSON.parse(content);
59
+ if (!parsed || !Array.isArray(parsed.executions)) throw new Error(`Invalid report execution data: ${reportPath}`);
60
+ base = parsed;
61
+ for (const execution of parsed.executions)executions.set(execution.id ? `id:${execution.id}` : `anonymous:${anonymous++}`, execution);
62
+ };
63
+ const manifest = await readReportArtifactManifestAsync(reportPath);
64
+ if (manifest) for (const group of manifest.groups)for (const path of group.dumps)collect(await (0, promises_namespaceObject.readFile)((0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(reportPath), path), 'utf8'));
65
+ else await (0, external_html_utils_js_namespaceObject.streamDumpScriptsAsync)(reportPath, ({ content })=>{
66
+ collect((0, utils_namespaceObject.antiEscapeScriptTag)(content));
67
+ return false;
68
+ });
69
+ if (!base) throw new Error(`No replay dump found in report: ${reportPath}`);
70
+ return {
71
+ ...base,
72
+ executions: [
73
+ ...executions.values()
74
+ ]
75
+ };
76
+ }
77
+ function readReportArtifactManifest(reportPath) {
78
+ const manifestPath = (0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(reportPath), 'report.json');
79
+ if (!(0, external_node_fs_namespaceObject.existsSync)(manifestPath) || !(0, external_node_fs_namespaceObject.existsSync)(reportPath)) return;
80
+ const entry = (0, external_html_utils_js_namespaceObject.extractReportArtifactPathSync)(reportPath);
81
+ if (!entry) return;
82
+ const manifest = (0, report_artifact_namespaceObject.parseReportArtifactManifest)(JSON.parse((0, external_node_fs_namespaceObject.readFileSync)((0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(reportPath), entry), 'utf8')));
83
+ if (manifest.entry !== (0, external_node_path_namespaceObject.basename)(reportPath)) throw new Error('Report entry does not match its artifact manifest');
84
+ return manifest;
85
+ }
86
+ function readReportDumpScripts(reportPath) {
87
+ const dumps = [];
88
+ streamReportDumpScripts(reportPath, (dump)=>{
89
+ dumps.push(dump);
90
+ return false;
91
+ });
92
+ return dumps;
93
+ }
94
+ function streamReportDumpScripts(reportPath, visitor) {
95
+ const manifest = readReportArtifactManifest(reportPath);
96
+ if (!manifest) return void (0, external_html_utils_js_namespaceObject.streamDumpScriptsSync)(reportPath, (dump)=>dump.openTag.includes('data-group-id') ? visitor(dump) : false);
97
+ for (const group of manifest.groups)for (const path of group.dumps){
98
+ const content = (0, external_node_fs_namespaceObject.readFileSync)((0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(reportPath), path), 'utf8');
99
+ JSON.parse(content);
100
+ const tag = (0, external_html_utils_js_namespaceObject.generateDumpScriptTag)(content, {
101
+ 'data-group-id': group.id,
102
+ ...group.attributes
103
+ });
104
+ if (visitor({
105
+ openTag: tag.slice(0, tag.indexOf('>') + 1),
106
+ content
107
+ })) return;
108
+ }
109
+ }
110
+ function readReportRunnerDump(reportPath) {
111
+ const manifest = readReportArtifactManifest(reportPath);
112
+ if (!manifest) return (0, external_html_utils_js_namespaceObject.extractTestRunReportDumpSync)(reportPath) ?? void 0;
113
+ if (!manifest.runner) return;
114
+ return JSON.parse((0, external_node_fs_namespaceObject.readFileSync)((0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(reportPath), manifest.runner), 'utf8'));
115
+ }
116
+ exports.readReportActionDump = __webpack_exports__.readReportActionDump;
117
+ exports.readReportArtifactManifest = __webpack_exports__.readReportArtifactManifest;
118
+ exports.readReportArtifactManifestAsync = __webpack_exports__.readReportArtifactManifestAsync;
119
+ exports.readReportDumpScripts = __webpack_exports__.readReportDumpScripts;
120
+ exports.readReportRunnerDump = __webpack_exports__.readReportRunnerDump;
121
+ exports.streamReportDumpScripts = __webpack_exports__.streamReportDumpScripts;
122
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
123
+ "readReportActionDump",
124
+ "readReportArtifactManifest",
125
+ "readReportArtifactManifestAsync",
126
+ "readReportDumpScripts",
127
+ "readReportRunnerDump",
128
+ "streamReportDumpScripts"
129
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
130
+ Object.defineProperty(exports, '__esModule', {
131
+ value: true
132
+ });
133
+
134
+ //# sourceMappingURL=report-artifact-reader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dump/report-artifact-reader.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/dump/report-artifact-reader.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { existsSync, readFileSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { parseReportArtifactManifest } from '@midscene/shared/report-artifact';\nimport { antiEscapeScriptTag } from '@midscene/shared/utils';\nimport type { TestRunReportDump } from '../test-run-report';\nimport type { IExecutionDump, IReportActionDump } from '../types';\nimport {\n extractReportArtifactPathAsync,\n extractReportArtifactPathSync,\n extractTestRunReportDumpSync,\n generateDumpScriptTag,\n streamDumpScriptsAsync,\n streamDumpScriptsSync,\n} from './html-utils';\n\n/** Async counterpart for servers; missing manifests identify ordinary inline HTML. */\nexport async function readReportArtifactManifestAsync(reportPath: string) {\n const manifestPath = join(dirname(reportPath), 'report.json');\n const exists = await stat(manifestPath)\n .then(() => true)\n .catch((error) => {\n if (error.code === 'ENOENT') return false;\n throw error;\n });\n if (!exists) return undefined;\n const entry = await extractReportArtifactPathAsync(reportPath);\n if (!entry) return undefined;\n const manifest = parseReportArtifactManifest(\n JSON.parse(await readFile(join(dirname(reportPath), entry), 'utf8')),\n );\n if (manifest.entry !== basename(reportPath))\n throw new Error('Report entry does not match its artifact manifest');\n return manifest;\n}\n\n/** Read the complete replay, retaining the latest progress for every execution ID. */\nexport async function readReportActionDump(\n reportPath: string,\n): Promise<IReportActionDump> {\n let base: IReportActionDump | undefined;\n const executions = new Map<string, IExecutionDump>();\n let anonymous = 0;\n const collect = (content: string) => {\n const parsed = JSON.parse(content) as IReportActionDump;\n if (!parsed || !Array.isArray(parsed.executions))\n throw new Error(`Invalid report execution data: ${reportPath}`);\n base = parsed;\n for (const execution of parsed.executions)\n executions.set(\n execution.id ? `id:${execution.id}` : `anonymous:${anonymous++}`,\n execution,\n );\n };\n const manifest = await readReportArtifactManifestAsync(reportPath);\n if (manifest) {\n for (const group of manifest.groups) {\n for (const path of group.dumps)\n collect(await readFile(join(dirname(reportPath), path), 'utf8'));\n }\n } else {\n await streamDumpScriptsAsync(reportPath, ({ content }) => {\n collect(antiEscapeScriptTag(content));\n return false;\n });\n }\n if (!base) throw new Error(`No replay dump found in report: ${reportPath}`);\n return { ...base, executions: [...executions.values()] };\n}\n\n/** Read the versioned directory format; ordinary inline HTML stays self-contained. */\nexport function readReportArtifactManifest(reportPath: string) {\n const manifestPath = join(dirname(reportPath), 'report.json');\n if (!existsSync(manifestPath) || !existsSync(reportPath)) return undefined;\n const entry = extractReportArtifactPathSync(reportPath);\n if (!entry) return undefined;\n const manifest = parseReportArtifactManifest(\n JSON.parse(readFileSync(join(dirname(reportPath), entry), 'utf8')),\n );\n if (manifest.entry !== basename(reportPath))\n throw new Error('Report entry does not match its artifact manifest');\n return manifest;\n}\n\nexport function readReportDumpScripts(\n reportPath: string,\n): { openTag: string; content: string }[] {\n const dumps: { openTag: string; content: string }[] = [];\n streamReportDumpScripts(reportPath, (dump) => {\n dumps.push(dump);\n return false;\n });\n return dumps;\n}\n\n/** Stream inline HTML or external data one execution at a time. */\nexport function streamReportDumpScripts(\n reportPath: string,\n visitor: (dump: { openTag: string; content: string }) => boolean,\n): void {\n const manifest = readReportArtifactManifest(reportPath);\n if (!manifest) {\n // The bundled Viewer can contain literal dump-tag strings. Generated\n // execution tags carry a group ID; template strings must not be parsed.\n streamDumpScriptsSync(reportPath, (dump) =>\n dump.openTag.includes('data-group-id') ? visitor(dump) : false,\n );\n return;\n }\n for (const group of manifest.groups) {\n for (const path of group.dumps) {\n const content = readFileSync(join(dirname(reportPath), path), 'utf8');\n // Validate before passing the data to synchronous report consumers.\n JSON.parse(content);\n const tag = generateDumpScriptTag(content, {\n 'data-group-id': group.id,\n ...group.attributes,\n });\n if (visitor({ openTag: tag.slice(0, tag.indexOf('>') + 1), content }))\n return;\n }\n }\n}\n\nexport function readReportRunnerDump(\n reportPath: string,\n): TestRunReportDump | undefined {\n const manifest = readReportArtifactManifest(reportPath);\n if (!manifest) return extractTestRunReportDumpSync(reportPath) ?? undefined;\n if (!manifest.runner) return undefined;\n return JSON.parse(\n readFileSync(join(dirname(reportPath), manifest.runner), 'utf8'),\n ) as TestRunReportDump;\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","readReportArtifactManifestAsync","reportPath","manifestPath","join","dirname","exists","stat","error","entry","extractReportArtifactPathAsync","manifest","parseReportArtifactManifest","JSON","readFile","basename","Error","readReportActionDump","base","executions","Map","anonymous","collect","content","parsed","Array","execution","group","path","streamDumpScriptsAsync","antiEscapeScriptTag","readReportArtifactManifest","existsSync","extractReportArtifactPathSync","readFileSync","readReportDumpScripts","dumps","streamReportDumpScripts","dump","visitor","streamDumpScriptsSync","tag","generateDumpScriptTag","readReportRunnerDump","extractTestRunReportDumpSync","undefined"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;ACWO,eAAeI,gCAAgCC,UAAkB;IACtE,MAAMC,eAAeC,AAAAA,IAAAA,mCAAAA,IAAAA,AAAAA,EAAKC,AAAAA,IAAAA,mCAAAA,OAAAA,AAAAA,EAAQH,aAAa;IAC/C,MAAMI,SAAS,MAAMC,AAAAA,IAAAA,yBAAAA,IAAAA,AAAAA,EAAKJ,cACvB,IAAI,CAAC,IAAM,MACX,KAAK,CAAC,CAACK;QACN,IAAIA,AAAe,aAAfA,MAAM,IAAI,EAAe,OAAO;QACpC,M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for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ withReportArtifactLock: ()=>withReportArtifactLock,
28
+ writeReportArtifactFile: ()=>writeReportArtifactFile,
29
+ ReportArtifactStore: ()=>ReportArtifactStore
30
+ });
31
+ const promises_namespaceObject = require("node:fs/promises");
32
+ const external_node_path_namespaceObject = require("node:path");
33
+ const report_artifact_namespaceObject = require("@midscene/shared/report-artifact");
34
+ const utils_namespaceObject = require("@midscene/shared/utils");
35
+ function _define_property(obj, key, value) {
36
+ if (key in obj) Object.defineProperty(obj, key, {
37
+ value: value,
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true
41
+ });
42
+ else obj[key] = value;
43
+ return obj;
44
+ }
45
+ async function writeReportArtifactFile(path, content) {
46
+ await (0, promises_namespaceObject.mkdir)((0, external_node_path_namespaceObject.dirname)(path), {
47
+ recursive: true
48
+ });
49
+ const temporary = `${path}.${(0, utils_namespaceObject.uuid)()}.tmp`;
50
+ try {
51
+ await (0, promises_namespaceObject.writeFile)(temporary, content, 'utf8');
52
+ await (0, promises_namespaceObject.rename)(temporary, path);
53
+ } finally{
54
+ await (0, promises_namespaceObject.unlink)(temporary).catch((error)=>{
55
+ if ('ENOENT' !== error.code) throw error;
56
+ });
57
+ }
58
+ }
59
+ async function withReportArtifactLock(root, publish, timeoutMs = 10000) {
60
+ const lockPath = (0, external_node_path_namespaceObject.resolve)(root, '.report.json.lock');
61
+ await (0, promises_namespaceObject.mkdir)((0, external_node_path_namespaceObject.dirname)(lockPath), {
62
+ recursive: true
63
+ });
64
+ const startedAt = Date.now();
65
+ const acquire = async ()=>{
66
+ while(true)try {
67
+ return await (0, promises_namespaceObject.open)(lockPath, 'wx');
68
+ } catch (error) {
69
+ if ('EEXIST' !== error.code) throw error;
70
+ if (Date.now() - startedAt >= timeoutMs) throw new Error(`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.`, {
71
+ cause: error
72
+ });
73
+ await new Promise((resolve)=>setTimeout(resolve, 20 + 10 * Math.random()));
74
+ }
75
+ };
76
+ const lock = await acquire();
77
+ try {
78
+ await lock.writeFile(JSON.stringify({
79
+ pid: process.pid
80
+ }));
81
+ return await publish();
82
+ } finally{
83
+ await lock.close().finally(()=>(0, promises_namespaceObject.unlink)(lockPath));
84
+ }
85
+ }
86
+ class ReportArtifactStore {
87
+ async writeExecution(key, serialized, attributes) {
88
+ this.assertOpen();
89
+ this.queue = this.queue.then(async ()=>{
90
+ let path = this.executionPaths.get(key);
91
+ if (!path) {
92
+ path = `data/${this.manifest.reportId}/${++this.nextExecution}.json`;
93
+ this.executionPaths.set(key, path);
94
+ }
95
+ await writeReportArtifactFile((0, external_node_path_namespaceObject.join)(this.root, path), serialized);
96
+ const group = this.manifest.groups[0];
97
+ group.attributes = attributes;
98
+ if (!group.dumps.includes(path)) group.dumps.push(path);
99
+ await this.publish();
100
+ });
101
+ await this.queue;
102
+ }
103
+ async writeRunner(serialized) {
104
+ this.assertOpen();
105
+ this.queue = this.queue.then(async ()=>{
106
+ const path = `data/${this.manifest.reportId}/runner.json`;
107
+ await writeReportArtifactFile((0, external_node_path_namespaceObject.join)(this.root, path), serialized);
108
+ this.manifest.runner = path;
109
+ await this.publish();
110
+ });
111
+ await this.queue;
112
+ }
113
+ async finalize() {
114
+ if (!this.finalization) this.finalization = this.queue = this.queue.then(async ()=>{
115
+ this.manifest.groups[0].status = 'complete';
116
+ await this.publish();
117
+ });
118
+ await this.finalization;
119
+ }
120
+ assertOpen() {
121
+ if (this.finalization) throw new Error('The report artifact stream has been finalized.');
122
+ }
123
+ async publish() {
124
+ const path = (0, external_node_path_namespaceObject.resolve)(this.root, 'report.json');
125
+ await withReportArtifactLock(this.root, async ()=>{
126
+ let manifest = this.manifest;
127
+ if (this.reuseExistingReport || this.hasPublished) {
128
+ const existing = await (0, promises_namespaceObject.readFile)(path, 'utf8').catch((error)=>{
129
+ if ('ENOENT' === error.code) return;
130
+ throw error;
131
+ });
132
+ if (void 0 !== existing) {
133
+ const previous = (0, report_artifact_namespaceObject.parseReportArtifactManifest)(JSON.parse(existing));
134
+ if (previous.kind !== manifest.kind || previous.entry !== manifest.entry) throw new Error('Cannot combine reports with different kinds or entries');
135
+ manifest = {
136
+ ...previous,
137
+ groups: [
138
+ ...new Map([
139
+ ...previous.groups,
140
+ ...manifest.groups
141
+ ].map((group)=>[
142
+ group.id,
143
+ group
144
+ ])).values()
145
+ ],
146
+ runner: manifest.runner ?? previous.runner
147
+ };
148
+ }
149
+ }
150
+ manifest = {
151
+ ...manifest,
152
+ status: manifest.groups.every((group)=>'complete' === group.status) ? 'complete' : 'running'
153
+ };
154
+ (0, report_artifact_namespaceObject.parseReportArtifactManifest)(manifest);
155
+ await writeReportArtifactFile(path, JSON.stringify(manifest));
156
+ this.hasPublished = true;
157
+ });
158
+ }
159
+ constructor(root, reportId, kind = 'agent', reuseExistingReport = false, entry = 'index.html'){
160
+ _define_property(this, "root", void 0);
161
+ _define_property(this, "reuseExistingReport", void 0);
162
+ _define_property(this, "executionPaths", void 0);
163
+ _define_property(this, "nextExecution", void 0);
164
+ _define_property(this, "manifest", void 0);
165
+ _define_property(this, "queue", void 0);
166
+ _define_property(this, "hasPublished", void 0);
167
+ _define_property(this, "finalization", void 0);
168
+ this.root = root;
169
+ this.reuseExistingReport = reuseExistingReport;
170
+ this.executionPaths = new Map();
171
+ this.nextExecution = 0;
172
+ this.queue = Promise.resolve();
173
+ this.hasPublished = false;
174
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(reportId)) throw new Error('Invalid report artifact ID');
175
+ this.manifest = {
176
+ schemaVersion: 1,
177
+ kind,
178
+ status: 'running',
179
+ reportId,
180
+ entry,
181
+ groups: [
182
+ {
183
+ id: reportId,
184
+ status: 'running',
185
+ attributes: {},
186
+ dumps: []
187
+ }
188
+ ]
189
+ };
190
+ }
191
+ }
192
+ exports.ReportArtifactStore = __webpack_exports__.ReportArtifactStore;
193
+ exports.withReportArtifactLock = __webpack_exports__.withReportArtifactLock;
194
+ exports.writeReportArtifactFile = __webpack_exports__.writeReportArtifactFile;
195
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
196
+ "ReportArtifactStore",
197
+ "withReportArtifactLock",
198
+ "writeReportArtifactFile"
199
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
200
+ Object.defineProperty(exports, '__esModule', {
201
+ value: true
202
+ });
203
+
204
+ //# sourceMappingURL=report-artifact-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dump/report-artifact-store.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/dump/report-artifact-store.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","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":["__webpack_require__","definition","key","Object","obj","prop","Symbol","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","serialized","attributes","join","group","manifest","existing","readFile","undefined","previous","parseReportArtifactManifest","Map","reportId","kind","reuseExistingReport","entry"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;ACUO,eAAeI,wBACpBC,IAAY,EACZC,OAA4B;IAE5B,MAAMC,AAAAA,IAAAA,yBAA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