"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 iac_exports = {};
__export(iac_exports, {
  cdkResolver: () => cdkResolver,
  samResolver: () => samResolver,
  serverlessResolver: () => serverlessResolver,
  sstResolver: () => sstResolver
});
module.exports = __toCommonJS(iac_exports);
const sstResolver = {
  name: "sst",
  detect(context) {
    if (context.fileExists("sst.config.ts") || context.fileExists("sst.config.js")) return true;
    const pkg = context.readFile("package.json");
    if (pkg) {
      try {
        const parsed = JSON.parse(pkg);
        const deps = { ...parsed.dependencies, ...parsed.devDependencies };
        if ("sst" in deps) return true;
      } catch {
      }
    }
    return false;
  },
  resolve(ref, context) {
    if (ref.referenceName.includes(".") && !ref.referenceName.startsWith(".")) {
      const id = resolveHandlerString(ref.referenceName, context);
      if (id) return { original: ref, targetNodeId: id, confidence: 0.9, resolvedBy: "framework" };
    }
    if (/^[A-Z][a-zA-Z]+$/.test(ref.referenceName)) {
      const id = resolveConstruct(ref.referenceName, ["stacks", "infra", "src", "lib"], context);
      if (id) return { original: ref, targetNodeId: id, confidence: 0.75, resolvedBy: "framework" };
    }
    return null;
  },
  extractNodes(filePath, content) {
    const nodes = [];
    const now = Date.now();
    const routePattern = /\.route\s*\(\s*["'](\w+)\s+([^"']+)["']/g;
    let match;
    while ((match = routePattern.exec(content)) !== null) {
      const line = content.slice(0, match.index).split("\n").length;
      const method = match[1].toUpperCase();
      const routePath = match[2];
      const name = `${method} ${routePath}`;
      nodes.push({
        id: `route:${filePath}:${method}:${routePath}:${line}`,
        kind: "route",
        name,
        qualifiedName: `${filePath}::${name}`,
        filePath,
        startLine: line,
        endLine: line,
        startColumn: 0,
        endColumn: match[0].length,
        language: "typescript",
        updatedAt: now
      });
    }
    const routeObjPattern = /["'](GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ANY)\s+([^"']+)["']\s*:/g;
    while ((match = routeObjPattern.exec(content)) !== null) {
      if (!content.includes("sst") && !content.includes("Api") && !content.includes("Function")) continue;
      const line = content.slice(0, match.index).split("\n").length;
      const method = match[1];
      const routePath = match[2];
      const name = `${method} ${routePath}`;
      const id = `route:${filePath}:${method}:${routePath}:${line}`;
      if (!nodes.some((n) => n.id === id)) {
        nodes.push({
          id,
          kind: "route",
          name,
          qualifiedName: `${filePath}::${name}`,
          filePath,
          startLine: line,
          endLine: line,
          startColumn: 0,
          endColumn: match[0].length,
          language: "typescript",
          updatedAt: now
        });
      }
    }
    return nodes;
  }
};
const cdkResolver = {
  name: "cdk",
  detect(context) {
    if (context.fileExists("cdk.json")) return true;
    const pkg = context.readFile("package.json");
    if (pkg) {
      try {
        const parsed = JSON.parse(pkg);
        const deps = { ...parsed.dependencies, ...parsed.devDependencies };
        if ("aws-cdk-lib" in deps || "aws-cdk" in deps || "@aws-cdk/core" in deps) return true;
      } catch {
      }
    }
    const requirements = context.readFile("requirements.txt");
    if (requirements && requirements.includes("aws-cdk")) return true;
    return false;
  },
  resolve(ref, context) {
    if (ref.referenceName.includes(".") && !ref.referenceName.startsWith(".")) {
      const id = resolveHandlerString(ref.referenceName, context);
      if (id) return { original: ref, targetNodeId: id, confidence: 0.9, resolvedBy: "framework" };
    }
    if (/^[A-Z][a-zA-Z]+Stack$/.test(ref.referenceName)) {
      const id = resolveConstruct(ref.referenceName, ["lib", "stacks", "infra", "src"], context);
      if (id) return { original: ref, targetNodeId: id, confidence: 0.85, resolvedBy: "framework" };
    }
    if (/^[A-Z][a-zA-Z]+Construct$/.test(ref.referenceName) || /^[A-Z][a-zA-Z]+$/.test(ref.referenceName)) {
      const id = resolveConstruct(ref.referenceName, ["lib", "constructs", "src", "infra"], context);
      if (id) return { original: ref, targetNodeId: id, confidence: 0.7, resolvedBy: "framework" };
    }
    return null;
  },
  extractNodes(filePath, content) {
    const nodes = [];
    const now = Date.now();
    const addMethodPattern = /\.addMethod\s*\(\s*['"](\w+)['"]/g;
    const addResourcePattern = /\.addResource\s*\(\s*['"]([^'"]+)['"]/g;
    let match;
    const resources = [];
    while ((match = addResourcePattern.exec(content)) !== null) {
      const line = content.slice(0, match.index).split("\n").length;
      resources.push({ path: match[1], line });
    }
    while ((match = addMethodPattern.exec(content)) !== null) {
      const line = content.slice(0, match.index).split("\n").length;
      const method = match[1].toUpperCase();
      const nearestResource = resources.filter((r) => r.line <= line).pop();
      const routePath = nearestResource ? `/${nearestResource.path}` : "/";
      const name = `${method} ${routePath}`;
      nodes.push({
        id: `route:${filePath}:${method}:${routePath}:${line}`,
        kind: "route",
        name,
        qualifiedName: `${filePath}::${name}`,
        filePath,
        startLine: line,
        endLine: line,
        startColumn: 0,
        endColumn: match[0].length,
        language: filePath.endsWith(".py") ? "python" : "typescript",
        updatedAt: now
      });
    }
    const httpApiPattern = /addRoutes\s*\(\s*\{[^}]*path\s*:\s*['"]([^'"]+)['"][^}]*methods\s*:\s*\[([^\]]+)\]/gs;
    while ((match = httpApiPattern.exec(content)) !== null) {
      const line = content.slice(0, match.index).split("\n").length;
      const routePath = match[1];
      const methods = match[2].match(/HttpMethod\.(\w+)/g) ?? [];
      for (const m of methods) {
        const method = m.replace("HttpMethod.", "");
        const name = `${method} ${routePath}`;
        nodes.push({
          id: `route:${filePath}:${method}:${routePath}:${line}`,
          kind: "route",
          name,
          qualifiedName: `${filePath}::${name}`,
          filePath,
          startLine: line,
          endLine: line,
          startColumn: 0,
          endColumn: match[0].length,
          language: filePath.endsWith(".py") ? "python" : "typescript",
          updatedAt: now
        });
      }
    }
    return nodes;
  }
};
const serverlessResolver = {
  name: "serverless",
  detect(context) {
    return context.fileExists("serverless.yml") || context.fileExists("serverless.yaml") || context.fileExists("serverless.ts") || context.fileExists("serverless.js");
  },
  resolve(ref, context) {
    if (ref.referenceName.includes(".") && !ref.referenceName.startsWith(".")) {
      const id = resolveHandlerString(ref.referenceName, context);
      if (id) return { original: ref, targetNodeId: id, confidence: 0.9, resolvedBy: "framework" };
    }
    return null;
  },
  extractNodes(filePath, content) {
    const nodes = [];
    const now = Date.now();
    const basename = filePath.split("/").pop() ?? "";
    if (!basename.startsWith("serverless.")) return nodes;
    if (filePath.endsWith(".yml") || filePath.endsWith(".yaml")) {
      const functionBlocks = content.split(/^\s{2}\w+:/gm);
      const httpPattern = /- http(?:Api)?:\s*\n\s+(?:method:\s*(\w+)\s*\n\s+path:\s*(\S+)|path:\s*(\S+)\s*\n\s+method:\s*(\w+))/g;
      const simpleHttpPattern = /- http(?:Api)?:\s*(\w+)\s+(\S+)/g;
      let match;
      while ((match = httpPattern.exec(content)) !== null) {
        const line = content.slice(0, match.index).split("\n").length;
        const method = (match[1] || match[4]).toUpperCase();
        const routePath = match[2] || match[3];
        const name = `${method} ${routePath}`;
        nodes.push({
          id: `route:${filePath}:${method}:${routePath}:${line}`,
          kind: "route",
          name,
          qualifiedName: `${filePath}::${name}`,
          filePath,
          startLine: line,
          endLine: line,
          startColumn: 0,
          endColumn: match[0].length,
          language: "yaml",
          updatedAt: now
        });
      }
      while ((match = simpleHttpPattern.exec(content)) !== null) {
        const line = content.slice(0, match.index).split("\n").length;
        const method = match[1].toUpperCase();
        const routePath = match[2];
        const name = `${method} ${routePath}`;
        const id = `route:${filePath}:${method}:${routePath}:${line}`;
        if (!nodes.some((n) => n.id === id)) {
          nodes.push({
            id,
            kind: "route",
            name,
            qualifiedName: `${filePath}::${name}`,
            filePath,
            startLine: line,
            endLine: line,
            startColumn: 0,
            endColumn: match[0].length,
            language: "yaml",
            updatedAt: now
          });
        }
      }
    } else {
      const routePattern = /["'](GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ANY)\s+([^"']+)["']/g;
      let match;
      while ((match = routePattern.exec(content)) !== null) {
        const line = content.slice(0, match.index).split("\n").length;
        const method = match[1];
        const routePath = match[2];
        const name = `${method} ${routePath}`;
        nodes.push({
          id: `route:${filePath}:${method}:${routePath}:${line}`,
          kind: "route",
          name,
          qualifiedName: `${filePath}::${name}`,
          filePath,
          startLine: line,
          endLine: line,
          startColumn: 0,
          endColumn: match[0].length,
          language: "typescript",
          updatedAt: now
        });
      }
    }
    return nodes;
  }
};
const samResolver = {
  name: "sam",
  detect(context) {
    for (const name of ["template.yaml", "template.yml", "sam.yaml", "sam.yml"]) {
      const content = context.readFile(name);
      if (content && content.includes("AWS::Serverless")) return true;
    }
    if (context.fileExists("samconfig.toml") || context.fileExists("samconfig.yaml")) return true;
    return false;
  },
  resolve(ref, context) {
    if (ref.referenceName.includes(".") && !ref.referenceName.startsWith(".")) {
      const id = resolveHandlerString(ref.referenceName, context);
      if (id) return { original: ref, targetNodeId: id, confidence: 0.9, resolvedBy: "framework" };
    }
    return null;
  },
  extractNodes(filePath, content) {
    const nodes = [];
    const now = Date.now();
    const basename = filePath.split("/").pop() ?? "";
    if (!basename.match(/^(template|sam)\.(ya?ml)$/)) return nodes;
    if (!content.includes("AWS::Serverless")) return nodes;
    const apiEventPattern = /Type:\s*(?:Api|HttpApi)\s*\n\s+Properties:\s*\n(?:\s+.*\n)*?\s+Path:\s*(\S+)\s*\n(?:\s+.*\n)*?\s+Method:\s*(\w+)/g;
    let match;
    while ((match = apiEventPattern.exec(content)) !== null) {
      const line = content.slice(0, match.index).split("\n").length;
      const routePath = match[1];
      const method = match[2].toUpperCase();
      const name = `${method} ${routePath}`;
      nodes.push({
        id: `route:${filePath}:${method}:${routePath}:${line}`,
        kind: "route",
        name,
        qualifiedName: `${filePath}::${name}`,
        filePath,
        startLine: line,
        endLine: line,
        startColumn: 0,
        endColumn: match[0].length,
        language: "yaml",
        updatedAt: now
      });
    }
    const simplePattern = /Method:\s*(\w+)\s*\n\s+Path:\s*(\S+)|Path:\s*(\S+)\s*\n\s+Method:\s*(\w+)/g;
    while ((match = simplePattern.exec(content)) !== null) {
      const line = content.slice(0, match.index).split("\n").length;
      const method = (match[1] || match[4]).toUpperCase();
      const routePath = match[2] || match[3];
      const name = `${method} ${routePath}`;
      const id = `route:${filePath}:${method}:${routePath}:${line}`;
      if (!nodes.some((n) => n.id === id)) {
        nodes.push({
          id,
          kind: "route",
          name,
          qualifiedName: `${filePath}::${name}`,
          filePath,
          startLine: line,
          endLine: line,
          startColumn: 0,
          endColumn: match[0].length,
          language: "yaml",
          updatedAt: now
        });
      }
    }
    return nodes;
  }
};
function resolveHandlerString(handlerStr, context) {
  const lastDot = handlerStr.lastIndexOf(".");
  if (lastDot <= 0) return null;
  const filePart = handlerStr.slice(0, lastDot);
  const funcName = handlerStr.slice(lastDot + 1);
  const extensions = [".ts", ".js", ".mjs", ".py", ".go"];
  for (const ext of extensions) {
    const candidates = [
      `${filePart}${ext}`,
      `${filePart}/index${ext}`
    ];
    for (const candidate of candidates) {
      if (context.fileExists(candidate)) {
        const node = context.getNodesInFile(candidate).find(
          (n) => n.name === funcName && (n.kind === "function" || n.kind === "method" || n.kind === "variable")
        );
        if (node) return node.id;
      }
    }
  }
  const dirs = ["src", "lib", "handlers", "functions", "lambdas", "api"];
  for (const file of context.getAllFiles()) {
    if (!dirs.some((d) => file.includes(`/${d}/`) || file.startsWith(`${d}/`))) continue;
    if (!file.includes(filePart.split("/").pop())) continue;
    const node = context.getNodesInFile(file).find(
      (n) => n.name === funcName && (n.kind === "function" || n.kind === "method" || n.kind === "variable")
    );
    if (node) return node.id;
  }
  return null;
}
function resolveConstruct(name, dirs, context) {
  for (const file of context.getAllFiles()) {
    if (!(file.endsWith(".ts") || file.endsWith(".js") || file.endsWith(".py"))) continue;
    if (!dirs.some((d) => file.includes(`/${d}/`) || file.startsWith(`${d}/`))) continue;
    const node = context.getNodesInFile(file).find(
      (n) => n.name === name && (n.kind === "class" || n.kind === "function" || n.kind === "variable")
    );
    if (node) return node.id;
  }
  return null;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  cdkResolver,
  samResolver,
  serverlessResolver,
  sstResolver
});
//# sourceMappingURL=iac.js.map
