All files / src/linter lintProject.ts

78.26% Statements 252/322
70.92% Branches 161/227
62.96% Functions 17/27
80.19% Lines 251/313

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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874  2x 2x         2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x   2x   2x                                                                   2x   2x     2x     1204x       1204x         1204x               1204x   1204x         350x 350x 350x     1204x                   1326x   1326x 350x 350x 350x 350x         1326x                             222x     258x 240x     18x 36x 36x 36x       222x     44x       45x   45x 45x     225x           1204x     1204x   1204x 205x 999x 189x 810x 263x 547x 8x 539x 174x 365x 15x   350x     1204x       1204x       298x 43x   255x 43x   212x 42x   170x 42x   128x 42x   86x 42x     44x             419x 72x     347x 347x 347x   347x 1326x 1326x 1326x   1326x       1326x   1326x 1x                   1326x 122x           297x                                 10x                                           2x                   2x                                 1x           1x 1x   1x                 1x                         7x           7x 7x 7x 7x 7x   7x                     7x                                                               45x   45x             45x 45x 45x 214x 214x             45x 45x 45x   45x 222x 222x           45x 43x   43x       43x 42x     43x 205x   205x 1x                   205x 205x 205x   205x 1x               45x 45x 222x 222x       222x   45x     45x 45x 45x   45x 42x   42x   42x 42x     42x 189x   189x                     189x 189x 188x   188x 1x     1x           45x 45x                   45x 42x   42x   42x 41x     42x 263x   263x                         263x 263x   263x   263x 2x           263x 7x 7x                             45x 45x   45x 42x   42x   42x 8x     42x 8x   8x                         8x 8x   8x   8x             8x 8x 8x                                 45x   45x 42x   42x   42x 41x     42x 174x   174x                     174x 174x   174x   174x                   45x 45x   45x 42x   42x   42x 8x     42x 15x   15x                     15x 15x   15x   15x                   45x   45x             45x 44x   44x   44x 43x     44x 350x   350x                     350x 350x   350x   350x 3x               45x           2x     1x   1x   1x 1x   1x 1x   1x                               1x 1x 1x     1x         1x       1x                                                                                        
// for use in node only
import * as fs from "fs";
import * as path from "path";
 
import type { Attribute, Schema } from "@featurevisor/types";
import type { ZodError } from "zod";
 
import { getAttributeZodSchema } from "./attributeSchema";
import { getConditionsZodSchema } from "./conditionSchema";
import { getSegmentZodSchema } from "./segmentSchema";
import { getGroupZodSchema } from "./groupSchema";
import { getFeatureZodSchema } from "./featureSchema";
import { getSchemaZodSchema } from "./schema";
import { getTestsZodSchema } from "./testSchema";
import { getTargetZodSchema } from "./targetSchema";
 
import { checkForCircularDependencyInRequired } from "./checkCircularDependency";
import { checkForFeatureExceedingGroupSlotPercentage } from "./checkPercentageExceedingSlot";
import { getLintIssuesFromZodError, printZodError } from "./printError";
import { Dependencies } from "../dependencies";
import { CLI_FORMAT_BOLD_UNDERLINE, CLI_FORMAT_GREEN, CLI_FORMAT_RED } from "../tester/cliFormat";
import { Plugin } from "../cli";
import { assertProjectSetJsonSelection, getProjectSetExecutions, printSetHeader } from "../sets";
 
export type LintEntityType =
  | "attribute"
  | "segment"
  | "feature"
  | "group"
  | "schema"
  | "target"
  | "test";
 
export interface LintProjectOptions {
  keyPattern?: string;
  entityType?: string;
  authors?: boolean;
  json?: boolean;
  pretty?: boolean;
}
 
export interface LintErrorItem {
  filePath: string;
  entityType: LintEntityType;
  key: string;
  message: string;
  path: (string | number)[];
  code?: string;
  value?: unknown;
}
 
export interface LintResult {
  hasError: boolean;
  errors: LintErrorItem[];
}
 
