All files / generate-code typescript.ts

88.12% Statements 334/379
79.92% Branches 219/274
91.11% Functions 41/45
90.02% Lines 325/361

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 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 9741x 1x                                   41x   9x   25x   4x   3x                                 37x 37x       354x               86x 86x 86x 86x   86x                                         86x 81x 81x   156x 156x 156x         81x     5x 2x         2x     3x       30x 25x     60x             436x     436x         26x 26x 1x             8x 8x 8x 20x 20x 20x   8x                           390x 11x   379x 379x 4x 8x   4x   375x   375x     375x 375x     375x   34x     156x         58x   41x 37x 37x   4x   86x                           279x 24x   255x                                           109x 109x 109x   109x 29x       109x           24x 24x 24x   24x         24x   24x   24x 24x 3x 3x 1x 1x   2x     24x                   85x 85x 85x   85x 1x       84x     84x 1x 2x   1x 1x 20x     1x 1x                   83x   25x     25x 25x 25x       23x 23x   45x 45x 45x 900x   45x 45x         23x 2x         2x 2x 40x   2x     2x 2x   23x     23x   2x 2x     58x 15x 15x   12x           12x 2x 2x 2x             10x 10x         4x 4x   9x 9x 9x 180x   9x 9x         4x     4x             6x 6x 6x 120x   6x 6x             3x 3x                     43x       43x     43x   43x   43x 43x 43x                     536x     537x   536x       34x   34x       34x       27x 15x     12x 26x     12x               109x 109x 28x 28x       109x           24x 24x 24x     85x 85x       85x 1x     84x   84x 84x 1680x 4x         84x                   1x 1x 20x   1x 1x 20x 20x 20x 20x 20x   1x             1x   1x 17x 340x           1x 1x 17x 17x     1x       1x 1x   1x                           1x         1x 1x         1x 1x   1x     1x 1x 1x 20x 20x         1x 1x 1x 1x 1x 1x 1x         1x 1x 20x       1x 1x 1x     1x 1x 1x   1x 17x   17x       17x           17x         17x     1x       1x 1x 1x         1x 1x   17x     1x               1x 1x 1x         1x           1x   1x 27x   27x       27x               27x 27x     1x 1x 1x 27x   27x 27x 27x   27x 14x 14x   14x 109x 109x 109x               109x           109x 109x   109x         109x 109x 109x 3x         106x 1x         105x 55x           50x               14x 13x       27x   27x                               27x 27x 27x                 1x 1x   27x 27x   27x 12x     27x 14x 109x         109x 109x       27x 12x     15x       1x         1x                               1x 1x 1x   1x                                               1x 1x 1x       1x                                                                         1x                 27x     1x 1x 1x    
import * as fs from "fs";
import * as path from "path";
 
import type {
  Attribute,
  ParsedFeature,
  Schema,
  VariableSchema,
  VariableSchemaWithInline,
} from "@featurevisor/types";
import { Dependencies } from "../dependencies";
 
export interface TypeScriptGenerationOptions {
  tag?: string | string[];
  react?: boolean;
  individualFeatures?: boolean;
}
 
function convertFeaturevisorTypeToTypeScriptType(featurevisorType: string): string {
  switch (featurevisorType) {
    case "boolean":
      return "boolean";
    case "string":
      return "string";
    case "integer":
      return "number";
    case "double":
      return "number";
    case "date":
      return "Date | string";
    case "semver":
      return "string";
    case "array":
      return "string[]";
    case "object":
      return "Record<string, unknown>";
    case "json":
      return "unknown";
    default:
      throw new Error(`Unknown type: ${featurevisorType}`);
  }
}
 
function shouldWrapArrayItemType(typeName: string): boolean {
  const trimmed = typeName.trim();
  return trimmed.includes("|") || trimmed.includes("&");
}
 
function formatObjectKey(key: string): string {
  return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
}
 
function buildObjectTypeFromSchema(
  schema: Schema,
  schemasByKey: Record<string, Schema>,
  schemaTypeNames?: Record<string, string>,
): string {
  const props = schema.properties;
  const additional = schema.additionalProperties;
  const hasProps = props && typeof props === "object" && Object.keys(props).length > 0;
  const hasAdditional = additional && typeof additional === "object";
 
  Iif (hasProps && hasAdditional) {
    const requiredSet = new Set(schema.required || []);
    const propEntries = Object.entries(props as Record<string, Schema>).map(([k, v]) => {
      const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
      const optional = !requiredSet.has(k);
      return optional
        ? `${formatObjectKey(k)}?: ${propType}`
        : `${formatObjectKey(k)}: ${propType}`;
    });
    const propUnion = Object.entries(props as Record<string, Schema>)
      .map(([, v]) => schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames))
      .join(" | ");
    const additionalType = schemaToTypeScriptType(
      additional as Schema,
      schemasByKey,
      schemaTypeNames,
    );
    const indexType = [additionalType, propUnion].filter(Boolean).join(" | ");
    return `{ ${propEntries.join("; ")}; [key: string]: ${indexType} }`;
  }
 
  if (hasProps) {
    const requiredSet = new Set(schema.required || []);
    const entries = Object.entries(props as Record<string, Schema>)
      .map(([k, v]) => {
        const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
        const optional = !requiredSet.has(k);
        return optional
          ? `${formatObjectKey(k)}?: ${propType}`
          : `${formatObjectKey(k)}: ${propType}`;
      })
      .join("; ");
    return `{ ${entries} }`;
  }
 
  if (hasAdditional) {
    const additionalType = schemaToTypeScriptType(
      additional as Schema,
      schemasByKey,
      schemaTypeNames,
    );
    return `Record<string, ${additionalType}>`;
  }
 
  return "Record<string, unknown>";
}
 
