All files / src/builder mutator.ts

88.15% Statements 134/152
74.3% Branches 107/144
100% Functions 6/6
94.81% Lines 128/135

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                            622x 838x 838x 838x     838x 188x     838x 838x 838x 1790x 1790x 12852x 12852x   1790x 1790x 1751x 170x 170x 410x 170x 170x 170x 170x 73x 73x 73x 73x 73x   97x 97x     1581x   39x 39x 39x 39x 39x 39x 39x 39x             39x 39x     1790x     838x       81x 81x 81x   28x             28x 28x   53x   1x             1x 1x 1x 1x 1x 1x   1x   52x                   211x 19x   19x             19x 19x 5x 5x   14x 14x 14x       192x   30x             30x 30x 30x 30x 48x 48x 48x   30x 28x 10x 10x   18x 9x 9x   9x 9x 9x       162x 162x 162x 3x 3x   159x 12x 12x 12x 12x   147x 11x 11x 11x 11x   136x 136x       222x           221x 216x   216x 216x 4x 2x 2x 1x 1x   1x 1x 1x     2x     212x 212x   212x     212x 81x 81x 80x     211x 211x    
import type { VariableSchema, VariableValue } from "@featurevisor/types";
 
export type PathPart =
  | { key: string }
  | { key: string; index: number }
  | { key: string; selector: { prop: string; value: string } };
 
export type MutationOperation = "set" | "append" | "prepend" | "after" | "before" | "remove";
 
export interface ParsedNotation {
  segments: PathPart[];
  operation: MutationOperation;
}
 
export function parseNotation(notation: string): ParsedNotation {
  let rest = notation.trim();
  const operationMatch = rest.match(/:((?:append|prepend|after|before|remove))$/);
  const operation: MutationOperation = operationMatch
    ? (operationMatch[1] as MutationOperation)
    : "set";
  if (operationMatch) {
    rest = rest.slice(0, -operationMatch[0].length);
  }
 
  const segments: PathPart[] = [];
  let i = 0;
  while (i < rest.length) {
    let key = "";
    while (i < rest.length && rest[i] !== "." && rest[i] !== "[") {
      key += rest[i];
      i++;
    }
    key = key.trim();
    if (key) {
      if (rest[i] === "[") {
        i++;
        const bracketStart = i;
        while (i < rest.length && rest[i] !== "]") i++;
        const bracketContent = rest.slice(bracketStart, i);
        i++;
        const eq = bracketContent.indexOf("=");
        if (eq >= 0) {
          const prop = bracketContent.slice(0, eq).trim();
          let val = bracketContent.slice(eq + 1).trim();
          Iif (val.startsWith('"') && val.endsWith('"')) val = val.slice(1, -1);
          else Iif (val.startsWith("'") && val.endsWith("'")) val = val.slice(1, -1);
          segments.push({ key, selector: { prop, value: val } });
        } else {
          const index = parseInt(bracketContent.trim(), 10);
          segments.push({ key, index });
        }
      } else {
        segments.push({ key });
      }
    } else Eif (rest[i] === "[") {
      i++;
      const bracketStart = i;
      while (i < rest.length && rest[i] !== "]") i++;
      const bracketContent = rest.slice(bracketStart, i);
      i++;
      const eq = bracketContent.indexOf("=");
      Iif (eq >= 0) {
        const prop = bracketContent.slice(0, eq).trim();
        let val = bracketContent.slice(eq + 1).trim();
        if (val.startsWith('"') && val.endsWith('"')) val = val.slice(1, -1);
        else if (val.startsWith("'") && val.endsWith("'")) val = val.slice(1, -1);
        segments.push({ key: "", selector: { prop, value: val } });
      } else {
        const index = parseInt(bracketContent.trim(), 10);
        segments.push({ key: "", index });
      }
    }
    if (rest[i] === ".") i++;
  }
 
  return { segments, operation };
}
 
