if (typeof process === 'object' && process !== null &&
    process.env !== null && typeof process.env === 'object') {
  process.env.DD_GIT_REPOSITORY_URL = 'https://token@github.com/superblocksteam/superblocks.git';
  process.env.DD_GIT_COMMIT_SHA = '71329cb2a26133447acee36261ec5a5145024e84';
}
import { createRequire as $dd_createRequire } from 'module';
import { fileURLToPath as $dd_fileURLToPath } from 'url';
import { dirname as $dd_dirname } from 'path';
globalThis.require ??= $dd_createRequire(import.meta.url);
globalThis.__filename ??= $dd_fileURLToPath(import.meta.url);
globalThis.__dirname ??= $dd_dirname(globalThis.__filename);

import {
  init_cjs_shims
} from "./chunk-MTQ2JLIW.js";

// ../../../vite-plugin-file-sync/dist/ai-service/mcp/embedded-playwright-mcp-server.js
init_cjs_shims();
import { once } from "node:events";
import fs from "node:fs";
import http from "node:http";
import { chromium, firefox, webkit } from "playwright";
var PlaywrightActionLogger = class {
  logContent = "";
  sessionId;
  startTime;
  actionCount = 0;
  saveArtifact;
  runTimestamp;
  logger;
  constructor(options) {
    this.sessionId = options.sessionId;
    this.startTime = Date.now();
    this.saveArtifact = options.saveArtifact;
    this.runTimestamp = options.runTimestamp || (/* @__PURE__ */ new Date()).toISOString();
    this.logger = options.logger;
    this.logContent += this.formatSection("PLAYWRIGHT SESSION START") + "\n";
    this.logContent += `Session ID: ${this.sessionId}
`;
    this.logContent += `Timestamp: ${(/* @__PURE__ */ new Date()).toISOString()}

`;
  }
  formatSection(title) {
    const prefix = `------ ${title} `;
    const remaining = Math.max(0, 72 - prefix.length);
    return prefix + "-".repeat(remaining);
  }
  truncateString(s, maxBytes) {
    if (s.length <= maxBytes)
      return s;
    return s.slice(0, maxBytes) + `
... [truncated ${s.length - maxBytes} bytes]`;
  }
  /**
   * Log the start of a Playwright action.
   */
  logActionStart(action, params) {
    this.actionCount++;
    const timestamp = (/* @__PURE__ */ new Date()).toISOString();
    this.logContent += `ACTION #${this.actionCount}: ${action}
`;
    this.logContent += `  Timestamp: ${timestamp}
`;
    const logParams = {};
    for (const [key, value] of Object.entries(params)) {
      if (key === "screenshot" || key === "data")
        continue;
      logParams[key] = value;
    }
    if (Object.keys(logParams).length > 0) {
      this.logContent += `  Params:
`;
      for (const [key, value] of Object.entries(logParams)) {
        const valueStr = typeof value === "string" ? this.truncateString(value, 200) : JSON.stringify(value);
        this.logContent += `    ${key}: ${valueStr}
`;
      }
    }
  }
  /**
   * Log the result of a Playwright action.
   */
  logActionResult(result) {
    const success = result.success !== false;
    this.logContent += `  Result: ${success ? "SUCCESS" : "FAILED"}
`;
    if (result.error) {
      this.logContent += `  Error: ${result.error}
`;
    }
    if (result.runtimeErrors?.length > 0) {
      this.logContent += `  Runtime Errors:
`;
      for (const err of result.runtimeErrors) {
        this.logContent += `    - ${err.header}
`;
        if (err.stack) {
          const truncatedStack = this.truncateString(err.stack, 500);
          this.logContent += `      Stack: ${truncatedStack}
`;
        }
      }
    }
    const fieldsToLog = ["url", "text", "hasErrors", "errorCount", "count"];
    for (const field of fieldsToLog) {
      if (field in result && result[field] !== void 0) {
        this.logContent += `  ${field}: ${JSON.stringify(result[field])}
`;
      }
    }
    this.logContent += "\n";
  }
  /**
   * Log console messages from the page.
   */
  logConsoleLogs(logs) {
    if (logs.length === 0)
      return;
    this.logContent += `  Console Logs (${logs.length}):
`;
    const maxLogs = 20;
    const logsToShow = logs.slice(-maxLogs);
    for (const log of logsToShow) {
      const text = this.truncateString(log.text, 200);
      this.logContent += `    [${log.type}] ${text}
`;
    }
    if (logs.length > maxLogs) {
      this.logContent += `    ... and ${logs.length - maxLogs} more logs
`;
    }
  }
  /**
   * Save the log to an artifact file.
   */
  async save() {
    if (!this.saveArtifact) {
      this.logger.debug("[PlaywrightLogger] No saveArtifact function provided, skipping log save");
      return;
    }
    const duration = Date.now() - this.startTime;
    this.logContent += this.formatSection("PLAYWRIGHT SESSION END") + "\n";
    this.logContent += `End Timestamp: ${(/* @__PURE__ */ new Date()).toISOString()}
`;
    this.logContent += `Duration: ${duration}ms
`;
    this.logContent += `Total Actions: ${this.actionCount}
`;
    try {
      const artifact = {
        type: "file",
        filePath: `playwright-session-${this.sessionId}.log`,
        content: this.logContent
      };
      const stepId = `playwright-session-${this.sessionId}`;
      await this.saveArtifact(artifact, stepId, this.runTimestamp);
      this.logger.debug(`[PlaywrightLogger] Saved log artifact: ${artifact.filePath}`);
    } catch (error) {
      this.logger.error(`[PlaywrightLogger] Failed to save log: ${String(error)}`);
    }
  }
  /**
   * Save the current log and reset for a new session.
   * Used to save logs after each test run without closing the server.
   */
  async saveAndReset() {
    if (this.actionCount === 0) {
      this.logger.debug("[PlaywrightLogger] No actions logged, skipping save and reset");
      return;
    }
    await this.save();
    const newSessionId = String(Date.now());
    this.sessionId = newSessionId;
    this.startTime = Date.now();
    this.actionCount = 0;
    this.logContent = "";
    this.logContent += this.formatSection("PLAYWRIGHT SESSION START") + "\n";
    this.logContent += `Session ID: ${this.sessionId}
`;
    this.logContent += `Timestamp: ${(/* @__PURE__ */ new Date()).toISOString()}

`;
    this.logger.debug(`[PlaywrightLogger] Reset for new session: ${newSessionId}`);
  }
  getLogContent() {
    return this.logContent;
  }
};
var DEFAULT_VIEWPORT = { width: 1280, height: 800 };
var PLAYWRIGHT_ACTIONS = [
  "navigate",
  "click",
  "fill",
  "screenshot",
  "getText",
  "waitForSelector",
  "evaluate",
  "getUrl",
  "reload",
  "getConsoleLogs",
  "scroll",
  "scrollIntoView",
  "checkRuntimeErrors",
  "getEmbedEvents",
  "triggerEmbedEvent",
  "setEmbedProperties"
];
var capturedConsoleLogs = [];
var lastDrainedEmbedEvents = null;
async function startEmbeddedPlaywrightMcpServer(options) {
  const logger = options.logger;
  const sessionId = String(Date.now());
  const actionLogger = new PlaywrightActionLogger({
    sessionId,
    saveArtifact: options.saveArtifact,
    runTimestamp: options.runTimestamp,
    logger
  });
  let browser;
  let context = null;
  let shouldCloseBrowser = true;
  if (options?.connectWsEndpoint) {
    browser = await chromium.connect({
      wsEndpoint: options.connectWsEndpoint
    });
    shouldCloseBrowser = false;
  } else {
    browser = await launchBrowser();
  }
  if (options?.connectWsEndpoint) {
    const existing = browser.contexts();
    if (existing.length > 0) {
      context = existing[0];
    }
  }
  if (!context) {
    const contextOptions = {
      viewport: DEFAULT_VIEWPORT
    };
    if (options?.storageStateData) {
      contextOptions.storageState = options.storageStateData;
      if (options.appUrl && options.storageStateData.cookies?.length) {
        const appHost = new URL(options.appUrl).hostname;
        const duplicateCookies = options.storageStateData.cookies.filter((c) => ["auth0", "auth0_compat", "did", "did_compat"].includes(c.name)).map((c) => ({
          ...c,
          domain: appHost,
          secure: false,
          sameSite: "Lax"
        }));
        contextOptions.storageState.cookies = [
          ...contextOptions.storageState.cookies || [],
          ...duplicateCookies
        ];
      }
    } else if (options?.storageStatePath) {
      if (fs.existsSync(options.storageStatePath)) {
        contextOptions.storageState = options.storageStatePath;
      }
    }
    context = await browser.newContext(contextOptions);
  }
  if (!context) {
    throw new Error("Failed to create or reuse a Playwright context");
  }
  const initData = options.initData;
  const bootstrapData = options.bootstrapData;
  await context.addInitScript((payload) => {
    const { initData: init, bootstrapData: bootstrap } = payload;
    const EMBED_EVENTS_KEY = "__sb_embed_events__";
    window[EMBED_EVENTS_KEY] = window[EMBED_EVENTS_KEY] ?? [];
    window.__sbGetAndClearEmbedEvents = () => {
      const events = Array.isArray(window[EMBED_EVENTS_KEY]) ? window[EMBED_EVENTS_KEY] : [];
      window[EMBED_EVENTS_KEY] = [];
      return events;
    };
    const mockParent = {
      postMessage: (message, _targetOrigin) => {
        if (message?.type === "embed-emit-event") {
          window[EMBED_EVENTS_KEY].push({
            timestamp: Date.now(),
            eventName: message?.payload?.eventName,
            payload: message?.payload?.payload
          });
        }
        if (message?.type === "sb-ready" && init) {
          setTimeout(() => {
            window.postMessage({
              type: "sb-init",
              payload: {
                peerId: init.peerId,
                userId: init.userId,
                devServerAuthorization: init.devServerAuthorization,
                appId: init.appId,
                windowOriginUrl: init.windowOriginUrl
              },
              startTime: Date.now()
            }, "*");
          }, 10);
        }
        if (message?.type === "sb-editor-request-bootstrap" && bootstrap) {
          setTimeout(() => {
            window.postMessage({
              type: "sb-bootstrap-response",
              payload: bootstrap,
              startTime: Date.now()
            }, "*");
          }, 10);
        }
        if (message?.type === "authenticate-api-request") {
          const { callbackId } = message.payload || {};
          if (callbackId) {
            setTimeout(() => {
              window.postMessage({
                type: "resolve-promise",
                callbackId,
                payload: {}
                // Empty success result - no auth errors
              }, "*");
            }, 10);
          }
        }
      },
      // These properties make the mock look like a real window object
      // which helps pass any instanceof or property existence checks
      window,
      document,
      location: window.location
    };
    Object.defineProperty(window, "parent", {
      value: mockParent,
      writable: false,
      configurable: true
    });
    if (init) {
      setTimeout(() => {
        window.postMessage({
          type: "sb-init",
          payload: {
            peerId: init.peerId,
            userId: init.userId,
            devServerAuthorization: init.devServerAuthorization,
            appId: init.appId,
            windowOriginUrl: init.windowOriginUrl
          },
          startTime: Date.now()
        }, "*");
      }, 100);
    }
    if (bootstrap) {
      setTimeout(() => {
        window.postMessage({
          type: "sb-bootstrap-response",
          payload: bootstrap,
          startTime: Date.now()
        }, "*");
      }, 200);
      if (bootstrap.profiles) {
        setTimeout(() => {
          window.postMessage({
            type: "sb-global-sync",
            payload: {
              global: {
                profiles: bootstrap.profiles
              }
            },
            startTime: Date.now()
          }, "*");
        }, 300);
      }
    }
  }, {
    initData,
    bootstrapData
  });
  if (options?.jwt && options?.appUrl) {
    try {
      const appUrl = new URL(options.appUrl);
      const authDomains = /* @__PURE__ */ new Set([
        appUrl.hostname,
        "login-dev.superblocks.com",
        "login.superblocks.com"
      ]);
      await context.addInitScript(({ token, domains }) => {
        try {
          localStorage.setItem("sb_jwt", token);
          sessionStorage.setItem("sb_jwt", token);
          localStorage.setItem("access_token", token);
          sessionStorage.setItem("access_token", token);
        } catch {
        }
        try {
          domains.forEach((domain) => {
            document.cookie = `x-superblocks-authorization=Bearer ${token}; Path=/; SameSite=None; ${domain === "localhost" ? "" : "Secure;"} Domain=${domain}`;
            document.cookie = `sb_jwt=${token}; Path=/; SameSite=None; ${domain === "localhost" ? "" : "Secure;"} Domain=${domain}`;
          });
        } catch {
        }
      }, { token: options.jwt, domains: Array.from(authDomains) });
      const cookieBase = {
        value: `Bearer ${options.jwt}`,
        path: "/",
        httpOnly: false,
        sameSite: "None"
      };
      const cookies = [
        {
          ...cookieBase,
          name: "x-superblocks-authorization",
          domain: appUrl.hostname,
          secure: appUrl.protocol === "https:"
        },
        {
          ...cookieBase,
          name: "sb_jwt",
          value: options.jwt,
          domain: appUrl.hostname,
          secure: appUrl.protocol === "https:"
        }
      ];
      authDomains.forEach((domain) => {
        if (domain !== appUrl.hostname) {
          cookies.push({
            ...cookieBase,
            name: "x-superblocks-authorization",
            domain,
            secure: true
          });
          cookies.push({
            ...cookieBase,
            name: "sb_jwt",
            value: options.jwt,
            domain,
            secure: true
          });
        }
      });
      await context.addCookies(cookies);
    } catch (error) {
      logger.error(`[MCP-Server] \u274C Failed to seed JWT cookie/localStorage: ${String(error)}`, {
        error: {
          kind: "McpServerSeedJwtError",
          message: String(error),
          stack: error instanceof Error ? error.stack : void 0
        }
      });
    }
  }
  if (options?.sessionStorageData?.items?.length) {
    const { origin, items } = options.sessionStorageData;
    try {
      await context.addInitScript(({ targetOrigin, entries }) => {
        if (location.origin === targetOrigin) {
          try {
            entries.forEach(({ name, value }) => {
              sessionStorage.setItem(name, value);
            });
          } catch {
          }
        }
      }, { targetOrigin: origin, entries: items });
    } catch {
    }
  }
  if (options?.extraOrigins?.length) {
    for (const originData of options.extraOrigins) {
      const { origin, localStorage: localStorage2 = [], sessionStorage: sessionStorage2 = [] } = originData;
      const seedLocal = localStorage2;
      const seedSession = sessionStorage2;
      if (seedLocal.length > 0 || seedSession.length > 0) {
        try {
          await context.addInitScript(({ targetOrigin, lsEntries, ssEntries }) => {
            if (location.origin === targetOrigin) {
              lsEntries.forEach(({ name, value }) => {
                try {
                  globalThis.localStorage?.setItem(name, value);
                } catch {
                }
              });
              ssEntries.forEach(({ name, value }) => {
                try {
                  globalThis.sessionStorage?.setItem(name, value);
                } catch {
                }
              });
            }
          }, {
            targetOrigin: origin,
            lsEntries: seedLocal,
            ssEntries: seedSession
          });
        } catch {
        }
      }
    }
  }
  const page = await context.newPage();
  const existingPages = context.pages();
  const activePage = existingPages.length > 0 ? existingPages[0] : page;
  capturedConsoleLogs = [];
  activePage.on("console", (msg) => {
    capturedConsoleLogs.push({
      type: msg.type(),
      text: msg.text(),
      timestamp: Date.now()
    });
  });
  if (options?.appUrl) {
    try {
      await activePage.goto(options.appUrl, {
        waitUntil: "load",
        timeout: 6e4
      });
    } catch (error) {
      logger.warn(`[MCP-Server] Auto-navigation to ${options.appUrl} failed: ${String(error)}`, {
        error: {
          kind: "McpServerAutoNavError",
          message: String(error),
          stack: error instanceof Error ? error.stack : void 0
        }
      });
    }
  }
  const server = http.createServer((req, res) => {
    void (async () => {
      try {
        if (req.method !== "POST") {
          res.writeHead(405, { "Content-Type": "application/json" });
          res.end(JSON.stringify({
            jsonrpc: "2.0",
            id: null,
            error: {
              code: -32600,
              message: "Only POST requests are supported"
            }
          }));
          return;
        }
        const body = await readRequestBody(req);
        let request;
        try {
          request = JSON.parse(body);
        } catch (error) {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({
            jsonrpc: "2.0",
            id: null,
            error: {
              code: -32700,
              message: `Invalid JSON: ${String(error)}`
            }
          }));
          return;
        }
        const response = await handleJsonRpcRequest(request, activePage, actionLogger);
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify(response));
      } catch (error) {
        res.writeHead(500, { "Content-Type": "application/json" });
        res.end(JSON.stringify({
          jsonrpc: "2.0",
          id: null,
          error: {
            code: -32603,
            message: `Server error: ${String(error)}`
          }
        }));
      }
    })();
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  const address = server.address();
  const url = `http://${address.address}:${address.port}/mcp`;
  return {
    url,
    close: async () => {
      await actionLogger.save();
      await Promise.allSettled([
        new Promise((resolve, reject) => {
          server.close((error) => {
            if (error) {
              reject(error);
            } else {
              resolve();
            }
          });
        }),
        page.close().catch(() => {
        }),
        context.close().catch(() => {
        }),
        shouldCloseBrowser ? browser.close().catch(() => {
        }) : Promise.resolve()
      ]);
    },
    flushLog: async () => {
      await actionLogger.saveAndReset();
    },
    captureInteractiveElements: async () => {
      try {
        await page.waitForLoadState("domcontentloaded");
        const elements = await page.evaluate(() => {
          const selector = 'button, a, input, select, textarea, [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"], [role="menuitem"], [onclick], [data-testid]';
          const nodeList = document.querySelectorAll(selector);
          return Array.from(nodeList).map((el) => {
            const text = el.textContent?.trim().slice(0, 100);
            const id = el.id || void 0;
            const className = el.className || void 0;
            const testId = el.getAttribute("data-testid") || void 0;
            const placeholder = el.getAttribute("placeholder") || void 0;
            const href = el.getAttribute("href") || void 0;
            const type = el.getAttribute("type") || void 0;
            const role = el.getAttribute("role") || void 0;
            const ariaLabel = el.getAttribute("aria-label") || void 0;
            const name = el.getAttribute("name") || void 0;
            const disabled = el.hasAttribute("disabled") || el.getAttribute("aria-disabled") === "true";
            return {
              tag: el.tagName.toLowerCase(),
              text: text || void 0,
              id,
              className: typeof className === "string" ? className : void 0,
              testId,
              placeholder,
              href,
              type,
              role,
              ariaLabel,
              name,
              disabled: disabled || void 0
            };
          }).filter((el) => {
            return el.text || el.id || el.testId || el.placeholder || el.ariaLabel || el.name;
          });
        });
        return elements;
      } catch (error) {
        logger.warn(`Failed to capture interactive elements: ${String(error)}`);
        return [];
      }
    }
  };
}
async function launchBrowser() {
  const browserName = process.env.PLAYWRIGHT_MCP_BROWSER ?? "chromium";
  const headless = process.env.HEADLESS !== "false";
  switch (browserName) {
    case "chromium":
      return chromium.launch({ headless });
    case "firefox":
      return firefox.launch({ headless });
    case "webkit":
      return webkit.launch({ headless });
    default:
      throw new Error(`Unsupported PLAYWRIGHT_MCP_BROWSER: ${browserName}`);
  }
}
async function readRequestBody(req) {
  const chunks = [];
  for await (const chunk of req) {
    chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
  }
  return Buffer.concat(chunks).toString("utf-8");
}
async function handleJsonRpcRequest(request, page, actionLogger) {
  const { method, id } = request;
  try {
    if (method === "tools/list") {
      return {
        jsonrpc: "2.0",
        id,
        result: {
          tools: [
            {
              name: "playwright_action",
              description: `Execute Playwright browser automation actions. The browser is already navigated to the app.

ACTIONS:
- screenshot: Take a screenshot. Params: { fullPage?: boolean }
- click: Click an element. Params: { selector: string }
- fill: Type into an input. Params: { selector: string, value: string }
- getText: Get text content. Params: { selector: string }
- waitForSelector: Wait for element. Params: { selector: string }
- evaluate: Run JavaScript. Params: { script: string }
- getUrl: Get current URL. No params.
- reload: Reload the page. No params.
- navigate: Go to URL. Params: { url: string }
- getConsoleLogs: Get browser console logs. Params: { clear?: boolean }
- getEmbedEvents: Get the most recent embed events emitted by the app. Params: { }
- triggerEmbedEvent: Trigger an incoming embed event as if sent by the embedder. Params: { eventName: string, payload?: object }
- setEmbedProperties: Set embed properties as if sent by the embedder. Params: { properties: object }
- scroll: Scroll the page. Params: { x?: number, y?: number, deltaX?: number, deltaY?: number }
- scrollIntoView: Scroll element into view. Params: { selector: string }
- checkRuntimeErrors: Explicitly check for component crashes. No params.

RUNTIME ERROR DETECTION:
Actions (navigate, click, fill, evaluate) automatically detect component crashes.
When a component crashes, the action returns:
- success: false
- runtimeErrors: Array of { header: string, stack?: string }
- error: Summary message

If you see runtimeErrors in a response, the test should FAIL. Include the error details in your summary.

SELECTOR EXAMPLES:
- By testid: [data-testid="login-form"]
- By name: input[name="username"], textarea[name="bio"]
- By placeholder: input[placeholder="Enter name"]
- By type: input[type="email"], button[type="submit"]  
- By text content: button:has-text("Submit"), a:has-text("Click here")
- By ID: #submitBtn, #loginForm
- By class: .btn-primary, .form-input
- Combining: form#login input[name="password"]

Any selector that playwright supports can be used.

CSS SELECTOR SYNTAX (IMPORTANT):
\u2713 CORRECT: input[name="email"], button[type="submit"], #myId, .myClass
\u2717 WRONG: input [name="email"] (no space before bracket!)
\u2717 WRONG: input[name=email] (quotes required around value)

TIPS:
1. Use specific selectors: prefer [name="x"] or [placeholder="x"] over generic .class
2. If click/fill fails, the element may not be visible - try waitForSelector first
3. For dynamic content, use waitForSelector before interacting
4. Navigate, click, and fill will automatically take a screenshot of the page after the action is performed
5. If success is false due to runtimeErrors, FAIL the test and report the error details`,
              inputSchema: {
                type: "object",
                properties: {
                  action: {
                    type: "string",
                    enum: PLAYWRIGHT_ACTIONS,
                    description: "The action to perform. Most actions require a 'selector' parameter."
                  },
                  description: {
                    type: "string",
                    description: "Brief description of what this test step is verifying (e.g., 'Verify login form appears', 'Test submit button functionality'). This will be displayed in the test report."
                  },
                  selector: {
                    type: "string",
                    description: 'CSS selector for the target element. NO SPACE before brackets! Example: input[name="email"] NOT input [name="email"]'
                  },
                  value: {
                    type: "string",
                    description: "Value to fill (for 'fill' action)"
                  },
                  url: {
                    type: "string",
                    description: "URL to navigate to (for 'navigate' action)"
                  },
                  script: {
                    type: "string",
                    description: "JavaScript to execute in browser (for 'evaluate' action). No imports allowed."
                  },
                  fullPage: {
                    type: "boolean",
                    description: "Capture full scrollable page (for 'screenshot' action)"
                  },
                  clear: {
                    type: "boolean",
                    description: "Clear logs after retrieving (for 'getConsoleLogs' action)"
                  },
                  eventName: {
                    type: "string",
                    description: "Embed event name to trigger (for 'triggerEmbedEvent' action)"
                  },
                  payload: {
                    type: "object",
                    description: "Optional payload to send with the embed event (for 'triggerEmbedEvent' action)",
                    additionalProperties: true
                  },
                  properties: {
                    type: "object",
                    description: "Embed properties to set (for 'setEmbedProperties' action)",
                    additionalProperties: true
                  },
                  x: {
                    type: "number",
                    description: "Absolute horizontal scroll position in pixels (for 'scroll' action)"
                  },
                  y: {
                    type: "number",
                    description: "Absolute vertical scroll position in pixels (for 'scroll' action)"
                  },
                  deltaX: {
                    type: "number",
                    description: "Relative horizontal scroll amount in pixels (for 'scroll' action)"
                  },
                  deltaY: {
                    type: "number",
                    description: "Relative vertical scroll amount in pixels (for 'scroll' action)"
                  },
                  testCaseId: {
                    type: "string",
                    description: "ID of the test case this action belongs to. Required when test cases are predefined. Links this action to a specific test case for status tracking."
                  }
                },
                required: ["action", "description"]
              }
            }
          ]
        }
      };
    }
    if (method === "tools/call") {
      const params = request.params;
      if (!params || params.name !== "playwright_action") {
        throw new Error(`Unknown tool: ${params?.name ?? "undefined"}`);
      }
      const action = params.arguments?.action;
      if (!action || !PLAYWRIGHT_ACTIONS.includes(action)) {
        throw new Error(`Unsupported Playwright action: ${String(action)}`);
      }
      actionLogger.logActionStart(action, params.arguments ?? {});
      const result = await executePlaywrightAction(action, page, params.arguments ?? {});
      actionLogger.logActionResult(result);
      const testCaseId = params.arguments?.testCaseId;
      if (testCaseId) {
        result.testCaseId = testCaseId;
      }
      return {
        jsonrpc: "2.0",
        id,
        result: {
          content: result
        }
      };
    }
    if (method === "disconnect") {
      return {
        jsonrpc: "2.0",
        id,
        result: {}
      };
    }
    throw new Error(`Unsupported method: ${method}`);
  } catch (error) {
    return {
      jsonrpc: "2.0",
      id,
      error: {
        code: -32603,
        message: String(error)
      }
    };
  }
}
async function checkForRuntimeErrors(page) {
  try {
    const errorElements = await page.locator('[data-testid="runtime-error-details"]').all();
    if (errorElements.length === 0) {
      return { hasErrors: false, errors: [] };
    }
    const errors = [];
    for (const element of errorElements) {
      try {
        const header = await element.locator("h3").textContent() || "Component error";
        let stack;
        try {
          const codeElement = element.locator("pre code");
          const codeText = await codeElement.textContent({ timeout: 1e3 });
          stack = codeText || void 0;
        } catch {
        }
        errors.push({ header, stack });
      } catch {
        errors.push({ header: "Unknown component error" });
      }
    }
    return { hasErrors: true, errors };
  } catch {
    return { hasErrors: false, errors: [] };
  }
}
async function captureScreenshot(page) {
  try {
    await page.evaluate(() => document.fonts.ready);
    await page.waitForTimeout(100);
  } catch {
  }
  const pngBuffer = await page.screenshot({
    fullPage: false,
    scale: "css",
    type: "png"
  });
  return {
    data: pngBuffer.toString("base64"),
    format: "png"
  };
}
async function drainEmbedEvents(page) {
  try {
    const events = await page.evaluate(() => {
      return window.__sbGetAndClearEmbedEvents?.() ?? null;
    });
    if (Array.isArray(events) && events.length > 0) {
      lastDrainedEmbedEvents = events;
      return events;
    }
    return null;
  } catch {
    return null;
  }
}
async function executePlaywrightAction(action, page, params) {
  switch (action) {
    case "navigate": {
      const url = params.url;
      const description = params.description || "Navigate to page";
      if (!url)
        throw new Error("Missing url parameter for navigate action");
      try {
        await page.goto(url, {
          waitUntil: "load",
          timeout: 6e4
          // 60 second timeout
        });
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        const runtimeErrors = await checkForRuntimeErrors(page);
        return {
          success: !runtimeErrors.hasErrors,
          action: "navigate",
          description,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            url,
            ...embedEvents ? { embedEvents } : {}
          },
          ...runtimeErrors.hasErrors && {
            runtimeErrors: runtimeErrors.errors,
            error: `Component crashed with ${runtimeErrors.errors.length} runtime error(s): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
          }
        };
      } catch (error) {
        console.error(`\u{1F3AC} MCP Server: Navigation failed: ${String(error)}`);
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: false,
          action: "navigate",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            url,
            ...embedEvents ? { embedEvents } : {}
          },
          error: `Navigation to ${url} failed: ${String(error)}`
        };
      }
    }
    case "click": {
      const selector = params.selector;
      const description = params.description || "Click element";
      if (!selector)
        throw new Error("Missing selector for click action");
      try {
        await page.locator(selector).click({ timeout: params.timeout ?? 1e4 });
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        const runtimeErrors = await checkForRuntimeErrors(page);
        return {
          success: !runtimeErrors.hasErrors,
          action: "click",
          description,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            selector,
            ...embedEvents ? { embedEvents } : {}
          },
          ...runtimeErrors.hasErrors && {
            runtimeErrors: runtimeErrors.errors,
            error: `Component crashed with ${runtimeErrors.errors.length} runtime error(s): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
          }
        };
      } catch (error) {
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: false,
          action: "click",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            selector,
            ...embedEvents ? { embedEvents } : {}
          },
          error: `Click failed on "${selector}": ${String(error)}`
        };
      }
    }
    case "fill": {
      const selector = params.selector;
      const value = params.value ?? "";
      const description = params.description || "Fill input";
      if (!selector)
        throw new Error("Missing selector for fill action");
      try {
        await page.locator(selector).fill(value, { timeout: params.timeout ?? 1e4 });
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        const runtimeErrors = await checkForRuntimeErrors(page);
        return {
          success: !runtimeErrors.hasErrors,
          action: "fill",
          description,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            selector,
            value,
            ...embedEvents ? { embedEvents } : {}
          },
          ...runtimeErrors.hasErrors && {
            runtimeErrors: runtimeErrors.errors,
            error: `Component crashed with ${runtimeErrors.errors.length} runtime error(s): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
          }
        };
      } catch (error) {
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: false,
          action: "fill",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            selector,
            value,
            ...embedEvents ? { embedEvents } : {}
          },
          error: `Fill failed on "${selector}": ${String(error)}`
        };
      }
    }
    case "screenshot": {
      const description = params.description || "Capture current state";
      const screenshot = await captureScreenshot(page);
      const embedEvents = await drainEmbedEvents(page);
      return {
        success: true,
        action: "screenshot",
        description,
        screenshot: screenshot.data,
        format: screenshot.format,
        context: {
          fullPage: Boolean(params.fullPage),
          ...embedEvents ? { embedEvents } : {}
        }
      };
    }
    case "getText": {
      const selector = params.selector;
      if (!selector)
        throw new Error("Missing selector for getText action");
      try {
        const text = await page.locator(selector).textContent({
          timeout: params.timeout ?? 1e4
        });
        return { success: true, text };
      } catch (error) {
        return {
          success: false,
          error: `getText failed on "${selector}": ${String(error)}`
        };
      }
    }
    case "waitForSelector": {
      const selector = params.selector;
      if (!selector) {
        throw new Error("Missing selector for waitForSelector action");
      }
      try {
        await page.locator(selector).waitFor({
          timeout: params.timeout ?? 15e3
        });
        return { success: true };
      } catch (error) {
        return {
          success: false,
          error: `waitForSelector failed on "${selector}": ${String(error)}`
        };
      }
    }
    case "evaluate": {
      const script = params.script;
      const description = params.description || "Execute JavaScript";
      if (typeof script !== "string") {
        throw new Error("Missing script for evaluate action");
      }
      const hasImport = /\bimport\s+/.test(script);
      const hasExport = /\bexport\s+/.test(script);
      const hasRequire = /\brequire\s*\(/.test(script);
      if (hasImport || hasExport || hasRequire) {
        throw new Error("Cannot use import/export/require statements in browser evaluate context. Please use plain JavaScript that can run in a browser console. For example, use 'document.querySelector' instead of importing libraries.");
      }
      try {
        const wrappedScript = `(() => {
          try {
            ${script}
          } catch (e) {
            return { error: e.toString(), stack: e.stack };
          }
        })()`;
        const result = await page.evaluate(wrappedScript);
        if (result && typeof result === "object" && "error" in result) {
          throw new Error(`Browser evaluation failed: ${result.error}`);
        }
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        const runtimeErrors = await checkForRuntimeErrors(page);
        return {
          success: !runtimeErrors.hasErrors,
          action: "evaluate",
          description,
          result,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            script: script.substring(0, 100) + (script.length > 100 ? "..." : ""),
            ...embedEvents ? { embedEvents } : {}
          },
          ...runtimeErrors.hasErrors && {
            runtimeErrors: runtimeErrors.errors,
            error: `Component crashed with ${runtimeErrors.errors.length} runtime error(s): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
          }
        };
      } catch (error) {
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        const errorMsg = String(error);
        if (errorMsg.includes("SyntaxError") || errorMsg.includes("import") || errorMsg.includes("module")) {
          return {
            success: false,
            action: "evaluate",
            description,
            screenshot: errorScreenshot?.data,
            format: errorScreenshot?.format ?? "png",
            context: {
              script: script.substring(0, 100) + (script.length > 100 ? "..." : ""),
              ...embedEvents ? { embedEvents } : {}
            },
            error: "JavaScript evaluation failed. Make sure your code is browser-compatible (no import/export statements). Error: " + errorMsg
          };
        }
        return {
          success: false,
          action: "evaluate",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            script: script.substring(0, 100) + (script.length > 100 ? "..." : ""),
            ...embedEvents ? { embedEvents } : {}
          },
          error: String(error)
        };
      }
    }
    case "getUrl": {
      return { success: true, url: page.url() };
    }
    case "reload": {
      await page.reload({
        waitUntil: params.waitUntil ?? "load",
        timeout: params.timeout
      });
      return { success: true };
    }
    case "getConsoleLogs": {
      const logs = [...capturedConsoleLogs];
      if (params.clear) {
        capturedConsoleLogs = [];
      }
      return {
        success: true,
        logs,
        count: logs.length
      };
    }
    case "getEmbedEvents": {
      const description = params.description || "Get embed events";
      const events = lastDrainedEmbedEvents ?? await drainEmbedEvents(page) ?? [];
      lastDrainedEmbedEvents = null;
      const screenshot = await captureScreenshot(page);
      const runtimeErrors = await checkForRuntimeErrors(page);
      return {
        success: !runtimeErrors.hasErrors,
        action: "getEmbedEvents",
        description,
        screenshot: screenshot.data,
        format: screenshot.format,
        events,
        count: events.length,
        ...runtimeErrors.hasErrors && {
          runtimeErrors: runtimeErrors.errors,
          error: `Component crashed with ${runtimeErrors.errors.length} runtime error(s): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
        }
      };
    }
    case "triggerEmbedEvent": {
      const description = params.description || "Trigger embed event";
      const eventName = params.eventName;
      const payload = params.payload ?? {};
      if (typeof eventName !== "string" || !eventName.trim()) {
        throw new Error("Missing eventName for triggerEmbedEvent action");
      }
      try {
        await page.evaluate(({ eventName: eventName2, payload: payload2 }) => {
          window.postMessage({
            type: "embed-trigger-event",
            payload: { eventName: eventName2, payload: payload2 },
            startTime: Date.now()
          }, "*");
        }, { eventName, payload });
        await page.waitForTimeout(50);
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        const runtimeErrors = await checkForRuntimeErrors(page);
        return {
          success: !runtimeErrors.hasErrors,
          action: "triggerEmbedEvent",
          description,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            eventName,
            ...embedEvents ? { embedEvents } : {}
          },
          ...runtimeErrors.hasErrors && {
            runtimeErrors: runtimeErrors.errors,
            error: `Component crashed with ${runtimeErrors.errors.length} runtime error(s): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
          }
        };
      } catch (error) {
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: false,
          action: "triggerEmbedEvent",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            eventName,
            ...embedEvents ? { embedEvents } : {}
          },
          error: `triggerEmbedEvent failed for "${eventName}": ${String(error)}`
        };
      }
    }
    case "setEmbedProperties": {
      const description = params.description || "Set embed properties";
      const properties = params.properties;
      if (!properties || typeof properties !== "object") {
        throw new Error("Missing properties for setEmbedProperties action");
      }
      try {
        await page.evaluate(({ properties: properties2 }) => {
          window.postMessage({
            type: "embed-property-change",
            payload: { properties: properties2 },
            startTime: Date.now()
          }, "*");
        }, { properties });
        await page.waitForTimeout(50);
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        const runtimeErrors = await checkForRuntimeErrors(page);
        return {
          success: !runtimeErrors.hasErrors,
          action: "setEmbedProperties",
          description,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            properties,
            ...embedEvents ? { embedEvents } : {}
          },
          ...runtimeErrors.hasErrors && {
            runtimeErrors: runtimeErrors.errors,
            error: `Component crashed with ${runtimeErrors.errors.length} runtime error(s): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
          }
        };
      } catch (error) {
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: false,
          action: "setEmbedProperties",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            properties,
            ...embedEvents ? { embedEvents } : {}
          },
          error: `setEmbedProperties failed: ${String(error)}`
        };
      }
    }
    case "scroll": {
      const { x, y, deltaX, deltaY } = params;
      const description = params.description || "Scroll page";
      try {
        await page.evaluate(({ x: x2, y: y2, deltaX: deltaX2, deltaY: deltaY2 }) => {
          if (deltaX2 !== void 0 || deltaY2 !== void 0) {
            window.scrollBy(deltaX2 ?? 0, deltaY2 ?? 0);
          } else if (x2 !== void 0 || y2 !== void 0) {
            window.scrollTo(x2 ?? window.scrollX, y2 ?? window.scrollY);
          }
        }, { x, y, deltaX, deltaY });
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: true,
          action: "scroll",
          description,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            x,
            y,
            deltaX,
            deltaY,
            ...embedEvents ? { embedEvents } : {}
          }
        };
      } catch (error) {
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: false,
          action: "scroll",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            x,
            y,
            deltaX,
            deltaY,
            ...embedEvents ? { embedEvents } : {}
          },
          error: `Scroll failed: ${String(error)}`
        };
      }
    }
    case "scrollIntoView": {
      const selector = params.selector;
      const description = params.description || "Scroll element into view";
      if (!selector) {
        throw new Error("Missing selector for scrollIntoView action");
      }
      try {
        await page.locator(selector).scrollIntoViewIfNeeded({
          timeout: params.timeout ?? 1e4
        });
        const screenshot = await captureScreenshot(page);
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: true,
          action: "scrollIntoView",
          description,
          screenshot: screenshot.data,
          format: screenshot.format,
          context: {
            selector,
            ...embedEvents ? { embedEvents } : {}
          }
        };
      } catch (error) {
        let errorScreenshot = null;
        try {
          errorScreenshot = await captureScreenshot(page);
        } catch {
        }
        const embedEvents = await drainEmbedEvents(page);
        return {
          success: false,
          action: "scrollIntoView",
          description,
          screenshot: errorScreenshot?.data,
          format: errorScreenshot?.format ?? "png",
          context: {
            selector,
            ...embedEvents ? { embedEvents } : {}
          },
          error: `scrollIntoView failed on "${selector}": ${String(error)}`
        };
      }
    }
    case "checkRuntimeErrors": {
      const description = params.description || "Check for component runtime errors";
      const screenshot = await captureScreenshot(page);
      const runtimeErrors = await checkForRuntimeErrors(page);
      return {
        success: !runtimeErrors.hasErrors,
        action: "checkRuntimeErrors",
        description,
        screenshot: screenshot.data,
        format: screenshot.format,
        hasErrors: runtimeErrors.hasErrors,
        errorCount: runtimeErrors.errors.length,
        ...runtimeErrors.hasErrors && {
          runtimeErrors: runtimeErrors.errors,
          error: `Found ${runtimeErrors.errors.length} component crash(es): ${runtimeErrors.errors.map((e) => e.header).join(", ")}`
        }
      };
    }
    default:
      throw new Error(`Unhandled Playwright action: ${action}`);
  }
}
export {
  startEmbeddedPlaywrightMcpServer
};
//# sourceMappingURL=embedded-playwright-mcp-server-ABTXT2CA.js.map