function formatTypeImport(typeNames: string[], fromPath: string): string {
  if (typeNames.length === 0) {
    return "";
  }
 
  return `import type {\n${typeNames.map((name) => `  ${name},`).join("\n")}\n} from "${fromPath}";\n\n`;
}
 
/**
 * Resolve a schema to its full definition, following schema references (schema: key).
 */
function resolveSchema(schema: Schema, schemasByKey: Record<string, Schema>): Schema {
  Iif (schema.schema && schemasByKey[schema.schema]) {
    return resolveSchema(schemasByKey[schema.schema], schemasByKey);
  }
  return schema;
}
 
/** Emit a TypeScript literal type for a primitive const value, or null if not a primitive. */
function constToLiteralType(constVal: unknown): string | null {
  Iif (constVal === null || constVal === undefined) return null;
  if (typeof constVal === "string") return JSON.stringify(constVal);
  if (typeof constVal === "number") return String(constVal);
  Iif (typeof constVal === "boolean") return constVal ? "true" : "false";
  return null;
}
 
/** Emit a TypeScript union of literal types for an enum array (primitives only), or null. */
function enumToUnionType(enumArr: unknown[]): string | null {
  Iif (enumArr.length === 0) return null;
  const literals: string[] = [];
  for (const v of enumArr) {
    const lit = constToLiteralType(v);
    Iif (lit === null) return null;
    literals.push(lit);
  }
  return literals.join(" | ");
}
 
/**
 * Converts a Schema (items or properties entry) to a TypeScript type string.
 * Handles nested object/array and resolves schema references recursively.
 * When schema has `oneOf`, emits a union of each branch type. When schema has primitive `const` or `enum`, emits a literal or union type.
 * When schemaTypeNames is provided and schema is a reference (schema: key), returns that type name instead of inlining.
 */
function schemaToTypeScriptType(
  schema: Schema,
  schemasByKey: Record<string, Schema>,
  schemaTypeNames?: Record<string, string>,
): string {
  if (schema?.schema && schemaTypeNames?.[schema.schema]) {
    return schemaTypeNames[schema.schema];
  }
  const resolved = resolveSchema(schema, schemasByKey);
  if (resolved.oneOf && Array.isArray(resolved.oneOf) && resolved.oneOf.length > 0) {
    const parts = resolved.oneOf.map((branch) =>
      schemaToTypeScriptType(branch as Schema, schemasByKey, schemaTypeNames),
    );
    return parts.join(" | ");
  }
  const literalFromConst = resolved.const !== undefined ? constToLiteralType(resolved.const) : null;
  const unionFromEnum =
    resolved.enum && Array.isArray(resolved.enum) && resolved.enum.length > 0
      ? enumToUnionType(resolved.enum)
      : null;
  const type = resolved.type as string | undefined;
  Iif (!type) {
    return literalFromConst ?? unionFromEnum ?? "unknown";
  }
  switch (type) {
    case "boolean":
      return literalFromConst ?? unionFromEnum ?? "boolean";
    case "string":
    case "semver":
      return literalFromConst ?? unionFromEnum ?? "string";
    case "date":
      return literalFromConst ?? unionFromEnum ?? "Date | string";
    case "integer":
    case "double":
      return literalFromConst ?? unionFromEnum ?? "number";
    case "array":
      if (resolved.items) {
        const itemType = schemaToTypeScriptType(resolved.items, schemasByKey, schemaTypeNames);
        return shouldWrapArrayItemType(itemType) ? `(${itemType})[]` : `${itemType}[]`;
      }
      return "string[]";
    case "object": {
      return buildObjectTypeFromSchema(resolved, schemasByKey, schemaTypeNames);
    }
    default:
      return "unknown";
  }
}
 
/**
 * Resolve variable schema to the schema shape used for code gen (inline or from schema reference).
 */
