Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

6.9 KB
Raw Blame
import type { LintPluginFailureReporter } from './plugin-failure.ts';
import { isLintPluginSelected, LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';

export async function lintDocument(
  text: string,
  config: LinterConfig,
  docName?: string,
  onPluginFailure?: LintPluginFailureReporter,
): Promise<LintDiagnostic[]> {
  if (!config.enabled) return [];
  const diagnostics: LintDiagnostic[] = [];
  for (const plugin of LINT_PLUGINS) {
    if (!isLintPluginSelected(config, plugin.id)) continue;
    const slice = config.plugins[plugin.id];
    try {
      diagnostics.push(...(await plugin.lint(text, slice as never, { docName })));
    } catch (err) {
      console.warn(`[lint] plugin "${plugin.id}" failed${docName ? ` on "${docName}"` : ''}`, err);
      onPluginFailure?.({
        source: plugin.id,
        phase: 'lint',
        ...(docName === undefined ? {} : { docName }),
        message: errorMessage(err),
      });
    }
  }
  return diagnostics;
}

export function fixDocument(
  text: string,
  config: LinterConfig,
  docName?: string,
  onPluginFailure?: LintPluginFailureReporter,
): string {
  if (!config.enabled) return text;
  let out = text;
  for (const plugin of LINT_PLUGINS) {
    if (!isLintPluginSelected(config, plugin.id) || !plugin.fix) continue;
    const slice = config.plugins[plugin.id];
    try {
      out = plugin.fix(out, slice as never);
    } catch (err) {
      console.warn(
        `[lint] plugin "${plugin.id}" fix failed${docName ? ` on "${docName}"` : ''}`,
        err,
      );
      onPluginFailure?.({
        source: plugin.id,
        phase: 'fix',
        ...(docName === undefined ? {} : { docName }),
        message: errorMessage(err),
      });
    }
  }
  return out;
}

const MAX_FAILURE_MESSAGE_LENGTH = 500;

function errorMessage(error: unknown): string {
  const raw = renderErrorMessage(error);
  return raw.length > MAX_FAILURE_MESSAGE_LENGTH
    ? `${raw.slice(0, MAX_FAILURE_MESSAGE_LENGTH)}… (truncated)`
    : raw;
}

function renderErrorMessage(error: unknown, depth = 0): string {
  if (error instanceof Error) {
    return error.cause === undefined || depth >= 3
      ? error.message
      : `${error.message} (cause: ${renderErrorMessage(error.cause, depth + 1)})`;
  }
  if (typeof error === 'object' && error !== null) {
    try {
      const json = JSON.stringify(error);
      if (json !== undefined) return json;
    } catch {}
  }
  return String(error);
}

export {
  type AppliesToPatternSummary,
  type AppliesToSummary,
  type CompiledAppliesTo,
  compileAppliesTo,
  findZeroMatchAppliesToPatterns,
  summarizeAppliesTo,
} from './applies-to.ts';
export { isMarkdownlintJsonConfig } from './config-files.ts';
export {
  type FrontmatterSchemasListSuccess,
  FrontmatterSchemasListSuccessSchema,
  type FrontmatterSchemaWriteRequest,
  FrontmatterSchemaWriteRequestSchema,
  isReLintFailedWarning,
  isReLintFailureReason,
  type LintAuditResponse,
  LintAuditResponseSchema,
  type LintConfigResponse,
  LintConfigResponseSchema,
  type LintDocResult,
  LintDocResultSchema,
  LinterConfigSchema,
  type LintFixRequest,
  LintFixRequestSchema,
  type LintFixResult,
  LintFixResultSchema,
  MarkdownlintRuleWriteRequestSchema,
  type PersistedLinterConfig,
  RE_LINT_FAILED_WARNING_PREFIX,
  RE_LINT_FAILURE_REASONS,
  type ReLintFailure,
  type ReLintFailureReason,
  ReLintFailureSchema,
  toEffectiveBase,
  type ValidationAuditCountsResponse,
  ValidationAuditCountsResponseSchema,
  type ValidationAuditResponse,
  ValidationAuditResponseSchema,
  type ValidationDocCounts,
  ValidationDocCountsSchema,
  type ValidationDocResult,
  ValidationDocResultSchema,
} from './config-schemas.ts';
export { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
export {
  applyFieldConstraint,
  emptyFrontmatterSchemaText,
  type FrontmatterFieldConstraint,
  FrontmatterSchemaEditError,
  isFrontmatterSchemaAsset,
  isToolManagedSchemaPath,
  removeSchemaField,
  renameSchemaField,
  type SchemaParentPathSegment,
} from './frontmatter-schema-edit.ts';
export {
  CANONICAL_SCHEMA_DIALECT_URIS,
  DEFAULT_SCHEMA_DIALECT,
  type FrontmatterSchemaDialect,
  frontmatterSchemaCompileError,
  isSupportedSchemaDialect,
  resolveFrontmatterSchemaDialect,
  SUPPORTED_SCHEMA_DIALECTS,
  selectApplicableFrontmatterSchemas,
} from './frontmatter-validate.ts';
export { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';
export {
  OKF_SCHEMA_DIR,
  type OkfSchemaFile,
  okfSchemaPathFor,
  renderOkfSchemaFiles,
} from './okf-frontmatter/materialize.ts';
export {
  OKF_FRONTMATTER_REGISTRY,
  okfAdvertisedSchemaMappings,
  runOkfFrontmatterRules,
  selectOkfFrontmatterSchemas,
} from './okf-frontmatter/registry.ts';
export {
  OKF_PROJECT_REGISTRY,
  type OkfProjectFinding,
  runOkfProjectRules,
} from './okf-project/rules.ts';
export {
  assertNeverOkfRuleGroupId,
  assertNeverOkfRuleId,
  isOkfRuleEnabled,
  OKF_RULE_GROUPS,
  OKF_RULE_IDS,
  type OkfRuleGroupId,
  type OkfRuleId,
  type OkfRuleToggles,
} from './okf-rule-meta.ts';
export {
  type LintPluginFailure,
  type LintPluginFailureReporter,
  summarizeLintPluginFailures,
} from './plugin-failure.ts';
export {
  DEFAULT_LINTER_CONFIG,
  type GoverningFrontmatterSchema,
  LINT_PLUGINS,
  type LinterConfig,
  type LintPlugin,
  type LintPluginId,
  selectAdvertisedFrontmatterMappings,
  selectFrontmatterOnlyConfig,
  selectGoverningFrontmatterSchemas,
} from './plugins.ts';
export { canonicalRuleId, findRuleConfigEntry } from './rule-aliases.ts';
export { MARKDOWNLINT_RULE_CATALOG } from './rule-catalog.generated.ts';
export {
  displayCategoryForRule,
  RULE_DISPLAY_CATEGORIES,
  type RuleDisplayCategory,
} from './rule-catalog-categories.ts';
export { applyTextEdits } from './text-edits.ts';
export type {
  FrontmatterSchemaMapping,
  FrontmatterScope,
  FrontmatterSlice,
  LinksValidationSetting,
  LintDiagnostic,
  LintPosition,
  LintRange,
  LintSeverity,
  LintTextEdit,
  LocalTargetDiagnosticEvidence,
  LocalTargetKind,
  LocalTargetResolutionMethod,
  LocalTargetRole,
  LocalTargetSourceForm,
  MarkdownlintRuleSetting,
  MarkdownlintRuleSeverity,
  MarkdownlintRuleWriteValue,
  MarkdownlintSlice,
  OkfSlice,
  ResolvedFrontmatterSchemaEntry,
  RuleCatalogEntry,
  RuleOptionSpec,
  RuleOptionType,
  ValidationDiagnostic,
  ValidationSource,
} from './types.ts';
export {
  DEFAULT_LINKS_VALIDATION,
  DEFAULT_SUPPRESS_LOG_LINK_ADVISORIES,
  isFrontmatterScoped,
  LINKS_VALIDATION_SETTINGS,
  LINT_PLUGIN_IDS,
  VALIDATION_SOURCES,
} from './types.ts';
export {
  countDiagnosticsBySource,
  type ValidationCountsBySource,
  type ValidationSourceCounts,
  type ValidationSourceKey,
  ZERO_SOURCE_COUNTS,
} from './validation-counts.ts';
export {
  AUDIT_EMPTY_SCOPE_WARNING,
  deriveValidationRunSources,
  isAuditEmptyScopeWarning,
  type ValidationRunMode,
  validationCoverageLines,
} from './validation-run-sources.ts';