import l from"stringify-object";import{CodeBuilder as A}from"../../helpers/code-builder.js";import{addIndentation as p,getPreserveTransformer as C,buildUrlExpression as w,printUrlVariablesDeclarations as T}from"../../helpers/code-helpers.js";import{normalizeMimeType as f}from"../../../../utils.js";import{HTTPSnippet as j}from"../../index.js";import{Lang as N}from"../../helpers/constants.js";import{MediaTypes as r}from"../../../../../constants.js";import{buildJSDeviceAuthorizationCodeSnippet as P}from"../../helpers/device-auth-snippets.js";const k=function(e,b,{target:v,client:y}){const i={indent:"  ",credentials:null,...b},t=new A({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:!0,lang:N.JAVASCRIPT}),a={method:e.method.toUpperCase()};Object.keys(e.headersObj).length&&(a.headers=e.headersObj);let h=!1;if(i.withComments&&L(t),e.securityOAuth2ExtraCalls?.length){const n=e.securityOAuth2ExtraCalls?.[0],s=new j(n).convert(v,y,{...i,withImports:!1,withComments:!1,variablesPrefix:"oAuth2"});t.push(s),t.blank(),n.flowType==="deviceAuthorization"&&P(t,{tokenUrl:n.tokenUrl??"YOUR_TOKEN_URL",clientId:n.clientId??"YOUR_CLIENT_ID",level:0}),a.headers=a.headers||{},a.headers.Authorization="'Bearer ' + accessToken",h=!0}i.credentials!==null&&(a.credentials=i.credentials);const m=Object.getOwnPropertyNames(e.queryObj).length;if(m&&t.push(`const ${t.var("query")} = new URLSearchParams(${l(e.queryObj,{indent:i.indent,inlineCharacterLimit:25})}).toString();`).blank(),e.postData)switch(f(e.postData.mimeType)){case r.URL_ENCODED:a.body=e.postData.paramsObj?`new URLSearchParams(${t.var("formData")}).toString()`:`"${e.postData.text}"`,e.postData.paramsObj&&t.push(`const ${t.var("formData")} = ${p(l(e.postData.paramsObj,{indent:i.indent,inlineCharacterLimit:25}),{level:0,firstLine:!1})};`).blank();break;case r.JSON:e.postData.jsonObj&&(a.body=`JSON.stringify(${p(l(e.postData.jsonObj,{indent:i.indent,inlineCharacterLimit:25}),{level:1,firstLine:!1})})`);break;case r.MULTIPART:if(t.push(`const ${t.var("form")} = new FormData();`),delete a?.headers?.["Content-Type"],e.postData?.params?.length>0)e.postData.params.forEach(function(n){t.push(`${t.var("form")}.append(%s, %s);`,JSON.stringify(n.name),JSON.stringify(n.value||n.fileName||""))});else if(e.postData.text){const n=e.postData.text,s=n.match(/^--([^\r\n]+)/);if(s){const $=s[1];n.split(new RegExp(`--${$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(o=>o.trim().length>0).forEach(o=>{const d=o.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(d){const g=d[1],D=d[2],u=o.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),S=u?u[1].trim():"",x=D||S;t.push(`${t.var("form")}.append(%s, %s);`,JSON.stringify(g),JSON.stringify(x))}})}else t.push(`${t.var("form")}.append('data', %s);`,JSON.stringify(e.postData.text))}a.body=t.var("form"),t.blank();break;default:e.postData.text&&(a.body=`\`${p(e.postData.text,{level:2,indent:i.indent,firstLine:!1}).trim()}\``)}const c=a.headers&&a.headers.Accept&&f(a.headers.Accept)===r.JSON||f(e.postData?.mimeType)===r.JSON;if(e.basicAuth){const{username:n,password:s}=e.basicAuth;a.headers=a.headers||{},a.headers.Authorization=`'Basic ' + btoa('${n}:${s}')`,h=!0}T(e,t);const O=w(e,t);return t.push(`const ${t.var("resp")} = await fetch(`).push(1,"`"+O+(m?"?${"+t.var("query")+"}":"")+"`,").push(p(l(a,{indent:i.indent,inlineCharacterLimit:25,transform:C({body:!0,authorizationHeader:h})}),{level:1,indent:i.indent})).push(");").blank(),e.allResponseCodes?.includes("204")?(t.push("if (resp.status === 204) {").push(1,"console.log('success');").push("} else {"),t.push(1,`const ${t.var("data")} = await ${t.var("resp")}.${c?"json()":"text()"};`).push(1,`console.log(${t.var("data")});`).push("}")):t.push(`const ${t.var("data")} = await ${t.var("resp")}.${c?"json()":"text()"};`).push(`console.log(${t.var("data")});`),t.join()};function L(e){e.push("/**"),e.push(" * Requires ES8-compatible browser: https://caniuse.com/async-functions"),e.push(" */"),e.blank()}const F={key:"fetch",title:"fetch",link:"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",description:"Perform asynchronous HTTP requests with the Fetch API"};var H=k;export{H as default,F as info};