const ENTITY_NAME_REGEX = /^[a-zA-Z0-9_\-./]+$/;
const ENTITY_NAME_REGEX_ERROR =
  "Names must be alphanumeric and can contain _, -, /, ., and the configured namespace character";
 
const ATTRIBUTE_NAME_REGEX_ERROR =
  "Names must be alphanumeric and can contain _, -, /, ., and the configured namespace character";
 
function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
 
function isValidEntityKey(key: string, namespaceCharacter: string): boolean {
  const keyWithoutNamespaceCharacter = key.replace(
    new RegExp(escapeRegExp(namespaceCharacter), "g"),
    "",
  );
 
  return ENTITY_NAME_REGEX.test(keyWithoutNamespaceCharacter);
}
 
function getPathSegmentsFromKey(
  key: string,
  namespaceCharacter: string,
  entityType?: LintEntityType,
): string[] {
  const pathSegments = key.split(namespaceCharacter);
 
  if (
    entityType === "test" &&
    pathSegments.length > 1 &&
    ["spec", "feature", "segment"].includes(pathSegments[pathSegments.length - 1])
  ) {
    const suffix = pathSegments[pathSegments.length - 1];
    pathSegments[pathSegments.length - 2] = `${pathSegments[pathSegments.length - 2]}.${suffix}`;
    pathSegments.pop();
  }
 
  return pathSegments;
}
 
function getReservedNameCheckValue(
  entityType: LintEntityType,
  name: string,
  isFile: boolean,
  extension: string,
): string {
  let value =
    isFile && name.endsWith(`.${extension}`) ? name.slice(0, -extension.length - 1) : name;
 
  if (entityType === "test" && isFile) {
    for (const suffix of [".spec", ".feature", ".segment"]) {
      Eif (value.endsWith(suffix)) {
        value = value.slice(0, -suffix.length);
        break;
      }
    }
  }
 
  return value;
}
 
async function getAuthorsOfEntity(datasource, entityType, entityKey): Promise<string[]> {
  const entries = await datasource.listHistoryEntries(entityType, entityKey);
  const authors: string[] = Array.from(new Set(entries.map((entry) => entry.author)));
 
  return authors;
}
 
function collectExplicitAttributePaths(
  attributeKey: string,
  attribute: Attribute,
  result: Set<string>,
): void {
  result.add(attributeKey);
 
  function visit(prefix: string, schema: Attribute | Attribute["properties"][string]) {
    if (!schema || schema.type !== "object" || !schema.properties) {
      return;
    }
 
    for (const propertyKey of Object.keys(schema.properties)) {
      const propertyPath = `${prefix}.${propertyKey}`;
      result.add(propertyPath);
      visit(propertyPath, schema.properties[propertyKey]);
    }
  }
 
  visit(attributeKey, attribute);
}
 
