@automationcloud/client
Advanced tools
Comparing version 1.4.3 to 1.5.0
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.AutomationCloud=e():t.AutomationCloud=e()}(self,(function(){return t={739:t=>{self,t.exports=(()=>{"use strict";var t={300:(t,e)=>{var n=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n)return n;throw new Error("unable to locate global object")}();t.exports=e=n.fetch,n.fetch&&(e.default=n.fetch.bind(n)),e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response},395:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthAgent=void 0,e.AuthAgent=class{}},614:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BasicAuthAgent=void 0;const s=n(395),r=n(20);class o extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{username:t,password:e}=this.params,n=`${t}:${e}`;return"Basic "+r.toBase64(n)}invalidate(){}}e.BasicAuthAgent=o},924:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BearerAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{prefix:t="Bearer",token:e}=this.params;return e?`${t} ${e}`:null}invalidate(){}}e.BearerAuthAgent=r},12:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(26),e),r(n(614),e),r(n(924),e),r(n(890),e),r(n(658),e)},26:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{async getHeader(){return null}invalidate(){}}e.NoAuthAgent=r},890:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthNotSupportedError=e.OAuth1Agent=void 0;const s=n(395),r=n(222);class o extends s.AuthAgent{async getHeader(t){throw new a}invalidate(){}}e.OAuth1Agent=o;class a extends r.Exception{constructor(){super("This auth agent is not supported in browser environment.")}}e.AuthNotSupportedError=a},658:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.OAuth2Agent=e.OAuth2GrantType=void 0;const r=n(458),o=s(n(91)),a=n(395);var i;!function(t){t.CLIENT_CREDENTIALS="client_credentials",t.REFRESH_TOKEN="refresh_token",t.AUTHORIZATION_CODE="authorization_code",t.PASSWORD="password"}(i=e.OAuth2GrantType||(e.OAuth2GrantType={}));class c extends a.AuthAgent{constructor(t){super(),this.params=Object.assign({fetch:o.default},t)}async getHeader(){const t=await this.getAccessToken();return t?"Bearer "+t:null}async createToken(t){const{tokenUrl:e,fetch:n}=this.params,s=new r.Request({fetch:n}),o=Object.entries(t).filter((([t,e])=>null!=e)),a=await s.send("post",e,{body:new URLSearchParams(o)}),i=await a.json();return{accessToken:i.access_token,accessExpiresIn:i.expires_in,refreshToken:i.refresh_token}}setTokens(t){const{accessToken:e,accessExpiresIn:n,refreshToken:s}=t,r=n?Date.now()+1e3*n:null;this.params.accessToken=e,this.params.expiresAt=r,s&&(this.params.refreshToken=s)}invalidate(){this.params.accessToken=null,this.params.expiresAt=null}async getAccessToken(){const t=[this.tryCachedAccessToken,this.tryRefreshToken,this.tryClientSecret];for(const e of t)try{const t=await e.call(this);if(t)return t}catch(t){this.invalidate()}return null}async tryCachedAccessToken(){const{accessToken:t,expiresAt:e,minValiditySeconds:n=300}=this.params;return t&&(null==e||e-1e3*n>Date.now())?t:null}async tryRefreshToken(){const{refreshToken:t,clientId:e,clientSecret:n}=this.params;if(!t)return null;try{const s=await this.createToken({grant_type:i.REFRESH_TOKEN,client_id:e,client_secret:n,refresh_token:t});return this.setTokens(s),s.accessToken}catch(t){throw this.params.refreshToken=null,t}}async tryClientSecret(){const{clientId:t,clientSecret:e}=this.params;if(!e)return null;const n=await this.createToken({grant_type:i.CLIENT_CREDENTIALS,client_id:t,client_secret:e});return this.setTokens(n),n.accessToken}}e.OAuth2Agent=c},222:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},91:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"!=typeof window&&window.fetch?fetch.bind(window):n(300)},863:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Response=void 0,r(n(458),e),r(n(395),e),r(n(12),e),r(n(157),e),r(n(687),e);const a=o(n(210));e.Response=a.default},458:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.RequestFailedError=e.Request=e.DEFAULT_REQUEST_CONFIG=e.NETWORK_ERRORS=void 0;const r=n(222),o=n(12),a=s(n(91));e.NETWORK_ERRORS=["EAI_AGAIN","EHOSTDOWN","EHOSTUNREACH","ECONNABORTED","ECONNREFUSED","ECONNRESET","EPIPE"],e.DEFAULT_REQUEST_CONFIG={baseUrl:"",auth:new o.NoAuthAgent,retryAttempts:4,retryDelay:500,retryDelayIncrement:500,retryStatusCodes:[429,502,503,504],authInvalidateStatusCodes:[401,403],authInvalidateInterval:6e4,headers:{},fetch:a.default},e.Request=class{constructor(t){this.authInvalidatedAt=0,this.config=Object.assign(Object.assign({},e.DEFAULT_REQUEST_CONFIG),t)}async get(t,e={}){return await this.sendJson("get",t,e)}async post(t,e={}){return await this.sendJson("post",t,e)}async put(t,e={}){return await this.sendJson("put",t,e)}async delete(t,e={}){return await this.sendJson("delete",t,e)}async sendJson(t,e,n={}){const{body:s,query:r,headers:o}=n,a=await this.send(t,e,{headers:Object.assign({"content-type":"application/json"},o),query:r,body:s?JSON.stringify(s):null}),{status:i}=a;return 204===i||"0"===a.headers.get("content-length")?null:await a.json()}async send(t,n,s={}){var r,o,a;const{fetch:i}=this.config,c=Math.max(this.config.retryAttempts+1,1);let u,l;for(let h=0;h<c;h++){let c=!1,d=this.config.retryDelay+this.config.retryDelayIncrement*h;try{const e=await this.prepareRequestSpec(t,n,s),r=await i(e.url,{method:e.method,headers:e.headers,body:e.body});if(!r.ok)throw this.config.authInvalidateStatusCodes.includes(r.status)?(c=Date.now()-this.authInvalidatedAt>this.config.authInvalidateInterval,this.authInvalidatedAt=Date.now(),d=0,this.config.auth.invalidate()):c=this.config.retryStatusCodes.includes(r.status),await this.createErrorFromResponse(e,r);return r}catch(i){const h=null===(r=i.details)||void 0===r?void 0:r.status,p=null===(o=i.details)||void 0===o?void 0:o.statusText,f={method:t,url:n,headers:null!==(a=s.headers)&&void 0!==a?a:{},status:h,statusText:p};if(c||e.NETWORK_ERRORS.includes(i.code)){u=i,l=f,this.onRetry(i,f),await new Promise((t=>setTimeout(t,d)));continue}throw this.onError(i,f),i}}throw this.onError(u,l),u}async sendRaw(t,e,n={}){const s=await this.prepareRequestSpec(t,e,n),{fetch:r}=this.config;return await r(s.url,{method:s.method,headers:s.headers,body:s.body})}async prepareRequestSpec(t,e,n={}){var s,r;const{auth:o}=this.config,{body:a}=n,i=this.prepareUrl(e,n),c=null!==(s=await o.getHeader({url:i,method:t,body:a}))&&void 0!==s?s:"";return{method:t,url:i,headers:this.mergeHeaders({"content-type":null!==(r=this.inferContentTypeFromBody(a))&&void 0!==r?r:""},this.config.headers||{},{authorization:c},n.headers||{}),body:a}}prepareUrl(t,e){var n;const{baseUrl:s}=this.config,r=s&&"/"!==s.slice(-1)?s+"/":s,o=new URL("/"===t[0]?t.slice(1):t,r||void 0);return o.search=new URLSearchParams(Object.entries(null!==(n=e.query)&&void 0!==n?n:{})).toString(),o.toString()}inferContentTypeFromBody(t){switch(!0){case null==t:return null;case t instanceof URLSearchParams:return"application/x-www-form-urlencoded";case"object"==typeof t:return"application/json";case"string"==typeof t:return"text/plain";default:return null}}mergeHeaders(...t){const e={};for(const n of t)for(const[t,s]of Object.entries(n))s&&(e[t.toLowerCase()]=s);return e}async createErrorFromResponse(t,e){return new i(t,e)}onRetry(t,e){}onError(t,e){}};class i extends r.Exception{constructor(t,e){super(`Request failed: ${e.status} ${e.statusText}`),this.details={method:t.method,url:t.url,requestHeaders:t.headers,status:e.status,statusText:e.statusText},Object.defineProperty(this,"requestSpec",{enumerable:!1,value:t}),Object.defineProperty(this,"response",{enumerable:!1,value:e})}}e.RequestFailedError=i},210:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"==typeof Response?n(300).Response:Response},157:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},20:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.toBase64=void 0,e.toBase64=function(t){return btoa(t)}},687:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.fetchMock=void 0;const r=s(n(210));e.fetchMock=function(t,e={},n){const s={called:!1,calledCount:0,params:[]},o=(o,a)=>new Promise(((i,c)=>{const u=Object.assign({status:200},t);if(s.called=!0,s.calledCount+=1,s.params.push({fullUrl:o,fetchOptions:a}),n)return c(n);i(new r.default(JSON.stringify(e),u))}));return o.spy=s,o}}},e={};return function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863)})()},729:t=>{"use strict";var e=Object.prototype.hasOwnProperty,n="~";function s(){}function r(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function o(t,e,s,o,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var i=new r(s,o||t,a),c=n?n+e:e;return t._events[c]?t._events[c].fn?t._events[c]=[t._events[c],i]:t._events[c].push(i):(t._events[c]=i,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function i(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),i.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(n?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},i.prototype.listeners=function(t){var e=n?n+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,o=s.length,a=new Array(o);r<o;r++)a[r]=s[r].fn;return a},i.prototype.listenerCount=function(t){var e=n?n+t:t,s=this._events[e];return s?s.fn?1:s.length:0},i.prototype.emit=function(t,e,s,r,o,a){var i=n?n+t:t;if(!this._events[i])return!1;var c,u,l=this._events[i],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,s),!0;case 4:return l.fn.call(l.context,e,s,r),!0;case 5:return l.fn.call(l.context,e,s,r,o),!0;case 6:return l.fn.call(l.context,e,s,r,o,a),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(t,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,s);break;case 4:l[u].fn.call(l[u].context,e,s,r);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},i.prototype.on=function(t,e,n){return o(this,t,e,n,!1)},i.prototype.once=function(t,e,n){return o(this,t,e,n,!0)},i.prototype.removeListener=function(t,e,s,r){var o=n?n+t:t;if(!this._events[o])return this;if(!e)return a(this,o),this;var i=this._events[o];if(i.fn)i.fn!==e||r&&!i.once||s&&i.context!==s||a(this,o);else{for(var c=0,u=[],l=i.length;c<l;c++)(i[c].fn!==e||r&&!i[c].once||s&&i[c].context!==s)&&u.push(i[c]);u.length?this._events[o]=1===u.length?u[0]:u:a(this,o)}return this},i.prototype.removeAllListeners=function(t){var e;return t?(e=n?n+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,t.exports=i},330:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AcRequest=e.AcApi=void 0;const s=n(739);e.AcApi=class{constructor(t){this.params=t;const e="string"==typeof t.auth?new s.BasicAuthAgent({username:t.auth}):new s.OAuth2Agent({clientId:t.auth.clientId,clientSecret:t.auth.clientSecret,tokenUrl:t.apiTokenUrl});this.request=new r({baseUrl:t.apiUrl,auth:e,retryAttempts:t.requestRetryCount,retryDelay:t.requestRetryDelay})}async createJob(t){const{serviceId:e,category:n,input:s}=t;return await this.request.post("/jobs",{body:{serviceId:e,category:n,input:s}})}async getJob(t){return await this.request.get(`/jobs/${t}`)}async getJobAccessToken(t){return(await this.request.get(`/jobs/${t}/end-user`)).token}async getJobEvents(t,e){const{data:n}=await this.request.get(`/jobs/${t}/events`,{query:{offset:e}});return n}async getJobOutput(t,e){var n;try{return await this.request.get(`/jobs/${t}/outputs/${e}`)}catch(t){if(404===(null===(n=t.details)||void 0===n?void 0:n.status))return null;throw t}}async sendJobInput(t,e,n){return await this.request.post(`/jobs/${t}/inputs`,{body:{key:e,data:n}})}async cancelJob(t){await this.request.post(`/jobs/${t}/cancel`)}async queryPreviousOutputs(t,e,n=[]){const{data:s}=await this.request.post(`/services/${t}/previous-job-outputs`,{body:{inputs:n},query:{key:e}});return s}};class r extends s.Request{async createErrorFromResponse(t,e){var n;if(null===(n=e.headers.get("content-type"))||void 0===n?void 0:n.startsWith("application/json")){const t=await e.json();if(t.name&&t.message){const e=new Error(t.message);return e.name=t.name,e.code=t.code,e.details=t.details,e}}return super.createErrorFromResponse(t,e)}}e.AcRequest=r},967:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Client=void 0;const s=n(330),r=n(909),o=n(157),a=n(894);e.Client=class{constructor(t){this.logger=console,this.config=Object.assign({apiUrl:"https://api.automationcloud.net",apiTokenUrl:"https://auth.automationcloud.net/auth/realms/automationcloud/protocol/openid-connect/token",vaultUrl:"https://vault.automationcloud.net",pollInterval:1e3,requestRetryCount:4,requestRetryDelay:500,autoTrack:!0},t),this.api=new s.AcApi({logger:this.logger,apiTokenUrl:this.config.apiTokenUrl,apiUrl:this.config.apiUrl,auth:this.config.auth,requestRetryCount:this.config.requestRetryCount,requestRetryDelay:this.config.requestRetryDelay}),this.vault=new a.Vault(this)}async getJob(t){const e=new r.Job(this);return await e.trackExisting(t),e}async queryPreviousOutput(t,e=[]){const n=await this.api.queryPreviousOutputs(this.config.serviceId,t,e);return n.length?n[0]:null}async createJob(t={}){return await this._createJob(Object.assign({category:o.JobCategory.TEST,input:{}},t))}async _createJob(t){const e=new r.Job(this,t);return await e.start(),e}}},313:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.JobTrackError=e.JobFailedError=e.JobOutputWaitError=e.JobAlreadyStartedError=e.JobNotInitializedError=void 0;const s=n(222);class r extends s.Exception{constructor(){super("Invalid state: job not yet initialized")}}e.JobNotInitializedError=r;class o extends s.Exception{constructor(t={}){super("Job is already initialized"),this.details=t}}e.JobAlreadyStartedError=o;class a extends s.Exception{constructor(t,e={}){super(t),this.message=t,this.details=e}}e.JobOutputWaitError=a;class i extends s.Exception{constructor(t){var e,n,s;super(null!==(e=null==t?void 0:t.message)&&void 0!==e?e:"Unknown error"),this.name=null!==(n=null==t?void 0:t.code)&&void 0!==n?n:"UnknownError",this.details=Object.assign({category:null!==(s=null==t?void 0:t.category)&&void 0!==s?s:"server"},null==t?void 0:t.details)}}e.JobFailedError=i;class c extends s.Exception{constructor(t){super(`Job tracking failed: ${t.message}`),this.details={cause:t}}}e.JobTrackError=c},222:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},863:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(330),e),r(n(967),e),r(n(222),e),r(n(313),e),r(n(909),e),r(n(273),e),r(n(157),e),r(n(894),e)},909:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&s(e,t,n);return r(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.Job=void 0;const a=n(729),i=o(n(313)),c=n(157);e.Job=class{constructor(t,e={}){this.client=t,this._events=new a.EventEmitter,this._inputsMap=new Map,this._outputsMap=new Map,this._state=c.JobState.CREATED,this._error=null,this._awaitingInputKey=null,this._trackPromise=null,this._jobId=null,this._jobEventOffset=0,this._isTracking=!1,this._initParams=Object.assign({category:c.JobCategory.TEST,input:{}},e)}get jobId(){if(!this._jobId)throw new i.JobNotInitializedError;return this._jobId}async start(){if(this._jobId)throw new i.JobAlreadyStartedError(this.jobId);const{category:t,input:e}=this._initParams,{serviceId:n}=this.client.config,{id:s,state:r}=await this.api.createJob({serviceId:n,category:t,input:e});this._jobId=s,this._setState(r);for(const[t,n]of Object.entries(e))this._inputsMap.set(t,{key:t,data:n});this.client.config.autoTrack&&this.startTracking()}async trackExisting(t){if(this._jobId)throw new i.JobAlreadyStartedError({jobId:this.jobId});const{state:e,category:n}=await this.api.getJob(t);this._jobId=t,this._initParams.category=n,this._setState(e),this.startTracking()}startTracking(){this._trackPromise||(this._isTracking=!0,this._trackPromise=this._track(),this._trackPromise.catch((t=>{})).then((()=>{this._isTracking=!1,this._trackPromise=null})))}stopTracking(){this._isTracking=!1}getState(){return this._state}_setState(t){const e=this._state;this._state=t,this._events.emit("stateChanged",t,e)}getErrorInfo(){return this._error}getAwaitingInputKey(){return this._awaitingInputKey}async getAccessToken(){return await this.api.getJobAccessToken(this.jobId)}async submitInput(t,e){await this.api.sendJobInput(this.jobId,t,e),this._inputsMap.set(t,{key:t,data:e})}async getOutput(t){var e;let n=null!==(e=this._outputsMap.get(t))&&void 0!==e?e:null;return n||(n=await this.api.getJobOutput(this.jobId,t),n&&this._outputsMap.set(t,n)),null==n?void 0:n.data}async waitForCompletion(){await this._trackPromise}async cancel(){await this.api.cancelJob(this.jobId)}async waitForOutputs(...t){return await this._waitFor((()=>{const e=this._checkOutputs(t);if(null!=e)return e;if(this.getState()===c.JobState.FAIL)throw new i.JobOutputWaitError("Job failed, and specified outputs were not emitted",{state:this.getState(),jobId:this.jobId});if(this.getState()===c.JobState.SUCCESS)throw new i.JobOutputWaitError("Job succeeded, but specified outputs were not emitted",{state:this.getState(),jobId:this.jobId})}))}async _waitFor(t){return new Promise(((e,n)=>{const s=()=>{try{const n=t();void 0!==n&&(o(),e(n))}catch(t){o(),n(t)}},r=t=>{o(),n(t)},o=()=>{this._events.off("trackTick",s),this._events.off("trackError",r)};this._events.on("trackTick",s),this._events.on("trackError",r),s()}))}onAwaitingInput(t,e){return this._createJobEventHandler("awaitingInput",(async n=>{if("*"===t||n===t){const s=await e(n);void 0!==s&&await this.submitInput(t,s)}}))}onOutput(t,e){return this._createJobEventHandler("output",(async n=>{this._matchKey(t,n.key)&&await e(n.data)}))}onDynamicOutput(t,e){return this._createJobEventHandler("output",(async n=>{(n.key.startsWith(t+":")||this._matchKey(t,n.key))&&await e(n.key,n.data)}))}onAnyOutput(t){return this._createJobEventHandler("output",(async e=>{await t(e.key,e.data)}))}onOutputEvent(t,e){return this.onDynamicOutput("events",(async(n,s)=>{s&&"object"==typeof s&&this._matchKey(t,s.type)&&await e(s)}))}onStateChanged(t){return this._createJobEventHandler("stateChanged",t)}onSuccess(t){return this._createJobEventHandler("success",t)}onFail(t){return this._createJobEventHandler("fail",t)}async _track(){for(;this._isTracking;){const{pollInterval:t}=this.client.config;try{const t=await this.api.getJobEvents(this.jobId,this._jobEventOffset);this._jobEventOffset+=t.length;for(const e of t)await this._processJobEvent(e);this._events.emit("trackTick")}catch(t){const e=new i.JobTrackError(t);throw this._events.emit("trackError",e),e}switch(this._state){case c.JobState.SUCCESS:return;case c.JobState.FAIL:throw new i.JobFailedError(this._error)}await new Promise((e=>setTimeout(e,t)))}}async _processJobEvent(t){const e=t.key;switch(t.name){case"awaitingInput":this._setState(c.JobState.AWAITING_INPUT),this._awaitingInputKey=e,this._events.emit("awaitingInput",e);break;case"createOutput":{const t=await this.api.getJobOutput(this.jobId,e);if(t){const n=t.data;this._outputsMap.set(e,{key:e,data:n}),this._events.emit("output",{key:e,data:n})}}break;case"processing":this._setState(c.JobState.PROCESSING);break;case"success":this._setState(c.JobState.SUCCESS),this._events.emit("success");break;case"fail":{const{error:t}=await this.api.getJob(this.jobId);this._setState(c.JobState.FAIL),this._error=Object.assign({category:"server",code:"UnknownError",message:"Unknown error"},t);const e=new i.JobFailedError(this._error);this._events.emit("fail",e)}}}_checkOutputs(t){const e=[];for(const n of t){const t=this._outputsMap.get(n);if(!t)break;e.push(t.data)}return e.length===t.length?e:null}get api(){return this.client.api}_createJobEventHandler(t,e){const n=async(...t)=>{await e(...t)};return this._events.on(t,n),()=>this._events.off(t,n)}_matchKey(t,e){if(t.endsWith(":*")){const n=t.split(":")[0];return e.startsWith(n+":")}return e===t}}},273:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},157:(t,e)=>{"use strict";var n,s;Object.defineProperty(e,"__esModule",{value:!0}),e.JobCategory=e.JobState=void 0,(s=e.JobState||(e.JobState={})).CREATED="created",s.SCHEDULED="scheduled",s.PROCESSING="processing",s.AWAITING_INPUT="awaitingInput",s.AWAITING_TDS="awaitingTds",s.PENDING="pending",s.SUCCESS="success",s.FAIL="fail",(n=e.JobCategory||(e.JobCategory={})).LIVE="live",n.TEST="test"},894:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Vault=void 0;const s=n(739);function r(t){return"string"==typeof t?t:[t.name,t.label,t.placeholder].map((t=>t.replace(/_/g,""))).join("_")}e.Vault=class{constructor(t){this.client=t;const{config:e}=t,n="string"==typeof e.auth?new s.BasicAuthAgent({username:e.auth}):new s.OAuth2Agent({clientId:e.auth.clientId,clientSecret:e.auth.clientSecret,tokenUrl:e.apiTokenUrl});this.request=new s.Request({baseUrl:e.vaultUrl,auth:n})}get api(){return this.client.api}async createOtp(){const{id:t}=await this.request.post("/otp");return t}async createPanToken(t,e){const n=null!=e?e:await this.createOtp(),{panToken:s}=await this.request.post("/pan",{body:{otp:n,pan:t}});return s}getPaymentIframeUrl(t,e={}){var n,s,o;const a=[["otp",t],["css",e.cssUrl],["name",e.name],["fields",null===(n=e.fields)||void 0===n?void 0:n.map(r).join(",")],["brands",null===(s=e.brands)||void 0===s?void 0:s.join(",")],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(o=e.iframeUrl)&&void 0!==o?o:"https://vault.automationcloud.net/forms/index.html")+"?"+a.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}getSingleInputIframeUrl(t,e={}){var n;const s=[["otp",t],["css",e.cssUrl],["inputType",e.inputType],["pattern",e.pattern],["minlength",e.minlength],["maxlength",e.maxlength],["required",e.required],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(n=e.iframeUrl)&&void 0!==n?n:"https://vault.automationcloud.net/forms/single-input.html")+"?"+s.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}}}},e={},function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863);var t,e})); | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.AutomationCloud=e():t.AutomationCloud=e()}(self,(function(){return t={739:t=>{self,t.exports=(()=>{"use strict";var t={300:(t,e)=>{var n=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n)return n;throw new Error("unable to locate global object")}();t.exports=e=n.fetch,n.fetch&&(e.default=n.fetch.bind(n)),e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response},395:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthAgent=void 0,e.AuthAgent=class{}},614:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BasicAuthAgent=void 0;const s=n(395),r=n(20);class o extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{username:t,password:e}=this.params,n=`${t}:${e}`;return"Basic "+r.toBase64(n)}invalidate(){}}e.BasicAuthAgent=o},924:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BearerAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{prefix:t="Bearer",token:e}=this.params;return e?`${t} ${e}`:null}invalidate(){}}e.BearerAuthAgent=r},12:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(26),e),r(n(614),e),r(n(924),e),r(n(890),e),r(n(658),e)},26:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{async getHeader(){return null}invalidate(){}}e.NoAuthAgent=r},890:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthNotSupportedError=e.OAuth1Agent=void 0;const s=n(395),r=n(222);class o extends s.AuthAgent{async getHeader(t){throw new i}invalidate(){}}e.OAuth1Agent=o;class i extends r.Exception{constructor(){super("This auth agent is not supported in browser environment.")}}e.AuthNotSupportedError=i},658:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.OAuth2Agent=e.OAuth2GrantType=void 0;const r=n(458),o=s(n(91)),i=n(395);var a;!function(t){t.CLIENT_CREDENTIALS="client_credentials",t.REFRESH_TOKEN="refresh_token",t.AUTHORIZATION_CODE="authorization_code",t.PASSWORD="password"}(a=e.OAuth2GrantType||(e.OAuth2GrantType={}));class c extends i.AuthAgent{constructor(t){super(),this.params=Object.assign({fetch:o.default},t)}async getHeader(){const t=await this.getAccessToken();return t?"Bearer "+t:null}async createToken(t){const{tokenUrl:e,fetch:n}=this.params,s=new r.Request({fetch:n}),o=Object.entries(t).filter((([t,e])=>null!=e)),i=await s.send("post",e,{body:new URLSearchParams(o)}),a=await i.json();return{accessToken:a.access_token,accessExpiresIn:a.expires_in,refreshToken:a.refresh_token}}setTokens(t){const{accessToken:e,accessExpiresIn:n,refreshToken:s}=t,r=n?Date.now()+1e3*n:null;this.params.accessToken=e,this.params.expiresAt=r,s&&(this.params.refreshToken=s)}invalidate(){this.params.accessToken=null,this.params.expiresAt=null}async getAccessToken(){const t=[this.tryCachedAccessToken,this.tryRefreshToken,this.tryClientSecret];for(const e of t)try{const t=await e.call(this);if(t)return t}catch(t){this.invalidate()}return null}async tryCachedAccessToken(){const{accessToken:t,expiresAt:e,minValiditySeconds:n=300}=this.params;return t&&(null==e||e-1e3*n>Date.now())?t:null}async tryRefreshToken(){const{refreshToken:t,clientId:e,clientSecret:n}=this.params;if(!t)return null;try{const s=await this.createToken({grant_type:a.REFRESH_TOKEN,client_id:e,client_secret:n,refresh_token:t});return this.setTokens(s),s.accessToken}catch(t){throw this.params.refreshToken=null,t}}async tryClientSecret(){const{clientId:t,clientSecret:e}=this.params;if(!e)return null;const n=await this.createToken({grant_type:a.CLIENT_CREDENTIALS,client_id:t,client_secret:e});return this.setTokens(n),n.accessToken}}e.OAuth2Agent=c},222:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},91:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"!=typeof window&&window.fetch?fetch.bind(window):n(300)},863:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Response=void 0,r(n(458),e),r(n(395),e),r(n(12),e),r(n(157),e),r(n(687),e);const i=o(n(210));e.Response=i.default},458:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.RequestFailedError=e.Request=e.DEFAULT_REQUEST_CONFIG=e.NETWORK_ERRORS=void 0;const r=n(222),o=n(12),i=s(n(91));e.NETWORK_ERRORS=["EAI_AGAIN","EHOSTDOWN","EHOSTUNREACH","ECONNABORTED","ECONNREFUSED","ECONNRESET","EPIPE"],e.DEFAULT_REQUEST_CONFIG={baseUrl:"",auth:new o.NoAuthAgent,retryAttempts:4,retryDelay:500,retryDelayIncrement:500,retryStatusCodes:[429,502,503,504],authInvalidateStatusCodes:[401,403],authInvalidateInterval:6e4,headers:{},fetch:i.default},e.Request=class{constructor(t){this.authInvalidatedAt=0,this.config=Object.assign(Object.assign({},e.DEFAULT_REQUEST_CONFIG),t)}async get(t,e={}){return await this.sendJson("get",t,e)}async post(t,e={}){return await this.sendJson("post",t,e)}async put(t,e={}){return await this.sendJson("put",t,e)}async delete(t,e={}){return await this.sendJson("delete",t,e)}async sendJson(t,e,n={}){const{body:s,query:r,headers:o}=n,i=await this.send(t,e,{headers:Object.assign({"content-type":"application/json"},o),query:r,body:s?JSON.stringify(s):null}),{status:a}=i;return 204===a||"0"===i.headers.get("content-length")?null:await i.json()}async send(t,n,s={}){var r,o,i;const{fetch:a}=this.config,c=Math.max(this.config.retryAttempts+1,1);let u,l;for(let h=0;h<c;h++){let c=!1,d=this.config.retryDelay+this.config.retryDelayIncrement*h;try{const e=await this.prepareRequestSpec(t,n,s),r=await a(e.url,{method:e.method,headers:e.headers,body:e.body});if(!r.ok)throw this.config.authInvalidateStatusCodes.includes(r.status)?(c=Date.now()-this.authInvalidatedAt>this.config.authInvalidateInterval,this.authInvalidatedAt=Date.now(),d=0,this.config.auth.invalidate()):c=this.config.retryStatusCodes.includes(r.status),await this.createErrorFromResponse(e,r);return r}catch(a){const h=null===(r=a.details)||void 0===r?void 0:r.status,p=null===(o=a.details)||void 0===o?void 0:o.statusText,f={method:t,url:n,headers:null!==(i=s.headers)&&void 0!==i?i:{},status:h,statusText:p};if(c||e.NETWORK_ERRORS.includes(a.code)){u=a,l=f,this.onRetry(a,f),await new Promise((t=>setTimeout(t,d)));continue}throw this.onError(a,f),a}}throw this.onError(u,l),u}async sendRaw(t,e,n={}){const s=await this.prepareRequestSpec(t,e,n),{fetch:r}=this.config;return await r(s.url,{method:s.method,headers:s.headers,body:s.body})}async prepareRequestSpec(t,e,n={}){var s,r;const{auth:o}=this.config,{body:i}=n,a=this.prepareUrl(e,n),c=null!==(s=await o.getHeader({url:a,method:t,body:i}))&&void 0!==s?s:"";return{method:t,url:a,headers:this.mergeHeaders({"content-type":null!==(r=this.inferContentTypeFromBody(i))&&void 0!==r?r:""},this.config.headers||{},{authorization:c},n.headers||{}),body:i}}prepareUrl(t,e){var n;const{baseUrl:s}=this.config,r=s&&"/"!==s.slice(-1)?s+"/":s,o=new URL("/"===t[0]?t.slice(1):t,r||void 0);return o.search=new URLSearchParams(Object.entries(null!==(n=e.query)&&void 0!==n?n:{})).toString(),o.toString()}inferContentTypeFromBody(t){switch(!0){case null==t:return null;case t instanceof URLSearchParams:return"application/x-www-form-urlencoded";case"object"==typeof t:return"application/json";case"string"==typeof t:return"text/plain";default:return null}}mergeHeaders(...t){const e={};for(const n of t)for(const[t,s]of Object.entries(n))s&&(e[t.toLowerCase()]=s);return e}async createErrorFromResponse(t,e){return new a(t,e)}onRetry(t,e){}onError(t,e){}};class a extends r.Exception{constructor(t,e){super(`Request failed: ${e.status} ${e.statusText}`),this.details={method:t.method,url:t.url,requestHeaders:t.headers,status:e.status,statusText:e.statusText},Object.defineProperty(this,"requestSpec",{enumerable:!1,value:t}),Object.defineProperty(this,"response",{enumerable:!1,value:e})}}e.RequestFailedError=a},210:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"==typeof Response?n(300).Response:Response},157:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},20:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.toBase64=void 0,e.toBase64=function(t){return btoa(t)}},687:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.fetchMock=void 0;const r=s(n(210));e.fetchMock=function(t,e={},n){const s={called:!1,calledCount:0,params:[]},o=(o,i)=>new Promise(((a,c)=>{const u=Object.assign({status:200},t);if(s.called=!0,s.calledCount+=1,s.params.push({fullUrl:o,fetchOptions:i}),n)return c(n);a(new r.default(JSON.stringify(e),u))}));return o.spy=s,o}}},e={};return function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863)})()},729:t=>{"use strict";var e=Object.prototype.hasOwnProperty,n="~";function s(){}function r(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function o(t,e,s,o,i){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new r(s,o||t,i),c=n?n+e:e;return t._events[c]?t._events[c].fn?t._events[c]=[t._events[c],a]:t._events[c].push(a):(t._events[c]=a,t._eventsCount++),t}function i(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),a.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(n?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},a.prototype.listeners=function(t){var e=n?n+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,o=s.length,i=new Array(o);r<o;r++)i[r]=s[r].fn;return i},a.prototype.listenerCount=function(t){var e=n?n+t:t,s=this._events[e];return s?s.fn?1:s.length:0},a.prototype.emit=function(t,e,s,r,o,i){var a=n?n+t:t;if(!this._events[a])return!1;var c,u,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,s),!0;case 4:return l.fn.call(l.context,e,s,r),!0;case 5:return l.fn.call(l.context,e,s,r,o),!0;case 6:return l.fn.call(l.context,e,s,r,o,i),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(t,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,s);break;case 4:l[u].fn.call(l[u].context,e,s,r);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},a.prototype.on=function(t,e,n){return o(this,t,e,n,!1)},a.prototype.once=function(t,e,n){return o(this,t,e,n,!0)},a.prototype.removeListener=function(t,e,s,r){var o=n?n+t:t;if(!this._events[o])return this;if(!e)return i(this,o),this;var a=this._events[o];if(a.fn)a.fn!==e||r&&!a.once||s&&a.context!==s||i(this,o);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==e||r&&!a[c].once||s&&a[c].context!==s)&&u.push(a[c]);u.length?this._events[o]=1===u.length?u[0]:u:i(this,o)}return this},a.prototype.removeAllListeners=function(t){var e;return t?(e=n?n+t:t,this._events[e]&&i(this,e)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a},330:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AcApi=void 0;const s=n(31);e.AcApi=class{constructor(t){this.client=t;const e=this.client.config;this.request=s.AcRequest.create(e,e.apiUrl)}get logger(){return this.client.logger}async createJob(t){const{serviceId:e,category:n,input:s}=t;return await this.request.post("/jobs",{body:{serviceId:e,category:n,input:s}})}async getJob(t){return await this.request.get(`/jobs/${t}`)}async getJobAccessToken(t){return(await this.request.get(`/jobs/${t}/end-user`)).token}async getJobEvents(t,e){const{data:n}=await this.request.get(`/jobs/${t}/events`,{query:{offset:e}});return n}async getJobOutput(t,e){var n;try{return await this.request.get(`/jobs/${t}/outputs/${e}`)}catch(t){if(404===(null===(n=t.details)||void 0===n?void 0:n.status))return null;throw t}}async sendJobInput(t,e,n){return await this.request.post(`/jobs/${t}/inputs`,{body:{key:e,data:n}})}async cancelJob(t){await this.request.post(`/jobs/${t}/cancel`)}async queryPreviousOutputs(t,e,n=[]){const{data:s}=await this.request.post(`/services/${t}/previous-job-outputs`,{body:{inputs:n},query:{key:e}});return s}}},31:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AcRequest=void 0;const s=n(739);class r extends s.Request{static create(t,e){const n=this.createAuthAgent(t);return new r({baseUrl:e,auth:n,retryAttempts:t.requestRetryCount,retryDelay:t.requestRetryDelay,headers:t.additionalHeaders})}static createAuthAgent(t){const e=t.auth;return e?"string"==typeof e?new s.BasicAuthAgent({username:e}):new s.OAuth2Agent({clientId:e.clientId,clientSecret:e.clientSecret,tokenUrl:t.apiTokenUrl}):new s.NoAuthAgent}async createErrorFromResponse(t,e){var n;if(null===(n=e.headers.get("content-type"))||void 0===n?void 0:n.startsWith("application/json")){const t=await e.json();if(t.name&&t.message){const e=new Error(t.message);return e.name=t.name,e.code=t.code,e.details=t.details,e}}return super.createErrorFromResponse(t,e)}}e.AcRequest=r},396:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Vault=void 0;const s=n(31);function r(t){return"string"==typeof t?t:[t.name,t.label,t.placeholder].map((t=>t.replace(/_/g,""))).join("_")}e.Vault=class{constructor(t){this.client=t;const{config:e}=this.client;this.request=s.AcRequest.create(e,e.vaultUrl)}async createOtp(){const{id:t}=await this.request.post("/otp");return t}async createPanToken(t,e){const n=null!=e?e:await this.createOtp(),{panToken:s}=await this.request.post("/pan",{body:{otp:n,pan:t}});return s}getPaymentIframeUrl(t,e={}){var n,s,o;const i=[["otp",t],["css",e.cssUrl],["name",e.name],["fields",null===(n=e.fields)||void 0===n?void 0:n.map(r).join(",")],["brands",null===(s=e.brands)||void 0===s?void 0:s.join(",")],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(o=e.iframeUrl)&&void 0!==o?o:"https://vault.automationcloud.net/forms/index.html")+"?"+i.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}getSingleInputIframeUrl(t,e={}){var n;const s=[["otp",t],["css",e.cssUrl],["inputType",e.inputType],["pattern",e.pattern],["minlength",e.minlength],["maxlength",e.maxlength],["required",e.required],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(n=e.iframeUrl)&&void 0!==n?n:"https://vault.automationcloud.net/forms/single-input.html")+"?"+s.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}}},967:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Client=void 0;const s=n(330),r=n(396),o=n(313),i=n(909),a=n(157);e.Client=class{constructor(t={}){this.logger=console,this.config=Object.assign({serviceId:null,auth:null,apiUrl:"https://api.automationcloud.net",apiTokenUrl:"https://auth.automationcloud.net/auth/realms/automationcloud/protocol/openid-connect/token",vaultUrl:"https://vault.automationcloud.net",pollInterval:1e3,requestRetryCount:4,requestRetryDelay:500,autoTrack:!0,additionalHeaders:{}},t),this.api=new s.AcApi(this),this.vault=new r.Vault(this)}async getJob(t){const e=new i.Job(this);return await e.trackExisting(t),e}async queryPreviousOutput(t,e=[]){const{serviceId:n}=this.config;if(!n)throw new o.ClientConfigError("serviceId is required to query previous outputs");const s=await this.api.queryPreviousOutputs(n,t,e);return s.length?s[0]:null}async createJob(t={}){return await this._createJob(Object.assign({serviceId:this.config.serviceId,category:a.JobCategory.TEST,input:{}},t))}async _createJob(t){const e=new i.Job(this,t);return await e.start(),e}}},313:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.JobTrackError=e.JobFailedError=e.JobOutputWaitError=e.JobAlreadyStartedError=e.JobNotInitializedError=e.ClientConfigError=void 0;const s=n(222);class r extends s.Exception{}e.ClientConfigError=r;class o extends s.Exception{constructor(){super("Invalid state: job not yet initialized")}}e.JobNotInitializedError=o;class i extends s.Exception{constructor(t={}){super("Job is already initialized"),this.details=t}}e.JobAlreadyStartedError=i;class a extends s.Exception{constructor(t,e={}){super(t),this.message=t,this.details=e}}e.JobOutputWaitError=a;class c extends s.Exception{constructor(t){var e,n,s;super(null!==(e=null==t?void 0:t.message)&&void 0!==e?e:"Unknown error"),this.name=null!==(n=null==t?void 0:t.code)&&void 0!==n?n:"UnknownError",this.details=Object.assign({category:null!==(s=null==t?void 0:t.category)&&void 0!==s?s:"server"},null==t?void 0:t.details)}}e.JobFailedError=c;class u extends s.Exception{constructor(t){super(`Job tracking failed: ${t.message}`),this.details={cause:t}}}e.JobTrackError=u},222:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},863:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(330),e),r(n(396),e),r(n(967),e),r(n(313),e),r(n(222),e),r(n(909),e),r(n(273),e),r(n(157),e)},909:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&s(e,t,n);return r(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.Job=void 0;const i=n(729),a=o(n(313)),c=n(157);e.Job=class{constructor(t,e={}){var n;this.client=t,this._events=new i.EventEmitter,this._inputsMap=new Map,this._outputsMap=new Map,this._state=c.JobState.CREATED,this._error=null,this._awaitingInputKey=null,this._trackPromise=null,this._jobId=null,this._jobEventOffset=0,this._isTracking=!1,this._initParams=Object.assign({serviceId:null!==(n=e.serviceId)&&void 0!==n?n:null,category:c.JobCategory.TEST,input:{}},e)}get jobId(){if(!this._jobId)throw new a.JobNotInitializedError;return this._jobId}async start(){if(this._jobId)throw new a.JobAlreadyStartedError(this.jobId);const{category:t,input:e}=this._initParams,{serviceId:n}=this._initParams;if(!n)throw new a.ClientConfigError("serviceId is required to start the job");const{id:s,state:r}=await this.api.createJob({serviceId:n,category:t,input:e});this._jobId=s,this._setState(r);for(const[t,n]of Object.entries(e))this._inputsMap.set(t,{key:t,data:n});this.client.config.autoTrack&&this.startTracking()}async trackExisting(t){if(this._jobId)throw new a.JobAlreadyStartedError({jobId:this.jobId});const{state:e,category:n}=await this.api.getJob(t);this._jobId=t,this._initParams.category=n,this._setState(e),this.startTracking()}startTracking(){this._trackPromise||(this._isTracking=!0,this._trackPromise=this._track(),this._trackPromise.catch((t=>{})).then((()=>{this._isTracking=!1,this._trackPromise=null})))}stopTracking(){this._isTracking=!1}getState(){return this._state}_setState(t){const e=this._state;this._state=t,this._events.emit("stateChanged",t,e)}getErrorInfo(){return this._error}getAwaitingInputKey(){return this._awaitingInputKey}async getAccessToken(){return await this.api.getJobAccessToken(this.jobId)}async submitInput(t,e){await this.api.sendJobInput(this.jobId,t,e),this._inputsMap.set(t,{key:t,data:e})}async getOutput(t){var e;let n=null!==(e=this._outputsMap.get(t))&&void 0!==e?e:null;return n||(n=await this.api.getJobOutput(this.jobId,t),n&&this._outputsMap.set(t,n)),null==n?void 0:n.data}async waitForCompletion(){await this._trackPromise}async cancel(){await this.api.cancelJob(this.jobId)}async waitForOutputs(...t){return await this._waitFor((()=>{const e=this._checkOutputs(t);if(null!=e)return e;if(this.getState()===c.JobState.FAIL)throw new a.JobOutputWaitError("Job failed, and specified outputs were not emitted",{state:this.getState(),jobId:this.jobId});if(this.getState()===c.JobState.SUCCESS)throw new a.JobOutputWaitError("Job succeeded, but specified outputs were not emitted",{state:this.getState(),jobId:this.jobId})}))}async _waitFor(t){return new Promise(((e,n)=>{const s=()=>{try{const n=t();void 0!==n&&(o(),e(n))}catch(t){o(),n(t)}},r=t=>{o(),n(t)},o=()=>{this._events.off("trackTick",s),this._events.off("trackError",r)};this._events.on("trackTick",s),this._events.on("trackError",r),s()}))}onAwaitingInput(t,e){return this._createJobEventHandler("awaitingInput",(async n=>{if("*"===t||n===t){const s=await e(n);void 0!==s&&await this.submitInput(t,s)}}))}onOutput(t,e){return this._createJobEventHandler("output",(async n=>{this._matchKey(t,n.key)&&await e(n.data)}))}onDynamicOutput(t,e){return this._createJobEventHandler("output",(async n=>{(n.key.startsWith(t+":")||this._matchKey(t,n.key))&&await e(n.key,n.data)}))}onAnyOutput(t){return this._createJobEventHandler("output",(async e=>{await t(e.key,e.data)}))}onOutputEvent(t,e){return this.onDynamicOutput("events",(async(n,s)=>{s&&"object"==typeof s&&this._matchKey(t,s.type)&&await e(s)}))}onStateChanged(t){return this._createJobEventHandler("stateChanged",t)}onSuccess(t){return this._createJobEventHandler("success",t)}onFail(t){return this._createJobEventHandler("fail",t)}async _track(){for(;this._isTracking;){const{pollInterval:t}=this.client.config;try{const t=await this.api.getJobEvents(this.jobId,this._jobEventOffset);this._jobEventOffset+=t.length;for(const e of t)await this._processJobEvent(e);this._events.emit("trackTick")}catch(t){const e=new a.JobTrackError(t);throw this._events.emit("trackError",e),e}switch(this._state){case c.JobState.SUCCESS:return;case c.JobState.FAIL:throw new a.JobFailedError(this._error)}await new Promise((e=>setTimeout(e,t)))}}async _processJobEvent(t){const e=t.key;switch(t.name){case"awaitingInput":this._setState(c.JobState.AWAITING_INPUT),this._awaitingInputKey=e,this._events.emit("awaitingInput",e);break;case"createOutput":{const t=await this.api.getJobOutput(this.jobId,e);if(t){const n=t.data;this._outputsMap.set(e,{key:e,data:n}),this._events.emit("output",{key:e,data:n})}}break;case"processing":this._setState(c.JobState.PROCESSING);break;case"success":this._setState(c.JobState.SUCCESS),this._events.emit("success");break;case"fail":{const{error:t}=await this.api.getJob(this.jobId);this._setState(c.JobState.FAIL),this._error=Object.assign({category:"server",code:"UnknownError",message:"Unknown error"},t);const e=new a.JobFailedError(this._error);this._events.emit("fail",e)}}}_checkOutputs(t){const e=[];for(const n of t){const t=this._outputsMap.get(n);if(!t)break;e.push(t.data)}return e.length===t.length?e:null}get api(){return this.client.api}_createJobEventHandler(t,e){const n=async(...t)=>{await e(...t)};return this._events.on(t,n),()=>this._events.off(t,n)}_matchKey(t,e){if(t.endsWith(":*")){const n=t.split(":")[0];return e.startsWith(n+":")}return e===t}}},273:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},157:(t,e)=>{"use strict";var n,s;Object.defineProperty(e,"__esModule",{value:!0}),e.JobCategory=e.JobState=void 0,(s=e.JobState||(e.JobState={})).CREATED="created",s.SCHEDULED="scheduled",s.PROCESSING="processing",s.AWAITING_INPUT="awaitingInput",s.AWAITING_TDS="awaitingTds",s.PENDING="pending",s.SUCCESS="success",s.FAIL="fail",(n=e.JobCategory||(e.JobCategory={})).LIVE="live",n.TEST="test"}},e={},function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863);var t,e})); |
@@ -1,4 +0,4 @@ | ||
import { Request, RequestSpec } from '@automationcloud/request'; | ||
import { Logger } from './logger'; | ||
import { ClientAuthParams, JobCategory, JobError, JobInputObject, JobState } from './types'; | ||
import { Request } from '@automationcloud/request'; | ||
import { Client } from './client'; | ||
import { JobCategory, JobError, JobInputObject, JobState } from './types'; | ||
/** | ||
@@ -10,5 +10,6 @@ * Automation Cloud HTTP client adapter. | ||
export declare class AcApi { | ||
params: AcApiParams; | ||
protected request: Request; | ||
constructor(params: AcApiParams); | ||
protected client: Client; | ||
request: Request; | ||
constructor(client: Client); | ||
get logger(): import("./logger").Logger; | ||
createJob(params: { | ||
@@ -27,5 +28,2 @@ serviceId: string; | ||
} | ||
export declare class AcRequest extends Request { | ||
protected createErrorFromResponse(requestSpec: RequestSpec, res: Response): Promise<Error>; | ||
} | ||
/** | ||
@@ -81,13 +79,2 @@ * @internal | ||
} | ||
/** | ||
* @internal | ||
*/ | ||
export interface AcApiParams { | ||
apiUrl: string; | ||
apiTokenUrl: string; | ||
auth: ClientAuthParams; | ||
logger: Logger; | ||
requestRetryCount: number; | ||
requestRetryDelay: number; | ||
} | ||
//# sourceMappingURL=ac-api.d.ts.map |
@@ -16,4 +16,4 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.AcRequest = exports.AcApi = void 0; | ||
const request_1 = require("@automationcloud/request"); | ||
exports.AcApi = void 0; | ||
const ac_request_1 = require("./ac-request"); | ||
/** | ||
@@ -25,18 +25,10 @@ * Automation Cloud HTTP client adapter. | ||
class AcApi { | ||
constructor(params) { | ||
this.params = params; | ||
const auth = typeof params.auth === 'string' ? | ||
new request_1.BasicAuthAgent({ username: params.auth }) : | ||
new request_1.OAuth2Agent({ | ||
clientId: params.auth.clientId, | ||
clientSecret: params.auth.clientSecret, | ||
tokenUrl: params.apiTokenUrl, | ||
}); | ||
this.request = new AcRequest({ | ||
baseUrl: params.apiUrl, | ||
auth, | ||
retryAttempts: params.requestRetryCount, | ||
retryDelay: params.requestRetryDelay, | ||
}); | ||
constructor(client) { | ||
this.client = client; | ||
const config = this.client.config; | ||
this.request = ac_request_1.AcRequest.create(config, config.apiUrl); | ||
} | ||
get logger() { | ||
return this.client.logger; | ||
} | ||
async createJob(params) { | ||
@@ -102,19 +94,2 @@ const { serviceId, category, input } = params; | ||
exports.AcApi = AcApi; | ||
class AcRequest extends request_1.Request { | ||
async createErrorFromResponse(requestSpec, res) { | ||
var _a; | ||
if ((_a = res.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.startsWith('application/json')) { | ||
const json = await res.json(); | ||
if (json.name && json.message) { | ||
const error = new Error(json.message); | ||
error.name = json.name; | ||
error.code = json.code; | ||
error.details = json.details; | ||
return error; | ||
} | ||
} | ||
return super.createErrorFromResponse(requestSpec, res); | ||
} | ||
} | ||
exports.AcRequest = AcRequest; | ||
//# sourceMappingURL=ac-api.js.map |
import { AcApi, AcJobInput, AcPreviousJobOutput } from './ac-api'; | ||
import { Vault } from './ac-vault'; | ||
import { Job } from './job'; | ||
import { Logger } from './logger'; | ||
import { ClientConfig, ClientOptions, JobInitParams } from './types'; | ||
import { Vault } from './vault'; | ||
import { ClientConfig, JobInitParams } from './types'; | ||
/** | ||
@@ -37,3 +37,3 @@ * A Client instance is used to run a job on a particular service. | ||
api: AcApi; | ||
constructor(params: ClientOptions); | ||
constructor(options?: Partial<ClientConfig>); | ||
/** | ||
@@ -40,0 +40,0 @@ * Resumes the tracking of the job that was previously created. |
@@ -18,5 +18,6 @@ "use strict"; | ||
const ac_api_1 = require("./ac-api"); | ||
const ac_vault_1 = require("./ac-vault"); | ||
const errors_1 = require("./errors"); | ||
const job_1 = require("./job"); | ||
const types_1 = require("./types"); | ||
const vault_1 = require("./vault"); | ||
/** | ||
@@ -40,14 +41,7 @@ * A Client instance is used to run a job on a particular service. | ||
class Client { | ||
constructor(params) { | ||
constructor(options = {}) { | ||
this.logger = console; | ||
this.config = Object.assign({ apiUrl: 'https://api.automationcloud.net', apiTokenUrl: 'https://auth.automationcloud.net/auth/realms/automationcloud/protocol/openid-connect/token', vaultUrl: 'https://vault.automationcloud.net', pollInterval: 1000, requestRetryCount: 4, requestRetryDelay: 500, autoTrack: true }, params); | ||
this.api = new ac_api_1.AcApi({ | ||
logger: this.logger, | ||
apiTokenUrl: this.config.apiTokenUrl, | ||
apiUrl: this.config.apiUrl, | ||
auth: this.config.auth, | ||
requestRetryCount: this.config.requestRetryCount, | ||
requestRetryDelay: this.config.requestRetryDelay, | ||
}); | ||
this.vault = new vault_1.Vault(this); | ||
this.config = Object.assign({ serviceId: null, auth: null, apiUrl: 'https://api.automationcloud.net', apiTokenUrl: 'https://auth.automationcloud.net/auth/realms/automationcloud/protocol/openid-connect/token', vaultUrl: 'https://vault.automationcloud.net', pollInterval: 1000, requestRetryCount: 4, requestRetryDelay: 500, autoTrack: true, additionalHeaders: {} }, options); | ||
this.api = new ac_api_1.AcApi(this); | ||
this.vault = new ac_vault_1.Vault(this); | ||
} | ||
@@ -72,3 +66,7 @@ /** | ||
async queryPreviousOutput(key, inputs = []) { | ||
const outputs = await this.api.queryPreviousOutputs(this.config.serviceId, key, inputs); | ||
const { serviceId } = this.config; | ||
if (!serviceId) { | ||
throw new errors_1.ClientConfigError('serviceId is required to query previous outputs'); | ||
} | ||
const outputs = await this.api.queryPreviousOutputs(serviceId, key, inputs); | ||
return outputs.length ? outputs[0] : null; | ||
@@ -89,3 +87,3 @@ } | ||
async createJob(options = {}) { | ||
return await this._createJob(Object.assign({ category: types_1.JobCategory.TEST, input: {} }, options)); | ||
return await this._createJob(Object.assign({ serviceId: this.config.serviceId, category: types_1.JobCategory.TEST, input: {} }, options)); | ||
} | ||
@@ -92,0 +90,0 @@ /** |
import { Exception } from './exception'; | ||
import { JobError } from './types'; | ||
export declare class ClientConfigError extends Exception { | ||
} | ||
export declare class JobNotInitializedError extends Exception { | ||
@@ -4,0 +6,0 @@ constructor(); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JobTrackError = exports.JobFailedError = exports.JobOutputWaitError = exports.JobAlreadyStartedError = exports.JobNotInitializedError = void 0; | ||
exports.JobTrackError = exports.JobFailedError = exports.JobOutputWaitError = exports.JobAlreadyStartedError = exports.JobNotInitializedError = exports.ClientConfigError = void 0; | ||
const exception_1 = require("./exception"); | ||
class ClientConfigError extends exception_1.Exception { | ||
} | ||
exports.ClientConfigError = ClientConfigError; | ||
class JobNotInitializedError extends exception_1.Exception { | ||
@@ -6,0 +9,0 @@ constructor() { |
export * from './ac-api'; | ||
export * from './ac-vault'; | ||
export * from './client'; | ||
export * from './errors'; | ||
export * from './exception'; | ||
export * from './errors'; | ||
export * from './job'; | ||
export * from './logger'; | ||
export * from './types'; | ||
export * from './vault'; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -14,9 +14,9 @@ "use strict"; | ||
__exportStar(require("./ac-api"), exports); | ||
__exportStar(require("./ac-vault"), exports); | ||
__exportStar(require("./client"), exports); | ||
__exportStar(require("./errors"), exports); | ||
__exportStar(require("./exception"), exports); | ||
__exportStar(require("./errors"), exports); | ||
__exportStar(require("./job"), exports); | ||
__exportStar(require("./logger"), exports); | ||
__exportStar(require("./types"), exports); | ||
__exportStar(require("./vault"), exports); | ||
//# sourceMappingURL=index.js.map |
@@ -60,2 +60,3 @@ "use strict"; | ||
constructor(client, params = {}) { | ||
var _a; | ||
this.client = client; | ||
@@ -72,3 +73,3 @@ this._events = new eventemitter3_1.EventEmitter(); | ||
this._isTracking = false; | ||
this._initParams = Object.assign({ category: types_1.JobCategory.TEST, input: {} }, params); | ||
this._initParams = Object.assign({ serviceId: (_a = params.serviceId) !== null && _a !== void 0 ? _a : null, category: types_1.JobCategory.TEST, input: {} }, params); | ||
} | ||
@@ -98,3 +99,6 @@ /** | ||
const { category, input } = this._initParams; | ||
const { serviceId } = this.client.config; | ||
const { serviceId } = this._initParams; | ||
if (!serviceId) { | ||
throw new errors.ClientConfigError('serviceId is required to start the job'); | ||
} | ||
const { id, state } = await this.api.createJob({ serviceId, category, input }); | ||
@@ -101,0 +105,0 @@ this._jobId = id; |
@@ -6,2 +6,6 @@ /** | ||
/** | ||
* Service id to start automation job on. Defaults to `client.config.serviceId`. | ||
*/ | ||
serviceId: string | null; | ||
/** | ||
* Initial job inputs (provided as objects). | ||
@@ -108,7 +112,2 @@ */ | ||
/** | ||
* Automation Cloud client configuration, consists of required and optional parameters. | ||
*/ | ||
export declare type ClientConfig = ClientRequiredParams & ClientOptionalParams; | ||
export declare type ClientOptions = ClientRequiredParams & Partial<ClientOptionalParams>; | ||
/** | ||
* Automation Cloud authentication. | ||
@@ -119,14 +118,17 @@ * | ||
*/ | ||
export declare type ClientAuthParams = string | { | ||
export declare type ClientAuthParams = { | ||
clientId: string; | ||
clientSecret: string; | ||
}; | ||
} | string | null; | ||
/** | ||
* Required Client configuration parameters. | ||
* Optional Client configuration parameters. | ||
*/ | ||
export interface ClientRequiredParams { | ||
export interface ClientConfig { | ||
/** | ||
* A UUID of the Service to be executed (you can obtain it from Automation Cloud dashboard). | ||
* | ||
* If not specified, then it must be explicitly passed when required (e.g. to create a job, | ||
* query previous outputs, etc). | ||
*/ | ||
serviceId: string; | ||
serviceId: string | null; | ||
/** | ||
@@ -136,9 +138,13 @@ * Automation Cloud authentication parameters. | ||
auth: ClientAuthParams; | ||
} | ||
/** | ||
* Optional Client configuration parameters. | ||
*/ | ||
export interface ClientOptionalParams { | ||
/** | ||
* Automation Cloud API base URL. Trailing slash should not be included. | ||
*/ | ||
apiUrl: string; | ||
/** | ||
* Automation Cloud OAuth2 token URL. | ||
*/ | ||
apiTokenUrl: string; | ||
/** | ||
* Automation Cloud Vault API URL. Trailing slash should not be included. | ||
*/ | ||
vaultUrl: string; | ||
@@ -161,3 +167,7 @@ /** | ||
autoTrack: boolean; | ||
/** | ||
* Additional headers to send alongside API requests. | ||
*/ | ||
additionalHeaders: Record<string, string>; | ||
} | ||
//# sourceMappingURL=types.d.ts.map |
{ | ||
"name": "@automationcloud/client", | ||
"version": "1.4.3", | ||
"version": "1.5.0", | ||
"description": "JavaScript/TypeScript Client Library for Automation Cloud API", | ||
@@ -13,2 +13,3 @@ "main": "out/main/index.js", | ||
"lint": "eslint . --ext=.js,.ts --cache", | ||
"lint:fix": "eslint . --ext=.js,.ts --cache --fix", | ||
"docs": "typedoc --tsconfig ./tsconfig.json ./src/main && git add docs/", | ||
@@ -53,2 +54,3 @@ "preversion": "npm run lint && npm run clean && npm run compile && npm run docs && npm run build:browser", | ||
"@typescript-eslint/parser": "^4.9.0", | ||
"@ubio/eslint-config": "^1.1.2", | ||
"dotenv": "^8.2.0", | ||
@@ -55,0 +57,0 @@ "eslint": "^7.14.0", |
@@ -15,6 +15,8 @@ // Copyright 2020 UBIO Limited | ||
import { Request, BasicAuthAgent, OAuth2Agent, RequestSpec } from '@automationcloud/request'; | ||
import { Logger } from './logger'; | ||
import { ClientAuthParams, JobCategory, JobError, JobInputObject, JobState } from './types'; | ||
import { Request } from '@automationcloud/request'; | ||
import { AcRequest } from './ac-request'; | ||
import { Client } from './client'; | ||
import { JobCategory, JobError, JobInputObject, JobState } from './types'; | ||
/** | ||
@@ -26,23 +28,15 @@ * Automation Cloud HTTP client adapter. | ||
export class AcApi { | ||
protected request: Request; | ||
request: Request; | ||
constructor( | ||
public params: AcApiParams, | ||
protected client: Client, | ||
) { | ||
const auth = typeof params.auth === 'string' ? | ||
new BasicAuthAgent({ username: params.auth }) : | ||
new OAuth2Agent({ | ||
clientId: params.auth.clientId, | ||
clientSecret: params.auth.clientSecret, | ||
tokenUrl: params.apiTokenUrl, | ||
}); | ||
this.request = new AcRequest({ | ||
baseUrl: params.apiUrl, | ||
auth, | ||
retryAttempts: params.requestRetryCount, | ||
retryDelay: params.requestRetryDelay, | ||
// Note: retryDelayIncrement stays the same to avoid unintentional DDoS | ||
}); | ||
const config = this.client.config; | ||
this.request = AcRequest.create(config, config.apiUrl); | ||
} | ||
get logger() { | ||
return this.client.logger; | ||
} | ||
async createJob(params: { | ||
@@ -115,19 +109,3 @@ serviceId: string, | ||
} | ||
} | ||
export class AcRequest extends Request { | ||
protected async createErrorFromResponse(requestSpec: RequestSpec, res: Response): Promise<Error> { | ||
if (res.headers.get('content-type')?.startsWith('application/json')) { | ||
const json = await res.json(); | ||
if (json.name && json.message) { | ||
const error = new Error(json.message) as any; | ||
error.name = json.name; | ||
error.code = json.code; | ||
error.details = json.details; | ||
return error; | ||
} | ||
} | ||
return super.createErrorFromResponse(requestSpec, res); | ||
} | ||
} | ||
@@ -190,13 +168,1 @@ | ||
} | ||
/** | ||
* @internal | ||
*/ | ||
export interface AcApiParams { | ||
apiUrl: string; | ||
apiTokenUrl: string; | ||
auth: ClientAuthParams; | ||
logger: Logger; | ||
requestRetryCount: number; | ||
requestRetryDelay: number; | ||
} |
@@ -16,6 +16,7 @@ // Copyright 2020 UBIO Limited | ||
import { AcApi, AcJobInput, AcPreviousJobOutput } from './ac-api'; | ||
import { Vault } from './ac-vault'; | ||
import { ClientConfigError } from './errors'; | ||
import { Job } from './job'; | ||
import { Logger } from './logger'; | ||
import { ClientConfig, ClientOptions, JobCategory, JobInitParams } from './types'; | ||
import { Vault } from './vault'; | ||
import { ClientConfig, JobCategory, JobInitParams } from './types'; | ||
@@ -57,4 +58,6 @@ /** | ||
constructor(params: ClientOptions) { | ||
constructor(options: Partial<ClientConfig> = {}) { | ||
this.config = { | ||
serviceId: null, | ||
auth: null, | ||
apiUrl: 'https://api.automationcloud.net', | ||
@@ -67,12 +70,6 @@ apiTokenUrl: 'https://auth.automationcloud.net/auth/realms/automationcloud/protocol/openid-connect/token', | ||
autoTrack: true, | ||
...params, | ||
additionalHeaders: {}, | ||
...options, | ||
}; | ||
this.api = new AcApi({ | ||
logger: this.logger, | ||
apiTokenUrl: this.config.apiTokenUrl, | ||
apiUrl: this.config.apiUrl, | ||
auth: this.config.auth, | ||
requestRetryCount: this.config.requestRetryCount, | ||
requestRetryDelay: this.config.requestRetryDelay, | ||
}); | ||
this.api = new AcApi(this); | ||
this.vault = new Vault(this); | ||
@@ -100,3 +97,7 @@ } | ||
async queryPreviousOutput(key: string, inputs: AcJobInput[] = []): Promise<AcPreviousJobOutput | null> { | ||
const outputs = await this.api.queryPreviousOutputs(this.config.serviceId, key, inputs); | ||
const { serviceId } = this.config; | ||
if (!serviceId) { | ||
throw new ClientConfigError('serviceId is required to query previous outputs'); | ||
} | ||
const outputs = await this.api.queryPreviousOutputs(serviceId, key, inputs); | ||
return outputs.length ? outputs[0] : null; | ||
@@ -119,2 +120,3 @@ } | ||
return await this._createJob({ | ||
serviceId: this.config.serviceId, | ||
category: JobCategory.TEST, | ||
@@ -121,0 +123,0 @@ input: {}, |
import { Exception } from './exception'; | ||
import { JobError } from './types'; | ||
export class ClientConfigError extends Exception {} | ||
export class JobNotInitializedError extends Exception { | ||
@@ -29,3 +31,3 @@ constructor() { | ||
category: jobError?.category ?? 'server', | ||
... jobError?.details, | ||
...jobError?.details, | ||
}; | ||
@@ -32,0 +34,0 @@ } |
export * from './ac-api'; | ||
export * from './ac-vault'; | ||
export * from './client'; | ||
export * from './errors'; | ||
export * from './exception'; | ||
export * from './errors'; | ||
export * from './job'; | ||
export * from './logger'; | ||
export * from './types'; | ||
export * from './vault'; |
@@ -16,2 +16,3 @@ // Copyright 2020 UBIO Limited | ||
import { EventEmitter } from 'eventemitter3'; | ||
import { AcJobEvent } from './ac-api'; | ||
@@ -59,2 +60,3 @@ import { Client } from './client'; | ||
this._initParams = { | ||
serviceId: params.serviceId ?? null, | ||
category: JobCategory.TEST, | ||
@@ -90,3 +92,6 @@ input: {}, | ||
const { category, input } = this._initParams; | ||
const { serviceId } = this.client.config; | ||
const { serviceId } = this._initParams; | ||
if (!serviceId) { | ||
throw new errors.ClientConfigError('serviceId is required to start the job'); | ||
} | ||
const { id, state } = await this.api.createJob({ serviceId, category, input }); | ||
@@ -93,0 +98,0 @@ this._jobId = id; |
@@ -20,2 +20,6 @@ // Copyright 2020 UBIO Limited | ||
/** | ||
* Service id to start automation job on. Defaults to `client.config.serviceId`. | ||
*/ | ||
serviceId: string | null; | ||
/** | ||
* Initial job inputs (provided as objects). | ||
@@ -134,8 +138,2 @@ */ | ||
/** | ||
* Automation Cloud client configuration, consists of required and optional parameters. | ||
*/ | ||
export type ClientConfig = ClientRequiredParams & ClientOptionalParams; | ||
export type ClientOptions = ClientRequiredParams & Partial<ClientOptionalParams>; | ||
/** | ||
* Automation Cloud authentication. | ||
@@ -146,15 +144,19 @@ * | ||
*/ | ||
export type ClientAuthParams = string | { | ||
export type ClientAuthParams = { | ||
clientId: string; | ||
clientSecret: string; | ||
} | ||
} | string | null; | ||
/** | ||
* Required Client configuration parameters. | ||
* Optional Client configuration parameters. | ||
*/ | ||
export interface ClientRequiredParams { | ||
export interface ClientConfig { | ||
/** | ||
* A UUID of the Service to be executed (you can obtain it from Automation Cloud dashboard). | ||
* | ||
* If not specified, then it must be explicitly passed when required (e.g. to create a job, | ||
* query previous outputs, etc). | ||
*/ | ||
serviceId: string; | ||
serviceId: string | null; | ||
@@ -165,11 +167,18 @@ /** | ||
auth: ClientAuthParams; | ||
} | ||
/** | ||
* Optional Client configuration parameters. | ||
*/ | ||
export interface ClientOptionalParams { | ||
/** | ||
* Automation Cloud API base URL. Trailing slash should not be included. | ||
*/ | ||
apiUrl: string; | ||
/** | ||
* Automation Cloud OAuth2 token URL. | ||
*/ | ||
apiTokenUrl: string; | ||
/** | ||
* Automation Cloud Vault API URL. Trailing slash should not be included. | ||
*/ | ||
vaultUrl: string; | ||
/** | ||
@@ -179,2 +188,3 @@ * Poll interval in milliseconds for job state synchronization. Default: `1000` (1 second). | ||
pollInterval: number; | ||
/** | ||
@@ -184,2 +194,3 @@ * The number of times failed http requests to Automation Cloud API will be resent in case of failure. | ||
requestRetryCount: number; | ||
/** | ||
@@ -189,2 +200,3 @@ * The delay between re-sending the failed http requests. | ||
requestRetryDelay: number; | ||
/** | ||
@@ -194,2 +206,7 @@ * Whether or not to start tracking the job automatically when it is created. Default: `true`. | ||
autoTrack: boolean; | ||
/** | ||
* Additional headers to send alongside API requests. | ||
*/ | ||
additionalHeaders: Record<string, string>; | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
192306
54
3130
19