All files / src/services SchemaIntrospector.ts

97.4% Statements 75/77
92.15% Branches 47/51
93.33% Functions 14/15
97.29% Lines 72/74

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  9x 9x                                                                             9x                                                   9x   36x     36x       32x 3x     29x 29x   29x 26x     26x 91x     26x     26x   114x                 26x 112x               26x 26x 91x     26x           26x                 26x   3x           3x                                   3x         11x 1x   10x       15x 1x     14x 14x 9x       5x 1x   4x 1x   3x 1x     2x       5x 6x       2x 1x   1x       4x 1x     3x   3x 5x 4x                 4x 4x   4x 4x                 3x       4x   4x   8x 4x 4x   4x   4x 2x 2x 2x         4x       6x       2x      
import { GraphQLClient } from "../graphql/client";
import { gql } from "graphql-tag";
import { logger } from "../logger";
 
export interface FieldInfo {
  name: string;
  type: {
    name: string | null;
    kind: string;
    ofType?: {
      name: string | null;
      kind: string;
    } | null;
  };
}
 
export interface TypeInfo {
  name: string;
  fields: FieldInfo[] | null;
  enumValues?: Array<{ name: string; description?: string }> | null;
}
 
export interface SchemaInfo {
  workItemWidgetTypes: string[];
  typeDefinitions: Map<string, TypeInfo>;
  availableFeatures: Set<string>;
}
 
interface IntrospectionType {
  name: string;
  kind: string;
  fields?: FieldInfo[] | null;
  enumValues?: Array<{ name: string; description?: string }> | null;
}
 
interface IntrospectionResult {
  __schema: {
    types: IntrospectionType[];
  };
}
 
const INTROSPECTION_QUERY = gql`
  query IntrospectSchema {
    __schema {
      types {
        name
        kind
        fields {
          name
          type {
            name
            kind
            ofType {
              name
              kind
            }
          }
        }
        enumValues {
          name
          description
        }
      }
    }
  }
`;
 
export class SchemaIntrospector {
  private client: GraphQLClient;
  private cachedSchema: SchemaInfo | null = null;
 
  constructor(client: GraphQLClient) {
    this.client = client;
  }
 
  public async introspectSchema(): Promise<SchemaInfo> {
    if (this.cachedSchema) {
      return this.cachedSchema;
    }
 
    try {
      logger.debug("Introspecting GitLab GraphQL schema...");
 
      const result = await this.client.request<IntrospectionResult>(INTROSPECTION_QUERY);
      const types = result.__schema.types;
 
      // Extract WorkItem widget types
      const workItemWidgetType = types.find(type => type.name === "WorkItemWidgetType");
      const workItemWidgetTypes = workItemWidgetType?.enumValues?.map(value => value.name) ?? [];
 
      // Build type definitions map
      const typeDefinitions = new Map<string, TypeInfo>();
 
      // Focus on WorkItem-related types
      const relevantTypes = types.filter(
        type =>
          type.name &&
          (type.name.startsWith("WorkItem") ||
            type.name.includes("Widget") ||
            type.name === "AwardEmoji" ||
            type.name === "Milestone" ||
            type.name === "User" ||
            type.name === "Label")
      );
 
      for (const type of relevantTypes) {
        typeDefinitions.set(type.name, {
          name: type.name,
          fields: type.fields ?? null,
          enumValues: type.enumValues ?? null,
        });
      }
 
      // Determine available features based on widget types
      const availableFeatures = new Set<string>();
      for (const widgetType of workItemWidgetTypes) {
        availableFeatures.add(widgetType);
      }
 
      this.cachedSchema = {
        workItemWidgetTypes,
        typeDefinitions,
        availableFeatures,
      };
 
      logger.info(
        {
          widgetTypes: workItemWidgetTypes.length,
          typeDefinitions: typeDefinitions.size,
          features: availableFeatures.size,
        },
        "GraphQL schema introspection completed"
      );
 
      return this.cachedSchema;
    } catch (error) {
      logger.warn(
        { err: error as Error },
        "Schema introspection failed, using fallback schema info"
      );
 
      // Provide fallback schema info when introspection fails
      this.cachedSchema = {
        workItemWidgetTypes: [
          "ASSIGNEES",
          "LABELS",
          "MILESTONE",
          "DESCRIPTION",
          "START_AND_DUE_DATE",
          "WEIGHT",
          "TIME_TRACKING",
          "HEALTH_STATUS",
          "COLOR",
          "NOTIFICATIONS",
          "NOTES",
        ],
        typeDefinitions: new Map(),
        availableFeatures: new Set(["workItems", "epics", "issues"]),
      };
 
      return this.cachedSchema;
    }
  }
 
