@redocly/openapi-docs 3.14.0-next.12 → 3.14.0-next.13

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.
Files changed (23) hide show
  1. package/dist/redocly-openapi-docs.min.js +1541 -1528
  2. package/lib/components/Security/OAuthFlow.js +1 -1
  3. package/lib/components/Security/SecurityButton.js +14 -7
  4. package/lib/components/Security/SecurityFlow.d.ts +1 -1
  5. package/lib/components/Security/SecurityFlow.js +10 -5
  6. package/lib/services/code-samples/generator.d.ts +9 -2
  7. package/lib/services/code-samples/generator.js +1 -1
  8. package/lib/services/code-samples/httpsnippet/helpers/device-auth-snippets.d.ts +25 -0
  9. package/lib/services/code-samples/httpsnippet/helpers/device-auth-snippets.js +1 -0
  10. package/lib/services/code-samples/httpsnippet/targets/csharp/httpclient.js +2 -2
  11. package/lib/services/code-samples/httpsnippet/targets/csharpNewtonsoft/httpclient.js +2 -2
  12. package/lib/services/code-samples/httpsnippet/targets/go/native.js +3 -3
  13. package/lib/services/code-samples/httpsnippet/targets/java/httpclient.js +3 -3
  14. package/lib/services/code-samples/httpsnippet/targets/java8/apachehttp.js +2 -2
  15. package/lib/services/code-samples/httpsnippet/targets/javascript/fetch.js +1 -1
  16. package/lib/services/code-samples/httpsnippet/targets/node/fetch.js +1 -1
  17. package/lib/services/code-samples/httpsnippet/targets/php/curl.js +5 -5
  18. package/lib/services/code-samples/httpsnippet/targets/python/requests.js +5 -5
  19. package/lib/services/code-samples/httpsnippet/targets/r/httr.js +1 -1
  20. package/lib/services/code-samples/httpsnippet/targets/ruby/native.js +1 -1
  21. package/lib/services/code-samples/httpsnippet/targets/shell/curl.js +7 -6
  22. package/lib/types/open-api.d.ts +9 -0
  23. package/package.json +4 -3
@@ -1 +1 @@
1
- import{jsx as e,Fragment as a,jsxs as n}from"react/jsx-runtime";import{memo as i}from"react";import{SecuritySchemeItem as o}from"./SecuritySchemeItem.js";import{StyledLink as l}from"./styled.js";import{useTranslate as m}from"../../hooks/index.js";function s({flow:r}){const t=m();return n(a,{children:[e(o,{label:`${t("openapi.authorizationUrl","Authorization URL")}:`,value:r?.authorizationUrl&&e(l,{target:"_blank",rel:"noopener noreferrer",href:r?.authorizationUrl,children:r?.authorizationUrl})}),e(o,{label:`${t("openapi.tokenUrl","Token URL")}:`,value:r?.tokenUrl}),e(o,{label:`${t("openapi.refreshUrl","Refresh URL")}:`,value:r?.refreshUrl})]})}const f=i(s);export{f as OAuthFlow};
1
+ import{jsx as e,Fragment as a,jsxs as i}from"react/jsx-runtime";import{memo as l}from"react";import{SecuritySchemeItem as n}from"./SecuritySchemeItem.js";import{StyledLink as o}from"./styled.js";import{useTranslate as h}from"../../hooks/index.js";function u({flow:r}){const t=h();return i(a,{children:[e(n,{label:`${t("openapi.authorizationUrl","Authorization URL")}:`,value:r?.authorizationUrl&&e(o,{target:"_blank",rel:"noopener noreferrer",href:r?.authorizationUrl,children:r?.authorizationUrl})}),e(n,{label:`${t("openapi.tokenUrl","Token URL")}:`,value:r?.tokenUrl&&e(o,{target:"_blank",rel:"noopener noreferrer",href:r?.tokenUrl,children:r?.tokenUrl})}),e(n,{label:`${t("openapi.refreshUrl","Refresh URL")}:`,value:r?.refreshUrl&&e(o,{target:"_blank",rel:"noopener noreferrer",href:r?.refreshUrl,children:r?.refreshUrl})}),e(n,{label:`${t("openapi.deviceAuthorizationUrl","Device Authorization URL")}:`,value:r?.deviceAuthorizationUrl&&e(o,{target:"_blank",rel:"noopener noreferrer",href:r?.deviceAuthorizationUrl,children:r?.deviceAuthorizationUrl})})]})}const d=l(u);export{d as OAuthFlow};
@@ -1,8 +1,15 @@
1
- import{jsx as r,jsxs as t}from"react/jsx-runtime";import{Fragment as c}from"react";import{SecurityIcon as v}from"@redocly/theme/icons/SecurityIcon/SecurityIcon";import{Panel as f}from"@redocly/theme/components/Panel/Panel";import{Button as h}from"@redocly/theme/components/Button/Button";import{useTranslate as g}from"../../hooks/index.js";import{styled as e}from"../../styled-components.js";function T({securities:o,onClick:p}){const n=g();return r(y,{header:()=>t(b,{children:[r(v,{}),r(w,{children:n("openapi.security","Security")}),r(x,{onClick:p,variant:"link",children:n("openapi.viewSecurityDetails","View details")})]}),isExpandable:!1,children:r(S,{children:o.map((a,i)=>{const s=o.length>1&&a.schemes.length>1,m=a.schemes.map(({id:l},u)=>t(c,{children:[l,u<a.schemes.length-1&&r(d,{children:" and "})]},l));return t(c,{children:[s?"(":"",m,s?")":"",i<o.length-1&&r(d,{children:" or "})]},i)})})})}const y=e(f)`
1
+ import{jsx as r,jsxs as o}from"react/jsx-runtime";import{Fragment as d}from"react";import{SecurityIcon as v}from"@redocly/theme/icons/SecurityIcon/SecurityIcon";import{Panel as u}from"@redocly/theme/components/Panel/Panel";import{Button as h}from"@redocly/theme/components/Button/Button";import{Tooltip as y}from"@redocly/theme/components/Tooltip/Tooltip";import{WarningFilledIcon as b}from"@redocly/theme/icons/WarningFilledIcon/WarningFilledIcon";import{useTranslate as x}from"../../hooks/index.js";import{styled as e}from"../../styled-components.js";import{deprecatedCss as w}from"../common/index.js";function N({securities:a,onClick:m}){const i=x();return r(j,{header:()=>o(k,{children:[r(v,{}),r(B,{children:i("openapi.security","Security")}),r(T,{onClick:m,variant:"link",children:i("openapi.viewSecurityDetails","View details")})]}),isExpandable:!1,children:r(C,{children:a.map((t,n)=>{const s=a.length>1&&t.schemes.length>1,f=t.schemes.map(({id:l,deprecated:c=!1},g)=>o(d,{children:[o(S,{deprecated:c,children:[l,c&&r(y,{tip:i("openapi.badges.deprecated","Deprecated"),children:r(b,{color:"var(--badge-deprecated-bg-color)"})})]}),g<t.schemes.length-1&&r(p,{children:" and "})]},l));return o(d,{children:[s?"(":"",f,s?")":"",n<a.length-1&&r(p,{children:" or "})]},n)})})})}const S=e.span`
2
+ ${({deprecated:a})=>a&&w}
3
+ display: flex;
4
+ align-items: center;
5
+ gap: var(--spacing-xxs);
6
+ display: inline-flex;
7
+ };
8
+ `,j=e(u)`
2
9
  margin-top: var(--spacing-base);
