"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 openapi_exports = {};
__export(openapi_exports, {
  isOpenAPI: () => isOpenAPI,
  openapiParser: () => openapiParser
});
module.exports = __toCommonJS(openapi_exports);
function isOpenAPIContent(content, filePath) {
  const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
  if (ext === ".json") {
    try {
      const parsed = JSON.parse(content);
      return "openapi" in parsed || "swagger" in parsed;
    } catch {
      return false;
    }
  }
  return /^(openapi|swagger)\s*:/m.test(content);
}
function parseYAMLOperations(content) {
  const operations = [];
  const lines = content.split("\n");
  let inPaths = false;
  let currentPath = "";
  let currentMethod = "";
  let currentTags = [];
  let currentSummary = "";
  let currentDescription = "";
  let opStart = 0;
  let byteOffset = 0;
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const lineBytes = Buffer.byteLength(line, "utf8") + 1;
    if (/^paths\s*:/.test(line)) {
      inPaths = true;
      byteOffset += lineBytes;
      continue;
    }
    if (inPaths && /^\S/.test(line) && !/^paths/.test(line)) {
      if (currentPath && currentMethod) {
        operations.push({
          method: currentMethod.toUpperCase(),
          path: currentPath,
          summary: currentSummary,
          description: currentDescription,
          tags: currentTags.length > 0 ? currentTags : ["default"],
          byteStart: opStart,
          byteEnd: byteOffset
        });
      }
      inPaths = false;
      byteOffset += lineBytes;
      continue;
    }
    if (inPaths) {
      const pathMatch = line.match(/^\s{2}(['"]?)(\/[^'":\s]*)\1\s*:/);
      if (pathMatch) {
        if (currentPath && currentMethod) {
          operations.push({
            method: currentMethod.toUpperCase(),
            path: currentPath,
            summary: currentSummary,
            description: currentDescription,
            tags: currentTags.length > 0 ? currentTags : ["default"],
            byteStart: opStart,
            byteEnd: byteOffset
          });
          currentMethod = "";
          currentSummary = "";
          currentDescription = "";
          currentTags = [];
        }
        currentPath = pathMatch[2];
      }
      const methodMatch = line.match(/^\s{4}(get|post|put|delete|patch|head|options)\s*:/);
      if (methodMatch) {
        if (currentMethod) {
          operations.push({
            method: currentMethod.toUpperCase(),
            path: currentPath,
            summary: currentSummary,
            description: currentDescription,
            tags: currentTags.length > 0 ? currentTags : ["default"],
            byteStart: opStart,
            byteEnd: byteOffset
          });
        }
        currentMethod = methodMatch[1];
        currentSummary = "";
        currentDescription = "";
        currentTags = [];
        opStart = byteOffset;
      }
      const summaryMatch = line.match(/^\s{6}summary\s*:\s*['"]?(.+?)['"]?\s*$/);
      if (summaryMatch) currentSummary = summaryMatch[1];
      const descMatch = line.match(/^\s{6}description\s*:\s*['"]?(.+?)['"]?\s*$/);
      if (descMatch) currentDescription = descMatch[1];
      const tagMatch = line.match(/^\s{8}-\s*['"]?(.+?)['"]?\s*$/);
      if (tagMatch && i > 0 && /^\s{6}tags\s*:/.test(lines[i - 1] || "")) {
        currentTags.push(tagMatch[1]);
      }
      if (/^\s{6}tags\s*:/.test(line)) {
        for (let j = i + 1; j < lines.length && /^\s{8}-/.test(lines[j]); j++) {
          const t = lines[j].match(/^\s{8}-\s*['"]?(.+?)['"]?\s*$/);
          if (t) currentTags.push(t[1]);
        }
      }
    }
    byteOffset += lineBytes;
  }
  if (currentPath && currentMethod) {
    operations.push({
      method: currentMethod.toUpperCase(),
      path: currentPath,
      summary: currentSummary,
      description: currentDescription,
      tags: currentTags.length > 0 ? currentTags : ["default"],
      byteStart: opStart,
      byteEnd: byteOffset
    });
  }
  return operations;
}
function parseJSONOperations(content) {
  const operations = [];
  try {
    const spec = JSON.parse(content);
    const paths = spec.paths || {};
    const contentBytes = Buffer.byteLength(content, "utf8");
    const methods = ["get", "post", "put", "delete", "patch", "head", "options"];
    for (const [pathStr, pathItem] of Object.entries(paths)) {
      if (!pathItem || typeof pathItem !== "object") continue;
      for (const method of methods) {
        const op = pathItem[method];
        if (!op) continue;
        operations.push({
          method: method.toUpperCase(),
          path: pathStr,
          summary: op.summary || "",
          description: op.description || "",
          tags: Array.isArray(op.tags) ? op.tags : ["default"],
          byteStart: 0,
          byteEnd: contentBytes
        });
      }
    }
  } catch {
  }
  return operations;
}
function buildSections(operations, content) {
  const contentBytes = Buffer.byteLength(content, "utf8");
  if (operations.length === 0) {
    return [{
      title: "(API spec)",
      level: 0,
      byteStart: 0,
      byteEnd: contentBytes,
      content,
      children: []
    }];
  }
  const byTag = /* @__PURE__ */ new Map();
  for (const op of operations) {
    for (const tag of op.tags) {
      if (!byTag.has(tag)) byTag.set(tag, []);
      byTag.get(tag).push(op);
    }
  }
  const root = [];
  for (const [tag, ops] of byTag) {
    const children = ops.map((op) => ({
      title: `${op.method} ${op.path}`,
      level: 2,
      byteStart: op.byteStart,
      byteEnd: op.byteEnd,
      content: [op.summary, op.description].filter(Boolean).join("\n") || `${op.method} ${op.path}`,
      children: []
    }));
    root.push({
      title: tag,
      level: 1,
      byteStart: ops[0]?.byteStart ?? 0,
      byteEnd: ops[ops.length - 1]?.byteEnd ?? contentBytes,
      content: `Tag: ${tag}
${ops.map((o) => `${o.method} ${o.path}`).join("\n")}`,
      children
    });
  }
  return root;
}
const openapiParser = {
  name: "openapi",
  extensions: [],
  // Not registered by extension — detected by content
  parse(content, filePath) {
    const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
    const operations = ext === ".json" ? parseJSONOperations(content) : parseYAMLOperations(content);
    const sections = buildSections(operations, content);
    return { sections, format: "openapi" };
  }
};
function isOpenAPI(content, filePath) {
  return isOpenAPIContent(content, filePath);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  isOpenAPI,
  openapiParser
});
//# sourceMappingURL=openapi.js.map
