All files / src project.ts

94% Statements 94/100
86.27% Branches 44/51
100% Functions 10/10
95.65% Lines 88/92

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                                                                            98x 98x 98x 98x 98x             285x 285x 285x 285x 290x 49x 49x   241x 241x 4x 4x   237x 237x 237x   285x 289x       289x 289x 4x 4x   285x 285x 285x   285x 285x       8x               49x               993x           40x   953x 953x 953x 40x   913x 913x 953x 951x 26x 8x   925x     895x             34x 34x             191x   191x 191x 190x 188x 1x                   187x   3x   187x 187x 187x 187x 187x 187x             187x             187x 187x           187x 156x 156x 162x 162x         164x   156x                               374x 374x     385x   359x 359x                   359x 359x 354x 2x             2x   352x   5x           901x 901x                       8x 8x            
import { readFile, realpath } from "node:fs/promises";
import { isAbsolute, relative, resolve, sep, win32 } from "node:path";
 
import { parseManifest, type MouraManifest } from "./manifest.js";
import {
  locateRequirementMarkdown,
  parseRequirementMarkdown,
  parseSpecificationMarkdown,
  type RequirementSourceLocation,
} from "./markdown.js";
import {
  error,
  type ValidationError,
  type ValidationResult,
} from "./validation.js";
import { validateStructure } from "./validator.js";
 
export interface ProjectInput {
  readonly manifest: string;
  readonly requirementSources: ReadonlyMap<string, string>;
  readonly specificationSources: ReadonlyMap<string, string>;
}
 
export interface LoadedProjectResult extends ValidationResult {
  /** Present only when the complete project is structurally valid. */
  readonly manifest?: MouraManifest;
  /** Source metadata for report navigation; never part of Requirement identity. */
  readonly requirementLocations?: ReadonlyMap<
    string,
    RequirementSourceLocation
  >;
  /** Validated source contents used to build provider-neutral report pages. */
  readonly requirementSources?: ReadonlyMap<string, string>;
  readonly specificationSources?: ReadonlyMap<string, string>;
}
 
/** Reusable, deterministic validation entry point for in-memory project files. */
export function validateProject(input: ProjectInput): ValidationResult {
  const parsed = parseManifest(input.manifest);
  const errors: ValidationError[] = [...parsed.errors];
  Iif (!parsed.value) return { errors };
  errors.push(...validateParsedProject(parsed.value, input));
  return { errors };
}
 
function validateParsedProject(
  manifest: MouraManifest,
  input: Omit<ProjectInput, "manifest">,
): readonly ValidationError[] {
  const errors: ValidationError[] = [];
  const requirements = new Map<string, readonly string[]>();
  const specifications = new Map();
  for (const source of manifest.sources.requirements) {
    if (!isValidProjectRelativeSourcePath(source)) {
      errors.push(invalidSourcePath(source, "requirement"));
      continue;
    }
    const text = input.requirementSources.get(source);
    if (text === undefined) {
      errors.push(missingSource(source, "requirement"));
      continue;
    }
    const result = parseRequirementMarkdown(text, source, manifest);
    errors.push(...result.errors);
    Eif (result.value) requirements.set(source, result.value);
  }
  for (const source of manifest.sources.specifications) {
    Iif (!isValidProjectRelativeSourcePath(source)) {
      errors.push(invalidSourcePath(source, "specification"));
      continue;
    }
    const text = input.specificationSources.get(source);
    if (text === undefined) {
      errors.push(missingSource(source, "specification"));
      continue;
    }
    const result = parseSpecificationMarkdown(text, source, manifest);
    errors.push(...result.errors);
    Eif (result.value) specifications.set(source, result.value);
  }
  errors.push(...validateStructure(manifest, { requirements, specifications }));
  return errors;
}
 
function missingSource(path: string, kind: string): ValidationError {
  return error(
    "missing-source",
    `Configured ${kind} source ${path} was not provided`,
    { source: path },
  );
}
 
function invalidSourcePath(path: string, kind: string): ValidationError {
  return error(
    "invalid-source-path",
    `Configured ${kind} source ${path} must be a project-relative file path`,
    { source: path },
  );
}
 