3
10
  border: var(--panel-border);
4
11
  border-radius: var(--panel-border-radius);
5
- `,b=e.div`
12
+ `,k=e.div`
6
13
  display: flex;
7
14
  align-items: center;
8
15
  justify-content: space-between;
@@ -12,19 +19,19 @@ import{jsx as r,jsxs as t}from"react/jsx-runtime";import{Fragment as c}from"reac
12
19
  background-color: var(--layer-color);
13
20
  border-bottom: var(--panel-border);
14
21
  border-radius: var(--panel-border-radius) var(--panel-border-radius) 0 0;
15
- `,x=e(h)`
22
+ `,T=e(h)`
16
23
  margin-left: auto;
17
24
  font-size: var(--font-size-sm);
18
- `,w=e.span`
25
+ `,B=e.span`
19
26
  font-family: var(--font-family-base);
20
27
  font-weight: var(--font-weight-medium);
21
28
  color: var(--text-color-primary);
22
- `,S=e.div`
29
+ `,C=e.div`
23
30
  flex: 1;
24
31
  text-overflow: ellipsis;
25
32
  overflow: hidden;
26
33
  padding: var(--spacing-xs) var(--spacing-sm);
27
34
  color: var(--text-color-primary);
28
- `,d=e.span`
35
+ `,p=e.span`
29
36
  color: var(--text-color-description);
30
- `;export{T as SecurityButton};
37
+ `;export{N as SecurityButton};
@@ -1,5 +1,5 @@
1
1
  import type { ReactElement } from 'react';
2
2
  import type { SecurityRequirement, ExtendedOpenAPISecurityScheme } from '../../models/index.js';
