// @bun
import {
  exports_src
} from "./index-rs5zwr4j.js";
import {
  __require
} from "./index-e89anq5x.js";

// src/runtime-plugin.ts
var CORE_RUNTIME_SPECIFIER = "@opentui/core";
var CORE_TESTING_RUNTIME_SPECIFIER = "@opentui/core/testing";
var RUNTIME_MODULE_PREFIX = "opentui:runtime-module:";
var MAX_RUNTIME_RESOLVE_PARENTS = 64;
var DEFAULT_CORE_RUNTIME_MODULE_SPECIFIERS = [CORE_RUNTIME_SPECIFIER, CORE_TESTING_RUNTIME_SPECIFIER];
var DEFAULT_CORE_RUNTIME_MODULE_SPECIFIER_SET = new Set(DEFAULT_CORE_RUNTIME_MODULE_SPECIFIERS);
var isCoreRuntimeModuleSpecifier = (specifier) => {
  return DEFAULT_CORE_RUNTIME_MODULE_SPECIFIER_SET.has(specifier);
};
var loadCoreTestingRuntimeModule = async () => {
  return await import("./testing.js");
};
var escapeRegExp = (value) => {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
var exactSpecifierFilter = (specifier) => {
  return new RegExp(`^${escapeRegExp(specifier)}$`);
};
var runtimeModuleIdForSpecifier = (specifier) => {
  return `${RUNTIME_MODULE_PREFIX}${encodeURIComponent(specifier)}`;
};
var resolveRuntimeModuleExports = async (moduleEntry) => {
  if (typeof moduleEntry === "function") {
    return await moduleEntry();
  }
  return moduleEntry;
};
var sourcePath = (path) => {
  const searchIndex = path.indexOf("?");
  const hashIndex = path.indexOf("#");
  const end = [searchIndex, hashIndex].filter((index) => index >= 0).sort((a, b) => a - b)[0];
  return end === undefined ? path : path.slice(0, end);
};
var runtimeLoaderForPath = (path) => {
  const cleanPath = sourcePath(path);
  if (cleanPath.endsWith(".tsx")) {
    return "tsx";
  }
  if (cleanPath.endsWith(".jsx")) {
    return "jsx";
  }
  if (cleanPath.endsWith(".ts") || cleanPath.endsWith(".mts") || cleanPath.endsWith(".cts")) {
    return "ts";
  }
  if (cleanPath.endsWith(".js") || cleanPath.endsWith(".mjs") || cleanPath.endsWith(".cjs")) {
    return "js";
  }
  return null;
};
var runtimeSourceFilter = /^(?!.*(?:\/|\\)node_modules(?:\/|\\)).*\.(?:[cm]?js|[cm]?ts|jsx|tsx)(?:[?#].*)?$/;
var resolveImportSpecifierPatterns = [
  /(from\s+["'])([^"']+)(["'])/g,
  /(import\s+["'])([^"']+)(["'])/g,
  /(import\s*\(\s*["'])([^"']+)(["']\s*\))/g,
  /(require\s*\(\s*["'])([^"']+)(["']\s*\))/g
];
var isBareSpecifier = (specifier) => {
  if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\\")) {
    return false;
  }
  if (specifier.startsWith("node:") || specifier.startsWith("bun:") || specifier.startsWith("http:") || specifier.startsWith("https:") || specifier.startsWith("file:") || specifier.startsWith("data:")) {
    return false;
  }
  if (specifier.startsWith(RUNTIME_MODULE_PREFIX)) {
    return false;
  }
  return true;
};
var registerResolveParent = (resolveParentsByRecency, resolveParent) => {
  const existingIndex = resolveParentsByRecency.indexOf(resolveParent);
  if (existingIndex >= 0) {
    resolveParentsByRecency.splice(existingIndex, 1);
  }
  resolveParentsByRecency.push(resolveParent);
  if (resolveParentsByRecency.length > MAX_RUNTIME_RESOLVE_PARENTS) {
    resolveParentsByRecency.shift();
  }
};
var rewriteImportSpecifiers = (code, resolveReplacement) => {
  let transformedCode = code;
  for (const pattern of resolveImportSpecifierPatterns) {
    transformedCode = transformedCode.replace(pattern, (fullMatch, prefix, specifier, suffix) => {
      const replacement = resolveReplacement(specifier);
      if (!replacement || replacement === specifier) {
        return fullMatch;
      }
      return `${prefix}${replacement}${suffix}`;
    });
  }
  return transformedCode;
};
var resolveFromParent = (specifier, parent) => {
  try {
    const resolvedSpecifier = import.meta.resolve(specifier, parent);
    if (resolvedSpecifier === specifier || resolvedSpecifier.startsWith("node:") || resolvedSpecifier.startsWith("bun:")) {
      return null;
    }
    return resolvedSpecifier;
  } catch {
    return null;
  }
};
var rewriteImportsFromResolveParents = (code, resolveParentsByRecency) => {
  if (resolveParentsByRecency.length === 0) {
    return code;
  }
  const resolveFromParents = (specifier) => {
    if (!isBareSpecifier(specifier)) {
      return null;
    }
    for (let index = resolveParentsByRecency.length - 1;index >= 0; index -= 1) {
      const resolveParent = resolveParentsByRecency[index];
      const resolvedSpecifier = resolveFromParent(specifier, resolveParent);
      if (resolvedSpecifier) {
        return resolvedSpecifier;
      }
    }
    return null;
  };
  return rewriteImportSpecifiers(code, resolveFromParents);
};
var rewriteRuntimeSpecifiers = (code, runtimeModuleIdsBySpecifier) => {
  return rewriteImportSpecifiers(code, (specifier) => {
    const runtimeModuleId = runtimeModuleIdsBySpecifier.get(specifier);
    return runtimeModuleId ?? null;
  });
};
function createRuntimePlugin(input = {}) {
  const runtimeModules = new Map;
  runtimeModules.set(CORE_RUNTIME_SPECIFIER, input.core ?? exports_src);
  runtimeModules.set(CORE_TESTING_RUNTIME_SPECIFIER, loadCoreTestingRuntimeModule);
  for (const [specifier, moduleEntry] of Object.entries(input.additional ?? {})) {
    runtimeModules.set(specifier, moduleEntry);
  }
  const runtimeModuleIdsBySpecifier = new Map;
  for (const specifier of runtimeModules.keys()) {
    runtimeModuleIdsBySpecifier.set(specifier, runtimeModuleIdForSpecifier(specifier));
  }
  return {
    name: "bun-plugin-opentui-runtime-modules",
    setup: (build) => {
      const resolveParentsByRecency = [];
      for (const [specifier, moduleEntry] of runtimeModules.entries()) {
        const moduleId = runtimeModuleIdsBySpecifier.get(specifier);
        if (!moduleId) {
          continue;
        }
        build.module(moduleId, async () => ({
          exports: await resolveRuntimeModuleExports(moduleEntry),
          loader: "object"
        }));
        build.onResolve({ filter: exactSpecifierFilter(specifier) }, () => ({ path: moduleId }));
      }
      build.onLoad({ filter: runtimeSourceFilter }, async (args) => {
        const path = sourcePath(args.path);
        const loader = runtimeLoaderForPath(args.path);
        if (!loader) {
          throw new Error(`Unable to determine runtime loader for path: ${args.path}`);
        }
        const file = Bun.file(path);
        const contents = await file.text();
        const runtimeRewrittenContents = rewriteRuntimeSpecifiers(contents, runtimeModuleIdsBySpecifier);
        if (runtimeRewrittenContents !== contents) {
          registerResolveParent(resolveParentsByRecency, path);
        }
        const transformedContents = rewriteImportsFromResolveParents(runtimeRewrittenContents, resolveParentsByRecency);
        return {
          contents: transformedContents,
          loader
        };
      });
    }
  };
}

export { isCoreRuntimeModuleSpecifier, runtimeModuleIdForSpecifier, createRuntimePlugin };

//# debugId=320B34A5E2C7118F64756E2164756E21
//# sourceMappingURL=index-tae5jwnc.js.map