export function isValidProjectRelativeSourcePath(path: string): boolean {
  if (
    path.includes("\0") ||
    isAbsolute(path) ||
    win32.isAbsolute(path) ||
    /^[a-z]:/iu.test(path)
  )
    return false;
 
  const segments = path.split(/[\\/]/u);
  const finalSegment = segments.at(-1);
  if (finalSegment === "" || finalSegment === "." || finalSegment === "..")
    return false;
 
  let depth = 0;
  for (const segment of segments) {
    if (segment === "" || segment === ".") continue;
    if (segment === "..") {
      if (depth === 0) return false;
      depth -= 1;
    } else {
      depth += 1;
    }
  }
  return depth > 0;
}
 
/** Filesystem adapter used by the CLI; integrations can use validateProject directly. */
export async function validateProjectDirectory(
  directory: string,
): Promise<ValidationResult> {
  const loaded = await loadProjectDirectory(directory);
  return { errors: loaded.errors };
}
 
/** Load project files once and expose the manifest only after full validation. */
export async function loadProjectDirectory(
  directory: string,
): Promise<LoadedProjectResult> {
  const manifestPath = resolve(directory, "moura.yaml");
  let manifest: string;
  try {
    const projectRoot = await realpath(resolve(directory));
    const realManifestPath = await realpath(manifestPath);
    if (!isWithin(projectRoot, realManifestPath)) {
      return {
        errors: [
          error(
            "invalid-source-path",
            "Configured manifest source moura.yaml must remain within the project directory",
            { source: "moura.yaml" },
          ),
        ],
      };
    }
    manifest = await readFile(realManifestPath, "utf8");
  } catch (cause) {
    return { errors: [readError("moura.yaml", cause)] };
  }
  const parsed = parseManifest(manifest);
  Iif (!parsed.value) return { errors: parsed.errors };
  const requirementSources = new Map<string, string>();
  const specificationSources = new Map<string, string>();
  const errors: ValidationError[] = [];
  await load(
    parsed.value.sources.requirements,
    requirementSources,
    directory,
    errors,
    "requirement",
  );
  await load(
    parsed.value.sources.specifications,
    specificationSources,
    directory,
    errors,
    "specification",
  );
  errors.push(...parsed.errors);
  errors.push(
    ...validateParsedProject(parsed.value, {
      requirementSources,
      specificationSources,
    }),
  );
  if (errors.length > 0) return { errors };
  const requirementLocations = new Map<string, RequirementSourceLocation>();
  for (const source of parsed.value.sources.requirements) {
    const text = requirementSources.get(source)!;
    for (const [id, location] of locateRequirementMarkdown(
      text,
      source,
      parsed.value,
    ))
      requirementLocations.set(id, location);
  }
  return {
    manifest: parsed.value,
    requirementLocations,
    requirementSources,
    specificationSources,
    errors,
  };
}
 
async function load(
  paths: readonly string[],
  target: Map<string, string>,
  directory: string,
  errors: ValidationError[],
  kind: string,
): Promise<void> {
  const projectRoot = await realpath(resolve(directory));
  for (const path of paths) {
    // Core validation owns the manifest diagnostic. The adapter only skips the
    // unsafe read here so validateProject reports that contract error once.
    if (!isValidProjectRelativeSourcePath(path)) continue;
 
    const targetPath = resolve(projectRoot, path);
    Iif (!isWithin(projectRoot, targetPath)) {
      errors.push(
        error(
          "invalid-source-path",
          `Configured ${kind} source ${path} must remain within the project directory`,
          { source: path },
        ),
      );
      continue;
    }
    try {
      const realTargetPath = await realpath(targetPath);
      if (!isWithin(projectRoot, realTargetPath)) {
        errors.push(
          error(
            "invalid-source-path",
            `Configured ${kind} source ${path} must remain within the project directory`,
            { source: path },
          ),
        );
        continue;
      }
      target.set(path, await readFile(realTargetPath, "utf8"));
    } catch (cause) {
      errors.push(readError(path, cause, kind));
    }
  }
}
 
function isWithin(projectRoot: string, targetPath: string): boolean {
  const relativePath = relative(projectRoot, targetPath);
  return (
    relativePath !== ".." &&
    !relativePath.startsWith(`..${sep}`) &&
    !isAbsolute(relativePath)
  );
}
 
function readError(
  path: string,
  cause: unknown,
  kind = "manifest",
): ValidationError {
  const detail = cause instanceof Error ? cause.message : String(cause);
  return error(
    "unreadable-source",
    `Cannot read configured ${kind} source ${path}: ${detail}`,
    { source: path },
  );
}