| 1845 | * @returns {ICommonObject} - The processed state object |
| 1846 | */ |
| 1847 | export const processTemplateVariables = (state: ICommonObject, finalOutput: any): ICommonObject => { |
| 1848 | if (!state || Object.keys(state).length === 0) { |
| 1849 | return state |
| 1850 | } |
| 1851 | |
| 1852 | const newState = { ...state } |
| 1853 | |
| 1854 | for (const key in newState) { |
| 1855 | const stateValue = newState[key].toString() |
| 1856 | if (stateValue.includes('{{ output') || stateValue.includes('{{output')) { |
| 1857 | // Handle simple output replacement (with or without spaces) |
| 1858 | if (stateValue === '{{ output }}' || stateValue === '{{output}}') { |
| 1859 | newState[key] = finalOutput |
| 1860 | continue |
| 1861 | } |
| 1862 | |
| 1863 | // Handle JSON path expressions like {{ output.updated }} or {{output.updated}} |
| 1864 | // eslint-disable-next-line |
| 1865 | const match = stateValue.match(/\{\{\s*output\.([\w\.]+)\s*\}\}/) |
| 1866 | if (match) { |
| 1867 | try { |
| 1868 | // Parse the response if it's JSON |
| 1869 | const jsonResponse = typeof finalOutput === 'string' ? JSON.parse(finalOutput) : finalOutput |
| 1870 | // Get the value using lodash get |
| 1871 | const path = match[1] |
| 1872 | const value = get(jsonResponse, path) |
| 1873 | newState[key] = value ?? stateValue // Fall back to original if path not found |
| 1874 | } catch (e) { |
| 1875 | // If JSON parsing fails, keep original template |
| 1876 | newState[key] = stateValue |
| 1877 | } |
| 1878 | } else { |
| 1879 | // Handle simple {{ output }} replacement for backward compatibility |
| 1880 | newState[key] = newState[key].replaceAll('{{ output }}', finalOutput) |
| 1881 | } |
| 1882 | } |
| 1883 | } |
| 1884 | |
| 1885 | return newState |
| 1886 | } |
| 1887 | |
| 1888 | /** |
| 1889 | * Parse JSON body with comprehensive error handling and cleanup |