@browserstack/ai-sdk-node
Version:
Browserstack integrations
1 lines • 79.8 kB
JavaScript
'use strict';const a0_0x54a514=a0_0x43a8;function a0_0x43a8(_0xaa0691,_0x4c941b){const _0x12ac5d=a0_0x12ac();return a0_0x43a8=function(_0x43a8f4,_0x4f2060){_0x43a8f4=_0x43a8f4-0x83;let _0x293f53=_0x12ac5d[_0x43a8f4];return _0x293f53;},a0_0x43a8(_0xaa0691,_0x4c941b);}(function(_0x2a854c,_0x1292db){const _0x27f030=a0_0x43a8,_0x322f0d=_0x2a854c();while(!![]){try{const _0x1e10c6=parseInt(_0x27f030(0x9d))/0x1+parseInt(_0x27f030(0x94))/0x2*(-parseInt(_0x27f030(0x10a))/0x3)+-parseInt(_0x27f030(0xfb))/0x4+-parseInt(_0x27f030(0x83))/0x5*(parseInt(_0x27f030(0x103))/0x6)+-parseInt(_0x27f030(0xec))/0x7+-parseInt(_0x27f030(0x119))/0x8*(parseInt(_0x27f030(0xda))/0x9)+parseInt(_0x27f030(0xfd))/0xa*(parseInt(_0x27f030(0xed))/0xb);if(_0x1e10c6===_0x1292db)break;else _0x322f0d['push'](_0x322f0d['shift']());}catch(_0x44bdd5){_0x322f0d['push'](_0x322f0d['shift']());}}}(a0_0x12ac,0x5d4d9));var require$$0$2=require(a0_0x54a514(0xea)),require$$0$1=require(a0_0x54a514(0xe0)),require$$0$3=require('fs'),require$$1=require(a0_0x54a514(0x117));function getDefaultExportFromCjs(_0x560f7d){const _0x2556e0=a0_0x54a514;return _0x560f7d&&_0x560f7d[_0x2556e0(0x102)]&&Object['prototype'][_0x2556e0(0x92)][_0x2556e0(0x101)](_0x560f7d,_0x2556e0(0xaf))?_0x560f7d[_0x2556e0(0xaf)]:_0x560f7d;}function formatLogData$1(_0x1e68a8){const _0x190c8f=a0_0x54a514;return'['+_0x1e68a8['level']+_0x190c8f(0xbc)+_0x1e68a8[_0x190c8f(0x8f)]+'/'+_0x1e68a8[_0x190c8f(0xe6)]+']\x20'+_0x1e68a8[_0x190c8f(0xf9)];}let ConsoleLogger$1=class ConsoleLogger{constructor(){const _0x3c6d30=a0_0x54a514;this[_0x3c6d30(0x85)]=console;}[a0_0x54a514(0xc5)](_0x435087){const _0x4a3e49=a0_0x54a514;this[_0x4a3e49(0x85)][_0x4a3e49(0xbe)](formatLogData$1(_0x435087));}[a0_0x54a514(0xd0)](_0x2d097a){const _0x24132f=a0_0x54a514;this[_0x24132f(0x85)][_0x24132f(0xd0)](formatLogData$1(_0x2d097a));}[a0_0x54a514(0x111)](_0x113f78){const _0xe3ef2=a0_0x54a514;this[_0xe3ef2(0x85)]['error'](formatLogData$1(_0x113f78));}};var console_1={'ConsoleLogger':ConsoleLogger$1};function formatLogData(_0x2457c8){const _0x31a494=a0_0x54a514;return'['+_0x2457c8[_0x31a494(0xa6)]+_0x31a494(0xbc)+_0x2457c8[_0x31a494(0x8f)]+'/'+_0x2457c8['kind']+']\x20'+_0x2457c8[_0x31a494(0xf9)];}let CollectorLogger$1=class CollectorLogger{constructor(){this['driver']={'log':()=>{},'warn':()=>{},'error':()=>{}},this['logMap']={};}[a0_0x54a514(0xc5)](_0x3c5780,_0x4e1e23){const _0x38467f=a0_0x54a514;this[_0x38467f(0x85)][_0x38467f(0xbe)](formatLogData(_0x3c5780));if(_0x4e1e23)this[_0x38467f(0xa4)](_0x4e1e23,_0x3c5780);}[a0_0x54a514(0xd0)](_0x55e53a,_0x18c6a9){const _0x1f6010=a0_0x54a514;this[_0x1f6010(0x85)][_0x1f6010(0xd0)](formatLogData(_0x55e53a));if(_0x18c6a9)this[_0x1f6010(0xa4)](_0x18c6a9,_0x55e53a);}['error'](_0x5d4719,_0x3b3690){const _0x4f3f7e=a0_0x54a514;this['driver'][_0x4f3f7e(0x111)](formatLogData(_0x5d4719));if(_0x3b3690)this[_0x4f3f7e(0xa4)](_0x3b3690,_0x5d4719);}[a0_0x54a514(0xa4)](_0x3586ad,_0x2da967){const _0x26bc2e=a0_0x54a514;if(this['logMap'][_0x3586ad])this[_0x26bc2e(0xdd)][_0x3586ad][_0x26bc2e(0xe5)](_0x2da967);else this['logMap'][_0x3586ad]=[_0x2da967];}};var collectorLogger={'CollectorLogger':CollectorLogger$1};const {ConsoleLogger}=console_1,{CollectorLogger}=collectorLogger;let LOGGER_BASE=new CollectorLogger();function stringifyLog(_0x157b47){const _0x283306=a0_0x54a514;if(_0x157b47 instanceof Error)return _0x157b47['toString']()+',\x20trace:\x20'+_0x157b47[_0x283306(0x106)];const _0x1a8ad0=typeof _0x157b47;switch(_0x1a8ad0){case'string':return _0x157b47;case _0x283306(0xce):return _0x157b47;default:return JSON[_0x283306(0x9e)](_0x157b47);}}class AISDKLogger{constructor(_0x16d5e2){const _0x26c543=a0_0x54a514;this[_0x26c543(0x8f)]=_0x16d5e2;}[a0_0x54a514(0xc5)]({kind:_0x1643d3,requestId:_0x187cbf},..._0x58f3c1){const _0x41b231=a0_0x54a514,_0x4c9e01=this.#prepLogData(_0x58f3c1,_0x1643d3);LOGGER_BASE[_0x41b231(0xc5)](_0x4c9e01,_0x187cbf);}[a0_0x54a514(0xd0)]({kind:_0x521cd2,requestId:_0x3a4623},..._0x4421c7){const _0x32b8e1=this.#prepLogData(_0x4421c7,_0x521cd2,'warn');LOGGER_BASE['info'](_0x32b8e1,_0x3a4623);}['error']({kind:_0x4065c3,requestId:_0x202215},..._0x57b9c6){const _0x18fdb0=a0_0x54a514,_0x4e2da3=this.#prepLogData(_0x57b9c6,_0x4065c3,'error');LOGGER_BASE[_0x18fdb0(0xc5)](_0x4e2da3,_0x202215);}#prepLogData(_0x1c4633,_0x57b1fa,_0xaf25a8=a0_0x54a514(0xc5)){const _0x216f13=a0_0x54a514,_0x5cbc86=[];for(const _0x42cd4e of _0x1c4633){_0x5cbc86[_0x216f13(0xe5)](stringifyLog(_0x42cd4e));}return{'kind':_0x57b1fa,'module':this[_0x216f13(0x8f)],'message':''+_0x5cbc86[_0x216f13(0xd2)]('\x20'),'level':_0xaf25a8};}}function getLogger$a(_0x21516f=a0_0x54a514(0x113)){return new AISDKLogger(_0x21516f);}function getLogsForRequestId$1(_0x131557){const _0x4a5c88=a0_0x54a514;return LOGGER_BASE[_0x4a5c88(0xdd)][_0x131557];}function setLoggerBase(_0xa48ff8){const _0x8393c4=a0_0x54a514;switch(_0xa48ff8){case'console':LOGGER_BASE=new ConsoleLogger();break;case _0x8393c4(0x100):LOGGER_BASE=new CollectorLogger();break;default:throw new Error('unknown\x20logger\x20base.');}}var logger$a={'getLogger':getLogger$a,'setLoggerBase':setLoggerBase,'getLogsForRequestId':getLogsForRequestId$1};const axios$1=require$$0$1,REQUEST_TIMOUT=0x186a0,MAX_RETRY_COUNT=0x3,axiosInstance=axios$1[a0_0x54a514(0xa3)]({'timeout':REQUEST_TIMOUT});function setInstanceAuthInterceptors(_0x6cba28,_0x2e6067){const _0x1c745e=a0_0x54a514;let _0x473922=null;const _0x110505=async()=>{if(_0x473922)return _0x473922;const _0xa250d5=await _0x2e6067();return _0x473922=_0xa250d5,_0xa250d5;};_0x110505()[_0x1c745e(0xee)](()=>null);const _0xb22f74=async _0x5ef57b=>{const _0x22bbfd=_0x1c745e;if(_0x5ef57b[_0x22bbfd(0x9f)]?.[_0x22bbfd(0xf7)]===0x191){_0x473922=null;const _0x964a5d=_0x5ef57b[_0x22bbfd(0xdb)];_0x964a5d[_0x22bbfd(0xe1)]=(_0x964a5d['retryCount']||0x0)+0x1;if(_0x964a5d[_0x22bbfd(0xe1)]>MAX_RETRY_COUNT)return Promise[_0x22bbfd(0xbb)](_0x5ef57b);try{const _0x16958e=await _0x110505();_0x964a5d[_0x22bbfd(0xa8)][_0x22bbfd(0x89)]=_0x22bbfd(0x10e)+_0x16958e;}catch(_0x260ecd){return Promise[_0x22bbfd(0xbb)](_0x260ecd);}return _0x6cba28(_0x964a5d);}return Promise[_0x22bbfd(0xbb)](_0x5ef57b);},_0x55c7f5=async _0x202f7d=>{const _0x4d635e=_0x1c745e;let _0x4992f4=_0x473922;if(!_0x4992f4)try{_0x4992f4=await _0x110505();}catch(_0x18975c){return Promise[_0x4d635e(0xbb)](_0x18975c);}const _0x11800b=_0x202f7d;return _0x11800b[_0x4d635e(0xa8)][_0x4d635e(0x89)]=_0x4d635e(0x10e)+_0x4992f4,_0x11800b;};_0x6cba28[_0x1c745e(0xb2)]['response']['use'](_0x48edad=>_0x48edad,_0xb22f74),_0x6cba28[_0x1c745e(0xb2)]['request']['use'](_0x55c7f5);}function createAxiosInstanceWithTokenGenerator$1(_0x3cec1e){const _0x2e702d=a0_0x54a514,_0x34c15a=axios$1[_0x2e702d(0xa3)]({'timeout':REQUEST_TIMOUT});return setInstanceAuthInterceptors(_0x34c15a,_0x3cec1e),_0x34c15a;}function initAxios(_0x3b8aba){setInstanceAuthInterceptors(axiosInstance,_0x3b8aba);}var axiosInstance_1={'axiosInstance':axiosInstance,'initAxios':initAxios,'createAxiosInstanceWithTokenGenerator':createAxiosInstanceWithTokenGenerator$1},name=a0_0x54a514(0xcf),version=a0_0x54a514(0xad),description=a0_0x54a514(0x10f),main=a0_0x54a514(0xca),types=a0_0x54a514(0x116),scripts$1={'test':'mocha','release-tag':a0_0x54a514(0x115),'playwright-pi':'npx\x20playwright\x20install','format:check':a0_0x54a514(0xd4),'format:write':a0_0x54a514(0xb3),'lint:check':a0_0x54a514(0xb8),'lint:fix':a0_0x54a514(0xac),'bundle':a0_0x54a514(0xd1),'build:scripts':'vite\x20build','test:ext-run':a0_0x54a514(0x84),'test:direct-run':a0_0x54a514(0x10c)},author='',license='SEE\x20LICENSE\x20IN\x20LICENSE.md',dependencies={'axios':a0_0x54a514(0xc8),'uuid':'9.0.1'},devDependencies={'@rollup/plugin-commonjs':a0_0x54a514(0xd3),'@rollup/plugin-json':a0_0x54a514(0xe4),'@rollup/plugin-node-resolve':a0_0x54a514(0xfa),'@rollup/plugin-url':a0_0x54a514(0x9c),'@types/selenium-webdriver':a0_0x54a514(0xf4),'eslint':a0_0x54a514(0x112),'eslint-config-airbnb-base':a0_0x54a514(0x109),'eslint-config-prettier':a0_0x54a514(0xc0),'eslint-plugin-import':a0_0x54a514(0xc9),'extract-zip':a0_0x54a514(0xc6),'javascript-obfuscator':a0_0x54a514(0xd5),'mocha':a0_0x54a514(0x86),'rollup':a0_0x54a514(0x99),'rollup-plugin-copy':a0_0x54a514(0x110),'selenium-webdriver':'^4.21.0','vite':a0_0x54a514(0xd6)},require$$0={'name':name,'version':version,'description':description,'main':main,'types':types,'scripts':scripts$1,'author':author,'license':license,'dependencies':dependencies,'devDependencies':devDependencies};const pkg=require$$0,config$3={'TCG_SUGGEST_STEP_ENDPOINT':a0_0x54a514(0x98),'TCG_AUTO_HEAL_ENDPOINT':a0_0x54a514(0xde),'TCG_STEP_CONFIG_ENDPOINT':a0_0x54a514(0xf0),'TCG_EVENT_COLLECTOR_ENDPOINT':'/events/collector','PACKAGE_VERSION':pkg[a0_0x54a514(0xb9)],'RETRIES_LIMIT':0x1,'TCG_CALLS_LIMIT':0x5,'ITERATION_LIMIT':0x14};var config_1=config$3;const PLATFORMS$1={'desktop':'desktop','mobile':'mobile','app':'app'},CONNECTORS$2={'extension':a0_0x54a514(0x118),'direct':a0_0x54a514(0xaa)},SUPPORTED_PLATFORMS$1=[PLATFORMS$1[a0_0x54a514(0x107)],PLATFORMS$1[a0_0x54a514(0x95)]];var consts={'PLATFORMS':PLATFORMS$1,'SUPPORTED_PLATFORMS':SUPPORTED_PLATFORMS$1,'CONNECTORS':CONNECTORS$2};const {SUPPORTED_PLATFORMS,PLATFORMS,CONNECTORS:CONNECTORS$1}=consts,CONFIG={'domain':'https://tcg.browserstack.com','platform':PLATFORMS[a0_0x54a514(0x107)],'connector':CONNECTORS$1['extension'],'client':a0_0x54a514(0xcb)};let AISDK$1=class AISDK{static[a0_0x54a514(0xa2)]({domain:_0x241bde,platform:_0x21819b,connector:_0x58c6a9,client:_0x4adafd}){const _0x891cc=a0_0x54a514;if(_0x241bde){if(_0x241bde[_0x891cc(0x88)]('/'))_0x241bde=_0x241bde[_0x891cc(0xdc)](0x0,_0x241bde[_0x891cc(0x10b)]-0x1);CONFIG[_0x891cc(0xa5)]=_0x241bde;}_0x21819b&&SUPPORTED_PLATFORMS[_0x891cc(0xc4)](_0x21819b)&&(CONFIG[_0x891cc(0x8b)]=_0x21819b,CONFIG[_0x891cc(0x8b)]===PLATFORMS[_0x891cc(0x95)]&&(CONFIG['connector']=CONNECTORS$1[_0x891cc(0xaa)]));if(_0x58c6a9&&Object[_0x891cc(0xbf)](CONNECTORS$1)[_0x891cc(0xc4)](_0x58c6a9)){if(CONFIG[_0x891cc(0x8b)]===_0x891cc(0x95))CONFIG[_0x891cc(0xd7)]=CONNECTORS$1['direct'];else CONFIG[_0x891cc(0xd7)]=_0x58c6a9;}if(_0x4adafd)CONFIG['client']=_0x4adafd;}static[a0_0x54a514(0xa9)]({browserName:_0x1a9f60,version:_0x143b30}){const _0x25a716=a0_0x54a514,_0x4ce41d={'chrome':0x5c,'microsoftedge':0x5c,'edge':0x5c,'firefox':0x48};if(!_0x1a9f60)return![];if(!_0x4ce41d[_0x1a9f60])return![];if(!_0x143b30||_0x143b30===_0x25a716(0xc1))return!![];const _0x5e0ec5=_0x143b30[_0x25a716(0x105)]('.')['at'](0x0);if(!_0x5e0ec5||!_0x5e0ec5[_0x25a716(0xcd)](/^[0-9]+$/))return![];const _0x7d9410=parseInt(_0x5e0ec5,0xa);if(Number['isNaN'](_0x7d9410)||_0x4ce41d[_0x1a9f60]>_0x7d9410)return![];return!![];}};function getConfig$2(){const _0x453b4c=a0_0x54a514,_0x5e01f4={};for(const _0x5d80e1 of Object[_0x453b4c(0xbd)](CONFIG)){_0x5e01f4[_0x5d80e1]=CONFIG[_0x5d80e1];}return _0x5e01f4;}var config$2={'AISDK':AISDK$1,'getConfig':getConfig$2};const {v4:uuidv4$6}=require$$0$2,{createAxiosInstanceWithTokenGenerator}=axiosInstance_1,config$1=config_1,sdkConfig=config$2;let TCGService$5=class TCGService{constructor(_0x332afe){const _0x3c8ec9=a0_0x54a514;this[_0x3c8ec9(0xe0)]=createAxiosInstanceWithTokenGenerator(_0x332afe);}async['callTCG'](_0x3c2fe7,_0x1ebf56,{requestId:requestId=uuidv4$6(),controller:controller=new AbortController(),method:method=a0_0x54a514(0xeb)}){const _0x414885=a0_0x54a514;if(method)method=method[_0x414885(0xf5)]();const _0x18996b=sdkConfig[_0x414885(0x96)](),_0x25e822=_0x18996b['domain']+_0x3c2fe7;this[_0x414885(0xf3)](_0x3c2fe7,_0x1ebf56);const _0x5e325b={'headers':{'x-bstack-client-version':config$1['PACKAGE_VERSION'],'x-bstack-client':_0x18996b['client'],'x-bstack-traceRequestId':requestId},'signal':controller['signal']};try{let _0x39d969=null;if(method===_0x414885(0xeb))_0x39d969=await this[_0x414885(0xe0)]['post'](_0x25e822,_0x1ebf56,_0x5e325b);else{if(method==='get')_0x39d969=await this[_0x414885(0xe0)][_0x414885(0xb1)](_0x25e822,_0x5e325b);else throw new Error(_0x414885(0xcc));}return _0x39d969?.[_0x414885(0xc3)];}catch(_0x2de528){if(_0x2de528[_0x414885(0xe2)]==='CanceledError'){const _0x4b8b6e={'message':'User\x20cancelled\x20request'};throw _0x4b8b6e;}throw _0x2de528;}}['encodeRequestBody'](_0x45e567,_0x5d0f55){const _0xa5843b=a0_0x54a514;_0x45e567[_0xa5843b(0xc4)](_0xa5843b(0xff))&&(_0x5d0f55['browserContext']=Buffer['from'](_0x5d0f55[_0xa5843b(0xd8)])[_0xa5843b(0xa0)]('base64'),_0x5d0f55[_0xa5843b(0x8a)]=!![]);}};var tcg={'TCGService':TCGService$5};const {getLogger:getLogger$9}=logger$a,{TCGService:TCGService$4}=tcg;let EXTENSION_CACHE=null;const logger$9=getLogger$9(a0_0x54a514(0xab));let AIPlatform$2=class AIPlatform{static async[a0_0x54a514(0x90)](){const _0x316a71=a0_0x54a514;if(EXTENSION_CACHE)return logger$9[_0x316a71(0xc5)]({'kind':'getPlatformExtensions'},_0x316a71(0x114),EXTENSION_CACHE),EXTENSION_CACHE;const _0x5265b8=new TCGService$4(()=>'');logger$9[_0x316a71(0xc5)]({'kind':_0x316a71(0x8c)},_0x316a71(0x8e));const _0x1d8798=await _0x5265b8[_0x316a71(0xa1)](_0x316a71(0x9b),null,{'method':'get'});return EXTENSION_CACHE=_0x1d8798[_0x316a71(0xc3)],_0x1d8798['data'];}};var platform={'AIPlatform':AIPlatform$2};let NLToStepsError$9=class NLToStepsError extends Error{constructor(_0x1ee429,_0x4837b7=a0_0x54a514(0xf1),_0x1a37ed=a0_0x54a514(0x87)){const _0x2eddbd=a0_0x54a514;super('['+_0x4837b7+_0x2eddbd(0xfc)+_0x1ee429),this[_0x2eddbd(0x8f)]=_0x4837b7,this[_0x2eddbd(0xe2)]=_0x1a37ed;}},NLToStepsCancelledError$1=class NLToStepsCancelledError extends NLToStepsError$9{constructor(_0x1d6dd4,_0x3f620d='NLToSteps'){const _0x5af818=a0_0x54a514;super(_0x1d6dd4,_0x3f620d,_0x5af818(0xba));}},NLToStepsContextGeneratorError$1=class NLToStepsContextGeneratorError extends NLToStepsError$9{constructor(_0x43d99b,_0x5caa89=a0_0x54a514(0xf1)){const _0x2bbcc3=a0_0x54a514;super(_0x43d99b,_0x5caa89,_0x2bbcc3(0xf2));}};class NLToStepsServiceError extends NLToStepsError$9{constructor(_0xd74a76,_0x190981=a0_0x54a514(0xf1)){const _0x3db5e4=a0_0x54a514;super(_0xd74a76,_0x190981,_0x3db5e4(0x8d));}}function processError$1(_0x3f46b0,_0x4538cc){const _0x365a15=a0_0x54a514,_0x21d8eb={'failReason':_0x365a15(0xe8),'errorName':''};if(_0x3f46b0 instanceof NLToStepsCancelledError$1)_0x21d8eb['failReason']=_0x4538cc?_0x4538cc+_0x365a15(0xf6):'Cancelled\x20by\x20caller',_0x21d8eb[_0x365a15(0xef)]=_0x3f46b0[_0x365a15(0xe2)];else _0x3f46b0 instanceof NLToStepsError$9?(_0x21d8eb[_0x365a15(0xef)]=_0x3f46b0[_0x365a15(0xe2)]||'NLToStepsError',_0x21d8eb[_0x365a15(0xb6)]=_0x3f46b0[_0x365a15(0xf9)]||_0x365a15(0xb4)):(_0x21d8eb[_0x365a15(0xef)]=_0x365a15(0x108),_0x21d8eb[_0x365a15(0xb6)]=_0x365a15(0xa7)+(_0x3f46b0&&_0x3f46b0[_0x365a15(0xf9)]?_0x3f46b0[_0x365a15(0xf9)]:_0x365a15(0xb0)));return _0x21d8eb;}var errors={'NLToStepsError':NLToStepsError$9,'NLToStepsCancelledError':NLToStepsCancelledError$1,'NLToStepsContextGeneratorError':NLToStepsContextGeneratorError$1,'NLToStepsServiceError':NLToStepsServiceError,'processError':processError$1};const {getConfig:getConfig$1}=config$2;async function wait(_0x2f8673){return new Promise(_0x384e77=>setTimeout(_0x384e77,_0x2f8673));}async function waitSeconds$4(_0x1d20b9){return wait(_0x1d20b9*0x3e8);}function copyObjectWithout$1(_0x11d617,_0x19f94b){const _0x34f7a0=a0_0x54a514,_0x38e706={};return Object[_0x34f7a0(0xbd)](_0x11d617)['filter'](_0x4ee274=>!_0x19f94b[_0x34f7a0(0xc4)](_0x4ee274))['forEach'](_0x405488=>{_0x38e706[_0x405488]=_0x11d617[_0x405488];}),_0x38e706;}function buildEDSEvent$1(_0x19aafa,_0x1b83b6){const _0x2819e4=a0_0x54a514;if(!_0x19aafa)return{};const _0x43863f=getConfig$1(),_0x313aa4=JSON[_0x2819e4(0x10d)](JSON[_0x2819e4(0x9e)](_0x19aafa)),_0x27df93={'actions':_0x313aa4[_0x2819e4(0xb5)][_0x2819e4(0x93)],'requestId':_0x313aa4[_0x2819e4(0xb5)]['id'],'state':_0x313aa4[_0x2819e4(0xb5)][_0x2819e4(0xf8)],'request':{..._0x313aa4[_0x2819e4(0xb5)],'browser':_0x1b83b6,'client':_0x43863f[_0x2819e4(0x104)]}};return delete _0x27df93['request'][_0x2819e4(0x93)],delete _0x27df93[_0x2819e4(0xb5)][_0x2819e4(0xf8)],delete _0x27df93[_0x2819e4(0xb5)]['recordedMetrics'],delete _0x27df93[_0x2819e4(0xb5)][_0x2819e4(0xae)],_0x27df93;}function cleanRunStatus(_0x1f6d7c){const _0x30731d=a0_0x54a514,_0x38c39f=[_0x30731d(0x9a),'recordedLogs',_0x30731d(0xe3),_0x30731d(0xc7),_0x30731d(0xdf),_0x30731d(0x93)];_0x38c39f[_0x30731d(0xe9)](_0x30bd75=>{if(_0x1f6d7c&&_0x1f6d7c[_0x30bd75])delete _0x1f6d7c[_0x30bd75];});}var utils={'wait':wait,'waitSeconds':waitSeconds$4,'copyObjectWithout':copyObjectWithout$1,'buildEDSEvent':buildEDSEvent$1,'cleanRunStatus':cleanRunStatus};const {v4:uuidv4$5}=require$$0$2,{getLogger:getLogger$8}=logger$a,{NLToStepsError:NLToStepsError$8}=errors,{TCGService:TCGService$3}=tcg,{waitSeconds:waitSeconds$3,copyObjectWithout}=utils,MODULE$1='ExtensionConnector',logger$8=getLogger$8(MODULE$1),MAX_WAIT_RETRIES=0x2;let ExtensionConnector$1=class ExtensionConnector{constructor(_0x72dc70){const _0x566188=a0_0x54a514;this['request']=_0x72dc70,this['frameworkImpl']=_0x72dc70[_0x566188(0xe3)],this['extensionRequest']=null,this['started']=![],this[_0x566188(0x97)]=![],this[_0x566188(0xf7)]={'state':'RUNNING','request':this[_0x566188(0xb5)]},this[_0x566188(0x91)]=![],this[_0x566188(0xc2)]={},this[_0x566188(0xb7)]=new TCGService$3(_0x72dc70['authMethod']),this[_0x566188(0xd9)]=0x0;}async[a0_0x54a514(0xfe)](){const _0x521028=a0_0x54a514;if(this[_0x521028(0xe7)])return this.#getProgressV2();this[_0x521028(0xe7)]=!![],this['extensionRequest']=copyObjectWithout(this[_0x521028(0xb5)],[_0x521028(0xdf),'authMethod',_0x521028(0xe3)]);const startResponse=await this.frameworkImpl.executeScript(request=>{window.postMessage({type:'nls-message-start',data:request});return true;},[this.extensionRequest]);if(!startResponse){throw new NLToStepsError$8('unable to initiate objective execution.');}while(!this.complete){const currentStatus=await this.#waitForProgress();logger$8.info({'kind':'runInstance',requestId:this.request.id},'recieved new status',currentStatus.state,currentStatus.failReason);if(currentStatus)this.#setStatus(currentStatus);if(currentStatus.state!=='RUNNING'){switch(currentStatus.state){case'FAILED':this.complete=true;throw new NLToStepsError$8(`failed while running NL to Steps session with error: ${currentStatus.failReason}`);case'SUCCESS':this.complete=true;break;case'WAITING':await this.#handleWaitAction(currentStatus.currentWaitAction);break;}}if(!this.complete)await waitSeconds$3(2);}return this.status;}async cancel(reason='User cancellation'){logger$8.info({'kind':'cancel',requestId:this.request.id},'cancellation requested with reason: ',reason);if(this.complete){return this.status;}this.failed=true;try{await this.frameworkImpl.executeScript(data=>{window.postMessage({type:'nls-request-cancel',data:{id:data.id,reason:data.reason}});},[{id:this.request.id,reason}]);const waitTill=Date.now()+60000;let newStatus=this.status;while((!newStatus||newStatus.state!=='FAILED')&&Date.now()<waitTill){newStatus=await this.#getProgressV2();await waitSeconds$3(3);}this.#setStatus(newStatus);}catch(e){logger$8.error({kind:'cancel',requestId:this.request.id},'failed while cancelling the nls instance',this.request.id,e);}return this.status;}async #sendWaitResponse(id,response,success=true){logger$8.info({'kind':'sendWaitResponse',requestId:this.request.id},`sending response for waitAction: ${id}`);await this.frameworkImpl.executeScript(wr=>{window.postMessage({type:'nls-message-waitResponse',data:{id:wr.id,response:wr.response,success:wr.success}});},[{id,response,success}]);return true;}async #getProgressV2(){try{const progress=await this.frameworkImpl.executeScript(requestId=>{window.postMessage({type:'nls-get-progress',data:requestId});return new Promise((resolve,reject)=>{let status=null;const requestStatListener=e=>{status=e.detail.status;resolve(status);window.removeEventListener(`nls-response-${requestId}`,requestStatListener);};window.addEventListener(`nls-response-${requestId}`,requestStatListener);setTimeout(()=>{if(!status){reject(new Error('timeout while fetching status for request.'));}window.removeEventListener(`nls-response-${requestId}`,requestStatListener);},10000);});},[this.request.id]);return progress;}catch(e){logger$8.error({kind:'getProgress',requestId:this.request.id},'failed while getting progress',e);}return null;}async #handleWaitAction(waitAction){if(!this.waitMap[waitAction.id]){this.waitMap[waitAction.id]={req:waitAction,res:null,tries:0};}if(this.waitMap[waitAction.id].res){return true;}if(this.waitMap[waitAction.id].tries>=MAX_WAIT_RETRIES){logger$8.error({kind:'waitActionRetryExceeded',requestId:this.request.id},'retries exhuasted for wait action',{type:waitAction.type,id:waitAction.id});this.#sendWaitResponse(waitAction.id,null,false);throw new NLToStepsError$8('wait action retries exhuasted, forcing failure',MODULE$1);}try{logger$8.info({'kind':'waitActionTry'},'trying to process waitAction',{type:waitAction.type,id:waitAction.id});this.waitMap[waitAction.id].tries+=1;let waitResponse=null;let stepStatus=false;let inputResponse=null;let tcgResponse;const waitActionReq=waitAction.request;switch(waitAction.type){case'TCG':this.tcgCallCounter+=1;tcgResponse=await this.tcgService.callTCG(waitActionReq.endpoint,waitActionReq.request,{method:waitActionReq.method,requestId:`${this.request.id}:::${this.tcgCallCounter}`});logger$8.info({'kind':'tcgResponse',requestId:this.request.id},tcgResponse);waitResponse=tcgResponse;break;case'BEFORE_STEP':case'STEP':stepStatus=await this.request.waitCallback(waitAction);waitResponse=stepStatus;break;case'INPUT':inputResponse=await this.request.waitCallback(waitAction);waitResponse=inputResponse;break;case'NETWORK':await this.request.waitCallback({id:uuidv4$5(),type:waitActionReq.type});break;default:logger$8.warn({kind:'handleWaitAction',requestId:this.request.id},'unknown action type in wait action',waitAction);waitResponse=this.request.waitCallback(waitAction);}this.#sendWaitResponse(waitAction.id,waitResponse);this.waitMap[waitAction.id].res=waitResponse;return true;}catch(e){logger$8.error({kind:'waitActionTry',requestId:this.request.id},'failed while trying to process wait action',{type:waitAction.type,id:waitAction.id},e);if(waitAction.type==='TCG'){throw e;}return false;}}async #waitForProgress(){const startTime=Date.now();let progress=null;while(!progress&&Date.now()<startTime+60000){progress=await this.#getProgressV2();}if(!progress){throw new NLToStepsError$8('failed while waiting for objective progress',MODULE$1);}return progress;}#setStatus(givenStat){this.status.state=givenStat.state;this.status.failReason=givenStat.failReason;this.status.errorName=givenStat.errorName;this.status.request=givenStat;}};var extension={ExtensionConnector:ExtensionConnector$1};const ACTION_NAMES={click:'click',hover:'hover',type:'type',extractValue:'referUserToElement',visualValidate:'visualValidate',textValidate:'textValidate',elementExists:'elementExists'};const DEFAULT_SUPPORTED_ACTIONS$1=[ACTION_NAMES.click,ACTION_NAMES.type,ACTION_NAMES.hover];const CUSTOM_ACTIONS$1=[ACTION_NAMES.extractValue,ACTION_NAMES.visualValidate,ACTION_NAMES.textValidate,ACTION_NAMES.elementExists];const ALL_SUPPORTED_ACTIONS$1=[...DEFAULT_SUPPORTED_ACTIONS$1,...CUSTOM_ACTIONS$1];const OS$4={iOS:'iOS',android:'Android'};const Browsers={chrome:'chrome',safari:'safari',firefox:'firefox'};const CLICK_TRIM_EXCEPTION_ELEMS$1=[{nodeName:'select',notValidForAttributes:[]},{nodeName:'input',notValidForAttributes:[{key:'readonly',value:''},{key:'readonly',value:'true'}]}];var constants={ACTION_NAMES,DEFAULT_SUPPORTED_ACTIONS:DEFAULT_SUPPORTED_ACTIONS$1,CUSTOM_ACTIONS:CUSTOM_ACTIONS$1,ALL_SUPPORTED_ACTIONS:ALL_SUPPORTED_ACTIONS$1,OS:OS$4,Browsers,CLICK_TRIM_EXCEPTION_ELEMS:CLICK_TRIM_EXCEPTION_ELEMS$1};const aiFunctionName='generate';const namingCriteria$1=' criteria: alpha num with underscores and hiphens, no spaces, name cannot be generate';const inputTypes={variable:'variable',function:'function',ai:'ai',text:'text'};const inputTypeKeyMap={[inputTypes.variable]:'var',[inputTypes.function]:'func',[inputTypes.ai]:'func'};function getInputContent(input,type){const inputTypeKey=inputTypeKeyMap[type];if(!inputTypeKey){throw new Error('Unable to find the given input type key');}const rgx=new RegExp(`\\[\\[${inputTypeKey}:(.+)\\]\\]`);const matches=input.match(rgx);if(matches){return matches[1];}return null;}function parseVariable(varString){if(!varString)return null;let varContent=getInputContent(varString,inputTypes.variable);if(varContent===null)return null;if(varContent.match(/['"]+/g))varContent=varContent.replace(/['"]+/g,'');return{type:inputTypes.variable,value:varContent};}function parseFunctionArgs(argString){if(!argString)return[];const regex=/(\w+)\s*=\s*(?:'([^']+)'|"([^"]+)"|([^,]+))/g;const parsedArgs=[];let match=regex.exec(argString);while(match!==null){const name=match[1];const value=match[2]||match[3]||match[4];let parsedValue;if(value==='true'){parsedValue=true;}else if(value==='false'){parsedValue=false;}else if(!Number.isNaN(parseInt(value,10))){parsedValue=parseInt(value,10);}else{parsedValue=value;}parsedArgs.push({name:name.trim(),value:parsedValue});match=regex.exec(argString);}return parsedArgs;}function parseFunction(funcString){if(!funcString)return null;const funcDefinition=getInputContent(funcString,inputTypes.function);if(funcDefinition===null)return null;const funcGroups=funcDefinition.match(/^([A-Za-z0-9-_]+)(?:\((.*?)\))?$/);if(!funcGroups)return null;const funcName=funcGroups[1];let funcArgString=funcGroups[2];funcArgString=funcArgString?funcArgString.trim():'';if(!funcName)return null;const def={type:'function',value:funcName};def.args=parseFunctionArgs(funcArgString);return def;}function parseValueInputs$1(valueString,variables,functions){const baseRgx=/\[\[(var|func?):(.+?)?\]\]/ig;if(!valueString.match(baseRgx)){return null;}const allInputGroups=[];let inputMatch=baseRgx.exec(valueString);while(inputMatch!=null){allInputGroups.push(inputMatch);inputMatch=baseRgx.exec(valueString);}const finalInputs=[];let lastEnd=-1;for(inputMatch of allInputGroups){if(lastEnd+1!==inputMatch.index){const textInput={type:inputTypes.text,value:valueString.substring(lastEnd+1,inputMatch.index)};finalInputs.push(textInput);}const parsedInput=inputMatch[1]===inputTypeKeyMap[inputTypes.function]?parseFunction(inputMatch[0]):parseVariable(inputMatch[0]);if(parsedInput.type===inputTypes.function&&parsedInput.value===aiFunctionName){const descriptionArg=parsedInput.args.find(x=>x.name==='description');const defaultValArg=parsedInput.args.find(x=>x.name==='default');const aiInput={type:inputTypes.ai,value:descriptionArg?descriptionArg.value:undefined,defaultValue:defaultValArg?defaultValArg.value:undefined};if(!aiInput.value)aiInput.value=aiInput.defaultValue||'random string';finalInputs.push(aiInput);}else{finalInputs.push(parsedInput);}lastEnd=inputMatch.index+inputMatch[0].length-1;}if(lastEnd+1!==valueString.length){const textInput={type:inputTypes.text,value:valueString.substring(lastEnd+1,valueString.length)};finalInputs.push(textInput);}for(const input of finalInputs){if(input.type===inputTypes.variable){if(!variables||!variables[input.value]){return null;}input.value=variables[input.value].id;}if(input.type===inputTypes.function&&(!functions||!functions.find(x=>x.name===input.value))){return null;}}return finalInputs;}function isValidName(given){return given.match(/^[a-zA-Z0-9\-_]+$/)&&!given.match(/^generate$/i)&&given.length<=50;}function areVariablesValid(variables){for(const variable of variables){if(!isValidName(variable)){return{valid:false,message:`${variable} is not a valid variable name`};}}return{valid:true};}function validateFunctions$2(functionDefs){for(const def of functionDefs){if(!isValidName(def.name)){return{valid:false,message:`${JSON.stringify(def)} - definition invalid name invalid`};}if(def.description&&def.description.length>100){def.description=def.description.substring(0,100);}const argDefs=[];for(const arg of def.args){if(!arg.type)arg.type='string';if(!isValidName(arg.name)){return{valid:false,message:`${JSON.stringify(def)} - definition invalid. arg name: ${arg.name} for function ${def.name} invalid`};}if(!arg.type.match(/^(string|boolean|number)?$/i)){return{valid:false,message:`${JSON.stringify(def)} - definition invalid. arg type ${arg.type} for arg ${arg.name} of function ${def.name} invalid`};}argDefs.push(`${arg.name}: ${arg.type}`);}def.definition=`${def.name}(${argDefs.join(', ')})`;}return{valid:true};}function getVariableMap$1(variables){const identifierMap={};for(const variable of variables){let varName=variable&&variable.name&&variable.name.replace(/[^a-zA-Z0-9-_]+/g,'_');if(!varName||!varName.match(/[a-zA-Z]+/)){console.error(`failed to process variable, invalid / incomplete name: ${JSON.stringify(variable)}`);continue;}if(identifierMap[varName]){const originalVarname=varName;let count=1;while(identifierMap[varName]&&count<=20){varName=`${originalVarname}_${count}`;count+=1;}if(count>20){console.error(`ignoring variable, too many duplicates: ${JSON.stringify(variable)}`);continue;}}identifierMap[varName]=variable;}return identifierMap;}var inputs={parseVariable,parseFunction,parseValueInputs:parseValueInputs$1,areVariablesValid,validateFunctions:validateFunctions$2,getVariableMap:getVariableMap$1,namingCriteria:namingCriteria$1};const {NLToStepsError:NLToStepsError$7}=errors;let ApiCallLimitExceededError$2=class ApiCallLimitExceededError extends NLToStepsError$7{constructor(message){super(message,'NLToSteps','ApiCallLimitExceededError');}};var ApiCallLimitExceededError_1=ApiCallLimitExceededError$2;const {NLToStepsError:NLToStepsError$6}=errors;let RetryLimitExceededError$2=class RetryLimitExceededError extends NLToStepsError$6{constructor(message){super(message,'NLToSteps','RetryLimitExceededError');}};var RetryLimitExceededError_1=RetryLimitExceededError$2;const {NLToStepsError:NLToStepsError$5}=errors;let SuggestionEndedError$2=class SuggestionEndedError extends NLToStepsError$5{constructor(message){super(message,'NLToSteps','SuggestionEndedError');}};var SuggestionEndedError_1=SuggestionEndedError$2;const {NLToStepsError:NLToStepsError$4}=errors;let TestSuggestionEndedError$1=class TestSuggestionEndedError extends NLToStepsError$4{constructor(message){super(message,'NLToSteps','TestSuggestionEndedError');}};var TestSuggestionEndedError_1=TestSuggestionEndedError$1;const {NLToStepsError:NLToStepsError$3}=errors;let TcgCallFailureError$2=class TcgCallFailureError extends NLToStepsError$3{constructor(message){super(message,'NLToSteps','TcgCallFailureError');}};var TcgCallFailureError_1=TcgCallFailureError$2;const ApiCallLimitExceededError$1=ApiCallLimitExceededError_1;const RetryLimitExceededError$1=RetryLimitExceededError_1;const SuggestionEndedError$1=SuggestionEndedError_1;const TestSuggestionEndedError=TestSuggestionEndedError_1;const TcgCallFailureError$1=TcgCallFailureError_1;var exceptions={ApiCallLimitExceededError:ApiCallLimitExceededError$1,RetryLimitExceededError:RetryLimitExceededError$1,SuggestionEndedError:SuggestionEndedError$1,TestSuggestionEndedError,TcgCallFailureError:TcgCallFailureError$1};const metricNames$1={nlToStepsApiLatency:'nl_to_steps_tcg_latency',nlToStepsActionLatency:'nl_to_steps_action_latency',nlToStepsCtxLatency:'nl_to_steps_ctx_latency',nlToStepsTotalLatency:'nl_to_steps_total_latency',nlToStepsCycleLatency:'nl_to_steps_cycle_latency',nlToStepsCycleSteps:'nl_to_steps_cycle_steps',nlToStepsTcgFailure:'nl_to_steps_tcg_failure',nlToStepsCtxFailure:'nl_to_steps_ctx_failure',nlToStepsRetryFailure:'nl_to_steps_retry_failure',nlToStepsMaxCallsFailure:'nl_to_steps_max_calls_failure',nlToStepsTCGFailAction:'nl_to_steps_tcg_fail_action'};const tagNames$1={result:'result'};var metrics={metricNames:metricNames$1,tagNames:tagNames$1};const {v4:uuidv4$4}=require$$0$2;const config=config_1;const {ApiCallLimitExceededError,RetryLimitExceededError,SuggestionEndedError,TcgCallFailureError}=exceptions;const {metricNames,tagNames}=metrics;const {validateFunctions:validateFunctions$1,namingCriteria,parseValueInputs}=inputs;const {getLogger:getLogger$7}=logger$a;const {CLICK_TRIM_EXCEPTION_ELEMS}=constants;const {NLToStepsContextGeneratorError}=errors;const logger$7=getLogger$7('NLStepSuggestionV2');function findOffset(origin,height){return origin-origin%height;}let BrowserstackStepSuggestionV2$1=class BrowserstackStepSuggestionV2{constructor({prompt,testId=uuidv4$4(),supportedActions=['click','type','hover'],contextGenerator,actionHandler,requestId,waitForNetworkCalls}){this.prompt=prompt;this.supportedActions=supportedActions;this.requestId=requestId;this.suggestedActions=[];this.suggestedActionsState=[];this.testId=testId;this.lastFailedActions=[];this.currentAction=-1;this.shouldComplete=false;this.retries=0;this.tcgCallCount=0;this.complete=false;this.times={start:Date.now(),stepSuggestTime:null,cycleStart:null};this.contextGenerator=contextGenerator;this.actionHandler=actionHandler;this.waitForNetworkCalls=waitForNetworkCalls;}setComplete(){this.complete=true;this.recordTimeMetrics(metricNames.nlToStepsTotalLatency,this.times.start,Date.now());this.recordCustomLogs({prompt:this.prompt,actions:this.suggestedActionsState,logType:'NLtoStepsPerformedActions'});}recordTimeMetrics(name,start,end,tags={}){try{const value=end-start;this.actionHandler.recordMetrics({name,value,tags});}catch(e){logger$7.warn({kind:'browserstackStepSuggestionV2',requestId:this.requestId},'error while recording metrics',e);}}recordCustomLogs(logDetails){try{this.actionHandler.recordLogs(logDetails);}catch(e){logger$7.warn('error while recording logs',e);}}recordValueMetrics(name,value,tags={}){try{this.actionHandler.recordMetrics({name,value,tags});}catch(error){logger$7.error({kind:'browserStepsSuggestionV2MetricRecorderError'},'Error while recording metric using action Handler');}}async suggestAction({previousResultStatus=true,onBeforeFetch=async()=>{},requestId=uuidv4$4(),variables={},functions=[],useAIGenerator=false}){const actionIdentifier=uuidv4$4();if(this.complete){throw new SuggestionEndedError('suggestions ended for the set prompt.');}this.lastRequestId=requestId;if(this.times.stepSuggestTime!==null){this.recordTimeMetrics(metricNames.nlToStepsActionLatency,this.times.stepSuggestTime,Date.now(),{[tagNames.result]:previousResultStatus?'pass':'fail'});}if(this.suggestedActions[this.currentAction]){this.suggestedActions[this.currentAction].status=previousResultStatus?'SUCCESS':'FAIL';}if(!previousResultStatus){this.shouldComplete=false;this.lastFailedActions.push(this.suggestedActions[this.currentAction]?.raw_action);}else{this.retries=0;this.lastFailedActions=[];}this.currentAction+=1;while(!previousResultStatus&&this.currentAction<this.suggestedActions.length){this.suggestedActions[this.currentAction].status='SKIP';this.currentAction+=1;}if(this.currentAction>=this.suggestedActions.length){if(this.times.cycleStart!==null){this.recordTimeMetrics(metricNames.nlToStepsCycleLatency,this.times.cycleStart,Date.now());}this.times.cycleStart=Date.now();if(this.shouldComplete){this.setComplete();return null;}if(this.retries>=config.RETRIES_LIMIT){this.suggestedActionsState.push({actionType:'SDK ERROR: RetryLimitExceededError',identifier:actionIdentifier,appTime:Date.now()});this.setComplete(true);logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},'Retries limit exceeded');this.recordValueMetrics(metricNames.nlToStepsRetryFailure,1);throw new RetryLimitExceededError('Retries limit exceeded');}if(!previousResultStatus){this.retries+=1;logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},`\n\nRetry: ${this.retries}\n`);}await this.getActionsFromTCG(onBeforeFetch,requestId,this.suggestedActions.length,actionIdentifier,variables,functions,useAIGenerator);}await this.attachWindowProperties(this.suggestedActions[this.currentAction]);this.times.stepSuggestTime=Date.now();if(this.shouldComplete&&!this.suggestedActions[this.currentAction]?.action){this.suggestedActionsState.push({actionType:'SDK ERROR: TCG returned empty actions array',identifier:actionIdentifier,appTime:Date.now()});this.setComplete();return null;}if(!this.shouldComplete&&!this.suggestedActions[this.currentAction]?.action){this.suggestedActionsState.push({actionType:'SDK ERROR: Suggestion not matching with the website context',identifier:actionIdentifier,appTime:Date.now()});this.setComplete();throw new Error('Suggestion not matching with the website context');}const suggestedAction=this.suggestedActions[this.currentAction]?.action;const suggestedRawAction=this.suggestedActions[this.currentAction]?.raw_action;const suggestionId=this.suggestedActions[this.currentAction]?.suggestionId;const parsedInput=suggestedRawAction.input?parseValueInputs(suggestedRawAction.input,variables,functions):undefined;if(parsedInput){const varResponse=await this.actionHandler.waitForInput({input:suggestedAction.element.input_value,parsedInput});logger$7.info({'kind':'processInputs'},`Parsed input value response ${varResponse} for repr: ${JSON.stringify(parsedInput)}`);if(varResponse){suggestedAction.parsedValueInputs=parsedInput;suggestedAction.element.input_value=varResponse;}}this.suggestedActionsState.push({actionType:suggestedAction?.action_type,identifier:actionIdentifier,appTime:Date.now()});const suggestionToReturn={...suggestedAction,suggestionMeta:{identifier:actionIdentifier,rawAction:suggestedRawAction,suggestionId}};return suggestionToReturn;}async getContext(){try{const parseStart=Date.now();const generatedContext=await this.contextGenerator.getContext();this.recordTimeMetrics(metricNames.nlToStepsCtxLatency,parseStart,Date.now());return generatedContext;}catch(e){logger$7.error({kind:'browserstackStepSuggestionV2',requestId:this.requestId},'error while generating context',e);this.recordValueMetrics(metricNames.nlToStepsCtxFailure,1);throw new NLToStepsContextGeneratorError('error while generating context','ContextGenerator');}}async getActionsFromTCG(onBeforeFetch,requestId,alreadySuggestedActionsCount,actionIdentifier,variableMap,functions,useGeneratorFunction){const functionValidationResult=validateFunctions$1(functions);if(!functionValidationResult.valid){throw new Error(functionValidationResult.message+namingCriteria||`invalid functions${namingCriteria}`);}const sendingFunctions=functions.map(x=>({definition:x.definition,description:x.description}));const generatedContext=await this.getContext();if(onBeforeFetch)await onBeforeFetch();const [actions,suggestionId]=await this.callTCG(generatedContext,`${requestId}:::${alreadySuggestedActionsCount}`,this.prompt,this.contextGenerator.getURL(),this.contextGenerator.isBlockingPopupFound(),actionIdentifier,variableMap,sendingFunctions,useGeneratorFunction);logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},`Suggested actions returned from TCG: ${actions.length}`);this.recordValueMetrics(metricNames.nlToStepsCycleSteps,actions.length);this.suggestedActions=this.suggestedActions.concat(this.constructResponse(actions).map(action=>({status:'PENDING',action:action.action,raw_action:action.raw_action,suggestionId})));}async callTCG(generateContext,requestId,prompt,pageUrl,isBlockingPopupDetected,actionIdentifier,variableMap,functions,useGeneratorFunction){if(this.tcgCallCount>=config.TCG_CALLS_LIMIT){this.recordValueMetrics(metricNames.nlToStepsMaxCallsFailure,1);this.suggestedActionsState.push({actionType:'SDK ERROR: ApiCallLimitExceededError',identifier:actionIdentifier,appTime:Date.now()});this.setComplete(true);throw new ApiCallLimitExceededError('TCG API calls limit exceeded');}this.tcgCallCount+=1;logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},'Calling TCG to get suggested actions');const variables=Object.keys(variableMap);const requestBody={browserContext:generateContext.join(''),objective:prompt,isContextEncoded:false,url:pageUrl,previousActions:this.suggestedActions.filter(action=>action.status==='SUCCESS').map(action=>action.raw_action),lastFailedActions:this.lastFailedActions,supportedActions:this.supportedActions,isBlockingPopupDetected,variables,functions,useGeneratorFunction};try{if(this.waitForNetworkCalls){await this.actionHandler.callNetworkHandlers({type:'WAIT_BEFORE_TCG_CALL'});}const startTime=Date.now();const response=await this.actionHandler.callTCG(config.TCG_SUGGEST_STEP_ENDPOINT,'POST',requestBody,100000);logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},`Time taken to get data from TCG = ${(Date.now()-startTime)/1000} s\n`);this.recordTimeMetrics(metricNames.nlToStepsApiLatency,startTime,Date.now());if(this.waitForNetworkCalls){await this.actionHandler.callNetworkHandlers({type:'WAIT_AFTER_TCG_CALL'});}return[response.data,response.suggestion_id];}catch(error){logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},'Error while calling TCG',error);this.recordValueMetrics(metricNames.nlToStepsTcgFailure,1);this.suggestedActionsState.push({actionType:`SDK ERROR: ${error.message} ${error.stack}`,identifier:actionIdentifier,appTime:Date.now()});this.setComplete(true);this.currentAction-=1;throw new TcgCallFailureError('BStack AI Services Call failed');}}constructResponse(actions){const response=[];let contextGeneratorFailures=0;for(let idx=0;idx<actions.length;idx+=1){const action=actions[idx];const actionType=action.action;let inputValue=action.value;if(actionType==='fail'){this.shouldComplete=true;this.recordValueMetrics(metricNames.nlToStepsTCGFailAction,1);this.suggestedActionsState.push({actionType:'SDK ERROR: TCGFailActionError',identifier:uuidv4$4(),appTime:Date.now()});throw new Error('fail action received from TCG');}if(actionType==='complete'){this.shouldComplete=true;continue;}const element=this.contextGenerator.getElement(parseInt(action.id,10));if(element==null){contextGeneratorFailures+=1;logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},`Cannot find the element suggested by LLM. Skipping current action ${actionType} ${JSON.stringify(action)}`);continue;}const attributesDetails={tag_name:element.nodeName.toUpperCase(),attributes:this.contextGenerator.getAllAttributes(action.id)};const selectorsObj=element.nodeName==='select'?{selectTagOptionAttributes:[{innerText:inputValue}]}:{};if(element.nodeName==='select'&&inputValue){inputValue=this.contextGenerator.getSelectOptionValue(action.id,inputValue);}const actionDetails={action_type:actionType,aiSDKMeta:element.aiSDKMeta,element:{xpath:element.xpath,coordinates:{x:element.coordinates.x,y:element.coordinates.y},input_value:inputValue,selectorsObj,...attributesDetails},parsedValueInputs:null};if(actionType==='referUserToElement'){actionDetails.identifier=action.identifier;actionDetails.element.tag_name=element.nodeName.toUpperCase();}response.push({action:actionDetails,raw_action:action});const isClickTrimExceptionElem=CLICK_TRIM_EXCEPTION_ELEMS.find(obj=>{if(obj.nodeName!==element.nodeName)return false;const exceptionAttr=obj.notValidForAttributes.find(attr=>element.attributes[attr.key]===attr.value);if(exceptionAttr)return false;return true;});if(actionType==='click'&&!isClickTrimExceptionElem){const nextAction=actions[idx+1];if(nextAction&&nextAction.action==='complete'){continue;}logger$7.info({kind:'browserstackStepSuggestionV2_skipRestOnClick',requestId:this.requestId},`Performing ${actionType} action on ${JSON.stringify(action)}, context will most likely change, so skipping the rest of the actions.`);break;}}if(contextGeneratorFailures>0){this.shouldComplete=false;}return response;}async attachWindowProperties(givenAction){logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},'attaching window properties');const startTime=Date.now();let windowProperties;try{windowProperties=await this.contextGenerator.getWindowProperties();}catch(error){logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},'Failed fetching window properties. Error:',error);return null;}logger$7.info({kind:'browserstackStepSuggestionV2',requestId:this.requestId},`Time taken to fetch window properties = ${(Date.now()-startTime)/1000} s\n`);const elementYCoordinate=givenAction?.action?.element?.coordinates?.y;if(elementYCoordinate!==undefined){givenAction.action.window_properties={width:windowProperties.winWidth,height:windowProperties.winHeight,outer_width:windowProperties.winOuterWidth,outer_height:windowProperties.winOuterHeight,device_scale_factor:windowProperties.devicePixelRatio,scroll:{x_offset:0,y_offset:findOffset(elementYCoordinate,windowProperties.winHeight)}};}return null;}registerActionStatus(performedDetails){const actionIdentifier=performedDetails.identifier;const matchedActions=this.suggestedActionsState.filter(eachSuggestedAction=>eachSuggestedAction.identifier===actionIdentifier);if(matchedActions.length<1){return;}matchedActions[0].performedSuccessfully=performedDetails.performedSuccessfully;matchedActions[0].performedTime=Date.now();}};var browserstackStepSuggestionV2={BrowserstackStepSuggestionV2:BrowserstackStepSuggestionV2$1};const {BrowserstackStepSuggestionV2}=browserstackStepSuggestionV2;const {waitSeconds:waitSeconds$2}=utils;const {CUSTOM_ACTIONS}=constants;function a0_0x12ac(){const _0x573861=['195414xwEAVB','mobile','getConfig','complete','/browser-steps/suggest-steps','^3.29.4','recordedMetrics','/platform/desktop-extension','^8.0.2','745221zTctzZ','stringify','response','toString','callTCG','configure','create','pushLogToRequestId','domain','level','unexpected\x20error\x20while\x20executing\x20objective,\x20CAUSE:\x20','headers','checkExtensionCompatibility','direct','AISDK','eslint\x20--fix\x20.','1.5.17','recordedLogs','default','unknown\x20error','get','interceptors','prettier\x20--write\x20.','error\x20while\x20executing\x20objective.','request','failReason','tcgService','eslint\x20.','version','NLToStepsCancelledError','reject',']\x20[','keys','log','values','^9.1.0','latest','waitMap','data','includes','info','^2.0.1','authMethod','^1.7.4','^2.29.1','index.js','bstack','unsupported\x20method,\x20add\x20if\x20needed\x20in\x20callTCG','match','number','@browserstack/ai-sdk-node','warn','rm\x20-rf\x20dist\x20&&\x20rollup\x20-c\x20&&\x20node\x20publish-script.js\x20&&\x20javascript-obfuscator\x20./dist/index.js\x20--output\x20./dist/index.js','join','^25.0.8','prettier\x20--check\x20.','^4.0.0','^5.2.12','connector','browserContext','tcgCallCounter','16758drZyoI','config','substring','logMap','/browser-steps/auto-heal','waitCallback','axios','retryCount','name','frameworkImplementation','^6.1.0','push','kind','started','unknown','forEach','uuid','post','1053220jeFMCc','99HIMVvd','catch','errorName','/browser-steps/config','NLToSteps','NLToStepsContextGeneratorError','encodeRequestBody','^4.1.23','toLowerCase',',\x20Aborted','status','state','message','^15.2.3','2009204bllWbQ',']:\x20','1652930cQensD','runInstance','suggest-steps','collector','call','__esModule','674754tdtUJn','client','split','stack','desktop','UnknownError','^15.0.0','15FqwMnW','length','node\x20integration/nls-direct.js','parse','Bearer\x20','AI\x20/\x20ML\x20feature\x20integrations','^3.5.0','error','^8.56.0','AISDKNode','returning\x20cached\x20extension\x20info','sh\x20./scripts/update_version.sh','types','path','extension','632FRecyP','25ZeOHrW','node\x20integration/nls-ext.js','driver','^10.3.0','NLToStepsError','endsWith','Authorization','isContextEncoded','platform','getPlatformExtensions','NLToStepsServiceError','calling\x20TCG\x20for\x20extension\x20info','module','getDesktopExtensions','failed','hasOwnProperty','actions'];a0_0x12ac=function(){return _0x573861;};return a0_0x12ac();}const {getLogger:getLogger$6}=logger$a;const {ITERATION_LIMIT}=config_1;const {NLToStepsCancelledError,NLToStepsError:NLToStepsError$2}=errors;const logger$6=getLogger$6('NLToStepsExecutor');let NLToStepsExecutor$1=class NLToStepsExecutor{constructor({objective,player,contextGenerator,onWait,actionHandler,variables,functions,useAIGenerator,waitAfterActions,waitForCustomActions,waitForNetworkCalls,domUtils,requestId}){this.objective=objective;this.variables=variables;this.functions=functions;this.useAIGenerator=useAIGenerator;this.isCompleted=false;this.domUtils=domUtils;this.cancelled=false;this.onWait=onWait||(()=>{});this.player=player;this.contextGenerator=contextGenerator;this.requestId=requestId;this.actionHandler=actionHandler;this.previousActionSuccess=true;this.browserstackStepSuggestion=new BrowserstackStepSuggestionV2({prompt:this.objective,contextGenerator:this.contextGenerator,actionHandler:this.actionHandler,requestId,waitForNetworkCalls});this.waitAfterActions=waitAfterActions;this.waitForCustomActions=waitForCustomActions;this.waitForNetworkCalls=waitForNetworkCalls;this.performedSteps=[];}async execute(){let iterations=0;while(!this.isCompleted&&iterations<ITERATION_LIMIT&&!this.cancelled){await this.domUtils.waitForPageLoad();iterations+=1;const action=await this.getNextAction();if(this.cancelled)throw new NLToStepsCancelledError('execution is marked cancelled');if(action.complete){this.isCompleted=true;break;}else if(action.fail){break;}this.onWait();if(this.waitAfterActions||this.waitForCustomActions&&CUSTOM_ACTIONS.includes(action.action_type)){logger$6.info({'kind':'executor',requestId:this.requestId},`waiting for pre step-exec action. action_type: ${action.action_type}, waitAfter: ${this.waitAfterActions}, wait for custom actions: ${this.waitForCustomActions}`);const beforeActionStat=await this.actionHandler.doBeforeStepAction(action);logger$6.info({'kind':'executor',requestId:this.requestId},'pre-step wait action execution report: ',beforeActionStat);if(beforeActionStat===false){throw new NLToStepsError$2(`received invalid response for before step exec callback. reqId: ${this.requestId}`);}}const [actionStatus,playedAction,actionMeta]=await this.player.execute(action);playedAction.action={...playedAction.action,...actionMeta};ac