@redocly/openapi-docs 3.14.0-next.9 → 3.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/redocly-openapi-docs.min.js +2173 -2089
- package/lib/components/ContentItem/ContentItem.js +1 -1
- package/lib/components/ContentItems/Items.js +1 -1
- package/lib/components/ContentItems/helpers.js +1 -1
- package/lib/components/McpOverview/McpOverview.d.ts +5 -0
- package/lib/components/McpOverview/McpOverview.js +16 -0
- package/lib/components/McpOverview/index.d.ts +1 -0
- package/lib/components/McpOverview/index.js +1 -0
- package/lib/components/McpTool/McpTool.d.ts +6 -0
- package/lib/components/McpTool/McpTool.js +9 -0
- package/lib/components/McpTool/index.d.ts +1 -0
- package/lib/components/McpTool/index.js +1 -0
- package/lib/components/PanelItem/styled.js +1 -0
- package/lib/components/RedoclyOpenAPIDocs/Error.d.ts +3 -0
- package/lib/components/RedoclyOpenAPIDocs/Error.js +25 -0
- package/lib/components/RedoclyOpenAPIDocs/Providers.js +1 -1
- package/lib/components/RedoclyOpenAPIDocs/RedoclyOpenAPIDocsStandalone.js +1 -1
- package/lib/components/Replay/Replay.js +1 -1
- package/lib/components/RightPanel/RightPanel.js +1 -1
- package/lib/components/SectionItem/SectionItem.d.ts +1 -1
- package/lib/components/Security/OAuthFlow.js +1 -1
- package/lib/components/Security/SecurityButton.js +14 -7
- package/lib/components/Security/SecurityFlow.d.ts +1 -1
- package/lib/components/Security/SecurityFlow.js +10 -5
- package/lib/components/ServerList/ServerDescriptionTooltip.d.ts +4 -0
- package/lib/components/ServerList/ServerDescriptionTooltip.js +1 -0
- package/lib/components/ServerList/ServerList.js +14 -9
- package/lib/components/ServerListDropdown/ServerListDropdown.js +1 -1
- package/lib/components/SideMenu/hooks/useMenuItems.js +1 -1
- package/lib/components/TagItem/OperationNavigationItems.js +3 -3
- package/lib/components/TagItem/OperationsNavigation.js +2 -2
- package/lib/components/TagItem/TagItem.js +17 -7
- package/lib/components/TagItem/types.d.ts +2 -2
- package/lib/models/group.js +1 -1
- package/lib/models/types.d.ts +2 -0
- package/lib/services/code-samples/generator.d.ts +9 -2
- package/lib/services/code-samples/generator.js +1 -1
- package/lib/services/code-samples/httpsnippet/helpers/device-auth-snippets.d.ts +25 -0
- package/lib/services/code-samples/httpsnippet/helpers/device-auth-snippets.js +1 -0
- package/lib/services/code-samples/httpsnippet/targets/csharp/httpclient.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/csharpNewtonsoft/httpclient.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/go/native.js +3 -3
- package/lib/services/code-samples/httpsnippet/targets/java/httpclient.js +3 -3
- package/lib/services/code-samples/httpsnippet/targets/java8/apachehttp.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/javascript/fetch.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/node/fetch.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/php/curl.js +5 -5
- package/lib/services/code-samples/httpsnippet/targets/python/requests.js +5 -5
- package/lib/services/code-samples/httpsnippet/targets/r/httr.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/ruby/native.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/shell/curl.js +7 -6
- package/lib/services/menu/builder.js +1 -1
- package/lib/services/menu/tags.d.ts +1 -0
- package/lib/services/menu/tags.js +2 -1
- package/lib/services/types.d.ts +1 -1
- package/lib/standalone.js +1 -1
- package/lib/types/open-api.d.ts +56 -0
- package/lib/utils/hasNestedFields.d.ts +1 -1
- package/lib/utils/helpers.d.ts +2 -0
- package/lib/utils/helpers.js +4 -4
- package/lib/utils/loadAndBundleSpec.js +1 -1
- package/lib/utils/mcp.d.ts +3 -0
- package/lib/utils/mcp.js +1 -0
- package/lib/utils/menu.d.ts +2 -0
- package/lib/utils/menu.js +1 -0
- package/package.json +8 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as oe from"openapi-sampler";import L from"deepmerge";import{isObject as ce}from"@redocly/theme/core/openapi";import{areArraysEqual as ie,serializeParameterValue as P,getSecurityDetails as ue,getParameterValue as M,queryString as j,isArrayOfObjects as le,deleteEmptyArrayItem as pe}from"../../utils/index.js";import{normalizeMimeType as me,arrayMergeStrategy as z}from"../utils.js";import{MediaTypes as m}from"../../constants.js";import{HTTPSnippet as fe}from"./httpsnippet/index.js";import{getActiveMediaType as de}from"../../models/mediaContent.js";import J from"./httpsnippet/helpers/string-utility.js";function v(t,a,s){try{return oe.sample(t,a,s)}catch(c){return console.error(`Error sampling schema: ${c.message}`),null}}function ye(t,a){return t.find(s=>{const c=s.schemes.map(i=>i.id);return ie(c,a||[])})}function he(t,{exampleName:a="",skipOptionalParameters:s=!1,withOAuth2Call:c=!1,spec:i,generatedPayloadSamplesMaxDepth:r=8,pathParams:o={},properties:u={},activeMimeName:n=""},{environment:d,requestValues:k,activeSecuritySchemeIds:T}){const l=d.server,b=t.servers.find(e=>e.url===l)||t.servers[0],w=ye(t.security,T),{securityHeaders:A,securityCookies:F,securityQueries:X,securityOAuth2ExtraCalls:K,basicAuth:Q}=Se(w||t.security?.[0],c,d),p=t?.requestBody?.content&&de(t.requestBody.content,n),O={skipNonRequired:s,skipReadOnly:!0,maxSampleDepth:r,quiet:!0},h=k;let q=!1;const H=t.parameters.filter(e=>e.in==="header").filter(e=>!(s&&!e.required)).map(e=>({name:e.name,value:h.header?.[e.name]||M("header",e.name)||e.serverValues?.[l]?.example||e.example||P(e,v(e.schema.rawSchema,O,i))})).map(e=>(p?.name&&e.name.toLowerCase()==="content-type"&&(q=!0,e.value=p.name),e)).concat(A);!q&&p?.name&&H.unshift({name:"Content-Type",value:p?.name});const G=t.parameters.filter(e=>e.in==="cookie").filter(e=>!(s&&!e.required)).map(e=>j.parse(P(e,e.serverValues?.[l]?.example||e.example||v(e.schema.rawSchema,O,i)))).reduce((e,_)=>{for(const[y,S]of Object.entries(_))e.push({name:y,value:String(h.cookie?.[y]||S)});return e},[]).concat(F),W=t.parameters.filter(e=>e.in==="query").filter(e=>!(s&&!e.required)).map(e=>j.parse(P(e,e.serverValues?.[l]?.example||e.example||v(e.schema.rawSchema,O,i)))).reduce((e,_)=>{for(const[y,S]of Object.entries(_))e.push({name:y,value:le(h.query?.[y])&&JSON.stringify(pe(h.query?.[y]))||String(h.query?.[y]||S)});return e},[]).concat(X),Z=b?.url.replace(/\/$/,""),ee=t.path.replace(/^\//,""),te=`${Z}/${ee}`,re=t.parameters.filter(e=>e.in==="path").reduce((e,_)=>{const{in:y,name:S}=_;return e[S]=h.path?.[S]||_.serverValues?.[l]?.example||_.example||o[S]||M(y,S),e},{}),E=p?.name.toLowerCase(),I=E===m.MULTIPART||E===m.URL_ENCODED,R=I?p?.formExamples?.[a]:p?.examples?.[a],ae=I?p?.formExamples||{}:p?.examples||{},[U]=Object.values(ae),N=R?.serverValues?.[l]?.value||U?.serverValues?.[l]?.value,D=e=>!e||typeof e!="object"||!p?.schema?.rawSchema?null:v(ge(p.schema.rawSchema,e),{...O,format:"xml"},i),C=(()=>{if(h?.body)return h.body;if(E===m.XML){const e=D(N)||D(R?.value)||D(U?.value);if(e)return e;if(p?.schema)return v(p.schema.rawSchema,{...O,format:"xml"},i)}else{const e=p?.schema&&v(p.schema.rawSchema,{...O,format:"json"},i);return N||R?.value||U?.value||e}return""})();let g="",$=[];switch(me(E)){case m.JSON:g=JSON.stringify(V(C,u));break;case m.XML:g=C;break;case m.URL_ENCODED:case m.MULTIPART:g=j.stringify(V(C,u)),$=Y(V(C,u));break;default:g=String(C||"")}const se=g?{mimeType:p?.name||m.OCTET_STREAM,text:g,params:$}:void 0,ne=t.responses.map(e=>e.code);return{method:t.httpVerb,url:te,httpVersion:"HTTP/1.1",cookies:G,headers:H,queryString:W,postData:se,headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:K,basicAuth:Q,pathParameters:re,serverVariables:d,allResponseCodes:ne}}const f={withImports:!0,withComments:!1},x={curl:{code:"shell",defaultTarget:"curl",defaultOptions:{...f,short:!0}},JavaScript:{code:"javascript",defaultTarget:"fetch",defaultOptions:{...f,withImports:!1}},"Node.js":{code:"node",defaultTarget:"fetch",defaultOptions:{...f}},Python:{code:"python",defaultTarget:"requests",defaultOptions:{...f}},"Java8+Apache":{code:"java8",defaultTarget:"apachehttp",defaultOptions:{...f}},Java:{code:"java",defaultTarget:"httpclient",defaultOptions:{...f}},"C#":{code:"csharp",defaultTarget:"httpclient",defaultOptions:{...f}},"C#+Newtonsoft":{code:"csharpNewtonsoft",defaultTarget:"httpclient",defaultOptions:{...f}},Go:{code:"go",defaultTarget:"http.DefaultClient",defaultOptions:{...f}},PHP:{code:"php",defaultTarget:"curl",defaultOptions:{...f}},Ruby:{code:"ruby",defaultTarget:"net::http",defaultOptions:{...f}},R:{code:"r",defaultTarget:"httr",defaultOptions:{...f}}};function Ue({lang:t,operation:a,exampleName:s,pathParams:c,properties:i,options:r={},environment:o,translate:u}){try{const{skipOptionalParameters:n,withOAuth2Call:d,spec:k,generatedPayloadSamplesMaxDepth:T,store:l,activeMimeName:b}=r,w=he(a,{exampleName:s,pathParams:c,properties:i,skipOptionalParameters:n,withOAuth2Call:d,spec:k,generatedPayloadSamplesMaxDepth:T,activeMimeName:b},{environment:o,requestValues:l.requestValues,activeSecuritySchemeIds:l.activeSecuritySchemeIds}),A=new fe(w);return x[t]?A.convert(x[t].code,x[t].defaultTarget,{...x[t].defaultOptions,...r}):u("openapi.unsupportedLanguage","Language is not supported.")}catch(n){return console.error(n),u("openapi.failedToGenerateCodeSample","Failed to generate code sample.")}}function Se(t,a,s){const c={securityHeaders:[],securityCookies:[],securityQueries:[],securityOAuth2ExtraCalls:[],basicAuth:void 0},i=s?.server;for(const r of t?.schemes||[]){const o=ue(r.id,s),u=i&&r.serverValues&&r.serverValues[i],n={access_token:u?.["x-defaultAccessToken"]||r["x-defaultAccessToken"],token_type:u?.["x-defaultTokenType"]||r["x-defaultTokenType"],client_id:u?.["x-defaultClientId"]||r["x-defaultClientId"],client_secret:u?.["x-defaultClientSecret"]||r["x-defaultClientSecret"]},d=u?.["x-defaultUsername"]||r["x-defaultUsername"],k=u?.["x-defaultPassword"]||r["x-defaultPassword"],T=u&&"scopes"in u?u.scopes||[]:r.scopes||[];switch(r.type){case"openIdConnect":c.securityHeaders?.push({name:"Authorization",value:n.access_token?`${n.token_type||"Bearer"} ${n.access_token}`:o.token?`${n.token_type||o.token.token_type||"Bearer"} ${o.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>"});break;case"oauth2":{const l=n.access_token?`${n.token_type||"Bearer"} ${n.access_token}`:o.token?`${o.token.token_type||"Bearer"} ${o.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>";r.flows.clientCredentials&&a?c.securityOAuth2ExtraCalls.push(Te(r.flows.clientCredentials,T,{...o,client_id:n.client_id||o.client_id,client_secret:n.client_secret||o.client_secret})):r.flows.password&&a&&c.securityOAuth2ExtraCalls.push(_e(r.flows.password,T,{...o,client_id:n.client_id||o.client_id,client_secret:n.client_secret||o.client_secret})),c.securityHeaders?.push({name:"Authorization",value:l});break}case"apiKey":{const l=n.access_token||o.raw||"YOUR_API_KEY_HERE";r.in==="header"&&c.securityHeaders?.push({name:r.name,value:l}),r.in==="cookie"&&c.securityCookies.push({name:r.name,value:l}),r.in==="query"&&c.securityQueries.push({name:r.name,value:l});break}case"http":if(r.scheme==="basic")c.basicAuth={username:d||o.username||`<${J.toSnakeCase("Username")}>`,password:k||o.password||`<${J.toSnakeCase("Password")}>`};else{const l=n?.access_token||o.token?.access_token||`<YOUR_${r.bearerFormat||"TOKEN"}_HERE>`;c.securityHeaders?.push({name:"Authorization",value:`${Oe(r.scheme||"bearer")} ${l}`})}break}}return c}function _e(t,a,s){return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:m.URL_ENCODED},{name:"Accept",value:m.JSON}],queryString:[],postData:{mimeType:m.URL_ENCODED,text:"",params:[{name:"grant_type",value:"password"},{name:"client_id",value:s.client_id||"YOUR_CLIENT_ID"},{name:"client_secret",value:s.client_secret||"YOUR_CLIENT_SECRET"},{name:"username",value:s.username||"<username>"},{name:"password",value:s.password||"<password>"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(B)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[]}}function Te(t,a,s){return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:m.URL_ENCODED},{name:"Accept",value:m.JSON}],queryString:[],postData:{mimeType:m.URL_ENCODED,text:"",params:[{name:"grant_type",value:"client_credentials"},{name:"client_id",value:s.client_id||"YOUR_CLIENT_ID"},{name:"client_secret",value:s.client_secret||"YOUR_CLIENT_SECRET"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(B)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[]}}function V(t,a){if(t){if(ce(t))return Object.keys(t).length>0&&Object.keys(a).length===0?t:L(t,a,{arrayMerge:z});try{return L(JSON.parse(t),a,{arrayMerge:z})}catch{return!1}}return!1}function Y(t,a=""){const s=[];for(const[c,i]of Object.entries(t)){const r=a?`${a}[${c}]`:c;if(typeof i=="object"&&i!==null)s.push(...Y(i,r));else{const o=Array.isArray(t)&&typeof i=="string"&&a?a:r;s.push({name:o,value:String(i)})}}return s}function B(t){return t!==void 0}function Oe(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ge(t,a){if(!t||typeof t!="object"||!a||typeof a!="object")return t;const s=JSON.parse(JSON.stringify(t));function c(i,r){if(!(!i||!r||typeof i!="object"||typeof r!="object")&&i.properties){for(const o in i.properties)if(r[o]!==void 0){const u=i.properties[o],n=r[o];if(u.type==="object"&&typeof n=="object"&&!Array.isArray(n))c(u,n);else if(u.type==="array"&&Array.isArray(n)&&n.length>0){const d=n[0];u.items&&u.items.properties&&c(u.items,d)}else u.example=n}}}return c(s,a),s}export{Oe as capitalizeFirst,Ue as getCodeSample,V as getDataRequest,B as isDefined,v as safeSample};
|
|
1
|
+
import*as oe from"openapi-sampler";import $ from"deepmerge";import{isObject as ce}from"@redocly/theme/core/openapi";import{areArraysEqual as ie,serializeParameterValue as I,getSecurityDetails as ue,getParameterValue as M,queryString as P,isArrayOfObjects as le,deleteEmptyArrayItem as pe}from"../../utils/index.js";import{normalizeMimeType as me,arrayMergeStrategy as J}from"../utils.js";import{MediaTypes as p}from"../../constants.js";import{HTTPSnippet as de}from"./httpsnippet/index.js";import{getActiveMediaType as fe}from"../../models/mediaContent.js";import Y from"./httpsnippet/helpers/string-utility.js";function g(t,a,o){try{return oe.sample(t,a,o)}catch(n){return console.error(`Error sampling schema: ${n.message}`),null}}function ye(t,a){return t.find(o=>{const n=o.schemes.map(s=>s.id);return ie(n,a||[])})}function he(t,{exampleName:a="",skipOptionalParameters:o=!1,withOAuth2Call:n=!1,spec:s,generatedPayloadSamplesMaxDepth:r=8,pathParams:i={},properties:u={},activeMimeName:c=""},{environment:f,requestValues:C,activeSecuritySchemeIds:T}){const l=f.server,A=t.servers.find(e=>e.url===l)||t.servers[0],b=ye(t.security,T),{securityHeaders:w,securityCookies:F,securityQueries:X,securityOAuth2ExtraCalls:K,basicAuth:Q}=Se(b||t.security?.[0],n,f),m=t?.requestBody?.content&&fe(t.requestBody.content,c),O={skipNonRequired:o,skipReadOnly:!0,maxSampleDepth:r,quiet:!0},h=C;let N=!1;const H=t.parameters.filter(e=>e.in==="header").filter(e=>!(o&&!e.required)).map(e=>({name:e.name,value:h.header?.[e.name]||M("header",e.name)||e.serverValues?.[l]?.example||e.example||I(e,g(e.schema.rawSchema,O,s))})).map(e=>(m?.name&&e.name.toLowerCase()==="content-type"&&(N=!0,e.value=m.name),e)).concat(w);!N&&m?.name&&H.unshift({name:"Content-Type",value:m?.name});const G=t.parameters.filter(e=>e.in==="cookie").filter(e=>!(o&&!e.required)).map(e=>P.parse(I(e,e.serverValues?.[l]?.example||e.example||g(e.schema.rawSchema,O,s)))).reduce((e,_)=>{for(const[y,S]of Object.entries(_))e.push({name:y,value:String(h.cookie?.[y]||S)});return e},[]).concat(F),W=t.parameters.filter(e=>e.in==="query").filter(e=>!(o&&!e.required)).map(e=>P.parse(I(e,e.serverValues?.[l]?.example||e.example||g(e.schema.rawSchema,O,s)))).reduce((e,_)=>{for(const[y,S]of Object.entries(_))e.push({name:y,value:le(h.query?.[y])&&JSON.stringify(pe(h.query?.[y]))||String(h.query?.[y]||S)});return e},[]).concat(X),Z=A?.url.replace(/\/$/,""),ee=t.path.replace(/^\//,""),te=`${Z}/${ee}`,re=t.parameters.filter(e=>e.in==="path").reduce((e,_)=>{const{in:y,name:S}=_;return e[S]=h.path?.[S]||_.serverValues?.[l]?.example||_.example||i[S]||M(y,S),e},{}),E=m?.name.toLowerCase(),q=E===p.MULTIPART||E===p.URL_ENCODED,R=q?m?.formExamples?.[a]:m?.examples?.[a],ae=q?m?.formExamples||{}:m?.examples||{},[U]=Object.values(ae),L=R?.serverValues?.[l]?.value||U?.serverValues?.[l]?.value,D=e=>!e||typeof e!="object"||!m?.schema?.rawSchema?null:g(ge(m.schema.rawSchema,e),{...O,format:"xml"},s),k=(()=>{if(h?.body)return h.body;if(E===p.XML){const e=D(L)||D(R?.value)||D(U?.value);if(e)return e;if(m?.schema)return g(m.schema.rawSchema,{...O,format:"xml"},s)}else{const e=m?.schema&&g(m.schema.rawSchema,{...O,format:"json"},s);return L||R?.value||U?.value||e}return""})();let v="",z=[];switch(me(E)){case p.JSON:v=JSON.stringify(j(k,u));break;case p.XML:v=k;break;case p.URL_ENCODED:case p.MULTIPART:v=P.stringify(j(k,u)),z=B(j(k,u));break;default:v=String(k||"")}const se=v?{mimeType:m?.name||p.OCTET_STREAM,text:v,params:z}:void 0,ne=t.responses.map(e=>e.code);return{method:t.httpVerb,url:te,httpVersion:"HTTP/1.1",cookies:G,headers:H,queryString:W,postData:se,headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:K,basicAuth:Q,pathParameters:re,serverVariables:f,allResponseCodes:ne}}const d={withImports:!0,withComments:!1},x={curl:{code:"shell",defaultTarget:"curl",defaultOptions:{...d,short:!0}},JavaScript:{code:"javascript",defaultTarget:"fetch",defaultOptions:{...d,withImports:!1}},"Node.js":{code:"node",defaultTarget:"fetch",defaultOptions:{...d}},Python:{code:"python",defaultTarget:"requests",defaultOptions:{...d}},"Java8+Apache":{code:"java8",defaultTarget:"apachehttp",defaultOptions:{...d}},Java:{code:"java",defaultTarget:"httpclient",defaultOptions:{...d}},"C#":{code:"csharp",defaultTarget:"httpclient",defaultOptions:{...d}},"C#+Newtonsoft":{code:"csharpNewtonsoft",defaultTarget:"httpclient",defaultOptions:{...d}},Go:{code:"go",defaultTarget:"http.DefaultClient",defaultOptions:{...d}},PHP:{code:"php",defaultTarget:"curl",defaultOptions:{...d}},Ruby:{code:"ruby",defaultTarget:"net::http",defaultOptions:{...d}},R:{code:"r",defaultTarget:"httr",defaultOptions:{...d}}};function De({lang:t,operation:a,exampleName:o,pathParams:n,properties:s,options:r={},environment:i,translate:u}){try{const{skipOptionalParameters:c,withOAuth2Call:f,spec:C,generatedPayloadSamplesMaxDepth:T,store:l,activeMimeName:A}=r,b=he(a,{exampleName:o,pathParams:n,properties:s,skipOptionalParameters:c,withOAuth2Call:f,spec:C,generatedPayloadSamplesMaxDepth:T,activeMimeName:A},{environment:i,requestValues:l.requestValues,activeSecuritySchemeIds:l.activeSecuritySchemeIds}),w=new de(b);return x[t]?w.convert(x[t].code,x[t].defaultTarget,{...x[t].defaultOptions,...r}):u("openapi.unsupportedLanguage","Language is not supported.")}catch(c){return console.error(c),u("openapi.failedToGenerateCodeSample","Failed to generate code sample.")}}function Se(t,a,o){const n={securityHeaders:[],securityCookies:[],securityQueries:[],securityOAuth2ExtraCalls:[],basicAuth:void 0},s=o?.server;for(const r of t?.schemes||[]){const i=ue(r.id,o),u=s&&r.serverValues&&r.serverValues[s],c={access_token:u?.["x-defaultAccessToken"]||r["x-defaultAccessToken"],token_type:u?.["x-defaultTokenType"]||r["x-defaultTokenType"],client_id:u?.["x-defaultClientId"]||r["x-defaultClientId"],client_secret:u?.["x-defaultClientSecret"]||r["x-defaultClientSecret"]},f=u?.["x-defaultUsername"]||r["x-defaultUsername"],C=u?.["x-defaultPassword"]||r["x-defaultPassword"],T=u&&"scopes"in u?u.scopes||[]:r.scopes||[];switch(r.type){case"openIdConnect":n.securityHeaders?.push({name:"Authorization",value:c.access_token?`${c.token_type||"Bearer"} ${c.access_token}`:i.token?`${c.token_type||i.token.token_type||"Bearer"} ${i.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>"});break;case"oauth2":{const l=c.access_token?`${c.token_type||"Bearer"} ${c.access_token}`:i.token?`${i.token.token_type||"Bearer"} ${i.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>";r.flows.deviceAuthorization&&a?n.securityOAuth2ExtraCalls.push(Te(r.flows.deviceAuthorization,T)):r.flows.clientCredentials&&a?n.securityOAuth2ExtraCalls.push(Oe(r.flows.clientCredentials,T,{...i,client_id:c.client_id||i.client_id,client_secret:c.client_secret||i.client_secret})):r.flows.password&&a&&n.securityOAuth2ExtraCalls.push(_e(r.flows.password,T,{...i,client_id:c.client_id||i.client_id,client_secret:c.client_secret||i.client_secret})),n.securityHeaders?.push({name:"Authorization",value:l});break}case"apiKey":{const l=c.access_token||i.raw||"YOUR_API_KEY_HERE";r.in==="header"&&n.securityHeaders?.push({name:r.name,value:l}),r.in==="cookie"&&n.securityCookies.push({name:r.name,value:l}),r.in==="query"&&n.securityQueries.push({name:r.name,value:l});break}case"http":if(r.scheme==="basic")n.basicAuth={username:f||i.username||`<${Y.toSnakeCase("Username")}>`,password:C||i.password||`<${Y.toSnakeCase("Password")}>`};else{const l=c?.access_token||i.token?.access_token||`<YOUR_${r.bearerFormat||"TOKEN"}_HERE>`;n.securityHeaders?.push({name:"Authorization",value:`${ve(r.scheme||"bearer")} ${l}`})}break}}return n}function Te(t,a){const o=t["x-defaultClientId"]??"YOUR_CLIENT_ID",{tokenUrl:n,deviceAuthorizationUrl:s}=t;return{method:"POST",url:s,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:p.URL_ENCODED},{name:"Accept",value:p.JSON}],queryString:[],postData:{mimeType:p.URL_ENCODED,text:"",params:[{name:"client_id",value:o},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"deviceAuthorization",tokenUrl:n,clientId:o}}function _e(t,a,o){const{tokenUrl:n}=t,s=o.client_id??"YOUR_CLIENT_ID";return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:p.URL_ENCODED},{name:"Accept",value:p.JSON}],queryString:[],postData:{mimeType:p.URL_ENCODED,text:"",params:[{name:"grant_type",value:"password"},{name:"client_id",value:s},{name:"client_secret",value:o.client_secret||"YOUR_CLIENT_SECRET"},{name:"username",value:o.username||"<username>"},{name:"password",value:o.password||"<password>"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"password",tokenUrl:n,clientId:s}}function Oe(t,a,o){const{tokenUrl:n}=t,s=o.client_id??"YOUR_CLIENT_ID";return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:p.URL_ENCODED},{name:"Accept",value:p.JSON}],queryString:[],postData:{mimeType:p.URL_ENCODED,text:"",params:[{name:"grant_type",value:"client_credentials"},{name:"client_id",value:s},{name:"client_secret",value:o.client_secret||"YOUR_CLIENT_SECRET"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"clientCredentials",tokenUrl:n,clientId:s}}function j(t,a){if(t){if(ce(t))return Object.keys(t).length>0&&Object.keys(a).length===0?t:$(t,a,{arrayMerge:J});try{return $(JSON.parse(t),a,{arrayMerge:J})}catch{return!1}}return!1}function B(t,a=""){const o=[];for(const[n,s]of Object.entries(t)){const r=a?`${a}[${n}]`:n;if(typeof s=="object"&&s!==null)o.push(...B(s,r));else{const i=Array.isArray(t)&&typeof s=="string"&&a?a:r;o.push({name:i,value:String(s)})}}return o}function V(t){return t!==void 0}function ve(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ge(t,a){if(!t||typeof t!="object"||!a||typeof a!="object")return t;const o=JSON.parse(JSON.stringify(t));function n(s,r){if(!(!s||!r||typeof s!="object"||typeof r!="object")&&s.properties){for(const i in s.properties)if(r[i]!==void 0){const u=s.properties[i],c=r[i];if(u.type==="object"&&typeof c=="object"&&!Array.isArray(c))n(u,c);else if(u.type==="array"&&Array.isArray(c)&&c.length>0){const f=c[0];u.items&&u.items.properties&&n(u.items,f)}else u.example=c}}}return n(o,a),o}export{ve as capitalizeFirst,De as getCodeSample,j as getDataRequest,V as isDefined,g as safeSample};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { CodeBuilder } from './code-builder';
|
|
2
|
+
interface BuildCodeSnippetParams {
|
|
3
|
+
tokenUrl: string;
|
|
4
|
+
clientId: string;
|
|
5
|
+
level: number;
|
|
6
|
+
responseVariable?: string;
|
|
7
|
+
capitalize?: boolean;
|
|
8
|
+
short?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function buildJSDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: BuildCodeSnippetParams): void;
|
|
11
|
+
export declare function buildPythonDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: BuildCodeSnippetParams): void;
|
|
12
|
+
export declare function buildPHPDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: BuildCodeSnippetParams): void;
|
|
13
|
+
export declare function buildGoDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: BuildCodeSnippetParams): void;
|
|
14
|
+
export declare function buildCSharpDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: BuildCodeSnippetParams): void;
|
|
15
|
+
export declare function buildCSharpNewtonsoftDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: BuildCodeSnippetParams): void;
|
|
16
|
+
export declare function buildJavaDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: BuildCodeSnippetParams): void;
|
|
17
|
+
export declare function buildJava8DeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level }: {
|
|
18
|
+
tokenUrl: string;
|
|
19
|
+
clientId: string;
|
|
20
|
+
level: number;
|
|
21
|
+
}): void;
|
|
22
|
+
export declare function buildRDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level, responseVariable }: BuildCodeSnippetParams): void;
|
|
23
|
+
export declare function buildRubyDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, level, responseVariable, capitalize }: BuildCodeSnippetParams): void;
|
|
24
|
+
export declare function buildShellDeviceAuthorizationCodeSnippet(code: CodeBuilder, { tokenUrl, clientId, short }: BuildCodeSnippetParams): void;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function h(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,`const ${s.var("intervalMs")} = ((oAuth2Data.interval ?? 5) * 1000);`),s.push(t,`const ${s.var("deadline")} = Date.now() + (oAuth2Data.expires_in ?? 600) * 1000;`),s.push(t,`let ${s.var("accessToken")} = '';`),s.blank(),s.push(t,`while (Date.now() < ${s.var("deadline")}) {`),s.push(t+1,`await new Promise(resolve => setTimeout(resolve, ${s.var("intervalMs")}));`),s.blank(),s.push(t+1,`const oAuth2PollResponse = await fetch('${p}', {`),s.push(t+2,"method: 'POST',"),s.push(t+2,"headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },"),s.push(t+2,"body: new URLSearchParams({"),s.push(t+3,"'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',"),s.push(t+3,"'device_code': oAuth2Data.device_code,"),s.push(t+3,`'client_id': '${a}',`),s.push(t+2,"}).toString(),"),s.push(t+1,"});"),s.blank(),s.push(t+1,"const oAuth2PollData = await oAuth2PollResponse.json();"),s.push(t+1,"if (oAuth2PollData.access_token) {"),s.push(t+2,"accessToken = oAuth2PollData.access_token;"),s.push(t+2,"break;"),s.push(t+1,"}"),s.blank(),s.push(t+1,"if (oAuth2PollData.error === 'slow_down') {"),s.push(t+2,`${s.var("intervalMs")} = Math.min(${s.var("intervalMs")} * 2, 10000);`),s.push(t+1,"}"),s.blank(),s.push(t+1,"if (oAuth2PollData.error === 'access_denied' || oAuth2PollData.error === 'expired_token') {"),s.push(t+2,"throw new Error(`Device flow failed: ${oAuth2PollData.error}`);"),s.push(t+1,"}"),s.push(t,"}"),s.blank(),s.push(t,"if (!accessToken) throw new Error('Timed out waiting for authorization');"),s.blank()}function o(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,`${s.var("interval_ms").toLowerCase()} = (oauth2_data.get("interval", 5) * 1000)`),s.push(t,`${s.var("deadline").toLowerCase()} = time.time() + oauth2_data.get("expires_in", 600)`),s.push(t,`${s.var("access_token").toLowerCase()} = ""`),s.blank(),s.push(t,`while time.time() < ${s.var("deadline").toLowerCase()}:`),s.push(t+1,`time.sleep(${s.var("interval_ms").toLowerCase()} / 1000)`),s.blank(),s.push(t+1,"oauth2_poll_response = requests.post("),s.push(t+2,`"${p}",`),s.push(t+2,"data={"),s.push(t+3,'"grant_type": "urn:ietf:params:oauth:grant-type:device_code",'),s.push(t+3,'"device_code": oauth2_data["device_code"],'),s.push(t+3,`"client_id": "${a}"`),s.push(t+2,"},"),s.push(t+2,"headers={"),s.push(t+3,'"Content-Type": "application/x-www-form-urlencoded",'),s.push(t+3,'"Accept": "application/json"'),s.push(t+2,"}"),s.push(t+1,")"),s.blank(),s.push(t+1,"oauth2_poll_data = oauth2_poll_response.json()"),s.blank(),s.push(t+1,'if "access_token" in oauth2_poll_data:'),s.push(t+2,`${s.var("access_token").toLowerCase()} = oauth2_poll_data["access_token"]`),s.push(t+2,"break"),s.blank(),s.push(t+1,'if oauth2_poll_data.get("error") == "slow_down":'),s.push(t+2,`${s.var("interval_ms").toLowerCase()} = min(${s.var("interval_ms").toLowerCase()} * 2, 10000)`),s.blank(),s.push(t+1,'if oauth2_poll_data.get("error") in ["access_denied", "expired_token"]:'),s.push(t+2,`raise Exception(f"Device flow failed: {oauth2_poll_data['error']}")`),s.blank(),s.push(t,`if not ${s.var("access_token").toLowerCase()}:`),s.push(t+1,'raise Exception("Timed out waiting for authorization")'),s.blank()}function _(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,"$intervalMs = ($oAuth2Response->interval ?? 5) * 1000;"),s.push(t,"$deadline = time() + ($oAuth2Response->expires_in ?? 600);"),s.push(t,'$accessToken = "";'),s.blank(),s.push(t,"while (time() < $deadline) {"),s.push(t+1,"usleep($intervalMs * 1000);"),s.blank(),s.push(t+1,"$pollCurl = curl_init();"),s.push(t+1,"curl_setopt_array($pollCurl, ["),s.push(t+2,`CURLOPT_URL => "${p}",`),s.push(t+2,"CURLOPT_RETURNTRANSFER => true,"),s.push(t+2,"CURLOPT_POST => true,"),s.push(t+2,"CURLOPT_POSTFIELDS => http_build_query(["),s.push(t+3,'"grant_type" => "urn:ietf:params:oauth:grant-type:device_code",'),s.push(t+3,'"device_code" => $oAuth2Response->device_code,'),s.push(t+3,`"client_id" => "${a}"`),s.push(t+2,"]),"),s.push(t+2,"CURLOPT_HTTPHEADER => ["),s.push(t+3,'"Content-Type: application/x-www-form-urlencoded",'),s.push(t+3,'"Accept: application/json"'),s.push(t+2,"]"),s.push(t+1,"]);"),s.blank(),s.push(t+1,"$pollResponse = curl_exec($pollCurl);"),s.push(t+1,"curl_close($pollCurl);"),s.push(t+1,"$pollData = json_decode($pollResponse);"),s.blank(),s.push(t+1,"if (isset($pollData->access_token)) {"),s.push(t+2,"$accessToken = $pollData->access_token;"),s.push(t+2,"break;"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if (isset($pollData->error) && $pollData->error === "slow_down") {'),s.push(t+2,"$intervalMs = min($intervalMs * 2, 10000);"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if (isset($pollData->error) && in_array($pollData->error, ["access_denied", "expired_token"])) {'),s.push(t+2,'throw new Exception("Device flow failed: " . $pollData->error);'),s.push(t+1,"}"),s.push(t,"}"),s.blank(),s.push(t,"if (empty($accessToken)) {"),s.push(t+1,'throw new Exception("Timed out waiting for authorization");'),s.push(t,"}"),s.blank()}function k(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,"var intervalMs int64"),s.push(t,"if oAuth2ResBody.Interval != 0 {"),s.push(t+1,"intervalMs = oAuth2ResBody.Interval"),s.push(t,"} else {"),s.push(t+1,"intervalMs = 5"),s.push(t,"}"),s.blank(),s.push(t,"var expiresIn int64"),s.push(t,"if oAuth2ResBody.Expires_in != 0 {"),s.push(t+1,"expiresIn = oAuth2ResBody.Expires_in"),s.push(t,"} else {"),s.push(t+1,"expiresIn = 600"),s.push(t,"}"),s.push(t,"deadline := time.Now().Unix() + expiresIn"),s.push(t,"var accessToken string"),s.blank(),s.push(t,"for time.Now().Unix() < deadline {"),s.push(t+1,"time.Sleep(time.Duration(intervalMs) * time.Second)"),s.blank(),s.push(t+1,"pollData := url.Values{}"),s.push(t+1,'pollData.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")'),s.push(t+1,'pollData.Set("device_code", oAuth2ResBody.Device_code)'),s.push(t+1,`pollData.Set("client_id", "${a}")`),s.blank(),s.push(t+1,`pollReq, err := http.NewRequest("POST", "${p}", strings.NewReader(pollData.Encode()))`),s.push(t+1,"if err != nil {"),s.push(t+2,"panic(err)"),s.push(t+1,"}"),s.blank(),s.push(t+1,'pollReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")'),s.push(t+1,'pollReq.Header.Add("Accept", "application/json")'),s.push(t+1,'pollReq.Header.Add("Content-Length", strconv.Itoa(len(pollData.Encode())))'),s.blank(),s.push(t+1,"pollRes, err := http.DefaultClient.Do(pollReq)"),s.push(t+1,"if err != nil {"),s.push(t+2,"panic(err)"),s.push(t+1,"}"),s.blank(),s.push(t+1,"var pollResBody struct {"),s.push(t+2,"Access_token string"),s.push(t+2,"Error string"),s.push(t+1,"}"),s.push(t+1,"err = json.NewDecoder(pollRes.Body).Decode(&pollResBody)"),s.push(t+1,"if err != nil {"),s.push(t+2,"panic(err)"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if pollResBody.Access_token != "" {'),s.push(t+2,"accessToken = pollResBody.Access_token"),s.push(t+2,"break"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if pollResBody.Error == "slow_down" {'),s.push(t+2,"if intervalMs*2 < 10 {"),s.push(t+3,"intervalMs = intervalMs * 2"),s.push(t+2,"} else {"),s.push(t+3,"intervalMs = 10"),s.push(t+2,"}"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if pollResBody.Error == "access_denied" || pollResBody.Error == "expired_token" {'),s.push(t+2,'panic("Device flow failed: " + pollResBody.Error)'),s.push(t+1,"}"),s.push(t,"}"),s.blank(),s.push(t,'if accessToken == "" {'),s.push(t+1,'panic("Timed out waiting for authorization")'),s.push(t,"}"),s.blank()}function w(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,"using JsonDocument oauth2JsonDoc = JsonDocument.Parse(oauth2Response);"),s.blank(),s.push(t,'var intervalMs = oauth2JsonDoc.RootElement.TryGetProperty("interval", out var intervalProp)'),s.push(t+1,"? intervalProp.GetInt32() * 1000"),s.push(t+1,": 5000;"),s.push(t,'var expiresIn = oauth2JsonDoc.RootElement.TryGetProperty("expires_in", out var expiresProp)'),s.push(t+1,"? expiresProp.GetInt32()"),s.push(t+1,": 600;"),s.push(t,"var deadline = DateTime.UtcNow.AddSeconds(expiresIn);"),s.push(t,'var deviceCode = oauth2JsonDoc.RootElement.GetProperty("device_code").GetString();'),s.push(t,"string accessToken = null;"),s.blank(),s.push(t,"while (DateTime.UtcNow < deadline)"),s.push(t,"{"),s.push(t+1,"await Task.Delay(intervalMs);"),s.blank(),s.push(t+1,"List<KeyValuePair<string, string>> pollData = new List<KeyValuePair<string, string>>();"),s.push(t+1,'pollData.Add(new KeyValuePair<string, string>("grant_type", "urn:ietf:params:oauth:grant-type:device_code"));'),s.push(t+1,'pollData.Add(new KeyValuePair<string, string>("device_code", deviceCode));'),s.push(t+1,`pollData.Add(new KeyValuePair<string, string>("client_id", "${a}"));`),s.blank(),s.push(t+1,"using HttpResponseMessage pollResponse = await oauth2Client.PostAsync("),s.push(t+2,`"${p}",`),s.push(t+2,"new FormUrlEncodedContent(pollData));"),s.blank(),s.push(t+1,"string pollJson = await pollResponse.Content.ReadAsStringAsync();"),s.push(t+1,"using JsonDocument pollDoc = JsonDocument.Parse(pollJson);"),s.blank(),s.push(t+1,'if (pollDoc.RootElement.TryGetProperty("access_token", out var tokenProp))'),s.push(t+1,"{"),s.push(t+2,"accessToken = tokenProp.GetString();"),s.push(t+2,"break;"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if (pollDoc.RootElement.TryGetProperty("error", out var errorProp))'),s.push(t+1,"{"),s.push(t+2,"string errorValue = errorProp.GetString();"),s.push(t+2,'if (errorValue == "slow_down")'),s.push(t+2,"{"),s.push(t+3,"intervalMs = Math.Min(intervalMs * 2, 10000);"),s.push(t+2,"}"),s.push(t+2,'else if (errorValue == "access_denied" || errorValue == "expired_token")'),s.push(t+2,"{"),s.push(t+3,'throw new Exception($"Device flow failed: {errorValue}");'),s.push(t+2,"}"),s.push(t+1,"}"),s.push(t,"}"),s.blank(),s.push(t,"if (string.IsNullOrEmpty(accessToken))"),s.push(t,"{"),s.push(t+1,'throw new Exception("Timed out waiting for authorization");'),s.push(t,"}"),s.blank()}function b(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,"JObject oauth2JObject = JObject.Parse(oauth2Response);"),s.blank(),s.push(t,'var intervalMs = oauth2JObject["interval"] != null'),s.push(t+1,'? (int)oauth2JObject["interval"] * 1000'),s.push(t+1,": 5000;"),s.push(t,'var expiresIn = oauth2JObject["expires_in"] != null'),s.push(t+1,'? (int)oauth2JObject["expires_in"]'),s.push(t+1,": 600;"),s.push(t,"var deadline = DateTime.UtcNow.AddSeconds(expiresIn);"),s.push(t,'var deviceCode = oauth2JObject["device_code"].ToString();'),s.push(t,"string accessToken = null;"),s.blank(),s.push(t,"while (DateTime.UtcNow < deadline)"),s.push(t,"{"),s.push(t+1,"await Task.Delay(intervalMs);"),s.blank(),s.push(t+1,"List<KeyValuePair<string, string>> pollData = new List<KeyValuePair<string, string>>();"),s.push(t+1,'pollData.Add(new KeyValuePair<string, string>("grant_type", "urn:ietf:params:oauth:grant-type:device_code"));'),s.push(t+1,'pollData.Add(new KeyValuePair<string, string>("device_code", deviceCode));'),s.push(t+1,`pollData.Add(new KeyValuePair<string, string>("client_id", "${a}"));`),s.blank(),s.push(t+1,"var pollResponse = await client.PostAsync("),s.push(t+2,`"${p}",`),s.push(t+2,"new FormUrlEncodedContent(pollData));"),s.blank(),s.push(t+1,"string pollJson = await pollResponse.Content.ReadAsStringAsync();"),s.push(t+1,"JObject pollJObject = JObject.Parse(pollJson);"),s.blank(),s.push(t+1,'if (pollJObject["access_token"] != null)'),s.push(t+1,"{"),s.push(t+2,'accessToken = pollJObject["access_token"].ToString();'),s.push(t+2,"break;"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if (pollJObject["error"] != null)'),s.push(t+1,"{"),s.push(t+2,'string errorValue = pollJObject["error"].ToString();'),s.push(t+2,'if (errorValue == "slow_down")'),s.push(t+2,"{"),s.push(t+3,"intervalMs = Math.Min(intervalMs * 2, 10000);"),s.push(t+2,"}"),s.push(t+2,'else if (errorValue == "access_denied" || errorValue == "expired_token")'),s.push(t+2,"{"),s.push(t+3,'throw new Exception($"Device flow failed: {errorValue}");'),s.push(t+2,"}"),s.push(t+1,"}"),s.push(t,"}"),s.blank(),s.push(t,"if (string.IsNullOrEmpty(accessToken))"),s.push(t,"{"),s.push(t+1,'throw new Exception("Timed out waiting for authorization");'),s.push(t,"}"),s.blank()}function f(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,"var oauth2JsonObject = new JSONObject(oauth2Response.body());"),s.blank(),s.push(t,'var intervalMs = oauth2JsonObject.has("interval")'),s.push(t+1,'? oauth2JsonObject.getInt("interval") * 1000'),s.push(t+1,": 5000;"),s.push(t,'var expiresIn = oauth2JsonObject.has("expires_in")'),s.push(t+1,'? oauth2JsonObject.getInt("expires_in")'),s.push(t+1,": 600;"),s.push(t,"var deadline = System.currentTimeMillis() + (expiresIn * 1000L);"),s.push(t,'var deviceCode = oauth2JsonObject.getString("device_code");'),s.push(t,"String accessToken = null;"),s.blank(),s.push(t,"while (System.currentTimeMillis() < deadline) {"),s.push(t+1,"Thread.sleep(intervalMs);"),s.blank(),s.push(t+1,"HashMap<String, String> pollParams = new HashMap<>();"),s.push(t+1,'pollParams.put("grant_type", "urn:ietf:params:oauth:grant-type:device_code");'),s.push(t+1,'pollParams.put("device_code", deviceCode);'),s.push(t+1,`pollParams.put("client_id", "${a}");`),s.blank(),s.push(t+1,"var pollForm = pollParams.keySet().stream()"),s.push(t+2,'.map(key -> key + "=" + URLEncoder.encode(pollParams.get(key), StandardCharsets.UTF_8))'),s.push(t+2,'.collect(Collectors.joining("&"));'),s.blank(),s.push(t+1,"var pollRequest = HttpRequest.newBuilder()"),s.push(t+2,".POST(HttpRequest.BodyPublishers.ofString(pollForm))"),s.push(t+2,`.uri(URI.create("${p}"))`),s.push(t+2,'.header("Content-Type", "application/x-www-form-urlencoded")'),s.push(t+2,'.header("Accept", "application/json")'),s.push(t+2,".build();"),s.blank(),s.push(t+1,"var pollResponse = httpClient.send(pollRequest, HttpResponse.BodyHandlers.ofString());"),s.push(t+1,"var pollJsonObject = new JSONObject(pollResponse.body());"),s.blank(),s.push(t+1,'if (pollJsonObject.has("access_token")) {'),s.push(t+2,'accessToken = pollJsonObject.getString("access_token");'),s.push(t+2,"break;"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if (pollJsonObject.has("error")) {'),s.push(t+2,'String errorValue = pollJsonObject.getString("error");'),s.push(t+2,'if (errorValue.equals("slow_down")) {'),s.push(t+3,"intervalMs = Math.min(intervalMs * 2, 10000);"),s.push(t+2,"}"),s.push(t+2,'else if (errorValue.equals("access_denied") || errorValue.equals("expired_token")) {'),s.push(t+3,'throw new Exception("Device flow failed: " + errorValue);'),s.push(t+2,"}"),s.push(t+1,"}"),s.push(t,"}"),s.blank(),s.push(t,"if (accessToken == null) {"),s.push(t+1,'throw new Exception("Timed out waiting for authorization");'),s.push(t,"}"),s.blank()}function e(s,{tokenUrl:p,clientId:a,level:t}){s.push(t,'var intervalMs = oauth2Response.has("interval") ? oauth2Response.getInt("interval") * 1000 : 5000;'),s.push(t,'var expiresIn = oauth2Response.has("expires_in") ? oauth2Response.getInt("expires_in") : 600;'),s.push(t,"var deadline = System.currentTimeMillis() + (expiresIn * 1000L);"),s.push(t,'var deviceCode = oauth2Response.getString("device_code");'),s.push(t,"String accessToken = null;"),s.blank(),s.push(t,"while (System.currentTimeMillis() < deadline) {"),s.push(t+1,"Thread.sleep(intervalMs);"),s.blank(),s.push(t+1,`HttpPost pollRequest = new HttpPost("${p}");`),s.push(t+1,'pollRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");'),s.push(t+1,'pollRequest.setHeader("Accept", "application/json");'),s.blank(),s.push(t+1,"List<NameValuePair> pollParams = new ArrayList<NameValuePair>();"),s.push(t+1,'pollParams.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:device_code"));'),s.push(t+1,'pollParams.add(new BasicNameValuePair("device_code", deviceCode));'),s.push(t+1,`pollParams.add(new BasicNameValuePair("client_id", "${a}"));`),s.push(t+1,"pollRequest.setEntity(new UrlEncodedFormEntity(pollParams));"),s.blank(),s.push(t+1,"JSONObject pollResponse = new JSONObject(EntityUtils.toString(httpClient.execute(pollRequest).getEntity()));"),s.blank(),s.push(t+1,'if (pollResponse.has("access_token")) {'),s.push(t+2,'accessToken = pollResponse.getString("access_token");'),s.push(t+2,"break;"),s.push(t+1,"}"),s.blank(),s.push(t+1,'if (pollResponse.has("error")) {'),s.push(t+2,'String errorValue = pollResponse.getString("error");'),s.push(t+2,'if (errorValue.equals("slow_down")) {'),s.push(t+3,"intervalMs = Math.min(intervalMs * 2, 10000);"),s.push(t+2,"}"),s.push(t+2,'else if (errorValue.equals("access_denied") || errorValue.equals("expired_token")) {'),s.push(t+3,'throw new RuntimeException("Device flow failed: " + errorValue);'),s.push(t+2,"}"),s.push(t+1,"}"),s.push(t,"}"),s.blank(),s.push(t,"if (accessToken == null) {"),s.push(t+1,'throw new RuntimeException("Timed out waiting for authorization");'),s.push(t,"}"),s.blank()}function m(s,{tokenUrl:p,clientId:a,level:t,responseVariable:n}){const u=n||"oauth2_data_req";s.push(`oauth2_response = content(${u}, "parsed")`),s.blank(),s.push("interval_ms = if (!is.null(oauth2_response$interval)) oauth2_response$interval * 1000 else 5000"),s.push("expires_in = if (!is.null(oauth2_response$expires_in)) oauth2_response$expires_in else 600"),s.push("deadline = as.numeric(Sys.time()) + expires_in"),s.push("device_code = oauth2_response$device_code"),s.push("access_token = NULL"),s.blank(),s.push("while (as.numeric(Sys.time()) < deadline) {"),s.push(t+1,"Sys.sleep(interval_ms / 1000)"),s.blank(),s.push(t+1,"poll_body <- list("),s.push(t+2,'grant_type = "urn:ietf:params:oauth:grant-type:device_code",'),s.push(t+2,"device_code = device_code,"),s.push(t+2,`client_id = "${a}"`),s.push(t+1,")"),s.blank(),s.push(t+1,"poll_response <- POST("),s.push(t+2,`"${p}",`),s.push(t+2,'add_headers("Content-Type" = "application/x-www-form-urlencoded", "Accept" = "application/json"),'),s.push(t+2,"body = poll_body,"),s.push(t+2,'encode = "form",'),s.push(t+2,"verbose()"),s.push(t+1,")"),s.blank(),s.push(t+1,'poll_data = content(poll_response, "parsed")'),s.blank(),s.push(t+1,"if (!is.null(poll_data$access_token)) {"),s.push(t+2,"access_token = poll_data$access_token"),s.push(t+2,"break"),s.push(t+1,"}"),s.blank(),s.push(t+1,"if (!is.null(poll_data$error)) {"),s.push(t+2,'if (poll_data$error == "slow_down") {'),s.push(t+3,"interval_ms = min(interval_ms * 2, 10000)"),s.push(t+2,'} else if (poll_data$error %in% c("access_denied", "expired_token")) {'),s.push(t+3,'stop(paste("Device flow failed:", poll_data$error))'),s.push(t+2,"}"),s.push(t+1,"}"),s.push("}"),s.blank(),s.push("if (is.null(access_token)) {"),s.push(t+1,'stop("Timed out waiting for authorization")'),s.push("}"),s.blank()}function $(s,{tokenUrl:p,clientId:a,level:t,responseVariable:n,capitalize:u}){const i=n||"oAuth2Response",r=u?"OAuth2Data":"oauth2_data";s.push(`${r} = JSON.parse(${i}.body)`),s.blank(),s.push(`interval_ms = (${r}['interval'] || 5) * 1000`),s.push(`expires_in = ${r}['expires_in'] || 600`),s.push("deadline = Time.now.to_i + expires_in"),s.push(`device_code = ${r}['device_code']`),s.push("access_token = nil"),s.blank(),s.push("while Time.now.to_i < deadline"),s.push(t+1,"sleep(interval_ms / 1000.0)"),s.blank(),s.push(t+1,`poll_url = URI('${p}')`),s.push(t+1,"poll_http = Net::HTTP.new(poll_url.host, poll_url.port)"),s.push(t+1,"poll_request = Net::HTTP::Post.new(poll_url)"),s.push(t+1,"poll_request['Content-Type'] = 'application/x-www-form-urlencoded'"),s.push(t+1,"poll_request['Accept'] = 'application/json'"),s.push(t+1,"poll_request.body = URI.encode_www_form({"),s.push(t+2,"grant_type: 'urn:ietf:params:oauth:grant-type:device_code',"),s.push(t+2,"device_code: device_code,"),s.push(t+2,`client_id: '${a}'`),s.push(t+1,"})"),s.blank(),s.push(t+1,"poll_response = poll_http.request(poll_request)"),s.push(t+1,"poll_data = JSON.parse(poll_response.body)"),s.blank(),s.push(t+1,"if poll_data['access_token']"),s.push(t+2,"access_token = poll_data['access_token']"),s.push(t+2,"break"),s.push(t+1,"end"),s.blank(),s.push(t+1,"if poll_data['error']"),s.push(t+2,"if poll_data['error'] == 'slow_down'"),s.push(t+3,"interval_ms = [interval_ms * 2, 10000].min"),s.push(t+2,"elsif ['access_denied', 'expired_token'].include?(poll_data['error'])"),s.push(t+3,`raise "Device flow failed: #{poll_data['error']}"`),s.push(t+2,"end"),s.push(t+1,"end"),s.push("end"),s.blank(),s.push("raise 'Timed out waiting for authorization' if access_token.nil?"),s.blank()}function R(s,{tokenUrl:p,clientId:a,short:t}){s.push(""),s.push("# Parse device code response"),s.push(`DEVICE_CODE=$(echo "$OAUTH2_RESPONSE" | jq -r '.device_code')`),s.push(`INTERVAL=$(echo "$OAUTH2_RESPONSE" | jq -r '.interval // 5')`),s.push(`EXPIRES_IN=$(echo "$OAUTH2_RESPONSE" | jq -r '.expires_in // 600')`),s.push("DEADLINE=$(($(date +%s) + EXPIRES_IN))"),s.push('ACCESS_TOKEN=""'),s.push(""),s.push("# Poll for access token"),s.push("while [ $(date +%s) -lt $DEADLINE ]; do"),s.push(" sleep $INTERVAL"),s.push(""),s.push(` POLL_RESPONSE=$(curl -s ${t?"-X":"--request"} POST \\`),s.push(` ${p} \\`),s.push(` ${t?"-H":"--header"} 'Content-Type: application/x-www-form-urlencoded' \\`),s.push(` ${t?"-H":"--header"} 'Accept: application/json' \\`),s.push(` ${t?"-d":"--data"} grant_type=urn:ietf:params:oauth:grant-type:device_code \\`),s.push(` ${t?"-d":"--data"} device_code=$DEVICE_CODE \\`),s.push(` ${t?"-d":"--data"} client_id=${a})`),s.push(""),s.push(` ACCESS_TOKEN=$(echo "$POLL_RESPONSE" | jq -r '.access_token // empty')`),s.push(' [ ! -z "$ACCESS_TOKEN" ] && break'),s.push(""),s.push(` ERROR=$(echo "$POLL_RESPONSE" | jq -r '.error // empty')`),s.push(' if [ "$ERROR" = "slow_down" ]; then'),s.push(" INTERVAL=$((INTERVAL * 2))"),s.push(" [ $INTERVAL -gt 10 ] && INTERVAL=10"),s.push(' elif [ "$ERROR" = "access_denied" ] || [ "$ERROR" = "expired_token" ]; then'),s.push(' echo "Device flow failed: $ERROR" >&2'),s.push(" exit 1"),s.push(" fi"),s.push("done"),s.push(""),s.push('if [ -z "$ACCESS_TOKEN" ]; then'),s.push(' echo "Timed out waiting for authorization" >&2'),s.push(" exit 1"),s.push("fi"),s.push("")}export{w as buildCSharpDeviceAuthorizationCodeSnippet,b as buildCSharpNewtonsoftDeviceAuthorizationCodeSnippet,k as buildGoDeviceAuthorizationCodeSnippet,h as buildJSDeviceAuthorizationCodeSnippet,e as buildJava8DeviceAuthorizationCodeSnippet,f as buildJavaDeviceAuthorizationCodeSnippet,_ as buildPHPDeviceAuthorizationCodeSnippet,o as buildPythonDeviceAuthorizationCodeSnippet,m as buildRDeviceAuthorizationCodeSnippet,$ as buildRubyDeviceAuthorizationCodeSnippet,R as buildShellDeviceAuthorizationCodeSnippet};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isObject as
|
|
2
|
-
`).forEach((
|
|
1
|
+
import{isObject as y}from"@redocly/theme/core/openapi";import{CodeBuilder as b}from"../../helpers/code-builder.js";import{HTTPSnippet as w}from"../../index.js";import{buildUrlExpression as S,printUrlVariablesDeclarations as A}from"../../helpers/code-helpers.js";import{isEmptyObject as E,normalizeMimeType as m}from"../../../../utils.js";import{capitalizeFirst as O}from"../../../generator.js";import{Lang as k}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";import{isLastInArray as H,isLastProperty as j}from"../../../../../utils/index.js";import{buildCSharpDeviceAuthorizationCodeSnippet as x}from"../../helpers/device-auth-snippets.js";const L=function(e,c,{target:C,client:D}){const r=Object.assign({indent:" ",withWrapper:!0},c),t=new b({indentation:r.indent,variablesPrefix:r.variablesPrefix,capitalize:!0,lang:k.CSHARP}),T=P(e.method);if(r.withComments&&R(t),r.withWrapper&&(t.push("using System;"),t.push("using System.Net.Http;"),t.push("using System.Threading.Tasks;"),(h(i.JSON)||h(i.XML)||e.basicAuth)&&t.push("using System.Text;"),(h(i.URL_ENCODED)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Collections.Generic;"),(h(i.JSON)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Text.Json;"),l()&&t.push("using System.IO;"),(l()||e.basicAuth)&&t.push("using System.Net.Http.Headers;"),t.blank(),t.push("public class Program"),t.push("{"),t.push(1,"public static async Task Main()"),t.push(1,"{")),e.securityOAuth2ExtraCalls?.length){const s=e.securityOAuth2ExtraCalls?.[0],a=new w(s).convert(C,D,{...r,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(a),t.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),s.flowType==="deviceAuthorization"?x(t,{tokenUrl:s.tokenUrl??"YOUR_TOKEN_URL",clientId:s.clientId??"YOUR_CLIENT_ID",level:2}):(t.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),t.push(2,'var accessToken = inputJObject["access_token"].ToString();'),t.blank())}const f=Object.keys(e.allHeaders).filter(s=>{switch(s.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(f.length?(t.push(2,"System.Net.Http.HttpClient client = new()"),t.push(2,"{"),t.push(3,"DefaultRequestHeaders ="),t.push(3,"{"),f.forEach(s=>{const a=s.toLowerCase()==="authorization";t.push(4,'{"%s", %s},',s,e.securityOAuth2ExtraCalls?.length&&a?'"Bearer " + accessToken':`"${e.allHeaders[s]}"`)}),t.push(3,"}"),t.push(2,"};")):t.push(2,"System.Net.Http.HttpClient client = new();"),t.blank(),e.basicAuth){const{username:s,password:a}=e.basicAuth;t.push(2,`string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${s}:${a}"));`),t.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);'),t.blank()}if(e.postData)switch(m(e.postData.mimeType)){case i.URL_ENCODED:e.postData.params&&(t.blank(),t.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),e.postData.params.forEach(s=>{t.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',s.name,s.value)}),t.blank());break;case i.MULTIPART:e.postData.params&&(t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),e.postData.params.forEach(s=>{t.push(2,'postData.Add(new StringContent("%s"), "%s");',s.value,s.name)}));break;case i.JSON:e.postData.jsonObj&&(t.push(2,"string json = JsonSerializer.Serialize(new"),t.push(2,"{"),u(e.postData.jsonObj,3),t.push(2,"});"),t.blank(),t.push(2,'using StringContent postData = new(json, Encoding.UTF8, "%s");',e.postData.mimeType));break;case i.XML:e.postData.text&&(e.postData.text.trim().split(`
|
|
2
|
+
`).forEach((s,a)=>{const n=(a===0?'string xml = @"':"")+s.replace(/"/g,'""');t.push(a===0?2:3,n)}),t.push(2,'";'),t.push(2,'using StringContent postData = new StringContent(xml, Encoding.UTF8, "%s");',e.postData.mimeType));break}else l()&&(t.push(2,"var ms = new MemoryStream();"),t.push(2,"var postData = new StreamContent(ms);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));return A(e,t,3),t.push(2,"using HttpResponseMessage %s = await client.%sAsync(%s%s);",t.var("request"),T,S(e,t),r.withImports?U(e.method)?m(e.postData&&e.postData.mimeType)===i.URL_ENCODED?", new FormUrlEncodedContent(postData)":e.method==="delete"?"":e.postData&&e.postData.params||l()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),r.withWrapper&&(t.push(2,"string response = await request.Content.ReadAsStringAsync();"),t.blank(),t.push(2,"Console.WriteLine(response);"),t.push(1,"}"),t.push("}")),t.join();function h(s){return e.postData&&m(e.postData.mimeType)===s}function l(){return e.headersObj&&e.headersObj["Content-Type"]===i.OCTET_STREAM}function d(s,a){s.forEach((n,p)=>{const o=!H(s,p);Array.isArray(n)?d(n,a+1):y(n)?(t.push(a+1,"new {"),u(n,a+2),t.push(a+1,"}%s",o?",":"")):t.push(a+1,'"%s"%s',n,o?",":"")}),t.push(a,"},")}function u(s,a){for(const[n,p]of Object.entries(s)){const o=!j(s,n);if(Array.isArray(p))t.push(a,"%s = new[] {",n),d(p,a);else if(y(p)){const g=E(p);t.push(a,"%s = new %s",n,g?"{},":"{"),g||(u(p,a+1),t.push(a,"}%s",o?",":""))}else t.push(a,'%s = "%s"%s',n,p,o?",":"")}}},B={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var W=L;function R(e){e.push("// Requires >= .NET 5"),e.blank()}function P(e){return O(e.toLowerCase())}function U(e){return e&&["POST","PUT","DELETE","PATCH"].includes(e.toUpperCase())}export{W as default,B as info};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import f from"stringify-object";import{CodeBuilder as
|
|
2
|
-
`).forEach((a,
|
|
1
|
+
import f from"stringify-object";import{CodeBuilder as C}from"../../helpers/code-builder.js";import{HTTPSnippet as g}from"../../index.js";import{addIndentation as D,buildUrlExpression as T,printUrlVariablesDeclarations as y}from"../../helpers/code-helpers.js";import{normalizeMimeType as o}from"../../../../utils.js";import{capitalizeFirst as w}from"../../../generator.js";import{Lang as b}from"../../helpers/constants.js";import{MediaTypes as s}from"../../../../../constants.js";import{buildCSharpNewtonsoftDeviceAuthorizationCodeSnippet as O}from"../../helpers/device-auth-snippets.js";const S=function(t,l,{target:u,client:m}){const n=Object.assign({indent:" ",withWrapper:!0},l),e=new C({indentation:n.indent,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:b.CSHARPNEWTONSOFT}),c=A(t.method);if(n.withComments&&E(e),n.withWrapper&&(e.push("using System;"),e.push("using System.Net.Http;"),e.push("using System.Threading.Tasks;"),(r(s.JSON)||r(s.XML)||t.basicAuth)&&e.push("using System.Text;"),(r(s.URL_ENCODED)||t.securityOAuth2ExtraCalls?.length)&&e.push("using System.Collections.Generic;"),(r(s.JSON)||t.securityOAuth2ExtraCalls?.length)&&e.push("using Newtonsoft.Json.Linq;"),p()&&e.push("using System.IO;"),(p()||t.basicAuth)&&e.push("using System.Net.Http.Headers;"),e.blank(),e.push("public class Program"),e.push("{"),e.push(1,"private readonly IHttpClientFactory _httpClientFactory;"),e.push(1,"public static async Task Main(string[] args)"),e.push(1,"{"),e.push(2,"var client = _httpClientFactory.CreateClient();")),t.securityOAuth2ExtraCalls?.length){const a=t.securityOAuth2ExtraCalls?.[0],i=new g(a).convert(u,m,{...n,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});e.push(i),e.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),a.flowType==="deviceAuthorization"?O(e,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(e.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),e.push(2,'var accessToken = inputJObject["access_token"].ToString();'),e.blank())}const h=Object.keys(t.allHeaders).filter(a=>{switch(a.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(h.length&&h.forEach(a=>{const i=a.toLowerCase()==="authorization";e.push(2,'client.DefaultRequestHeaders.Add("%s", %s);',a,t.securityOAuth2ExtraCalls?.length&&i?'"Bearer " + accessToken':`"${t.allHeaders[a]}"`)}),t.basicAuth){const{username:a,password:i}=t.basicAuth;e.push(2,`var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${a}:${i}"));`),e.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);')}if(t.postData)switch(o(t.postData.mimeType)){case s.URL_ENCODED:t.postData.params&&(e.blank(),e.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),t.postData.params.forEach(a=>{e.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',a.name,a.value)}),e.blank());break;case s.MULTIPART:t.postData.params&&(e.blank(),e.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),t.postData.params.forEach(a=>{e.push(2,'postData.Add(new StringContent("%s"), "%s");',a.value,a.name)}));break;case s.JSON:t.postData.jsonObj&&(e.push(2,`JObject json = JObject.Parse(@"${D(f(t.postData.jsonObj,{indent:n.indent,inlineCharacterLimit:25}).replace(/"/g,'""'),{level:3,firstLine:!1})}");`),e.push(2,'var postData = new StringContent(json.ToString(), Encoding.UTF8, "%s");',t.postData.mimeType));break;case s.XML:t.postData.text&&(t.postData.text.trim().split(`
|
|
2
|
+
`).forEach((a,i)=>{const d=(i===0?'string xml = @"':"")+a.replace(/"/g,'""');e.push(i===0?3:4,d)}),e.push(2,'";'),e.push(2,'var postData = new StringContent(xml, Encoding.UTF8, "%s");',t.postData.mimeType));break}else p()&&(e.push(2,"var ms = new MemoryStream();"),e.push(2,"var postData = new StreamContent(ms);"),e.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));return y(t,e,3),e.push(2,"var %s = await client.%sAsync(%s%s);",e.var("request"),c,T(t,e),n.withImports?v(t.method)?o(t.postData&&t.postData.mimeType)===s.URL_ENCODED?", new FormUrlEncodedContent(postData)":t.method==="delete"?"":t.postData&&t.postData.params||p()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),n.withWrapper&&(e.push(2,"var response = await request.Content.ReadAsStringAsync();"),e.blank(),e.push(2,"Console.WriteLine(response);"),e.push(1,"}"),e.push("}")),e.join();function r(a){return t.postData&&o(t.postData.mimeType)===a}function p(){return t.headersObj&&t.headersObj["Content-Type"]===s.OCTET_STREAM}},M={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var F=S;function E(t){t.push("/*"),t.push(" * Requires >= .NET 5"),t.push(" *"),t.push(' * Requires package "Newtonsoft.Json" >= 9.01'),t.push(" * See here for installation details:"),t.push(" * https://www.newtonsoft.com/json"),t.push(" */"),t.blank()}function A(t){return w(t.toLowerCase())}function v(t){return t&&["POST","PUT","DELETE","PATCH"].includes(t.toUpperCase())}export{F as default,M as info};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{CodeBuilder as b}from"../../helpers/code-builder.js";import{HTTPSnippet as
|
|
2
|
-
`).map(
|
|
3
|
-
`).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${
|
|
1
|
+
import{CodeBuilder as b}from"../../helpers/code-builder.js";import{HTTPSnippet as $}from"../../index.js";import{Lang as w}from"../../helpers/constants.js";import{buildUrlExpression as q,printUrlVariablesDeclarations as D}from"../../helpers/code-helpers.js";import{normalizeMimeType as c}from"../../../../utils.js";import{MediaTypes as o}from"../../../../../constants.js";import{buildGoDeviceAuthorizationCodeSnippet as N}from"../../helpers/device-auth-snippets.js";const t=1;function u(s={},y){return c(s.mimeType)===y}const g=function(s,y,{target:m,client:f}){const i={capitalize:!0,showBoilerplate:!0,checkErrors:!0,printBody:!0,timeout:-1,indent:" ",...y},p=s.securityOAuth2ExtraCalls?.[0],n=i.checkErrors?"err":"_",d=s.method.toUpperCase(),e=new b({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:i.capitalize,lang:w.GO}),h=()=>{i.checkErrors&&e.push(t,"if err != nil {").push(t+1,"panic(err)").push(t,"}")};if(i.showBoilerplate&&(e.push("package main").blank().push("import (").push(t,'"fmt"'),(i.timeout>0||p?.flowType==="deviceAuthorization")&&e.push(t,'"time"'),p&&e.push(t,'"encoding/json"'),u(s.postData,o.MULTIPART)&&(e.push(t,'"mime/multipart"'),e.push(t,'"io"'),e.push(t,'"bytes"')),(u(s.postData,o.URL_ENCODED)||u(s.securityOAuth2ExtraCalls?.[0]?.postData,o.URL_ENCODED))&&(e.push(t,'"net/url"'),e.push(t,'"strconv"')),(u(s.postData,o.JSON)||u(s.securityOAuth2ExtraCalls?.[0]?.postData,o.JSON))&&e.push(t,'"bytes"'),(s.postData&&!u(s.postData,o.JSON)||p)&&e.push(t,'"strings"'),e.push(t,'"net/http"'),i.printBody&&e.push(t,'"io/ioutil"'),e.push(")").blank().push("func main() {")),Object.keys(s.allHeaders).length&&Object.keys(s.allHeaders).forEach(a=>{s.allHeaders[a]=`"${s.allHeaders[a]}"`}),p){const a="oAuth2",r=i.checkErrors?`${n} := `:"",l=i.capitalize?"Res":"res",v=new $(p).convert(m,f,{...i,printBody:!1,variablesPrefix:a,showBoilerplate:!1});e.push(v).blank(),p.flowType==="deviceAuthorization"?(e.push(t,`var ${a}${l}Body struct {`).push(t+1,"Device_code string").push(t+1,"Interval int64").push(t+1,"Expires_in int64").push(t,"}").push(t,`${r}json.NewDecoder(${a}${l}.Body).Decode(&${a}${l}Body)`).blank(),h(),N(e,{tokenUrl:p.tokenUrl??"YOUR_TOKEN_URL",clientId:p.clientId??"YOUR_CLIENT_ID",level:t}),s.allHeaders.Authorization='"Bearer " + accessToken'):(e.push(t,`var ${a}${l}Body struct {`).push(t+1,"Access_token string").push(t,"}").push(t,`${r}json.NewDecoder(${a}${l}.Body).Decode(&${a}${l}Body)`).blank(),h(),s.allHeaders.Authorization=`"Bearer " + ${a}${l}Body.Access_token`)}if(D(s,e,t),i.timeout>0&&(f=e.var("client"),e.push(t,"%s := http.Client{",f).push(t+1,"Timeout: time.Duration(%s * time.Second),",i.timeout).push(t,"}").blank()),e.push(t,`${e.var("reqUrl")} := ${q(s,e)}`),s.postData){let a;switch(c(s.postData.mimeType)){case o.URL_ENCODED:e.push(t,"%s := url.Values{}",e.var("data")),s.postData.params.forEach(r=>{e.push(t,'%s.Set("%s", "%s")',e.var("data"),r.name,r.value)}),e.push(t,'%s, %s := http.NewRequest("%s", %s, strings.NewReader(%s.Encode()))',e.var("req"),n,d,e.var("reqUrl"),e.var("data")),s.allHeaders["Content-Length"]=`strconv.Itoa(len(${e.var("data")}.Encode()))`;break;case o.JSON:a=JSON.stringify(s.postData.jsonObj,null,2).split(`
|
|
2
|
+
`).map(r=>i.indent+r).join(`
|
|
3
|
+
`).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${a}\`)`),e.push(t,'%s, %s := http.NewRequest("%s", %s, bytes.NewBuffer(%s))',e.var("req"),n,d,e.var("reqUrl"),e.var("data"));break;case o.MULTIPART:e.push(t,"%s := &bytes.Buffer{}",e.var("data")).push(t,"writer := multipart.NewWriter(%s)",e.var("data")),s.postData.params.forEach(r=>{if(!r.fileName&&!r.contentType){e.push(t,'%s, _ := writer.CreateFormField("%s")',e.var(`${r.name}Fw`),r.name).push(t,'_, %s = io.Copy(%s, strings.NewReader("%s"))',n,e.var(`${r.name}Fw`),r.value),h();return}r.fileName&&(e.push(t,'%s, %s = writer.CreateFormFile("%s", "%s")',e.var(`${r.name}Fw`),n,r.name,r.fileName),h())}),e.push(t,"writer.Close()").blank().push(t,"%s := bytes.NewReader(%s.Bytes())",e.var("payload"),e.var("data")).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,d,e.var("reqUrl"),e.var("payload")),s.allHeaders["Content-Type"]="writer.FormDataContentType()";break;default:s.postData.text&&e.push(t,"%s := strings.NewReader(%s)",e.var("payload"),JSON.stringify(s.postData?.text)).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,d,e.var("reqUrl"),e.var("payload"))}}else e.push(t,'%s, %s := http.NewRequest("%s", %s, nil)',e.var("req"),n,d,e.var("reqUrl"));if(Object.getOwnPropertyNames(s.queryObj).length){e.blank().push(t,`${e.var("query")} := ${e.var("req")}.URL.Query()`);for(const a in s.queryObj){const r=s.queryObj[a],v=typeof r=="string"&&/^\[.*\]$/.test(r)?`\`${r}\``:`"${r}"`;e.push(t,`${e.var("query")}.Add("${a}", ${v})`)}e.push(t,`${e.var("req")}.URL.RawQuery = ${e.var("query")}.Encode()`).blank()}if(h(),s.basicAuth){const{username:a,password:r}=s.basicAuth;e.push(t,`%s.SetBasicAuth("${a}", "${r}")`,e.var("req"))}return Object.keys(s.allHeaders).length&&Object.keys(s.allHeaders).forEach(a=>{e.push(t,'%s.Header.Add("%s", %s)',e.var("req"),a,s.allHeaders[a])}),e.push(t,"%s, %s := %s.Do(%s)",e.var("res"),n,f,e.var("req")),h(),i.printBody&&(e.push(t,"defer %s.Body.Close()",e.var("res")).push(t,"%s, %s := ioutil.ReadAll(%s.Body)",e.var("body"),n,e.var("res")),h()),e.blank().push(t,"fmt.Println(%s)",e.var("res")),i.printBody&&e.push(t,"fmt.Println(string(%s))",e.var("body")),i.showBoilerplate&&e.push("}"),e.join()},U={key:"native",title:"NewRequest",link:"http://golang.org/pkg/net/http/#NewRequest",description:"Golang HTTP client request"};var j=g;export{j as default,U as info};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{CodeBuilder as f}from"../../helpers/code-builder.js";import{HTTPSnippet as b}from"../../index.js";import{normalizeMimeType as
|
|
2
|
-
${y(JSON.stringify(t.postData.jsonObj,null,1).replace(/"/g,'\\"').replace(/^/gm,', "').replace(/$/gm,'"'),{level:3,indent:p.indent,firstLine:!1})}`),a.push(2,");"),a.blank());break;case
|
|
3
|
-
`).forEach(e=>{const
|
|
1
|
+
import{CodeBuilder as f}from"../../helpers/code-builder.js";import{HTTPSnippet as b}from"../../index.js";import{normalizeMimeType as o}from"../../../../utils.js";import{addIndentation as y,buildUrlExpression as g,printUrlVariablesDeclarations as v}from"../../helpers/code-helpers.js";import{Lang as c}from"../../helpers/constants.js";import{MediaTypes as n}from"../../../../../constants.js";import{buildJavaDeviceAuthorizationCodeSnippet as C}from"../../helpers/device-auth-snippets.js";const r=t=>!!(t.uriObj.query&&Object.keys(t.uriObj.query).length),h=t=>t.postData&&t.postData.mimeType===n.URL_ENCODED?"HttpRequest.BodyPublishers.ofString(form)":t.postData?"HttpRequest.BodyPublishers.ofString(payload)":["POST","PUT","PATCH"].includes(t.method.toUpperCase())?'HttpRequest.BodyPublishers.ofString("some body text")':"",j=function(t,s,{target:u,client:m}){const p=Object.assign({indent:" ",withWrapper:!0},s),a=new f({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:c.JAVA});if(p.withComments&&k(a,t),p.withImports&&O(a,t),p.withWrapper&&(a.push("public class App {"),a.push(1,"public static void main(String[] args) throws Exception {"),a.push(2,"var httpClient = HttpClient.newBuilder().build();"),a.blank()),t.securityOAuth2ExtraCalls?.length){const e=t.securityOAuth2ExtraCalls?.[0],i=new b(e).convert(u,m,{...p,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});a.push(i),a.blank(),a.push(2,"var oauth2Response = httpClient.send(oauth2Request, HttpResponse.BodyHandlers.ofString());"),e.flowType==="deviceAuthorization"?C(a,{tokenUrl:e.tokenUrl??"YOUR_TOKEN_URL",clientId:e.clientId??"YOUR_CLIENT_ID",level:2}):(a.push(2,'var accessToken = new JSONObject(oauth2Response.body()).getString("access_token");'),a.blank())}if(t.postData)switch(o(t.postData.mimeType)){case n.URL_ENCODED:t.postData.params&&(a.push(2,"HashMap<String, String> params = new HashMap<>();"),t.postData.params.forEach(e=>{a.push(2,'params.put("%s", "%s");',e.name,e.value)}),a.blank(),a.push(2,"var form = params.keySet().stream()"),a.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),a.push(3,'.collect(Collectors.joining("&"));'),a.blank());break;case n.JSON:t.postData.jsonObj&&(a.push(2,`var payload = String.join("\\n"
|
|
2
|
+
${y(JSON.stringify(t.postData.jsonObj,null,1).replace(/"/g,'\\"').replace(/^/gm,', "').replace(/$/gm,'"'),{level:3,indent:p.indent,firstLine:!1})}`),a.push(2,");"),a.blank());break;case n.XML:t.postData.text&&(a.push(2,'var payload = String.join("\\n"'),t.postData.text.trim().split(`
|
|
3
|
+
`).forEach(e=>{const i=e.replace(/"/g,'\\"');a.push(3,`"${i}", `)}),a.push(2,");"),a.blank());break;case n.MULTIPART:t.postData.params&&(a.push(2,"var multipartBody = MultipartBodyPublisher.newBuilder();"),t.postData.params&&t.postData.params.forEach(e=>{a.push(2,'multipartBody.append("%s", "%s");',e.name,e.value)}),a.push(2,"var body = multipartBody.build();"),a.blank());break}if(r(t)){a.push(2,"HashMap<String, String> params = new HashMap<>();");for(const[e,i]of Object.entries(t.uriObj.query))a.push(2,'params.put("%s", "%s");',e,i);a.blank(),a.push(2,"var query = params.keySet().stream()"),a.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),a.push(3,'.collect(Collectors.joining("&"));'),a.blank()}a.push(2,`var ${a.var("host")} = "%s";`,t.uriObj.protocol+"//"+t.uriObj.host),v(t,a,2);const d={...t,pathname:t.uriObj.pathname};a.push(2,`var ${a.var("pathname")} = %s;`,g(d,a)),a.push(2,`var ${a.var("request")} = HttpRequest.newBuilder()`),t.method.toUpperCase()==="PATCH"?a.push(3,'.method("PATCH", %s)',h(t)):a.push(3,".%s(%s)",t.method.toUpperCase(),h(t)),a.push(3,`.uri(URI.create(${a.var("host")} + ${a.var("pathname")} %s))`,r(t)?"+ '?' + query":""),t.securityOAuth2ExtraCalls?.length&&(t.allHeaders.Authorization='"Bearer " + accessToken');const l=Object.keys(t.allHeaders);if(l.length&&l.forEach(e=>{a.push(3,'.header("%s", %s)',e,e==="Authorization"&&t.securityOAuth2ExtraCalls?.length?t.allHeaders[e]:`"${t.allHeaders[e]}"`)}),t.basicAuth){const{username:e,password:i}=t.basicAuth;a.push(3,`.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(("${e}:${i}").getBytes()))`)}return a.push(3,".build();"),p.withWrapper&&(a.blank(),a.push(2,"var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());"),a.blank(),a.push(2,"System.out.println(response.body());"),a.push(1,"}"),a.push("}")),a.join()},U={key:"httpclient",title:"HttpClient",link:"https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html",description:"HttpClient (Java SE 11 & JDK 11 )"};var w=j;function k(t,s){t.push("/**"),t.push(" * Requires JDK >= 11"),s.securityOAuth2ExtraCalls?.length&&(t.push(" *"),t.push(' * Requires package "org.json" >= 20201115'),t.push(" * See here for installation details:"),t.push(" * https://search.maven.org/artifact/org.json/json")),t.push(" */"),t.blank()}function O(t,s){t.push("import java.net.*;"),t.push("import java.net.http.*;"),t.push("import java.util.*;"),(o(s.postData?.mimeType)===n.URL_ENCODED&&s.postData?.params||s.securityOAuth2ExtraCalls?.length||r(s))&&(t.push("import java.nio.charset.StandardCharsets;"),t.push("import java.util.stream.Collectors;")),s.securityOAuth2ExtraCalls?.length&&t.push("import org.json.JSONObject;"),t.blank()}export{w as default,U as info};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CodeBuilder as
|
|
2
|
-
`).forEach(a=>{const s=a.replace(/"/g,'\\"');e.push(3,`"${s}", `)}),e.push(2,");"),e.push(2,"%s.setEntity(new StringEntity(payload));",e.var("request")));break}return p.withWrapper&&(e.push(2,`String ${e.var("response")} = EntityUtils.toString(httpClient.execute(request).getEntity());`),e.blank(),e.push(2,"System.out.println(response);"),e.push(1,"}"),e.push("}")),e.join();function o(a,s){for(const[r,u]of Object.entries(a))l(u)?(e.push(s,'.put("%s", new JSONObject()',r),o(u,s+1),e.push(s,")")):e.push(s,'.put("%s", %s)',r,m(u))}},
|
|
1
|
+
import{CodeBuilder as d}from"../../helpers/code-builder.js";import{HTTPSnippet as j}from"../../index.js";import{isEmptyObject as y,normalizeMimeType as w}from"../../../../utils.js";import{capitalizeFirst as A}from"../../../generator.js";import{Lang as C}from"../../helpers/constants.js";import{buildUrlExpression as v,printUrlVariablesDeclarations as N}from"../../helpers/code-helpers.js";import{MediaTypes as n}from"../../../../../constants.js";import{buildJava8DeviceAuthorizationCodeSnippet as k}from"../../helpers/device-auth-snippets.js";const x=function(t,i,{target:h,client:E}){const p=Object.assign({indent:" ",withWrapper:!0},i),e=new d({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:C.JAVA8}),c=O(t.method);if(p.withComments&&D(e),p.withImports&&L(e,t),p.withWrapper&&(e.push("public class App {"),e.push(1,"public static void main(String[] args ) throws java.io.IOException {"),e.push(2,"HttpClient httpClient = HttpClientBuilder.create().build();"),e.blank()),t.securityOAuth2ExtraCalls?.length){const a=t.securityOAuth2ExtraCalls?.[0],s=new j(a).convert(h,E,{...p,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});e.push(s),e.push(2,"JSONObject %s = new JSONObject(EntityUtils.toString(httpClient.execute(%s).getEntity()));","oauth2Response","oauth2Request"),a.flowType==="deviceAuthorization"?k(e,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(e.push(2,'String accessToken = %s.getString("access_token");',"oauth2Response"),e.blank())}N(t,e,2);const S=v(t,e);e.push(2,`%s ${e.var("request")} = new %s(%s);`,c,c,S);const f=Object.keys(t.allHeaders);if(f.length&&!(t.postData&&t.postData.mimeType==n.MULTIPART)&&f.forEach(a=>{const s=a.toLowerCase()==="authorization";e.push(2,'%s.setHeader("%s", %s);',e.var("request"),a,t.securityOAuth2ExtraCalls?.length&&s?'"Bearer " + accessToken':`"${t.allHeaders[a]}"`)}),t.basicAuth){const{username:a,password:s}=t.basicAuth;e.push(2,`String encodedString = Base64.getEncoder().encodeToString("${a}:${s}".getBytes());`),e.push(2,'%s.setHeader("%s", "%s"+encodedString);',e.var("request"),"Authorization","Basic ")}if(t.postData)switch(w(t.postData.mimeType)){case n.URL_ENCODED:t.postData.params&&(e.blank(),e.push(2,"List<NameValuePair> params = new ArrayList<NameValuePair>();"),t.postData.params.forEach(a=>{e.push(2,'params.add(new BasicNameValuePair("%s", "%s"));',a.name,a.value)}),e.push(2,"%s.setEntity(new UrlEncodedFormEntity(params));",e.var("request")),e.blank());break;case n.MULTIPART:t.postData.params&&(e.push(2,"MultipartEntity reqEntity = new MultipartEntity();"),t.postData.params.forEach(a=>{e.push(2,'reqEntity.addPart("%s", %s);',a.name,b(a.value)?`new StringBody("${a.value}")`:a.value)}),e.push(2,"%s.setEntity(reqEntity);",e.var("request")));break;case n.JSON:if(t.postData.jsonObj){e.push(2,"JSONObject payload = new JSONObject();");for(const[a,s]of Object.entries(t.postData.jsonObj))Array.isArray(s)?(e.push(2,'payload.put("%s", new JSONArray()',a),s.forEach(r=>{l(r)?(e.push(3,".put(new JSONObject()"),o(r,4),e.push(3,")")):e.push(3,".put(%s)",m(r))}),e.push(2,");")):l(s)?(e.push(2,'payload.put("%s", new JSONObject()%s',a,y(s)?");":""),o(s,3),y(s)||e.push(2,");")):e.push(2,'payload.put("%s", %s);',a,m(s));e.push(2,"%s.setEntity(new StringEntity(payload.toString()));",e.var("request"))}break;case n.XML:t.postData.text&&(e.push(2,'String payload = String.join("\\n"'),t.postData.text.trim().split(`
|
|
2
|
+
`).forEach(a=>{const s=a.replace(/"/g,'\\"');e.push(3,`"${s}", `)}),e.push(2,");"),e.push(2,"%s.setEntity(new StringEntity(payload));",e.var("request")));break}return p.withWrapper&&(e.push(2,`String ${e.var("response")} = EntityUtils.toString(httpClient.execute(request).getEntity());`),e.blank(),e.push(2,"System.out.println(response);"),e.push(1,"}"),e.push("}")),e.join();function o(a,s){for(const[r,u]of Object.entries(a))l(u)?(e.push(s,'.put("%s", new JSONObject()',r),o(u,s+1),e.push(s,")")):e.push(s,'.put("%s", %s)',r,m(u))}},I={key:"apachehttp",title:"Apache http",link:"https://hc.apache.org/httpcomponents-client-4.5.x/",description:"Apache HttpClient"};var M=x;function D(t){t.push("/**"),t.push(" * Requires JDK >= 8"),t.push(" *"),t.push(" * Requires Apache HttpComponents Client >= 4.3.5"),t.push(" * See here for installation details:"),t.push(" * https://search.maven.org/artifact/org.apache.httpcomponents/httpcomponents-client"),t.push(" *"),t.push(' * Requires package "junit4"'),t.push(" * See here for installation details:"),t.push(" * https://junit.org/junit4"),t.push(" *"),t.push(' * Requires package "org.json" >= 20180130'),t.push(" * See here for installation details:"),t.push(" * https://search.maven.org/artifact/org.json/json"),t.push(" */"),t.blank()}function L(t,i){t.push("import org.apache.http.util.EntityUtils;"),t.push("import org.apache.http.NameValuePair;"),t.push("import org.apache.http.client.HttpClient;"),t.push("import org.apache.http.client.entity.UrlEncodedFormEntity;"),i.method&&g(t,i.method),i.securityOAuth2ExtraCalls?.length&&i.securityOAuth2ExtraCalls?.[0].method.toLowerCase()!==i.method.toLowerCase()&&g(t,i.securityOAuth2ExtraCalls?.[0].method),t.push("import org.apache.http.impl.client.HttpClientBuilder;"),t.push("import org.apache.http.message.BasicNameValuePair;"),t.push("import org.apache.http.entity.StringEntity;"),t.push("import org.json.JSONObject;"),t.push("import org.json.JSONArray;"),t.push("import java.util.ArrayList;"),t.push("import java.util.List;"),t.push("import org.apache.http.entity.mime.MultipartEntity;"),t.push("import org.apache.http.entity.mime.content.StringBody;"),i.basicAuth&&t.push("import java.util.Base64;"),t.blank()}function g(t,i){const h=O(i);t.push(`import org.apache.http.client.methods.${h};`)}function O(t){return"Http"+A(t.toLowerCase())}function b(t){return Object.prototype.toString.call(t)==="[object String]"}function l(t){const i=typeof t;return i==="function"||i==="object"&&!!t}function m(t){return b(t)?JSON.stringify(t):t??"JSONObject.NULL"}export{M as default,I as info};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import r from"stringify-object";import{CodeBuilder as v}from"../../helpers/code-builder.js";import{addIndentation as o,getPreserveTransformer as
|
|
1
|
+
import r from"stringify-object";import{CodeBuilder as v}from"../../helpers/code-builder.js";import{addIndentation as o,getPreserveTransformer as O,buildUrlExpression as y,printUrlVariablesDeclarations as $}from"../../helpers/code-helpers.js";import{normalizeMimeType as h}from"../../../../utils.js";import{HTTPSnippet as A}from"../../index.js";import{Lang as D}from"../../helpers/constants.js";import{MediaTypes as s}from"../../../../../constants.js";import{buildJSDeviceAuthorizationCodeSnippet as g}from"../../helpers/device-auth-snippets.js";const C=function(t,m,{target:c,client:u}){const i={indent:" ",credentials:null,...m},e=new v({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:!0,lang:D.JAVASCRIPT}),a={method:t.method.toUpperCase()};Object.keys(t.headersObj).length&&(a.headers=t.headersObj);let l=!1;if(i.withComments&&j(e),t.securityOAuth2ExtraCalls?.length){const n=t.securityOAuth2ExtraCalls?.[0],p=new A(n).convert(c,u,{...i,withImports:!1,withComments:!1,variablesPrefix:"oAuth2"});e.push(p),e.blank(),n.flowType==="deviceAuthorization"&&g(e,{tokenUrl:n.tokenUrl??"YOUR_TOKEN_URL",clientId:n.clientId??"YOUR_CLIENT_ID",level:0}),a.headers=a.headers||{},a.headers.Authorization="'Bearer ' + accessToken",l=!0}i.credentials!==null&&(a.credentials=i.credentials);const d=Object.getOwnPropertyNames(t.queryObj).length;if(d&&e.push(`const ${e.var("query")} = new URLSearchParams(${r(t.queryObj,{indent:i.indent,inlineCharacterLimit:25})}).toString();`).blank(),t.postData)switch(h(t.postData.mimeType)){case s.URL_ENCODED:a.body=t.postData.paramsObj?`new URLSearchParams(${e.var("formData")}).toString()`:t.postData.text,t.postData.paramsObj&&e.push(`const ${e.var("formData")} = ${o(r(t.postData.paramsObj,{indent:i.indent,inlineCharacterLimit:25}),{level:0,firstLine:!1})};`).blank();break;case s.JSON:t.postData.jsonObj&&(a.body=`JSON.stringify(${o(r(t.postData.jsonObj,{indent:i.indent,inlineCharacterLimit:25}),{level:1,firstLine:!1})})`);break;case s.MULTIPART:e.push(`const ${e.var("form")} = new FormData();`),delete a?.headers?.["Content-Type"],t.postData.params.forEach(function(n){e.push(`${e.var("form")}.append(%s, %s);`,JSON.stringify(n.name),JSON.stringify(n.value||n.fileName||""))}),a.body=e.var("form"),e.blank();break;default:t.postData.text&&(a.body=`\`${o(t.postData.text,{level:2,indent:i.indent,firstLine:!1}).trim()}\``)}const f=a.headers&&a.headers.Accept&&h(a.headers.Accept)===s.JSON||h(t.postData?.mimeType)===s.JSON;if(t.basicAuth){const{username:n,password:p}=t.basicAuth;a.headers=a.headers||{},a.headers.Authorization=`'Basic ' + btoa('${n}:${p}')`,l=!0}$(t,e);const b=y(t,e);return e.push(`const ${e.var("resp")} = await fetch(`).push(1,"`"+b+(d?"?${"+e.var("query")+"}":"")+"`,").push(o(r(a,{indent:i.indent,inlineCharacterLimit:25,transform:O({body:!0,authorizationHeader:l})}),{level:1,indent:i.indent})).push(");").blank(),t.allResponseCodes?.includes("204")?(e.push("if (resp.status === 204) {").push(1,"console.log('success');").push("} else {"),e.push(1,`const ${e.var("data")} = await ${e.var("resp")}.${f?"json()":"text()"};`).push(1,`console.log(${e.var("data")});`).push("}")):e.push(`const ${e.var("data")} = await ${e.var("resp")}.${f?"json()":"text()"};`).push(`console.log(${e.var("data")});`),e.join()};function j(t){t.push("/**"),t.push(" * Requires ES8-compatible browser: https://caniuse.com/async-functions"),t.push(" */"),t.blank()}const N={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 I=C;export{I as default,N as info};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import p from"stringify-object";import{CodeBuilder as y}from"../../helpers/code-builder.js";import{addIndentation as o,getPreserveTransformer as w,buildUrlExpression as k,printUrlVariablesDeclarations as D}from"../../helpers/code-helpers.js";import{Lang as $}from"../../helpers/constants.js";import{normalizeMimeType as f}from"../../../../utils.js";import{HTTPSnippet as g}from"../../index.js";import{MediaTypes as l}from"../../../../../constants.js";import{buildJSDeviceAuthorizationCodeSnippet as j}from"../../helpers/device-auth-snippets.js";const C=function(t,u,{target:b,client:v}){const s=Object.assign({indent:" ",showBoilerplate:!0,level:1},u),{level:a}=s;let d=!1;const e=new y({indentation:s.indent,variablesPrefix:s.variablesPrefix,capitalize:!0,lang:$.NODEJS});s.withComments&&S(e),s.withImports&&(e.push("import fetch from 'node-fetch';"),e.blank()),s.showBoilerplate&&e.push("async function run() {");const i={method:t.method.toUpperCase()};Object.keys(t.headersObj).length&&(i.headers=t.headersObj);let h=!1;if(t.securityOAuth2ExtraCalls?.length){const n=t.securityOAuth2ExtraCalls?.[0],r=new g(n).convert(b,v,{...s,withImports:!1,withComments:!1,variablesPrefix:"oAuth2",showBoilerplate:!1,level:1});e.push(r),e.blank(),n.flowType==="deviceAuthorization"&&j(e,{tokenUrl:n.tokenUrl??"YOUR_TOKEN_URL",clientId:n.clientId??"YOUR_CLIENT_ID",level:a}),i.headers=i.headers||{},i.headers.Authorization="'Bearer ' + accessToken",h=!0}const m=Object.getOwnPropertyNames(t.queryObj).length;if(m&&e.push(a,`const ${e.var("query")} = new URLSearchParams(${o(p(t.queryObj,{indent:s.indent,inlineCharacterLimit:25}),{level:a,indent:s.indent,firstLine:!1})}).toString();`).blank(),t.postData)switch(f(t.postData.mimeType)){case l.URL_ENCODED:i.body=t.postData.paramsObj?`new URLSearchParams(${e.var("formData")}).toString()`:t.postData.text,t.postData.paramsObj&&e.push(a,`const ${e.var("formData")} = ${o(p(t.postData.paramsObj,{indent:s.indent,inlineCharacterLimit:25}),{level:a,firstLine:!1})};`).blank();break;case l.JSON:t.postData.jsonObj&&(i.body=`JSON.stringify(${o(p(t.postData.jsonObj,{indent:s.indent,inlineCharacterLimit:25}),{level:a,firstLine:!1})})`);break;case l.MULTIPART:delete i?.headers?.["Content-Type"],s.withImports&&e.unshift("import FormData from 'form-data';"),e.push(a,`const ${e.var("form")} = new FormData();`),t.postData.params.forEach(function(n){if(!n.fileName&&!n.fileName&&!n.contentType){e.push(a,"form.append('"+n.name+"','"+n.value+"');");return}n.fileName&&(d=!0,e.blank(),e.push(a,`${e.var("form")}.append('" + param.name + "', fs.createReadStream('" + param.fileName + "'));`))}),i.body=e.var("form"),e.blank();break;default:t.postData.text&&(i.body=`\`${o(t.postData.text,{level:a+1,indent:s.indent,firstLine:!1}).trim()}\``)}if(t.cookies.length){let n="";t.cookies.forEach(function(r){n=n+encodeURIComponent(r.name)+"="+encodeURIComponent(r.value)+"; "}),n=n.trim(),i.headers||(i.headers={}),i.headers.cookie=n}if(t.basicAuth){const{username:n,password:r}=t.basicAuth;i.headers=i.headers||{},i.headers.Authorization=`'Basic ' + Buffer.from('${n}:${r}').toString('base64')`,h=!0}d&&s.withImports&&e.unshift("import fs from 'fs';");const c=i.headers&&i.headers.Accept&&f(i.headers.Accept)===l.JSON||f(t.postData?.mimeType)===l.JSON;D(t,e,a);const O=k(t,e);return e.push(a,`const ${e.var("resp")} = await fetch(`).push(a+1,"`"+O+(m?"?${"+e.var("query")+"}":"")+"`,").push(a+1,o(p(i,{indent:s.indent,inlineCharacterLimit:25,transform:w({body:!0,authorizationHeader:h})}),{level:a+1,indent:s.indent,firstLine:!1})).push(a,");").blank(),t.allResponseCodes?.includes("204")?(e.push(a,"if (resp.status === 204) {").push(a+1,"console.log('success');").push(a,"} else {"),e.push(a+1,`const ${e.var("data")} = await ${e.var("resp")}.${c?"json()":"text()"};`).push(a+1,`console.log(${e.var("data")});`).push(a,"}")):e.push(a,`const ${e.var("data")} = await ${e.var("resp")}.${c?"json()":"text()"};`).push(a,`console.log(${e.var("data")});`),s.showBoilerplate&&e.push("}").blank().push("run();"),e.join().replace(/"fs\.createReadStream\(\\"(.+)\\"\)"/,'fs.createReadStream("$1")')};function S(t){t.push("/**"),t.push(" * Requires Node.js >= 14"),t.push(" *"),t.push(' * Requires module "node-fetch" >= 2.6.1'),t.push(" * See here for installation details:"),t.push(" * https://www.npmjs.com/package/node-fetch"),t.push(" */"),t.blank()}const E={key:"fetch",title:"Fetch",link:"https://github.com/bitinn/node-fetch",description:"Simplified HTTP node-fetch client"};var P=C;export{P as default,E as info};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{format as
|
|
2
|
-
`).join("");
|
|
3
|
-
${e});`).blank();break}case T.URL_ENCODED:{const e=a.postData.params.map(({name:
|
|
4
|
-
${
|
|
5
|
-
`+
|
|
1
|
+
import{format as m}from"util";import{CodeBuilder as P}from"../../helpers/code-builder.js";import{HTTPSnippet as v}from"../../index.js";import{Lang as _}from"../../helpers/constants.js";import{buildUrlExpression as E,printUrlVariablesDeclarations as g}from"../../helpers/code-helpers.js";import{startCase as j}from"../../helpers/lodash-int.js";import{normalizeMimeType as A}from"../../../../utils.js";import{MediaTypes as T}from"../../../../../constants.js";import{objectToPhpArray as R}from"./utils.js";import{buildPHPDeviceAuthorizationCodeSnippet as L}from"../../helpers/device-auth-snippets.js";function b(a,c){return c?`$${c}${j(a)}`:`$${a}`}const x=function(a,c,{target:U,client:k}){const n={showBoilerplate:!0,checkErrors:!1,printBody:!0,indent:" ",noTags:!0,shortTags:!1,maxRedirects:10,namedErrors:!1,closingTag:!1,...c};let i,h=!1;const t=new P({indentation:n.indent,capitalize:!0,lang:_.PHP}),r=a.securityOAuth2ExtraCalls?.[0],o=b("curl",n.variablesPrefix),y=b("response",n.variablesPrefix),d=b("error",n.variablesPrefix);if(n.noTags||t.push(n.shortTags?"<?":"<?php").blank(),r){const e="oAuth2",s=new v(r).convert(U,k,{...n,showBoilerplate:!1,variablesPrefix:e});t.push(s),t.blank(),r.flowType==="deviceAuthorization"&&L(t,{tokenUrl:r.tokenUrl??"YOUR_TOKEN_URL",clientId:r.clientId??"YOUR_CLIENT_ID",level:0});const u=r.flowType==="deviceAuthorization"?"$accessToken":`${b("response",e)}->access_token`;a.allHeaders.Authorization=`Bearer " . ${u}`}const $=Object.keys(a.headersObj).sort().map(function(e){return e==="Authorization"&&r?m('"%s: %s',e,a.allHeaders.Authorization):m('"%s: %s"',e,a.headersObj[e])});if(a.basicAuth){const{username:e,password:s}=a.basicAuth;$.push(`"Authorization: Basic " . base64_encode("${e}:${s}")`)}n.showBoilerplate&&t.push("/**").push(" * Requires libcurl").push(" */").blank(),g(a,t);let l="";if(Object.keys(a.queryObj||{}).length){const e=R(a.queryObj||{},{indent:n.indent});l="$query",t.push(`${l} = ${e};`).blank()}if(t.push(`${o} = curl_init();`),t.blank(),a.postData)switch(A(a.postData.mimeType)){case T.JSON:{const e=R(a.postData.jsonObj||{},{indent:n.indent});h=!0,i="json_encode($payload)",t.push(`$payload = ${e};`).blank();break}case T.MULTIPART:{const e=a.postData.params.map(({name:s,value:u})=>`${n.indent}"${s}" => "${u}",
|
|
2
|
+
`).join("");h=!0,i="$payload",t.push(`$payload = array(
|
|
3
|
+
${e});`).blank();break}case T.URL_ENCODED:{const e=a.postData.params.map(({name:s,value:u})=>`${s}=${u}`).join("&");h=!0,i="$payload",t.push(`$payload = "${e}";`).blank();break}default:i=a.postData.text;break}let p=E(a,t);l&&(p.endsWith('"')?p=p.slice(0,-1)+`?" . http_build_query(${l})`:p+=` . "?" . http_build_query(${l})`);const C=[{escape:!h,name:"CURLOPT_POSTFIELDS",value:i},{escape:!0,name:"CURLOPT_PORT",value:a.uriObj.port},{escape:!1,name:"CURLOPT_URL",value:p},{escape:!1,name:"CURLOPT_RETURNTRANSFER",value:"true"},{escape:!0,name:"CURLOPT_CUSTOMREQUEST",value:a.method.toUpperCase()}];t.push(`curl_setopt_array(${o}, [`);const f=new P({indentation:n.indent,lineJoin:`
|
|
4
|
+
${n.indent}`,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:_.PHP});$.length&&f.push("CURLOPT_HTTPHEADER => [").push(1,$.join(`,
|
|
5
|
+
`+n.indent+n.indent)).push("],"),C.forEach(function(e){[null,void 0,""].includes(e.value)||f.push(m("%s => %s,",e.name,e.escape?JSON.stringify(e.value):e.value))});const O=a.cookies.map(function(e){return encodeURIComponent(e.name)+"="+encodeURIComponent(e.value)});return O.length&&f.push(m('CURLOPT_COOKIE => "%s",',O.join("; "))),t.push(1,f.join()).push("]);").blank().push(`${y} = curl_exec(${o});`).push(`${d} = curl_error(${o});`).blank().push(`curl_close(${o});`).blank().push(`if (${d}) {`),n.namedErrors?t.push(1,`echo array_flip(get_defined_constants(true)["curl"])[${d}];`):t.push(1,`echo "cURL Error #:" . ${d};`),t.push("} else {").push(1,`echo ${y};`).push("}"),!n.noTags&&n.closingTag&&t.blank().push("?>"),t.join()},M={key:"curl",title:"cURL",link:"http://php.net/manual/en/book.curl.php",description:"PHP with ext-curl"};var F=x;export{F as default,M as info};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{format as
|
|
2
|
-
${
|
|
1
|
+
import{format as D}from"util";import{CodeBuilder as k}from"../../helpers/code-builder.js";import{normalizeMimeType as T}from"../../../../utils.js";import{addIndentation as L,buildUrlExpression as j,printUrlVariablesDeclarations as A}from"../../helpers/code-helpers.js";import{HTTPSnippet as x}from"../../index.js";import{Lang as E}from"../../helpers/constants.js";import{MediaTypes as l}from"../../../../../constants.js";import{buildPythonDeviceAuthorizationCodeSnippet as R}from"../../helpers/device-auth-snippets.js";const g=function(e,d,{target:w,client:m}){const s=Object.assign({indent:" "},d),{level:f=0}=s,t=new k({indentation:s.indent,variablesPrefix:s.variablesPrefix,lang:E.PYTHON}),O=e.securityOAuth2ExtraCalls?.some(a=>a.flowType==="deviceAuthorization");s.withComments&&q(t),s.withImports&&(t.push("import requests"),O&&t.push("import time"),t.blank());let y=!1,i=e.allHeaders;if(e.securityOAuth2ExtraCalls?.length){const a=e.securityOAuth2ExtraCalls?.[0],n=new x(a).convert(w,m,{...s,withImports:!1,withComments:!1,variablesPrefix:"oauth2_"});t.push(n),t.blank(),a.flowType==="deviceAuthorization"&&R(t,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:f}),i=i||{},i.Authorization='"Bearer " + access_token',y=!0}A(e,t),t.push(`${t.var("url").toLowerCase()} = %s`,j(e,t)).blank();let b;Object.keys(e.queryObj||{}).length&&(b="query = "+_(e.queryObj,s.indent),t.push(b).blank());let p,h;const C=T(e.postData?.mimeType);if(e.postData)switch(C){case l.URL_ENCODED:p=e.postData.paramsObj?`${L(_(e.postData.paramsObj,s.indent),{level:0,firstLine:!1})}`:e.postData.text;break;case l.JSON:e.postData.jsonObj&&(p=L(_(e.postData.jsonObj,s.indent),{level:0,firstLine:!1}));break;case l.MULTIPART:const a=[];if(e.postData.params)for(const n of e.postData.params)a.push(`"${n.name}": "${n.value}"`);a.length&&(h=`data = {
|
|
2
|
+
${a.map(v=>` ${v}`).join(`,
|
|
3
3
|
`)}
|
|
4
|
-
}`),
|
|
5
|
-
${L(
|
|
6
|
-
'''`)}
|
|
4
|
+
}`),h&&t.push(h).blank();break;default:e.postData.text&&(p=`'''
|
|
5
|
+
${L(e.postData.text.trim(),{level:1,indent:s.indent,firstLine:!0})}
|
|
6
|
+
'''`)}p&&t.push(`${t.var("payload").toLowerCase()} = %s`,p).blank();let r;const u=Object.keys(i).length,$=(a,n)=>a==="Authorization"&&y?n:`"${n}"`;if(u===1)for(r in i)t.push(`${t.var("headers").toLowerCase()} = {"${r}": ${$(r,i[r])}}`).blank();else if(u>1){let a=1;t.push(`${t.var("headers").toLowerCase()} = {`);for(r in i)a++!==u?t.push(1,`"${r}": ${$(r,i[r])},`):t.push(1,`"${r}": ${$(r,i[r])}`);t.push(0,"}").blank()}const c=e.method.toLowerCase();let o=D(`${t.var("response").toLowerCase()} = requests.${c}(${t.var("url").toLowerCase()}`);if(C===l.MULTIPART&&h&&(o+=", data=data"),p){const a=C===l.JSON?"json":"data";o+=`, ${a}=${t.var("payload").toLowerCase()}`}return u>0&&(o+=`, headers=${t.var("headers").toLowerCase()}`),b&&(o+=`, params=${t.var("query").toLowerCase()}`),e.basicAuth&&(o+=`, auth=('${e.basicAuth.username}','${e.basicAuth.password}')`),o+=")",t.push(o).blank(),e.allResponseCodes?.includes("204")?t.push("if response.status_code == 204:").push(f+1,'print("success")').push("else:").push(f+1,`${t.var("data").toLowerCase()} = ${t.var("response").toLowerCase()}.json()`).push(f+1,`print(${t.var("data").toLowerCase()})`):t.push(`${t.var("data").toLowerCase()} = ${t.var("response").toLowerCase()}.json()`).push(`print(${t.var("data").toLowerCase()})`),t.join()};var M=g;function q(e){e.push('"""'),e.push("Requires python >= 3"),e.blank(),e.push('Requires module "requests" >= 2.25.1'),e.push("See here for installation details:"),e.push(" https://requests.readthedocs.io/"),e.push('"""'),e.blank()}function _(e,d){return JSON.stringify(e,function(m,s){return m&&typeof s=="boolean"?s?"__REDOCLY_<True>__":"__REDOCLY_<False>__":s===null?"__REDOCLY_<None>__":s},d).replace(/"__REDOCLY_<(\w+)>__"/g,"$1")}export{M as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CodeBuilder as k}from"../../helpers/code-builder.js";import{buildUrlExpression as
|
|
1
|
+
import{CodeBuilder as k}from"../../helpers/code-builder.js";import{buildUrlExpression as D,printUrlVariablesDeclarations as v}from"../../helpers/code-helpers.js";import{Lang as x}from"../../helpers/constants.js";import{HTTPSnippet as O}from"../../index.js";import{normalizeMimeType as T}from"../../../../utils.js";import{MediaTypes as p}from"../../../../../constants.js";import{postDataToRListBody as b,objectToRString as f}from"./utils.js";import{buildRDeviceAuthorizationCodeSnippet as _}from"../../helpers/device-auth-snippets.js";const n=1,w=function(a,c,{target:m,client:u}){const i=Object.assign({indent:" ",showBoilerplate:!0,printBody:!0},c),t=new k({indentation:i.indent,variablesPrefix:i.variablesPrefix,lang:x.R}),$=a.method.toUpperCase(),l=a.securityOAuth2ExtraCalls?.[0];if(i.showBoilerplate&&t.push("library(httr)").blank(),l){const e="oauth2_",o=new O(l).convert(m,u,{...i,variablesPrefix:e,showBoilerplate:!1}),h=`${e}data_req`;t.push(o),l.flowType==="deviceAuthorization"?_(t,{tokenUrl:l.tokenUrl??"YOUR_TOKEN_URL",clientId:l.clientId??"YOUR_CLIENT_ID",level:0,responseVariable:h}):(t.push(`access_token = content(${h}, "parsed")$access_token`),t.blank()),a.allHeaders.Authorization='paste("Bearer", access_token)'}let r,s="";if(a?.postData)switch(T(a?.postData?.mimeType)){case p.URL_ENCODED:{r="form",s=t.var("body");const e=b(a.postData.params,i);t.push(`${s} <- list(${e})`).blank();break}case p.JSON:{r="json",s=t.var("body");const e=f(a.postData.jsonObj,i);t.push(`${s} = '${e}'`).blank();break}case p.MULTIPART:{r="multipart",s=t.var("body");const e=b(a.postData.params,i);t.push(`${s} <- list(${e})`).blank();break}default:a.postData?.text&&(s=t.var("body"),r="raw",t.push(`${s} = ${f(a.postData?.text)}`).blank())}v(a,t),Object.keys({...a.pathParameters,...a.serverVariables}).length&&t.blank().push("# create you own operator").push('"%&%" <- function(x, y)paste0(x,y)').blank();const y=D(a,t);t.push(`url = ${y}`).blank();const d=t.var("data_req");if(t.push(`${d} <- ${$}(`),t.push(n,"url,"),a.basicAuth){const{username:e,password:o}=a.basicAuth;t.push(n,`authenticate("${e}", "${o}")`)}if(Object.keys(a.allHeaders).length){const e=`${Object.keys(a.allHeaders).map(o=>`"${o}" = ${a.allHeaders[o].startsWith("paste")?a.allHeaders[o]:`"${a.allHeaders[o]}"`}`).join(", ")}`;e&&t.push(n,`add_headers(${e}),`)}return s&&(t.push(n,`body = ${s},`),t.push(n,`encode = "${r}",`)),t.push(n,"verbose()"),t.push(")"),i.printBody&&t.blank().push(`content(${d}${r==="raw"?', "text"':""})`),t.join()};var E=w;export{E as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import l from"stringify-object";import{CodeBuilder as
|
|
1
|
+
import l from"stringify-object";import{CodeBuilder as m}from"../../helpers/code-builder.js";import{HTTPSnippet as T}from"../../index.js";import{Lang as $}from"../../helpers/constants.js";import{buildUrlExpression as O,printUrlVariablesDeclarations as v}from"../../helpers/code-helpers.js";import{normalizeMimeType as d}from"../../../../utils.js";import{MediaTypes as n}from"../../../../../constants.js";import{buildRubyDeviceAuthorizationCodeSnippet as y}from"../../helpers/device-auth-snippets.js";const E=1;function _(t={},o){return d(t.mimeType)===o}const H=function(t,o,{target:f,client:b}){const p=t.method.toUpperCase(),i=t.securityOAuth2ExtraCalls?.[0],r={capitalize:!0,showBoilerplate:!0,indent:" ",...o},e=new m({indentation:r.indent,variablesPrefix:r.variablesPrefix,capitalize:r.capitalize,lang:$.RUBY});r.showBoilerplate&&(e.push("require 'uri'").push("require 'net/http'"),t.uriObj.protocol==="https:"&&e.push("require 'openssl'"),(_(t.postData,n.JSON)||i)&&e.unshift("require 'json'"),e.blank()),Object.keys(t.allHeaders).length&&Object.keys(t.allHeaders).forEach(a=>{t.allHeaders[a]=`'${t.allHeaders[a]}'`});const c=["GET","POST","HEAD","DELETE","PATCH","PUT","OPTIONS","COPY","LOCK","UNLOCK","MOVE","TRACE"],h=p.charAt(0)+p.substring(1).toLowerCase();if(c.indexOf(p)<0&&e.push("class Net::HTTP::%s < Net::HTTPRequest",h).push(" METHOD = '%s'",p.toUpperCase()).push(" REQUEST_HAS_BODY = '%s'",t.postData?.text?"true":"false").push(" RESPONSE_HAS_BODY = true").push("end").blank(),i){const a="oAuth2",s=new T(i).convert(f,b,{...r,variablesPrefix:a,showBoilerplate:!1}),u=`${a}${r.capitalize?"Response":"response"}`;e.push(s),i.flowType==="deviceAuthorization"?y(e,{tokenUrl:i.tokenUrl??"YOUR_TOKEN_URL",clientId:i.clientId??"YOUR_CLIENT_ID",level:0,responseVariable:u,capitalize:r.capitalize}):(e.push(`access_token = JSON.parse(${u}.body)['access_token']`),e.blank()),t.allHeaders.Authorization='"Bearer " + access_token'}if(v(t,e),e.push(`${e.var("url")} = URI(${O(t,e)})`),Object.getOwnPropertyNames(t.queryObj).length&&(e.push(`${e.var("params")} = ${l(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")})`,h),Object.keys(t.allHeaders).length&&Object.keys(t.allHeaders).forEach(a=>{t.allHeaders[a]!==`'${n.MULTIPART}'`&&e.push(`${e.var("request")}['%s'] = %s`,a,t.allHeaders[a])}),t?.postData){const a={};switch(d(t?.postData?.mimeType)){case n.URL_ENCODED:t.postData.params.forEach(s=>{a[s.name]=s.value}),e.push(`${e.var("request")}.body = URI.encode_www_form(${l(a,{indent:r.indent,inlineCharacterLimit:25})})`);break;case n.JSON:e.push(`${e.var("request")}.body = ${l(t.postData.jsonObj,{indent:r.indent,inlineCharacterLimit:25}).replace(/null/g,"nil")}.to_json`);break;case n.MULTIPART:t.postData.params&&(e.push(`${e.var("form_data")} = [`),t.postData.params.forEach(s=>{e.push(E,`['${s.name}', '${s.value}'],`)}),e.push("]")),e.push(`${e.var("request")}.set_form(${e.var("form_data")}, '${n.MULTIPART}')`);break;default:t.postData?.text&&e.push(`${e.var("request")}.body = ${JSON.stringify(t.postData?.text)}`)}}if(t.basicAuth){const{username:a,password:s}=t.basicAuth;e.push(`${e.var("request")}.basic_auth('${a}', '${s}')`)}return e.blank().push(`${e.var("response")} = ${e.var("http")}.request(${e.var("request")})`).push(`puts ${e.var("response")}.read_body`).blank(),e.join()},j={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 N=H;export{N as default,j as info};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import{format as
|
|
2
|
-
`+
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import{format as r}from"util";import{CodeBuilder as f}from"../../helpers/code-builder.js";import n from"../../helpers/shell.js";import{addIndentation as u,buildUrlExpression as T}from"../../helpers/code-helpers.js";import{normalizeMimeType as A}from"../../../../utils.js";import{HTTPSnippet as C}from"../../index.js";import{MediaTypes as p}from"../../../../../constants.js";import{buildShellDeviceAuthorizationCodeSnippet as E}from"../../helpers/device-auth-snippets.js";const D=function(e,m,{target:c,client:b}){const t=Object.assign({indent:" ",short:!1,binary:!1},m),a=new f({indentation:t.indent,lineJoin:t.indent?` \\
|
|
2
|
+
`+t.indent:" "}),s=e.securityOAuth2ExtraCalls?.[0];let l="",h="";if(s&&(l=new C(s).convert(c,b,{...t,withComments:!1}),s.flowType==="deviceAuthorization")){l="OAUTH2_RESPONSE=$("+l.replace(/^curl -i/,"curl -s")+")";const i=new f({indentation:t.indent});E(i,{tokenUrl:s.tokenUrl??"YOUR_TOKEN_URL",clientId:s.clientId??"YOUR_CLIENT_ID",level:0,short:t.short}),h=i.join()}a.push(0,"curl -i %s %s",t.short?"-X":"--request",e.method.toUpperCase()),e.basicAuth&&a.push(r("-u %s:%s",e.basicAuth.username,e.basicAuth.password));const y=T(e,a);if(a.push(r("%s%s",t.short?"":"--url ",n.quote(y))),e.httpVersion==="HTTP/1.0"&&a.push(t.short?"-0":"--http1.0"),Object.keys(e.headersObj).sort().forEach(function(i){let o=e.headersObj[i];s?.flowType==="deviceAuthorization"&&i.toLowerCase()==="authorization"&&o==="Bearer <YOUR_TOKEN_HERE>"&&(o="Bearer $ACCESS_TOKEN");const O=r("%s: %s",i,o);a.push("%s %s",t.short?"-H":"--header",n.quote(O))}),e.allHeaders.cookie&&a.push("%s %s",t.short?"-b":"--cookie",n.quote(e.allHeaders.cookie)),e.postData)switch(A(e.postData.mimeType)){case p.MULTIPART:e.postData.params.map(function(i){let o;i.fileName?o=r("%s=@%s",i.name,i.fileName):o=r("%s=%s",i.name,i.value),a.push("%s %s",t.short?"-F":"--form",n.quote(o))});break;case p.URL_ENCODED:e.postData.params?e.postData.params.map(function(i){a.push("%s %s",t.binary?"--data-binary":t.short?"-d":"--data",n.quote(r("%s=%s",i.name,i.value)))}):a.push("%s %s",t.binary?"--data-binary":t.short?"-d":"--data",n.quote(e.postData.text));break;case p.JSON:e.postData.jsonObj&&a.push("%s %s",t.binary?"--data-binary":t.short?"-d":"--data",u(n.quote(JSON.stringify(e.postData.jsonObj,null,t.indent)),{level:1,indent:t.indent,firstLine:!1}));break;default:e.postData.text&&a.push("%s %s",t.binary?"--data-binary":t.short?"-d":"--data",u(n.quote(e.postData.text),{level:1,indent:t.indent,firstLine:!1}))}let d="";return t.withComments&&(d=`# Requires curl >= 7.2
|
|
3
|
+
`,s?.flowType==="deviceAuthorization"&&(d+=`# Requires jq for JSON parsing
|
|
4
|
+
`),d+=`
|
|
5
|
+
`),d+(l?l+`
|
|
6
|
+
`:"")+(h?h+`
|
|
7
|
+
`:"")+a.join()},L={key:"curl",title:"curl",link:"http://curl.haxx.se/",description:"cURL is a command line tool and library for transferring data with URL syntax"};var S=D;export{S as default,L as info};
|