import c from"stringify-object";import{CodeBuilder as g}from"../../helpers/code-builder.js";import{HTTPSnippet as H}from"../../index.js";import{Lang as P}from"../../helpers/constants.js";import{buildUrlExpression as q,printUrlVariablesDeclarations as U}from"../../helpers/code-helpers.js";import{normalizeMimeType as O}from"../../../../utils.js";import{MediaTypes as p}from"../../../../../constants.js";import{buildRubyDeviceAuthorizationCodeSnippet as k}from"../../helpers/device-auth-snippets.js";const h=1;function w(t={},u){return O(t.mimeType)===u}const C=function(t,u,{target:y,client:D}){const l=t.method.toUpperCase(),n=t.securityOAuth2ExtraCalls?.[0],r={capitalize:!0,showBoilerplate:!0,indent:"  ",...u},e=new g({indentation:r.indent,variablesPrefix:r.variablesPrefix,capitalize:r.capitalize,lang:P.RUBY});r.showBoilerplate&&(e.push("require 'uri'").push("require 'net/http'"),t.uriObj.protocol==="https:"&&e.push("require 'openssl'"),(w(t.postData,p.JSON)||n)&&e.unshift("require 'json'"),e.blank()),Object.keys(t.allHeaders).length&&Object.keys(t.allHeaders).forEach(a=>{t.allHeaders[a]=`'${t.allHeaders[a]}'`});const E=["GET","POST","HEAD","DELETE","PATCH","PUT","OPTIONS","COPY","LOCK","UNLOCK","MOVE","TRACE"],m=l.charAt(0)+l.substring(1).toLowerCase();if(E.indexOf(l)<0&&e.push("class Net::HTTP::%s < Net::HTTPRequest",m).push("  METHOD = '%s'",l.toUpperCase()).push("  REQUEST_HAS_BODY = '%s'",t.postData?.text?"true":"false").push("  RESPONSE_HAS_BODY = true").push("end").blank(),n){const a="oAuth2",i=new H(n).convert(y,D,{...r,variablesPrefix:a,showBoilerplate:!1}),s=`${a}${r.capitalize?"Response":"response"}`;e.push(i),n.flowType==="deviceAuthorization"?k(e,{tokenUrl:n.tokenUrl??"YOUR_TOKEN_URL",clientId:n.clientId??"YOUR_CLIENT_ID",level:0,responseVariable:s,capitalize:r.capitalize}):(e.push(`access_token = JSON.parse(${s}.body)['access_token']`),e.blank()),t.allHeaders.Authorization='"Bearer " + access_token'}if(U(t,e),e.push(`${e.var("url")} = URI(${q(t,e)})`),Object.getOwnPropertyNames(t.queryObj).length&&(e.push(`${e.var("params")} = ${c(t.queryObj,{indent:r.indent,inlineCharacterLimit:25})}`),e.push(`${e.var("url")}.query = URI.encode_www_form(${e.var("params")})`)),e.blank().push(`${e.var("http")} = Net::HTTP.new(${e.var("url")}.host, ${e.var("url")}.port)`),t.uriObj.protocol==="https:"&&e.push(`${e.var("http")}.use_ssl = true`),e.blank().push(`${e.var("request")} = Net::HTTP::%s.new(${e.var("url")})`,m),Object.keys(t.allHeaders).length&&Object.keys(t.allHeaders).forEach(a=>{t.allHeaders[a]!==`'${p.MULTIPART}'`&&e.push(`${e.var("request")}['%s'] = %s`,a,t.allHeaders[a])}),t?.postData){const a={};switch(O(t?.postData?.mimeType)){case p.URL_ENCODED:t.postData.params.length?(t.postData.params.forEach(s=>{a[s.name]=s.value}),e.push(`${e.var("request")}.body = URI.encode_www_form(${c(a,{indent:r.indent,inlineCharacterLimit:25})})`)):t.postData.text&&e.push(`${e.var("request")}.body = "${t.postData.text}"`);break;case p.JSON:e.push(`${e.var("request")}.body = ${c(t.postData.jsonObj,{indent:r.indent,inlineCharacterLimit:25}).replace(/null/g,"nil")}.to_json`);break;case p.MULTIPART:let i=!1;if(t.postData.params&&t.postData.params.length>0)e.push(`${e.var("form_data")} = [`),t.postData.params.forEach(s=>{s.fileName?e.push(h,`['${s.name}', File.open('${s.fileName}', 'rb')],`):e.push(h,`['${s.name}', '${s.value}'],`)}),e.push("]"),i=!0;else if(t.postData.text){const s=t.postData.text,b=s.match(/^--([^\r\n]+)/);if(b){const f=b[1],_=s.split(new RegExp(`--${f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(o=>o.trim().length>0);e.push(`${e.var("form_data")} = [`),_.forEach(o=>{const d=o.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(d){const $=d[1],T=d[2],v=o.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),x=(v?v[1].trim():"").replace(/\\/g,"\\\\").replace(/'/g,"\\'");T?e.push(h,`['${$}', File.open('${T}', 'rb')],`):e.push(h,`['${$}', '${x}'],`)}}),e.push("]"),i=!0}else{const f=t.postData.text.replace(/\\/g,"\\\\").replace(/'/g,"\\'");e.push(`${e.var("request")}.body = '${f}'`);break}}i&&e.push(`${e.var("request")}.set_form(${e.var("form_data")}, '${p.MULTIPART}')`);break;default:t.postData?.text&&e.push(`${e.var("request")}.body = ${JSON.stringify(t.postData?.text)}`)}}if(t.basicAuth){const{username:a,password:i}=t.basicAuth;e.push(`${e.var("request")}.basic_auth('${a}', '${i}')`)}return e.blank().push(`${e.var("response")} = ${e.var("http")}.request(${e.var("request")})`).push(`puts ${e.var("response")}.read_body`).blank(),e.join()},V={key:"native",title:"net::http",link:"http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html",description:"Ruby HTTP client"};var Y=C;export{Y as default,V as info};