export async function lintProject(
  deps: Dependencies,
  options: LintProjectOptions = {},
): Promise<LintResult> {
  const { projectConfig, datasource } = deps;
 
  const isJsonMode = options.json === true;
  const errors: LintErrorItem[] = [];
 
  function log(...args: unknown[]) {
    Iif (!isJsonMode) {
      console.log(...args);
    }
  }
 
  function getFullPathFromKey(type: LintEntityType, key: string, relative = false) {
    const fileName = `${getPathSegmentsFromKey(key, projectConfig.namespaceCharacter, type).join(
      path.sep,
    )}.${datasource.getExtension()}`;
    let fullPath = "";
 
    if (type === "attribute") {
      fullPath = path.join(projectConfig.attributesDirectoryPath, fileName);
    } else if (type === "segment") {
      fullPath = path.join(projectConfig.segmentsDirectoryPath, fileName);
    } else if (type === "feature") {
      fullPath = path.join(projectConfig.featuresDirectoryPath, fileName);
    } else if (type === "group") {
      fullPath = path.join(projectConfig.groupsDirectoryPath, fileName);
    } else if (type === "schema") {
      fullPath = path.join(projectConfig.schemasDirectoryPath, fileName);
    } else if (type === "target") {
      fullPath = path.join(projectConfig.targetsDirectoryPath, fileName);
    } else {
      fullPath = path.join(projectConfig.testsDirectoryPath, fileName);
    }
 
    Iif (relative) {
      fullPath = path.relative(process.cwd(), fullPath);
    }
 
    return fullPath;
  }
 
  function getEntityDirectoryPath(type: LintEntityType): string {
    if (type === "attribute") {
      return projectConfig.attributesDirectoryPath;
    }
    if (type === "segment") {
      return projectConfig.segmentsDirectoryPath;
    }
    if (type === "feature") {
      return projectConfig.featuresDirectoryPath;
    }
    if (type === "group") {
      return projectConfig.groupsDirectoryPath;
    }
    if (type === "schema") {
      return projectConfig.schemasDirectoryPath;
    }
    if (type === "target") {
      return projectConfig.targetsDirectoryPath;
    }
 
    return projectConfig.testsDirectoryPath;
  }
 
  async function lintReservedNamespaceCharacterInPathNames(
    entityType: LintEntityType,
    directoryPath: string,
  ) {
    if (!fs.existsSync(directoryPath)) {
      return;
    }
 
    const extension = datasource.getExtension();
    const namespaceCharacter = projectConfig.namespaceCharacter;
    const entries = fs.readdirSync(directoryPath, { withFileTypes: true });
 
    for (const entry of entries) {
      const entryPath = path.join(directoryPath, entry.name);
      const isFile = entry.isFile();
      const isDirectory = entry.isDirectory();
 
      Iif (!isDirectory && !(isFile && entry.name.endsWith(`.${extension}`))) {
        continue;
      }
 
      const nameToCheck = getReservedNameCheckValue(entityType, entry.name, isFile, extension);
 
      if (nameToCheck.includes(namespaceCharacter)) {
        await reportSimpleError({
          entityType,
          key: path.relative(getEntityDirectoryPath(entityType), entryPath),
          fullPath: entryPath,
          message: `Invalid file or directory name: "${entry.name}"`,
          detail: `Namespace character "${namespaceCharacter}" is not allowed in entity file or directory names.`,
          code: "invalid_name",
        });
      }
 
      if (isDirectory) {
        await lintReservedNamespaceCharacterInPathNames(entityType, entryPath);
      }
    }
  }
 
  async function lintReservedNamespaceCharacterInEntityPaths(entityType: LintEntityType) {
    await lintReservedNamespaceCharacterInPathNames(entityType, getEntityDirectoryPath(entityType));
  }
 
  async function printEntityHeader(entityType: LintEntityType, key: string, fullPath: string) {
    if (isJsonMode) {
      return;
    }
 
    console.log(CLI_FORMAT_BOLD_UNDERLINE, fullPath);
 
    if (options.authors) {
      const authors = await getAuthorsOfEntity(datasource, entityType, key);
      console.log(`     Authors: ${authors.join(", ")}\n`);
    }
  }
 
  function recordError(error: LintErrorItem) {
    errors.push(error);
  }
 
  async function reportSimpleError({
    entityType,
    key,
    fullPath,
    message,
    detail,
    pathParts = [],
    code,
    value,
  }: {
    entityType: LintEntityType;
    key: string;
    fullPath: string;
    message: string;
    detail?: string;
    pathParts?: (string | number)[];
    code?: string;
    value?: unknown;
  }) {
    recordError({
      filePath: path.relative(process.cwd(), fullPath),
      entityType,
      key,
      message,
      path: pathParts,
      code,
      value,
    });
 
    Iif (!isJsonMode) {
      await printEntityHeader(entityType, key, fullPath);
      console.log(CLI_FORMAT_RED, `  => Error: ${message}`);
      if (detail) {
        console.log(CLI_FORMAT_RED, `     ${detail}`);
      }
      console.log("");
    }
  }
 
  async function reportThrownError(
    entityType: LintEntityType,
    key: string,
    fullPath: string,
    error: unknown,
  ) {
    const pathFromError =
      error &&
      typeof error === "object" &&
      "featurevisorFilePath" in error &&
      typeof error.featurevisorFilePath === "string"
        ? error.featurevisorFilePath
        : undefined;
    const targetPath = pathFromError || fullPath;
    const message = error instanceof Error ? error.message : String(error);
 
    recordError({
      filePath: path.relative(process.cwd(), targetPath),
      entityType,
      key,
      message,
      path: [],
      code: error instanceof Error ? error.name : undefined,
    });
 
    Iif (!isJsonMode) {
      await printEntityHeader(entityType, key, targetPath);
      console.log("");
      console.log(error);
    }
  }
 
  async function reportZodValidationError(
    entityType: LintEntityType,
    key: string,
    fullPath: string,
    error: ZodError,
  ) {
    const issues = getLintIssuesFromZodError(error);
 
    const issuesWithTargetPath: {
      issue: (typeof issues)[0];
      targetPath: string;
      pathRelativeToFile: (string | number)[];
    }[] = [];
    for (const issue of issues) {
      const targetPath = fullPath;
      const pathRelativeToFile = issue.path;
      issuesWithTargetPath.push({ issue, targetPath, pathRelativeToFile });
 
      recordError({
        filePath: path.relative(process.cwd(), targetPath),
        entityType,
        key,
        message: issue.message,
        path: pathRelativeToFile,
        code: issue.code,
        value: issue.value,
      });
    }
 
    Iif (!isJsonMode) {
      if (entityType === "feature" && issuesWithTargetPath.length > 0) {
        const byPath = new Map<
          string,
          {
            issue: (typeof issuesWithTargetPath)[0]["issue"];
            pathRelativeToFile: (string | number)[];
          }[]
        >();
        for (const { issue, targetPath, pathRelativeToFile } of issuesWithTargetPath) {
          const pathKey = targetPath;
          if (!byPath.has(pathKey)) byPath.set(pathKey, []);
          byPath.get(pathKey)!.push({ issue, pathRelativeToFile });
        }
        for (const [targetPathKey, groupItems] of byPath) {
          await printEntityHeader(entityType, key, targetPathKey);
          for (const { issue, pathRelativeToFile } of groupItems) {
            console.log(CLI_FORMAT_RED, `  => Error: ${issue.message}`);
            console.log("     Path:", pathRelativeToFile.join("."));
            if (typeof issue.value !== "undefined" && issue.value !== "undefined") {
              console.log("     Value:", issue.value);
            }
            console.log("");
          }
        }
      } else {
        await printEntityHeader(entityType, key, fullPath);
        printZodError(error);
      }
    }
  }
 
  const keyPattern = options.keyPattern ? new RegExp(options.keyPattern) : null;
 
  Iif (keyPattern) {
    log("");
    log(`Linting only keys matching pattern: ${keyPattern}`);
    log("");
  }
 
  // List schemas and load parsed schemas for attribute and feature validation.
  const schemas = await datasource.listSchemas();
  const schemasByKey: Record<string, Schema> = {};
  for (const key of schemas) {
    try {
      schemasByKey[key] = await datasource.readSchema(key);
    } catch {
      // Schema file may be invalid; skip for cross-entity resolution and let schema linting report it.
    }
  }
 
  // lint attributes
  const attributes = await datasource.listAttributes();
  const attributeZodSchema = getAttributeZodSchema();
  const attributesByKey: Record<string, Attribute> = {};
 
  for (const key of attributes) {
    try {
      attributesByKey[key] = await datasource.readAttribute(key);
    } catch {
      // Attribute read failures are reported during attribute linting below.
    }
  }
 
  if (!options.entityType || options.entityType === "attribute") {
    await lintReservedNamespaceCharacterInEntityPaths("attribute");
 
    const filteredKeys = !keyPattern
      ? attributes
      : attributes.filter((key) => keyPattern.test(key));
 
    if (filteredKeys.length > 0) {
      log(`Linting ${filteredKeys.length} attributes...\n`);
    }
 
    for (const key of filteredKeys) {
      const fullPath = getFullPathFromKey("attribute", key);
 
      if (!isValidEntityKey(key, projectConfig.namespaceCharacter)) {
        await reportSimpleError({
          entityType: "attribute",
          key,
          fullPath,
          message: `Invalid name: "${key}"`,
          detail: ATTRIBUTE_NAME_REGEX_ERROR,
          code: "invalid_name",
        });
      }
 
      try {
        const parsed = attributesByKey[key] ?? (await datasource.readAttribute(key));
        const result = attributeZodSchema.safeParse(parsed);
 
        if (!result.success && "error" in result) {
          await reportZodValidationError("attribute", key, fullPath, result.error);
        }
      } catch (error) {
        await reportThrownError("attribute", key, fullPath, error);
      }
    }
  }
 
  const explicitAttributePaths = new Set<string>();
  for (const key of attributes) {
    const parsed = attributesByKey[key];
    Iif (!parsed) {
      continue;
    }
 
    collectExplicitAttributePaths(key, parsed, explicitAttributePaths);
  }
  const flattenedAttributes = Array.from(explicitAttributePaths);
 
  // lint segments
  const segments = await datasource.listSegments();
  const conditionsZodSchema = getConditionsZodSchema(projectConfig, attributesByKey, schemasByKey);
  const segmentZodSchema = getSegmentZodSchema(projectConfig, conditionsZodSchema);
 
  if (!options.entityType || options.entityType === "segment") {
    await lintReservedNamespaceCharacterInEntityPaths("segment");
 
    const filteredKeys = !keyPattern ? segments : segments.filter((key) => keyPattern.test(key));
 
    Eif (filteredKeys.length > 0) {
      log(`Linting ${filteredKeys.length} segments...\n`);
    }
 
    for (const key of filteredKeys) {
      const fullPath = getFullPathFromKey("segment", key);
 
      Iif (!isValidEntityKey(key, projectConfig.namespaceCharacter)) {
        await reportSimpleError({
          entityType: "segment",
          key,
          fullPath,
          message: `Invalid name: "${key}"`,
          detail: ENTITY_NAME_REGEX_ERROR,
          code: "invalid_name",
        });
      }
 
      try {
        const parsed = await datasource.readSegment(key);
        const result = segmentZodSchema.safeParse(parsed);
 
        if (!result.success && "error" in result) {
          await reportZodValidationError("segment", key, fullPath, result.error);
        }
      } catch (error) {
        await reportThrownError("segment", key, fullPath, error);
      }
    }
  }
 
  // lint features
  const features = await datasource.listFeatures();
  const featureZodSchema = getFeatureZodSchema(
    projectConfig,
    conditionsZodSchema,
    flattenedAttributes as [string, ...string[]],
    segments as [string, ...string[]],
    features as [string, ...string[]],
    schemas,
    schemasByKey,
  );
 
  if (!options.entityType || options.entityType === "feature") {
    await lintReservedNamespaceCharacterInEntityPaths("feature");
 
    const filteredKeys = !keyPattern ? features : features.filter((key) => keyPattern.test(key));
 
    if (filteredKeys.length > 0) {
      log(`Linting ${filteredKeys.length} features...\n`);
    }
 
    for (const key of filteredKeys) {
      const fullPath = getFullPathFromKey("feature", key);
 
      Iif (!isValidEntityKey(key, projectConfig.namespaceCharacter)) {
        await reportSimpleError({
          entityType: "feature",
          key,
          fullPath,
          message: `Invalid name: "${key}"`,
          detail: ENTITY_NAME_REGEX_ERROR,
          code: "invalid_name",
        });
      }
 
      let parsed;
 
      try {
        parsed = await datasource.readFeature(key);
 
        const result = featureZodSchema.safeParse(parsed);
 
        if (!result.success && "error" in result) {
          await reportZodValidationError("feature", key, fullPath, result.error);
        }
      } catch (error) {
        await reportThrownError("feature", key, fullPath, error);
      }
 
      if (parsed && parsed.required) {
        try {
          await checkForCircularDependencyInRequired(datasource, key, parsed.required);
        } catch (error) {
          await reportSimpleError({
            entityType: "feature",
            key,
            fullPath,
            message: error instanceof Error ? error.message : String(error),
            code: error instanceof Error ? error.name : "error",
          });
        }
      }
    }
  }
 
  // lint groups
  const groups = await datasource.listGroups();
  const groupZodSchema = getGroupZodSchema(projectConfig, datasource, features);
 
  if (!options.entityType || options.entityType === "group") {
    await lintReservedNamespaceCharacterInEntityPaths("group");
 
    const filteredKeys = !keyPattern ? groups : groups.filter((key) => keyPattern.test(key));
 
    if (filteredKeys.length > 0) {
      log(`Linting ${filteredKeys.length} groups...\n`);
    }
 
    for (const key of filteredKeys) {
      const fullPath = getFullPathFromKey("group", key);
 
      Iif (!isValidEntityKey(key, projectConfig.namespaceCharacter)) {
        await reportSimpleError({
          entityType: "group",
          key,
          fullPath,
          message: `Invalid name: "${key}"`,
          detail: ENTITY_NAME_REGEX_ERROR,
          code: "invalid_name",
        });
      }
 
      let parsed;
 
      try {
        parsed = await datasource.readGroup(key);
 
        const result = groupZodSchema.safeParse(parsed);
 
        Iif (!result.success && "error" in result) {
          await reportZodValidationError("group", key, fullPath, result.error);
        }
      } catch (error) {
        await reportThrownError("group", key, fullPath, error);
      }
 
      Eif (parsed) {
        try {
          await checkForFeatureExceedingGroupSlotPercentage(datasource, parsed, features);
        } catch (error) {
          await reportSimpleError({
            entityType: "group",
            key,
            fullPath,
            message: error instanceof Error ? error.message : String(error),
            code: error instanceof Error ? error.name : "error",
          });
        }
      }
    }
  }
 
  // @TODO: feature cannot exist in multiple groups
 
  // lint schemas (schemas and schemasByKey already loaded above for feature linting)
  const schemaZodSchema = getSchemaZodSchema(schemas);
 
  if (!options.entityType || options.entityType === "schema") {
    await lintReservedNamespaceCharacterInEntityPaths("schema");
 
    const filteredKeys = !keyPattern ? schemas : schemas.filter((key) => keyPattern.test(key));
 
    if (filteredKeys.length > 0) {
      log(`Linting ${filteredKeys.length} schemas...\n`);
    }
 
    for (const key of filteredKeys) {
      const fullPath = getFullPathFromKey("schema", key);
 
      Iif (!isValidEntityKey(key, projectConfig.namespaceCharacter)) {
        await reportSimpleError({
          entityType: "schema",
          key,
          fullPath,
          message: `Invalid name: "${key}"`,
          detail: ENTITY_NAME_REGEX_ERROR,
          code: "invalid_name",
        });
      }
 
      try {
        const parsed = await datasource.readSchema(key);
 
        const result = schemaZodSchema.safeParse(parsed);
 
        Iif (!result.success && "error" in result) {
          await reportZodValidationError("schema", key, fullPath, result.error);
        }
      } catch (error) {
        await reportThrownError("schema", key, fullPath, error);
      }
    }
  }
 
  // lint targets
  const targets = await datasource.listTargets();
  const targetZodSchema = getTargetZodSchema(projectConfig);
 
  if (!options.entityType || options.entityType === "target") {
    await lintReservedNamespaceCharacterInEntityPaths("target");
 
    const filteredKeys = !keyPattern ? targets : targets.filter((key) => keyPattern.test(key));
 
    if (filteredKeys.length > 0) {
      log(`Linting ${filteredKeys.length} targets...\n`);
    }
 
    for (const key of filteredKeys) {
      const fullPath = getFullPathFromKey("target", key);
 
      Iif (!isValidEntityKey(key, projectConfig.namespaceCharacter)) {
        await reportSimpleError({
          entityType: "target",
          key,
          fullPath,
          message: `Invalid name: "${key}"`,
          detail: ENTITY_NAME_REGEX_ERROR,
          code: "invalid_name",
        });
      }
 
      try {
        const parsed = await datasource.readTarget(key);
 
        const result = targetZodSchema.safeParse(parsed);
 
        Iif (!result.success && "error" in result) {
          await reportZodValidationError("target", key, fullPath, result.error);
        }
      } catch (error) {
        await reportThrownError("target", key, fullPath, error);
      }
    }
  }
 
  // lint tests
  const tests = await datasource.listTests();
 
  const testsZodSchema = getTestsZodSchema(
    projectConfig,
    features as [string, ...string[]],
    segments as [string, ...string[]],
    targets as [string, ...string[]],
  );
 
  if (!options.entityType || options.entityType === "test") {
    await lintReservedNamespaceCharacterInEntityPaths("test");
 
    const filteredKeys = !keyPattern ? tests : tests.filter((key) => keyPattern.test(key));
 
    if (filteredKeys.length > 0) {
      log(`Linting ${filteredKeys.length} tests...\n`);
    }
 
    for (const key of filteredKeys) {
      const fullPath = getFullPathFromKey("test", key);
 
      Iif (!isValidEntityKey(key, projectConfig.namespaceCharacter)) {
        await reportSimpleError({
          entityType: "test",
          key,
          fullPath,
          message: `Invalid name: "${key}"`,
          detail: ENTITY_NAME_REGEX_ERROR,
          code: "invalid_name",
        });
      }
 
      try {
        const parsed = await datasource.readTest(key);
 
        const result = testsZodSchema.safeParse(parsed);
 
        if (!result.success && "error" in result) {
          await reportZodValidationError("test", key, fullPath, result.error);
        }
      } catch (error) {
        await reportThrownError("test", key, fullPath, error);
      }
    }
  }
 
  return {
    hasError: errors.length > 0,
    errors,
  };
}
 