function getEffectiveVariableSchema(
  variableSchema: VariableSchema,
  schemasByKey: Record<string, Schema>,
): VariableSchemaWithInline | Schema | undefined {
  if ("schema" in variableSchema && variableSchema.schema) {
    return schemasByKey[variableSchema.schema];
  }
  return variableSchema as VariableSchemaWithInline;
}
 
/**
 * Generates TypeScript type/interface declarations and metadata for a variable.
 * Returns declarations to emit (interface or type alias) plus the type name and generic to use in the getter.
 * When isLiteralType is true, the getter return must be asserted so the SDK's primitive return type matches the literal.
 * When schemaTypeNames is provided, direct schema refs and schema refs in array items use those type names and schemaTypesUsed is populated.
 */
function generateVariableTypeDeclarations(
  variableKey: string,
  variableSchema: VariableSchema,
  schemasByKey: Record<string, Schema>,
  schemaTypeNames?: Record<string, string>,
): {
  declarations: string[];
  returnTypeName: string;
  genericArg: string;
  isLiteralType?: boolean;
  useGetVariable?: boolean;
  schemaTypesUsed: string[];
} {
  const typeName = getPascalCase(variableKey) + "Variable";
  const itemTypeName = getPascalCase(variableKey) + "VariableItem";
  const schemaTypesUsed: string[] = [];
 
  const addSchemaUsed = (name: string) => {
    if (name && !schemaTypesUsed.includes(name)) schemaTypesUsed.push(name);
  };
 
  // Direct schema reference: emit type alias to schema type and reuse it
  if (
    schemaTypeNames &&
    "schema" in variableSchema &&
    variableSchema.schema &&
    schemasByKey[variableSchema.schema]
  ) {
    const schemaKey = variableSchema.schema;
    const schemaTypeName = schemaTypeNames[schemaKey];
    const resolvedSchema = resolveSchema(schemasByKey[schemaKey], schemasByKey);
    const isOneOf =
      resolvedSchema.oneOf &&
      Array.isArray(resolvedSchema.oneOf) &&
      resolvedSchema.oneOf.length > 0 &&
      !resolvedSchema.type;
    const isLiteralSchema =
      resolvedSchema.const !== undefined ||
      (resolvedSchema.enum && Array.isArray(resolvedSchema.enum) && resolvedSchema.enum.length > 0);
    addSchemaUsed(schemaTypeName);
    // getVariableArray<T> expects T to be the element type, not the full array type
    let genericArg = schemaTypeName;
    if (resolvedSchema.type === "array" && resolvedSchema.items) {
      const itemsSchema = resolvedSchema.items as Schema;
      if ("schema" in itemsSchema && itemsSchema.schema && schemaTypeNames[itemsSchema.schema]) {
        genericArg = schemaTypeNames[itemsSchema.schema];
        addSchemaUsed(genericArg);
      } else {
        genericArg = schemaToTypeScriptType(itemsSchema, schemasByKey, schemaTypeNames);
      }
    }
    return {
      declarations: [`${INDENT_NS}export type ${typeName} = ${schemaTypeName};`],
      returnTypeName: schemaTypeName,
      genericArg,
      useGetVariable: isOneOf,
      isLiteralType: isOneOf || isLiteralSchema,
      schemaTypesUsed,
    };
  }
 
  const effective = getEffectiveVariableSchema(variableSchema, schemasByKey);
  const type = effective?.type;
  const declarations: string[] = [];
 
  if (type === "json") {
    return { declarations: [], returnTypeName: "T", genericArg: "T", schemaTypesUsed };
  }
 
  const effectiveOneOf =
    effective && "oneOf" in effective && Array.isArray((effective as Schema).oneOf)
      ? (effective as Schema).oneOf
      : undefined;
  if (effectiveOneOf && effectiveOneOf.length > 0 && !type) {
    const unionType = effectiveOneOf
      .map((branch) => schemaToTypeScriptType(branch as Schema, schemasByKey, schemaTypeNames))
      .join(" | ");
    if (schemaTypeNames) {
      Object.values(schemaTypeNames).forEach((n) => {
        Iif (unionType.includes(n)) addSchemaUsed(n);
      });
    }
    declarations.push(`${INDENT_NS}export type ${typeName} = ${unionType};`);
    return {
      declarations,
      returnTypeName: typeName,
      genericArg: typeName,
      isLiteralType: true,
      useGetVariable: true,
      schemaTypesUsed,
    };
  }
 
  if (type === "object") {
    const resolvedEffective =
      effective && ("properties" in effective || "additionalProperties" in effective)
        ? (resolveSchema(effective as Schema, schemasByKey) as Schema)
        : undefined;
    const props = resolvedEffective?.properties;
    const additional = resolvedEffective?.additionalProperties;
    if (
      (props && typeof props === "object" && Object.keys(props).length > 0) ||
      (additional && typeof additional === "object")
    ) {
      const requiredSet = new Set(resolvedEffective?.required || []);
      const entries = Object.entries(props ?? {})
        .map(([k, v]) => {
          const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
          if (schemaTypeNames)
            Object.values(schemaTypeNames).forEach((n) => {
              if (propType.includes(n)) addSchemaUsed(n);
            });
          const optional = !requiredSet.has(k);
          return optional
            ? `${INDENT_NS_BODY}${formatObjectKey(k)}?: ${propType};`
            : `${INDENT_NS_BODY}${formatObjectKey(k)}: ${propType};`;
        })
        .filter(Boolean);
      if (additional && typeof additional === "object") {
        const additionalType = schemaToTypeScriptType(
          additional as Schema,
          schemasByKey,
          schemaTypeNames,
        );
        if (schemaTypeNames)
          Object.values(schemaTypeNames).forEach((n) => {
            if (additionalType.includes(n)) addSchemaUsed(n);
          });
        const propUnion = Object.entries(props ?? {})
          .map(([, v]) => schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames))
          .join(" | ");
        const indexType = [additionalType, propUnion].filter(Boolean).join(" | ");
        entries.push(`${INDENT_NS_BODY}[key: string]: ${indexType};`);
      }
      declarations.push(
        `${INDENT_NS}export interface ${typeName} {\n${entries.join("\n")}\n${INDENT_NS}}`,
      );
      return { declarations, returnTypeName: typeName, genericArg: typeName, schemaTypesUsed };
    }
    declarations.push(`${INDENT_NS}export type ${typeName} = Record<string, unknown>;`);
    return { declarations, returnTypeName: typeName, genericArg: typeName, schemaTypesUsed };
  }
 
  if (type === "array") {
    const itemsSchema = effective && "items" in effective ? (effective.items as Schema) : undefined;
    if (itemsSchema) {
      const itemsRef =
        schemaTypeNames &&
        "schema" in itemsSchema &&
        itemsSchema.schema &&
        schemasByKey[itemsSchema.schema]
          ? schemaTypeNames[itemsSchema.schema]
          : null;
      if (itemsRef) {
        addSchemaUsed(itemsRef);
        declarations.push(`${INDENT_NS}export type ${itemTypeName} = ${itemsRef};`);
        return {
          declarations,
          returnTypeName: `${itemTypeName}[]`,
          genericArg: itemTypeName,
          schemaTypesUsed,
        };
      }
      const resolvedItems = resolveSchema(itemsSchema, schemasByKey);
      if (
        resolvedItems.type === "object" &&
        resolvedItems.properties &&
        Object.keys(resolvedItems.properties).length > 0
      ) {
        const requiredSet = new Set(resolvedItems.required || []);
        const entries = Object.entries(resolvedItems.properties)
          .map(([k, v]) => {
            const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
            if (schemaTypeNames)
              Object.values(schemaTypeNames).forEach((n) => {
                Iif (propType.includes(n)) addSchemaUsed(n);
              });
            const optional = !requiredSet.has(k);
            return optional
              ? `${INDENT_NS_BODY}${k}?: ${propType};`
              : `${INDENT_NS_BODY}${k}: ${propType};`;
          })
          .join("\n");
        declarations.push(
          `${INDENT_NS}export interface ${itemTypeName} {\n${entries}\n${INDENT_NS}}`,
        );
        return {
          declarations,
          returnTypeName: `${itemTypeName}[]`,
          genericArg: itemTypeName,
          schemaTypesUsed,
        };
      }
      const itemType = schemaToTypeScriptType(resolvedItems, schemasByKey, schemaTypeNames);
      if (schemaTypeNames)
        Object.values(schemaTypeNames).forEach((n) => {
          Iif (itemType.includes(n)) addSchemaUsed(n);
        });
      declarations.push(`${INDENT_NS}export type ${itemTypeName} = ${itemType};`);
      return {
        declarations,
        returnTypeName: `${itemTypeName}[]`,
        genericArg: itemTypeName,
        schemaTypesUsed,
      };
    }
    declarations.push(`${INDENT_NS}export type ${itemTypeName} = string;`);
    return {
      declarations,
      returnTypeName: `${itemTypeName}[]`,
      genericArg: itemTypeName,
      schemaTypesUsed,
    };
  }
 
  // primitive: boolean, string, integer, double (or unknown when schema ref unresolved)
  // When schema has primitive const or enum, emit literal or union type
  const effectiveConst =
    effective && "const" in effective && (effective as Schema).const !== undefined
      ? (effective as Schema).const
      : undefined;
  const effectiveEnum =
    effective && "enum" in effective && Array.isArray((effective as Schema).enum)
      ? (effective as Schema).enum
      : undefined;
  const literalType = effectiveConst !== undefined ? constToLiteralType(effectiveConst) : null;
  const enumUnion =
    effectiveEnum && effectiveEnum.length > 0 ? enumToUnionType(effectiveEnum) : null;
  const primitiveType =
    literalType ?? enumUnion ?? (type ? convertFeaturevisorTypeToTypeScriptType(type) : "unknown");
  declarations.push(`${INDENT_NS}export type ${typeName} = ${primitiveType};`);
  return {
    declarations,
    returnTypeName: typeName,
    genericArg: typeName,
    isLiteralType: literalType !== null || enumUnion !== null,
    schemaTypesUsed,
  };
}
 
