"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var pageBlueprint_exports = {};
__export(pageBlueprint_exports, {
  default: () => pageBlueprint_default
});
module.exports = __toCommonJS(pageBlueprint_exports);
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
var import_tool = require("./tool");
var import_blueprint = require("../../../dom-analyzer/blueprint");
var import_blueprintDiff = require("../../../dom-analyzer/blueprintDiff");
var import_possibleAssertions = require("../../../dom-analyzer/possibleAssertions");
const blueprint = (0, import_tool.defineTabTool)({
  capability: "core",
  schema: {
    name: "browser_blueprint",
    title: "Build PageBlueprint for the current page",
    description: [
      "Build a PageBlueprint for the currently loaded page.",
      "",
      "RETURN SHAPE \u2014 two cases:",
      "",
      "1. First call at a URL (or after the cache has evicted the entry):",
      '   {"isFullCapture": true, "pageHash": "...", "blueprint": {...full PageBlueprint...}, "possibleAssertions": [...]}',
      "   The possibleAssertions[] for full captures is small (\u22642 entries):",
      "   a HIGH-tier toHaveURL assertion plus a LOW-tier heading visibility",
      "   check. Anchor candidates only \u2014 full deltas come from same-URL pairs.",
      "",
      "2. Subsequent call at the same URL:",
      '   {"isFullCapture": false, "pageHash": "...", "previousPageHash": "...", "delta": {...BlueprintDelta...}, "possibleAssertions": [...]}',
      "   The delta is computed automatically against your most recent blueprint at this URL.",
      "   Empty arrays in delta (elementsAdded/Removed/textChanges) mean the action did not change observable DOM.",
      "",
      "   The possibleAssertions[] here is built mechanically from the delta",
      "   (interactive element add/remove, text changes, repeating-element",
      "   counts) and tends to carry richer signal than the full-capture set.",
      "",
      "   In both cases possibleAssertions are options the data supports, not",
      "   directives \u2014 read each, pick the ones that test something meaningful,",
      "   edit the locator if needed, and emit them as browser_assert calls.",
      "   Skip noise (e.g. timestamps).",
      "",
      "CAPTURE-ACT-CAPTURE: capture once before your action, perform the action, capture again \u2014 the second",
      "response IS the diff. You only need browser_blueprint_diff when comparing across different URLs.",
      "",
      "Logical names are stable \u2014 use them in generated test code. Refs (from browser_snapshot) are",
      "ephemeral \u2014 never use them in generated code."
    ].join("\n"),
    inputSchema: import_mcpBundle.z.object({}),
    type: "readOnly"
  },
  handle: async (tab, _params, response) => {
    try {
      const current = await (0, import_blueprint.buildPageBlueprint)(tab.page);
      const url = current.url;
      const previous = tab.blueprintCache.get(url);
      if (!previous) {
        tab.blueprintCache.put(url, current);
        const possibleAssertions2 = (0, import_possibleAssertions.buildFullCaptureAssertions)(current);
        response.addTextResult(JSON.stringify({
          isFullCapture: true,
          pageHash: current.pageHash,
          blueprint: current,
          possibleAssertions: possibleAssertions2
        }, null, 2));
        return;
      }
      const delta = (0, import_blueprintDiff.diffBlueprints)(previous, current);
      const possibleAssertions = (0, import_possibleAssertions.buildPossibleAssertions)(delta);
      tab.blueprintCache.put(url, current);
      response.addTextResult(JSON.stringify({
        isFullCapture: false,
        pageHash: current.pageHash,
        previousPageHash: previous.pageHash,
        delta,
        possibleAssertions
      }, null, 2));
    } catch (err) {
      if (err instanceof import_blueprint.BlueprintInvariantError) {
        response.addError(
          `Blueprint invariant violated: ${err.message}. This is a builder bug; please file an issue with the URL of the page that triggered it.`
        );
        return;
      }
      throw err;
    }
  }
});
const PageBlueprintLooseSchema = import_mcpBundle.z.object({
  schemaVersion: import_mcpBundle.z.literal(1).describe("Always 1 for the current PageBlueprint format. Copy from the captured blueprint."),
  url: import_mcpBundle.z.string().describe("Page URL the blueprint was captured from. Copy from the captured blueprint."),
  capturedAt: import_mcpBundle.z.string().describe("ISO-8601 UTC timestamp of capture. Copy from the captured blueprint."),
  pageHash: import_mcpBundle.z.string().describe("Cheap hash of the page structure for staleness detection. Copy from the captured blueprint."),
  sections: import_mcpBundle.z.array(import_mcpBundle.z.any()).describe("The blueprint's sections array \u2014 full structural data. Copy from the captured blueprint without modification.")
});
const blueprintDiff = (0, import_tool.defineTool)({
  capability: "core",
  schema: {
    name: "browser_blueprint_diff",
    title: "Diff two PageBlueprints",
    description: [
      "Compute a structured delta between two PageBlueprints.",
      "",
      "In most cases you do NOT need this tool \u2014 browser_blueprint already returns",
      "the delta against the previous capture at the same URL automatically.",
      "",
      "Use this tool only when:",
      "  \u2022 Comparing blueprints across DIFFERENT URLs (e.g. before/after a navigation)",
      "    \u2014 diffing across URLs is supported and produces a delta with urlChange populated.",
      "  \u2022 Reconstructing a delta from blueprints captured outside the current cache window.",
      "",
      "Both blueprints must be from the same MCP session \u2014 the tool cannot verify this.",
      "Judgment about which facts become assertions lives in the NL \u2192 Trace prompt,",
      "not in this tool."
    ].join("\n"),
    inputSchema: import_mcpBundle.z.object({
      before: PageBlueprintLooseSchema.describe("PageBlueprint captured BEFORE the action (e.g. before a click that opens a dialog). Pass the full blueprint object returned by an earlier browser_blueprint call."),
      after: PageBlueprintLooseSchema.describe("PageBlueprint captured AFTER the action. Same shape as `before`. The tool computes the structured delta \u2014 what was added, removed, or changed.")
    }),
    type: "readOnly"
  },
  handle: async (_context, params, response) => {
    const delta = (0, import_blueprintDiff.diffBlueprints)(
      params.before,
      params.after
    );
    response.addTextResult(JSON.stringify(delta, null, 2));
  }
});
var pageBlueprint_default = [blueprint, blueprintDiff];
