// src/actions/package/publint.ts
import { promises as fs3 } from "node:fs";
import path3 from "node:path";
import chalk3 from "chalk";
import { glob } from "glob";
import sortPackageJson from "sort-package-json";

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/reporting/xyReporter.ts
var strictMode = false;
function isStrictMode() {
  return strictMode || process.env.XY_STRICT === "1";
}

// src/actions/package/compile/XyConfig.ts
var PUBLISH_ONLY_CHECKS = [
  "files",
  "importToDefault",
  "main",
  "module",
  "publint",
  "rootSource",
  "rootTypes",
  "sideEffects",
  "source",
  "types"
];

// src/actions/package/compileTargetsPublint.ts
import fs from "node:fs";
import path from "node:path";
import chalk from "chalk";
import ts from "typescript";
var COMPILE_TARGET_NAMES = /* @__PURE__ */ new Set(["browser", "neutral", "node"]);
var CONFIG_FILE_NAMES = [
  "xy.config.ts",
  "xy.config.mts",
  "xy.config.cts",
  "xy.config.js",
  "xy.config.mjs",
  "xy.config.cjs"
];
function emptyResult() {
  return {
    errors: 0,
    modified: false,
    warnings: 0
  };
}
function findConfigFile(pkgDir) {
  for (const name of CONFIG_FILE_NAMES) {
    const candidate = path.join(pkgDir, name);
    if (fs.existsSync(candidate)) return candidate;
  }
  return void 0;
}
function getPropertyName(prop) {
  if (!ts.isPropertyAssignment(prop)) return void 0;
  const { name } = prop;
  if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
  return void 0;
}
function collectEmptyTargetProps(sourceFile) {
  const found = [];
  function visit(node) {
    if (ts.isPropertyAssignment(node) && getPropertyName(node) === "compile" && ts.isObjectLiteralExpression(node.initializer)) {
      for (const prop of node.initializer.properties) {
        if (ts.isPropertyAssignment(prop) && COMPILE_TARGET_NAMES.has(getPropertyName(prop) ?? "") && ts.isObjectLiteralExpression(prop.initializer) && prop.initializer.properties.length === 0) {
          found.push(prop);
        }
      }
    }
    ts.forEachChild(node, visit);
  }
  visit(sourceFile);
  return found;
}
function isWhitespace(char) {
  return char !== void 0 && /\s/.test(char);
}
function removeProperties(text, props, sourceFile) {
  const sorted = props.toSorted((a, b) => b.getStart(sourceFile) - a.getStart(sourceFile));
  let result = text;
  for (const prop of sorted) {
    let start = prop.getFullStart();
    let end = prop.getEnd();
    let cursor = end;
    while (isWhitespace(result[cursor])) cursor++;
    if (result[cursor] === ",") {
      end = cursor + 1;
    } else {
      let back = prop.getStart(sourceFile) - 1;
      while (back >= 0 && isWhitespace(result[back])) back--;
      if (result[back] === ",") start = back;
    }
    result = result.slice(0, start) + result.slice(end);
  }
  return result;
}
function checkCompileTargets(pkgDir, fix) {
  const result = emptyResult();
  const configPath = findConfigFile(pkgDir);
  if (configPath === void 0) return result;
  const text = fs.readFileSync(configPath, "utf8");
  const sourceFile = ts.createSourceFile(path.basename(configPath), text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
  const emptyProps = collectEmptyTargetProps(sourceFile);
  if (emptyProps.length === 0) return result;
  const configName = path.basename(configPath);
  if (fix) {
    fs.writeFileSync(configPath, removeProperties(text, emptyProps, sourceFile));
    for (const prop of emptyProps) {
      console.warn(chalk.yellow(`Publint [compileTargets]: removed deprecated empty "compile.${getPropertyName(prop)}" target from ${configName}`));
    }
    result.modified = true;
  } else {
    for (const prop of emptyProps) {
      console.warn(chalk.yellow(
        `Publint [compileTargets]: "compile.${getPropertyName(prop)} = {}" is treated as "do not build" \u2014 set it to \`false\` or remove it (use --fix to remove) in ${configName}`
      ));
    }
  }
  result.warnings += emptyProps.length;
  return result;
}

// src/actions/package/platformPublint.ts
import fs2 from "node:fs";
import { builtinModules } from "node:module";
import path2 from "node:path";
import chalk2 from "chalk";
import { globSync } from "glob";
import ts2 from "typescript";
var platformSegments = /* @__PURE__ */ new Set(["browser", "neutral", "node"]);
var nodeConditionNames = /* @__PURE__ */ new Set(["node", "node-addons"]);
var browserConditionNames = /* @__PURE__ */ new Set(["browser", "web", "webworker", "worker"]);
var neutralConditionNames = /* @__PURE__ */ new Set(["neutral"]);
var builtinModuleNames = new Set(
  builtinModules.map((mod) => mod.replace(/^node:/, "")).filter((mod) => !mod.startsWith("_"))
);
var codeExtensions = [".mjs", ".cjs", ".js"];
var declarationExtensions = [".d.mts", ".d.cts", ".d.ts"];
function emptyResult2() {
  return {
    errors: 0,
    modified: false,
    warnings: 0
  };
}
function toPosixPath(value) {
  return value.split(path2.sep).join("/");
}
function relativePath(pkgDir, filePath) {
  return toPosixPath(path2.relative(pkgDir, filePath));
}
function isSubpathExportKey(key) {
  return key === "." || key.startsWith("./");
}
function formatExportPath(pathParts) {
  return pathParts.map((part, index) => {
    if (index === 0) return part;
    if (part.startsWith("[")) return part;
    return /^[a-zA-Z_$][\w$]*$/.test(part) ? `.${part}` : `[${JSON.stringify(part)}]`;
  }).join("");
}
function conditionPlatform(key) {
  if (nodeConditionNames.has(key)) return "node";
  if (browserConditionNames.has(key)) return "browser";
  if (neutralConditionNames.has(key)) return "neutral";
  return void 0;
}
function getConditionPlatform(conditionPath) {
  for (const condition of conditionPath.toReversed()) {
    const platform = conditionPlatform(condition);
    if (platform) return platform;
  }
  return void 0;
}
function getPathPlatform(target) {
  const segments = target.replace(/^\.\//, "").split(/[\\/]+/);
  const distIndex = segments.indexOf("dist");
  const platform = distIndex === -1 ? void 0 : segments[distIndex + 1];
  return platformSegments.has(platform) ? platform : void 0;
}
function collectExportTargets(value, pathParts = ["exports"], conditionPath = []) {
  if (typeof value === "string") {
    if (!value.startsWith("./")) return [];
    return [{
      conditionPath,
      conditionPlatform: getConditionPlatform(conditionPath),
      exportPath: formatExportPath(pathParts),
      pathPlatform: getPathPlatform(value),
      target: value
    }];
  }
  if (Array.isArray(value)) {
    return value.flatMap((entry, index) => collectExportTargets(entry, [...pathParts, `[${index}]`], conditionPath));
  }
  if (typeof value !== "object" || value === null) return [];
  return Object.entries(value).flatMap(([key, nested]) => {
    const nextConditionPath = isSubpathExportKey(key) ? conditionPath : [...conditionPath, key];
    return collectExportTargets(nested, [...pathParts, key], nextConditionPath);
  });
}
function isDeclarationFile(filePath) {
  return declarationExtensions.some((ext) => filePath.endsWith(ext));
}
function isCodeFile(filePath) {
  return codeExtensions.some((ext) => filePath.endsWith(ext));
}
function hasCodeOrDeclarationExtension(filePath) {
  return isCodeFile(filePath) || isDeclarationFile(filePath);
}
function pathCandidates(filePath, extensions) {
  const candidates = [filePath];
  const parsed = path2.parse(filePath);
  const withoutExtension = parsed.ext ? filePath.slice(0, -parsed.ext.length) : filePath;
  for (const ext of extensions) {
    candidates.push(`${withoutExtension}${ext}`, `${filePath}${ext}`, path2.join(filePath, `index${ext}`));
  }
  return [...new Set(candidates)];
}
function declarationCandidates(filePath) {
  const extensionCandidates = filePath.endsWith(".mjs") ? [filePath.replace(/\.mjs$/, ".d.mts"), filePath.replace(/\.mjs$/, ".d.ts")] : filePath.endsWith(".cjs") ? [filePath.replace(/\.cjs$/, ".d.cts"), filePath.replace(/\.cjs$/, ".d.ts")] : filePath.endsWith(".js") ? [filePath.replace(/\.js$/, ".d.ts")] : [];
  return [.../* @__PURE__ */ new Set([filePath, ...extensionCandidates, ...pathCandidates(filePath, declarationExtensions)])];
}
function resolveExistingFile(filePath, declaration) {
  const candidates = declaration ? declarationCandidates(filePath) : pathCandidates(filePath, codeExtensions);
  return candidates.find((candidate) => fs2.existsSync(candidate) && fs2.statSync(candidate).isFile());
}
function resolveExportTargetFiles(pkgDir, target) {
  if (!hasCodeOrDeclarationExtension(target) && !target.includes("*")) return [];
  const relativeTarget = target.replace(/^\.\//, "");
  if (relativeTarget.includes("*")) {
    return globSync(relativeTarget, {
      cwd: pkgDir,
      nodir: true,
      absolute: true
    }).filter(hasCodeOrDeclarationExtension);
  }
  const absoluteTarget = path2.resolve(pkgDir, relativeTarget);
  const exact = fs2.existsSync(absoluteTarget) && fs2.statSync(absoluteTarget).isFile() ? absoluteTarget : resolveExistingFile(absoluteTarget, isDeclarationFile(relativeTarget));
  return exact != null && exact.length > 0 ? [exact] : [];
}
function isNodeBuiltin(specifier) {
  const normalized = specifier.replace(/^node:/, "");
  return specifier === "node" || specifier.startsWith("node:") || builtinModuleNames.has(normalized) || builtinModuleNames.has(normalized.split("/", 1)[0] ?? "");
}
function parseSourceFile(filePath) {
  const sourceCode = fs2.readFileSync(filePath, "utf8");
  const scriptKind = isCodeFile(filePath) ? ts2.ScriptKind.JS : ts2.ScriptKind.TS;
  return ts2.createSourceFile(path2.basename(filePath), sourceCode, ts2.ScriptTarget.Latest, true, scriptKind);
}
function stringLiteralText(node) {
  return node && ts2.isStringLiteral(node) ? node.text : void 0;
}
function collectModuleSpecifiers(sourceFile) {
  const specifiers = [];
  function addSpecifier(node) {
    const text = stringLiteralText(node);
    if (text != null && text.length > 0) specifiers.push(text);
  }
  function visit(node) {
    if (ts2.isImportDeclaration(node) || ts2.isExportDeclaration(node)) {
      addSpecifier(node.moduleSpecifier);
    } else if (ts2.isCallExpression(node) && node.expression.kind === ts2.SyntaxKind.ImportKeyword) {
      addSpecifier(node.arguments[0]);
    } else if (ts2.isCallExpression(node) && ts2.isIdentifier(node.expression) && node.expression.text === "require" && node.arguments.length > 0) {
      addSpecifier(node.arguments[0]);
    } else if (ts2.isImportTypeNode(node)) {
      if (ts2.isLiteralTypeNode(node.argument)) addSpecifier(node.argument.literal);
    } else if (ts2.isImportEqualsDeclaration(node) && ts2.isExternalModuleReference(node.moduleReference)) {
      addSpecifier(node.moduleReference.expression);
    }
    ts2.forEachChild(node, visit);
  }
  visit(sourceFile);
  for (const ref of sourceFile.typeReferenceDirectives) {
    specifiers.push(ref.fileName);
  }
  return specifiers;
}
function resolveLocalSpecifier(filePath, specifier, declaration) {
  if (!specifier.startsWith(".")) return void 0;
  return resolveExistingFile(path2.resolve(path2.dirname(filePath), specifier), declaration);
}
function nodeAmbientGlobalFromName(name) {
  if (name === "NodeJS") return "NodeJS";
  if (name === "Buffer") return "Buffer";
  if (name === "process") return "process";
  return void 0;
}
function getQualifiedRootName(name) {
  return ts2.isIdentifier(name) ? name.text : getQualifiedRootName(name.left);
}
function getPropertyAccessRootName(expression) {
  let current = expression;
  while (ts2.isPropertyAccessExpression(current)) {
    current = current.expression;
  }
  return ts2.isIdentifier(current) ? current.text : "";
}
function getNodeAmbientGlobal(sourceFile) {
  let ambient;
  function visit(node) {
    if (ambient != null && ambient.length > 0) return;
    if (ts2.isTypeReferenceNode(node)) {
      ambient = nodeAmbientGlobalFromName(getQualifiedRootName(node.typeName));
    } else if (ts2.isExpressionWithTypeArguments(node) && ts2.isIdentifier(node.expression)) {
      ambient = nodeAmbientGlobalFromName(node.expression.text);
    } else if (ts2.isExpressionWithTypeArguments(node) && ts2.isPropertyAccessExpression(node.expression)) {
      ambient = nodeAmbientGlobalFromName(getPropertyAccessRootName(node.expression));
    } else if (ts2.isTypeQueryNode(node)) {
      ambient = nodeAmbientGlobalFromName(getQualifiedRootName(node.exprName));
    }
    ts2.forEachChild(node, visit);
  }
  visit(sourceFile);
  return ambient;
}
function scanFileGraph(rootFile, platform, target) {
  const declaration = isDeclarationFile(rootFile);
  const queue = [rootFile];
  const seen = /* @__PURE__ */ new Set();
  const diagnostics = [];
  while (queue.length > 0) {
    const file = queue.shift();
    if (!(file != null && file.length > 0) || seen.has(file)) continue;
    seen.add(file);
    const sourceFile = parseSourceFile(file);
    for (const specifier of collectModuleSpecifiers(sourceFile)) {
      if (isNodeBuiltin(specifier)) {
        diagnostics.push({
          detail: specifier,
          exportPath: target.exportPath,
          file,
          kind: "node-builtin-import",
          platform,
          target: target.target
        });
      }
      const resolved = resolveLocalSpecifier(file, specifier, declaration);
      if (resolved != null && resolved.length > 0 && !seen.has(resolved)) queue.push(resolved);
    }
    if (declaration) {
      const ambient = getNodeAmbientGlobal(sourceFile);
      if (ambient != null && ambient.length > 0) {
        diagnostics.push({
          detail: ambient,
          exportPath: target.exportPath,
          file,
          kind: "node-ambient-type",
          platform,
          target: target.target
        });
      }
    }
  }
  return diagnostics;
}
function shouldScanForNodeUsage(target) {
  if (target.pathPlatform === "browser" || target.pathPlatform === "neutral") return target.pathPlatform;
  if (target.conditionPlatform === "browser" || target.conditionPlatform === "neutral") return target.conditionPlatform;
  return void 0;
}
function collectConditionTargetDiagnostics(targets) {
  const diagnostics = [];
  for (const target of targets) {
    const { conditionPlatform: condition, pathPlatform: output } = target;
    if (!condition || !output) continue;
    if (condition === "browser" && output === "node" || condition === "node" && output === "browser" || condition === "neutral" && output !== "neutral") {
      diagnostics.push({
        detail: `${condition} condition points to ${output} output`,
        exportPath: target.exportPath,
        kind: "condition-target-mismatch",
        platform: condition,
        target: target.target
      });
    }
  }
  return diagnostics;
}
function isRuntimeTarget(target) {
  return codeExtensions.some((ext) => target.target.endsWith(ext));
}
function isPortableTarget(target) {
  return target.conditionPlatform === "browser" || target.conditionPlatform === "neutral" || target.pathPlatform === "browser" || target.pathPlatform === "neutral" || !target.conditionPlatform && !target.pathPlatform;
}
function isNodeTarget(target) {
  return target.conditionPlatform === "node" || target.pathPlatform === "node";
}
function isNodeOnlyPackage(pkg, targets) {
  const runtimeTargets = targets.filter(isRuntimeTarget);
  const platformTargets = runtimeTargets.length > 0 ? runtimeTargets : targets;
  if (platformTargets.length === 0) return pkg.bin !== void 0;
  return platformTargets.some(isNodeTarget) && !platformTargets.some(isPortableTarget);
}
function readRootTsconfigTypes(pkgDir) {
  const configPath = path2.join(pkgDir, "tsconfig.json");
  if (!fs2.existsSync(configPath)) return [];
  const parsed = ts2.parseConfigFileTextToJson(configPath, fs2.readFileSync(configPath, "utf8"));
  const config = parsed.config;
  const types = config?.compilerOptions?.types;
  return Array.isArray(types) ? types.filter((value) => typeof value === "string") : [];
}
function collectTsconfigDiagnostics(pkgDir, pkg, targets) {
  if (targets.length === 0) return [];
  if (isNodeOnlyPackage(pkg, targets)) return [];
  const types = readRootTsconfigTypes(pkgDir);
  return types.includes("node") ? [{
    detail: 'compilerOptions.types includes "node"',
    file: path2.join(pkgDir, "tsconfig.json"),
    kind: "tsconfig-node-types"
  }] : [];
}
function diagnosticKey(pkgDir, diagnostic) {
  return [
    diagnostic.kind,
    diagnostic.platform ?? "",
    diagnostic.target ?? "",
    diagnostic.exportPath ?? "",
    diagnostic.file != null && diagnostic.file.length > 0 ? relativePath(pkgDir, diagnostic.file) : "",
    diagnostic.detail ?? ""
  ].join("\0");
}
function dedupeDiagnostics(pkgDir, diagnostics) {
  const seen = /* @__PURE__ */ new Set();
  const result = [];
  for (const diagnostic of diagnostics) {
    const key = diagnosticKey(pkgDir, diagnostic);
    if (seen.has(key)) continue;
    seen.add(key);
    result.push(diagnostic);
  }
  return result;
}
function renderDiagnostic(pkgDir, diagnostic) {
  switch (diagnostic.kind) {
    case "condition-target-mismatch": {
      return `Publint [platform]: ${diagnostic.detail} at ${diagnostic.exportPath} (${diagnostic.target})`;
    }
    case "node-builtin-import": {
      const file = relativePath(pkgDir, diagnostic.file ?? "");
      return `Publint [platform]: ${diagnostic.platform} export ${diagnostic.target} imports Node builtin "${diagnostic.detail}" in ${file} (${diagnostic.exportPath})`;
    }
    case "node-ambient-type": {
      const file = relativePath(pkgDir, diagnostic.file ?? "");
      return `Publint [platform]: ${diagnostic.platform} declaration ${diagnostic.target} exposes Node ambient "${diagnostic.detail}" in ${file} (${diagnostic.exportPath})`;
    }
    case "tsconfig-node-types": {
      return 'Publint [platform]: non-node package tsconfig.json should not include compilerOptions.types "node"';
    }
  }
}
function checkPlatform(pkgDir, pkg) {
  const result = emptyResult2();
  const targets = collectExportTargets(pkg.exports);
  const diagnostics = [...collectConditionTargetDiagnostics(targets)];
  for (const target of targets) {
    const platform = shouldScanForNodeUsage(target);
    if (!platform) continue;
    for (const file of resolveExportTargetFiles(pkgDir, target.target)) {
      diagnostics.push(...scanFileGraph(file, platform, target));
    }
  }
  diagnostics.push(...collectTsconfigDiagnostics(pkgDir, pkg, targets));
  for (const diagnostic of dedupeDiagnostics(pkgDir, diagnostics)) {
    console.error(chalk2.red(renderDiagnostic(pkgDir, diagnostic)));
    result.errors++;
  }
  return result;
}

// src/actions/package/publint.ts
var removeSourceFromExports = (exports) => {
  let removed = false;
  for (const [key, value] of Object.entries(exports)) {
    if (key === "source") {
      delete exports[key];
      removed = true;
    } else if (typeof value === "object" && value !== null && removeSourceFromExports(value)) removed = true;
  }
  return removed;
};
var hasSourceInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "source") return true;
    if (typeof value === "object" && value !== null && hasSourceInExports(value)) return true;
  }
  return false;
};
var hasImportKeyInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "import" && typeof value === "string" && value.endsWith(".mjs")) return true;
    if (typeof value === "object" && value !== null && hasImportKeyInExports(value)) return true;
  }
  return false;
};
var replaceImportWithDefault = (exports) => {
  let modified = false;
  for (const [key, value] of Object.entries(exports)) {
    if (key === "import" && typeof value === "string" && value.endsWith(".mjs")) {
      if (exports.default === void 0) {
        exports.default = value;
      }
      delete exports.import;
      if (exports.types === void 0) {
        exports.types = value.replace(/\.mjs$/, ".d.ts");
      }
      modified = true;
    } else if (typeof value === "object" && value !== null && replaceImportWithDefault(value)) modified = true;
  }
  return modified;
};
var hasTypesInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "types") return true;
    if (typeof value === "object" && value !== null && hasTypesInExports(value)) return true;
  }
  return false;
};
function ensureExportsPath(value) {
  if (value.startsWith("./") || value.startsWith("../")) return value;
  return `./${value}`;
}
function emptyCustomResult() {
  return {
    errors: 0,
    modified: false,
    warnings: 0
  };
}
function mergeResults(target, source) {
  target.errors += source.errors;
  target.warnings += source.warnings;
  target.modified = target.modified || source.modified;
}
function checkFiles(pkg, fix) {
  const result = emptyCustomResult();
  const files = pkg.files;
  if (files === void 0) {
    console.warn(chalk3.yellow('Publint [custom]: "files" field is missing'));
    result.warnings++;
  }
  if (Array.isArray(files) && !files.includes("README.md")) {
    files.push("README.md");
    console.warn(chalk3.yellow('Publint [custom]: added "README.md" to "files"'));
    result.modified = true;
    result.warnings++;
  }
  if (Array.isArray(files) && files.includes("src")) {
    if (fix) {
      pkg.files = files.filter((f) => f !== "src");
      console.warn(chalk3.yellow('Publint [custom]: removed "src" from "files"'));
      result.modified = true;
    } else {
      console.warn(chalk3.yellow('Publint [custom]: "src" should not be in "files" (use --fix to remove)'));
    }
    result.warnings++;
  }
  return result;
}
function checkExportsSource(pkg, fix) {
  const result = emptyCustomResult();
  const exports = pkg.exports;
  if (exports && typeof exports === "object" && hasSourceInExports(exports)) {
    if (fix) {
      removeSourceFromExports(exports);
      console.warn(chalk3.yellow('Publint [custom]: removed "source" entries from "exports"'));
      result.modified = true;
    } else {
      console.warn(chalk3.yellow('Publint [custom]: "source" entries should not be in "exports" (use --fix to remove)'));
    }
    result.warnings++;
  }
  return result;
}
function migrateFieldToExports(pkg, field, exportKey, fix) {
  const result = emptyCustomResult();
  if (pkg[field] === void 0) return result;
  const fieldValue = pkg[field];
  if (!fieldValue.endsWith(".js") && !fieldValue.endsWith(".mjs") && !fieldValue.endsWith(".cjs")) return result;
  if (fix) {
    const exportValue = ensureExportsPath(fieldValue);
    const exports = pkg.exports;
    if (exports && typeof exports === "object") {
      const dot = exports["."];
      if (dot != null && typeof dot === "object" && !Object.hasOwn(dot, exportKey)) {
        dot[exportKey] = exportValue;
        console.warn(chalk3.yellow(`Publint [custom]: migrated "${field}" to "exports['.'].${exportKey}" (${fieldValue})`));
      }
    } else if (pkg.exports == null) {
      pkg.exports = { ".": { [exportKey]: exportValue } };
      console.warn(chalk3.yellow(`Publint [custom]: migrated "${field}" to "exports" (.\u2192${fieldValue})`));
    }
    delete pkg[field];
    console.warn(chalk3.yellow(`Publint [custom]: removed deprecated "${field}" field`));
    result.modified = true;
  } else {
    console.warn(chalk3.yellow(`Publint [custom]: "${field}" field is deprecated, use "exports" instead (use --fix to remove)`));
  }
  result.warnings++;
  return result;
}
function checkSideEffects(pkg) {
  const result = emptyCustomResult();
  if (pkg.sideEffects !== false) {
    console.warn(chalk3.yellow('Publint [custom]: "sideEffects" field should be set to false'));
    result.warnings++;
  }
  return result;
}
function checkRootSource(pkg, fix) {
  const result = emptyCustomResult();
  for (const field of ["source", "src"]) {
    if (pkg[field] !== void 0) {
      if (fix) {
        delete pkg[field];
        console.warn(chalk3.yellow(`Publint [custom]: removed root-level "${field}" field`));
        result.modified = true;
      } else {
        console.warn(chalk3.yellow(`Publint [custom]: root-level "${field}" field should not be in package.json (use --fix to remove)`));
      }
      result.warnings++;
    }
  }
  return result;
}
function checkResolutions(pkg) {
  const result = emptyCustomResult();
  if (pkg.resolutions !== void 0) {
    console.warn(chalk3.yellow('Publint [custom]: "resolutions" in use'));
    console.warn(chalk3.gray(JSON.stringify(pkg.resolutions, null, 2)));
    result.warnings++;
  }
  return result;
}
function checkImportToDefault(pkg, fix) {
  const result = emptyCustomResult();
  const exports = pkg.exports;
  if (!exports || typeof exports !== "object") return result;
  if (!hasImportKeyInExports(exports)) return result;
  if (fix) {
    replaceImportWithDefault(exports);
    console.warn(chalk3.yellow('Publint [custom]: renamed "import" to "default" in "exports" and ensured "types" siblings'));
    result.modified = true;
  } else {
    console.warn(chalk3.yellow('Publint [custom]: "import" entries in "exports" should use "default" instead (use --fix to rename)'));
  }
  result.warnings++;
  return result;
}
function checkRootTypes(pkg, fix) {
  const result = emptyCustomResult();
  if (pkg.types === void 0) return result;
  const exports = pkg.exports;
  if (!exports || typeof exports !== "object" || !hasTypesInExports(exports)) return result;
  if (fix) {
    delete pkg.types;
    console.warn(chalk3.yellow('Publint [custom]: removed redundant root "types" field (already defined in "exports")'));
    result.modified = true;
  } else {
    console.warn(chalk3.yellow('Publint [custom]: root "types" field is redundant when "exports" defines types (use --fix to remove)'));
  }
  result.warnings++;
  return result;
}
function customPubLint(pkgDir, pkg, fix = false, exclude = /* @__PURE__ */ new Set()) {
  const result = emptyCustomResult();
  if (!exclude.has("files")) mergeResults(result, checkFiles(pkg, fix));
  if (!exclude.has("source")) mergeResults(result, checkExportsSource(pkg, fix));
  if (!exclude.has("rootSource")) mergeResults(result, checkRootSource(pkg, fix));
  if (!exclude.has("main")) mergeResults(result, migrateFieldToExports(pkg, "main", "default", fix));
  if (!exclude.has("types")) mergeResults(result, migrateFieldToExports(pkg, "types", "types", fix));
  if (!exclude.has("module")) mergeResults(result, migrateFieldToExports(pkg, "module", "default", fix));
  if (!exclude.has("importToDefault")) mergeResults(result, checkImportToDefault(pkg, fix));
  if (!exclude.has("rootTypes")) mergeResults(result, checkRootTypes(pkg, fix));
  if (!exclude.has("platform")) mergeResults(result, checkPlatform(pkgDir, pkg));
  if (!exclude.has("sideEffects")) mergeResults(result, checkSideEffects(pkg));
  if (!exclude.has("resolutions")) mergeResults(result, checkResolutions(pkg));
  return [result.errors, result.warnings, result.modified];
}
var ALWAYS_INCLUDED_PATTERNS = [
  "package.json",
  "README",
  "README.*",
  "LICENCE",
  "LICENCE.*",
  "LICENSE",
  "LICENSE.*",
  "CHANGELOG",
  "CHANGELOG.*"
];
async function resolvePackFiles(pkgDir, filesField) {
  const patterns = [...ALWAYS_INCLUDED_PATTERNS];
  if (filesField) {
    for (const pattern of filesField) {
      if (pattern.startsWith("!")) {
        patterns.push(pattern);
      } else {
        patterns.push(pattern, `${pattern}/**`);
      }
    }
  }
  const matched = await glob(patterns, {
    cwd: pkgDir,
    nodir: true,
    dot: false
  });
  const files = await Promise.all(
    matched.map(async (rel) => {
      const abs = path3.join(pkgDir, rel);
      let data = "";
      try {
        data = await fs3.readFile(abs, "utf8");
      } catch {
      }
      return { name: path3.join(pkgDir, rel), data };
    })
  );
  return files;
}
function logPublintMessage(message, pkg, formatMessage) {
  const formatted = `[${message.code}] ${formatMessage(message, pkg) ?? message.code}`;
  switch (message.type) {
    case "error": {
      console.error(chalk3.red(formatted));
      return;
    }
    case "warning": {
      console.warn(chalk3.yellow(formatted));
      return;
    }
    default: {
      console.log(chalk3.white(formatted));
    }
  }
}
async function runPublintLibrary(pkgDir, pkg, strict, pack) {
  const { publint } = await import("publint");
  let packOption = false;
  if (pack) {
    const files = await resolvePackFiles(pkgDir, pkg.files);
    packOption = { files };
  }
  const { messages } = await publint({
    level: "suggestion",
    pack: packOption,
    pkgDir,
    strict
  });
  const { formatMessage } = await import("publint/utils");
  for (const message of messages) {
    logPublintMessage(message, pkg, formatMessage);
  }
  return {
    errors: messages.filter((message) => message.type === "error").length,
    warnings: messages.filter((message) => message.type !== "error").length
  };
}
var packagePublintDetailed = async ({
  exclude = /* @__PURE__ */ new Set(),
  fix = false,
  pack = true,
  pkgDir: pkgDirParam,
  strict = isStrictMode(),
  verbose: _verbose = false
} = {}) => {
  const pkgDir = path3.resolve(pkgDirParam ?? INIT_CWD());
  const sortedPkg = sortPackageJson(await fs3.readFile(`${pkgDir}/package.json`, "utf8"));
  await fs3.writeFile(`${pkgDir}/package.json`, sortedPkg);
  const pkg = JSON.parse(await fs3.readFile(`${pkgDir}/package.json`, "utf8"));
  const effectiveExclude = Boolean(pkg.private) ? /* @__PURE__ */ new Set([...exclude, ...PUBLISH_ONLY_CHECKS]) : exclude;
  console.log(chalk3.green(`Publint: ${String(pkg.name)}${Boolean(pkg.private) ? chalk3.gray(" (private)") : ""}`));
  console.log(chalk3.gray(pkgDir));
  let libraryErrors = 0;
  let libraryWarnings = 0;
  if (!effectiveExclude.has("publint")) {
    const library = await runPublintLibrary(pkgDir, pkg, strict, pack);
    libraryErrors = library.errors;
    libraryWarnings = library.warnings;
  }
  const [errorCount, warningCount, modified] = customPubLint(pkgDir, pkg, fix, effectiveExclude);
  if (modified) {
    const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
    await fs3.writeFile(`${pkgDir}/package.json`, sorted);
  }
  const compileTargets = effectiveExclude.has("compileTargets") ? { errors: 0, warnings: 0 } : checkCompileTargets(pkgDir, fix);
  return {
    errors: libraryErrors + errorCount + compileTargets.errors,
    warnings: libraryWarnings + warningCount + compileTargets.warnings
  };
};
var packagePublint = async (params = {}) => {
  const result = await packagePublintDetailed(params);
  return result.errors + (isStrictMode() ? result.warnings : 0);
};
export {
  packagePublint,
  packagePublintDetailed
};
//# sourceMappingURL=publint.mjs.map