function getPascalCase(str) {
  // Remove special characters and split the string into an array of words
  const words = str.replace(/[^a-zA-Z0-9]/g, " ").split(" ");
 
  // Capitalize the first letter of each word and join them together
  const pascalCased = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
 
  return pascalCased;
}
 
function getRelativePath(from, to) {
  const relativePath = path.relative(from, to);
 
  Iif (relativePath.startsWith("..")) {
    return path.join(".", relativePath);
  }
 
  return relativePath;
}
 
function getVariationUnionFromFeature(parsedFeature: ParsedFeature): string | null {
  if (!parsedFeature.variations || parsedFeature.variations.length === 0) {
    return null;
  }
 
  const values = Array.from(
    new Set(parsedFeature.variations.map((variation) => JSON.stringify(variation.value))),
  );
 
  return values.length > 0 ? values.join(" | ") : null;
}
 
function getVariableTypeForFeaturesMap(
  variableSchema: VariableSchema,
  schemasByKey: Record<string, Schema>,
  schemaTypeNames?: Record<string, string>,
): { typeName: string; schemaTypesUsed: string[] } {
  const schemaTypesUsed: string[] = [];
  const addSchemaUsed = (name: string) => {
    if (name && !schemaTypesUsed.includes(name)) {
      schemaTypesUsed.push(name);
    }
  };
 
  if (
    schemaTypeNames &&
    "schema" in variableSchema &&
    variableSchema.schema &&
    schemasByKey[variableSchema.schema]
  ) {
    const schemaTypeName = schemaTypeNames[variableSchema.schema];
    addSchemaUsed(schemaTypeName);
    return { typeName: schemaTypeName, schemaTypesUsed };
  }
 
  const effective = getEffectiveVariableSchema(variableSchema, schemasByKey);
  Iif (!effective) {
    return { typeName: "unknown", schemaTypesUsed };
  }
 
  if ("type" in effective && effective.type === "json") {
    return { typeName: "unknown", schemaTypesUsed };
  }
 
  const typeName = schemaToTypeScriptType(effective as Schema, schemasByKey, schemaTypeNames);
 
  if (schemaTypeNames) {
    Object.values(schemaTypeNames).forEach((name) => {
      if (typeName.includes(name)) {
        addSchemaUsed(name);
      }
    });
  }
 
  return { typeName, schemaTypesUsed };
}
 
