import{__decorate}from"tslib";import Bluebird from"../../deps/bluebird_fork.js";import{validation}from"../../Validation.js";import{GenericActivityError}from"../../Errors.js";import{ChannelProvider}from"./ChannelProvider.js";import{activate}from"../../Hooks.js";function isJsonResponse(e){const t=e.response.headers["Content-Type"];if("string"==typeof t&&"application/json"===t.split(";")[0].trim())return!0;return!1}function encode(e){return null==e?"":"boolean"==typeof e?!0===e?"true":"false":"number"==typeof e?encodeURIComponent(e.toString()):"string"==typeof e?encodeURIComponent(e):"object"==typeof e?encodeURIComponent(JSON.stringify(e)):""}function makeQueryString(e){const t=[];for(const r in e){var n=e[r];if(n instanceof Array)for(const o of n)t.push(r+"="+encode(o));else t.push(r+"="+encode(n))}return t.join("&")}let WebRequest=class{execute(o,e,t){const s=t.create(o.channel,o.channelName);let n=s.request.url=validation.string("url",o.url,validation.never);s.request.headers=o.headers||{},s.timeout=validation.number("timeout",o.timeout,6e4),s.corsWithCredentials=validation.boolean("corsWithCredentials",o.corsWithCredentials,!1);t=o.query;null!=t&&(n=n.split("#")[0],r=makeQueryString(t),n=0<=n.indexOf("?")?n+"&"+r:n+"?"+r,s.request.url=n);var r=o.method;s.request.method="string"==typeof r?r:"GET";r=o.blob;r instanceof ArrayBuffer&&(s.request.content=r);r=o.text;"string"==typeof r&&(s.request.content=r);r=o.json;void 0!==r&&(s.request.json=r);r=o.form;null!=r&&(s.request.content=makeQueryString(r)),"blob"===o.expect&&(s.binary=!0),e.cancellationToken.finally(function(){s.cancel()});const i=(new Date).valueOf();return s.send().then(function(r){return Bluebird.attempt(function(){const e={channel:s,elapsed:(new Date).valueOf()-i};var t=s.response.content;"string"==typeof t&&(e.text=t,"json"===o.expect&&(r||isJsonResponse(s))&&(e.json=JSON.parse(t))),t instanceof ArrayBuffer&&(e.blob=t);t=s.response.payload;if(null!=t&&(e.json=t),r)return e;const n=new GenericActivityError("WF0014","Cannot perform web request.");return n.timedOut=e.elapsed>=s.timeout,n.elapsed=e.elapsed,n.error=s.response.error,n.partialResult=e,Bluebird.reject(n)})})}};WebRequest.action="gcx:wf:core:request:WebRequest",WebRequest.suite="gcx:wf:builtin",WebRequest=__decorate([activate(ChannelProvider)],WebRequest);export{WebRequest};