"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }




var _chunkUXPZNWPHjs = require('./chunk-UXPZNWPH.js');

// src/utils.ts
var _assert = require('assert'); var _assert2 = _interopRequireDefault(_assert);
var _child_process = require('child_process');
var _fs = require('fs');
var _os = require('os');
var _path = require('path');
var _fs3 = require('@aico-test/shared/fs');
var _utils = require('@aico-test/shared/utils');
var logDir = _path.join.call(void 0, process.cwd(), "./midscene_run/");
var logEnvReady = false;
var groupedActionDumpFileExt = "web-dump.json";
function getLogDir() {
  return logDir;
}
function setLogDir(dir) {
  logDir = dir;
}
function getLogDirByType(type) {
  const dir = _path.join.call(void 0, getLogDir(), type);
  if (!_fs.existsSync.call(void 0, dir)) {
    _fs.mkdirSync.call(void 0, dir, { recursive: true });
  }
  return dir;
}
var reportTpl = null;
function getReportTpl() {
  if (_utils.ifInBrowser) {
    if (!reportTpl && window.get_midscene_report_tpl) {
      reportTpl = window.get_midscene_report_tpl();
    }
    return reportTpl;
  }
  if (!reportTpl) {
    let reportPath = _path.join.call(void 0, __dirname, "../../report/index.html");
    if (!_fs.existsSync.call(void 0, reportPath)) {
      reportPath = _path.join.call(void 0, __dirname, "../report/index.html");
    }
    reportTpl = _fs.readFileSync.call(void 0, reportPath, "utf-8");
  }
  return reportTpl;
}
function replaceStringWithFirstAppearance(str, target, replacement) {
  const index = str.indexOf(target);
  return str.slice(0, index) + replacement + str.slice(index + target.length);
}
function reportHTMLContent(dumpData) {
  const tpl = getReportTpl();
  if (!tpl) {
    console.warn("reportTpl is not set, will not write report");
    return "";
  }
  let reportContent;
  if (Array.isArray(dumpData) && dumpData.length === 0 || typeof dumpData === "undefined") {
    reportContent = replaceStringWithFirstAppearance(
      tpl,
      "{{dump}}",
      `<script type="midscene_web_dump" type="application/json"></script>`
    );
  } else if (typeof dumpData === "string") {
    reportContent = replaceStringWithFirstAppearance(
      tpl,
      "{{dump}}",
      `<script type="midscene_web_dump" type="application/json">${dumpData}</script>`
    );
  } else {
    const dumps = dumpData.map(({ dumpString, attributes }) => {
      const attributesArr = Object.keys(attributes || {}).map((key) => {
        return `${key}="${encodeURIComponent(attributes[key])}"`;
      });
      return `<script type="midscene_web_dump" type="application/json" ${attributesArr.join(
        " "
      )}
>${dumpString}
</script>`;
    });
    reportContent = replaceStringWithFirstAppearance(
      tpl,
      "{{dump}}",
      dumps.join("\n")
    );
  }
  return reportContent;
}
function writeDumpReport(fileName, dumpData) {
  if (_utils.ifInBrowser) {
    console.log("will not write report in browser");
    return null;
  }
  const midscenePkgInfo = _fs3.getRunningPkgInfo.call(void 0, __dirname);
  if (!midscenePkgInfo) {
    console.warn("midscenePkgInfo not found, will not write report");
    return null;
  }
  const reportPath = _path.join.call(void 0, getLogDirByType("report"), `${fileName}.html`);
  const reportContent = reportHTMLContent(dumpData);
  if (!reportContent) {
    console.warn("reportContent is empty, will not write report");
    return null;
  }
  _fs.writeFileSync.call(void 0, reportPath, reportContent);
  return reportPath;
}
function writeLogFile(opts) {
  if (_utils.ifInBrowser) {
    return "/mock/report.html";
  }
  const { fileName, fileExt, fileContent, type = "dump" } = opts;
  const targetDir = getLogDirByType(type);
  if (!logEnvReady) {
    _assert2.default.call(void 0, targetDir, "logDir should be set before writing dump file");
    const gitIgnorePath = _path.join.call(void 0, targetDir, "../../.gitignore");
    let gitIgnoreContent = "";
    if (_fs.existsSync.call(void 0, gitIgnorePath)) {
      gitIgnoreContent = _fs.readFileSync.call(void 0, gitIgnorePath, "utf-8");
    }
    const logDirName = _path.basename.call(void 0, logDir);
    if (!gitIgnoreContent.includes(`${logDirName}/`)) {
      _fs.writeFileSync.call(void 0, 
        gitIgnorePath,
        `${gitIgnoreContent}
# AICO dump files
${logDirName}/report
${logDirName}/tmp
`,
        "utf-8"
      );
    }
    logEnvReady = true;
  }
  const filePath = _path.join.call(void 0, targetDir, `${fileName}.${fileExt}`);
  if (type !== "dump") {
    const outputResourceDir = _path.dirname.call(void 0, filePath);
    if (!_fs.existsSync.call(void 0, outputResourceDir)) {
      _fs.mkdirSync.call(void 0, outputResourceDir, { recursive: true });
    }
    _fs.writeFileSync.call(void 0, filePath, fileContent);
  }
  if (opts == null ? void 0 : opts.generateReport) {
    return writeDumpReport(fileName, fileContent);
  }
  return filePath;
}
function getTmpDir() {
  if (_utils.ifInBrowser) {
    return null;
  }
  const runningPkgInfo = _fs3.getRunningPkgInfo.call(void 0, );
  if (!runningPkgInfo) {
    return null;
  }
  const { name } = runningPkgInfo;
  const path = _path.join.call(void 0, _os.tmpdir.call(void 0, ), name);
  _fs.mkdirSync.call(void 0, path, { recursive: true });
  return path;
}
function getTmpFile(fileExtWithoutDot) {
  if (_utils.ifInBrowser) {
    return null;
  }
  const tmpDir = getTmpDir();
  const filename = `${_utils.uuid.call(void 0, )}.${fileExtWithoutDot}`;
  return _path.join.call(void 0, tmpDir, filename);
}
function overlapped(container, target) {
  return container.left < target.left + target.width && container.left + container.width > target.left && container.top < target.top + target.height && container.top + container.height > target.top;
}
async function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
function replacerForPageObject(key, value) {
  var _a, _b;
  if (value && ((_a = value.constructor) == null ? void 0 : _a.name) === "Page") {
    return "[Page object]";
  }
  if (value && ((_b = value.constructor) == null ? void 0 : _b.name) === "Browser") {
    return "[Browser object]";
  }
  return value;
}
function stringifyDumpData(data, indents) {
  return JSON.stringify(data, replacerForPageObject, indents);
}
function getVersion() {
  return "2.0.0";
}
function debugLog(...message) {
  const debugMode = _chunkUXPZNWPHjs.getAIConfig.call(void 0, _chunkUXPZNWPHjs.MIDSCENE_DEBUG_MODE);
  if (debugMode) {
    console.log("[Midscene]", ...message);
  }
}
var lastReportedRepoUrl = "";
function uploadTestInfoToServer({ testUrl }) {
  let repoUrl = "";
  let userEmail = "";
  const extraConfig = _chunkUXPZNWPHjs.getAIConfigInJson.call(void 0, _chunkUXPZNWPHjs.MIDSCENE_OPENAI_INIT_CONFIG_JSON);
  const serverUrl = extraConfig == null ? void 0 : extraConfig.REPORT_SERVER_URL;
  try {
    repoUrl = _child_process.execSync.call(void 0, "git config --get remote.origin.url").toString().trim();
    userEmail = _child_process.execSync.call(void 0, "git config --get user.email").toString().trim();
  } catch (error) {
    debugLog("Failed to get git info:", error);
  }
  if (serverUrl && (repoUrl && repoUrl !== lastReportedRepoUrl || !repoUrl && testUrl)) {
    debugLog("Uploading test info to server", {
      serverUrl,
      repoUrl,
      testUrl,
      userEmail
    });
    fetch(serverUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        repo_url: repoUrl,
        test_url: testUrl,
        user_email: userEmail
      })
    }).then((response) => response.json()).then((data) => {
      debugLog("Successfully uploaded test info to server:", data);
    }).catch(
      (error) => debugLog("Failed to upload test info to server:", error)
    );
    lastReportedRepoUrl = repoUrl;
  }
}


















exports.groupedActionDumpFileExt = groupedActionDumpFileExt; exports.getLogDir = getLogDir; exports.setLogDir = setLogDir; exports.getLogDirByType = getLogDirByType; exports.replaceStringWithFirstAppearance = replaceStringWithFirstAppearance; exports.reportHTMLContent = reportHTMLContent; exports.writeDumpReport = writeDumpReport; exports.writeLogFile = writeLogFile; exports.getTmpDir = getTmpDir; exports.getTmpFile = getTmpFile; exports.overlapped = overlapped; exports.sleep = sleep; exports.replacerForPageObject = replacerForPageObject; exports.stringifyDumpData = stringifyDumpData; exports.getVersion = getVersion; exports.uploadTestInfoToServer = uploadTestInfoToServer;

//# sourceMappingURL=chunk-ZTGKMHS3.js.map