"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const listeners = [];
function emitCommand(subcommand, args, result, selectorContext) {
  for (const fn of listeners) {
    try {
      fn(subcommand, args, result, selectorContext);
    } catch {
    }
  }
}
function getSelectorContextForRef(refId) {
  const el = refMap.get(refId);
  if (!el) return void 0;
  const role = getRole(el);
  const name = getAccessibleName(el);
  const testId = el.getAttribute("data-testid") ?? void 0;
  let elementRect;
  if (typeof el.getBoundingClientRect === "function") {
    const r = el.getBoundingClientRect();
    elementRect = { x: r.x, y: r.y, width: r.width, height: r.height };
  }
  return {
    role: role || el.tagName.toLowerCase(),
    name,
    tagName: el.tagName,
    testId,
    elementRect
  };
}
let refMap = /* @__PURE__ */ new Map();
let refCounter = 0;
const consoleMessages = [];
const networkRequests = [];
function installBridgeListener() {
  if (typeof window === "undefined") return;
  window.addEventListener("message", (event) => {
    const data = event.data;
    if (!data || typeof data !== "object") return;
    if (data.type === "almostnode-console") {
      if (consoleMessages.length < 1e3) {
        const text = Array.isArray(data.args) ? data.args.join(" ") : String(data.args);
        consoleMessages.push({ level: data.level || "log", text });
      }
    }
    if (data.type === "almostnode-network") {
      if (networkRequests.length < 1e3) {
        networkRequests.push({
          method: data.method || "GET",
          url: data.url || "",
          status: data.status || 0,
          statusText: data.statusText || "",
          duration: data.duration || 0,
          size: data.size || 0
        });
      }
    }
  });
}
installBridgeListener();
function getPreviewIframe() {
  if (typeof document === "undefined") return null;
  return document.getElementById("webidePreview");
}
function getIframeDoc(iframe) {
  try {
    return iframe.contentDocument;
  } catch {
    return null;
  }
}
function getIframeWindow(iframe) {
  try {
    return iframe.contentWindow;
  } catch {
    return null;
  }
}
function resolveRef(ref) {
  return refMap.get(ref) ?? null;
}
function ok(stdout) {
  return { stdout, stderr: "", exitCode: 0 };
}
function err(stderr) {
  return { stdout: "", stderr, exitCode: 1 };
}
function delay(ms) {
  return new Promise((r) => setTimeout(r, ms));
}
function isInputElement(el) {
  return el.tagName === "INPUT";
}
function isTextAreaElement(el) {
  return el.tagName === "TEXTAREA";
}
function isInputOrTextArea(el) {
  return el.tagName === "INPUT" || el.tagName === "TEXTAREA";
}
const IMPLICIT_ROLES = {
  A: "link",
  BUTTON: "button",
  INPUT: "textbox",
  TEXTAREA: "textbox",
  SELECT: "combobox",
  IMG: "img",
  NAV: "navigation",
  MAIN: "main",
  HEADER: "banner",
  FOOTER: "contentinfo",
  ASIDE: "complementary",
  SECTION: "region",
  ARTICLE: "article",
  FORM: "form",
  TABLE: "table",
  TH: "columnheader",
  TD: "cell",
  TR: "row",
  UL: "list",
  OL: "list",
  LI: "listitem",
  H1: "heading",
  H2: "heading",
  H3: "heading",
  H4: "heading",
  H5: "heading",
  H6: "heading",
  DIALOG: "dialog",
  DETAILS: "group",
  SUMMARY: "button",
  PROGRESS: "progressbar",
  METER: "meter",
  OUTPUT: "status"
};
const SKIP_TAGS = /* @__PURE__ */ new Set(["SCRIPT", "STYLE", "NOSCRIPT", "SVG", "HEAD", "META", "LINK", "BR", "HR"]);
function isVisible(el) {
  const htmlEl = el;
  if (!htmlEl.style) return true;
  const style = htmlEl.style;
  if (style.display === "none" || style.visibility === "hidden") return false;
  if (htmlEl.hidden) return false;
  if (htmlEl.offsetParent === null && style.position !== "fixed" && style.position !== "sticky") {
    if (el.parentElement && el.parentElement.tagName !== "BODY") return false;
  }
  return true;
}
function getRole(el) {
  const explicit = el.getAttribute("role");
  if (explicit) return explicit;
  return IMPLICIT_ROLES[el.tagName] ?? null;
}
function getAccessibleName(el) {
  var _a;
  const ariaLabel = el.getAttribute("aria-label");
  if (ariaLabel) return ariaLabel;
  const ariaLabelledBy = el.getAttribute("aria-labelledby");
  if (ariaLabelledBy) {
    const doc = el.ownerDocument;
    const parts = ariaLabelledBy.split(/\s+/).map((id) => {
      var _a2, _b;
      return (_b = (_a2 = doc.getElementById(id)) == null ? void 0 : _a2.textContent) == null ? void 0 : _b.trim();
    }).filter(Boolean);
    if (parts.length) return parts.join(" ");
  }
  if (isInputOrTextArea(el) || el.tagName === "SELECT") {
    if (el.id) {
      const label = el.ownerDocument.querySelector(`label[for="${el.id}"]`);
      if (label) return ((_a = label.textContent) == null ? void 0 : _a.trim()) || "";
    }
    const placeholder = el.getAttribute("placeholder");
    if (placeholder) return placeholder;
  }
  if (el.tagName === "IMG") {
    return el.alt || "";
  }
  return "";
}
function buildSnapshotTree(root) {
  refMap = /* @__PURE__ */ new Map();
  refCounter = 0;
  const results = [];
  function walk(el) {
    var _a, _b;
    if (SKIP_TAGS.has(el.tagName)) return null;
    if (!isVisible(el)) return null;
    const role = getRole(el);
    const children = [];
    for (const child of Array.from(el.children)) {
      const node = walk(child);
      if (node) children.push(node);
    }
    const hasRole = role !== null;
    const isTextLeaf = !hasRole && children.length === 0 && ((_a = el.textContent) == null ? void 0 : _a.trim()) && el.childElementCount === 0;
    if (!hasRole && !isTextLeaf) {
      return children.length === 1 ? children[0] : children.length > 1 ? { role: "group", name: "", ref: "", attrs: [], children } : null;
    }
    refCounter++;
    const ref = `e${refCounter}`;
    refMap.set(ref, el);
    const name = getAccessibleName(el) || (isTextLeaf ? el.textContent.trim() : "");
    const attrs = [];
    if (/^H[1-6]$/.test(el.tagName)) {
      attrs.push(`level=${el.tagName[1]}`);
    }
    if (isInputElement(el)) {
      const inputEl = el;
      const type = inputEl.type.toLowerCase();
      if (type === "checkbox" || type === "radio") {
        attrs.push(inputEl.checked ? "checked" : "unchecked");
      }
      if (type !== "text" && type !== "search" && type !== "password" && type !== "email" && type !== "url" && type !== "tel" && type !== "number") {
        attrs.push(`type=${type}`);
      }
    }
    if ((_b = el.hasAttribute) == null ? void 0 : _b.call(el, "disabled")) {
      attrs.push("disabled");
    }
    if (isInputOrTextArea(el) && el.value) {
      const val = el.value;
      const truncated = val.length > 40 ? val.slice(0, 40) + "..." : val;
      attrs.push(`value="${truncated}"`);
    }
    if (el.tagName === "A") {
      const href = el.getAttribute("href");
      if (href) {
        const truncated = href.length > 60 ? href.slice(0, 60) + "..." : href;
        attrs.push(`url="${truncated}"`);
      }
    }
    return {
      role: role || "text",
      name: name.length > 80 ? name.slice(0, 80) + "..." : name,
      ref,
      attrs,
      children
    };
  }
  for (const child of Array.from(root.children)) {
    const node = walk(child);
    if (node) results.push(node);
  }
  return results;
}
function renderTree(nodes, indent = 0) {
  const lines = [];
  const prefix = "  ".repeat(indent);
  for (const node of nodes) {
    let line = `${prefix}- ${node.role}`;
    if (node.name) line += ` "${node.name}"`;
    for (const attr of node.attrs) line += ` [${attr}]`;
    if (node.ref) line += ` [ref=${node.ref}]`;
    lines.push(line);
    if (node.children.length > 0) {
      lines.push(renderTree(node.children, indent + 1));
    }
  }
  return lines.join("\n");
}
async function resolvePreviewUrl(url) {
  var _a;
  try {
    const parsed = new URL(url);
    if (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") {
      const port = parseInt(parsed.port || (parsed.protocol === "https:" ? "443" : "80"), 10);
      const { getServerBridge } = await Promise.resolve().then(() => require("./fetch-virtual-server-J6SUa9HS.cjs")).then((n) => n.serverBridge);
      const bridge = getServerBridge();
      const virtualBase = bridge.getServerUrl(port);
      return `${virtualBase}${parsed.pathname}${parsed.search}${parsed.hash}`;
    }
  } catch {
    if (url.startsWith("/")) {
      try {
        const { getServerBridge } = await Promise.resolve().then(() => require("./fetch-virtual-server-J6SUa9HS.cjs")).then((n) => n.serverBridge);
        const bridge = getServerBridge();
        const iframe = document.querySelector('iframe[src*="/__virtual__/"]');
        const iframeMatch = (_a = iframe == null ? void 0 : iframe.src) == null ? void 0 : _a.match(/\/__virtual__\/(\d+)/);
        const port = iframeMatch ? parseInt(iframeMatch[1], 10) : bridge.getServerPorts()[0];
        if (port) {
          return `${bridge.getServerUrl(port)}${url}`;
        }
      } catch {
      }
    }
  }
  return url;
}
function revealPreviewIframe(iframe, url) {
  var _a, _b;
  const emptyState = (_a = iframe.parentElement) == null ? void 0 : _a.querySelector(
    ".almostnode-preview-surface__empty"
  );
  if (emptyState) {
    emptyState.hidden = true;
    emptyState.style.display = "none";
  }
  iframe.hidden = false;
  iframe.style.display = "block";
  const status = (_b = iframe.closest(".almostnode-preview-surface")) == null ? void 0 : _b.querySelector(
    ".almostnode-preview-surface__status"
  );
  if (status) {
    status.textContent = url;
  }
}
async function cmdOpen(args) {
  const url = args[0];
  if (!url) return err("usage: playwright-cli open <url>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found. Run your dev server first.\n");
  const resolvedUrl = await resolvePreviewUrl(url);
  revealPreviewIframe(iframe, resolvedUrl);
  iframe.src = resolvedUrl;
  await new Promise((resolve) => {
    const onLoad = () => {
      iframe.removeEventListener("load", onLoad);
      resolve();
    };
    iframe.addEventListener("load", onLoad);
    setTimeout(resolve, 1e4);
  });
  await delay(100);
  return ok(`Navigated to ${resolvedUrl}
`);
}
async function cmdSnapshot() {
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found. Run your dev server first.\n");
  const doc = getIframeDoc(iframe);
  if (!doc || !doc.body) return err("preview iframe has no document. Wait for the page to load.\n");
  const tree = buildSnapshotTree(doc.body);
  if (tree.length === 0) {
    return ok("(empty page - no accessible elements found)\n");
  }
  const output = renderTree(tree);
  return ok(output + "\n");
}
async function cmdClick(args) {
  const refId = args[0];
  if (!refId) return err("usage: playwright-cli click <ref>\n");
  const el = resolveRef(refId);
  if (!el) return err(`element ref '${refId}' not found. Run 'playwright-cli snapshot' first.
`);
  if (!el.isConnected) return err(`element '${refId}' is no longer in the document.
`);
  const iframe = getPreviewIframe();
  const doc = el.ownerDocument;
  const win = doc.defaultView || iframe && getIframeWindow(iframe) || window;
  if (typeof el.scrollIntoView === "function") {
    el.scrollIntoView({ block: "center" });
  }
  await delay(0);
  if (typeof el.click === "function") {
    el.click();
  } else {
    const ME = win.MouseEvent || MouseEvent;
    el.dispatchEvent(
      new ME("click", { bubbles: true, cancelable: true, view: win })
    );
  }
  await delay(50);
  return ok(`Clicked ${refId}
`);
}
async function cmdFill(args) {
  var _a, _b, _c;
  const refId = args[0];
  const value = args.slice(1).join(" ");
  if (!refId || value === void 0) return err("usage: playwright-cli fill <ref> <text>\n");
  const el = resolveRef(refId);
  if (!el) return err(`element ref '${refId}' not found. Run 'playwright-cli snapshot' first.
`);
  if (!el.isConnected) return err(`element '${refId}' is no longer in the document.
`);
  if (!isInputOrTextArea(el) && !el.hasAttribute("contenteditable")) {
    return err(`element '${refId}' cannot be filled (not an input/textarea).
`);
  }
  const iframe = getPreviewIframe();
  const doc = el.ownerDocument;
  const win = doc.defaultView || iframe && getIframeWindow(iframe) || window;
  if (typeof el.focus === "function") el.focus();
  if (isInputOrTextArea(el)) {
    const isTextarea = isTextAreaElement(el);
    const proto = isTextarea ? (_a = win == null ? void 0 : win.HTMLTextAreaElement) == null ? void 0 : _a.prototype : (_b = win == null ? void 0 : win.HTMLInputElement) == null ? void 0 : _b.prototype;
    const nativeSetter = proto ? (_c = Object.getOwnPropertyDescriptor(proto, "value")) == null ? void 0 : _c.set : null;
    if (nativeSetter) {
      nativeSetter.call(el, value);
    } else {
      el.value = value;
    }
    const tracker = el._valueTracker;
    if (tracker) {
      tracker.setValue("");
    }
    const InputEventCtor = win.InputEvent || InputEvent;
    const EventCtor = win.Event || Event;
    let inputEvent;
    try {
      inputEvent = new InputEventCtor("input", {
        bubbles: true,
        cancelable: true,
        inputType: "insertText",
        data: value
      });
    } catch {
      inputEvent = new EventCtor("input", { bubbles: true, cancelable: true });
    }
    el.dispatchEvent(inputEvent);
    el.dispatchEvent(new EventCtor("change", { bubbles: true, cancelable: true }));
  } else {
    el.textContent = value;
    const EventCtor = win.Event || Event;
    el.dispatchEvent(new EventCtor("input", { bubbles: true }));
  }
  await delay(50);
  return ok(`Filled ${refId} with "${value}"
`);
}
async function cmdType(args) {
  var _a, _b, _c;
  const text = args.join(" ");
  if (!text) return err("usage: playwright-cli type <text>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found. Run your dev server first.\n");
  const doc = getIframeDoc(iframe);
  if (!doc) return err("preview iframe has no document.\n");
  const el = doc.activeElement;
  if (!el) return err("no element is focused. Click or fill an element first.\n");
  const win = doc.defaultView || getIframeWindow(iframe) || window;
  const KE = win.KeyboardEvent || KeyboardEvent;
  const isTextarea = isTextAreaElement(el);
  const proto = isTextarea ? (_a = win == null ? void 0 : win.HTMLTextAreaElement) == null ? void 0 : _a.prototype : (_b = win == null ? void 0 : win.HTMLInputElement) == null ? void 0 : _b.prototype;
  const nativeSetter = isInputOrTextArea(el) && proto ? (_c = Object.getOwnPropertyDescriptor(proto, "value")) == null ? void 0 : _c.set : null;
  for (const char of text) {
    el.dispatchEvent(new KE("keydown", { key: char, bubbles: true, cancelable: true }));
    if (isInputOrTextArea(el)) {
      const InputEventCtor = win.InputEvent || InputEvent;
      try {
        el.dispatchEvent(
          new InputEventCtor("beforeinput", {
            bubbles: true,
            cancelable: true,
            inputType: "insertText",
            data: char
          })
        );
      } catch {
      }
      const newValue = (el.value || "") + char;
      if (nativeSetter) {
        nativeSetter.call(el, newValue);
      } else {
        el.value = newValue;
      }
      const tracker = el._valueTracker;
      if (tracker) tracker.setValue("");
      try {
        el.dispatchEvent(
          new InputEventCtor("input", {
            bubbles: true,
            cancelable: true,
            inputType: "insertText",
            data: char
          })
        );
      } catch {
        el.dispatchEvent(new (win.Event || Event)("input", { bubbles: true }));
      }
    }
    el.dispatchEvent(new KE("keyup", { key: char, bubbles: true, cancelable: true }));
  }
  await delay(50);
  return ok(`Typed "${text}"
`);
}
async function cmdPress(args) {
  var _a, _b, _c;
  const key = args[0];
  if (!key) return err("usage: playwright-cli press <key>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found. Run your dev server first.\n");
  const doc = getIframeDoc(iframe);
  if (!doc) return err("preview iframe has no document.\n");
  const el = doc.activeElement || doc.body;
  const win = doc.defaultView || getIframeWindow(iframe) || window;
  const KE = win.KeyboardEvent || KeyboardEvent;
  if (typeof el.focus === "function") el.focus();
  el.dispatchEvent(new KE("keydown", { key, bubbles: true, cancelable: true }));
  if (key.length === 1 && isInputOrTextArea(el)) {
    const InputEventCtor = win.InputEvent || InputEvent;
    const isTextarea = isTextAreaElement(el);
    const proto = isTextarea ? (_a = win == null ? void 0 : win.HTMLTextAreaElement) == null ? void 0 : _a.prototype : (_b = win == null ? void 0 : win.HTMLInputElement) == null ? void 0 : _b.prototype;
    const nativeSetter = proto ? (_c = Object.getOwnPropertyDescriptor(proto, "value")) == null ? void 0 : _c.set : null;
    try {
      el.dispatchEvent(
        new InputEventCtor("beforeinput", {
          bubbles: true,
          cancelable: true,
          inputType: "insertText",
          data: key
        })
      );
    } catch {
    }
    const newValue = (el.value || "") + key;
    if (nativeSetter) {
      nativeSetter.call(el, newValue);
    } else {
      el.value = newValue;
    }
    const tracker = el._valueTracker;
    if (tracker) tracker.setValue("");
    try {
      el.dispatchEvent(
        new InputEventCtor("input", {
          bubbles: true,
          cancelable: true,
          inputType: "insertText",
          data: key
        })
      );
    } catch {
      el.dispatchEvent(new (win.Event || Event)("input", { bubbles: true }));
    }
  } else if (key === "Enter") {
    el.dispatchEvent(new KE("keypress", { key, bubbles: true, cancelable: true }));
    if (isInputElement(el) && el.form && typeof el.form.requestSubmit === "function") {
      try {
        el.form.requestSubmit();
      } catch {
      }
    }
  } else {
    el.dispatchEvent(new KE("keypress", { key, bubbles: true, cancelable: true }));
  }
  el.dispatchEvent(new KE("keyup", { key, bubbles: true, cancelable: true }));
  await delay(50);
  return ok(`Pressed ${key}
`);
}
async function cmdHover(args) {
  const refId = args[0];
  if (!refId) return err("usage: playwright-cli hover <ref>\n");
  const el = resolveRef(refId);
  if (!el) return err(`element ref '${refId}' not found. Run 'playwright-cli snapshot' first.
`);
  if (!el.isConnected) return err(`element '${refId}' is no longer in the document.
`);
  const iframe = getPreviewIframe();
  const doc = el.ownerDocument;
  const win = doc.defaultView || iframe && getIframeWindow(iframe) || window;
  const ME = win.MouseEvent || MouseEvent;
  el.dispatchEvent(new ME("mouseover", { bubbles: true, cancelable: true, view: win }));
  el.dispatchEvent(new ME("mouseenter", { bubbles: false, cancelable: false, view: win }));
  await delay(0);
  return ok(`Hovered ${refId}
`);
}
async function cmdEval(args) {
  const expr = args.join(" ");
  if (!expr) return err("usage: playwright-cli eval <expression>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found. Run your dev server first.\n");
  const win = getIframeWindow(iframe);
  if (!win) return err("preview iframe has no window.\n");
  try {
    const result = win.eval(expr);
    const output = typeof result === "string" ? result : JSON.stringify(result, null, 2);
    return ok((output ?? "undefined") + "\n");
  } catch (e) {
    return err(`eval error: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
async function cmdConsole(args) {
  const levelFilter = args[0];
  const severityOrder = ["error", "warn", "warning", "log", "info", "debug"];
  let filtered = consoleMessages;
  if (levelFilter) {
    const normalizedFilter = levelFilter === "warning" ? "warn" : levelFilter;
    const filterIdx = severityOrder.indexOf(normalizedFilter);
    if (filterIdx === -1) {
      return err(`unknown console level '${levelFilter}'. Use: error, warning, info, debug
`);
    }
    const allowedLevels = new Set(severityOrder.slice(0, filterIdx + 1));
    filtered = consoleMessages.filter((m) => {
      const normalized = m.level === "warn" ? "warn" : m.level;
      return allowedLevels.has(normalized);
    });
  }
  if (filtered.length === 0) {
    return ok("(no console messages)\n");
  }
  const lines = filtered.map((m) => `[${m.level}] ${m.text}`);
  return ok(lines.join("\n") + "\n");
}
async function cmdNetwork() {
  if (networkRequests.length === 0) {
    return ok("(no network requests)\n");
  }
  const lines = networkRequests.map((r) => {
    const sizeStr = r.size > 0 ? ` ${r.size}B` : "";
    return `[fetch] ${r.method} ${r.url} ${r.status} ${r.statusText} ${r.duration}ms${sizeStr}`;
  });
  return ok(lines.join("\n") + "\n");
}
function parseCookies(doc) {
  const raw = doc.cookie;
  if (!raw) return [];
  return raw.split(";").map((c) => {
    const [name, ...rest] = c.trim().split("=");
    return { name, value: rest.join("=") };
  });
}
async function cmdCookieList(args) {
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found.\n");
  const doc = getIframeDoc(iframe);
  if (!doc) return err("preview iframe has no document.\n");
  const domainFilter = args[0] === "--domain" ? args[1] : void 0;
  const cookies = parseCookies(doc);
  if (cookies.length === 0) return ok("(no cookies)\n");
  const filtered = domainFilter ? cookies.filter((c) => c.name.includes(domainFilter)) : cookies;
  if (filtered.length === 0) return ok("(no matching cookies)\n");
  const lines = filtered.map((c) => `${c.name}=${c.value}`);
  return ok(lines.join("\n") + "\n");
}
async function cmdCookieGet(args) {
  const name = args[0];
  if (!name) return err("usage: playwright-cli cookie-get <name>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found.\n");
  const doc = getIframeDoc(iframe);
  if (!doc) return err("preview iframe has no document.\n");
  const cookie = parseCookies(doc).find((c) => c.name === name);
  if (!cookie) return ok(`(cookie '${name}' not found)
`);
  return ok(`${cookie.value}
`);
}
async function cmdCookieSet(args) {
  const name = args[0];
  const value = args.slice(1).join(" ");
  if (!name || value === void 0) return err("usage: playwright-cli cookie-set <name> <value>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found.\n");
  const doc = getIframeDoc(iframe);
  if (!doc) return err("preview iframe has no document.\n");
  doc.cookie = `${name}=${value};path=/`;
  return ok(`Set cookie ${name}
`);
}
async function cmdCookieDelete(args) {
  const name = args[0];
  if (!name) return err("usage: playwright-cli cookie-delete <name>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found.\n");
  const doc = getIframeDoc(iframe);
  if (!doc) return err("preview iframe has no document.\n");
  doc.cookie = `${name}=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT`;
  return ok(`Deleted cookie ${name}
`);
}
async function cmdCookieClear() {
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found.\n");
  const doc = getIframeDoc(iframe);
  if (!doc) return err("preview iframe has no document.\n");
  const cookies = parseCookies(doc);
  for (const c of cookies) {
    doc.cookie = `${c.name}=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT`;
  }
  return ok(`Cleared ${cookies.length} cookie(s)
`);
}
function getStorage(type) {
  const iframe = getPreviewIframe();
  if (!iframe) return null;
  const win = getIframeWindow(iframe);
  if (!win) return null;
  return type === "local" ? win.localStorage : win.sessionStorage;
}
function storageLabel(type) {
  return type === "local" ? "localStorage" : "sessionStorage";
}
async function cmdStorageList(type) {
  const storage = getStorage(type);
  if (!storage) return err("no preview iframe found.\n");
  if (storage.length === 0) return ok(`(no ${storageLabel(type)} entries)
`);
  const lines = [];
  for (let i = 0; i < storage.length; i++) {
    const key = storage.key(i);
    const val = storage.getItem(key) ?? "";
    const truncated = val.length > 80 ? val.slice(0, 80) + "..." : val;
    lines.push(`${key} = ${truncated}`);
  }
  return ok(lines.join("\n") + "\n");
}
async function cmdStorageGet(type, args) {
  const key = args[0];
  if (!key) return err(`usage: playwright-cli ${storageLabel(type).toLowerCase()}-get <key>
`);
  const storage = getStorage(type);
  if (!storage) return err("no preview iframe found.\n");
  const val = storage.getItem(key);
  if (val === null) return ok(`(key '${key}' not found)
`);
  return ok(`${val}
`);
}
async function cmdStorageSet(type, args) {
  const key = args[0];
  const value = args.slice(1).join(" ");
  if (!key || value === void 0) return err(`usage: playwright-cli ${storageLabel(type).toLowerCase()}-set <key> <value>
`);
  const storage = getStorage(type);
  if (!storage) return err("no preview iframe found.\n");
  storage.setItem(key, value);
  return ok(`Set ${storageLabel(type)} key '${key}'
`);
}
async function cmdStorageDelete(type, args) {
  const key = args[0];
  if (!key) return err(`usage: playwright-cli ${storageLabel(type).toLowerCase()}-delete <key>
`);
  const storage = getStorage(type);
  if (!storage) return err("no preview iframe found.\n");
  storage.removeItem(key);
  return ok(`Deleted ${storageLabel(type)} key '${key}'
`);
}
async function cmdStorageClear(type) {
  const storage = getStorage(type);
  if (!storage) return err("no preview iframe found.\n");
  const count = storage.length;
  storage.clear();
  return ok(`Cleared ${count} ${storageLabel(type)} entry/entries
`);
}
async function cmdClose() {
  refMap = /* @__PURE__ */ new Map();
  consoleMessages.length = 0;
  networkRequests.length = 0;
  return ok("Cleared state.\n");
}
async function cmdResize(args) {
  const w = parseInt(args[0], 10);
  const h = parseInt(args[1], 10);
  if (isNaN(w) || isNaN(h)) return err("usage: playwright-cli resize <width> <height>\n");
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found. Run your dev server first.\n");
  iframe.style.width = `${w}px`;
  iframe.style.height = `${h}px`;
  return ok(`Resized preview to ${w}x${h}
`);
}
async function cmdScreenshot(args, vfs) {
  const iframe = getPreviewIframe();
  if (!iframe) return err("no preview iframe found. Run your dev server first.\n");
  const doc = getIframeDoc(iframe);
  if (!doc || !doc.body) return err("preview iframe has no document. Wait for the page to load.\n");
  const outputPath = args[0] || "/tmp/screenshot.png";
  const parentDir = outputPath.substring(0, outputPath.lastIndexOf("/")) || "/";
  if (!vfs.existsSync(parentDir)) {
    vfs.mkdirSync(parentDir, { recursive: true });
  }
  try {
    const html2canvas = (await Promise.resolve().then(() => require("./html2canvas.esm-CpBUo6M0.cjs"))).default;
    const canvas = await html2canvas(doc.body, {
      windowWidth: iframe.clientWidth || doc.documentElement.scrollWidth,
      windowHeight: iframe.clientHeight || doc.documentElement.scrollHeight,
      width: iframe.clientWidth || doc.documentElement.scrollWidth,
      height: iframe.clientHeight || doc.documentElement.scrollHeight,
      useCORS: true,
      allowTaint: true,
      foreignObjectRendering: false,
      logging: false
    });
    const blob = await new Promise((resolve, reject) => {
      canvas.toBlob((b) => b ? resolve(b) : reject(new Error("toBlob failed")), "image/png");
    });
    const pngData = new Uint8Array(await blob.arrayBuffer());
    vfs.writeFileSync(outputPath, pngData);
    return ok(`Screenshot saved to ${outputPath} (${pngData.length} bytes)
`);
  } catch (e) {
    return err(`screenshot failed: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
function cmdHelp() {
  return ok(
    `playwright-cli — interact with the preview iframe

Commands:
  open <url>              Navigate the preview iframe to a URL
  snapshot                Build accessibility tree with element refs
  click <ref>             Click an element by ref (e.g. e3)
  fill <ref> <text>       Fill an input/textarea with text
  type <text>             Type text into the focused element
  press <key>             Press a keyboard key (e.g. Enter, ArrowDown)
  hover <ref>             Hover over an element
  eval <expression>       Evaluate JS in the preview iframe
  console [level]         Show captured console messages
  network                 Show captured network requests
  cookie-list [--domain]  List cookies
  cookie-get <name>       Get a cookie value
  cookie-set <name> <val> Set a cookie
  cookie-delete <name>    Delete a cookie
  cookie-clear            Clear all cookies
  localstorage-list       List localStorage entries
  localstorage-get <key>  Get localStorage value
  localstorage-set <k> <v> Set localStorage value
  localstorage-delete <k> Delete localStorage entry
  localstorage-clear      Clear all localStorage
  sessionstorage-list     List sessionStorage entries
  sessionstorage-get <k>  Get sessionStorage value
  sessionstorage-set <k> <v> Set sessionStorage value
  sessionstorage-delete <k> Delete sessionStorage entry
  sessionstorage-clear    Clear all sessionStorage
  resize <width> <height> Resize the preview iframe
  screenshot [path]       Capture preview as PNG (default: /tmp/screenshot.png)
  close                   Clear element refs and console state
  help                    Show this help message

Workflow:
  1. Start your dev server (npm run dev)
  2. playwright-cli snapshot    — get element refs
  3. playwright-cli click e3    — interact using refs
  4. playwright-cli snapshot    — re-snapshot after DOM changes
`
  );
}
async function runPlaywrightCommand(args, _ctx, _vfs) {
  const subcommand = args[0];
  if (!subcommand || subcommand === "help" || subcommand === "--help") {
    return cmdHelp();
  }
  const subArgs = args.slice(1);
  let result;
  let selectorContext;
  const refBasedCommands = /* @__PURE__ */ new Set(["click", "fill", "hover"]);
  if (refBasedCommands.has(subcommand) && subArgs[0]) {
    const el = refMap.get(subArgs[0]);
    if (el && typeof el.scrollIntoView === "function") {
      el.scrollIntoView({ block: "center" });
    }
    selectorContext = getSelectorContextForRef(subArgs[0]);
  }
  switch (subcommand) {
    case "open":
      result = await cmdOpen(subArgs);
      break;
    case "snapshot":
      result = await cmdSnapshot();
      break;
    case "click":
      result = await cmdClick(subArgs);
      break;
    case "fill":
      result = await cmdFill(subArgs);
      break;
    case "type":
      result = await cmdType(subArgs);
      break;
    case "press":
      result = await cmdPress(subArgs);
      break;
    case "hover":
      result = await cmdHover(subArgs);
      break;
    case "eval":
      result = await cmdEval(subArgs);
      break;
    case "console":
      result = await cmdConsole(subArgs);
      break;
    case "network":
      result = await cmdNetwork();
      break;
    case "cookie-list":
      result = await cmdCookieList(subArgs);
      break;
    case "cookie-get":
      result = await cmdCookieGet(subArgs);
      break;
    case "cookie-set":
      result = await cmdCookieSet(subArgs);
      break;
    case "cookie-delete":
      result = await cmdCookieDelete(subArgs);
      break;
    case "cookie-clear":
      result = await cmdCookieClear();
      break;
    case "localstorage-list":
      result = await cmdStorageList("local");
      break;
    case "localstorage-get":
      result = await cmdStorageGet("local", subArgs);
      break;
    case "localstorage-set":
      result = await cmdStorageSet("local", subArgs);
      break;
    case "localstorage-delete":
      result = await cmdStorageDelete("local", subArgs);
      break;
    case "localstorage-clear":
      result = await cmdStorageClear("local");
      break;
    case "sessionstorage-list":
      result = await cmdStorageList("session");
      break;
    case "sessionstorage-get":
      result = await cmdStorageGet("session", subArgs);
      break;
    case "sessionstorage-set":
      result = await cmdStorageSet("session", subArgs);
      break;
    case "sessionstorage-delete":
      result = await cmdStorageDelete("session", subArgs);
      break;
    case "sessionstorage-clear":
      result = await cmdStorageClear("session");
      break;
    case "close":
      result = await cmdClose();
      break;
    case "resize":
      result = await cmdResize(subArgs);
      break;
    case "screenshot":
      result = await cmdScreenshot(subArgs, _vfs);
      break;
    default:
      return err(`unknown command: ${subcommand}. Run 'playwright-cli help' for usage.
`);
  }
  emitCommand(subcommand, subArgs, result, selectorContext);
  return result;
}
exports.buildSnapshotTree = buildSnapshotTree;
exports.getAccessibleName = getAccessibleName;
exports.getRole = getRole;
exports.runPlaywrightCommand = runPlaywrightCommand;
//# sourceMappingURL=playwright-command-BfXCt3-x.cjs.map
