'use strict';

var fs2 = require('fs');
var path3 = require('path');
require('crypto');
var module$1 = require('module');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var fs2__default = /*#__PURE__*/_interopDefault(fs2);
var path3__default = /*#__PURE__*/_interopDefault(path3);

// src/features/gen-html/infrastructure/local-server/registry.ts
function normalizeOutputRelativePath(outputDirectory, filePath) {
  return path3__default.default.relative(outputDirectory, filePath).split(path3__default.default.sep).join("/");
}
var STORY_FILE_PATTERN = /\.stories\.[cm]?[jt]sx?$/i;
function isGenHtmlStoryFilePath(filePath) {
  return STORY_FILE_PATTERN.test(filePath);
}

// src/features/gen-html/infrastructure/runtime.ts
function listOutputFiles(outputDirectory) {
  if (!fs2__default.default.existsSync(outputDirectory) || !fs2__default.default.statSync(outputDirectory).isDirectory()) {
    return [];
  }
  const files = [];
  const visitDirectory = (directoryPath) => {
    const entries = fs2__default.default.readdirSync(directoryPath, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
    for (const entry of entries) {
      const entryPath = path3__default.default.join(directoryPath, entry.name);
      if (entry.isDirectory()) {
        visitDirectory(entryPath);
        continue;
      }
      if (entry.isFile()) {
        files.push(normalizeOutputRelativePath(outputDirectory, entryPath));
      }
    }
  };
  visitDirectory(outputDirectory);
  return files.sort((left, right) => left.localeCompare(right));
}
function isGenHtmlPreviewDirectoryCandidate(outputDirectory) {
  return listOutputFiles(outputDirectory).some((filePath) => isGenHtmlStoryFilePath(filePath));
}
var LOCAL_SERVER_SASS_VERSION = "^1.86.3";
var LOCAL_SERVER_REACT_QUERY_VERSION = "^5.81.2";
var LOCAL_SERVER_TYPES_NODE_VERSION = "^25.0.10";
var LOCAL_SERVER_TYPES_REACT_VERSION = "19.1.0";
var LOCAL_SERVER_TYPES_REACT_DOM_VERSION = "19.1.1";
var LOCAL_SERVER_TYPESCRIPT_VERSION = "5.8.2";
var LOCAL_SERVER_VITE_VERSION = "^6.3.1";
var STORYBOOK_VERSION = "8.6.14";
var IMPORT_SPECIFIER_PATTERN = /\b(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s*)?['"]([^'"`]+)['"]|\bimport\s*\(\s*['"]([^'"`]+)['"]\s*\)/g;
var SOURCE_FILE_EXTENSION_PATTERN = /\.[cm]?[jt]sx?$/i;
var NODE_BUILTIN_MODULE_NAMES = new Set(
  module$1.builtinModules.flatMap((moduleName) => [moduleName, moduleName.replace(/^node:/, ""), `node:${moduleName.replace(/^node:/, "")}`])
);
var LOCAL_SERVER_DEFAULT_PACKAGE_JSON = {
  dependencies: {
    "@types/node": LOCAL_SERVER_TYPES_NODE_VERSION,
    "@types/react": LOCAL_SERVER_TYPES_REACT_VERSION,
    "@types/react-dom": LOCAL_SERVER_TYPES_REACT_DOM_VERSION,
    "@tanstack/react-query": LOCAL_SERVER_REACT_QUERY_VERSION,
    "@storybook/addon-essentials": STORYBOOK_VERSION,
    "@storybook/react": STORYBOOK_VERSION,
    "@storybook/react-vite": STORYBOOK_VERSION,
    react: "^19.1.0",
    "react-dom": "^19.1.0",
    sass: LOCAL_SERVER_SASS_VERSION,
    storybook: STORYBOOK_VERSION,
    typescript: LOCAL_SERVER_TYPESCRIPT_VERSION,
    vite: LOCAL_SERVER_VITE_VERSION
  }};
function getLocalServerPaths(paths) {
  const directoryPath = path3__default.default.join(paths.baseDir, "local-server");
  const generatedDirectoryPath = path3__default.default.join(directoryPath, "generated");
  const multipleDirectoryPath = path3__default.default.join(directoryPath, "multiple");
  const storybookConfigDirectoryPath = path3__default.default.join(directoryPath, ".storybook");
  return {
    directoryPath,
    generatedDirectoryPath,
    generatedRegistryPath: path3__default.default.join(directoryPath, "generated-registry.json"),
    multipleDirectoryPath,
    logPath: path3__default.default.join(directoryPath, "server.log"),
    packageJsonPath: path3__default.default.join(directoryPath, "package.json"),
    packageCustomJsonPath: path3__default.default.join(directoryPath, "package-custom.json"),
    previewTargetPath: path3__default.default.join(directoryPath, "preview-target.json"),
    refreshLockPath: path3__default.default.join(directoryPath, "refresh.lock"),
    scssModuleDeclarationPath: path3__default.default.join(directoryPath, "scss.d.ts"),
    serverLockPath: path3__default.default.join(directoryPath, "server.lock"),
    statePath: path3__default.default.join(directoryPath, "server-state.json"),
    storybookConfigDirectoryPath,
    storybookMainConfigPath: path3__default.default.join(storybookConfigDirectoryPath, "main.ts"),
    storybookManagerConfigPath: path3__default.default.join(storybookConfigDirectoryPath, "manager.tsx"),
    storybookPreviewConfigPath: path3__default.default.join(storybookConfigDirectoryPath, "preview.ts"),
    tsconfigPath: path3__default.default.join(directoryPath, "tsconfig.json")
  };
}
function readJsonFile(filePath) {
  if (!fs2__default.default.existsSync(filePath)) {
    return void 0;
  }
  const raw = fs2__default.default.readFileSync(filePath, "utf8").trim();
  if (!raw) {
    return void 0;
  }
  return JSON.parse(raw);
}
function writeJsonFile(filePath, value) {
  fs2__default.default.mkdirSync(path3__default.default.dirname(filePath), { recursive: true });
  fs2__default.default.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}
`, "utf8");
}

// src/features/gen-html/infrastructure/local-server/dependencies/generated-output.ts
function isBareImportSpecifier(specifier) {
  return Boolean(specifier) && !specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.includes("://") && !specifier.startsWith("\0");
}
function getPackageNameFromImportSpecifier(specifier) {
  if (!isBareImportSpecifier(specifier) || NODE_BUILTIN_MODULE_NAMES.has(specifier)) {
    return "";
  }
  if (specifier.startsWith("@")) {
    const [scope, name] = specifier.split("/");
    return scope && name ? `${scope}/${name}` : "";
  }
  return specifier.split("/")[0] || "";
}
function listSourceFiles(directoryPath) {
  if (!fs2__default.default.existsSync(directoryPath) || !fs2__default.default.statSync(directoryPath).isDirectory()) {
    return [];
  }
  const collected = [];
  const queue = [directoryPath];
  while (queue.length > 0) {
    const currentDirectoryPath = queue.pop();
    if (!currentDirectoryPath) {
      continue;
    }
    for (const entry of fs2__default.default.readdirSync(currentDirectoryPath, { withFileTypes: true })) {
      const entryPath = path3__default.default.join(currentDirectoryPath, entry.name);
      if (entry.isDirectory()) {
        queue.push(entryPath);
        continue;
      }
      if (entry.isFile() && SOURCE_FILE_EXTENSION_PATTERN.test(entry.name)) {
        collected.push(entryPath);
      }
    }
  }
  return collected.sort((left, right) => left.localeCompare(right));
}
function isBundledLocalServerDependency(packageName) {
  return Object.prototype.hasOwnProperty.call(LOCAL_SERVER_DEFAULT_PACKAGE_JSON.dependencies, packageName);
}
function collectOutputDependencyNames(outputDirectory) {
  const packageNames = /* @__PURE__ */ new Set();
  for (const filePath of listSourceFiles(outputDirectory)) {
    const source = fs2__default.default.readFileSync(filePath, "utf8");
    let match = IMPORT_SPECIFIER_PATTERN.exec(source);
    while (match) {
      const packageName = getPackageNameFromImportSpecifier(match[1] || match[2] || "");
      if (packageName && !isBundledLocalServerDependency(packageName)) {
        packageNames.add(packageName);
      }
      match = IMPORT_SPECIFIER_PATTERN.exec(source);
    }
    IMPORT_SPECIFIER_PATTERN.lastIndex = 0;
  }
  return [...packageNames].sort((left, right) => left.localeCompare(right));
}

// src/features/gen-html/infrastructure/local-server/registry.ts
function normalizeOutputDirectory(outputDirectory) {
  return path3__default.default.resolve(outputDirectory);
}
function createDependencyFingerprint(dependencyNames) {
  return dependencyNames.join("|");
}
function listGeneratedOutputDirectories(paths) {
  const { generatedDirectoryPath } = getLocalServerPaths(paths);
  if (!fs2__default.default.existsSync(generatedDirectoryPath) || !fs2__default.default.statSync(generatedDirectoryPath).isDirectory()) {
    return [];
  }
  return fs2__default.default.readdirSync(generatedDirectoryPath, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path3__default.default.join(generatedDirectoryPath, entry.name)).sort((left, right) => left.localeCompare(right));
}
function createRegistryEntry(outputDirectory, componentName = "") {
  const dependencyNames = collectOutputDependencyNames(outputDirectory);
  const normalizedOutputDirectory = normalizeOutputDirectory(outputDirectory);
  return {
    componentName: componentName || path3__default.default.basename(normalizedOutputDirectory),
    dependencyFingerprint: createDependencyFingerprint(dependencyNames),
    dependencyNames,
    outputDirectory: normalizedOutputDirectory,
    previewEligible: isGenHtmlPreviewDirectoryCandidate(normalizedOutputDirectory),
    updatedAt: (/* @__PURE__ */ new Date()).toISOString()
  };
}
function readGeneratedOutputRegistry(paths) {
  try {
    const registry = readJsonFile(getLocalServerPaths(paths).generatedRegistryPath);
    const entries = Array.isArray(registry?.entries) ? registry.entries.filter((entry) => typeof entry.outputDirectory === "string" && entry.outputDirectory.trim()) : [];
    return {
      entries,
      version: 1
    };
  } catch {
    return {
      entries: [],
      version: 1
    };
  }
}
function writeGeneratedOutputRegistry(paths, registry) {
  writeJsonFile(getLocalServerPaths(paths).generatedRegistryPath, {
    entries: registry.entries.sort((left, right) => left.outputDirectory.localeCompare(right.outputDirectory)),
    version: 1
  });
}
function upsertGeneratedOutputRegistryEntry(options) {
  const registry = readGeneratedOutputRegistry(options.paths);
  const nextEntry = createRegistryEntry(options.outputDirectory, options.componentName);
  const entries = registry.entries.filter(
    (entry) => normalizeOutputDirectory(entry.outputDirectory) !== nextEntry.outputDirectory
  );
  entries.push(nextEntry);
  writeGeneratedOutputRegistry(options.paths, {
    entries});
  options.trace(
    "local-server:registry:upsert",
    `component=${nextEntry.componentName} dependencies=${nextEntry.dependencyNames.length} preview=${nextEntry.previewEligible}`
  );
  return nextEntry;
}
function syncGeneratedOutputRegistryFromDisk(paths, trace) {
  const existingRegistry = readGeneratedOutputRegistry(paths);
  const existingNames = new Map(
    existingRegistry.entries.map((entry) => [normalizeOutputDirectory(entry.outputDirectory), entry.componentName])
  );
  const entries = listGeneratedOutputDirectories(paths).map(
    (outputDirectory) => createRegistryEntry(outputDirectory, existingNames.get(normalizeOutputDirectory(outputDirectory)) || "")
  );
  const registry = {
    entries,
    version: 1
  };
  writeGeneratedOutputRegistry(paths, registry);
  trace("local-server:registry:sync", `entries=${entries.length}`);
  return registry;
}
function listPreviewEligibleOutputDirectories(registry) {
  return registry.entries.filter((entry) => entry.previewEligible).map((entry) => entry.outputDirectory).sort((left, right) => left.localeCompare(right));
}

exports.listPreviewEligibleOutputDirectories = listPreviewEligibleOutputDirectories;
exports.readGeneratedOutputRegistry = readGeneratedOutputRegistry;
exports.syncGeneratedOutputRegistryFromDisk = syncGeneratedOutputRegistryFromDisk;
exports.upsertGeneratedOutputRegistryEntry = upsertGeneratedOutputRegistryEntry;
exports.writeGeneratedOutputRegistry = writeGeneratedOutputRegistry;