3
- export declare function SecurityFlow({ type, bearerFormat, name, flows, openIdConnectUrl, description, id, securities, in: apiKeyIn, }: Partial<ExtendedOpenAPISecurityScheme> & {
3
+ export declare function SecurityFlow({ type, bearerFormat, name, flows, openIdConnectUrl, description, id, securities, in: apiKeyIn, deprecated, oauth2MetadataUrl, }: Partial<ExtendedOpenAPISecurityScheme> & {
4
4
  securities: SecurityRequirement[];
5
5
  }): ReactElement | null;
@@ -1,16 +1,21 @@
1
- import{jsx as r,Fragment as p,jsxs as i}from"react/jsx-runtime";import{SecuritySchemeItem as a}from"./SecuritySchemeItem.js";import{titleize as v}from"../../utils/index.js";import{OAuthFlow as g}from"./OAuthFlow.js";import{StyledLink as w}from"./styled.js";import{Markdown as x}from"../Markdown/index.js";import{useTranslate as S}from"../../hooks/index.js";import{OAuthScopes as y}from"./OAuthScopes.js";import{styled as m}from"../../styled-components.js";function K({type:o,bearerFormat:c,name:d,flows:t,openIdConnectUrl:n,description:h,id:l,securities:u,in:f}){const e=S();if(!o||!l)return null;const b={http:i(p,{children:[r(a,{label:e("openapi.httpAuthorizationScheme","HTTP Authorization Scheme"),value:o}),r(a,{label:e("openapi.bearerFormat","Bearer Format"),value:c})]}),apiKey:r(a,{label:`${v(f||"")} ${e("openapi.parameterName","parameter name")}:`,value:d}),oauth2:i(p,{children:[r(a,{label:e("openapi.flowType","Flow type"),value:o}),t&&Object.keys(t).map(s=>r(g,{flow:t[s]},s))]}),openIdConnect:r(a,{label:e("openapi.connectUrl","Connect URL"),value:n&&r(w,{target:"_blank",rel:"noopener noreferrer",href:n,children:n})})};return i(F,{children:[r(T,{children:l}),r(x,{source:h}),i(z,{children:[b[o]||null,r(y,{id:l,securities:u,flows:t})]})]})}const F=m.div`
1
+ import{jsx as e,Fragment as m,jsxs as t}from"react/jsx-runtime";import{Badge as S}from"@redocly/theme/components/Badge/Badge";import{SecuritySchemeItem as a}from"./SecuritySchemeItem.js";import{titleize as w}from"../../utils/index.js";import{OAuthFlow as y}from"./OAuthFlow.js";import{StyledLink as d}from"./styled.js";import{Markdown as F}from"../Markdown/index.js";import{useTranslate as T}from"../../hooks/index.js";import{OAuthScopes as k}from"./OAuthScopes.js";import{styled as n}from"../../styled-components.js";function N({type:o,bearerFormat:h,name:u,flows:i,openIdConnectUrl:l,description:f,id:p,securities:g,in:b,deprecated:v=!1,oauth2MetadataUrl:s}){const r=T();if(!o||!p)return null;const x={http:t(m,{children:[e(a,{label:r("openapi.httpAuthorizationScheme","HTTP Authorization Scheme"),value:o}),e(a,{label:r("openapi.bearerFormat","Bearer Format"),value:h})]}),apiKey:e(a,{label:`${w(b||"")} ${r("openapi.parameterName","parameter name")}:`,value:u}),oauth2:t(m,{children:[e(a,{label:r("openapi.flowType","Flow type"),value:o}),i&&Object.keys(i).map(c=>e(y,{flow:i[c]},c))]}),openIdConnect:e(a,{label:r("openapi.connectUrl","Connect URL"),value:l&&e(d,{target:"_blank",rel:"noopener noreferrer",href:l,children:l})})};return t(j,{children:[t(z,{children:[e(_,{children:p}),v&&e(S,{deprecated:!0,children:r("openapi.badges.deprecated","Deprecated")})]}),e(F,{source:f}),s&&e(a,{label:r("openapi.oauth2MetadataUrl","OAuth2 Metadata URL"),value:e(d,{target:"_blank",rel:"noopener noreferrer",href:s,children:s})}),t(A,{children:[x[o]||null,e(k,{id:p,securities:g,flows:i})]})]})}const z=n.div`
2
+ display: flex;
3
+ align-items: center;
4
+ gap: var(--spacing-xxs);
5
+ margin: 0 0 var(--spacing-xs);
6
+ `,j=n.div`
2
7
  background: var(--layer-color);
3
8
  padding: var(--spacing-base);
4
9
  border-radius: var(--border-radius);
5
10
  border: 1px solid var(--border-color-secondary);
6
11
  width: 100%;
7
12
  margin-top: var(--spacing-base);
8
- `,z=m.div`
13
+ `,A=n.div`
9
14
  width: 100%;
10
15
  margin-top: var(--spacing-md);
11
- `,T=m.p`
16
+ `,_=n.p`
12
17
  font-size: var(--font-size-base);
13
- margin: 0 0 var(--spacing-xs);
18
+ margin: 0;
14
19
  text-transform: capitalize;
15
20
  font-weight: var(--font-weight-semibold);
16
- `;export{K as SecurityFlow};
21
+ `;export{N as SecurityFlow};
@@ -1,11 +1,11 @@
1
1
  import * as Sampler from 'openapi-sampler';
2
2
  import type { JSONSchema7 } from 'json-schema';
3
- import type { OperationModel } from '../../models/index.js';
3
+ import type { OperationModel, ExtendedOpenAPISecurityScheme } from '../../models/index.js';
4
4
  import type * as HAR from './har.js';
5
5
  import type { Languages } from './types.js';
6
6
  import { type TFunction } from '@redocly/theme/core/openapi';
7
7
  export type CustomHAR = HAR.Request & {
8
- securityOAuth2ExtraCalls?: HAR.Request[];
8
+ securityOAuth2ExtraCalls?: OAuth2ExtraCall[];
9
9
  basicAuth?: {
10
10
  username: string;
11
11
  password: string;
@@ -27,6 +27,13 @@ export declare function getCodeSample({ lang, operation, exampleName, pathParams
27
27
  environment: Record<string, string>;
28
28
  translate: TFunction;
29
29
  }): string;
30
+ type OAuth2ExtraCall = HAR.Request & {
31
+ flowType: keyof ExtendedOpenAPISecurityScheme['flows'];
32
+ securityOAuth2ExtraCalls: OAuth2ExtraCall[];
33
+ tokenUrl?: string;
34
+ clientId?: string;
35
+ };
30
36
  export declare function getDataRequest(exampleValue: any, properties: any): boolean | any;
31
37
  export declare function isDefined<T>(arg?: T): arg is T;
32
38
  export declare function capitalizeFirst(str: string): string;
39
+ export {};
@@ -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 d}from"@redocly/theme/core/openapi";import{CodeBuilder as T}from"../../helpers/code-builder.js";import{HTTPSnippet as w}from"../../index.js";import{buildUrlExpression as S,printUrlVariablesDeclarations as E}from"../../helpers/code-helpers.js";import{isEmptyObject as A,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";const x=function(s,c,{target:C,client:D}){const r=Object.assign({indent:" ",withWrapper:!0},c),t=new T({indentation:r.indent,variablesPrefix:r.variablesPrefix,capitalize:!0,lang:k.CSHARP}),b=L(s.method);if(r.withComments&&P(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)||s.basicAuth)&&t.push("using System.Text;"),(h(i.URL_ENCODED)||s.securityOAuth2ExtraCalls?.length)&&t.push("using System.Collections.Generic;"),(h(i.JSON)||s.securityOAuth2ExtraCalls?.length)&&t.push("using System.Text.Json;"),l()&&t.push("using System.IO;"),(l()||s.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,"{")),s.securityOAuth2ExtraCalls?.length){const e=new w(s.securityOAuth2ExtraCalls?.[0]).convert(C,D,{...r,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(e),t.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),t.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),t.push(2,'var accessToken = inputJObject["access_token"].ToString();'),t.blank()}const f=Object.keys(s.allHeaders).filter(e=>{switch(e.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(e=>{t.push(4,'{"%s", %s},',e,s.securityOAuth2ExtraCalls?.length?'"Bearer " + accessToken':`"${s.allHeaders[e]}"`)}),t.push(3,"}"),t.push(2,"};")):t.push(2,"System.Net.Http.HttpClient client = new();"),t.blank(),s.basicAuth){const{username:e,password:a}=s.basicAuth;t.push(2,`string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${e}:${a}"));`),t.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);'),t.blank()}if(s.postData)switch(m(s.postData.mimeType)){case i.URL_ENCODED:s.postData.params&&(t.blank(),t.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),s.postData.params.forEach(e=>{t.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',e.name,e.value)}),t.blank());break;case i.MULTIPART:s.postData.params&&(t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),s.postData.params.forEach(e=>{t.push(2,'postData.Add(new StringContent("%s"), "%s");',e.value,e.name)}));break;case i.JSON:s.postData.jsonObj&&(t.push(2,"string json = JsonSerializer.Serialize(new"),t.push(2,"{"),u(s.postData.jsonObj,3),t.push(2,"});"),t.blank(),t.push(2,'using StringContent postData = new(json, Encoding.UTF8, "%s");',s.postData.mimeType));break;case i.XML:s.postData.text&&(s.postData.text.trim().split(`
2
- `).forEach((e,a)=>{const n=(a===0?'string xml = @"':"")+e.replace(/"/g,'""');t.push(a===0?2:3,n)}),t.push(2,'";'),t.push(2,'using StringContent postData = new StringContent(xml, Encoding.UTF8, "%s");',s.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 E(s,t,3),t.push(2,"using HttpResponseMessage %s = await client.%sAsync(%s%s);",t.var("request"),b,S(s,t),r.withImports?M(s.method)?m(s.postData&&s.postData.mimeType)===i.URL_ENCODED?", new FormUrlEncodedContent(postData)":s.method==="delete"?"":s.postData&&s.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(e){return s.postData&&m(s.postData.mimeType)===e}function l(){return s.headersObj&&s.headersObj["Content-Type"]===i.OCTET_STREAM}function g(e,a){e.forEach((n,p)=>{const o=!H(e,p);Array.isArray(n)?g(n,a+1):d(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(e,a){for(const[n,p]of Object.entries(e)){const o=!j(e,n);if(Array.isArray(p))t.push(a,"%s = new[] {",n),g(p,a);else if(d(p)){const y=A(p);t.push(a,"%s = new %s",n,y?"{},":"{"),y||(u(p,a+1),t.push(a,"}%s",o?",":""))}else t.push(a,'%s = "%s"%s',n,p,o?",":"")}}},V={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var B=x;function P(s){s.push("// Requires >= .NET 5"),s.blank()}function L(s){return O(s.toLowerCase())}function M(s){return s&&["POST","PUT","DELETE","PATCH"].includes(s.toUpperCase())}export{B as default,V as info};
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 g}from"../../helpers/code-builder.js";import{HTTPSnippet as C}from"../../index.js";import{addIndentation as D,buildUrlExpression as y,printUrlVariablesDeclarations as T}from"../../helpers/code-helpers.js";import{normalizeMimeType as o}from"../../../../utils.js";import{capitalizeFirst as b}from"../../../generator.js";import{Lang as w}from"../../helpers/constants.js";import{MediaTypes as s}from"../../../../../constants.js";const S=function(t,h,{target:u,client:m}){const n=Object.assign({indent:" ",withWrapper:!0},h),e=new g({indentation:n.indent,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:w.CSHARPNEWTONSOFT}),c=E(t.method);if(n.withComments&&O(e),n.withWrapper&&(e.push("using System;"),e.push("using System.Net.Http;"),e.push("using System.Threading.Tasks;"),(i(s.JSON)||i(s.XML)||t.basicAuth)&&e.push("using System.Text;"),(i(s.URL_ENCODED)||t.securityOAuth2ExtraCalls?.length)&&e.push("using System.Collections.Generic;"),(i(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=new C(t.securityOAuth2ExtraCalls?.[0]).convert(u,m,{...n,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});e.push(a),e.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),e.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),e.push(2,'var accessToken = inputJObject["access_token"].ToString();'),e.blank()}const l=Object.keys(t.allHeaders).filter(a=>{switch(a.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(l.length&&l.forEach(a=>{e.push(2,'client.DefaultRequestHeaders.Add("%s", %s);',a,t.securityOAuth2ExtraCalls?.length?'"Bearer " + accessToken':`"${t.allHeaders[a]}"`)}),t.basicAuth){const{username:a,password:r}=t.basicAuth;e.push(2,`var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${a}:${r}"));`),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,r)=>{const d=(r===0?'string xml = @"':"")+a.replace(/"/g,'""');e.push(r===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 T(t,e,3),e.push(2,"var %s = await client.%sAsync(%s%s);",e.var("request"),c,y(t,e),n.withImports?A(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 i(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 N=S;function O(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 E(t){return b(t.toLowerCase())}function A(t){return t&&["POST","PUT","DELETE","PATCH"].includes(t.toUpperCase())}export{N as default,M as info};
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 q}from"../../index.js";import{Lang as w}from"../../helpers/constants.js";import{buildUrlExpression as $,printUrlVariablesDeclarations as g}from"../../helpers/code-helpers.js";import{normalizeMimeType as m}from"../../../../utils.js";import{MediaTypes as p}from"../../../../../constants.js";const t=1;function l(s={},y){return m(s.mimeType)===y}const D=function(s,y,{target:c,client:d}){const i={capitalize:!0,showBoilerplate:!0,checkErrors:!0,printBody:!0,timeout:-1,indent:" ",...y},f=s.securityOAuth2ExtraCalls?.[0],n=i.checkErrors?"err":"_",h=s.method.toUpperCase(),e=new b({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:i.capitalize,lang:w.GO}),o=()=>{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&&e.push(t,'"time"'),f&&e.push(t,'"encoding/json"'),l(s.postData,p.MULTIPART)&&(e.push(t,'"mime/multipart"'),e.push(t,'"io"'),e.push(t,'"bytes"')),(l(s.postData,p.URL_ENCODED)||l(s.securityOAuth2ExtraCalls?.[0]?.postData,p.URL_ENCODED))&&(e.push(t,'"net/url"'),e.push(t,'"strconv"')),(l(s.postData,p.JSON)||l(s.securityOAuth2ExtraCalls?.[0]?.postData,p.JSON))&&e.push(t,'"bytes"'),(s.postData&&!l(s.postData,p.JSON)||f)&&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(r=>{s.allHeaders[r]=`"${s.allHeaders[r]}"`}),f){const r="oAuth2",a=i.checkErrors?`${n} := `:"",u=i.capitalize?"Res":"res",v=new q(f).convert(c,d,{...i,printBody:!1,variablesPrefix:r,showBoilerplate:!1});e.push(v).blank().push(t,`var ${r}${u}Body struct {`).push(t+1,"Access_token string").push(t,"}").push(t,`${a}json.NewDecoder(${r}${u}.Body).Decode(&${r}${u}Body)`).blank(),o(),s.allHeaders.Authorization=`"Bearer " + ${r}${u}Body.Access_token`}if(g(s,e,t),i.timeout>0&&(d=e.var("client"),e.push(t,"%s := http.Client{",d).push(t+1,"Timeout: time.Duration(%s * time.Second),",i.timeout).push(t,"}").blank()),e.push(t,`${e.var("reqUrl")} := ${$(s,e)}`),s.postData){let r;switch(m(s.postData.mimeType)){case p.URL_ENCODED:e.push(t,"%s := url.Values{}",e.var("data")),s.postData.params.forEach(a=>{e.push(t,'%s.Set("%s", "%s")',e.var("data"),a.name,a.value)}),e.push(t,'%s, %s := http.NewRequest("%s", %s, strings.NewReader(%s.Encode()))',e.var("req"),n,h,e.var("reqUrl"),e.var("data")),s.allHeaders["Content-Length"]=`strconv.Itoa(len(${e.var("data")}.Encode()))`;break;case p.JSON:r=JSON.stringify(s.postData.jsonObj,null,2).split(`
2
- `).map(a=>i.indent+a).join(`
3
- `).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${r}\`)`),e.push(t,'%s, %s := http.NewRequest("%s", %s, bytes.NewBuffer(%s))',e.var("req"),n,h,e.var("reqUrl"),e.var("data"));break;case p.MULTIPART:e.push(t,"%s := &bytes.Buffer{}",e.var("data")).push(t,"writer := multipart.NewWriter(%s)",e.var("data")),s.postData.params.forEach(a=>{if(!a.fileName&&!a.contentType){e.push(t,'%s, _ := writer.CreateFormField("%s")',e.var(`${a.name}Fw`),a.name).push(t,'_, %s = io.Copy(%s, strings.NewReader("%s"))',n,e.var(`${a.name}Fw`),a.value),o();return}a.fileName&&(e.push(t,'%s, %s = writer.CreateFormFile("%s", "%s")',e.var(`${a.name}Fw`),n,a.name,a.fileName),o())}),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,h,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,h,e.var("reqUrl"),e.var("payload"))}}else e.push(t,'%s, %s := http.NewRequest("%s", %s, nil)',e.var("req"),n,h,e.var("reqUrl"));if(Object.getOwnPropertyNames(s.queryObj).length){e.blank().push(t,`${e.var("query")} := ${e.var("req")}.URL.Query()`);for(const r in s.queryObj){const a=s.queryObj[r],v=typeof a=="string"&&/^\[.*\]$/.test(a)?`\`${a}\``:`"${a}"`;e.push(t,`${e.var("query")}.Add("${r}", ${v})`)}e.push(t,`${e.var("req")}.URL.RawQuery = ${e.var("query")}.Encode()`).blank()}if(o(),s.basicAuth){const{username:r,password:a}=s.basicAuth;e.push(t,`%s.SetBasicAuth("${r}", "${a}")`,e.var("req"))}return Object.keys(s.allHeaders).length&&Object.keys(s.allHeaders).forEach(r=>{e.push(t,'%s.Header.Add("%s", %s)',e.var("req"),r,s.allHeaders[r])}),e.push(t,"%s, %s := %s.Do(%s)",e.var("res"),n,d,e.var("req")),o(),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")),o()),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()},A={key:"native",title:"NewRequest",link:"http://golang.org/pkg/net/http/#NewRequest",description:"Golang HTTP client request"};var T=D;export{T as default,A as info};
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 l}from"../../../../utils.js";import{addIndentation as y,buildUrlExpression as g,printUrlVariablesDeclarations as v}from"../../helpers/code-helpers.js";import{Lang as j}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";const r=t=>!!(t.uriObj.query&&Object.keys(t.uriObj.query).length),o=t=>t.postData&&t.postData.mimeType===i.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")':"",C=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:j.JAVA});if(p.withComments&&k(a,t),p.withImports&&c(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=new b(t.securityOAuth2ExtraCalls?.[0]).convert(u,m,{...p,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});a.push(e),a.blank(),a.push(2,"var oauth2Response = httpClient.send(oauth2Request, HttpResponse.BodyHandlers.ofString());"),a.push(2,'var accessToken = new JSONObject(oauth2Response.body()).getString("access_token");'),a.blank()}if(t.postData)switch(l(t.postData.mimeType)){case i.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 i.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 i.XML:t.postData.text&&(a.push(2,'var payload = String.join("\\n"'),t.postData.text.trim().split(`
3
- `).forEach(e=>{const n=e.replace(/"/g,'\\"');a.push(3,`"${n}", `)}),a.push(2,");"),a.blank());break;case i.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,n]of Object.entries(t.uriObj.query))a.push(2,'params.put("%s", "%s");',e,n);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)',o(t)):a.push(3,".%s(%s)",t.method.toUpperCase(),o(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 h=Object.keys(t.allHeaders);if(h.length&&h.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:n}=t.basicAuth;a.push(3,`.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(("${e}:${n}").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()},w={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 R=C;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 c(t,s){t.push("import java.net.*;"),t.push("import java.net.http.*;"),t.push("import java.util.*;"),(l(s.postData?.mimeType)===i.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{R as default,w as info};
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 j}from"../../helpers/code-builder.js";import{HTTPSnippet as d}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 k}from"../../helpers/code-helpers.js";import{MediaTypes as n}from"../../../../../constants.js";const N=function(t,i,{target:h,client:E}){const p=Object.assign({indent:" ",withWrapper:!0},i),e=new j({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:C.JAVA8}),c=b(t.method);if(p.withComments&&x(e),p.withImports&&q(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=new d(t.securityOAuth2ExtraCalls?.[0]).convert(h,E,{...p,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});e.push(a),e.push(2,"JSONObject %s = new JSONObject(EntityUtils.toString(httpClient.execute(%s).getEntity()));","oauth2Response","oauth2Request"),e.push(2,'String accessToken = %s.getString("access_token");',"oauth2Response"),e.blank()}k(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=>{e.push(2,'%s.setHeader("%s", %s);',e.var("request"),a,t.securityOAuth2ExtraCalls?.length?'"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,O(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))}},U={key:"apachehttp",title:"Apache http",link:"https://hc.apache.org/httpcomponents-client-4.5.x/",description:"Apache HttpClient"};var R=N;function x(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 q(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=b(i);t.push(`import org.apache.http.client.methods.${h};`)}function b(t){return"Http"+A(t.toLowerCase())}function O(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 O(t)?JSON.stringify(t):t??"JSONObject.NULL"}export{R as default,U as info};
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 y,buildUrlExpression as O,printUrlVariablesDeclarations as $}from"../../helpers/code-helpers.js";import{normalizeMimeType as p}from"../../../../utils.js";import{HTTPSnippet as g}from"../../index.js";import{Lang as D}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";const A=function(e,f,{target:m,client:c}){const n={indent:" ",credentials:null,...f},t=new v({indentation:n.indent,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:D.JAVASCRIPT}),a={method:e.method.toUpperCase()};Object.keys(e.headersObj).length&&(a.headers=e.headersObj);let l=!1;if(n.withComments&&j(t),e.securityOAuth2ExtraCalls?.length){const s=new g(e.securityOAuth2ExtraCalls?.[0]).convert(m,c,{...n,withImports:!1,withComments:!1,variablesPrefix:"oAuth2"});t.push(s),t.blank(),a.headers=a.headers||{},a.headers.Authorization="'Bearer ' + oAuth2Data.access_token",l=!0}n.credentials!==null&&(a.credentials=n.credentials);const h=Object.getOwnPropertyNames(e.queryObj).length;if(h&&t.push(`const ${t.var("query")} = new URLSearchParams(${r(e.queryObj,{indent:n.indent,inlineCharacterLimit:25})}).toString();`).blank(),e.postData)switch(p(e.postData.mimeType)){case i.URL_ENCODED:a.body=e.postData.paramsObj?`new URLSearchParams(${t.var("formData")}).toString()`:e.postData.text,e.postData.paramsObj&&t.push(`const ${t.var("formData")} = ${o(r(e.postData.paramsObj,{indent:n.indent,inlineCharacterLimit:25}),{level:0,firstLine:!1})};`).blank();break;case i.JSON:e.postData.jsonObj&&(a.body=`JSON.stringify(${o(r(e.postData.jsonObj,{indent:n.indent,inlineCharacterLimit:25}),{level:1,firstLine:!1})})`);break;case i.MULTIPART:t.push(`const ${t.var("form")} = new FormData();`),delete a?.headers?.["Content-Type"],e.postData.params.forEach(function(s){t.push(`${t.var("form")}.append(%s, %s);`,JSON.stringify(s.name),JSON.stringify(s.value||s.fileName||""))}),a.body=t.var("form"),t.blank();break;default:e.postData.text&&(a.body=`\`${o(e.postData.text,{level:2,indent:n.indent,firstLine:!1}).trim()}\``)}const d=a.headers&&a.headers.Accept&&p(a.headers.Accept)===i.JSON||p(e.postData?.mimeType)===i.JSON;if(e.basicAuth){const{username:s,password:b}=e.basicAuth;a.headers=a.headers||{},a.headers.Authorization=`'Basic ' + btoa('${s}:${b}')`,l=!0}$(e,t);const u=O(e,t);return t.push(`const ${t.var("resp")} = await fetch(`).push(1,"`"+u+(h?"?${"+t.var("query")+"}":"")+"`,").push(o(r(a,{indent:n.indent,inlineCharacterLimit:25,transform:y({body:!0,authorizationHeader:l})}),{level:1,indent:n.indent})).push(");").blank(),e.allResponseCodes?.includes("204")?(t.push("if (resp.status === 204) {").push(1,"console.log('success');").push("} else {"),t.push(1,`const ${t.var("data")} = await ${t.var("resp")}.${d?"json()":"text()"};`).push(1,`console.log(${t.var("data")});`).push("}")):t.push(`const ${t.var("data")} = await ${t.var("resp")}.${d?"json()":"text()"};`).push(`console.log(${t.var("data")});`),t.join()};function j(e){e.push("/**"),e.push(" * Requires ES8-compatible browser: https://caniuse.com/async-functions"),e.push(" */"),e.blank()}const T={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 N=A;export{N as default,T as info};
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 h from"stringify-object";import{CodeBuilder as w}from"../../helpers/code-builder.js";import{addIndentation as r,getPreserveTransformer as y,buildUrlExpression as $,printUrlVariablesDeclarations as k}from"../../helpers/code-helpers.js";import{Lang as D}from"../../helpers/constants.js";import{normalizeMimeType as f}from"../../../../utils.js";import{HTTPSnippet as g}from"../../index.js";import{MediaTypes as o}from"../../../../../constants.js";const j=function(t,c,{target:b,client:v}){const n=Object.assign({indent:" ",showBoilerplate:!0,level:1},c),{level:a}=n;let m=!1;const e=new w({indentation:n.indent,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:D.NODEJS});n.withComments&&S(e),n.withImports&&(e.push("import fetch from 'node-fetch';"),e.blank()),n.showBoilerplate&&e.push("async function run() {");const i={method:t.method.toUpperCase()};Object.keys(t.headersObj).length&&(i.headers=t.headersObj);let l=!1;if(t.securityOAuth2ExtraCalls?.length){const s=new g(t.securityOAuth2ExtraCalls?.[0]).convert(b,v,{...n,withImports:!1,withComments:!1,variablesPrefix:"oAuth2",showBoilerplate:!1,level:1});e.push(s),e.blank(),i.headers=i.headers||{},i.headers.Authorization="'Bearer ' + oAuth2Data.access_token",l=!0}const d=Object.getOwnPropertyNames(t.queryObj).length;if(d&&e.push(a,`const ${e.var("query")} = new URLSearchParams(${r(h(t.queryObj,{indent:n.indent,inlineCharacterLimit:25}),{level:a,indent:n.indent,firstLine:!1})}).toString();`).blank(),t.postData)switch(f(t.postData.mimeType)){case o.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")} = ${r(h(t.postData.paramsObj,{indent:n.indent,inlineCharacterLimit:25}),{level:a,firstLine:!1})};`).blank();break;case o.JSON:t.postData.jsonObj&&(i.body=`JSON.stringify(${r(h(t.postData.jsonObj,{indent:n.indent,inlineCharacterLimit:25}),{level:a,firstLine:!1})})`);break;case o.MULTIPART:delete i?.headers?.["Content-Type"],n.withImports&&e.unshift("import FormData from 'form-data';"),e.push(a,`const ${e.var("form")} = new FormData();`),t.postData.params.forEach(function(s){if(!s.fileName&&!s.fileName&&!s.contentType){e.push(a,"form.append('"+s.name+"','"+s.value+"');");return}s.fileName&&(m=!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=`\`${r(t.postData.text,{level:a+1,indent:n.indent,firstLine:!1}).trim()}\``)}if(t.cookies.length){let s="";t.cookies.forEach(function(p){s=s+encodeURIComponent(p.name)+"="+encodeURIComponent(p.value)+"; "}),s=s.trim(),i.headers||(i.headers={}),i.headers.cookie=s}if(t.basicAuth){const{username:s,password:p}=t.basicAuth;i.headers=i.headers||{},i.headers.Authorization=`'Basic ' + Buffer.from('${s}:${p}').toString('base64')`,l=!0}m&&n.withImports&&e.unshift("import fs from 'fs';");const u=i.headers&&i.headers.Accept&&f(i.headers.Accept)===o.JSON||f(t.postData?.mimeType)===o.JSON;k(t,e,a);const O=$(t,e);return e.push(a,`const ${e.var("resp")} = await fetch(`).push(a+1,"`"+O+(d?"?${"+e.var("query")+"}":"")+"`,").push(a+1,r(h(i,{indent:n.indent,inlineCharacterLimit:25,transform:y({body:!0,authorizationHeader:l})}),{level:a+1,indent:n.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")}.${u?"json()":"text()"};`).push(a+1,`console.log(${e.var("data")});`).push(a,"}")):e.push(a,`const ${e.var("data")} = await ${e.var("resp")}.${u?"json()":"text()"};`).push(a,`console.log(${e.var("data")});`),n.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 P={key:"fetch",title:"Fetch",link:"https://github.com/bitinn/node-fetch",description:"Simplified HTTP node-fetch client"};var U=j;export{U as default,P as info};
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 d}from"util";import{CodeBuilder as O}from"../../helpers/code-builder.js";import{HTTPSnippet as g}from"../../index.js";import{Lang as R}from"../../helpers/constants.js";import{buildUrlExpression as E,printUrlVariablesDeclarations as j}from"../../helpers/code-helpers.js";import{startCase as v}from"../../helpers/lodash-int.js";import{normalizeMimeType as x}from"../../../../utils.js";import{MediaTypes as T}from"../../../../../constants.js";import{objectToPhpArray as _}from"./utils.js";function f(a,p){return p?`$${p}${v(a)}`:`$${a}`}const L=function(a,p,{target:k,client:U}){const t={showBoilerplate:!0,checkErrors:!1,printBody:!0,indent:" ",noTags:!0,shortTags:!1,maxRedirects:10,namedErrors:!1,closingTag:!1,...p};let s,u=!1;const n=new O({indentation:t.indent,capitalize:!0,lang:R.PHP}),m=a.securityOAuth2ExtraCalls?.[0],i=f("curl",t.variablesPrefix),y=f("response",t.variablesPrefix),h=f("error",t.variablesPrefix);if(t.noTags||n.push(t.shortTags?"<?":"<?php").blank(),m){const e="oAuth2",r=new g(m).convert(k,U,{...t,showBoilerplate:!1,variablesPrefix:e});n.push(r),n.blank(),a.allHeaders.Authorization=`Bearer " . ${f("response",e)}.access_token`}const b=Object.keys(a.headersObj).sort().map(function(e){return e==="Authorization"&&m?d('"%s: %s',e,a.allHeaders.Authorization):d('"%s: %s"',e,a.headersObj[e])});if(a.basicAuth){const{username:e,password:r}=a.basicAuth;b.push(`"Authorization: Basic " . base64_encode("${e}:${r}")`)}t.showBoilerplate&&n.push("/**").push(" * Requires libcurl").push(" */").blank(),j(a,n);let o="";if(Object.keys(a.queryObj||{}).length){const e=_(a.queryObj||{},{indent:t.indent});o="$query",n.push(`${o} = ${e};`).blank()}if(n.push(`${i} = curl_init();`),n.blank(),a.postData)switch(x(a.postData.mimeType)){case T.JSON:{const e=_(a.postData.jsonObj||{},{indent:t.indent});u=!0,s="json_encode($payload)",n.push(`$payload = ${e};`).blank();break}case T.MULTIPART:{const e=a.postData.params.map(({name:r,value:$})=>`${t.indent}"${r}" => "${$}",
2
- `).join("");u=!0,s="$payload",n.push(`$payload = array(
3
- ${e});`).blank();break}case T.URL_ENCODED:{const e=a.postData.params.map(({name:r,value:$})=>`${r}=${$}`).join("&");u=!0,s="$payload",n.push(`$payload = "${e}";`).blank();break}default:s=a.postData.text;break}let l=E(a,n);o&&(l.endsWith('"')?l=l.slice(0,-1)+`?" . http_build_query(${o})`:l+=` . "?" . http_build_query(${o})`);const C=[{escape:!u,name:"CURLOPT_POSTFIELDS",value:s},{escape:!0,name:"CURLOPT_PORT",value:a.uriObj.port},{escape:!1,name:"CURLOPT_URL",value:l},{escape:!1,name:"CURLOPT_RETURNTRANSFER",value:"true"},{escape:!0,name:"CURLOPT_CUSTOMREQUEST",value:a.method.toUpperCase()}];n.push(`curl_setopt_array(${i}, [`);const c=new O({indentation:t.indent,lineJoin:`
4
- ${t.indent}`,variablesPrefix:t.variablesPrefix,capitalize:!0,lang:R.PHP});b.length&&c.push("CURLOPT_HTTPHEADER => [").push(1,b.join(`,
5
- `+t.indent+t.indent)).push("],"),C.forEach(function(e){[null,void 0,""].includes(e.value)||c.push(d("%s => %s,",e.name,e.escape?JSON.stringify(e.value):e.value))});const P=a.cookies.map(function(e){return encodeURIComponent(e.name)+"="+encodeURIComponent(e.value)});return P.length&&c.push(d('CURLOPT_COOKIE => "%s",',P.join("; "))),n.push(1,c.join()).push("]);").blank().push(`${y} = curl_exec(${i});`).push(`${h} = curl_error(${i});`).blank().push(`curl_close(${i});`).blank().push(`if (${h}) {`),t.namedErrors?n.push(1,`echo array_flip(get_defined_constants(true)["curl"])[${h}];`):n.push(1,`echo "cURL Error #:" . ${h};`),n.push("} else {").push(1,`echo ${y};`).push("}"),!t.noTags&&t.closingTag&&n.blank().push("?>"),n.join()},V={key:"curl",title:"cURL",link:"http://php.net/manual/en/book.curl.php",description:"PHP with ext-curl"};var I=L;export{I as default,V as info};
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};