import inquirer from 'inquirer'; import chalk from 'chalk'; export async function getApiResponseFilterFields( responseFilters: any, ): Promise<{ filterType: string; filterKey: string; fields: string[] } | null> { // Convert responseFilters to an array const filtersArray = Object.entries(responseFilters).flatMap( ([filterType, filters]) => Object.entries(filters as any).map( ([filterKey, filterDetails]: [string, any]) => ({ filterType, filterKey, expression: filterDetails.expression, }), ), ); // Ask the user to select a filter key const { selectedFilter } = await inquirer.prompt([ { type: 'list', name: 'selectedFilter', message: 'Select the response filter key you want to process:', choices: filtersArray.map((filter, i) => ({ name: `${i + 1}. Filter Type: ${chalk.yellow(filter.filterType)}, Filter Key: ${chalk.yellow(filter.filterKey)}`, value: filter, })), }, ]); // Find the selected filter const selectedFilterDetails = filtersArray.find( (filter) => filter.filterType === selectedFilter.filterType && filter.filterKey === selectedFilter.filterKey, ); if (!selectedFilterDetails) { console.error(chalk.red('✗ Selected filter not found.')); return null; } const { filterType, filterKey, expression } = selectedFilterDetails; // Parse the expression to extract fields let fields: string[] = []; if (filterType === 'jsonata') { // Use regular expression to extract field names from JSONata expression const jsonataFieldRegex = /"([^"]+)":/g; let match; while ((match = jsonataFieldRegex.exec(expression)) !== null) { fields.push(match[1]); } } else if (filterType === 'xpath') { // Use regular expression to extract field names from XPath expression const xpathFieldRegex = /([a-zA-Z_][\w-]*)\s*:/g; let match; while ((match = xpathFieldRegex.exec(expression)) !== null) { fields.push(match[1]); } } else if (filterType === 'scriban') { console.error( chalk.red('✗ Scriban filters are not supported for field extraction.'), ); return null; } return { filterType, filterKey, fields }; }