All files / src/lib/project/migration/snapshots scriptEventDefs.ts

100% Statements 23/23
92.59% Branches 25/27
100% Functions 4/4
100% Lines 21/21

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                15x         9x 15x 3x 12x         8x     9x     15x         3x 3x   3x 6x       6x 4x       3x     15x     15x   15x 869x   1486x         15x    
import type { ScriptEventFieldSchema } from "shared/lib/entities/entitiesTypes";
import type {
  ScriptEventDefs,
  ScriptEventDefsFieldTypeLookup,
} from "shared/lib/scripts/scriptDefHelpers";
 
export type ScriptEventDefsSnapshot = Record<string, Record<string, string>>;
 
const snapshotScriptEventFields = (
  fields: ScriptEventFieldSchema[],
  fieldTypes?: ReadonlySet<string>,
  fieldsSnapshot: Record<string, string> = {},
): Record<string, string> => {
  for (const field of fields) {
    if (field.type === "group" && field.fields) {
      snapshotScriptEventFields(field.fields, fieldTypes, fieldsSnapshot);
    } else if (
      field.key &&
      field.type &&
      (!fieldTypes || fieldTypes.has(field.type))
    ) {
      fieldsSnapshot[field.key] = field.type;
    }
  }
  return fieldsSnapshot;
};
 
export const scriptEventDefsToSnapshot = (
  scriptEventDefs: ScriptEventDefs,
  fieldTypes?: readonly string[],
): ScriptEventDefsSnapshot => {
  const selectedFieldTypes =
    fieldTypes && fieldTypes.length > 0 ? new Set(fieldTypes) : undefined;
  const snapshot: ScriptEventDefsSnapshot = {};
 
  for (const id of Object.keys(scriptEventDefs).sort()) {
    const fieldsSnapshot = snapshotScriptEventFields(
      scriptEventDefs[id]?.fields ?? [],
      selectedFieldTypes,
    );
    if (!selectedFieldTypes || Object.keys(fieldsSnapshot).length > 0) {
      snapshot[id] = fieldsSnapshot;
    }
  }
 
  return snapshot;
};
 
export const scriptEventDefsFromSnapshot = (
  snapshot: ScriptEventDefsSnapshot,
): ScriptEventDefsFieldTypeLookup => {
  const scriptEventDefs: ScriptEventDefsFieldTypeLookup = {};
 
  for (const [id, fields] of Object.entries(snapshot)) {
    scriptEventDefs[id] = {
      fieldsLookup: Object.fromEntries(
        Object.entries(fields).map(([key, type]) => [key, { type }]),
      ),
    };
  }
 
  return scriptEventDefs;
};