({
script,
context,
}: {
script: string;
context: RequestContext;
})
| 18 | |
| 19 | const executeCurlRequest = (options: unknown) => curlRequest(options as Parameters<typeof curlRequest>[0]); |
| 20 | export const runScript = async ({ |
| 21 | script, |
| 22 | context, |
| 23 | }: { |
| 24 | script: string; |
| 25 | context: RequestContext; |
| 26 | }): Promise<RequestContext> => { |
| 27 | // console.log(script); |
| 28 | const scriptConsole = getNewConsole(); |
| 29 | |
| 30 | const executionContext = await initInsomniaObject(context, scriptConsole.log, executeCurlRequest); |
| 31 | |
| 32 | const evalInterceptor = (script: string) => { |
| 33 | invariant(script && typeof script === 'string', 'eval is called with invalid or empty value'); |
| 34 | const result = eval(script); |
| 35 | return result; |
| 36 | }; |
| 37 | |
| 38 | const AsyncFunction = (async () => {}).constructor; |
| 39 | const executeScript = AsyncFunction( |
| 40 | 'insomnia', |
| 41 | 'require', |
| 42 | 'console', |
| 43 | 'eval', |
| 44 | '_', |
| 45 | 'setTimeout', |
| 46 | // disable these as they are not supported in web or existing implementation |
| 47 | 'setImmediate', |
| 48 | 'queueMicrotask', |
| 49 | 'process', |
| 50 | ` |
| 51 | const $ = insomnia; |
| 52 | ${script}; |
| 53 | return insomnia;`, |
| 54 | ); |
| 55 | |
| 56 | const mutatedInsomniaObject = await executeScript( |
| 57 | executionContext, |
| 58 | requireInterceptor, |
| 59 | scriptConsole, |
| 60 | evalInterceptor, |
| 61 | _, |
| 62 | proxiedSetTimeout, |
| 63 | ); |
| 64 | if (mutatedInsomniaObject == null || !(mutatedInsomniaObject instanceof InsomniaObject)) { |
| 65 | throw new Error('insomnia object is invalid or script returns earlier than expected.'); |
| 66 | } |
| 67 | const mutatedContextObject = mutatedInsomniaObject.toObject(); |
| 68 | const updatedRequest = mergeRequests(context.request, mutatedContextObject.request); |
| 69 | const updatedSettings = mergeSettings(context.settings, mutatedContextObject.request); |
| 70 | const updatedCertificates = mergeClientCertificates(context.clientCertificates, mutatedContextObject.request); |
| 71 | const updatedCookieJar = mergeCookieJar(context.cookieJar, mutatedContextObject.cookieJar); |
| 72 | |
| 73 | await fs.promises.appendFile(context.timelinePath, scriptConsole.dumpLogs()); |
| 74 | |
| 75 | // console.log('mutatedInsomniaObject', mutatedContextObject); |
| 76 | // console.log('context', context); |
| 77 |
nothing calls this directly
no test coverage detected