All files / builder buildDatafile.ts

49.54% Statements 108/218
34.95% Branches 43/123
41.37% Functions 12/29
51.44% Lines 107/208

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 6471x                                               1x   1x 1x   1x 1x 1x 1x                                 1x                                                                                                     1x           2x 2x 2x     2x 2x 2x                 2x 2x   2x 2x   2x 2x   2x       2x       2x                                                               2x               2x 2x 2x 2x             2x       2x               2x 2x 2x   2x 2x 4x 8x 6x     6x 6x       8x 2x     2x 4x               2x               2x                   2x                                                                                                                         2x                 2x         2x   2x 2x 2x   2x 4x 4x   4x   8x 6x                           2x 2x                                       2x                           2x     2x             2x           2x                 2x       2x 2x 2x   2x 4x   4x       4x                     2x                                                           2x         2x 2x   2x                                                               2x 2x   2x                                               2x                                                                             2x                     2x               2x                   2x 2x       2x 2x     2x     2x 2x 4x 4x         2x   2x       2x 2x 2x   2x     2x 2x       2x         2x    
import * as fs from "fs";
 
import type { Schema, VariableType } from "@featurevisor/types";
import {
  Segment,
  Feature,
  DatafileContent,
  DatafileContentV1,
  Variation,
  VariableOverride,
  Traffic,
  SegmentKey,
  AttributeKey,
  Attribute,
  GroupSegment,
  Condition,
  ExistingState,
  FeatureKey,
  Allocation,
  Expose,
  Rule,
  Force,
} from "@featurevisor/types";
 
import { ProjectConfig, SCHEMA_VERSION } from "../config";
import { Datasource } from "../datasource";
import { extractAttributeKeysFromConditions, extractSegmentKeysFromGroupSegments } from "../utils";
import { generateHashForDatafile, generateHashForFeature, getSegmentHashes } from "./hashes";
 
import { getTraffic } from "./traffic";
import { getFeatureRanges } from "./getFeatureRanges";
import { convertToV1 } from "./convertToV1";
import {
  resolveMutationsForMultipleVariables,
  resolveMutationsForSingleVariable,
} from "./mutateVariables";
 
export interface CustomDatafileOptions {
  featureKey?: string;
  environment: string;
  projectConfig: ProjectConfig;
  datasource: Datasource;
  revision?: string;
  schemaVersion?: string;
  inflate?: number;
  tag?: string;
  tags?: BuildTags;
}
 
export async function getCustomDatafile(
  options: CustomDatafileOptions,
): Promise<DatafileContent | DatafileContentV1> {
  let featuresToInclude;
 
  Iif (options.featureKey) {
    const requiredChain = await options.datasource.getRequiredFeaturesChain(options.featureKey);
    featuresToInclude = Array.from(requiredChain);
  }
 
  const existingState = await options.datasource.readState(options.environment);
  const datafileContent = await buildDatafile(
    options.projectConfig,
    options.datasource,
    {
      schemaVersion: options.schemaVersion || SCHEMA_VERSION,
      revision: options.revision || "tester",
      environment: options.environment,
      features: featuresToInclude,
      inflate: options.inflate,
      tag: options.tag,
      tags: options.tags,
    },
    existingState,
  );
 
  return datafileContent;
}
 
export interface BuildOrTags {
  or: string[];
}
 
export interface BuildAndTags {
  and: string[];
}
 
export type BuildTags = BuildOrTags | BuildAndTags | string[];
 
export interface BuildOptions {
  schemaVersion: string;
  revision: string;
  featurevisorVersion?: string;
  revisionFromHash?: boolean;
  environment: string | false;
  tag?: string;
  tags?: BuildTags;
  features?: FeatureKey[];
  inflate?: number;
}
 