  public isWidgetTypeAvailable(widgetType: string): boolean {
    if (!this.cachedSchema) {
      throw new Error("Schema not introspected yet. Call introspectSchema() first.");
    }
    return this.cachedSchema.availableFeatures.has(widgetType);
  }
 
  public getFieldsForType(typeName: string): FieldInfo[] {
    if (!this.cachedSchema) {
      throw new Error("Schema not introspected yet. Call introspectSchema() first.");
    }
 
    const typeInfo = this.cachedSchema.typeDefinitions.get(typeName);
    if (typeInfo?.fields) {
      return typeInfo.fields;
    }
 
    // Fallback field information for common widget types when full schema unavailable
    if (typeName === "WorkItemWidgetAssignees") {
      return [{ name: "assignees", type: { name: "UserConnection", kind: "OBJECT" } }];
    }
    if (typeName === "WorkItemWidgetLabels") {
      return [{ name: "labels", type: { name: "LabelConnection", kind: "OBJECT" } }];
    }
    if (typeName === "WorkItemWidgetMilestone") {
      return [{ name: "milestone", type: { name: "Milestone", kind: "OBJECT" } }];
    }
 
    return [];
  }
 
  public hasField(typeName: string, fieldName: string): boolean {
    const fields = this.getFieldsForType(typeName);
    return fields.some(field => field.name === fieldName);
  }
 
  public getAvailableWidgetTypes(): string[] {
    if (!this.cachedSchema) {
      throw new Error("Schema not introspected yet. Call introspectSchema() first.");
    }
    return this.cachedSchema.workItemWidgetTypes;
  }
 
  public generateSafeWidgetQuery(requestedWidgets: string[]): string {
    if (!this.cachedSchema) {
      throw new Error("Schema not introspected yet. Call introspectSchema() first.");
    }
 
    const safeWidgets: string[] = [];
 
    for (const widget of requestedWidgets) {
      if (this.isWidgetTypeAvailable(widget)) {
        const widgetTypeName = `WorkItemWidget${
          widget.charAt(0) +
          widget
            .slice(1)
            .toLowerCase()
            .replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase())
        }`;
 
        // Generate safe field selections for this widget
        const fields = this.getFieldsForType(widgetTypeName);
        const safeFields = this.generateSafeFieldSelections(fields);
 
        Eif (safeFields.length > 0) {
          safeWidgets.push(`
            ... on ${widgetTypeName} {
              ${safeFields.join("\n              ")}
            }
          `);
        }
      }
    }
 
    return safeWidgets.join("\n");
  }
 
  private generateSafeFieldSelections(fields: FieldInfo[]): string[] {
    const safeFields: string[] = [];
 
    for (const field of fields) {
      // Skip complex fields that require sub-selections for now
      if (field.type.kind === "SCALAR" || field.type.kind === "ENUM") {
        safeFields.push(field.name);
      } else Eif (field.type.kind === "OBJECT" && field.name !== "type") {
        // Add basic object fields with simple sub-selections
        Iif (field.name === "milestone") {
          safeFields.push(`${field.name} { id title state }`);
        } else if (field.name === "assignees" || field.name === "participants") {
          safeFields.push(`${field.name} { nodes { id username } }`);
        } else Eif (field.name === "labels") {
          safeFields.push(`${field.name} { nodes { id title color } }`);
        }
      }
    }
 
    return safeFields;
  }
 
  public getCachedSchema(): SchemaInfo | null {
    return this.cachedSchema;
  }
 
  public clearCache(): void {
    this.cachedSchema = null;
  }
}