@redocly/openapi-docs 3.14.0-next.12 → 3.14.0-next.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/redocly-openapi-docs.min.js +1618 -1583
- package/lib/components/ContentItem/ContentItem.js +1 -1
- package/lib/components/RedoclyOpenAPIDocs/Error.d.ts +3 -0
- package/lib/components/RedoclyOpenAPIDocs/Error.js +25 -0
- package/lib/components/RedoclyOpenAPIDocs/RedoclyOpenAPIDocsStandalone.js +1 -1
- package/lib/components/Security/OAuthFlow.js +1 -1
- package/lib/components/Security/SecurityButton.js +14 -7
- package/lib/components/Security/SecurityFlow.d.ts +1 -1
- package/lib/components/Security/SecurityFlow.js +10 -5
- package/lib/components/ServerList/ServerDescriptionTooltip.d.ts +4 -0
- package/lib/components/ServerList/ServerDescriptionTooltip.js +1 -0
- package/lib/components/ServerList/ServerList.js +14 -9
- package/lib/components/ServerListDropdown/ServerListDropdown.js +1 -1
- package/lib/services/code-samples/generator.d.ts +9 -2
- package/lib/services/code-samples/generator.js +1 -1
- package/lib/services/code-samples/httpsnippet/helpers/device-auth-snippets.d.ts +25 -0
- package/lib/services/code-samples/httpsnippet/helpers/device-auth-snippets.js +1 -0
- package/lib/services/code-samples/httpsnippet/targets/csharp/httpclient.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/csharpNewtonsoft/httpclient.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/go/native.js +3 -3
- package/lib/services/code-samples/httpsnippet/targets/java/httpclient.js +3 -3
- package/lib/services/code-samples/httpsnippet/targets/java8/apachehttp.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/javascript/fetch.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/node/fetch.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/php/curl.js +5 -5
- package/lib/services/code-samples/httpsnippet/targets/python/requests.js +5 -5
- package/lib/services/code-samples/httpsnippet/targets/r/httr.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/ruby/native.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/shell/curl.js +7 -6
- package/lib/standalone.js +1 -1
- package/lib/types/open-api.d.ts +10 -0
- package/lib/utils/helpers.d.ts +2 -0
- package/lib/utils/helpers.js +4 -4
- package/lib/utils/loadAndBundleSpec.js +1 -1
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,Fragment as m,jsxs as
|
|
1
|
+
import{jsx as e,Fragment as m,jsxs as f}from"react/jsx-runtime";import{memo as u}from"react";import{useAtomValue as x}from"jotai";import{joinWithSeparator as y}from"../../services/index.js";import{TagItem as p}from"../TagItem/index.js";import{OperationItem as I}from"../OperationItem/index.js";import{Section as g}from"../common/index.js";import{useIsExpanded as C}from"./useIsExpanded.js";import{SectionItem as h}from"../SectionItem/index.js";import j from"../ContentItems/useScrollOnRender.js";import{isRootItem as S}from"../ContentItems/helpers.js";import{ApiInfo as A}from"../ApiInfo/index.js";import{layoutAtom as E}from"../../jotai/app.js";const R={group:null,tag:p,section:h,schema:p,operation:I,root:A};function _({item:o,routingBasePath:t,children:s,layout:a}){const i=S(o),r=R[i?"root":o.type],d=o.type==="tag"&&o.items.length>0,n=C({item:o,routingBasePath:t});let c=j(o,t);const l=x(E);return f(m,{children:[r&&e(g,{id:o.id,ref:c,sectionId:y(t,o.id),underlined:o.type==="operation"||o.type==="schema",expanded:d&&!n,children:e(r,{item:o,routingBasePath:t,isExpanded:n,layout:a||l})}),(n||o.type!=="tag")&&!!o.items?.length&&e(m,{children:s})]})}const G=u(_);export{G as ContentItem};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import{jsx as e,jsxs as r,Fragment as i}from"react/jsx-runtime";import t from"styled-components";import{GlobalStyle as a}from"@redocly/theme/core/openapi";function f({description:o}){return console.error(o),r(i,{children:[e(a,{}),r(n,{children:[e(l,{children:";("}),e(s,{children:"Something went wrong..."}),r(g,{children:["Please check the console for get more details or"," ",e("a",{target:"_blank",rel:"noopener noreferrer",href:"https://redocly.com/docs/redoc",children:"documentation"}),"."]})]})]})}const n=t.div`
|
|
2
|
+
height: 100vh;
|
|
3
|
+
max-width: var(--page-404-max-width);
|
|
4
|
+
display: flex;
|
|
5
|
+
flex-direction: column;
|
|
6
|
+
justify-content: center;
|
|
7
|
+
margin: var(--page-404-margin-vertical) var(--page-404-margin-horizontal);
|
|
8
|
+
font-family: var(--page-404-font-family);
|
|
9
|
+
gap: var(--page-404-gap);
|
|
10
|
+
`,l=t.div`
|
|
11
|
+
color: var(--page-404-status-text-color);
|
|
12
|
+
font-size: var(--page-404-status-font-size);
|
|
13
|
+
line-height: var(--page-404-status-line-height);
|
|
14
|
+
font-weight: var(--page-404-status-font-weight);
|
|
15
|
+
`,s=t.div`
|
|
16
|
+
color: var(--page-404-title-text-color);
|
|
17
|
+
font-size: var(--page-404-title-font-size);
|
|
18
|
+
line-height: var(--page-404-title-line-height);
|
|
19
|
+
font-weight: var(--page-404-title-font-weight);
|
|
20
|
+
`,g=t.div`
|
|
21
|
+
color: var(--page-404-description-text-color);
|
|
22
|
+
font-size: var(--page-404-description-font-size);
|
|
23
|
+
line-height: var(--page-404-description-line-height);
|
|
24
|
+
font-weight: var(--page-404-description-font-weight);
|
|
25
|
+
`;export{f as ErrorPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as s}from"react/jsx-runtime";import{cloneElement as w,isValidElement as x,useEffect as g,useMemo as A,useState as c}from"react";import{Loading as O}from"@redocly/theme/components/Loaders/Loading";import{useDeepCompareMemoize as D,fixSpec as E}from"./utils.js";import{argValueToBoolean as L}from"../../utils/index.js";import{RedoclyOpenAPIDocs as P}from"./RedoclyOpenAPIDocs.js";import{loadAndBundleDefinition as u,loadOpenapiConfig as B}from"../../utils/loadAndBundleSpec.js";import{ErrorPage as I}from"./Error.js";async function k(e,o,t){let n;if(t?.skipBundle){if(!e)throw new Error('spec must be specified when using "skipBundleAndConvert"');n=e}else n=await u(e||o);try{E(n)}catch{}return n}function _(e,o){return e.endsWith(".md")?u({openapi:"3.0.0",info:{title:o||"",version:"1.0",description:{$ref:e}},paths:{}}):u(e)}const C=({options:e,definitionUrl:o,definition:t,activeSampleLanguage:n,children:r})=>{const[i,l]=c(),[h,f]=c(!0),[d,y]=c(null),[m,S]=c(e||{});g(()=>{async function v(){f(!0);try{const p=await B();S({...e,...p}),y(await k(t,o,e))}catch(p){l(p.message)}}v()},[t,o,e]);const a=A(()=>{if(d)return{definition:d,options:m,definitionUrl:o,activeSampleLanguage:n}},D([d,o,m]));return g(()=>{a&&f(!1)},[a]),i?s(I,{description:i||"Please check path to your OpenAPI description"}):a?h?L(e?.hideLoading,!1)?null:s(O,{color:"--loading-spinner-color"}):x(r)?w(r,{store:a}):null:null};function $({definition:e,definitionUrl:o,options:t={},activeItemId:n,activeSampleLanguage:r,activeDeepLink:i,router:l}){return s(C,{definition:e,definitionUrl:o,options:t,activeItemId:n,activeSampleLanguage:r,activeDeepLink:i,children:s(P,{withCommonStyles:!0,router:l||"hash"})})}export{C as AppProvider,$ as RedoclyOpenAPIDocsStandalone,_ as loadAndBundleSpecOrMd,k as loadSingle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,Fragment as a,jsxs as
|
|
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
|
|
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
|
-
`,
|
|
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
|
-
`,
|
|
22
|
+
`,T=e(h)`
|
|
16
23
|
margin-left: auto;
|
|
17
24
|
font-size: var(--font-size-sm);
|
|
18
|
-
`,
|
|
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
|
-
`,
|
|
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
|
-
`,
|
|
35
|
+
`,p=e.span`
|
|
29
36
|
color: var(--text-color-description);
|
|
30
|
-
`;export{
|
|
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
|
|
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
|
-
`,
|
|
13
|
+
`,A=n.div`
|
|
9
14
|
width: 100%;
|
|
10
15
|
margin-top: var(--spacing-md);
|
|
11
|
-
`,
|
|
16
|
+
`,_=n.p`
|
|
12
17
|
font-size: var(--font-size-base);
|
|
13
|
-
margin: 0
|
|
18
|
+
margin: 0;
|
|
14
19
|
text-transform: capitalize;
|
|
15
20
|
font-weight: var(--font-weight-semibold);
|
|
16
|
-
`;export{
|
|
21
|
+
`;export{N as SecurityFlow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as t}from"react/jsx-runtime";import{useEffect as s,useState as i}from"react";import{Button as a}from"@redocly/theme/components/Button/Button";import{Tooltip as m}from"@redocly/theme/components/Tooltip/Tooltip";import{InformationIcon as c}from"@redocly/theme/icons/InformationIcon/InformationIcon";const v=({description:n})=>{const[o,e]=i(!1);return s(()=>{const r=()=>{o&&e(!1)};if(o)return document.addEventListener("touchmove",r,{passive:!0}),()=>{document.removeEventListener("touchmove",r)}},[o]),t(m,{tip:n,placement:"bottom",arrowPosition:"left",isOpen:o,children:t(a,{size:"small",variant:"ghost",icon:t(c,{}),"data-testid":"server-item-description-tooltip",onClick:()=>e(!0),onBlur:()=>e(!1),onFocus:()=>e(!0),onMouseEnter:()=>e(!0),onMouseLeave:()=>e(!1),onTouchCancel:()=>e(!1)})})};export{v as ServerDescriptionTooltip};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{jsx as i,jsxs as
|
|
1
|
+
import{jsx as i,jsxs as o}from"react/jsx-runtime";import{CopyButton as x}from"@redocly/theme/components/Buttons/CopyButton";import{getServerDisplayName as b}from"../../utils/helpers.js";import{PanelItemDescription as u,Title as y}from"../PanelItem/index.js";import{ViewNested as w}from"../ViewNested/index.js";import{Tag as S}from"../common/index.js";import{Markdown as T}from"../Markdown/index.js";import{styled as e}from"../../styled-components.js";import{ServerDescriptionTooltip as j}from"./ServerDescriptionTooltip.js";const q=({servers:h,path:f,translate:r})=>i(D,{children:h.map(t=>{const a=t.url+f,p=Object.keys(t.variables||{}).length,d=p===1?"variable":"variables",l=`${p||""} ${r(`openapi.${d}`,d)}`,v=!!t.name&&!!t.description;return o("div",{children:[o(L,{children:[i(u,{"data-testid":"server-panel-item-name",children:b(t)}),v&&i(j,{description:t.description})]}),o(O,{children:[i(y,{suppressHydrationWarning:!0,children:a}),i(x,{data:a},a)]}),t.variables&&i(w,{expandText:`${r("openapi.actions.show","Show")} ${l}`,hideText:`${r("openapi.actions.hide","Hide")} ${l}`,expandByDefault:!1,expandable:!0,hideDivider:!0,children:i($,{children:Object.entries(t.variables||{}).map(([c,n])=>o(z,{children:[i(k,{children:c}),o(s,{children:[r("openapi.default","Default")," ",i(g,{children:n.default})]}),i(W,{source:n.description}),n.enum&&o(s,{children:[r("openapi.enum","Enum")," ",i(C,{children:n.enum.map(m=>i(g,{children:m},m))})]})]},c))})})]},t.url)})}),D=e.div`
|
|
2
2
|
& > div {
|
|
3
3
|
border-bottom: 1px solid var(--border-color-secondary);
|
|
4
4
|
margin-bottom: var(--spacing-xs);
|
|
@@ -10,7 +10,7 @@ import{jsx as i,jsxs as t}from"react/jsx-runtime";import{CopyButton as v}from"@r
|
|
|
10
10
|
margin-bottom: 0;
|
|
11
11
|
padding-bottom: 0;
|
|
12
12
|
}
|
|
13
|
-
|
|
13
|
+
`,$=e.div`
|
|
14
14
|
padding-left: var(--spacing-xxs);
|
|
15
15
|
& > div {
|
|
16
16
|
border-bottom: 1px solid var(--border-color-secondary);
|
|
@@ -28,11 +28,11 @@ import{jsx as i,jsxs as t}from"react/jsx-runtime";import{CopyButton as v}from"@r
|
|
|
28
28
|
margin-bottom: 0;
|
|
29
29
|
padding-bottom: 0;
|
|
30
30
|
}
|
|
31
|
-
`,
|
|
31
|
+
`,z=e.div`
|
|
32
32
|
display: flex;
|
|
33
33
|
flex-direction: column;
|
|
34
34
|
flex-wrap: wrap;
|
|
35
|
-
|
|
35
|
+
`,W=e(T)`
|
|
36
36
|
font-size: var(--font-size-sm);
|
|
37
37
|
line-height: var(--line-height-sm);
|
|
38
38
|
color: var(--text-color-primary);
|
|
@@ -42,18 +42,23 @@ import{jsx as i,jsxs as t}from"react/jsx-runtime";import{CopyButton as v}from"@r
|
|
|
42
42
|
font-size: var(--font-size-sm);
|
|
43
43
|
line-height: var(--line-height-sm);
|
|
44
44
|
color: var(--text-color-primary);
|
|
45
|
-
`,
|
|
45
|
+
`,k=e(s)`
|
|
46
46
|
padding-bottom: var(--spacing-xxs);
|
|
47
47
|
font-weight: var(--font-weight-semibold);
|
|
48
|
-
`,
|
|
48
|
+
`,C=e.span`
|
|
49
49
|
display: flex;
|
|
50
50
|
gap: var(--spacing-xxs);
|
|
51
51
|
flex-wrap: wrap;
|
|
52
|
-
`,g=e(
|
|
52
|
+
`,g=e(S)`
|
|
53
53
|
font-size: var(--font-size-sm);
|
|
54
54
|
line-height: var(--line-height-sm);
|
|
55
|
-
`,
|
|
55
|
+
`,L=e.div`
|
|
56
|
+
display: flex;
|
|
57
|
+
justify-content: start;
|
|
58
|
+
align-items: center;
|
|
59
|
+
gap: var(--spacing-xxs);
|
|
60
|
+
`,O=e.div`
|
|
56
61
|
display: flex;
|
|
57
62
|
justify-content: space-between;
|
|
58
63
|
align-items: center;
|
|
59
|
-
`;export{
|
|
64
|
+
`;export{q as ServerList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as t,jsxs as d}from"react/jsx-runtime";import{useMemo as f,useCallback as l}from"react";import{useAtom as S,useAtomValue as g}from"jotai";import{DropdownMenu as w}from"@redocly/theme/components/Dropdown/DropdownMenu";import{Dropdown as y}from"@redocly/theme/components/Dropdown/Dropdown";import{HttpVerb as k}from"../common/index.js";import{PathWrapper as A,Path as C,StyledCopyButton as b,StyledDropdownMenuItem as D}from"./styled.js";import{PanelItem as P}from"../PanelItem/index.js";import{joinWithSeparator as j}from"../../services/index.js";import{getServerDisplayName as x,replaceVariables as V}from"../../utils/index.js";import{environmentAtom as M}from"../../jotai/app.js";import{useActiveWithFallback as E,useTelemetry as N}from"../../hooks/index.js";import{getServerEnvName as p}from"../../utils/environments.js";import{createTargetServerSwitchEvent as W}from"../../events/index.js";import{globalStoreAtom as I}from"../../jotai/store.js";const X=({operation:r,className:h})=>{const n=N(),[[v],i]=S(M),{options:{events:m}}=g(I),s=E(r.servers.map(e=>({...e,key:e.url})),v.server),a=l(e=>{e.stopPropagation()},[]),c=l(e=>()=>{if(r.servers.length!==1&&(i({environment:p(e)}),n.sendOpenapiDocsSwitchServersClickedMessage({server:p(e)}),m?.targetServerSwitch&&e)){const o=W({operation:r,serverUrl:e.url});m.targetServerSwitch(o)}},[r,i,n,m]),u=f(()=>r.servers.map(e=>{const o=j(V(e),r.path);return t(D,{onAction:c(e),children:t(P,{header:x(e),title:o,actions:[t(b,{data:o,toasterPlacement:"left",onCopyClick:a},o)],active:e.url===s,withCheckmark:!0})},o)}),[r.servers,r.path,c,a,s]);return t(y,{className:h,trigger:d(A,{variant:"ghost",children:[t(k,{color:r.httpVerb,children:r.httpVerb}),t(C,{children:r.path})]}),withArrow:!0,children:t(w,{children:u})})};export{X as ServerListDropdown};
|
|
@@ -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?:
|
|
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
|
|
2
|
-
`).forEach((
|
|
1
|
+
import{isObject as y}from"@redocly/theme/core/openapi";import{CodeBuilder as b}from"../../helpers/code-builder.js";import{HTTPSnippet as w}from"../../index.js";import{buildUrlExpression as S,printUrlVariablesDeclarations as A}from"../../helpers/code-helpers.js";import{isEmptyObject as E,normalizeMimeType as m}from"../../../../utils.js";import{capitalizeFirst as O}from"../../../generator.js";import{Lang as k}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";import{isLastInArray as H,isLastProperty as j}from"../../../../../utils/index.js";import{buildCSharpDeviceAuthorizationCodeSnippet as x}from"../../helpers/device-auth-snippets.js";const L=function(e,c,{target:C,client:D}){const r=Object.assign({indent:" ",withWrapper:!0},c),t=new b({indentation:r.indent,variablesPrefix:r.variablesPrefix,capitalize:!0,lang:k.CSHARP}),T=P(e.method);if(r.withComments&&R(t),r.withWrapper&&(t.push("using System;"),t.push("using System.Net.Http;"),t.push("using System.Threading.Tasks;"),(h(i.JSON)||h(i.XML)||e.basicAuth)&&t.push("using System.Text;"),(h(i.URL_ENCODED)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Collections.Generic;"),(h(i.JSON)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Text.Json;"),l()&&t.push("using System.IO;"),(l()||e.basicAuth)&&t.push("using System.Net.Http.Headers;"),t.blank(),t.push("public class Program"),t.push("{"),t.push(1,"public static async Task Main()"),t.push(1,"{")),e.securityOAuth2ExtraCalls?.length){const s=e.securityOAuth2ExtraCalls?.[0],a=new w(s).convert(C,D,{...r,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(a),t.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),s.flowType==="deviceAuthorization"?x(t,{tokenUrl:s.tokenUrl??"YOUR_TOKEN_URL",clientId:s.clientId??"YOUR_CLIENT_ID",level:2}):(t.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),t.push(2,'var accessToken = inputJObject["access_token"].ToString();'),t.blank())}const f=Object.keys(e.allHeaders).filter(s=>{switch(s.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(f.length?(t.push(2,"System.Net.Http.HttpClient client = new()"),t.push(2,"{"),t.push(3,"DefaultRequestHeaders ="),t.push(3,"{"),f.forEach(s=>{const a=s.toLowerCase()==="authorization";t.push(4,'{"%s", %s},',s,e.securityOAuth2ExtraCalls?.length&&a?'"Bearer " + accessToken':`"${e.allHeaders[s]}"`)}),t.push(3,"}"),t.push(2,"};")):t.push(2,"System.Net.Http.HttpClient client = new();"),t.blank(),e.basicAuth){const{username:s,password:a}=e.basicAuth;t.push(2,`string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${s}:${a}"));`),t.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);'),t.blank()}if(e.postData)switch(m(e.postData.mimeType)){case i.URL_ENCODED:e.postData.params&&(t.blank(),t.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),e.postData.params.forEach(s=>{t.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',s.name,s.value)}),t.blank());break;case i.MULTIPART:e.postData.params&&(t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),e.postData.params.forEach(s=>{t.push(2,'postData.Add(new StringContent("%s"), "%s");',s.value,s.name)}));break;case i.JSON:e.postData.jsonObj&&(t.push(2,"string json = JsonSerializer.Serialize(new"),t.push(2,"{"),u(e.postData.jsonObj,3),t.push(2,"});"),t.blank(),t.push(2,'using StringContent postData = new(json, Encoding.UTF8, "%s");',e.postData.mimeType));break;case i.XML:e.postData.text&&(e.postData.text.trim().split(`
|
|
2
|
+
`).forEach((s,a)=>{const n=(a===0?'string xml = @"':"")+s.replace(/"/g,'""');t.push(a===0?2:3,n)}),t.push(2,'";'),t.push(2,'using StringContent postData = new StringContent(xml, Encoding.UTF8, "%s");',e.postData.mimeType));break}else l()&&(t.push(2,"var ms = new MemoryStream();"),t.push(2,"var postData = new StreamContent(ms);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));return A(e,t,3),t.push(2,"using HttpResponseMessage %s = await client.%sAsync(%s%s);",t.var("request"),T,S(e,t),r.withImports?U(e.method)?m(e.postData&&e.postData.mimeType)===i.URL_ENCODED?", new FormUrlEncodedContent(postData)":e.method==="delete"?"":e.postData&&e.postData.params||l()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),r.withWrapper&&(t.push(2,"string response = await request.Content.ReadAsStringAsync();"),t.blank(),t.push(2,"Console.WriteLine(response);"),t.push(1,"}"),t.push("}")),t.join();function h(s){return e.postData&&m(e.postData.mimeType)===s}function l(){return e.headersObj&&e.headersObj["Content-Type"]===i.OCTET_STREAM}function d(s,a){s.forEach((n,p)=>{const o=!H(s,p);Array.isArray(n)?d(n,a+1):y(n)?(t.push(a+1,"new {"),u(n,a+2),t.push(a+1,"}%s",o?",":"")):t.push(a+1,'"%s"%s',n,o?",":"")}),t.push(a,"},")}function u(s,a){for(const[n,p]of Object.entries(s)){const o=!j(s,n);if(Array.isArray(p))t.push(a,"%s = new[] {",n),d(p,a);else if(y(p)){const g=E(p);t.push(a,"%s = new %s",n,g?"{},":"{"),g||(u(p,a+1),t.push(a,"}%s",o?",":""))}else t.push(a,'%s = "%s"%s',n,p,o?",":"")}}},B={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var W=L;function R(e){e.push("// Requires >= .NET 5"),e.blank()}function P(e){return O(e.toLowerCase())}function U(e){return e&&["POST","PUT","DELETE","PATCH"].includes(e.toUpperCase())}export{W as default,B as info};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import f from"stringify-object";import{CodeBuilder as
|
|
2
|
-
`).forEach((a,
|
|
1
|
+
import f from"stringify-object";import{CodeBuilder as C}from"../../helpers/code-builder.js";import{HTTPSnippet as g}from"../../index.js";import{addIndentation as D,buildUrlExpression as T,printUrlVariablesDeclarations as y}from"../../helpers/code-helpers.js";import{normalizeMimeType as o}from"../../../../utils.js";import{capitalizeFirst as w}from"../../../generator.js";import{Lang as b}from"../../helpers/constants.js";import{MediaTypes as s}from"../../../../../constants.js";import{buildCSharpNewtonsoftDeviceAuthorizationCodeSnippet as O}from"../../helpers/device-auth-snippets.js";const S=function(t,l,{target:u,client:m}){const n=Object.assign({indent:" ",withWrapper:!0},l),e=new C({indentation:n.indent,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:b.CSHARPNEWTONSOFT}),c=A(t.method);if(n.withComments&&E(e),n.withWrapper&&(e.push("using System;"),e.push("using System.Net.Http;"),e.push("using System.Threading.Tasks;"),(r(s.JSON)||r(s.XML)||t.basicAuth)&&e.push("using System.Text;"),(r(s.URL_ENCODED)||t.securityOAuth2ExtraCalls?.length)&&e.push("using System.Collections.Generic;"),(r(s.JSON)||t.securityOAuth2ExtraCalls?.length)&&e.push("using Newtonsoft.Json.Linq;"),p()&&e.push("using System.IO;"),(p()||t.basicAuth)&&e.push("using System.Net.Http.Headers;"),e.blank(),e.push("public class Program"),e.push("{"),e.push(1,"private readonly IHttpClientFactory _httpClientFactory;"),e.push(1,"public static async Task Main(string[] args)"),e.push(1,"{"),e.push(2,"var client = _httpClientFactory.CreateClient();")),t.securityOAuth2ExtraCalls?.length){const a=t.securityOAuth2ExtraCalls?.[0],i=new g(a).convert(u,m,{...n,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});e.push(i),e.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),a.flowType==="deviceAuthorization"?O(e,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(e.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),e.push(2,'var accessToken = inputJObject["access_token"].ToString();'),e.blank())}const h=Object.keys(t.allHeaders).filter(a=>{switch(a.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(h.length&&h.forEach(a=>{const i=a.toLowerCase()==="authorization";e.push(2,'client.DefaultRequestHeaders.Add("%s", %s);',a,t.securityOAuth2ExtraCalls?.length&&i?'"Bearer " + accessToken':`"${t.allHeaders[a]}"`)}),t.basicAuth){const{username:a,password:i}=t.basicAuth;e.push(2,`var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${a}:${i}"));`),e.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);')}if(t.postData)switch(o(t.postData.mimeType)){case s.URL_ENCODED:t.postData.params&&(e.blank(),e.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),t.postData.params.forEach(a=>{e.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',a.name,a.value)}),e.blank());break;case s.MULTIPART:t.postData.params&&(e.blank(),e.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),t.postData.params.forEach(a=>{e.push(2,'postData.Add(new StringContent("%s"), "%s");',a.value,a.name)}));break;case s.JSON:t.postData.jsonObj&&(e.push(2,`JObject json = JObject.Parse(@"${D(f(t.postData.jsonObj,{indent:n.indent,inlineCharacterLimit:25}).replace(/"/g,'""'),{level:3,firstLine:!1})}");`),e.push(2,'var postData = new StringContent(json.ToString(), Encoding.UTF8, "%s");',t.postData.mimeType));break;case s.XML:t.postData.text&&(t.postData.text.trim().split(`
|
|
2
|
+
`).forEach((a,i)=>{const d=(i===0?'string xml = @"':"")+a.replace(/"/g,'""');e.push(i===0?3:4,d)}),e.push(2,'";'),e.push(2,'var postData = new StringContent(xml, Encoding.UTF8, "%s");',t.postData.mimeType));break}else p()&&(e.push(2,"var ms = new MemoryStream();"),e.push(2,"var postData = new StreamContent(ms);"),e.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));return y(t,e,3),e.push(2,"var %s = await client.%sAsync(%s%s);",e.var("request"),c,T(t,e),n.withImports?v(t.method)?o(t.postData&&t.postData.mimeType)===s.URL_ENCODED?", new FormUrlEncodedContent(postData)":t.method==="delete"?"":t.postData&&t.postData.params||p()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),n.withWrapper&&(e.push(2,"var response = await request.Content.ReadAsStringAsync();"),e.blank(),e.push(2,"Console.WriteLine(response);"),e.push(1,"}"),e.push("}")),e.join();function r(a){return t.postData&&o(t.postData.mimeType)===a}function p(){return t.headersObj&&t.headersObj["Content-Type"]===s.OCTET_STREAM}},M={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var F=S;function E(t){t.push("/*"),t.push(" * Requires >= .NET 5"),t.push(" *"),t.push(' * Requires package "Newtonsoft.Json" >= 9.01'),t.push(" * See here for installation details:"),t.push(" * https://www.newtonsoft.com/json"),t.push(" */"),t.blank()}function A(t){return w(t.toLowerCase())}function v(t){return t&&["POST","PUT","DELETE","PATCH"].includes(t.toUpperCase())}export{F as default,M as info};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{CodeBuilder as b}from"../../helpers/code-builder.js";import{HTTPSnippet as
|
|
2
|
-
`).map(
|
|
3
|
-
`).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${
|
|
1
|
+
import{CodeBuilder as b}from"../../helpers/code-builder.js";import{HTTPSnippet as $}from"../../index.js";import{Lang as w}from"../../helpers/constants.js";import{buildUrlExpression as q,printUrlVariablesDeclarations as D}from"../../helpers/code-helpers.js";import{normalizeMimeType as c}from"../../../../utils.js";import{MediaTypes as o}from"../../../../../constants.js";import{buildGoDeviceAuthorizationCodeSnippet as N}from"../../helpers/device-auth-snippets.js";const t=1;function u(s={},y){return c(s.mimeType)===y}const g=function(s,y,{target:m,client:f}){const i={capitalize:!0,showBoilerplate:!0,checkErrors:!0,printBody:!0,timeout:-1,indent:" ",...y},p=s.securityOAuth2ExtraCalls?.[0],n=i.checkErrors?"err":"_",d=s.method.toUpperCase(),e=new b({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:i.capitalize,lang:w.GO}),h=()=>{i.checkErrors&&e.push(t,"if err != nil {").push(t+1,"panic(err)").push(t,"}")};if(i.showBoilerplate&&(e.push("package main").blank().push("import (").push(t,'"fmt"'),(i.timeout>0||p?.flowType==="deviceAuthorization")&&e.push(t,'"time"'),p&&e.push(t,'"encoding/json"'),u(s.postData,o.MULTIPART)&&(e.push(t,'"mime/multipart"'),e.push(t,'"io"'),e.push(t,'"bytes"')),(u(s.postData,o.URL_ENCODED)||u(s.securityOAuth2ExtraCalls?.[0]?.postData,o.URL_ENCODED))&&(e.push(t,'"net/url"'),e.push(t,'"strconv"')),(u(s.postData,o.JSON)||u(s.securityOAuth2ExtraCalls?.[0]?.postData,o.JSON))&&e.push(t,'"bytes"'),(s.postData&&!u(s.postData,o.JSON)||p)&&e.push(t,'"strings"'),e.push(t,'"net/http"'),i.printBody&&e.push(t,'"io/ioutil"'),e.push(")").blank().push("func main() {")),Object.keys(s.allHeaders).length&&Object.keys(s.allHeaders).forEach(a=>{s.allHeaders[a]=`"${s.allHeaders[a]}"`}),p){const a="oAuth2",r=i.checkErrors?`${n} := `:"",l=i.capitalize?"Res":"res",v=new $(p).convert(m,f,{...i,printBody:!1,variablesPrefix:a,showBoilerplate:!1});e.push(v).blank(),p.flowType==="deviceAuthorization"?(e.push(t,`var ${a}${l}Body struct {`).push(t+1,"Device_code string").push(t+1,"Interval int64").push(t+1,"Expires_in int64").push(t,"}").push(t,`${r}json.NewDecoder(${a}${l}.Body).Decode(&${a}${l}Body)`).blank(),h(),N(e,{tokenUrl:p.tokenUrl??"YOUR_TOKEN_URL",clientId:p.clientId??"YOUR_CLIENT_ID",level:t}),s.allHeaders.Authorization='"Bearer " + accessToken'):(e.push(t,`var ${a}${l}Body struct {`).push(t+1,"Access_token string").push(t,"}").push(t,`${r}json.NewDecoder(${a}${l}.Body).Decode(&${a}${l}Body)`).blank(),h(),s.allHeaders.Authorization=`"Bearer " + ${a}${l}Body.Access_token`)}if(D(s,e,t),i.timeout>0&&(f=e.var("client"),e.push(t,"%s := http.Client{",f).push(t+1,"Timeout: time.Duration(%s * time.Second),",i.timeout).push(t,"}").blank()),e.push(t,`${e.var("reqUrl")} := ${q(s,e)}`),s.postData){let a;switch(c(s.postData.mimeType)){case o.URL_ENCODED:e.push(t,"%s := url.Values{}",e.var("data")),s.postData.params.forEach(r=>{e.push(t,'%s.Set("%s", "%s")',e.var("data"),r.name,r.value)}),e.push(t,'%s, %s := http.NewRequest("%s", %s, strings.NewReader(%s.Encode()))',e.var("req"),n,d,e.var("reqUrl"),e.var("data")),s.allHeaders["Content-Length"]=`strconv.Itoa(len(${e.var("data")}.Encode()))`;break;case o.JSON:a=JSON.stringify(s.postData.jsonObj,null,2).split(`
|
|
2
|
+
`).map(r=>i.indent+r).join(`
|
|
3
|
+
`).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${a}\`)`),e.push(t,'%s, %s := http.NewRequest("%s", %s, bytes.NewBuffer(%s))',e.var("req"),n,d,e.var("reqUrl"),e.var("data"));break;case o.MULTIPART:e.push(t,"%s := &bytes.Buffer{}",e.var("data")).push(t,"writer := multipart.NewWriter(%s)",e.var("data")),s.postData.params.forEach(r=>{if(!r.fileName&&!r.contentType){e.push(t,'%s, _ := writer.CreateFormField("%s")',e.var(`${r.name}Fw`),r.name).push(t,'_, %s = io.Copy(%s, strings.NewReader("%s"))',n,e.var(`${r.name}Fw`),r.value),h();return}r.fileName&&(e.push(t,'%s, %s = writer.CreateFormFile("%s", "%s")',e.var(`${r.name}Fw`),n,r.name,r.fileName),h())}),e.push(t,"writer.Close()").blank().push(t,"%s := bytes.NewReader(%s.Bytes())",e.var("payload"),e.var("data")).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,d,e.var("reqUrl"),e.var("payload")),s.allHeaders["Content-Type"]="writer.FormDataContentType()";break;default:s.postData.text&&e.push(t,"%s := strings.NewReader(%s)",e.var("payload"),JSON.stringify(s.postData?.text)).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,d,e.var("reqUrl"),e.var("payload"))}}else e.push(t,'%s, %s := http.NewRequest("%s", %s, nil)',e.var("req"),n,d,e.var("reqUrl"));if(Object.getOwnPropertyNames(s.queryObj).length){e.blank().push(t,`${e.var("query")} := ${e.var("req")}.URL.Query()`);for(const a in s.queryObj){const r=s.queryObj[a],v=typeof r=="string"&&/^\[.*\]$/.test(r)?`\`${r}\``:`"${r}"`;e.push(t,`${e.var("query")}.Add("${a}", ${v})`)}e.push(t,`${e.var("req")}.URL.RawQuery = ${e.var("query")}.Encode()`).blank()}if(h(),s.basicAuth){const{username:a,password:r}=s.basicAuth;e.push(t,`%s.SetBasicAuth("${a}", "${r}")`,e.var("req"))}return Object.keys(s.allHeaders).length&&Object.keys(s.allHeaders).forEach(a=>{e.push(t,'%s.Header.Add("%s", %s)',e.var("req"),a,s.allHeaders[a])}),e.push(t,"%s, %s := %s.Do(%s)",e.var("res"),n,f,e.var("req")),h(),i.printBody&&(e.push(t,"defer %s.Body.Close()",e.var("res")).push(t,"%s, %s := ioutil.ReadAll(%s.Body)",e.var("body"),n,e.var("res")),h()),e.blank().push(t,"fmt.Println(%s)",e.var("res")),i.printBody&&e.push(t,"fmt.Println(string(%s))",e.var("body")),i.showBoilerplate&&e.push("}"),e.join()},U={key:"native",title:"NewRequest",link:"http://golang.org/pkg/net/http/#NewRequest",description:"Golang HTTP client request"};var j=g;export{j as default,U as info};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{CodeBuilder as f}from"../../helpers/code-builder.js";import{HTTPSnippet as b}from"../../index.js";import{normalizeMimeType as
|
|
2
|
-
${y(JSON.stringify(t.postData.jsonObj,null,1).replace(/"/g,'\\"').replace(/^/gm,', "').replace(/$/gm,'"'),{level:3,indent:p.indent,firstLine:!1})}`),a.push(2,");"),a.blank());break;case
|
|
3
|
-
`).forEach(e=>{const
|
|
1
|
+
import{CodeBuilder as f}from"../../helpers/code-builder.js";import{HTTPSnippet as b}from"../../index.js";import{normalizeMimeType as o}from"../../../../utils.js";import{addIndentation as y,buildUrlExpression as g,printUrlVariablesDeclarations as v}from"../../helpers/code-helpers.js";import{Lang as c}from"../../helpers/constants.js";import{MediaTypes as n}from"../../../../../constants.js";import{buildJavaDeviceAuthorizationCodeSnippet as C}from"../../helpers/device-auth-snippets.js";const r=t=>!!(t.uriObj.query&&Object.keys(t.uriObj.query).length),h=t=>t.postData&&t.postData.mimeType===n.URL_ENCODED?"HttpRequest.BodyPublishers.ofString(form)":t.postData?"HttpRequest.BodyPublishers.ofString(payload)":["POST","PUT","PATCH"].includes(t.method.toUpperCase())?'HttpRequest.BodyPublishers.ofString("some body text")':"",j=function(t,s,{target:u,client:m}){const p=Object.assign({indent:" ",withWrapper:!0},s),a=new f({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:c.JAVA});if(p.withComments&&k(a,t),p.withImports&&O(a,t),p.withWrapper&&(a.push("public class App {"),a.push(1,"public static void main(String[] args) throws Exception {"),a.push(2,"var httpClient = HttpClient.newBuilder().build();"),a.blank()),t.securityOAuth2ExtraCalls?.length){const e=t.securityOAuth2ExtraCalls?.[0],i=new b(e).convert(u,m,{...p,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});a.push(i),a.blank(),a.push(2,"var oauth2Response = httpClient.send(oauth2Request, HttpResponse.BodyHandlers.ofString());"),e.flowType==="deviceAuthorization"?C(a,{tokenUrl:e.tokenUrl??"YOUR_TOKEN_URL",clientId:e.clientId??"YOUR_CLIENT_ID",level:2}):(a.push(2,'var accessToken = new JSONObject(oauth2Response.body()).getString("access_token");'),a.blank())}if(t.postData)switch(o(t.postData.mimeType)){case n.URL_ENCODED:t.postData.params&&(a.push(2,"HashMap<String, String> params = new HashMap<>();"),t.postData.params.forEach(e=>{a.push(2,'params.put("%s", "%s");',e.name,e.value)}),a.blank(),a.push(2,"var form = params.keySet().stream()"),a.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),a.push(3,'.collect(Collectors.joining("&"));'),a.blank());break;case n.JSON:t.postData.jsonObj&&(a.push(2,`var payload = String.join("\\n"
|
|
2
|
+
${y(JSON.stringify(t.postData.jsonObj,null,1).replace(/"/g,'\\"').replace(/^/gm,', "').replace(/$/gm,'"'),{level:3,indent:p.indent,firstLine:!1})}`),a.push(2,");"),a.blank());break;case n.XML:t.postData.text&&(a.push(2,'var payload = String.join("\\n"'),t.postData.text.trim().split(`
|
|
3
|
+
`).forEach(e=>{const i=e.replace(/"/g,'\\"');a.push(3,`"${i}", `)}),a.push(2,");"),a.blank());break;case n.MULTIPART:t.postData.params&&(a.push(2,"var multipartBody = MultipartBodyPublisher.newBuilder();"),t.postData.params&&t.postData.params.forEach(e=>{a.push(2,'multipartBody.append("%s", "%s");',e.name,e.value)}),a.push(2,"var body = multipartBody.build();"),a.blank());break}if(r(t)){a.push(2,"HashMap<String, String> params = new HashMap<>();");for(const[e,i]of Object.entries(t.uriObj.query))a.push(2,'params.put("%s", "%s");',e,i);a.blank(),a.push(2,"var query = params.keySet().stream()"),a.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),a.push(3,'.collect(Collectors.joining("&"));'),a.blank()}a.push(2,`var ${a.var("host")} = "%s";`,t.uriObj.protocol+"//"+t.uriObj.host),v(t,a,2);const d={...t,pathname:t.uriObj.pathname};a.push(2,`var ${a.var("pathname")} = %s;`,g(d,a)),a.push(2,`var ${a.var("request")} = HttpRequest.newBuilder()`),t.method.toUpperCase()==="PATCH"?a.push(3,'.method("PATCH", %s)',h(t)):a.push(3,".%s(%s)",t.method.toUpperCase(),h(t)),a.push(3,`.uri(URI.create(${a.var("host")} + ${a.var("pathname")} %s))`,r(t)?"+ '?' + query":""),t.securityOAuth2ExtraCalls?.length&&(t.allHeaders.Authorization='"Bearer " + accessToken');const l=Object.keys(t.allHeaders);if(l.length&&l.forEach(e=>{a.push(3,'.header("%s", %s)',e,e==="Authorization"&&t.securityOAuth2ExtraCalls?.length?t.allHeaders[e]:`"${t.allHeaders[e]}"`)}),t.basicAuth){const{username:e,password:i}=t.basicAuth;a.push(3,`.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(("${e}:${i}").getBytes()))`)}return a.push(3,".build();"),p.withWrapper&&(a.blank(),a.push(2,"var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());"),a.blank(),a.push(2,"System.out.println(response.body());"),a.push(1,"}"),a.push("}")),a.join()},U={key:"httpclient",title:"HttpClient",link:"https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html",description:"HttpClient (Java SE 11 & JDK 11 )"};var w=j;function k(t,s){t.push("/**"),t.push(" * Requires JDK >= 11"),s.securityOAuth2ExtraCalls?.length&&(t.push(" *"),t.push(' * Requires package "org.json" >= 20201115'),t.push(" * See here for installation details:"),t.push(" * https://search.maven.org/artifact/org.json/json")),t.push(" */"),t.blank()}function O(t,s){t.push("import java.net.*;"),t.push("import java.net.http.*;"),t.push("import java.util.*;"),(o(s.postData?.mimeType)===n.URL_ENCODED&&s.postData?.params||s.securityOAuth2ExtraCalls?.length||r(s))&&(t.push("import java.nio.charset.StandardCharsets;"),t.push("import java.util.stream.Collectors;")),s.securityOAuth2ExtraCalls?.length&&t.push("import org.json.JSONObject;"),t.blank()}export{w as default,U as info};
|