function getAtSegment(obj: VariableValue, seg: PathPart): VariableValue {
  Iif (obj === null || obj === undefined) return undefined;
  const o = obj as Record<string, unknown>;
  if ("index" in seg) {
    const arr =
      seg.key === ""
        ? Array.isArray(obj)
          ? obj
          : undefined
        : Array.isArray(obj)
          ? obj
          : (o[seg.key] as unknown[]);
    Iif (!Array.isArray(arr)) return undefined;
    return arr[seg.index] as VariableValue;
  }
  if ("selector" in seg) {
    const arr =
      seg.key === ""
        ? Array.isArray(obj)
          ? obj
          : undefined
        : Array.isArray(obj)
          ? obj
          : (o[seg.key] as unknown[]);
    Iif (!Array.isArray(arr)) return undefined;
    const { prop, value } = seg.selector;
    const found = arr.find((item) => {
      Iif (item === null || typeof item !== "object") return false;
      const v = (item as Record<string, unknown>)[prop];
      return String(v) === value;
    });
    return found as VariableValue;
  }
  return o[seg.key] as VariableValue;
}
 
function setAtSegment(
  obj: Record<string, unknown> | unknown[],
  seg: PathPart,
  _value: VariableValue,
  op: MutationOperation,
  setValue: VariableValue | undefined,
): void {
  if ("index" in seg) {
    const i = seg.index;
    const arr =
      seg.key === ""
        ? Array.isArray(obj)
          ? obj
          : undefined
        : Array.isArray(obj)
          ? obj
          : ((obj as Record<string, unknown>)[seg.key] as unknown[]);
    Iif (!Array.isArray(arr)) return;
    if (op === "remove") {
      arr.splice(i, 1);
      return;
    }
    Eif (op === "set") {
      arr[i] = setValue;
      return;
    }
    return;
  }
  if ("selector" in seg) {
    const arr =
      seg.key === ""
        ? Array.isArray(obj)
          ? obj
          : undefined
        : Array.isArray(obj)
          ? obj
          : ((obj as Record<string, unknown>)[seg.key] as unknown[]);
    Iif (!Array.isArray(arr)) return;
    const { prop, value: selVal } = seg.selector;
    const numVal = /^\d+$/.test(selVal) ? parseInt(selVal, 10) : null;
    const idx = arr.findIndex((item) => {
      Iif (item === null || typeof item !== "object") return false;
      const v = (item as Record<string, unknown>)[prop];
      return String(v) === selVal || (numVal !== null && v === numVal);
    });
    if (idx < 0) return;
    if (op === "remove") {
      arr.splice(idx, 1);
      return;
    }
    if (op === "after" && setValue !== undefined) {
      arr.splice(idx + 1, 0, setValue);
      return;
    }
    Eif (op === "before" && setValue !== undefined) {
      arr.splice(idx, 0, setValue);
      return;
    }
    return;
  }
  const key = seg.key;
  const o = obj as Record<string, unknown>;
  if (op === "remove") {
    delete o[key];
    return;
  }
  if (op === "append" && setValue !== undefined) {
    const arr = (o[key] ?? []) as unknown[];
    arr.push(setValue);
    o[key] = arr;
    return;
  }
  if (op === "prepend" && setValue !== undefined) {
    const arr = (o[key] ?? []) as unknown[];
    arr.unshift(setValue);
    o[key] = arr;
    return;
  }
  Eif (op === "set") {
    o[key] = setValue as unknown;
  }
}
 
export function mutate(
  _schema: VariableSchema,
  value: VariableValue,
  notation: string,
  setValue: VariableValue | undefined,
): VariableValue {
  if (value === null || value === undefined) return value;
  const result = JSON.parse(JSON.stringify(value)) as VariableValue;
 
  const { segments, operation } = parseNotation(notation);
  if (segments.length === 0) {
    if (Array.isArray(result) && setValue !== undefined) {
      const arr = result as VariableValue[];
      if (operation === "append") {
        arr.push(setValue);
        return result;
      }
      Eif (operation === "prepend") {
        arr.unshift(setValue);
        return result;
      }
    }
    return result;
  }
 
  const last = segments[segments.length - 1];
  const parentSegments = segments.slice(0, -1);
 
  let container: Record<string, unknown> | unknown[] = result as
    | Record<string, unknown>
    | unknown[];
  for (const seg of parentSegments) {
    const next = getAtSegment(container as VariableValue, seg);
    if (next === undefined) return result;
    container = next as Record<string, unknown> | unknown[];
  }
 
  setAtSegment(container, last, undefined, operation, setValue);
  return result;
}