"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseMablScript = parseMablScript;
exports.loadMablScriptIntoSteps = loadMablScriptIntoSteps;
exports.yamlifyTheLoadedSteps = yamlifyTheLoadedSteps;
exports.loadYamlSteps = loadYamlSteps;
exports.interpretStepsFromObjectsInFlow = interpretStepsFromObjectsInFlow;
exports.interpretStepsFromObjects = interpretStepsFromObjects;
exports.mablscriptTheLoadedSteps = mablscriptTheLoadedSteps;
exports.parseMablScriptIntoSteps = parseMablScriptIntoSteps;
exports.extractInputVariables = extractInputVariables;
exports.extractOutputVariables = extractOutputVariables;
exports.parseMablScriptIntoV2Step = parseMablScriptIntoV2Step;
exports.getQueryIds = getQueryIds;
exports.getSnippetIdsFromJsonFlow = getSnippetIdsFromJsonFlow;
exports.getSnippetIdsFromMablscriptFlow = getSnippetIdsFromMablscriptFlow;
exports.getSnippetIdsFromFlow = getSnippetIdsFromFlow;
exports.getSnippetIdsFromFlows = getSnippetIdsFromFlows;
const esprima_1 = require("esprima");
const estraverse_1 = require("estraverse");
const AssertStep_1 = require("./steps/AssertStep");
const AssertStepOld_1 = require("./steps/AssertStepOld");
const AwaitTabStep_1 = require("./steps/AwaitTabStep");
const ClickStep_1 = require("./steps/ClickStep");
const js_yaml_1 = require("js-yaml");
const EchoStep_1 = require("./steps/EchoStep");
const ElseStep_1 = require("./steps/ElseStep");
const EndStep_1 = require("./steps/EndStep");
const EnterTextStep_1 = require("./steps/EnterTextStep");
const IfConditionStep_1 = require("./steps/IfConditionStep");
const EvaluateJavaScriptStep_1 = require("./steps/EvaluateJavaScriptStep");
const MablStep_1 = require("./MablStep");
const SetViewportStep_1 = require("./steps/SetViewportStep");
const VisitUrlStep_1 = require("./steps/VisitUrlStep");
const WaitStep_1 = require("./steps/WaitStep");
const AwaitUploadsStep_1 = require("./steps/AwaitUploadsStep");
const ClearCookiesStep_1 = require("./steps/ClearCookiesStep");
const CreateVariableStep_1 = require("./steps/CreateVariableStep");
const DoubleClickStep_1 = require("./steps/DoubleClickStep");
const DownloadStep_1 = require("./steps/DownloadStep");
const HoverStep_1 = require("./steps/HoverStep");
const SendKeyStep_1 = require("./steps/SendKeyStep");
const NavigateStep_1 = require("./steps/NavigateStep");
const OpenEmailStep_1 = require("./steps/OpenEmailStep");
const RemoveCookieStep_1 = require("./steps/RemoveCookieStep");
const SelectStep_1 = require("./steps/SelectStep");
const SetCookieStep_1 = require("./steps/SetCookieStep");
const SetFilesStep_1 = require("./steps/SetFilesStep");
const SwitchContextStep_1 = require("./steps/SwitchContextStep");
const SendHttpRequestStep_1 = require("./steps/SendHttpRequestStep");
const FindAction_1 = require("./actions/FindAction");
const ExtractAction_1 = require("./actions/ExtractAction");
const ConditionAction_1 = require("./actions/ConditionAction");
const GetVariableValue_1 = require("./actions/GetVariableValue");
const GetUrlAction_1 = require("./actions/GetUrlAction");
const MablAction_1 = require("./MablAction");
const GenerateRandomStringAction_1 = require("./actions/GenerateRandomStringAction");
const AwaitDownloadAction_1 = require("./actions/AwaitDownloadAction");
const AwaitPDFDownloadAction_1 = require("./actions/AwaitPDFDownloadAction");
const GenerateEmailAddressAction_1 = require("./actions/GenerateEmailAddressAction");
const MablSymbol_1 = require("./MablSymbol");
const ElseIfConditionStep_1 = require("./steps/ElseIfConditionStep");
const JavaScriptAction_1 = require("./actions/JavaScriptAction");
const ClickAndHoldStep_1 = require("./steps/ClickAndHoldStep");
const ReleaseStep_1 = require("./steps/ReleaseStep");
const CountAction_1 = require("./actions/CountAction");
const typescript_api_client_1 = require("@mablhq-internal/typescript-api-client");
const AccessibilityCheck_1 = require("./steps/AccessibilityCheck");
const EvaluateFlowStep_1 = require("./steps/EvaluateFlowStep");
const RightClickStep_1 = require("./steps/RightClickStep");
const EnterAuthCodeStep_1 = require("./steps/EnterAuthCodeStep");
const TapStep_1 = require("./mobile/steps/TapStep");
const EnterTextStep_2 = require("./mobile/steps/EnterTextStep");
const SetOrientationStep_1 = require("./mobile/steps/SetOrientationStep");
const ScrollStep_1 = require("./mobile/steps/ScrollStep");
const CreateVariableMobileStep_1 = require("./mobile/steps/CreateVariableMobileStep");
const NavigateBackStep_1 = require("./mobile/steps/NavigateBackStep");
const NavigateHomeStep_1 = require("./mobile/steps/NavigateHomeStep");
const CreateVariableStepDescriptor_1 = require("./types/CreateVariableStepDescriptor");
const SnippetsDescriptor_1 = require("./types/SnippetsDescriptor");
const PushFileStep_1 = require("./mobile/steps/PushFileStep");
const InstallAppStep_1 = require("./mobile/steps/InstallAppStep");
const UninstallAppStep_1 = require("./mobile/steps/UninstallAppStep");
const PrepareSessionStep_1 = require("./mobile/steps/PrepareSessionStep");
const OpenLinkStep_1 = require("./mobile/steps/OpenLinkStep");
const DatabaseQueryStep_1 = require("./steps/DatabaseQueryStep");
const HideKeyboardStep_1 = require("./mobile/steps/HideKeyboardStep");
const OpenAppStep_1 = require("./mobile/steps/OpenAppStep");
const StepGroupStep_1 = require("./steps/StepGroupStep");
const ActionTypes = [
    AwaitDownloadAction_1.AwaitDownloadAction,
    AwaitPDFDownloadAction_1.AwaitPDFDownloadAction,
    ConditionAction_1.ConditionAction,
    CountAction_1.CountAction,
    ExtractAction_1.ExtractAction,
    FindAction_1.FindAction,
    GenerateEmailAddressAction_1.GenerateEmailAddressAction,
    GenerateRandomStringAction_1.GenerateRandomStringAction,
    GetVariableValue_1.GetVariableValue,
    GetUrlAction_1.GetUrlAction,
    JavaScriptAction_1.JavaScriptAction,
];
const StepTypes = [
    AccessibilityCheck_1.AccessibilityCheckStep,
    AssertStep_1.AssertStep,
    AwaitTabStep_1.AwaitTabStep,
    AwaitUploadsStep_1.AwaitUploadsStep,
    ClearCookiesStep_1.ClearCookiesStep,
    ClickStep_1.ClickStep,
    ClickAndHoldStep_1.ClickAndHoldStep,
    CreateVariableStep_1.CreateVariableStep,
    DatabaseQueryStep_1.DatabaseQueryStep,
    DoubleClickStep_1.DoubleClickStep,
    DownloadStep_1.DownloadStep,
    EchoStep_1.EchoStep,
    ElseStep_1.ElseStep,
    ElseIfConditionStep_1.ElseIfConditionStep,
    EndStep_1.EndStep,
    EnterAuthCodeStep_1.EnterAuthCodeStep,
    EnterTextStep_1.EnterTextStep,
    EvaluateFlowStep_1.EvaluateFlowStep,
    HoverStep_1.HoverStep,
    IfConditionStep_1.IfConditionStep,
    EvaluateJavaScriptStep_1.EvaluateJavaScriptStep,
    SendKeyStep_1.SendKeyStep,
    NavigateStep_1.NavigateStep,
    OpenEmailStep_1.OpenEmailStep,
    ReleaseStep_1.ReleaseStep,
    RemoveCookieStep_1.RemoveCookieStep,
    RightClickStep_1.RightClickStep,
    SelectStep_1.SelectStep,
    SendHttpRequestStep_1.SendHttpRequestStep,
    SetCookieStep_1.SetCookieStep,
    SetFilesStep_1.SetFilesStep,
    SetViewportStep_1.SetViewportStep,
    SwitchContextStep_1.SwitchContextStep,
    VisitUrlStep_1.VisitUrlStep,
    WaitStep_1.WaitStep,
];
const MobileStepTypes = [
    AssertStep_1.AssertStep,
    CreateVariableMobileStep_1.CreateVariableMobileStep,
    HideKeyboardStep_1.HideKeyboardStep,
    IfConditionStep_1.IfConditionStep,
    InstallAppStep_1.InstallAppStep,
    NavigateBackStep_1.NavigateBackStep,
    NavigateHomeStep_1.NavigateHomeStep,
    TapStep_1.TapStep,
    EnterTextStep_2.EnterTextStep,
    SetOrientationStep_1.SetOrientationStep,
    ScrollStep_1.ScrollStep,
    OpenAppStep_1.OpenAppStep,
    OpenLinkStep_1.OpenLinkStep,
    PrepareSessionStep_1.PrepareSessionStep,
    PushFileStep_1.PushFileStep,
    UninstallAppStep_1.UninstallAppStep,
];
function parseMablScript(mablscript) {
    const ast = (0, esprima_1.parseScript)(mablscript, { loc: true });
    const stepStack = {};
    let stepLine = 0;
    (0, estraverse_1.traverse)(ast, {
        enter(node) {
            switch (node.type) {
                case 'ExpressionStatement':
                    stepStack[stepLine] = [];
                    return;
                case 'CallExpression': {
                    const callExpression = node;
                    stepStack[stepLine].unshift(parseCallExpression(callExpression));
                    return;
                }
                default:
                    break;
            }
        },
        leave(node) {
            switch (node.type) {
                case 'ExpressionStatement':
                    stepLine += 1;
                    return;
                default:
                    break;
            }
        },
    });
    return stepStack;
}
const rawMablscriptToObjectsStepMap = {};
StepTypes.forEach((step) => {
    step.mablScriptStepNames
        .concat(step.yamlMablScriptNames)
        .forEach((name) => (rawMablscriptToObjectsStepMap[name] = step));
});
const rawMablscriptToObjectsActionsMap = {};
ActionTypes.forEach((step) => {
    step.mablScriptStepNames.forEach((name) => (rawMablscriptToObjectsActionsMap[name] = step));
});
const legacyMablscriptStepGeneratorMap = {};
StepTypes.forEach((step) => {
    step.mablScriptStepNames.forEach((name) => {
        legacyMablscriptStepGeneratorMap[name] = step
            .fromLegacyMablscript;
    });
});
function loadMablScriptIntoSteps(parsedMablscript) {
    return Object.entries(parsedMablscript).map(([stepIndexString, [...parsed]]) => {
        const lastAction = parsed.pop();
        const actions = parsed.map((parsedAction, actionIndex) => {
            const actionType = rawMablscriptToObjectsActionsMap[parsedAction.name];
            const action = actionType
                ? new actionType(parsedAction.name, parsedAction.arguments)
                : new MablAction_1.MablAction(parsedAction.name, parsedAction.name, parsedAction.arguments);
            action.setActionSourceIndexInStep(actionIndex);
            return action;
        });
        let step;
        if (lastAction.name.startsWith('assert_') &&
            lastAction.name !== 'assert_download') {
            step = AssertStepOld_1.AssertStepOldConverter.convert(lastAction.name, lastAction.arguments, actions);
        }
        else if (lastAction.name === 'assert') {
            step = AssertStep_1.AssertStep.fromLegacyMablscript(lastAction.arguments, actions);
        }
        else {
            const stepGenerator = legacyMablscriptStepGeneratorMap[lastAction.name];
            step = stepGenerator
                ? stepGenerator(lastAction.arguments, actions)
                : new MablStep_1.MablStep(lastAction.name, lastAction.arguments, actions, lastAction.name);
        }
        step.setActionSourceIndexInStep(actions.length);
        step.setStepSourceIndexInFlow(parseInt(stepIndexString));
        return step;
    });
}
function yamlifyTheLoadedSteps(translatedSteps) {
    const steps = translatedSteps.map((step) => step.getFormattedStep());
    return (0, js_yaml_1.dump)(steps);
}
const yamlMablscriptToObjectsStepV1Map = {};
StepTypes.forEach((step) => {
    step.yamlMablScriptNames.forEach((name) => {
        yamlMablscriptToObjectsStepV1Map[name] = step.fromYaml;
    });
});
const yamlMablscriptToObjectsMobileStepMap = {};
MobileStepTypes.forEach((step) => {
    step.yamlMablScriptNames.forEach((name) => (yamlMablscriptToObjectsMobileStepMap[name] = step.fromYaml));
});
function loadYamlSteps(yamlSteps, isMobile) {
    const loadedStepData = (0, js_yaml_1.load)(yamlSteps);
    return interpretStepsFromObjects(loadedStepData, isMobile);
}
function interpretStepsFromObjectsInFlow(flow, isMobile) {
    const steps = interpretStepsFromObjects(flow.json_steps?.steps, isMobile);
    applyStepDescriptionsAndAnnotations(steps, flow);
    return steps;
}
function flowHasAppVersion(flow) {
    return !!(flow.created_by_app_version || flow.variant_last_updated_by_app_version);
}
function applyStepDescriptionsAndAnnotations(steps, flow) {
    if (flow.json_steps?.steps && flowHasAppVersion(flow)) {
        return;
    }
    if (flow.script_description || flow.step_annotations) {
        const flowDescriptions = flow.script_description?.split('\n') ?? [];
        steps.forEach((step, index) => {
            if (flowDescriptions[index]) {
                step.setDescription(flowDescriptions[index]);
            }
            const stepAnnotation = flow?.step_annotations?.[index];
            if (stepAnnotation) {
                step.setAnnotation(stepAnnotation);
            }
        });
    }
}
function interpretStepsFromObjects(steps, isMobile) {
    return steps.map((stepObject, index) => {
        const stepName = Object.keys(stepObject)[0];
        const stepArgs = stepObject[stepName];
        const isStepDisabled = stepObject[stepName].disabled;
        const step = stepFromObjectInfo(stepName, stepArgs, isMobile ?? false);
        step.setStepSourceIndexInFlow(index);
        step.setActionSourceIndexInStep(step.actions.length);
        step.actions?.forEach((action, actionIndex) => action.setActionSourceIndexInStep(actionIndex));
        if (stepArgs.id && !step.id) {
            step.setStepId(stepArgs.id);
        }
        if (isStepDisabled) {
            step.setDisabled(isStepDisabled);
        }
        return step;
    });
}
function stepFromObjectInfo(stepName, stepArgs, isMobile) {
    if (stepName.startsWith('assert_') && stepName !== 'assert_download') {
        return AssertStepOld_1.AssertStepOldConverter.convert(stepName, stepArgs, []);
    }
    if (stepName === 'StepGroup' || stepName === 'step_group') {
        stepArgs.isMobile = isMobile;
        stepArgs.steps = stepArgs.steps || [];
        stepArgs.intent = stepArgs.intent || { description: '' };
        return new StepGroupStep_1.StepGroupStep(stepArgs, interpretStepsFromObjects);
    }
    if (isMobile &&
        Object.keys(yamlMablscriptToObjectsMobileStepMap).includes(stepName)) {
        return yamlMablscriptToObjectsMobileStepMap[stepName](stepName, stepArgs);
    }
    if (Object.keys(yamlMablscriptToObjectsStepV1Map).includes(stepName)) {
        return yamlMablscriptToObjectsStepV1Map[stepName](stepName, stepArgs);
    }
    return new MablStep_1.MablStep(stepName, [], [], stepName);
}
function getMablscriptMaybeWithComment(step) {
    return `${step.isDisabled() ? '//' : ''}${step.toMablscript()}`;
}
function mablscriptTheLoadedSteps(translatedSteps) {
    const steps = translatedSteps.map((step) => getMablscriptMaybeWithComment(step));
    return steps.join('\n');
}
function parseCallExpression(callExpression) {
    const calleeName = getNameFromCallee(callExpression);
    const expressionArgs = getArgumentsFromCallExpressionArgs(callExpression.arguments);
    return {
        name: calleeName,
        arguments: expressionArgs,
    };
}
function getNameFromCallee(expression) {
    switch (expression.callee.type) {
        case 'Identifier':
            const identifier = expression.callee;
            return identifier.name;
        case 'MemberExpression':
            const memberExpression = expression.callee;
            if (memberExpression.property.type === 'Identifier') {
                const identifier = memberExpression.property;
                return identifier.name;
            }
    }
    return '';
}
function getArgumentsFromCallExpressionArgs(expressionArguments) {
    const expressionArgs = [];
    expressionArguments.forEach((expressionArg) => {
        if (expressionArg === null) {
            throw new Error(`Unsupported null argument supplied`);
        }
        switch (expressionArg.type) {
            case 'ArrayExpression':
                const arrayExpression = expressionArg;
                const arrayArgs = parseArrayExpression(arrayExpression);
                expressionArgs.push(arrayArgs);
                break;
            case 'Literal':
                const literal = expressionArg;
                expressionArgs.push(literal.value);
                break;
            case 'Identifier':
                const singleIdentifier = expressionArg;
                expressionArgs.push(new MablSymbol_1.MablSymbol(singleIdentifier.name));
                break;
            case 'MemberExpression':
                const memberExpression = expressionArg;
                if (expressionArg.object.type === 'MemberExpression') {
                    const chainedVariableExpression = memberExpressionChainBuilder(memberExpression);
                    const property = memberExpression.property;
                    expressionArgs.push(new MablSymbol_1.MablSymbol(`${chainedVariableExpression}.${property.name}`));
                }
                else {
                    const identifier = memberExpression.object;
                    const property = memberExpression.property;
                    expressionArgs.push(new MablSymbol_1.MablSymbol(`${identifier.name}.${property.name}`));
                }
                break;
            case 'ObjectExpression':
                expressionArgs.push(parseObjectExpression(expressionArg));
                break;
            default:
                throw new Error(`Unsupported argument supplied`);
        }
    });
    return expressionArgs;
}
function memberExpressionChainBuilder(memberExpression) {
    if (memberExpression.object.type === 'MemberExpression') {
        const memberExpressProp = memberExpression.object.property;
        return `${memberExpressionChainBuilder(memberExpression.object)}.${memberExpressProp.name}`;
    }
    const rootIdentifier = memberExpression.object;
    return rootIdentifier.name;
}
function parseObjectExpression(expression) {
    const finalObj = {};
    expression.properties
        .filter((property) => !!property.value)
        .map((property) => property)
        .forEach((property) => {
        let key;
        let value;
        switch (property.value.type) {
            case 'UnaryExpression':
                key = property.key;
                value = property.value;
                const operator = value.operator;
                const rawValue = Number(value.argument.raw);
                if (operator === '-') {
                    value = -Math.abs(rawValue);
                }
                else {
                    throw Error(`Cannot parse UnaryExpression ${property}`);
                }
                finalObj[key.name] = value;
                break;
            case 'Literal':
                key =
                    property.key.type === 'Identifier'
                        ?
                            property.key
                        :
                            property.key;
                value = property.value;
                if (property.key.type === 'Identifier') {
                    key = property.key;
                    finalObj[key.name] = value.value;
                }
                else {
                    key = property.key;
                    finalObj[key.value] = value.value;
                }
                break;
            case 'ArrayExpression':
                const arrayExpression = property.value;
                const arrayArgs = parseArrayExpression(arrayExpression);
                if (property.key.type === 'Identifier') {
                    key = property.key;
                    finalObj[key.name] = arrayArgs;
                }
                else {
                    key = property.key;
                    finalObj[key.value] = arrayArgs;
                }
                break;
            case 'ObjectExpression':
                key = property.key;
                value = parseObjectExpression(property.value);
                finalObj[key.name || key.value] = value;
        }
    });
    return finalObj;
}
function parseArrayExpression(arrayExpression) {
    let arrayArgs = [];
    arrayExpression.elements.forEach((element) => {
        arrayArgs = [
            ...arrayArgs,
            ...getArgumentsFromCallExpressionArgs([element]),
        ];
    });
    return arrayArgs;
}
function removeCommentsAndGetDisabledIndices(mablscript) {
    const disabledIndices = [];
    const lines = [];
    mablscript.split('\n').forEach((line, index) => {
        if (line.startsWith('//')) {
            disabledIndices.push(index);
            line = line.substring(2);
        }
        lines.push(line);
    });
    const updatedScript = lines.join('\n');
    return { updatedScript, disabledIndices };
}
function parseMablScriptIntoSteps(flow) {
    let loadedSteps = [];
    if (flow.json_steps?.steps) {
        const isMobile = flow.flow_type === typescript_api_client_1.TestTypeEnum.Mobile;
        loadedSteps = interpretStepsFromObjects(flow.json_steps.steps, isMobile);
    }
    else if (flow.script) {
        const { updatedScript, disabledIndices } = removeCommentsAndGetDisabledIndices(flow.script);
        const parsed = parseMablScript(updatedScript);
        loadedSteps = loadMablScriptIntoSteps(parsed);
        loadedSteps
            .filter((_step, index) => disabledIndices.includes(index))
            .forEach((step) => step.setDisabled(true));
    }
    applyStepDescriptionsAndAnnotations(loadedSteps, flow);
    return loadedSteps;
}
function extractInputVariables(steps) {
    return (0, MablAction_1.distinctStrings)(steps.flatMap((step) => step.getInputVariables()));
}
function extractOutputVariables(steps) {
    return (0, MablAction_1.distinctStrings)(steps.flatMap((step) => step.getOutputVariables()));
}
function parseMablScriptIntoV2Step(script) {
    if (!script) {
        throw new Error('Unable to parse step with invalid script');
    }
    const parsedMablscriptStep = parseMablScriptIntoSteps({
        script,
    });
    const stepAsObject = parsedMablscriptStep[0].getFormattedStep();
    let [parsedStep] = interpretStepsFromObjects([stepAsObject], true);
    if (parsedStep.getStepName() === 'UnimplementedStep') {
        [parsedStep] = interpretStepsFromObjects([stepAsObject], false);
    }
    return parsedStep;
}
function getQueryIds(flows, testType) {
    if (testType !== typescript_api_client_1.TestTypeEnum.Browser) {
        return [];
    }
    const querySteps = flows.flatMap((flow) => parseMablScriptIntoSteps(flow).filter(DatabaseQueryStep_1.isDatabaseQueryStep));
    return uniqueArray(querySteps.map(getSnippetIdFromStep).filter(isDefined));
}
function getSnippetIdFromStep(step) {
    let jsDescriptor;
    if ((0, EvaluateJavaScriptStep_1.isEvaluateJavaScriptStep)(step)) {
        jsDescriptor = step.evaluateJsAction.javaScript;
    }
    else if ((0, IfConditionStep_1.isIfConditionStep)(step) || (0, ElseIfConditionStep_1.isElseIfConditionStep)(step)) {
        if ((0, JavaScriptAction_1.isJavaScriptActionDescriptor)(step.primaryAction)) {
            jsDescriptor = step.primaryAction.javaScript;
        }
    }
    else if ((0, CreateVariableStep_1.isCreateVariableStep)(step)) {
        if (step.generationType === CreateVariableStepDescriptor_1.VariableGenerator.JAVASCRIPT &&
            (0, JavaScriptAction_1.isJavaScriptActionDescriptor)(step.descriptor.generator)) {
            jsDescriptor = step.descriptor.generator.javaScript;
        }
    }
    else if ((0, DatabaseQueryStep_1.isDatabaseQueryStep)(step)) {
        jsDescriptor = step.descriptor.snippet;
    }
    else if ((0, CreateVariableMobileStep_1.isCreateVariableMobileStep)(step)) {
        if ((0, JavaScriptAction_1.isJavaScriptActionDescriptor)(step.descriptor.generator)) {
            jsDescriptor = step.descriptor.generator.javaScript;
        }
    }
    if ((jsDescriptor && (0, SnippetsDescriptor_1.isReusableSnippetDescriptor)(jsDescriptor)) ||
        (0, SnippetsDescriptor_1.isLegacyReusableSnippetDescriptor)(jsDescriptor)) {
        return jsDescriptor.snippetInvariantId;
    }
    return undefined;
}
function isDefined(value) {
    return value !== undefined;
}
function uniqueArray(array) {
    return Array.from(new Set(array));
}
function getSnippetIdsFromJsonFlow(flow) {
    const steps = interpretStepsFromObjects(flow.json_steps?.steps ?? [], true);
    return getSnippetIdsFromSteps(steps);
}
function getSnippetIdsFromMablscriptFlow(flow) {
    const steps = parseMablScriptIntoSteps(flow);
    return getSnippetIdsFromSteps(steps);
}
function getSnippetIdsFromSteps(steps) {
    const snippetIds = [];
    for (const step of steps) {
        if (step instanceof StepGroupStep_1.StepGroupStep) {
            snippetIds.push(...getSnippetIdsFromSteps(step.steps));
        }
        else {
            const snippetId = getSnippetIdFromStep(step);
            if (snippetId !== undefined) {
                snippetIds.push(snippetId);
            }
        }
    }
    return snippetIds;
}
function getSnippetIdsFromFlow(flow, testType) {
    if (flow.snippet_references !== undefined) {
        return flow.snippet_references.map((reference) => reference.id);
    }
    switch (testType) {
        case typescript_api_client_1.TestTypeEnum.Api:
            return [];
        case typescript_api_client_1.TestTypeEnum.Mobile:
            return getSnippetIdsFromJsonFlow(flow);
        case typescript_api_client_1.TestTypeEnum.Browser:
            return getSnippetIdsFromMablscriptFlow(flow);
        default:
            return [];
    }
}
function getSnippetIdsFromFlows(flows, testType) {
    return uniqueArray(flows.flatMap((flow) => getSnippetIdsFromFlow(flow, testType)));
}