export async function buildDatafile(
  projectConfig: ProjectConfig,
  datasource: Datasource,
  options: BuildOptions,
  existingState: ExistingState,
): Promise<DatafileContent | DatafileContentV1> {
  const segmentKeysUsedByTag = new Set<SegmentKey>();
  const attributeKeysUsedByTag = new Set<AttributeKey>();
  const { featureRanges, featureIsInGroup } = await getFeatureRanges(projectConfig, datasource);
 
  // Load schemas for resolving variable schema references in features
  const schemaKeys = await datasource.listSchemas();
  const schemasByKey: Record<string, Schema> = {};
  for (const key of schemaKeys) {
    try {
      schemasByKey[key] = await datasource.readSchema(key);
    } catch {
      // Schema file may be invalid; skip for datafile build
    }
  }
 
  // features
  const features: Feature[] = [];
  const featuresDirectory = projectConfig.featuresDirectoryPath;
 
  if (fs.existsSync(featuresDirectory)) {
    const featureFiles = await datasource.listFeatures();
 
    for (const featureKey of featureFiles) {
      const parsedFeature = await datasource.readFeature(featureKey);
 
      Iif (parsedFeature.archived === true) {
        continue;
      }
 
      Iif (options.tag && parsedFeature.tags.indexOf(options.tag) === -1) {
        continue;
      }
 
      Iif (options.tags) {
        // plain array of tags: treat as OR tags
        if (Array.isArray(options.tags)) {
          Iif (
            options.tags.some((searchTag) => parsedFeature.tags.indexOf(searchTag) !== -1) === false
          ) {
            continue;
          }
        } else {
          // OR tags
          const orTags = options.tags as BuildOrTags;
          Iif (orTags.or) {
            Iif (
              orTags.or.some((searchTag) => parsedFeature.tags.indexOf(searchTag) !== -1) === false
            ) {
              continue;
            }
          }
 
          // AND tags
          const andTags = options.tags as BuildAndTags;
          Iif (andTags.and) {
            Iif (
              andTags.and.every((searchTag) => parsedFeature.tags.indexOf(searchTag) !== -1) ===
              false
            ) {
              continue;
            }
          }
        }
      }
 
      Iif (options.features && options.features.indexOf(featureKey) === -1) {
        continue;
      }
 
      let expose: Expose | undefined;
      let rules: Rule[];
      let force: Force[] | undefined;
 
      if (options.environment) {
        expose = parsedFeature.expose?.[options.environment] as Expose | undefined;
        rules = parsedFeature.rules?.[options.environment] as Rule[];
        force = parsedFeature.force?.[options.environment] as Force[] | undefined;
      } else E{
        expose = parsedFeature.expose as Expose | undefined;
        rules = parsedFeature.rules as Rule[];
        force = parsedFeature.force as Force[] | undefined;
      }
 
      Iif (expose === false) {
        continue;
      }
 
      Iif (Array.isArray(expose)) {
        const exposeTags = expose;
 
        Iif (options.tag && exposeTags.indexOf(options.tag) === -1) {
          continue;
        }
      }
 
      for (const parsedRule of rules) {
        const extractedSegmentKeys = extractSegmentKeysFromGroupSegments(parsedRule.segments);
        extractedSegmentKeys.forEach((segmentKey) => segmentKeysUsedByTag.add(segmentKey));
 
        if (parsedRule.variableOverrides) {
          for (const variableOverrides of Object.values(parsedRule.variableOverrides)) {
            for (const override of variableOverrides) {
              if (typeof override.conditions !== "undefined") {
                const extractedAttributeKeys = extractAttributeKeysFromConditions(
                  override.conditions,
                );
                extractedAttributeKeys.forEach((attributeKey) =>
                  attributeKeysUsedByTag.add(attributeKey),
                );
              }
 
              if (typeof override.segments !== "undefined") {
                const extractedOverrideSegmentKeys = extractSegmentKeysFromGroupSegments(
                  override.segments as GroupSegment | GroupSegment[],
                );
                extractedOverrideSegmentKeys.forEach((segmentKey) =>
                  segmentKeysUsedByTag.add(segmentKey),
                );
              }
            }
          }
        }
      }
 
      const feature: Feature = {
        key: featureKey,
        deprecated: parsedFeature.deprecated === true ? true : undefined,
        bucketBy: parsedFeature.bucketBy || projectConfig.defaultBucketBy,
        required: parsedFeature.required,
        disabledVariationValue: parsedFeature.disabledVariationValue,
        variations: Array.isArray(parsedFeature.variations)
          ? parsedFeature.variations.map((variation: Variation) => {
              const mappedVariation: any = {
                value: variation.value,
                weight: variation.weight, // @NOTE: added so state files can maintain weight info, but datafiles don't need this. find a way to remove it from datafiles later
                variables: resolveMutationsForMultipleVariables(
                  parsedFeature.variablesSchema,
                  variation.variables,
                ),
                variableOverrides: variation.variableOverrides,
              };
 
              Iif (variation.variableOverrides) {
                const variableOverrides = variation.variableOverrides;
                const variableKeys = Object.keys(variableOverrides);
 
                for (const variableKey of variableKeys) {
                  const baseValue = mappedVariation.variables
                    ? mappedVariation.variables[variableKey]
                    : undefined;
 
                  mappedVariation.variableOverrides[variableKey] = variableOverrides[
                    variableKey
                  ].map((override: VariableOverride) => {
                    Iif (typeof override.conditions !== "undefined") {
                      const extractedAttributeKeys = extractAttributeKeysFromConditions(
                        override.conditions,
                      );
                      extractedAttributeKeys.forEach((attributeKey) =>
                        attributeKeysUsedByTag.add(attributeKey),
                      );
 
                      return {
                        conditions:
                          projectConfig.stringify && typeof override.conditions !== "string"
                            ? JSON.stringify(override.conditions)
                            : override.conditions,
                        value: resolveMutationsForSingleVariable(
                          parsedFeature.variablesSchema,
                          variableKey,
                          override.value,
                          baseValue,
                        ),
                      };
                    }
 
                    Iif (typeof override.segments !== "undefined") {
                      const extractedSegmentKeys = extractSegmentKeysFromGroupSegments(
                        override.segments as GroupSegment | GroupSegment[],
                      );
                      extractedSegmentKeys.forEach((segmentKey) =>
                        segmentKeysUsedByTag.add(segmentKey),
                      );
 
                      return {
                        segments:
                          projectConfig.stringify && typeof override.segments !== "string"
                            ? JSON.stringify(override.segments)
                            : override.segments,
                        value: resolveMutationsForSingleVariable(
                          parsedFeature.variablesSchema,
                          variableKey,
                          override.value,
                          baseValue,
                        ),
                      };
                    }
 
                    return override;
                  });
                }
              }
 
              return mappedVariation;
            })
          : undefined,
        traffic: getTraffic(
          parsedFeature.variations,
          rules,
          existingState.features[featureKey],
          featureRanges.get(featureKey) || [],
        ).map((t: Traffic) => {
          const resolvedVariables = resolveMutationsForMultipleVariables(
            parsedFeature.variablesSchema,
            t.variables,
          );
 
          let resolvedVariableOverrides = t.variableOverrides;
 
          if (t.variableOverrides) {
            resolvedVariableOverrides = {};
            const variableKeys = Object.keys(t.variableOverrides);
 
            for (const variableKey of variableKeys) {
              const overrides = t.variableOverrides[variableKey];
              const baseValue = resolvedVariables ? resolvedVariables[variableKey] : undefined;
 
              resolvedVariableOverrides[variableKey] = overrides.map(
                (override: VariableOverride) => {
                  if (typeof override.conditions !== "undefined") {
                    return {
                      conditions:
                        projectConfig.stringify && typeof override.conditions !== "string"
                          ? JSON.stringify(override.conditions)
                          : override.conditions,
                      value: resolveMutationsForSingleVariable(
                        parsedFeature.variablesSchema,
                        variableKey,
                        override.value,
                        baseValue,
                      ),
                    };
                  }
 
                  if (typeof override.segments !== "undefined") {
                    return {
                      segments:
                        projectConfig.stringify && typeof override.segments !== "string"
                          ? JSON.stringify(override.segments)
                          : override.segments,
                      value: resolveMutationsForSingleVariable(
                        parsedFeature.variablesSchema,
                        variableKey,
                        override.value,
                        baseValue,
                      ),
                    };
                  }
 
                  return override;
                },
              );
            }
          }
 
          return {
            ...t,
            variables: resolvedVariables,
            variableOverrides: resolvedVariableOverrides,
            segments:
              typeof t.segments !== "string" && projectConfig.stringify
                ? JSON.stringify(t.segments)
                : t.segments,
          };
        }),
        ranges: featureRanges.get(featureKey) || undefined,
      };
 
      // update state in memory, so that next datafile build can use it (in case it contains the same feature)
      existingState.features[featureKey] = {
        variations: Array.isArray(feature.variations)
          ? feature.variations.map((v: Variation) => {
              return {
                value: v.value,
                weight: v.weight || 0,
              };
            })
          : undefined,
        traffic: feature.traffic.map((t: Traffic) => {
          return {
            key: t.key,
            percentage: t.percentage,
            allocation:
              t.allocation &&
              t.allocation.map((a: Allocation) => {
                return {
                  variation: a.variation,
                  range: a.range,
                };
              }),
          };
        }),
      };
 
      Iif (featureIsInGroup[featureKey] === true) {
        feature.ranges = featureRanges.get(featureKey);
      }
 
      if (parsedFeature.variablesSchema) {
        const variableKeys = Object.keys(parsedFeature.variablesSchema);
        feature.variablesSchema = {};
 
        for (const variableKey of variableKeys) {
          const v = parsedFeature.variablesSchema[variableKey];
          const resolved =
            "schema" in v && v.schema
              ? schemasByKey[v.schema]
              : (v as { type: string; properties?: Schema; required?: string[]; items?: Schema });
 
          feature.variablesSchema[variableKey] = {
            key: variableKey,
            type: (resolved?.type ?? "string") as VariableType,
            defaultValue: v.defaultValue,
            deprecated: v.deprecated === true ? true : undefined,
            useDefaultWhenDisabled: v.useDefaultWhenDisabled === true ? true : undefined,
            disabledValue: typeof v.disabledValue !== "undefined" ? v.disabledValue : undefined,
          };
        }
      }
 
      Iif (force) {
        feature.force = force.map((f) => {
          Iif (f.segments) {
            const extractedSegmentKeys = extractSegmentKeysFromGroupSegments(f.segments);
            extractedSegmentKeys.forEach((segmentKey) => segmentKeysUsedByTag.add(segmentKey));
 
            f.segments =
              typeof f.segments !== "string" && projectConfig.stringify
                ? JSON.stringify(f.segments)
                : f.segments;
          }
 
          Iif (f.conditions) {
            f.conditions =
              typeof f.conditions !== "string" && projectConfig.stringify
                ? JSON.stringify(f.conditions)
                : f.conditions;
          }
 
          Iif (f.variables) {
            f.variables = resolveMutationsForMultipleVariables(
              parsedFeature.variablesSchema,
              f.variables,
            );
          }
 
          return f;
        });
      }
 
      features.push(feature);
    }
  }
 
  // segments
  const segments: Segment[] = [];
  const segmentsDirectory = projectConfig.segmentsDirectoryPath;
 
  Iif (fs.existsSync(segmentsDirectory)) {
    const segmentFiles = await datasource.listSegments();
 
    for (const segmentKey of segmentFiles) {
      const parsedSegment = await datasource.readSegment(segmentKey);
 
      Iif (parsedSegment.archived === true) {
        continue;
      }
 
      Iif (segmentKeysUsedByTag.has(segmentKey) === false) {
        continue;
      }
 
      const extractedAttributeKeys = extractAttributeKeysFromConditions(
        parsedSegment.conditions as Condition | Condition[],
      );
      extractedAttributeKeys.forEach((attributeKey) => attributeKeysUsedByTag.add(attributeKey));
 
      const segment: Segment = {
        key: segmentKey,
        conditions:
          typeof parsedSegment.conditions !== "string" && projectConfig.stringify === true
            ? JSON.stringify(parsedSegment.conditions)
            : parsedSegment.conditions,
      };
 
      segments.push(segment);
    }
  }
 
  // attributes
  const attributes: Attribute[] = [];
  const attributesDirectory = projectConfig.attributesDirectoryPath;
 
  Iif (fs.existsSync(attributesDirectory)) {
    const attributeFiles = await datasource.listAttributes();
 
    for (const attributeKey of attributeFiles) {
      const parsedAttribute = await datasource.readAttribute(attributeKey);
 
      Iif (parsedAttribute.archived === true) {
        continue;
      }
 
      Iif (attributeKeysUsedByTag.has(attributeKey) === false) {
        continue;
      }
 
      const attribute: Attribute = {
        key: attributeKey,
        type: parsedAttribute.type,
      };
 
      attributes.push(attribute);
    }
  }
 
  // inflate
  Iif (options.inflate && options.inflate >= 2) {
    const allFeatureKeys = features.map((f) => f.key);
    const allSegmentKeys = segments.map((s) => s.key);
    const allAttributeKeys = attributes.map((a) => a.key);
 
    for (let i = 0; i < options.inflate - 1; i++) {
      // feature
      for (const featureKey of allFeatureKeys) {
        const originalFeature = features.find((f) => f.key === featureKey) as Feature;
 
        features.unshift({
          ...originalFeature,
          key: `${originalFeature.key}-${i}`,
        });
      }
 
      // segment
      for (const segmentKey of allSegmentKeys) {
        const originalSegment = segments.find((s) => s.key === segmentKey) as Segment;
 
        segments.unshift({
          ...originalSegment,
          key: `${originalSegment.key}-${i}`,
        });
      }
 
      // attribute
      for (const attributeKey of allAttributeKeys) {
        const originalAttribute = attributes.find((a) => a.key === attributeKey) as Attribute;
 
        attributes.unshift({
          ...originalAttribute,
          key: `${originalAttribute.key}-${i}`,
        });
      }
    }
  }
 
  // schema v1
  Iif (options.schemaVersion === "1") {
    return convertToV1({
      revision: options.revision,
      projectConfig,
      attributes,
      features,
      segments,
    });
  }
 
  // schema v2
  const datafileContentV2: DatafileContent = {
    schemaVersion: "2",
    featurevisorVersion: options.featurevisorVersion,
    revision: options.revision,
    segments: {},
    features: {},
  };
 
  datafileContentV2.segments = segments.reduce((acc, segment) => {
    // key check needed for supporting v1 datafile generation
    Iif (segment.key) {
      acc[segment.key] = segment;
      delete acc[segment.key].key; // remove key from segment, as it is not needed in v2 datafile
    }
 
    return acc;
  }, {});
 
  datafileContentV2.features = features.reduce((acc, feature) => {
    Iif (!feature.key) {
      return acc;
    }
 
    const featureKey = feature.key as FeatureKey;
    const featureV2 = feature;
 
    // remove key, as it is not needed in v2 datafile
    delete featureV2.key;
 
    // remove variablesSchema[key].key
    if (featureV2.variablesSchema) {
      for (const [variableKey, variable] of Object.entries(featureV2.variablesSchema)) {
        if (variable.key) {
          delete featureV2.variablesSchema[variableKey].key;
        }
      }
    }
 
    acc[featureKey] = featureV2;
 
    return acc;
  }, {});
 
  // add feature hashes for change detection
  const segmentHashes = getSegmentHashes(datafileContentV2.segments);
  Object.keys(datafileContentV2.features).forEach((featureKey) => {
    const hash = generateHashForFeature(featureKey, datafileContentV2.features, segmentHashes);
 
    datafileContentV2.features[featureKey].hash = hash;
 
    // check needed to support --inflate option
    if (existingState.features[featureKey]) {
      existingState.features[featureKey].hash = hash;
    }
  });
 
  Iif (options.revisionFromHash) {
    const datafileHash = generateHashForDatafile(datafileContentV2);
    datafileContentV2.revision = `${datafileHash}`;
  }
 
  return datafileContentV2;
}