/**
 * Generates the content of Schemas.ts: one exported type per schema key, using schema refs between schemas.
 */
function generateSchemasFileContent(
  schemaKeys: string[],
  schemasByKey: Record<string, Schema>,
): string {
  const schemaTypeNames: Record<string, string> = {};
  for (const k of schemaKeys) {
    schemaTypeNames[k] = getPascalCase(k) + "Schema";
  }
  const lines: string[] = [];
  for (const key of schemaKeys) {
    const schema = schemasByKey[key];
    Iif (!schema) continue;
    const name = schemaTypeNames[key];
    const typeStr = schemaToTypeScriptType(schema, schemasByKey, schemaTypeNames);
    lines.push(`export type ${name} = ${typeStr};`);
  }
  return lines.join("\n") + "\n";
}
 
function generateAttributesFileContent(
  attributes: Array<Attribute & { key: string; typescriptType: string }>,
  schemaTypeNames: Record<string, string>,
): string {
  const schemaTypesUsed = new Set<string>();
 
  for (const attribute of attributes) {
    Object.values(schemaTypeNames).forEach((typeName) => {
      Iif (attribute.typescriptType.includes(typeName)) {
        schemaTypesUsed.add(typeName);
      }
    });
  }
 
  const importLine = formatTypeImport(Array.from(schemaTypesUsed).sort(), "./schemas");
  const lines = attributes.map((attribute) => {
    const typeName = `${getPascalCase(attribute.key)}Attribute`;
    return `export type ${typeName} = ${attribute.typescriptType};`;
  });
 
  return `${importLine}${lines.join("\n")}\n`;
}
 
// Indentation for generated namespace content (2 spaces per level)
const INDENT_NS = "  ";
const INDENT_NS_BODY = "    ";
 
const instanceSnippet = `
import { FeaturevisorInstance } from "@featurevisor/sdk";
 
let _instance: FeaturevisorInstance;
 
export function setInstance(instance: FeaturevisorInstance) {
  _instance = instance;
}
 
export function getInstance(): FeaturevisorInstance {
  return _instance as FeaturevisorInstance;
}
`.trimStart();
 