export const lintPlugin: Plugin = {
  command: "lint",
  handler: async function (options) {
    const { rootDirectoryPath, projectConfig, datasource, parsed } = options;
 
    assertProjectSetJsonSelection(projectConfig, parsed.set, parsed.json);
 
    const executions = await getProjectSetExecutions(projectConfig, datasource, parsed.set);
    let hasError = false;
 
    for (const execution of executions) {
      printSetHeader(projectConfig, execution.set, parsed.json);
 
      const result = await lintProject(
        {
          rootDirectoryPath,
          projectConfig: execution.projectConfig,
          datasource: execution.datasource,
          options: parsed,
        },
        {
          keyPattern: parsed.keyPattern,
          entityType: parsed.entityType,
          authors: parsed.authors,
          json: parsed.json,
          pretty: parsed.pretty,
        },
      );
 
      Eif (parsed.json) {
        const payload = { errors: result.errors };
        console.log(parsed.pretty ? JSON.stringify(payload, null, 2) : JSON.stringify(payload));
      }
 
      Iif (result.hasError) {
        hasError = true;
      }
    }
 
    Iif (hasError) {
      return false;
    }
 
    Iif (!parsed.json) {
      console.log("");
      console.log(CLI_FORMAT_GREEN, "✔ No lint errors found");
    }
  },
  examples: [
    {
      command: "lint",
      description: "lint all entities",
    },
    {
      command: "lint --entityType=feature",
      description: "lint only features",
    },
    {
      command: "lint --entityType=segment",
      description: "lint only segments",
    },
    {
      command: "lint --entityType=group",
      description: "lint only groups",
    },
    {
      command: "lint --entityType=schema",
      description: "lint only schemas",
    },
    {
      command: "lint --entityType=test",
      description: "lint only tests",
    },
    {
      command: 'lint --keyPattern="abc"',
      description: `lint only entities with keys containing "abc"`,
    },
    {
      command: "lint --json",
      description: "print lint errors as JSON",
    },
    {
      command: "lint --json --pretty",
      description: "print lint errors as pretty JSON",
    },
  ],
};