export async function generateTypeScriptCodeForProject(
  deps: Dependencies,
  outputPath: string,
  options: TypeScriptGenerationOptions = {},
) {
  const { rootDirectoryPath, datasource } = deps;
  const selectedTags = options.tag
    ? Array.isArray(options.tag)
      ? options.tag
      : [options.tag]
    : [];
  const shouldGenerateReact = Boolean(options.react);
  const shouldGenerateIndividualFeatures = options.individualFeatures !== false;
 
  console.log("\nGenerating TypeScript code...\n");
 
  // Load schemas for resolving variable schema references
  const schemaListKeys = await datasource.listSchemas();
  const schemasByKey: Record<string, Schema> = {};
  for (const key of schemaListKeys) {
    try {
      schemasByKey[key] = await datasource.readSchema(key);
    } catch {
      // Schema file may be invalid; skip for code gen
    }
  }
  const schemaKeys = Object.keys(schemasByKey);
  const hasSchemasFile = schemaKeys.length > 0;
  if (hasSchemasFile) {
    const schemasContent = generateSchemasFileContent(schemaKeys, schemasByKey);
    const schemasFilePath = path.join(outputPath, "schemas.ts");
    fs.writeFileSync(schemasFilePath, schemasContent);
    console.log(
      `Schemas type file written at: ${getRelativePath(rootDirectoryPath, schemasFilePath)}`,
    );
  }
 
  const schemaTypeNames: Record<string, string> = {};
  for (const k of schemaKeys) {
    schemaTypeNames[k] = getPascalCase(k) + "Schema";
  }
 
  // instance
  const instanceFilePath = path.join(outputPath, "instance.ts");
  fs.writeFileSync(instanceFilePath, instanceSnippet);
  console.log(`Instance file written at: ${getRelativePath(rootDirectoryPath, instanceFilePath)}`);
 
  // attributes
  const attributeFiles = await datasource.listAttributes();
  const attributes: (Attribute & { typescriptType: string })[] = [];
  const attributeTypeNames: Record<string, string> = {};
 
  for (const attributeKey of attributeFiles) {
    const parsedAttribute = await datasource.readAttribute(attributeKey);
 
    Iif (parsedAttribute.archived) {
      continue;
    }
 
    const typescriptType = schemaToTypeScriptType(
      parsedAttribute as Schema,
      schemasByKey,
      hasSchemasFile ? schemaTypeNames : undefined,
    );
 
    attributes.push({
      ...parsedAttribute,
      key: attributeKey,
      typescriptType,
    });
    attributeTypeNames[attributeKey] = `${getPascalCase(attributeKey)}Attribute`;
  }
 
  const attributesFileContent = generateAttributesFileContent(
    attributes as Array<Attribute & { key: string; typescriptType: string }>,
    hasSchemasFile ? schemaTypeNames : {},
  );
  const attributesFilePath = path.join(outputPath, "attributes.ts");
  fs.writeFileSync(attributesFilePath, attributesFileContent);
  console.log(
    `Attributes type file written at: ${getRelativePath(rootDirectoryPath, attributesFilePath)}`,
  );
 
  // context
  const contextImport = formatTypeImport(Object.values(attributeTypeNames).sort(), "./attributes");
  const attributeProperties = attributes
    .map((attribute) => {
      return `  ${formatObjectKey(attribute.key)}?: ${attributeTypeNames[attribute.key]};`;
    })
    .join("\n");
  const contextContent = `
import type { AttributeKey, AttributeValue } from "@featurevisor/sdk";
${contextImport}export interface Context {
${attributeProperties}
  [key: AttributeKey]: AttributeValue;
}
`.trimStart();
 
  const contextTypeFilePath = path.join(outputPath, "context.ts");
  fs.writeFileSync(contextTypeFilePath, contextContent);
  console.log(
    `Context type file written at: ${getRelativePath(rootDirectoryPath, contextTypeFilePath)}`,
  );
 
  // features
  const featureFiles = await datasource.listFeatures();
 
  const parsedFeatures: {
    featureKey: string;
    parsedFeature: ParsedFeature;
    namespaceValue: string;
  }[] = [];
 
  for (const featureKey of featureFiles) {
    const parsedFeature = (await datasource.readFeature(featureKey)) as ParsedFeature;
 
    Iif (typeof parsedFeature.archived !== "undefined" && parsedFeature.archived) {
      continue;
    }
 
    Iif (selectedTags.length > 0) {
      const featureTags = Array.isArray(parsedFeature.tags) ? parsedFeature.tags : [];
      const hasTags = selectedTags.every((tag) => featureTags.includes(tag));
      Iif (!hasTags) {
        continue;
      }
    }
 
    const namespaceValue = getPascalCase(featureKey) + "Feature";
    parsedFeatures.push({ featureKey, parsedFeature, namespaceValue });
  }
 
  const featureNamespaces: string[] = [];
  if (shouldGenerateIndividualFeatures) {
    for (const { featureKey, parsedFeature, namespaceValue } of parsedFeatures) {
      featureNamespaces.push(namespaceValue);
 
      let variableTypeDeclarations = "";
      let variableMethods = "";
      const featureSchemaTypesUsed = new Set<string>();
 
      if (parsedFeature.variablesSchema) {
        const variableKeys = Object.keys(parsedFeature.variablesSchema);
        const allDeclarations: string[] = [];
 
        for (const variableKey of variableKeys) {
          const variableSchema = parsedFeature.variablesSchema[variableKey];
          const effective = getEffectiveVariableSchema(variableSchema, schemasByKey);
          const variableType = effective?.type;
          const {
            declarations,
            returnTypeName,
            genericArg,
            isLiteralType,
            useGetVariable,
            schemaTypesUsed,
          } = generateVariableTypeDeclarations(
            variableKey,
            variableSchema,
            schemasByKey,
            hasSchemasFile ? schemaTypeNames : undefined,
          );
          schemaTypesUsed.forEach((t) => featureSchemaTypesUsed.add(t));
          allDeclarations.push(...declarations);
 
          const internalMethodName = `getVariable${
            variableType === "json" ? "JSON" : getPascalCase(variableType ?? "string")
          }`;
 
          const hasGeneric =
            variableType === "json" || variableType === "array" || variableType === "object";
          const literalAssertion = isLiteralType ? ` as ${returnTypeName} | null` : "";
          if (useGetVariable) {
            variableMethods += `
 
${INDENT_NS}export function get${getPascalCase(variableKey)}(context: Context = {}): ${returnTypeName} | null {
${INDENT_NS_BODY}return getInstance().getVariable(key, "${variableKey}", context)${literalAssertion};
${INDENT_NS}}`;
          } else if (variableType === "json") {
            variableMethods += `
 
${INDENT_NS}export function get${getPascalCase(variableKey)}<T = unknown>(context: Context = {}): T | null {
${INDENT_NS_BODY}return getInstance().${internalMethodName}<T>(key, "${variableKey}", context);
${INDENT_NS}}`;
          } else if (hasGeneric) {
            variableMethods += `
 
${INDENT_NS}export function get${getPascalCase(variableKey)}(context: Context = {}): ${returnTypeName} | null {
${INDENT_NS_BODY}return getInstance().${internalMethodName}<${genericArg}>(key, "${variableKey}", context);
${INDENT_NS}}`;
          } else {
            variableMethods += `
 
${INDENT_NS}export function get${getPascalCase(variableKey)}(context: Context = {}): ${returnTypeName} | null {
${INDENT_NS_BODY}return getInstance().${internalMethodName}(key, "${variableKey}", context)${literalAssertion};
${INDENT_NS}}`;
          }
        }
 
        if (allDeclarations.length > 0) {
          variableTypeDeclarations = "\n\n" + allDeclarations.join("\n\n");
        }
      }
 
      const schemasImportLine = formatTypeImport([...featureSchemaTypesUsed].sort(), "./schemas");
 
      const featureContent = `
import { Context } from "./context";
import { getInstance } from "./instance";
${schemasImportLine}export namespace ${namespaceValue} {
${INDENT_NS}export const key = "${featureKey}";${variableTypeDeclarations}
 
${INDENT_NS}export function isEnabled(context: Context = {}) {
${INDENT_NS_BODY}return getInstance().isEnabled(key, context);
${INDENT_NS}}
 
${INDENT_NS}export function getVariation(context: Context = {}) {
${INDENT_NS_BODY}return getInstance().getVariation(key, context);
${INDENT_NS}}${variableMethods}
}
`.trimStart();
 
      const featureNamespaceFilePath = path.join(outputPath, `${namespaceValue}.ts`);
      fs.writeFileSync(featureNamespaceFilePath, featureContent);
      console.log(
        `Feature ${featureKey} file written at: ${getRelativePath(
          rootDirectoryPath,
          featureNamespaceFilePath,
        )}`,
      );
    }
  }
 
  const featuresTypeSchemasUsed = new Set<string>();
  const featureTypeEntries = parsedFeatures
    .map(({ featureKey, parsedFeature }) => {
      const featureLines: string[] = [];
      const variationUnion = getVariationUnionFromFeature(parsedFeature);
 
      if (variationUnion) {
        featureLines.push(`${INDENT_NS_BODY}variation: ${variationUnion};`);
      }
 
      if (parsedFeature.variablesSchema) {
        for (const [variableKey, variableSchema] of Object.entries(parsedFeature.variablesSchema)) {
          const { typeName, schemaTypesUsed } = getVariableTypeForFeaturesMap(
            variableSchema,
            schemasByKey,
            hasSchemasFile ? schemaTypeNames : undefined,
          );
          schemaTypesUsed.forEach((name) => featuresTypeSchemasUsed.add(name));
          featureLines.push(`${INDENT_NS_BODY}${formatObjectKey(variableKey)}: ${typeName};`);
        }
      }
 
      if (featureLines.length === 0) {
        return `${INDENT_NS}${formatObjectKey(featureKey)}: null;`;
      }
 
      return `${INDENT_NS}${formatObjectKey(featureKey)}: {\n${featureLines.join("\n")}\n${INDENT_NS}};`;
    })
    .join("\n");
 
  const featuresSchemasImportLine = formatTypeImport(
    [...featuresTypeSchemasUsed].sort(),
    "./schemas",
  );
 
  const featuresFileContent = `
${featuresSchemasImportLine}export type Features = {
${featureTypeEntries}
};
 
export type FeatureKey = keyof Features;
export type VariableKey<F extends FeatureKey> = Features[F] extends Record<string, unknown>
  ? Extract<Exclude<keyof Features[F], "variation">, string>
  : never;
export type VariableType<F extends FeatureKey, V extends VariableKey<F>> = Features[F] extends Record<string, unknown>
  ? Features[F][V]
  : never;
export type Variation<F extends FeatureKey> = Features[F] extends { variation: infer V }
  ? V
  : never;
`.trimStart();
  const featuresFilePath = path.join(outputPath, "features.ts");
  fs.writeFileSync(featuresFilePath, featuresFileContent);
  console.log(`Features file written at: ${getRelativePath(rootDirectoryPath, featuresFilePath)}`);
 
  const functionsFileContent = `
import { FeatureKey, Variation, VariableKey, VariableType } from "./features";
import { Context } from "./context";
import { getInstance } from "./instance";
 
export function isEnabled(featureKey: FeatureKey, context: Context = {}): boolean {
  return getInstance().isEnabled(featureKey, context);
}
 
export function getVariation<F extends FeatureKey>(
  featureKey: F,
  context: Context = {},
): Variation<F> | null {
  return getInstance().getVariation(featureKey, context) as Variation<F> | null;
}
 
export function getVariable<F extends FeatureKey, V extends VariableKey<F>>(
  featureKey: F,
  variableKey: V,
  context: Context = {},
): VariableType<F, V> | null {
  return getInstance().getVariable(featureKey, variableKey, context) as VariableType<F, V> | null;
}
`.trimStart();
  const functionsFilePath = path.join(outputPath, "functions.ts");
  fs.writeFileSync(functionsFilePath, functionsFileContent);
  console.log(
    `Functions file written at: ${getRelativePath(rootDirectoryPath, functionsFilePath)}`,
  );
 
  Iif (shouldGenerateReact) {
    const reactFileContent = `
import {
  useFlag as useFlagOriginal,
  useVariation as useVariationOriginal,
  useVariable as useVariableOriginal,
} from "@featurevisor/react";
 
import type { FeatureKey, Variation, VariableKey, VariableType } from "./features";
import type { Context } from "./context";
 
export function useFlag(featureKey: FeatureKey, context: Context = {}): boolean {
  return useFlagOriginal(featureKey, context);
}
 
export function useVariation<F extends FeatureKey>(
  featureKey: F,
  context: Context = {},
): Variation<F> | null {
  return useVariationOriginal(featureKey, context) as Variation<F> | null;
}
 
export function useVariable<F extends FeatureKey, V extends VariableKey<F>>(
  featureKey: F,
  variableKey: V,
  context: Context = {},
): VariableType<F, V> | null {
  return useVariableOriginal(featureKey, variableKey, context) as VariableType<F, V> | null;
}
`.trimStart();
    const reactFilePath = path.join(outputPath, "react.ts");
    fs.writeFileSync(reactFilePath, reactFileContent);
    console.log(`React file written at: ${getRelativePath(rootDirectoryPath, reactFilePath)}`);
  }
 
  // index
  const indexContent =
    [
      `export * from "./attributes";`,
      `export * from "./context";`,
      `export * from "./instance";`,
      ...(hasSchemasFile ? [`export * from "./schemas";`] : []),
      `export * from "./features";`,
      `export * from "./functions";`,
      ...(shouldGenerateReact ? [`export * from "./react";`] : []),
      ...featureNamespaces.map((featureNamespace) => {
        return `export * from "./${featureNamespace}";`;
      }),
    ].join("\n") + "\n";
  const indexFilePath = path.join(outputPath, "index.ts");
  fs.writeFileSync(indexFilePath, indexContent);
  console.log(`Index file written at: ${getRelativePath(rootDirectoryPath, indexFilePath)}`);
}