@redocly/framework 1.0.0-next.3 → 1.0.0-next.5
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/client/app.js +1 -1
- package/dist/client/webmcp/tools/shared.js +1 -1
- package/dist/content-layer/markdown/resolve/ast.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/partial.js +1 -1
- package/dist/content-layer/markdown/service.js +1 -1
- package/dist/content-layer/markdown/tags/partial.d.ts +7 -2
- package/dist/content-layer/markdown/tags/partial.js +1 -1
- package/dist/content-layer/markdown/types/service.d.ts +2 -0
- package/dist/content-layer/markdown/utils/reparse-example-fences.d.ts +4 -1
- package/dist/content-layer/markdown/utils/reparse-example-fences.js +1 -1
- package/dist/content-layer/markdown/utils/substitute-variables.js +1 -1
- package/dist/content-layer/markdown/utils/walk-markdoc-ast.d.ts +2 -2
- package/dist/content-layer/markdown/utils/walk-markdoc-ast.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/rebase-item-links.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/execute-schema.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +4 -3
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/allowed-hosts.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-bridge.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-errors.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/ssrf-guard.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/gateway/upstream-auth-scheme.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/rate-limit.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/index.js +1 -1
- package/dist/server/app.js +3 -3
- package/dist/server/content.js +9 -9
- package/dist/server/lambda-entry.js +1 -1
- package/dist/server/llms-txt.js +1 -1
- package/dist/server/node-entry.js +1 -1
- package/dist/server/public-url.js +1 -0
- package/dist/server/search/cache.js +1 -0
- package/dist/server/search/route.js +1 -1
- package/dist/shared/constants/l10n/langs/ar.js +1 -1
- package/dist/shared/constants/l10n/langs/de.js +1 -1
- package/dist/shared/constants/l10n/langs/en.js +1 -1
- package/dist/shared/constants/l10n/langs/es.js +1 -1
- package/dist/shared/constants/l10n/langs/fr.js +1 -1
- package/dist/shared/constants/l10n/langs/hi.js +1 -1
- package/dist/shared/constants/l10n/langs/it.js +1 -1
- package/dist/shared/constants/l10n/langs/ja.js +1 -1
- package/dist/shared/constants/l10n/langs/ko.js +1 -1
- package/dist/shared/constants/l10n/langs/pl.js +1 -1
- package/dist/shared/constants/l10n/langs/pt-br.js +1 -1
- package/dist/shared/constants/l10n/langs/pt.js +1 -1
- package/dist/shared/constants/l10n/langs/ru.js +1 -1
- package/dist/shared/constants/l10n/langs/uk.js +1 -1
- package/dist/shared/constants/l10n/langs/zh.js +1 -1
- package/dist/shared/utils/routes/markdown-copy-url.js +1 -0
- package/package.json +4 -4
- package/dist/shared/utils/routes/markdown-path.js +0 -1
package/dist/client/app.js
CHANGED
|
@@ -3,7 +3,7 @@ import{isObject as e}from"../shared/utils/is-object.js";import"../shared/constan
|
|
|
3
3
|
[id]:has([data-deep-link-anchor]) {
|
|
4
4
|
scroll-margin-top: var(--navbar-offset);
|
|
5
5
|
}
|
|
6
|
-
`,U=()=>void 0,Et=async()=>void 0;function W(e){return N(c)?.[e]}function Dt(e){return W(e)}function Ot(e){return Object.fromEntries(Object.keys(e?.loaderData??{}).map(e=>[e,e]))}function kt(e){return e?{isPublic:e.isPublic??!0,metadata:e.metadata??{},path:e.path,sharedDataIds:Ot(e),slug:e.slug,status:e.status,template:e.template,title:e.title}:null}function At(e,t){if(!e)return{};let n=e.metadata??{};return{frontmatter:t?{...n,...t.frontmatter}:n,metadata:{markdoc:{tagList:[]},...n},variables:{rbac:{teams:[...e.auth?.userInfo?.teams??[]]}},path:e.path,sharedDataIds:Ot(e),slug:e.slug,status:e.status,template:e.template,title:e.title,...e.isTranslationFallback?{isTranslationFallback:!0}:{}}}function jt(e,t){let n=At(e,t);return t?{...n,headings:oe(t.ast),editPage:t.editPage,lastModified:t.lastModified}:n}function Mt(){return kt(N(l))}function Nt(){return At(N(l),ae(N(c)))}function Pt(e){return W(e)}function G(e){return e.type!==`separator`&&e.external!==!0&&typeof e.link==`string`&&e.link!==``}function Ft(e,t=[]){for(let n of e??[])t.push(n),Ft(n.items,t);return t}function It(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let t of Ft(e)){if(!G(t))continue;let e=g(t.link);n.has(e)||(n.add(e),r.push(t))}let i=g(t),a=r.findIndex(e=>g(e.link)===i);if(a!==-1)return{prevPage:Lt(r[a-1]),nextPage:Lt(r[a+1])}}function Lt(e){return e?{type:`link`,label:e.label??``,link:e.link}:void 0}const K={breadcrumbs:[],currentItemSiblings:void 0};function Rt(e,t,n,r=[]){if(n?.hide===!0)return K;let i=g(t),a=Bt(e,i)?.filter(zt);if(a===void 0||a.length===0)return K;let o=new Set(a.map(e=>e.link&&g(e.link))),s=[...n?.prefixItems??[],...r.filter(e=>!o.has(g(e.link))).map(({label:e,icon:t,link:n})=>({label:e,icon:t,link:n})),...a.map((e,t)=>({label:e.label,labelTranslationKey:e.labelTranslationKey,icon:e.icon,link:t===a.length-1?void 0:e.link}))];return s.length<2?K:{breadcrumbs:s,currentItemSiblings:Vt(a.at(-2),i)}}function zt(e){return typeof e.label==`string`&&e.label!==``}function Bt(e,t){for(let n of e??[]){let e=G(n)&&g(n.link)===t,r=Bt(n.items,t);if(r)return e?[n]:[n,...r];if(e)return[n]}}function Vt(e,t){let n=[];for(let r of e?.items??[])G(r)&&zt(r)&&g(r.link)!==t&&n.push({label:r.label,labelTranslationKey:r.labelTranslationKey,link:r.link,icon:r.icon});return n}function Ht(){let e=N(l),t=N(s),n=N(u),r=N(c),i=L(),o=ut(i),f=k(e),{activeSlug:p,items:m}=pe({items:n.items,activeVersion:f,sectionSlug:o?he(o,e?.slug):null,pageSlug:me(e,i.pathname)}),[h,g]=I(()=>fe(m)),[_,ee]=I({sidebarData:n,activeSlug:p}),[v,y]=I(),[x,te]=I(!1),{translate:S}=ne(),C=n.backLink;P(()=>{if(!v)return;let e=setTimeout(()=>y(void 0),Ut);return()=>clearTimeout(e)},[v]),(_.sidebarData!==n||_.activeSlug!==p)&&(ee({sidebarData:n,activeSlug:p}),g(fe(m)));let w=F(null),T=F(!1);P(()=>{T.current&&(T.current=!1,requestAnimationFrame(()=>w.current?.focus()))},[h]);let{versionPicker:E}=V(),D=!E?.hide&&be(r),ie=!E?.hide&&E?.showForUnversioned===!0&&!f.name;if(m.length===0&&!D)return null;let O=h[h.length-1];return/* @__PURE__ */ z(mt,{collapsed:x,versions:D?/* @__PURE__ */ z(wt,{pageVersion:f.name}):ie?/* @__PURE__ */ z(re,{}):null,menuItemsAnimation:v,footer:/* @__PURE__ */ B(ve,{$collapsed:x,children:[d(r).removeAttribution===!1&&!x&&/* @__PURE__ */ z(_e,{}),/* @__PURE__ */ z(ht,{collapsedSidebar:x,isApiDocs:e?.template===a,layout:t.layout,onChangeCollapseSidebarClick:()=>te(e=>!e),onChangeViewClick:t.toggle})]}),header:O?/* @__PURE__ */ z(Wt,{"data-component-name":`Sidebar/BackButton`,icon:/* @__PURE__ */ z(ft,{}),iconPosition:`left`,onClick:()=>{y(`slideInLeft`),g(h.slice(0,-1)),b.sendSidebarDrilldownBackClickedMessage([nt(`sidebarDrilldownBack`,`button`)])},ref:w,size:`medium`,variant:`ghost`,children:x?``:`Back`}):C?/* @__PURE__ */ z(Wt,{"data-component-name":`Sidebar/BackButton`,icon:/* @__PURE__ */ z(ft,{}),iconPosition:`left`,size:`medium`,to:C.link,variant:`ghost`,children:x?``:S(`sidebar.menu.backToLabel`,{value:C.label})}):void 0,menu:/* @__PURE__ */ z(pt,{items:O?de(O,p):m,onDrilldownOpen:e=>{T.current=!0,y(`slideInRight`),g([...h,e])}})},n.key)}const Ut=350,Wt=it(dt)`
|
|
6
|
+
`,U=()=>void 0,Et=async()=>void 0;function W(e){return N(c)?.[e]}function Dt(e){return W(e)}function Ot(e){return Object.fromEntries(Object.keys(e?.loaderData??{}).map(e=>[e,e]))}function kt(e){return e?{isPublic:e.isPublic??!0,metadata:e.metadata??{},path:e.path,sharedDataIds:Ot(e),slug:e.slug,status:e.status,template:e.template,title:e.title}:null}function At(e,t){if(!e)return{};let n=e.metadata??{};return{frontmatter:t?{...n,...t.frontmatter}:n,metadata:{markdoc:{tagList:[]},...n},variables:{rbac:{teams:[...e.auth?.userInfo?.teams??[]]}},path:e.path,sharedDataIds:Ot(e),slug:e.slug,status:e.status,template:e.template,title:e.title,...e.isTranslationFallback?{isTranslationFallback:!0}:{},...e.markdownUrl?{markdownUrl:e.markdownUrl}:{}}}function jt(e,t){let n=At(e,t);return t?{...n,headings:oe(t.ast),editPage:t.editPage,lastModified:t.lastModified}:n}function Mt(){return kt(N(l))}function Nt(){return At(N(l),ae(N(c)))}function Pt(e){return W(e)}function G(e){return e.type!==`separator`&&e.external!==!0&&typeof e.link==`string`&&e.link!==``}function Ft(e,t=[]){for(let n of e??[])t.push(n),Ft(n.items,t);return t}function It(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let t of Ft(e)){if(!G(t))continue;let e=g(t.link);n.has(e)||(n.add(e),r.push(t))}let i=g(t),a=r.findIndex(e=>g(e.link)===i);if(a!==-1)return{prevPage:Lt(r[a-1]),nextPage:Lt(r[a+1])}}function Lt(e){return e?{type:`link`,label:e.label??``,link:e.link}:void 0}const K={breadcrumbs:[],currentItemSiblings:void 0};function Rt(e,t,n,r=[]){if(n?.hide===!0)return K;let i=g(t),a=Bt(e,i)?.filter(zt);if(a===void 0||a.length===0)return K;let o=new Set(a.map(e=>e.link&&g(e.link))),s=[...n?.prefixItems??[],...r.filter(e=>!o.has(g(e.link))).map(({label:e,icon:t,link:n})=>({label:e,icon:t,link:n})),...a.map((e,t)=>({label:e.label,labelTranslationKey:e.labelTranslationKey,icon:e.icon,link:t===a.length-1?void 0:e.link}))];return s.length<2?K:{breadcrumbs:s,currentItemSiblings:Vt(a.at(-2),i)}}function zt(e){return typeof e.label==`string`&&e.label!==``}function Bt(e,t){for(let n of e??[]){let e=G(n)&&g(n.link)===t,r=Bt(n.items,t);if(r)return e?[n]:[n,...r];if(e)return[n]}}function Vt(e,t){let n=[];for(let r of e?.items??[])G(r)&&zt(r)&&g(r.link)!==t&&n.push({label:r.label,labelTranslationKey:r.labelTranslationKey,link:r.link,icon:r.icon});return n}function Ht(){let e=N(l),t=N(s),n=N(u),r=N(c),i=L(),o=ut(i),f=k(e),{activeSlug:p,items:m}=pe({items:n.items,activeVersion:f,sectionSlug:o?he(o,e?.slug):null,pageSlug:me(e,i.pathname)}),[h,g]=I(()=>fe(m)),[_,ee]=I({sidebarData:n,activeSlug:p}),[v,y]=I(),[x,te]=I(!1),{translate:S}=ne(),C=n.backLink;P(()=>{if(!v)return;let e=setTimeout(()=>y(void 0),Ut);return()=>clearTimeout(e)},[v]),(_.sidebarData!==n||_.activeSlug!==p)&&(ee({sidebarData:n,activeSlug:p}),g(fe(m)));let w=F(null),T=F(!1);P(()=>{T.current&&(T.current=!1,requestAnimationFrame(()=>w.current?.focus()))},[h]);let{versionPicker:E}=V(),D=!E?.hide&&be(r),ie=!E?.hide&&E?.showForUnversioned===!0&&!f.name;if(m.length===0&&!D)return null;let O=h[h.length-1];return/* @__PURE__ */ z(mt,{collapsed:x,versions:D?/* @__PURE__ */ z(wt,{pageVersion:f.name}):ie?/* @__PURE__ */ z(re,{}):null,menuItemsAnimation:v,footer:/* @__PURE__ */ B(ve,{$collapsed:x,children:[d(r).removeAttribution===!1&&!x&&/* @__PURE__ */ z(_e,{}),/* @__PURE__ */ z(ht,{collapsedSidebar:x,isApiDocs:e?.template===a,layout:t.layout,onChangeCollapseSidebarClick:()=>te(e=>!e),onChangeViewClick:t.toggle})]}),header:O?/* @__PURE__ */ z(Wt,{"data-component-name":`Sidebar/BackButton`,icon:/* @__PURE__ */ z(ft,{}),iconPosition:`left`,onClick:()=>{y(`slideInLeft`),g(h.slice(0,-1)),b.sendSidebarDrilldownBackClickedMessage([nt(`sidebarDrilldownBack`,`button`)])},ref:w,size:`medium`,variant:`ghost`,children:x?``:`Back`}):C?/* @__PURE__ */ z(Wt,{"data-component-name":`Sidebar/BackButton`,icon:/* @__PURE__ */ z(ft,{}),iconPosition:`left`,size:`medium`,to:C.link,variant:`ghost`,children:x?``:S(`sidebar.menu.backToLabel`,{value:C.label})}):void 0,menu:/* @__PURE__ */ z(pt,{items:O?de(O,p):m,onDrilldownOpen:e=>{T.current=!0,y(`slideInRight`),g([...h,e])}})},n.key)}const Ut=350,Wt=it(dt)`
|
|
7
7
|
padding: var(--menu-item-padding-vertical) 0;
|
|
8
8
|
height: calc(var(--line-height-base) + var(--menu-item-padding-vertical) * 2);
|
|
9
9
|
justify-content: flex-start;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeRouteSlug as e}from"../../../shared/utils/routes/normalize-route-slug.js";import{splitUrlSuffix as t}from"../../../shared/utils/routes/split-url-suffix.js";import{stripPathPrefix as n}from"../../../shared/path-prefix.js";import{
|
|
1
|
+
import{normalizeRouteSlug as e}from"../../../shared/utils/routes/normalize-route-slug.js";import{splitUrlSuffix as t}from"../../../shared/utils/routes/split-url-suffix.js";import{stripPathPrefix as n}from"../../../shared/path-prefix.js";import{markdownCopyUrl as r}from"../../../shared/utils/routes/markdown-copy-url.js";function i(i){let{path:a}=t(i);return r(e(n(a)??a))}const a=`https://site.invalid`;function o(e){let t=e.trim();if(!t.startsWith(`/`))return;let n=URL.parse(t,a);if(n?.origin===a)return`${n.pathname}${n.search}${n.hash}`}async function s(e){let t=await fetch(e,{headers:{accept:`text/plain`}});if(t.ok&&!t.headers.get(`content-type`)?.startsWith(`text/html`))return await t.text()}function c(e,t,n){let r=typeof e==`number`?e:Number(e);return!Number.isFinite(r)||r<=0?t:Math.min(Math.floor(r),n)}export{c as clampLimit,s as fetchText,i as markdownPathForRoute,o as toSitePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isObject as e}from"../../../shared/utils/is-object.js";import{markdocNodeRange as t}from"../utils/node-source-range.js";import{PARTIAL_L10N_ATTRIBUTE as n}from"../tags/partial.js";import{builtInMarkdocTags as r}from"../constants/builtin-tags.js";import{walkMarkdocAst as i}from"../utils/walk-markdoc-ast.js";import{getExampleContent as a,walkWithExampleContent as o}from"../utils/reparse-example-fences.js";import{parseMarkdownDocument as s}from"../utils/parse-cache.js";import{substituteStaticVariables as c}from"../utils/substitute-variables.js";import{collectMarkdocTagNames as l,isPromptTag as u,resolveMarkdocBuildTimeAttributes as d}from"./markdoc.js";import{inlineRawPartials as f}from"./raw-partials.js";import{renderMarkdocDiagrams as p}from"./render-diagrams.js";import m from"@redocly/markdoc";const h=/* @__PURE__ */ new Set([`parse-error`,`missing-opening`,`missing-closing`,`fence-tag-error`,`no-inline-annotations`]);async function g(e,t,n){let i=await f(e,t,n.resolverContext),a=s(i.source),o=n.validation?x(a,t,v(n.validation)):[],{entityDeps:u,assetUsages:h,linkRefs:g,problems:_}=await d(a,{tags:n.tags??r,sourceFilePath:t,resolverContext:n.resolverContext,source:i.source});n.variables&&c(a,n.variables);let y=await p(a,t,n.resolverContext.logger),b=w(a,t),S=n.transform?.(a)??[];return C(a),{ast:m.compact(a),entityDeps:[...i.entityDeps,...u],assetUsages:h,linkRefs:g,tagList:l(a),problems:[...i.problems,..._,...b,...o,...S,...y]}}const _=/* @__PURE__ */ new WeakMap;function v(e){let t=_.get(e);return t===void 0&&(t=m.prepareConfig({...e,tags:y(e.tags),nodes:y(e.nodes)}),_.set(e,t)),t}function y(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).map(([e,t])=>{let{validate:n}=t;return n===void 0?[e,t]:[e,{...t,validate(e,t){try{return n.call(this,e,t)}catch(t){return[{id:`validate-failed`,level:`error`,message:`The validate() of '${e.tag??e.type}' failed: ${b(t)}`}]}}}]}))}const b=e=>e instanceof Error?e.message:String(e);function x(e,t,n){let r=[e],i=/* @__PURE__ */ new Set,s=[];for(let t of o(e,u)){for(let e of t.errors??[])i.add(e);let e=a(t);e&&r.push(e),u(t)&&s.push({node:t,children:t.children})}for(let e of s)e.node.children=[];try{return r.flatMap(e=>m.validate(e,n)).filter(e=>!i.has(e.error)).map(e=>S(e,t))}catch(e){return[{code:`markdoc/validation-error`,message:`Markdoc validation failed: ${b(e)}`,location:{filePath:t,range:{start:{line:1},end:{line:1}}}}]}finally{for(let e of s)e.node.children=e.children}}function S(e,n){let{level:r,message:i}=e.error,a={code:`markdoc/validation-error`,message:i,location:{filePath:n,range:t(e)??{start:{line:1},end:{line:1}}}};return r!==`error`&&r!==`critical`&&(a.severity=`warning`),a}function C(t){for(let r of i(t)){let t=r.tag===`partial`?r.attributes[n]:void 0;e(t)&&(r.attributes[n]=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,m.compact(t)])))}}function w(e,n){let r=[];for(let i of o(e))for(let e of i.errors){let a=h.has(e.id)?`markdoc/parse-error`:`markdoc/validation-error`;r.push({code:a,message:e.message,location:{filePath:n,range:t(i)??{start:{line:1},end:{line:1}}}})}return r}export{g as resolveMarkdownAst};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{L10N_DIR as e}from"../../../../shared/constants/l10n/defaults.js";import{delocalizeL10nPath as t,l10nDirOf as n}from"../../../../shared/utils/l10n.js";import{markdocErrorResult as r,replaceWithMarkdocError as i}from"../../tags/markdoc-error.js";import{PARTIAL_L10N_ATTRIBUTE as a}from"../../tags/partial.js";import{shiftRange as o}from"../../../../shared/utils/shift-range.js";import{inlinedLinkRefs as s}from"../../../link-checker/node-ref.js";import{resolveResolverTarget as c}from"./context-paths.js";import{getPartialsFolders as l,isPartialPath as u}from"../../utils/partials.js";import{FRONTMATTER_BLOCK_RE as d,computeFrontmatterLineOffset as f}from"../../utils/frontmatter-offset.js";import{substituteStaticVariables as p}from"../../utils/substitute-variables.js";import{resolveMarkdocBuildTimeAttributes as m}from"../markdoc.js";import{join as h}from"node:path";async function g(o){let{node:s,attributeName:d}=o,f=s.attributes[d];if(typeof f!=`string`||f===``||o.io===void 0)return null;let p=c(o,f);if(p===null)return null;if(!u(p.contentPath,o.config)){let e=`Partial ${p.contentPath} must live in a partials folder (markdown.partialsFolders: ${l(o.config).join(`, `)})`;return r(s,e,o.sourceFilePath)}let m=n(o.sourceFilePath),g=[],v=m!==void 0&&n(p.contentPath)===void 0?`${e}/${m}/${p.contentPath}`:p.contentPath;if(!await o.io.exists(h(o.contentDir,v))){g.push({kind:`file`,path:v});let e=t(v);if(e!==void 0&&g.push({kind:`file`,path:e}),e===void 0||!await o.io.exists(h(o.contentDir,e))){let e=`Partial file ${p.contentPath} does not exist`;return r(s,e,o.sourceFilePath,g)}v=e}let y=o.partialChain??[o.sourceFilePath];if(y.includes(v))return i(s,`Circular partial inclusion: ${[...y,v].join(` -> `)}`),{entityDeps:[{kind:`file`,path:v}]};let b=await o.io.readFile(h(o.contentDir,v)),x=await _(o,v,b,y);s.children=x.ast.children;let S=[{entityDeps:g},x.result];if(m===void 0&&n(p.contentPath)===void 0){let t={};for(let n of o.markdown.contentLocales){let r=`${e}/${n}/${p.contentPath}`,i=h(o.contentDir,r);if(!await o.io.exists(i)){S.push({entityDeps:[{kind:`file`,path:r}]});continue}let a=await _(o,r,await o.io.readFile(i),y);t[n]=a.ast,S.push(a.result)}Object.keys(t).length>0&&(s.attributes[a]=t)}return{entityDeps:S.flatMap(e=>e.entityDeps??[]),assetUsages:S.flatMap(e=>e.assetUsages??[]),linkRefs:S.flatMap(e=>e.linkRefs??[]),problems:S.flatMap(e=>e.problems??[])}}async function _(e,t,n,r){let i=n.replace(d,``),a=structuredClone(e.markdown.parseCached(i)),o=await m(a,{tags:e.tags,sourceFilePath:t,resolverContext:{config:e.config,contentDir:e.contentDir,entities:e.entities,file:e.file,io:e.io,logger:e.logger,markdown:e.markdown,plugin:e.plugin},partialChain:[...r,t],source:i}),c=e.node.attributes.variables;typeof c==`object`&&c&&!Array.isArray(c)&&p(a,c);let l=f(n);return{ast:a,result:{entityDeps:[{kind:`file`,path:t},...o.entityDeps],assetUsages:o.assetUsages,linkRefs:s(o.linkRefs,t,l),problems:o.problems.map(e=>v(e,l))}}}function v(e,t){if(t===0||e.location?.range===void 0)return e;let n={...e.location,range:o(e.location.range,t)};return{...e,location:n}}export{g as resolvePartialFileAttribute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseMarkdownCached as e}from"./utils/parse-cache.js";import{looksLikeMarkdown as t,resolveImageReference as n,resolveImageSrcSet as r,resolveLocalReference as i}from"./resolve/references.js";function a(a){return{disabledTags:a.disabledTags??/* @__PURE__ */ new Set,looksLikeMarkdown:t,parseCached:e,resolveLocalReference:(e,t,n)=>i(e,t,a.state,a.resolveAudienceTag,a.contentLocales,n),resolveImageReference:(e,t)=>n(e,t,a.state,a.resolveAudienceTag,a.contentLocales),resolveImageSrcSet:(e,t)=>r(e,t,a.state,a.resolveAudienceTag,a.contentLocales)}}export{a as createMarkdownService};
|
|
1
|
+
import{parseMarkdownCached as e}from"./utils/parse-cache.js";import{looksLikeMarkdown as t,resolveImageReference as n,resolveImageSrcSet as r,resolveLocalReference as i}from"./resolve/references.js";function a(a){return{disabledTags:a.disabledTags??/* @__PURE__ */ new Set,contentLocales:a.contentLocales??[],looksLikeMarkdown:t,parseCached:e,resolveLocalReference:(e,t,n)=>i(e,t,a.state,a.resolveAudienceTag,a.contentLocales,n),resolveImageReference:(e,t)=>n(e,t,a.state,a.resolveAudienceTag,a.contentLocales),resolveImageSrcSet:(e,t)=>r(e,t,a.state,a.resolveAudienceTag,a.contentLocales)}}export{a as createMarkdownService};
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import type { Schema } from '@redocly/markdoc';
|
|
1
|
+
import type { Node, Schema } from '@redocly/markdoc';
|
|
2
|
+
/** The resolved `@l10n/<locale>/` twins of a root page's partial, by locale. */
|
|
3
|
+
export declare const PARTIAL_L10N_ATTRIBUTE = "l10n";
|
|
4
|
+
/** The resolved locale twins a `partial` tag carries; none for any other node. */
|
|
5
|
+
export declare function getPartialTwins(node: Node): Node[];
|
|
2
6
|
/**
|
|
3
7
|
* Build-time-inlined partial: the `partialFile` resolver reads the file, inlines
|
|
4
8
|
* its resolved AST as children, and substitutes the static `variables` map. As in
|
|
5
|
-
* Markdoc's own `partial` tag, the children render with `variables` in scope.
|
|
9
|
+
* Markdoc's own `partial` tag, the children render with `variables` in scope. A page
|
|
10
|
+
* of a locale (`$lang`) renders the partial's twin in that locale instead, when it has one.
|
|
6
11
|
*/
|
|
7
12
|
export declare const partial: Schema;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject as e}from"../../../shared/utils/is-object.js";const t={selfClosing:!0,attributes:{file:{type:String,required:!0,render:!1,buildTimeResolver:`partialFile`},variables:{type:Object,render:!1}},transform(
|
|
1
|
+
import{isObject as e}from"../../../shared/utils/is-object.js";const t=`l10n`;function n(n){let r=n.tag===`partial`?n.attributes[t]:void 0;return e(r)?Object.values(r):[]}const r={selfClosing:!0,attributes:{file:{type:String,required:!0,render:!1,buildTimeResolver:`partialFile`},variables:{type:Object,render:!1}},transform(n,r){let i=n.attributes[t],a=r.variables?.lang,o=typeof a==`string`&&i?.[a]||n,s=n.attributes.variables;return e(s)?o.transformChildren({...r,variables:{...r.variables,...s}}):o.transformChildren(r)}};export{t as PARTIAL_L10N_ATTRIBUTE,n as getPartialTwins,r as partial};
|
|
@@ -3,6 +3,8 @@ import type { ReferenceResolution, ResolveImageSrcSetResult } from '../resolve/r
|
|
|
3
3
|
export type MarkdownService = {
|
|
4
4
|
/** Engine-internal gate (empty until R11): a listed tag resolves to an error node. */
|
|
5
5
|
disabledTags: ReadonlySet<string>;
|
|
6
|
+
/** Content locales whose `@l10n/<locale>/` twins a root source reports. */
|
|
7
|
+
contentLocales: readonly string[];
|
|
6
8
|
looksLikeMarkdown(value: string): boolean;
|
|
7
9
|
parseCached(rawSource: string): ParsedMarkdown;
|
|
8
10
|
/** `includingPagePath`: the page a partial source is inlined into. */
|
|
@@ -8,6 +8,9 @@ type ParseMarkdownFn = (content: string) => MarkdocNode;
|
|
|
8
8
|
export declare function reparseExampleFences(ast: MarkdocNode, source: string, parseMarkdown: ParseMarkdownFn): void;
|
|
9
9
|
/** The parsed body of a `{% markdoc-example %}` tag; `undefined` for any other node. */
|
|
10
10
|
export declare function getExampleContent(node: MarkdocNode): MarkdocNode | undefined;
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Every node of `ast`, of the example bodies in it and of the locale twins of its partials,
|
|
13
|
+
* nested ones included, in one walk.
|
|
14
|
+
*/
|
|
12
15
|
export declare function walkWithExampleContent(ast: MarkdocNode, skipChildren?: WalkMarkdocAstOptions['skipChildren']): Generator<MarkdocNode>;
|
|
13
16
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{getPartialTwins as e}from"../tags/partial.js";import{walkMarkdocAst as t}from"./walk-markdoc-ast.js";import{EXAMPLE_CONTENT_ATTRIBUTE as n,MARKDOC_EXAMPLE_TAG as r}from"@redocly/theme/core/constants";function i(e,t,a){if(t.includes(r))for(let t of s(e)){if(!t.children.length)continue;let{content:e}=t.attributes;if(typeof e!=`string`)continue;let r=a(e),o=(t.location?.start.line??0)+1;for(let e of r.children)l(e,o);t.children=[],t.slots={},t.errors=t.errors.filter(e=>e.id!==`no-inline-annotations`),t.attributes[n]=r,i(r,e,a)}}function a(e){return c(e)?.attributes[n]}function o(n,r){return t(n,{getExtraNodes:t=>{let n=a(t);return n?[n]:e(t)},skipChildren:r})}function*s(e){for(let n of t(e)){let e=c(n);e&&(yield e)}}function c(e){if(e.type!==`tag`||e.tag!==r)return;let[t]=e.children;return t?.type===`fence`?t:void 0}function l(e,n){for(let r of t(e)){let{location:e}=r;e&&(typeof e.start?.line==`number`&&(e.start.line+=n),typeof e.end?.line==`number`&&(e.end.line+=n))}}export{a as getExampleContent,i as reparseExampleFences,o as walkWithExampleContent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{getPartialTwins as e}from"../tags/partial.js";function t(t,r){let i=t=>{t.attributes=n(t.attributes,r);for(let e of t.children)i(e);for(let e of Object.values(t.slots??{}))i(e);for(let n of e(t))i(n)};i(t)}function n(e,t){if(Array.isArray(e))return e.map(e=>n(e,t));if(typeof e!=`object`||!e)return e;let r=e;if(r.$$mdtype===`Variable`&&Array.isArray(r.path)){let[n,...i]=r.path;if(typeof n==`string`&&n in t){let e=t[n];for(let t of i){if(typeof e!=`object`||!e)return;e=e[t]}return e}return e}if(r.$$mdtype===`Function`){let r=e;return r.parameters&&=n(r.parameters,t),e}if(r.$$mdtype!==void 0)return e;let i={};for(let[r,a]of Object.entries(e))i[r]=n(a,t);return i}export{t as substituteStaticVariables};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Node as MarkdocNode } from '@redocly/markdoc';
|
|
2
2
|
export type WalkMarkdocAstOptions = {
|
|
3
|
-
/** Returns
|
|
4
|
-
|
|
3
|
+
/** Returns more trees to walk under a node, before its children. */
|
|
4
|
+
getExtraNodes?: (node: MarkdocNode) => readonly MarkdocNode[];
|
|
5
5
|
/** A node for which this returns `true` is yielded, but nothing under it is walked. */
|
|
6
6
|
skipChildren?: (node: MarkdocNode) => boolean;
|
|
7
7
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function*e(n,r={}){if(yield n,r.skipChildren?.(n))return;let
|
|
1
|
+
function*e(n,r={}){if(yield n,r.skipChildren?.(n))return;for(let t of r.getExtraNodes?.(n)??[])yield*e(t,r);for(let i of n.children)t(i)&&(yield*e(i,r));let i=n.slots??{};for(let n of Object.values(i))t(n)&&(yield*e(n,r))}function t(e){return typeof e==`object`&&!!e&&`type`in e&&`children`in e}export{e as walkMarkdocAst};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ITEM_ROUTE_PATH_KEYS as e}from"@redocly/api-docs/lib/utils/previous-route-slug.js";
|
|
1
|
+
import{ITEM_ROUTE_PATH_KEYS as e}from"@redocly/api-docs/lib/utils/previous-route-slug.js";function t(t,n,r){let i=n===`/`?`/`:`${n}/`,a=r===`/`?``:r,o=e=>e===n?r:e.startsWith(i)?`${a}/${e.slice(i.length)}`:e,s=t=>{if(typeof t!=`object`||!t)return t;let n={...t};for(let t of e){let e=n[t];typeof e==`string`&&(n[t]=o(e))}return Array.isArray(n.items)&&(n.items=n.items.map(s)),n};return t.map(s)}export{t as rebaseItemLinks};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t}from"../../../loaders/define.js";import{runtimeFile as n}from"../../utils/runtime-file.js";import{runtimeTemplate as r}from"../../templates.js";import{SEARCH_API_TITLE_FACET_FIELD as i,SEARCH_API_VERSION_FACET_FIELD as a,SEARCH_GROUP_FACET_FIELD as o}from"../../../../shared/search/facets.js";import{configuredFacetFields as s,extractFacetsFromFrontmatter as c,invalidFacetValueProblems as l,searchCategoryOf as u}from"../../../search/facet-values.js";import{toPosixPath as d}from"../../../../shared/utils/to-posix-path.js";import{TRANSLATIONS_FILE_PATTERN as f}from"../../../../shared/constants/l10n/defaults.js";import{isObject as p}from"../../../../shared/utils/is-object.js";import{notInPlanProblem as m}from"../../../plan-gates.js";import{filePathToRouteSlug as h}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{SPEC_KIND_ARAZZO as g,SPEC_KIND_ASYNCAPI as _,SPEC_KIND_GRAPHQL as v,SPEC_KIND_OPENAPI as y}from"../../types/api-entity.js";import{isPlanFeatureGranted as b}from"../../../../shared/plan-gates.js";import{packMarkdocAstsDeep as x,unpackMarkdocAstsDeep as S}from"../../../markdown/utils/packed-ast.js";import{parseMarkdownCached as C}from"../../../markdown/utils/parse-cache.js";import{createApiEntityKey as w}from"../../utils/api-entity-key.js";import{API_DOCS_API_LOADER_ID as T,API_DOCS_PLUGIN_ID as ee,API_DOCS_RENDER_DEP_KEY as E,API_DOCS_RENDER_LOADER_ID as D,API_DOCS_SIDEBAR_LOADER_ID as te,API_DOCS_TEMPLATE_ID as O,SPEC_DOWNLOAD_ROUTE_PATHS as k,SPEC_PATH_PARAM as ne}from"./server/shared.js";import{resolveApiBundleConfig as re,resolveApiOptions as ie,resolveNestedFeedback as ae,schemaCatalogLink as oe,withDownloadUrls as se,withFeedbackOption as ce,withMockServerOption as le}from"./server/options.js";import{annotateApiDocsRbac as ue}from"../../../../server/rbac/api-docs.js";import{SERVER_ONLY_VALUE_KEY as A}from"../../../loaders/server-only-value.js";import{getLoadedProjectPlugins as de}from"../../project/loaded-set.js";import{API_OUTPUT_MANIFEST_KEY as j}from"../../../api-outputs.js";import{API_DOCS_MARKDOC_TAG_SET as M,resolveMarkdocTagSet as N}from"../../../markdown/constants/tag-sets.js";import{pageLocale as P}from"../../utils/page-locale.js";import{buildBundledApiDefinition as F,resolveLlmsDescriptions as I}from"./server/build-definition.js";import{collectSidebarSubpathTargets as L,toSidebarSubtree as R,toSubpathTarget as z}from"./server/build-sidebar.js";import{buildApiDocsMarkdownDocs as B}from"./server/markdown-docs.js";import{join as V,relative as H}from"node:path";import fe from"@redocly/markdoc";const pe=[`.yaml`,`.yml`,`.json`,`.gql`,`.graphql`],me={[y]:`OpenAPI`,[_]:`AsyncAPI`,[v]:`GraphQL`,[g]:`Arazzo`},U=t(D,async e=>{let{buildItems:t}=await import(`@redocly/api-docs`),n=K(e),r=await e.io.readFile(n.absolutePath),i=e.routes.byFilePath(e.file.path)?.slug,a=se(e.args.options,e.file.path,e.args.kind),o=e.args.kind===`openapi`?le(a,e.config,i):a,s={entityDeps:[],assetUsages:[],linkRefs:[],problems:[],pending:[]},c=G(e.contentDir),l={markdown:e.markdown,loader:{config:e.config,entities:e.entities,file:e.file,io:e.io,logger:e.logger,plugin:e.plugin},sink:s},u=await F({kind:e.args.kind,source:r,relativePath:n.relativePath,contentDir:e.contentDir,pagePath:e.file.path,options:o,bundle:q(e.args,c),metadata:X(e.args.options),markdownResolution:l,rbac:{warn:t=>e.logger?.warn(t)}}),d={...p(u.document)&&p(u.document.info)?{infoDescription:u.document.info.description}:{},...await I(u.document,l,{contentDir:e.contentDir,specPath:n.relativePath,pagePath:e.file.path})};e.args.kind===`openapi`&&o.showSchemaCatalogLinks&&p(u.document)&&(u.document[`x-schema-catalog-link`]=oe(e.file.path)),u.options=ce(u.options,u.document,e.args.feedback??e.config.feedback);let f=i?.toLowerCase()??`/`,{items:m,store:h,specType:g}=await t({...u,basePath:f,markdownParser:e=>fe.compact(C(e))}),_=JSON.stringify({items:x(m),store:x(h),options:u.options,specType:g,basePath:f,title:be(u.document,e.args.kind,m),metadata:ye(u.document),[A]:{llms:d}});return{value:await e.createBlobRef(_,{format:`json`}),entityDeps:[...Y(e.file.path,[...u.fileDependencies,...c.paths]),...s.entityDeps],assetUsages:s.assetUsages,markdoc:{tagSet:M},linkRefs:s.linkRefs,problems:s.problems}},{async searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=S(e),r=await Ee(t.entities,t.route.originFilePath),d={...t.route.metadata,...p(n.metadata)?n.metadata:{}},{category:f,isInvalid:m}=u(d),{facets:h,invalidFields:g}=c({[i]:t.route.metadata.title,[a]:t.route.metadata.version,...d},s(t.config)),{buildApiDocsSearchDocuments:_}=await import(`./server/search-documents.js`);return{..._(n,r,{groupKey:f,facets:h,warn:e=>t.logger?.warn(e)}),problems:l([...g,...m?[o]:[]],t.route.originFilePath)}},async markdown(e,t){if(t.route===void 0)return null;let n=S(e),r=t.route.originFilePath??void 0,i=r?await t.entities.load(w(r)).catch(()=>void 0):void 0,{tags:a}=await N(M);return B(n,ve(i,n[A]?.llms),r,{tags:a,locale:P(t)})},usesProjectMarkdocSchema:!0}),W=t(T,async e=>{let t=K(e),n=await e.io.readFile(t.absolutePath),r=G(e.contentDir),i=await F({kind:e.args.kind,source:n,relativePath:t.relativePath,contentDir:e.contentDir,bundle:q(e.args,r),metadata:X(e.args.options)}),a=e.args.kind===v,o=a?n:JSON.stringify(i.document);return{value:o.length>65536?await e.createBlobRef(o,{format:a?`text`:`json`}):a?n:i.document,metadata:{...Z(e.file.path,e.args.kind,e.args.options,e.args.rbac),...ge(i.document,e.routes.byFilePath(e.file.path)?.slug)},entityDeps:Y(e.file.path,[...i.fileDependencies,...r.paths])}});function G(e){let t=de(e)?.lintPlugins??[];return{plugins:t,paths:t.map(t=>d(H(e,t.path))).filter(e=>e!==``&&!e.startsWith(`../`))}}function K(e){let t=e.args.source?.path??e.file.path;return{relativePath:t,absolutePath:V(e.contentDir,t)}}function he(e){let t=e[j];return p(t)&&typeof t.root==`string`?t.root:void 0}function q(e,t){let{config:n,configDir:r}=e.bundleConfig??{config:{},configDir:``};return{config:n,configDir:r,plugins:t.plugins}}function ge(e,t){let n=p(e)&&p(e.info)?e.info:{},r=p(n[`x-metadata`])?n[`x-metadata`]:{},i=typeof n.description==`string`?n.description.trim():``;return{...t===void 0?{}:{routeSlug:t},...Q(n.version)?{version:String(n.version)}:{},...typeof r.apiId==`string`?{apiId:r.apiId}:{},description:i||void 0}}const J=t(te,async e=>{let{buildNavItems:t,collectPreviousRouteSlugs:n}=await import(`@redocly/api-docs`),r=await e.entities.load(w(e.file.path)),i=e.args.kind===`graphql`?(await import(`graphql`)).parse(r):r,a=ue(i,e.args.kind,{warn:t=>e.logger?.warn(t)}),{items:o}=await t({type:e.args.kind,document:a,options:e.args.options,basePath:`/`,markdownParser:C}),s=R(o),c=n(o).map(({from:e})=>z(e));return{value:s,targetInventories:[{kind:`subpath`,exhaustive:!0,targets:[...L(s),...c]}]}});function Y(e,t){return[{kind:`file`,path:e},...t.map(e=>({kind:`file`,path:e}))]}const _e={arazzo:`Arazzo Docs`,asyncapi:`AsyncAPI Docs`,graphql:`GraphQL Docs`,openapi:`OpenAPI Docs`};function ve(e,t){if(t===void 0||!p(e))return e;let n=p(e.info)?e.info:{},r=p(e.components)?e.components:{};return{...e,...t.infoDescription===void 0?{}:{info:{...n,description:t.infoDescription}},...t.servers===void 0?{}:{servers:t.servers},...t.securitySchemes===void 0?{}:{components:{...r,securitySchemes:t.securitySchemes}}}}function ye(e){let t=p(e)&&p(e.info)?e.info:{};return p(t[`x-metadata`])?t[`x-metadata`]:{}}function be(e,t,n){let r=p(e)&&p(e.info)?e.info:{};if(typeof r.title==`string`&&r.title!==``)return r.title;let i=p(n[0])?n[0].label:void 0;return typeof i==`string`&&i!==``?i:_e[t]}const xe=[`rbac`,`sidebar`,`excludeFromSearch`,`template`];function Se(e,t){let n=p(e.manifest.info)?e.manifest.info:{},r={};typeof n.title==`string`&&(r.title=n.title),Q(n.version)&&(r.version=String(n.version)),typeof n.summary==`string`&&(r.summary=n.summary),p(n[`x-metadata`])&&Object.assign(r,n[`x-metadata`]),p(t.metadata)&&Object.assign(r,t.metadata);for(let e of xe)delete r[e];return r}function X(e){return p(e.metadata)?e.metadata:void 0}function Ce(e){let t=X(e)?.title;return typeof t==`string`&&t.length>0?t:void 0}function Z(e,t,n,r){let i=Ce(n);return{specType:t,sourcePath:e,...i===void 0?{}:{title:i},...r===void 0?{}:{rbac:r},...Object.keys(n).length>0?{options:n}:{},...p(n.mockServer)?{mockServer:n.mockServer}:{}}}function Q(e){return typeof e==`string`||typeof e==`number`}function we(e){if(e.ext===`.gql`||e.ext===`.graphql`)return v;let{openapi:t,swagger:n,asyncapi:r,arazzo:i}=e.manifest;return Q(t)||Q(n)?y:Q(r)?_:Q(i)?g:null}const Te=e({id:ee,version:`0.43.0`,content:{filter:{extensions:pe},async extractFile(e,t){if(f.test(e.path))return null;let n=we(e);if(n===null)return null;if(n!==`arazzo`&&!b(t.config,n))return{routes:[],problems:[m(`${me[n]} documents`)]};let r=e.path,i=he(e.manifest),a=i??r,{rbac:o,...s}=await ie(t.io,t.config,r,n,a),c={filePath:r,kind:n,options:s,...o===void 0||!b(t.config,`rbac`)?{}:{rbac:o}};i!==void 0&&(c.source={path:i});let l=await ae(t.io,t.config,a);if(l!==void 0&&(c.feedback=l),n!==`graphql`){let e=await re(t.io,t.config,r,a);Object.keys(e.config).length>0&&(c.bundleConfig=e)}let u=W.withArgs(c,{stableKey:w(r),type:`api`,metadata:Z(r,n,s,c.rbac)});if(n===`arazzo`)return{routes:[],entities:[u]};let d=Se(e,s);s.excludeFromSearch===!0&&(d.excludeFromSearch=!0),d.type=n,c.rbac!==void 0&&(d.rbac=c.rbac);let p=U.withArgs(c,{stableKey:`api-docs:render:${r}`}),g=J.withArgs(c,{stableKey:`api-docs:sidebar:${r}`}),_=h(r);return{routes:[{deps:{[E]:p},metadata:d,routeId:`page`,sidebarSubtree:g,slug:null,slugHint:_,template:O,wildcardPrefix:!0}],entities:[u,p,g]}}},loaders:[W,U,J],templates:{[O]:r(n(`./client/template.tsx`,import.meta.url))},server:{routes:[$(k.bundle,`bundle`),$(k.deprecatedBundle,`bundle`),$(k.graphql,`graphql`)]}});function $(e,t){return{method:`GET`,path:e+ne,handler:{filePath:`./server/spec-download.ts`,importer:import.meta.url,exportName:t}}}async function Ee(e,t){if(t)try{return await e.load(w(t))}catch{return}}export{Te as apiDocsContentPlugin};
|
|
1
|
+
import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t}from"../../../loaders/define.js";import{runtimeFile as n}from"../../utils/runtime-file.js";import{runtimeTemplate as r}from"../../templates.js";import{SEARCH_API_TITLE_FACET_FIELD as i,SEARCH_API_VERSION_FACET_FIELD as a,SEARCH_GROUP_FACET_FIELD as o}from"../../../../shared/search/facets.js";import{configuredFacetFields as s,extractFacetsFromFrontmatter as c,invalidFacetValueProblems as l,searchCategoryOf as u}from"../../../search/facet-values.js";import{toPosixPath as d}from"../../../../shared/utils/to-posix-path.js";import{TRANSLATIONS_FILE_PATTERN as f}from"../../../../shared/constants/l10n/defaults.js";import{isObject as p}from"../../../../shared/utils/is-object.js";import{notInPlanProblem as m}from"../../../plan-gates.js";import{filePathToRouteSlug as h}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{SPEC_KIND_ARAZZO as g,SPEC_KIND_ASYNCAPI as _,SPEC_KIND_GRAPHQL as v,SPEC_KIND_OPENAPI as y}from"../../types/api-entity.js";import{isPlanFeatureGranted as b}from"../../../../shared/plan-gates.js";import{packMarkdocAstsDeep as x,unpackMarkdocAstsDeep as S}from"../../../markdown/utils/packed-ast.js";import{parseMarkdownCached as C}from"../../../markdown/utils/parse-cache.js";import{createApiEntityKey as w}from"../../utils/api-entity-key.js";import{API_DOCS_API_LOADER_ID as T,API_DOCS_PLUGIN_ID as ee,API_DOCS_RENDER_DEP_KEY as E,API_DOCS_RENDER_LOADER_ID as D,API_DOCS_SIDEBAR_LOADER_ID as te,API_DOCS_TEMPLATE_ID as O,SPEC_DOWNLOAD_ROUTE_PATHS as k,SPEC_PATH_PARAM as ne}from"./server/shared.js";import{resolveApiBundleConfig as re,resolveApiOptions as ie,resolveNestedFeedback as ae,schemaCatalogLink as oe,withDownloadUrls as se,withFeedbackOption as ce,withMockServerOption as le}from"./server/options.js";import{annotateApiDocsRbac as ue}from"../../../../server/rbac/api-docs.js";import{SERVER_ONLY_VALUE_KEY as A}from"../../../loaders/server-only-value.js";import{getLoadedProjectPlugins as de}from"../../project/loaded-set.js";import{API_OUTPUT_MANIFEST_KEY as j}from"../../../api-outputs.js";import{API_DOCS_MARKDOC_TAG_SET as M,resolveMarkdocTagSet as N}from"../../../markdown/constants/tag-sets.js";import{pageLocale as P}from"../../utils/page-locale.js";import{buildBundledApiDefinition as F,resolveLlmsDescriptions as I}from"./server/build-definition.js";import{collectSidebarSubpathTargets as L,toSidebarSubtree as R,toSubpathTarget as z}from"./server/build-sidebar.js";import{buildApiDocsMarkdownDocs as B}from"./server/markdown-docs.js";import{join as V,relative as H}from"node:path";import fe from"@redocly/markdoc";const pe=[`.yaml`,`.yml`,`.json`,`.gql`,`.graphql`],me={[y]:`OpenAPI`,[_]:`AsyncAPI`,[v]:`GraphQL`,[g]:`Arazzo`},U=t(D,async e=>{let{buildItems:t}=await import(`@redocly/api-docs`),n=K(e),r=await e.io.readFile(n.absolutePath),i=e.routes.byFilePath(e.file.path)?.slug,a=se(e.args.options,e.file.path,e.args.kind),o=e.args.kind===`openapi`?le(a,e.config,i):a,s={entityDeps:[],assetUsages:[],linkRefs:[],problems:[],pending:[]},c=G(e.contentDir),l={markdown:e.markdown,loader:{config:e.config,entities:e.entities,file:e.file,io:e.io,logger:e.logger,plugin:e.plugin},sink:s},u=await F({kind:e.args.kind,source:r,relativePath:n.relativePath,contentDir:e.contentDir,pagePath:e.file.path,options:o,bundle:q(e.args,c),metadata:X(e.args.options),markdownResolution:l,rbac:{warn:t=>e.logger?.warn(t)}}),d={...p(u.document)&&p(u.document.info)?{infoDescription:u.document.info.description}:{},...await I(u.document,l,{contentDir:e.contentDir,specPath:n.relativePath,pagePath:e.file.path})};e.args.kind===`openapi`&&o.showSchemaCatalogLinks&&p(u.document)&&(u.document[`x-schema-catalog-link`]=oe(e.file.path)),u.options=ce(u.options,u.document,e.args.feedback??e.config.feedback);let f=i?.toLowerCase()??`/`,{items:m,store:h,specType:g}=await t({...u,basePath:f,markdownParser:e=>fe.compact(C(e))}),_=JSON.stringify({items:x(m),store:x(h),options:u.options,specType:g,basePath:f,title:be(u.document,e.args.kind,m),metadata:ye(u.document),[A]:{llms:d}});return{value:await e.createBlobRef(_,{format:`json`}),entityDeps:[...Y(e.file.path,[...u.fileDependencies,...c.paths]),...s.entityDeps],assetUsages:s.assetUsages,markdoc:{tagSet:M},linkRefs:s.linkRefs,problems:s.problems}},{async searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=S(e),r=await Ee(t.entities,t.route.originFilePath),d={...t.route.metadata,...p(n.metadata)?n.metadata:{}},{category:f,isInvalid:m}=u(d),{facets:h,invalidFields:g}=c({[i]:t.route.metadata.title,[a]:t.route.metadata.version,...d},s(t.config)),{buildApiDocsSearchDocuments:_}=await import(`./server/search-documents.js`);return{..._(n,r,{groupKey:f,facets:h,warn:e=>t.logger?.warn(e)}),problems:l([...g,...m?[o]:[]],t.route.originFilePath)}},async markdown(e,t){if(t.route===void 0)return null;let n=S(e),r=t.route.originFilePath??void 0,i=r?await t.entities.load(w(r)).catch(()=>void 0):void 0,{tags:a}=await N(M);return B(n,ve(i,n[A]?.llms),r,{tags:a,locale:P(t)})},usesProjectMarkdocSchema:!0}),W=t(T,async e=>{let t=K(e),n=await e.io.readFile(t.absolutePath),r=G(e.contentDir),i=await F({kind:e.args.kind,source:n,relativePath:t.relativePath,contentDir:e.contentDir,bundle:q(e.args,r),metadata:X(e.args.options)}),a=e.args.kind===v,o=a?n:JSON.stringify(i.document);return{value:o.length>65536?await e.createBlobRef(o,{format:a?`text`:`json`}):a?n:i.document,metadata:{...Z(e.file.path,e.args.kind,e.args.options,e.args.rbac),...ge(i.document,e.routes.byFilePath(e.file.path)?.slug)},entityDeps:Y(e.file.path,[...i.fileDependencies,...r.paths])}});function G(e){let t=de(e)?.lintPlugins??[];return{plugins:t,paths:t.map(t=>d(H(e,t.path))).filter(e=>e!==``&&!e.startsWith(`../`))}}function K(e){let t=e.args.source?.path??e.file.path;return{relativePath:t,absolutePath:V(e.contentDir,t)}}function he(e){let t=e[j];return p(t)&&typeof t.root==`string`?t.root:void 0}function q(e,t){let{config:n,configDir:r}=e.bundleConfig??{config:{},configDir:``};return{config:n,configDir:r,plugins:t.plugins}}function ge(e,t){let n=p(e)&&p(e.info)?e.info:{},r=p(n[`x-metadata`])?n[`x-metadata`]:{},i=typeof n.description==`string`?n.description.trim():``;return{...t===void 0?{}:{routeSlug:t},...Q(n.version)?{version:String(n.version)}:{},...typeof r.apiId==`string`?{apiId:r.apiId}:{},description:i||void 0}}const J=t(te,async e=>{let{buildNavItems:t,collectPreviousRouteSlugs:n}=await import(`@redocly/api-docs`),r=await e.entities.load(w(e.file.path)),i=e.args.kind===`graphql`?(await import(`graphql`)).parse(r):r,a=ue(i,e.args.kind,{warn:t=>e.logger?.warn(t)}),{items:o}=await t({type:e.args.kind,document:a,options:e.args.options,basePath:`/`,markdownParser:C}),s=R(o),c=n(o).map(({from:e})=>z(e));return{value:s,targetInventories:[{kind:`subpath`,exhaustive:!0,targets:[...L(s),...c]}]}});function Y(e,t){return[{kind:`file`,path:e},...t.map(e=>({kind:`file`,path:e}))]}const _e={arazzo:`Arazzo Docs`,asyncapi:`AsyncAPI Docs`,graphql:`GraphQL Docs`,openapi:`OpenAPI Docs`};function ve(e,t){if(t===void 0||!p(e))return e;let n=p(e.info)?e.info:{},r=p(e.components)?e.components:{};return{...e,...t.infoDescription===void 0?{}:{info:{...n,description:t.infoDescription}},...t.servers===void 0?{}:{servers:t.servers},...t.securitySchemes===void 0?{}:{components:{...r,securitySchemes:t.securitySchemes}}}}function ye(e){let t=p(e)&&p(e.info)?e.info:{};return p(t[`x-metadata`])?t[`x-metadata`]:{}}function be(e,t,n){let r=p(e)&&p(e.info)?e.info:{};if(typeof r.title==`string`&&r.title!==``)return r.title;let i=p(n[0])?n[0].label:void 0;return typeof i==`string`&&i!==``?i:_e[t]}const xe=[`rbac`,`sidebar`,`excludeFromSearch`,`template`];function Se(e,t){let n=p(e.manifest.info)?e.manifest.info:{},r={};typeof n.title==`string`&&(r.title=n.title),Q(n.version)&&(r.version=String(n.version)),typeof n.summary==`string`&&(r.summary=n.summary),p(n[`x-metadata`])&&Object.assign(r,n[`x-metadata`]),p(t.metadata)&&Object.assign(r,t.metadata);for(let e of xe)delete r[e];return r}function X(e){return p(e.metadata)?e.metadata:void 0}function Ce(e){let t=X(e)?.title;return typeof t==`string`&&t.length>0?t:void 0}function Z(e,t,n,r){let i=Ce(n);return{specType:t,sourcePath:e,...i===void 0?{}:{title:i},...r===void 0?{}:{rbac:r},...Object.keys(n).length>0?{options:n}:{},...p(n.mockServer)?{mockServer:n.mockServer}:{}}}function Q(e){return typeof e==`string`||typeof e==`number`}function we(e){if(e.ext===`.gql`||e.ext===`.graphql`)return v;let{openapi:t,swagger:n,asyncapi:r,arazzo:i}=e.manifest;return Q(t)||Q(n)?y:Q(r)?_:Q(i)?g:null}const Te=e({id:ee,version:`0.44.0`,content:{filter:{extensions:pe},async extractFile(e,t){if(f.test(e.path))return null;let n=we(e);if(n===null)return null;if(n!==`arazzo`&&!b(t.config,n))return{routes:[],problems:[m(`${me[n]} documents`)]};let r=e.path,i=he(e.manifest),a=i??r,{rbac:o,...s}=await ie(t.io,t.config,r,n,a),c={filePath:r,kind:n,options:s,...o===void 0||!b(t.config,`rbac`)?{}:{rbac:o}};i!==void 0&&(c.source={path:i});let l=await ae(t.io,t.config,a);if(l!==void 0&&(c.feedback=l),n!==`graphql`){let e=await re(t.io,t.config,r,a);Object.keys(e.config).length>0&&(c.bundleConfig=e)}let u=W.withArgs(c,{stableKey:w(r),type:`api`,metadata:Z(r,n,s,c.rbac)});if(n===`arazzo`)return{routes:[],entities:[u]};let d=Se(e,s);s.excludeFromSearch===!0&&(d.excludeFromSearch=!0),d.type=n,c.rbac!==void 0&&(d.rbac=c.rbac);let p=U.withArgs(c,{stableKey:`api-docs:render:${r}`}),g=J.withArgs(c,{stableKey:`api-docs:sidebar:${r}`}),_=h(r);return{routes:[{deps:{[E]:p},metadata:d,routeId:`page`,sidebarSubtree:g,slug:null,slugHint:_,template:O,wildcardPrefix:!0}],entities:[u,p,g]}}},loaders:[W,U,J],templates:{[O]:r(n(`./client/template.tsx`,import.meta.url))},server:{routes:[$(k.bundle,`bundle`),$(k.deprecatedBundle,`bundle`),$(k.graphql,`graphql`)]}});function $(e,t){return{method:`GET`,path:e+ne,handler:{filePath:`./server/spec-download.ts`,importer:import.meta.url,exportName:t}}}async function Ee(e,t){if(t)try{return await e.load(w(t))}catch{return}}export{Te as apiDocsContentPlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t}from"../../../loaders/define.js";import{runtimeFile as n}from"../../utils/runtime-file.js";import{createPluginScopedId as r}from"../../utils/scoped-id.js";import{runtimeTemplate as i}from"../../templates.js";import{SEARCH_GROUP_FACET_FIELD as a}from"../../../../shared/search/facets.js";import{configuredFacetFields as o,extractFacetsFromFrontmatter as s,invalidFacetValueProblems as c,searchCategoryOf as l}from"../../../search/facet-values.js";import{isObject as u}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as d}from"../../../../shared/utils/routes/normalize-route-slug.js";import{resolveContentPath as f}from"../../../../shared/utils/resolve-content-path.js";import{PAGE_BANNER_SCHEMA as p,sanitizeConfig as m}from"../../../config-schema.js";import{notInPlanProblem as h}from"../../../plan-gates.js";import{matchPathMap as g}from"../../utils/glob.js";import{filePathToRouteSlug as _}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{isPlanFeatureGranted as v}from"../../../../shared/plan-gates.js";import{splitUrlSuffix as y}from"../../../../shared/utils/routes/split-url-suffix.js";import{packMarkdocAst as ee,unpackMarkdocAst as b}from"../../../markdown/utils/packed-ast.js";import{isRouteSlugTarget as x}from"../../../../shared/utils/routes/is-route-slug-target.js";import{loadSidebarSubtreeLabel as S}from"../../utils/sidebar-label.js";import{markdocNodeRange as C}from"../../../markdown/utils/node-source-range.js";import{replaceWithMarkdocError as te}from"../../../markdown/tags/markdoc-error.js";import{CODE_WALKTHROUGH_TAG_NAMES as ne,builtInMarkdocTags as re}from"../../../markdown/constants/builtin-tags.js";import{walkMarkdocAst as w}from"../../../markdown/utils/walk-markdoc-ast.js";import{markdocFirstHeading as ie}from"../../../markdown/search/to-text.js";import{safeDecodeURI as ae}from"../../../../shared/utils/safe-decode-uri.js";import{shiftRange as oe}from"../../../../shared/utils/shift-range.js";import{classifyLinkTarget as se}from"../../../link-checker/classify.js";import{onDiskLinkRefs as ce}from"../../../link-checker/node-ref.js";import{isPartialPath as le}from"../../../markdown/utils/partials.js";import{FRONTMATTER_BLOCK_RE as ue,computeFrontmatterLineOffset as de}from"../../../markdown/utils/frontmatter-offset.js";import{inlineRawPartials as fe}from"../../../markdown/resolve/raw-partials.js";import{resolveMarkdownAst as T}from"../../../markdown/resolve/ast.js";import{resolveBannerForAppData as E}from"../app-data/banner.js";import{MARKDOC_DOCUMENT_LOADER_KEY as D}from"../../../../shared/constants/route-deps.js";import{isMarkdocValidationEnabled as O,resolveMarkdocTagSet as k,resolveMarkdownPageValidationSet as A,userMarkdocSchemaFiles as j,userMarkdocTagNames as M}from"../../../markdown/constants/tag-sets.js";import{pageLocale as N}from"../../utils/page-locale.js";import{markdocAstToMarkdownDoc as P}from"../../../markdown/search/to-markdown.js";import{collectAnchors as F}from"../../../markdown/utils/collect-anchors.js";import{frontmatterVariable as I}from"../../../markdown/utils/frontmatter-variable.js";import{markdownFirstHeading as L}from"../../../markdown/utils/first-heading.js";import{markdocAstToSearchSections as R}from"../../../markdown/search/to-sections.js";import{isInternalPagePath as z}from"../../utils/internal-page-path.js";import{parseExplicitSlugs as B}from"../../utils/explicit-slugs.js";import{isSkillContentPath as V}from"../../utils/skill-paths.js";import{SOURCE_TEMPLATE_PREFIX as pe}from"../../../../shared/constants/template-ids.js";import{captureSnippet as H,splitSourceLines as me}from"../../../../shared/utils/capture-snippet.js";import{curationKeywordsOf as he}from"../../../search/keywords.js";import ge from"js-yaml";const U=`markdoc-page`,W=r(`internal.markdoc`,`document`),G=r(`internal.markdoc`,`sidebar-item`),_e=`Documentation`,K=t(W,async e=>{let t=await e.io.readFile(e.file.absolutePath),{content:n,frontmatter:r,frontmatterError:i}=Y(t),a=J(e),{ast:o,entityDeps:s,assetUsages:c,tagList:l,problems:u,linkRefs:d}=await T(n,e.file.path,{resolverContext:a,tags:(await k()).tags,variables:{get env(){return e.config.publicEnv??{}}},transform:t=>Ee(t,e.file.path,Te(e.config)),validation:O()?await A():void 0}),f=de(t);je(o);let p=await we(r.seo,e),m=v(e.config,`banner`)?await E(Me(r,e.file.path,e.logger),a):void 0,h=await Oe(r,e),g=await ke(r.navigation,e),_={...h.frontmatter,navigation:g.value,seo:p.seo,banner:m?.banner},y=Ne(r,o);return{value:{ast:ee(o),frontmatter:_,tagList:l,title:y,editPage:Ce(e.config,r,e.file.path),lastModified:e.file.lastModifiedAt},entityDeps:[...s,...ye(),...p.entityDeps,...m?.deps??[],...h.entityDeps,...g.entityDeps],assetUsages:[...c,...p.assetUsages,...m?.assetUsages??[],...h.assetUsages],problems:be(t,e.file.path,f,u,i),linkRefs:[...ce(d,f),...g.linkRefs],targetInventories:[xe(o,{frontmatter:I(_,y)})]}},{usesProjectMarkdocSchema:!0,async markdown(e,t){let{tags:n}=await k(),{chunks:r,headings:i}=P(b(e.ast),{tags:n,locale:N(t),variables:{frontmatter:I(e.frontmatter,e.title),env:t.config.publicEnv??{}}});return[{chunks:r,headings:i,...e.title?{title:e.title}:{}}]},searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=t.route.slug,r=e.title??Q(t.route.originFilePath??n),{category:i,isInvalid:u}=l(t.route.metadata),{facets:d,invalidFields:f}=s(t.route.metadata,o(t.config)),p=he(e.frontmatter.keywords);return{docs:R(b(e.ast),r,{frontmatter:I(e.frontmatter,e.title)}).map((e,t)=>{let r={docKey:e.docKey,routeSlug:n,title:e.title,text:e.text,groupKey:i??`Documentation`,facets:d};e.anchor!==void 0&&(r.anchor=e.anchor),e.path!==void 0&&(r.path=e.path);let a=t===0?p:{excludes:p?.excludes};return(a?.includes||a?.excludes)&&(r.keywords=a),e.rbacTeams!==void 0&&(r.rbacScope=Object.fromEntries(e.rbacTeams.map(e=>[e,`read`]))),r}),problems:c([...f,...u?[a]:[]],t.route.originFilePath)}}}),q=t(G,async e=>{let{content:t,frontmatter:n}=Y(await e.io.readFile(e.file.absolutePath)),r=await fe(t,e.file.path,J(e));return{value:{label:Z(n)??L(r.source)??Q(e.args.filePath)},entityDeps:r.entityDeps}});function J(e){return{config:e.config,contentDir:e.contentDir,entities:e.entities,file:e.file,io:e.io,logger:e.logger,markdown:e.markdown,plugin:e.plugin}}const ve=e({id:`internal.markdoc`,version:`3.44.0`,content:{filter:{match:e=>e.toLowerCase().endsWith(`.md`)&&!V(e)},extractFile(e,t){if(z(e.path)||le(e.path,t.config))return{routes:[]};if(!v(t.config,`markdown`))return{routes:[],problems:[h(`Markdown pages`)]};let{banner:n,...r}=e.manifest,i=Pe(e,t),a=B(r.slug),o=K.withArgs({filePath:e.path}),s=q.withArgs({filePath:e.path});return{routes:a.length>0?a.map(e=>({deps:{[D]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:e,slugHint:null,template:i})):[{deps:{[D]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:null,slugHint:_(e.path),template:i}],entities:[o]}}},loaders:[K,q],templates:{[U]:i(n(`./client/template.tsx`,import.meta.url))}});function Y(e){let t=e.match(ue);if(!t)return{content:e,frontmatter:{}};let n=t[1]??``;try{let r=ge.load(n);return{content:e.slice(t[0].length),frontmatter:u(r)?r:{}}}catch(n){let r=n instanceof Error?n.message:String(n);return{content:e.slice(t[0].length),frontmatter:{},frontmatterError:r}}}function ye(){return(j()??[]).map(e=>({kind:`file`,path:e}))}function be(e,t,n,r,i){if(r.length===0&&i===void 0)return[];let a=me(e),o=r.map(e=>Se(e,a,n,t));if(i!==void 0){let e={start:{line:1},end:{line:n}};o.push({code:`markdown/frontmatter-parse`,message:i,location:{filePath:t,range:e,snippet:H(a,e)}})}return o}function xe(e,t){let{ids:n,exhaustive:r}=F(e,t);return{kind:`anchor`,exhaustive:r,targets:n}}function Se(e,t,n,r){let i=e.location?.range;if(!i)return e;let a=oe(i,n);return{...e,location:{filePath:r,range:a,snippet:H(t,a)}}}function Ce(e,t,n){let r=u(t.markdown)?t.markdown:{},i={...e.markdown?.editPage,...u(r.editPage)?r.editPage:{}};if(i.hide!==!0&&typeof i.baseUrl==`string`&&i.baseUrl!==``)return{to:`${i.baseUrl.replace(/(?<!\/)\/+$/,``)}/${n}`}}async function we(e,t){if(!u(e)||typeof e.image!=`string`)return{seo:e,entityDeps:[],assetUsages:[]};let n=await t.markdown.resolveImageReference(e.image,t.file.path);return n.result.kind===`assetRef`?{seo:{...e,image:n.result.url},entityDeps:n.entityDeps,assetUsages:n.assetUsages}:{seo:e,entityDeps:n.entityDeps,assetUsages:[]}}function Te(e){let t=/* @__PURE__ */ new Map;if(!v(e,`customMarkdocTags`))for(let e of M())t.set(e,`Custom Markdoc tags are not in this project's plan, so \`${e}\` is ignored.`);if(!v(e,`codeWalkthrough`))for(let e of ne)t.set(e,`\`${e}\` is not in this project's plan and is ignored.`);return t}function Ee(e,t,n){let r=[];if(n.size===0)return r;for(let i of w(e)){let e=i.type===`tag`&&i.tag!==void 0?n.get(i.tag):void 0;e!==void 0&&(r.push({code:`configuration/ignored`,message:e,location:{filePath:t,range:C(i)??{start:{line:1},end:{line:1}}}}),te(i,e))}return r}const De=[`image`,`links`];async function Oe(e,t){let n=t.config.markdown?.frontMatterKeysToResolve??De,r={...e},i=[],a=[];for(let o of n){let n=e[o];if(typeof n!=`string`)continue;let s=await t.markdown.resolveLocalReference(n,t.file.path);i.push(...s.entityDeps),a.push(...s.assetUsages),s.result.kind!==`passthrough`&&(r[o]=s.result.url)}return{frontmatter:r,entityDeps:i,assetUsages:a}}async function ke(e,t){let n=[],r=[];if(!u(e))return{value:e,entityDeps:n,linkRefs:r};let i={...e};for(let a of[`nextButton`,`previousButton`]){let o=e[a];if(!u(o)||typeof o.page!=`string`)continue;let{page:s,...c}=o,l=se(ae(s),t.file.path);l!==null&&r.push({kind:`link`,raw:s,...l});let d=await X(s,t);n.push(...d.entityDeps),i[a]={...c,label:typeof c.label==`string`?c.label:d.route&&await Ae(d.route,t),link:d.link}}return{value:i,entityDeps:n,linkRefs:r}}async function Ae(e,t){let n=await S(t.entities,e);if(n!==void 0)return n;let r=t.routes.get(e.slug)?.metadata.seo;return u(r)&&typeof r.title==`string`&&r.title.trim()!==``?r.title:e.slug}async function X(e,t){let n=e.trim(),{path:r,suffix:i}=y(n);if(x(r)){let e=t.routes.bySlug(d(r));return{link:e&&`${e.slug}${i}`,route:e,entityDeps:[]}}let a=await t.markdown.resolveLocalReference(n,t.file.path);if(a.result.kind!==`pageUrl`)return{entityDeps:a.entityDeps};let o=a.result.url;return{link:o,route:t.routes.bySlug(y(o).path)??a.entityDeps.map(e=>e.kind===`file`?t.routes.byFilePath(e.path):void 0).reverse().find(e=>e!==void 0),entityDeps:a.entityDeps}}function je(e){let t=/* @__PURE__ */ new Map;for(let n of w(e)){if(n.type!==`tag`||n.tag===void 0||re[n.tag]?.attributes?.__idx===void 0)continue;let e=(t.get(n.tag)??0)+1;t.set(n.tag,e),n.attributes.__idx=e}}function Me(e,t,n){if(e.banner===void 0)return;let{value:r,problems:i}=m(p,{banner:e.banner});for(let e of i)n?.warn(`${t}: ${e.message}`);return r.banner}function Ne(e,t){return Z(e)??ie(t)??void 0}function Z(e){let t=u(e.seo)?e.seo.title:void 0;return typeof t==`string`&&t.trim()!==``?t:void 0}function Q(e){let t=(e.split(`/`).pop()??e).replace(/\.[^.]+$/,``);return t===``?e:t}function Pe(e,t){let n=e.manifest.template;if(typeof n==`string`&&n.trim()!==``)return $(n,e.path,t.logger);let r=g(e.path,t.config.markdown?.template);return typeof r==`string`&&r.trim()!==``?$(r,`redocly.yaml`,t.logger):U}function $(e,t,n){if(!e.startsWith(`./`)&&!e.startsWith(`../`)&&!e.startsWith(`/`))return e;let r=f(e,t);return r===null?(n.warn(`Template reference "${e}" in ${t} escapes the content root; falling back to ${U}.`),U):`${pe}${r}`}export{W as MARKDOC_DOCUMENT_LOADER_ID,_e as MARKDOC_SEARCH_GROUP,G as MARKDOC_SIDEBAR_ITEM_LOADER_ID,U as MARKDOC_TEMPLATE_ID,ve as markdocContentPlugin};
|
|
1
|
+
import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t}from"../../../loaders/define.js";import{runtimeFile as n}from"../../utils/runtime-file.js";import{createPluginScopedId as r}from"../../utils/scoped-id.js";import{runtimeTemplate as i}from"../../templates.js";import{SEARCH_GROUP_FACET_FIELD as a}from"../../../../shared/search/facets.js";import{configuredFacetFields as o,extractFacetsFromFrontmatter as s,invalidFacetValueProblems as c,searchCategoryOf as l}from"../../../search/facet-values.js";import{isObject as u}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as d}from"../../../../shared/utils/routes/normalize-route-slug.js";import{resolveContentPath as f}from"../../../../shared/utils/resolve-content-path.js";import{PAGE_BANNER_SCHEMA as p,sanitizeConfig as m}from"../../../config-schema.js";import{notInPlanProblem as h}from"../../../plan-gates.js";import{matchPathMap as g}from"../../utils/glob.js";import{filePathToRouteSlug as _}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{isPlanFeatureGranted as v}from"../../../../shared/plan-gates.js";import{splitUrlSuffix as y}from"../../../../shared/utils/routes/split-url-suffix.js";import{packMarkdocAst as ee,unpackMarkdocAst as b}from"../../../markdown/utils/packed-ast.js";import{isRouteSlugTarget as x}from"../../../../shared/utils/routes/is-route-slug-target.js";import{loadSidebarSubtreeLabel as S}from"../../utils/sidebar-label.js";import{markdocNodeRange as C}from"../../../markdown/utils/node-source-range.js";import{replaceWithMarkdocError as te}from"../../../markdown/tags/markdoc-error.js";import{getPartialTwins as ne}from"../../../markdown/tags/partial.js";import{CODE_WALKTHROUGH_TAG_NAMES as re,builtInMarkdocTags as ie}from"../../../markdown/constants/builtin-tags.js";import{walkMarkdocAst as w}from"../../../markdown/utils/walk-markdoc-ast.js";import{markdocFirstHeading as ae}from"../../../markdown/search/to-text.js";import{safeDecodeURI as oe}from"../../../../shared/utils/safe-decode-uri.js";import{shiftRange as se}from"../../../../shared/utils/shift-range.js";import{classifyLinkTarget as ce}from"../../../link-checker/classify.js";import{onDiskLinkRefs as le}from"../../../link-checker/node-ref.js";import{isPartialPath as ue}from"../../../markdown/utils/partials.js";import{FRONTMATTER_BLOCK_RE as de,computeFrontmatterLineOffset as fe}from"../../../markdown/utils/frontmatter-offset.js";import{inlineRawPartials as T}from"../../../markdown/resolve/raw-partials.js";import{resolveMarkdownAst as E}from"../../../markdown/resolve/ast.js";import{resolveBannerForAppData as D}from"../app-data/banner.js";import{MARKDOC_DOCUMENT_LOADER_KEY as O}from"../../../../shared/constants/route-deps.js";import{isMarkdocValidationEnabled as k,resolveMarkdocTagSet as A,resolveMarkdownPageValidationSet as j,userMarkdocSchemaFiles as M,userMarkdocTagNames as N}from"../../../markdown/constants/tag-sets.js";import{pageLocale as P}from"../../utils/page-locale.js";import{markdocAstToMarkdownDoc as F}from"../../../markdown/search/to-markdown.js";import{collectAnchors as I}from"../../../markdown/utils/collect-anchors.js";import{frontmatterVariable as L}from"../../../markdown/utils/frontmatter-variable.js";import{markdownFirstHeading as R}from"../../../markdown/utils/first-heading.js";import{markdocAstToSearchSections as z}from"../../../markdown/search/to-sections.js";import{isInternalPagePath as B}from"../../utils/internal-page-path.js";import{parseExplicitSlugs as V}from"../../utils/explicit-slugs.js";import{isSkillContentPath as pe}from"../../utils/skill-paths.js";import{SOURCE_TEMPLATE_PREFIX as me}from"../../../../shared/constants/template-ids.js";import{captureSnippet as H,splitSourceLines as he}from"../../../../shared/utils/capture-snippet.js";import{curationKeywordsOf as ge}from"../../../search/keywords.js";import _e from"js-yaml";const U=`markdoc-page`,W=r(`internal.markdoc`,`document`),G=r(`internal.markdoc`,`sidebar-item`),ve=`Documentation`,K=t(W,async e=>{let t=await e.io.readFile(e.file.absolutePath),{content:n,frontmatter:r,frontmatterError:i}=Y(t),a=J(e),{ast:o,entityDeps:s,assetUsages:c,tagList:l,problems:u,linkRefs:d}=await E(n,e.file.path,{resolverContext:a,tags:(await A()).tags,variables:{get env(){return e.config.publicEnv??{}}},transform:t=>De(t,e.file.path,Ee(e.config)),validation:k()?await j():void 0}),f=fe(t);Me(o);let p=await Te(r.seo,e),m=v(e.config,`banner`)?await D(Ne(r,e.file.path,e.logger),a):void 0,h=await ke(r,e),g=await Ae(r.navigation,e),_={...h.frontmatter,navigation:g.value,seo:p.seo,banner:m?.banner},y=Pe(r,o);return{value:{ast:ee(o),frontmatter:_,tagList:l,title:y,editPage:we(e.config,r,e.file.path),lastModified:e.file.lastModifiedAt},entityDeps:[...s,...be(),...p.entityDeps,...m?.deps??[],...h.entityDeps,...g.entityDeps],assetUsages:[...c,...p.assetUsages,...m?.assetUsages??[],...h.assetUsages],problems:xe(t,e.file.path,f,u,i),linkRefs:[...le(d,f),...g.linkRefs],targetInventories:[Se(o,{frontmatter:L(_,y)})]}},{usesProjectMarkdocSchema:!0,async markdown(e,t){let{tags:n}=await A(),{chunks:r,headings:i}=F(b(e.ast),{tags:n,locale:P(t),variables:{frontmatter:L(e.frontmatter,e.title),env:t.config.publicEnv??{}}});return[{chunks:r,headings:i,...e.title?{title:e.title}:{}}]},searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=t.route.slug,r=e.title??Q(t.route.originFilePath??n),{category:i,isInvalid:u}=l(t.route.metadata),{facets:d,invalidFields:f}=s(t.route.metadata,o(t.config)),p=ge(e.frontmatter.keywords);return{docs:z(b(e.ast),r,{frontmatter:L(e.frontmatter,e.title)}).map((e,t)=>{let r={docKey:e.docKey,routeSlug:n,title:e.title,text:e.text,groupKey:i??`Documentation`,facets:d};e.anchor!==void 0&&(r.anchor=e.anchor),e.path!==void 0&&(r.path=e.path);let a=t===0?p:{excludes:p?.excludes};return(a?.includes||a?.excludes)&&(r.keywords=a),e.rbacTeams!==void 0&&(r.rbacScope=Object.fromEntries(e.rbacTeams.map(e=>[e,`read`]))),r}),problems:c([...f,...u?[a]:[]],t.route.originFilePath)}}}),q=t(G,async e=>{let{content:t,frontmatter:n}=Y(await e.io.readFile(e.file.absolutePath)),r=await T(t,e.file.path,J(e));return{value:{label:Z(n)??R(r.source)??Q(e.args.filePath)},entityDeps:r.entityDeps}});function J(e){return{config:e.config,contentDir:e.contentDir,entities:e.entities,file:e.file,io:e.io,logger:e.logger,markdown:e.markdown,plugin:e.plugin}}const ye=e({id:`internal.markdoc`,version:`3.45.0`,content:{filter:{match:e=>e.toLowerCase().endsWith(`.md`)&&!pe(e)},extractFile(e,t){if(B(e.path)||ue(e.path,t.config))return{routes:[]};if(!v(t.config,`markdown`))return{routes:[],problems:[h(`Markdown pages`)]};let{banner:n,...r}=e.manifest,i=Fe(e,t),a=V(r.slug),o=K.withArgs({filePath:e.path}),s=q.withArgs({filePath:e.path});return{routes:a.length>0?a.map(e=>({deps:{[O]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:e,slugHint:null,template:i})):[{deps:{[O]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:null,slugHint:_(e.path),template:i}],entities:[o]}}},loaders:[K,q],templates:{[U]:i(n(`./client/template.tsx`,import.meta.url))}});function Y(e){let t=e.match(de);if(!t)return{content:e,frontmatter:{}};let n=t[1]??``;try{let r=_e.load(n);return{content:e.slice(t[0].length),frontmatter:u(r)?r:{}}}catch(n){let r=n instanceof Error?n.message:String(n);return{content:e.slice(t[0].length),frontmatter:{},frontmatterError:r}}}function be(){return(M()??[]).map(e=>({kind:`file`,path:e}))}function xe(e,t,n,r,i){if(r.length===0&&i===void 0)return[];let a=he(e),o=r.map(e=>Ce(e,a,n,t));if(i!==void 0){let e={start:{line:1},end:{line:n}};o.push({code:`markdown/frontmatter-parse`,message:i,location:{filePath:t,range:e,snippet:H(a,e)}})}return o}function Se(e,t){let{ids:n,exhaustive:r}=I(e,t);return{kind:`anchor`,exhaustive:r,targets:n}}function Ce(e,t,n,r){let i=e.location?.range;if(!i)return e;let a=se(i,n);return{...e,location:{filePath:r,range:a,snippet:H(t,a)}}}function we(e,t,n){let r=u(t.markdown)?t.markdown:{},i={...e.markdown?.editPage,...u(r.editPage)?r.editPage:{}};if(i.hide!==!0&&typeof i.baseUrl==`string`&&i.baseUrl!==``)return{to:`${i.baseUrl.replace(/(?<!\/)\/+$/,``)}/${n}`}}async function Te(e,t){if(!u(e)||typeof e.image!=`string`)return{seo:e,entityDeps:[],assetUsages:[]};let n=await t.markdown.resolveImageReference(e.image,t.file.path);return n.result.kind===`assetRef`?{seo:{...e,image:n.result.url},entityDeps:n.entityDeps,assetUsages:n.assetUsages}:{seo:e,entityDeps:n.entityDeps,assetUsages:[]}}function Ee(e){let t=/* @__PURE__ */ new Map;if(!v(e,`customMarkdocTags`))for(let e of N())t.set(e,`Custom Markdoc tags are not in this project's plan, so \`${e}\` is ignored.`);if(!v(e,`codeWalkthrough`))for(let e of re)t.set(e,`\`${e}\` is not in this project's plan and is ignored.`);return t}function De(e,t,n){let r=[];if(n.size===0)return r;for(let i of w(e,{getExtraNodes:ne})){let e=i.type===`tag`&&i.tag!==void 0?n.get(i.tag):void 0;e!==void 0&&(r.push({code:`configuration/ignored`,message:e,location:{filePath:t,range:C(i)??{start:{line:1},end:{line:1}}}}),te(i,e))}return r}const Oe=[`image`,`links`];async function ke(e,t){let n=t.config.markdown?.frontMatterKeysToResolve??Oe,r={...e},i=[],a=[];for(let o of n){let n=e[o];if(typeof n!=`string`)continue;let s=await t.markdown.resolveLocalReference(n,t.file.path);i.push(...s.entityDeps),a.push(...s.assetUsages),s.result.kind!==`passthrough`&&(r[o]=s.result.url)}return{frontmatter:r,entityDeps:i,assetUsages:a}}async function Ae(e,t){let n=[],r=[];if(!u(e))return{value:e,entityDeps:n,linkRefs:r};let i={...e};for(let a of[`nextButton`,`previousButton`]){let o=e[a];if(!u(o)||typeof o.page!=`string`)continue;let{page:s,...c}=o,l=ce(oe(s),t.file.path);l!==null&&r.push({kind:`link`,raw:s,...l});let d=await je(s,t);n.push(...d.entityDeps),i[a]={...c,label:typeof c.label==`string`?c.label:d.route&&await X(d.route,t),link:d.link}}return{value:i,entityDeps:n,linkRefs:r}}async function X(e,t){let n=await S(t.entities,e);if(n!==void 0)return n;let r=t.routes.get(e.slug)?.metadata.seo;return u(r)&&typeof r.title==`string`&&r.title.trim()!==``?r.title:e.slug}async function je(e,t){let n=e.trim(),{path:r,suffix:i}=y(n);if(x(r)){let e=t.routes.bySlug(d(r));return{link:e&&`${e.slug}${i}`,route:e,entityDeps:[]}}let a=await t.markdown.resolveLocalReference(n,t.file.path);if(a.result.kind!==`pageUrl`)return{entityDeps:a.entityDeps};let o=a.result.url;return{link:o,route:t.routes.bySlug(y(o).path)??a.entityDeps.map(e=>e.kind===`file`?t.routes.byFilePath(e.path):void 0).reverse().find(e=>e!==void 0),entityDeps:a.entityDeps}}function Me(e){let t=/* @__PURE__ */ new Map;for(let n of w(e)){if(n.type!==`tag`||n.tag===void 0||ie[n.tag]?.attributes?.__idx===void 0)continue;let e=(t.get(n.tag)??0)+1;t.set(n.tag,e),n.attributes.__idx=e}}function Ne(e,t,n){if(e.banner===void 0)return;let{value:r,problems:i}=m(p,{banner:e.banner});for(let e of i)n?.warn(`${t}: ${e.message}`);return r.banner}function Pe(e,t){return Z(e)??ae(t)??void 0}function Z(e){let t=u(e.seo)?e.seo.title:void 0;return typeof t==`string`&&t.trim()!==``?t:void 0}function Q(e){let t=(e.split(`/`).pop()??e).replace(/\.[^.]+$/,``);return t===``?e:t}function Fe(e,t){let n=e.manifest.template;if(typeof n==`string`&&n.trim()!==``)return $(n,e.path,t.logger);let r=g(e.path,t.config.markdown?.template);return typeof r==`string`&&r.trim()!==``?$(r,`redocly.yaml`,t.logger):U}function $(e,t,n){if(!e.startsWith(`./`)&&!e.startsWith(`../`)&&!e.startsWith(`/`))return e;let r=f(e,t);return r===null?(n.warn(`Template reference "${e}" in ${t} escapes the content root; falling back to ${U}.`),U):`${me}${r}`}export{W as MARKDOC_DOCUMENT_LOADER_ID,ve as MARKDOC_SEARCH_GROUP,G as MARKDOC_SIDEBAR_ITEM_LOADER_ID,U as MARKDOC_TEMPLATE_ID,ye as markdocContentPlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EXECUTE_TOOL_NAME as e}from"../../constants.js";import{buildExecuteDescription as t}from"./prompts.js";const n=`Execute code`;function r(e){return e.readOnlyHint?`Query the docs with code`:n}const i={name:e,title:n,description:t(!1),schema:{type:`object`,required:[`code`,`description`],additionalProperties:!1,properties:{code:{type:`string`,description:`JavaScript to run in the sandbox. Return a value to receive it as the result.`,minLength:1},description:{type:`string`,description:`A short, human-readable summary of what this code does.`,minLength:1},sessionHandle:{type:`string`,description:`Handle returned by createAnonymousSession. Required when an API needs credentials. This parameter is only offered when createAnonymousSession is available, so pass it whenever you have called that tool.`,minLength:1}}},
|
|
1
|
+
import{EXECUTE_TOOL_NAME as e}from"../../constants.js";import{buildExecuteDescription as t}from"./prompts.js";const n=`Execute code`;function r(e){return e.readOnlyHint?`Query the docs with code`:n}const i={name:e,title:n,description:t(!1),schema:{type:`object`,required:[`code`,`description`],additionalProperties:!1,properties:{code:{type:`string`,description:`JavaScript to run in the sandbox. Return a value to receive it as the result.`,minLength:1},description:{type:`string`,description:`A short, human-readable summary of what this code does.`,minLength:1},sessionHandle:{type:`string`,description:`Handle returned by createAnonymousSession. Required when an API needs credentials. This parameter is only offered when createAnonymousSession is available, so pass it whenever you have called that tool.`,minLength:1}}}},a={result:{description:`The value the code returned, as JSON`},error:{type:`string`,description:`Why the code failed. Set only on a failed call`}},o={type:`array`,description:"Every `fetch` request that reached an API before the failure, with its status; running the code again sends them again. Set only on a failed call",items:{type:`object`,properties:{method:{type:`string`},url:{type:`string`},status:{type:`number`,description:`Unset when no response arrived`}}}};function s(e){return{type:`object`,properties:e?{...a,sentFetches:o}:a}}export{i as EXECUTE_TOOL_SCHEMA,s as executeOutputSchema,r as executeToolTitle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SystemRoute as e}from"../../../../../../server/constants/system-routes.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{secretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{
|
|
1
|
+
import{SystemRoute as e}from"../../../../../../server/constants/system-routes.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{secretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{buildAllowedOriginMatchers as g}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as _}from"./fetch/ssrf-guard.js";import{getDefaultAgent as v,readCappedBody as y}from"./fetch/fetch-bridge.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t;if(e.req.method===`GET`){let n=await h(t),i=e.req.query(`token`)??``,a=await s.peekElicitation(r,i);return a?R(a,t,n)??M({kv:r,site:n,token:i,target:a},{},200):L(n)}if(e.req.method===`POST`){let i=await h(t),o=await e.req.formData(),c=F(o,`token`),l=await s.peekElicitation(r,c);if(!l)return L(i);let u=R(l,t,i);if(u)return u;let d={kv:r,site:i,token:c,target:l,form:o,ctx:t};switch(F(o,`action`)){case n.remove:return O(d,k(l,F(o,`scheme`)));case n.removeAll:return O(d,a(l));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=a(t),s=i.map((e,t)=>F(n,o(`client_id`,t)).trim()),c=t=>M(e,{error:t,clientIds:s},400),l=T(i,n);if(`error`in l)return c(l.error);if(l.writes.length===0)return c(E(i));let u=[];for(let e of l.writes){if(e.kind!==`exchange`){u.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),c(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));u.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,u)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let s=F(t,o(`secret`,r)).trim();if(s){let t=i(a.auth,s);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,s)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let c=F(t,o(`client_id`,r)).trim(),l=F(t,o(`client_secret`,r)).trim();if(c&&l)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:c,clientSecret:l});else if(c||l)return{error:D(e,r,c?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{kv:n,target:r}=e,i=await s.getStoredSchemes(n,r.subject,r.api),a=t.filter(e=>i[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return a.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,a)}function k(e,t){let n=S.test(t)?a(e)[Number(t)]:void 0;return n?[n]:[]}async function A({kv:e,site:t,token:n}){return await s.consumeElicitation(e,n)?I(t,u(),200):L(t)}async function j({kv:e,site:t,token:n},r){let i=await s.consumeElicitation(e,n);if(!i)return L(t);for(let t of r)t.kind===`remove`?await s.deleteSecret(e,i.subject,i.api,t.scheme):await s.setSecret(e,i.subject,i.api,t.scheme,t.secret);let a=await s.getStoredSchemes(e,i.subject,i.api),o={action:r.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:r.map(e=>e.scheme),stored:Object.keys(a).sort()};return I(t,p(i,o),200)}async function M({kv:e,site:t,token:n,target:r},i,a){let o=await s.getStoredSchemes(e,r.subject,r.api);return I(t,l({site:t,target:r,token:n,stored:o,...i}),a)}async function N(e,t,n){try{let r=g([{url:e.tokenUrl}]),a=_(e.tokenUrl,r),o=new AbortController,s=setTimeout(()=>o.abort(),3e4),c;try{c=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:o.signal,dispatcher:v()})}finally{clearTimeout(s)}if(!c.ok)return P(`token endpoint returned ${c.status}`);let l;try{l=await y(c,65536)}catch{return P(`token response exceeded the size cap`)}let u;try{u=JSON.parse(l)}catch{return P(`token response was not valid JSON`)}let d=typeof u==`object`&&u&&`access_token`in u?u.access_token:void 0,f=typeof d==`string`?d.trim():``;return f?i(e,f)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${f}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(c(t,e),{status:n,headers:b})}function L(e){return I(e,d(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,f(o?.email),403);let c=`${t(e.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,m(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t,MCP_CREDENTIALS_ROUTE as n}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import{secretStore as i}from"./secret-store.js";import{operationsForScheme as a,orderedSchemesOf as o}from"./upstream-auth-scheme.js";import{CLIENT_CAPABILITIES_META_KEY as s,inputRequired as c,inputResponse as l}from"@modelcontextprotocol/server";const u=`credentials`,d=/* @__PURE__ */ new Map;function f(e,t){let n=d.get(e);if(n)return n;let r=t().finally(()=>{d.delete(e)});return d.set(e,r),r}function p(e){return!!(e.envelope?.[s])?.elicitation?.url}function m(e){return e.envelope!==void 0}function h(e){let t=l(e,u);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function g(e,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${e}" API.`,...n?[`The credentials page:`,n]:[],``,r?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${t}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
|
|
2
|
-
`)}async function _(e,{kv:t,subject:n,baseUrl:r,apis:a}){if(typeof e!=`string`)return;let o=await i.peekElicitation(t,e);if(o?.subject===n&&a.includes(o.api))return{apiName:o.name,url:
|
|
2
|
+
`)}async function _(e,{kv:t,subject:n,baseUrl:r,apis:a}){if(typeof e!=`string`)return;let o=await i.peekElicitation(t,e);if(o?.subject===n&&a.includes(o.api))return{apiName:o.name,url:A(r,e)}}function v(e,t){return Object.keys(e).length>1?t:void 0}async function y(e){let{token:t,url:n}=await w(e);return c({inputRequests:{[u]:c.elicitUrl({message:D(e),url:n})},requestState:t})}async function b(e){let{url:t}=await w(e);return j(e,t,E(e.subject))}function x(e,{schemeLabel:n,canManageCredentials:r}){let i=C(e);if(!e.sentScheme&&(e.status===401||!e.schemes))return[`The "${e.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,e.unsupportedSchemes?`Do not replace them. This operation accepts only ${e.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
|
|
3
|
+
`);if(e.status===403&&e.sentScheme)return[`The "${e.name}" API refused this operation with the stored ${n?`"${n}" `:``}credential (${i}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...r?[``,...S(e),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${t}\` with api: "${e.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
|
|
3
4
|
`);let a=e.status===401?`The "${e.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${e.name}" API rejected the request with ${i}.`;if(!r)return[a,``,e.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
|
|
4
|
-
`);let o=n?`api: "${e.api}" and scheme: "${n}"`:`api: "${e.api}"
|
|
5
|
-
`)}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function
|
|
5
|
+
`);let o=n?`api: "${e.api}" and scheme: "${n}"`:`api: "${e.api}"`;return[a,``,...S(e),`Do not retry the same call. Call \`${t}\` with ${o} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
|
|
6
|
+
`)}function S(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function C({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function w({kv:e,subject:t,baseUrl:n,target:r,auth:a,apiAuth:o}){let s=o?T(o):[],c=await i.createElicitation(e,{subject:t,api:r.api,name:r.name,scheme:r.scheme,schemeLabel:r.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?r.acceptedSchemes:void 0});return{token:c,url:A(n,c)}}function T(e){return o(e.schemes).map(t=>{let n=a(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function E(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function D({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=O(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${k(i)} needs credentials.${a} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function O({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function k(e){return e.charAt(0).toUpperCase()+e.slice(1)}function A(t,r){let i=new URL(e(n),t);return i.searchParams.set(`token`,r),i.toString()}function j({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
|
|
6
7
|
`)}export{u as CREDENTIALS_INPUT_REQUEST_KEY,_ as acceptedCredentialsLink,g as buildCredentialsAcceptedHint,x as buildCredentialsToolHint,b as buildUpstreamCredentialFallback,y as buildUpstreamCredentialInputRequired,h as credentialElicitationAnswer,f as dedupeElicitation,m as isStatelessRequest,v as schemeLabelOf,p as supportsUrlElicitation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=/\{(?<!\{[^}]*?\{)([^}]+)\}/g;function
|
|
1
|
+
const e=/\{(?<!\{[^}]*?\{)([^}]+)\}/g,t=/^([a-z][a-z0-9+.-]*):\/\//i,n=/[/?#]/,r=/:(\d+|\{[^}]+\})$/,i=/^\{([^}]+)\}$/,a=/^\d+$/,o={"http:":80,"https:":443};function s(e=[]){let t=[];for(let n of e)t.push(...l(n));return t}function c(e,t){return e.protocol===t.protocol&&e.ports.includes(t.port)&&e.hostname.test(t.hostname)}function l(e){let t=h(e.url);if(!t)return[];let n=u(t.host,e.variables),r=f(t,e.variables);if(!n||r.length===0)return[];let i=[{protocol:t.protocol,hostname:n,ports:r}];return t.protocol===`http:`&&r.includes(``)&&i.push({protocol:`https:`,hostname:n,ports:[``]}),i}function u(t,n){let r=``,i=0,a=!1;for(let o of t.matchAll(e)){let[e,s]=o,c=t.slice(i,o.index);c.includes(`.`)&&(a=!0),r+=g(c);let l=d(n?.[s]);l.guaranteesDot&&(a=!0),r+=l.pattern,i=o.index+e.length}let o=t.slice(i);return o.includes(`.`)&&(a=!0),r+=g(o),a?RegExp(`^${r}$`,`i`):null}function d(e){let t=e?.enum?.filter(Boolean);if(t&&t.length>0)return{pattern:`(?:${t.map(g).join(`|`)})`,guaranteesDot:t.every(e=>e.includes(`.`))};let n=e?.default?.split(`.`).slice(1).join(`.`);return n?{pattern:`[^.]+\\.${g(n)}`,guaranteesDot:!0}:{pattern:`[^.]+`,guaranteesDot:!1}}function f({protocol:e,port:t},n){let r=i.exec(t)?.[1],a=r?p(n?.[r]):[t];return[...new Set(a.flatMap(t=>m(e,t)))]}function p(e){let t=e?.enum?.filter(Boolean).map(String);return t&&t.length>0?t:e?.default?[String(e.default)]:[]}function m(e,t){if(t===``)return[``];if(!a.test(t))return[];let n=Number(t);return[n===o[e]?``:String(n)]}function h(e){if(!e)return null;let i=(t.exec(e)?.[1]??`https`).toLowerCase();if(i!==`http`&&i!==`https`)return null;let a=e.replace(t,``).split(n,1)[0];if(!a)return null;let o=a.includes(`@`)?a.slice(a.lastIndexOf(`@`)+1):a,s=r.exec(o),c=s?o.slice(0,s.index):o;return c?{protocol:`${i}:`,host:c,port:s?.[1]??``}:null}function g(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}export{s as buildAllowedOriginMatchers,c as matchesOrigin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as ee}from"../api-call-operations.js";import{GatewayFetchBlockedError as l,GatewayFetchSystemError as u,GatewayFetchUserError as d}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as f}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as p}from"undici";const m=`x-forwarded-for`,re=/%2f|%5c/i,h=/* @__PURE__ */ new Set([401,403,407]),g=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let _;function v(e){if(!_){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),_=new p({connect:{lookup:t({allowLoopback:n})}})}return _}function y({apis:e,onAuthRequired:t,sent:f,runEnded:p,logger:m,telemetry:g,fetchImpl:_=fetch,dispatcher:y=v(m),timeoutMs:b=3e4,deadline:T=1/0,maxResponseBytes:E=1048576,maxFetchesPerExec:D,beforeSend:ge,caller:O,allowedHttpMethods:k}){let A=e.flatMap(e=>e.matchers),_e=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),j=e.flatMap(e=>Object.values(e.secrets??{})),M=j.flatMap(a),ve=j.map(e=>e.header),N=e.flatMap(e=>e.credentialQueryParams??[]),P=0,F=!1;return async a=>{let v=c(a.method??`GET`),j=Date.now(),I,L,R,z={},B,V,H,U;try{if(D!==void 0){let e=Math.max(0,D);if(P+=1,P>e)throw new d(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(k&&!k.includes(v))throw new l(`${v} is not allowed: this project permits only ${k.join(`, `)} API calls`,ae(a.url));let o=ie(a.url,A,_e);if(I=o.hostname,L=te(o.pathname),re.test(o.pathname))throw new l(`${v} ${o.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,o.hostname);let c=e.filter(e=>e.matchers.some(e=>e.test(o.hostname))),u=c.flatMap(e=>e.operations?ee(e.operations,o.pathname,v).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),x=Math.min(...u.map(e=>e.variables)),C=u.filter(e=>e.variables===x);if(c.length>0&&(u.length===0||C.some(e=>!e.visible)))throw new l(`${v} ${o.pathname} is not a documented operation of ${c.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,o.hostname);let w=C.find(e=>!e.callable);if(w)throw new l(`${v} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let W=new Set(C.map(e=>e.api)).size===1?C[0].api:void 0;R=W?.slug;let G=de(a.securityScheme,W),K=G?[G]:W?le(W,o.pathname,v):void 0,q=W&&K?ue(W,K):void 0,J=q?W?.secrets?.[q]:void 0;z=me({callerHeaders:a.headers,secret:J,clientIp:O?.clientIp});let Y=fe(a.headers,o,c,J);if(Y&&(J||F))throw new d(pe(Y,!!J));if(T-Date.now()<=0)throw new d(`The execute time limit ended before this request was sent`);await ge?.(),F||=!!J,B=J?q:void 0;let X=new AbortController,ye=T-Date.now();if(U=ye<b?setTimeout(()=>X.abort(new d(`The request did not finish before the execute time limit`)),ye):setTimeout(()=>X.abort(),b),p?.aborted)throw new d(`The execute call had already answered, so this request was not sent`);H={method:v,url:i(o.origin+o.pathname,M)},f?.push(H);let Z=await _(o,{method:v,headers:z,body:a.body,redirect:`manual`,signal:X.signal,dispatcher:y});V=Z.status,H.status=Z.status;let Q=``;try{Q=await ce(Z,E)}finally{if(h.has(Z.status)&&W&&t){let e={api:W.slug,name:W.name,status:Z.status};q&&(e.scheme=q),K?.length&&(e.schemes=[...K]),B&&(e.sentScheme=B);let n=ne(Q,Z.headers.get(`content-type`),M);n&&(e.detail=n),t(e)}}let $=r(he(Z.headers),M);if(oe(Z.status)){$=n($,ve);let{location:e}=$;e&&!se(e,o,A)&&delete $.location}let be=S(Z.status);return g?.gatewayFetchPerformed({host:o.hostname,method:v,outcome:be,durationMs:Date.now()-j,path:L,api:R,status:Z.status,bytes:Buffer.byteLength(Q,`utf8`),injectedScheme:B}),s(m,{rawUrl:o.href,method:v,host:o.hostname,outcome:be,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:L,api:R,status:Z.status,injectedScheme:B,requestHeaders:z,requestBody:a.body,responseHeaders:$,responseBody:Q,caller:O}),{status:Z.status,statusText:i(Z.statusText,M),ok:Z.ok,headers:$,bodyText:i(Q,M)}}catch(e){H&&f&&x(e)&&f.splice(f.indexOf(H),1);let{outcome:t,userSafe:n}=C(e,V),r=I??(n instanceof l?n.host:void 0)??ae(a.url)??`invalid-url`;throw g?.gatewayFetchPerformed({host:r,method:v,outcome:t,durationMs:Date.now()-j,path:L,api:R,status:V,injectedScheme:B}),s(m,{rawUrl:a.url,method:v,host:r,outcome:t,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:L,api:R,status:V,injectedScheme:B,requestHeaders:z,requestBody:a.body,caller:O}),n||(m?.error(`Gateway MCP fetch failed [${v} ${r}]: ${i(w(e),M)} headers=${o(z)}`),new u(`Upstream fetch failed due to an internal error`))}finally{U!==void 0&&clearTimeout(U)}}}function b(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof d||n instanceof e)return n;n=n.cause}}function x(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function S(e){return h.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function C(t,n){let r=b(t),i=n===void 0?void 0:S(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof l||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function ie(e,t,n){try{return f(e,t)}catch(e){throw e instanceof l&&n?new l(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function ae(e){try{return new URL(e).hostname||void 0}catch{return}}function oe(e){return e>=300&&e<400}function se(e,t,n){try{return!!f(new URL(e,t).href,n)}catch{return!1}}function w(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function ce(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw T(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw T(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function T(e,t){return new d(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function le(e,t,n){let r=e.routes?.find(e=>e.method===n&&e.pattern.test(t));return r?r.schemes:E(e)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new d(`securityScheme must be a security scheme name (a string)`);if(!t)throw new d(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new d(`Unknown securityScheme "${e}" for ${t.name}; valid values: ${n.join(`, `)}`);return e}function E(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function fe(e,t,n,r){let i=D([...g,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=D(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function D(e){return new Set(e.map(e=>e.toLowerCase()))}function pe({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function me({callerHeaders:e,secret:t,clientIp:n}){let r={};for(let[t,n]of Object.entries(e??{})){let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==m&&(r[t]=n)}return n&&(r[m]=n),t&&(r[t.header]=t.value),r}function he(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{y as buildFetchBridge,v as getDefaultAgent,ce as readCappedBody};
|
|
1
|
+
import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as l}from"../api-call-operations.js";import{matchesOrigin as ee}from"./allowed-hosts.js";import{GatewayFetchBlockedError as u,GatewayFetchHostNotAllowedError as d,GatewayFetchSystemError as f,GatewayFetchUserError as p}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as m}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as h}from"undici";const g=`x-forwarded-for`,re=/%2f|%5c/i,_=/* @__PURE__ */ new Set([401,403,407]),ie=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let v;function y(e){if(!v){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),v=new h({connect:{lookup:t({allowLoopback:n})}})}return v}function b({apis:e,onAuthRequired:t,sent:d,runEnded:m,logger:h,telemetry:g,fetchImpl:ie=fetch,dispatcher:v=y(h),timeoutMs:b=3e4,deadline:S=1/0,maxResponseBytes:D=1048576,maxFetchesPerExec:O,beforeSend:_e,caller:k,allowedHttpMethods:A}){let j=e.flatMap(e=>e.matchers),ve=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),M=e.flatMap(e=>Object.values(e.secrets??{})),N=M.flatMap(a),ye=M.map(e=>e.header),P=e.flatMap(e=>e.credentialQueryParams??[]),F=0,I=!1;return async a=>{let y=c(a.method??`GET`),M=Date.now(),L,R,z,B={},V,H,U,W,G=!1;try{if(O!==void 0){let e=Math.max(0,O);if(F+=1,F>e)throw new p(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(A&&!A.includes(y))throw new u(`${y} is not allowed: this project permits only ${A.join(`, `)} API calls`,T(a.url));let o=oe(a.url,j,ve);if(L=o.hostname,R=te(o.pathname),re.test(o.pathname))throw new u(`${y} ${o.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,o.hostname);let c=e.filter(e=>e.matchers.some(e=>ee(e,o))),f=c.flatMap(e=>e.operations?l(e.operations,o.pathname,y).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),x=Math.min(...f.map(e=>e.variables)),C=f.filter(e=>e.variables===x);if(c.length>0&&(f.length===0||C.some(e=>!e.visible)))throw new u(`${y} ${o.pathname} is not a documented operation of ${c.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,o.hostname);let w=C.find(e=>!e.callable);if(w)throw new u(`${y} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let E=new Set(C.map(e=>e.api)).size===1?C[0].api:void 0;z=E?.slug;let K=E?.routes?.find(e=>e.method===y&&e.pattern.test(o.pathname));if(K?.unsupportedSchemes&&a.securityScheme!=null)throw new p(`${y} ${o.pathname} accepts only ${K.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Call it without securityScheme, and do not replace the stored credentials.`);let be=de(a.securityScheme,E),q=be?[be]:E?K?.schemes??fe(E):void 0,J=E&&q?ue(E,q):void 0,Y=J?E?.secrets?.[J]:void 0;if((y===`GET`||y===`HEAD`)&&a.body!==void 0)throw new p(`A ${y} request cannot have a body; remove \`body\``);B=he({callerHeaders:a.headers,secret:Y,clientIp:k?.clientIp});let xe=pe(a.headers,o,c,Y);if(xe&&(Y||I))throw new p(me(xe,!!Y));if(S-Date.now()<=0)throw new p(`The execute time limit ended before this request was sent`);await _e?.(),I||=!!Y,V=Y?J:void 0;let X=new AbortController,Se=S-Date.now();if(W=Se<b?setTimeout(()=>X.abort(new p(`The request did not finish before the execute time limit`)),Se):setTimeout(()=>{G=!0,X.abort()},b),m?.aborted)throw new p(`The execute call had already answered, so this request was not sent`);U={method:y,url:i(o.origin+o.pathname,N)},d?.push(U);let Z=await ie(o,{method:y,headers:B,body:a.body,redirect:`manual`,signal:X.signal,dispatcher:v});H=Z.status,U.status=Z.status;let Q=``;try{Q=await le(Z,D)}finally{if(_.has(Z.status)&&E&&t){let e={api:E.slug,name:E.name,status:Z.status};J&&(e.scheme=J),q?.length&&(e.schemes=[...q]),V&&(e.sentScheme=V),K?.unsupportedSchemes&&(e.unsupportedSchemes=[...K.unsupportedSchemes]);let n=ne(Q,Z.headers.get(`content-type`),N);n&&(e.detail=n),t(e)}}let $=r(ge(Z.headers),N);if(se(Z.status)){$=n($,ye);let{location:e}=$;e&&!ce(e,o,j)&&delete $.location}let Ce=ae(Z.status);return g?.gatewayFetchPerformed({host:o.hostname,method:y,outcome:Ce,durationMs:Date.now()-M,path:R,api:z,status:Z.status,bytes:Buffer.byteLength(Q,`utf8`),injectedScheme:V}),s(h,{rawUrl:o.href,method:y,host:o.hostname,outcome:Ce,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:R,api:z,status:Z.status,injectedScheme:V,requestHeaders:B,requestBody:a.body,responseHeaders:$,responseBody:Q,caller:k}),{status:Z.status,statusText:i(Z.statusText,N),ok:Z.ok,headers:$,bodyText:i(Q,N)}}catch(e){let t=U!==void 0&&C(e);t&&U&&d&&d.splice(d.indexOf(U),1);let{outcome:n,userSafe:r}=w(e,H),c=L??(r instanceof u?r.host:void 0)??T(a.url)??`invalid-url`;if(g?.gatewayFetchPerformed({host:c,method:y,outcome:n,durationMs:Date.now()-M,path:R,api:z,status:H,injectedScheme:V}),s(h,{rawUrl:a.url,method:y,host:c,outcome:n,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:R,api:z,status:H,injectedScheme:V,requestHeaders:B,requestBody:a.body,caller:k}),r)throw r;let l=G?{reason:`timeout after ${b} ms`,message:H===void 0?`The API did not answer within ${b/1e3} s`:`The API did not finish its answer within ${b/1e3} s`}:t?{reason:`connect failure ${x(e)??`without a code`}`,message:`Could not connect to ${c}`}:{reason:E(e),message:`Upstream fetch failed due to an internal error`};throw h?.error(`Gateway MCP fetch failed [${y} ${c}]: ${i(l.reason,N)} headers=${o(B)}`),new f(l.message)}finally{W!==void 0&&clearTimeout(W)}}}function x(e){let t=e;for(let e=0;e<5&&t instanceof Error;e++){if(`code`in t&&typeof t.code==`string`)return t.code;if(t instanceof AggregateError)return t.errors.map(x).find(e=>e!==void 0);t=t.cause}}function S(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof p||n instanceof e)return n;n=n.cause}}function C(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;if(n instanceof AggregateError)return n.errors.some(C);let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function ae(e){return _.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function w(t,n){let r=S(t),i=n===void 0?void 0:ae(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof u||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function oe(e,t,n){try{return m(e,t)}catch(e){throw e instanceof d&&n?new u(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function T(e){try{return new URL(e).hostname||void 0}catch{return}}function se(e){return e>=300&&e<400}function ce(e,t,n){try{return!!m(new URL(e,t).href,n)}catch{return!1}}function E(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function le(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw D(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw D(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function D(e,t){return new p(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new p(`securityScheme must be a security scheme name (a string)`);if(!t)throw new p(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new p(`This site cannot send securityScheme "${e}" to ${t.name}; valid values: ${n.join(`, `)}`);return e}function fe(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function pe(e,t,n,r){let i=O([...ie,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=O(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function O(e){return new Set(e.map(e=>e.toLowerCase()))}function me({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function he({callerHeaders:e,secret:t,clientIp:n}){let r={},i=new Headers;for(let[t,n]of Object.entries(e??{})){try{i.append(t,n)}catch{throw new p(`The "${t}" header is invalid: a header name must be a token and a value must hold no line breaks or characters above U+00FF`)}let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==g&&(r[t]=n)}return n&&(r[g]=n),t&&(r[t.header]=t.value),r}function ge(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{b as buildFetchBridge,y as getDefaultAgent,le as readCappedBody};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e){super(e),this.name=`GatewayFetchUserError`}},t=class extends e{host;constructor(e,t){super(e),this.name=`GatewayFetchBlockedError`,this.host=t}},n=class extends Error{constructor(e){super(e),this.name=`GatewayFetchSystemError`}};export{t as GatewayFetchBlockedError,n as GatewayFetchSystemError,e as GatewayFetchUserError};
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`GatewayFetchUserError`}},t=class extends e{host;constructor(e,t){super(e),this.name=`GatewayFetchBlockedError`,this.host=t}},n=class extends t{constructor(e){super(`Host "${e}" is not allowed`,e),this.name=`GatewayFetchHostNotAllowedError`}},r=class extends Error{constructor(e){super(e),this.name=`GatewayFetchSystemError`}};export{t as GatewayFetchBlockedError,n as GatewayFetchHostNotAllowedError,r as GatewayFetchSystemError,e as GatewayFetchUserError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isBlockedIp as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{
|
|
1
|
+
import{isBlockedIp as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{matchesOrigin as t}from"./allowed-hosts.js";import{GatewayFetchBlockedError as n,GatewayFetchHostNotAllowedError as r,GatewayFetchUserError as i}from"./fetch-errors.js";import{findUnresolvedPlaceholders as a,unresolvedPlaceholderMessage as o}from"./url-placeholders.js";import{isIP as s}from"node:net";function c(e,s){let c;try{c=new URL(e)}catch{throw new i(`Invalid URL: ${e}`)}if(c.protocol!==`http:`&&c.protocol!==`https:`)throw new i(`Only http(s) URLs are allowed, got ${c.protocol}`);if(c.username||c.password)throw new i(`URLs must not contain embedded credentials`);let f=a(c.hostname);if(f.length>0)throw new i(o(f));let p=d(c.hostname),m=l(p)?[]:s.filter(e=>e.hostname.test(p));if(m.length===0)throw new r(p);if(!m.some(e=>t(e,c))){let e=u(c.hostname,m);throw new n(`Origin "${c.origin}" is not allowed; use the documented ${e.length===1?`origin`:`origins`} of ${p}: ${e.join(`, `)}`,p)}let h=a(c.pathname);if(h.length>0)throw new i(o(h));return c}function l(t){let n=d(t.toLowerCase()).split(`%`)[0];return n===`localhost`||n.endsWith(`.localhost`)?!0:s(n)!==0&&e(n)}function u(e,t){let n=t.flatMap(({protocol:t,ports:n})=>n.map(n=>`${t}//${e}${n?`:${n}`:``}`));return[...new Set(n)]}function d(e){return e.replace(/^\[|\]$/g,``)}export{c as assertUrlAllowed,l as isBlockedAddress};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t}from"../../constants.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{formatError as r}from"../tool-errors.js";import{callAttribution as i}from"../audit.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as o}from"../codemode/constants.js";import{resolveSecretSubject as s}from"./subject.js";import{ipRateLimitKey as c}from"../rate-limit.js";import{callableApis as l,excludedOperations as u}from"./eligibility.js";import{getAllowedHttpMethods as d}from"./allowed-http-methods.js";import{apiCallOperationsOf as f}from"./api-call-operations.js";import{secretStore as p}from"./secret-store.js";import{
|
|
1
|
+
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t}from"../../constants.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{formatError as r}from"../tool-errors.js";import{callAttribution as i}from"../audit.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as o}from"../codemode/constants.js";import{resolveSecretSubject as s}from"./subject.js";import{ipRateLimitKey as c}from"../rate-limit.js";import{callableApis as l,excludedOperations as u}from"./eligibility.js";import{getAllowedHttpMethods as d}from"./allowed-http-methods.js";import{apiCallOperationsOf as f}from"./api-call-operations.js";import{secretStore as p}from"./secret-store.js";import{buildAllowedOriginMatchers as m}from"./fetch/allowed-hosts.js";import{GatewayFetchUserError as h}from"./fetch/fetch-errors.js";import{buildFetchBridge as g}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as _,orderedSchemesOf as v,resolveUpstreamApiAuth as y}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as b,buildCredentialsAcceptedHint as x,buildCredentialsToolHint as S,buildUpstreamCredentialFallback as C,buildUpstreamCredentialInputRequired as w,credentialElicitationAnswer as T,dedupeElicitation as E,isStatelessRequest as D,schemeLabelOf as O,supportsUrlElicitation as k}from"./elicitation.js";import{applyFetchCount as A}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as j,upstreamAuthKey as M}from"./upstream-auth.js";import{createAnonymousSessionTool as N,manageApiCredentialsTool as P,removeApiCredentialsTool as F}from"./tools.js";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(){return[N,P,F]}function R(e){return new Map(e.map(e=>[e.relativePath,y(e)]))}function z(e,t,n,r,a,o,s){return g({apis:t.map(t=>{let i=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:m(t.servers),secrets:r?.[t.relativePath],defaultScheme:i.defaultScheme,routes:i.routes,credentialHeaders:_(i.schemes),credentialQueryParams:i.credentialQueryParams,schemePriority:v(i.schemes),operations:f(t.fullDefinition,t.definition,t.servers,u(e,t.relativePath))}}),onAuthRequired:a,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:i(e),allowedHttpMethods:d(e.config.mcp)})}function B(e){let{callerSubject:t,clientIp:n}=i(e),r={subject:t,ip:n&&c(n)};return async()=>{let t=await A(e.kv,r,o,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new h(t.message)}}async function V(e,t){if(t)try{return await p.getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${r(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:e,sessionHandle:n,serverContext:r,run:i},o){let c=s(e,n);if(c.kind===`invalid`)return{content:[{type:`text`,text:c.message}],isError:!0};let u=c.kind===`resolved`?c.subject:void 0,[d,f]=await Promise.all([l(e),V(e,u)]),p=R(d),m=[],h=new AbortController,g=await i(z(e,d,p,f,e=>m.push(e),o,h.signal)).finally(()=>h.abort());if(m.length===0)return g;let _=j(m).map(e=>q(e,p));if(c.kind===`anonymous`)return _.some(e=>e.schemes)?K(g,[{type:`text`,text:c.message}]):K(g,[{type:`text`,text:Z(_,{plans:p,canManageCredentials:!1})},...g.content]);let v=D(r.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${v?`2026-07-28`:`2025`} urlElicitation=${k(r.mcpReq)}`);let y={ctx:e,serverContext:r,subject:c.subject,stored:J(f),plans:p,canManageCredentials:!a(t,e.metadata)},b=v?await $(y,_,!o.some(W)):await ee(y,_);switch(b.kind){case`inputRequired`:return b.result;case`prependText`:return K(g,[{type:`text`,text:b.text},...g.content]);case`none`:return g}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(t,n){if(!t.isError||n.length===0)return t;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
|
|
2
2
|
`+r.map(e=>`${e.method} ${e.url} -> ${e.status??`no response`}`).join(`
|
|
3
|
-
`);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(M({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!t.has(M(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?O(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>S(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
|
|
3
|
+
`);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(M({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(M(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?O(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>S(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
|
|
4
4
|
|
|
5
5
|
`)}function Q({ctx:e,subject:t,plans:r},i){let[a,...o]=i,s=r.get(a.api),c=a.scheme??s.defaultScheme,l=a.schemes&&a.schemes.length>1?a.schemes:void 0;return{subject:t,baseUrl:n(e.request),target:{api:a.api,name:a.name,scheme:c,schemeLabel:l?void 0:X(a,r),acceptedSchemes:l},auth:s.schemes[c]??{kind:`raw`},apiAuth:s,kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:a.status,detail:a.detail,otherApiNames:o.map(e=>e.name)}}}async function $(e,t,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=T(a.mcpReq.inputResponses);if(l===`declined`)return{kind:`none`};let u=t.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(t,e)};if(l===`accepted`){let e=await b(a.mcpReq.requestState(),{kv:i.kv,subject:o,baseUrl:n(i.request),apis:u.map(e=>e.api)}),t=e?.apiName??u[0].name;return{kind:`prependText`,text:x(t,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!k(a.mcpReq)?{kind:`prependText`,text:await C(d)}:{kind:`inputRequired`,result:await w(d)}}async function ee(e,t){let n=t.filter(t=>Y(t,e.stored));if(n.length===0)return{kind:`prependText`,text:Z(t,e)};let r=Q(e,n);return{kind:`prependText`,text:await E(`${e.subject}:${M(n[0])}`,()=>C(r))}}export{L as gatewayTools,H as runExecuteWithGateway};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{OPERATION_METHODS as e}from"../tools/openapi-document.js";import{basePathPrefix as t,operationHttpMethod as n,pathPattern as r}from"./route-pattern.js";const
|
|
2
|
-
`)[0].trim();a&&(n[r]=a.slice(0,120))}return n}function
|
|
1
|
+
import{OPERATION_METHODS as e}from"../tools/openapi-document.js";import{basePathPrefix as t,operationHttpMethod as n,pathPattern as r,pathVariableCount as i}from"./route-pattern.js";const a=`default`,o={kind:`raw`},s=[`oauth2ClientCredentials`,`bearer`,`apiKey`,`cookie`,`raw`],c=new Set(e);function l(){return{schemes:{[a]:o},defaultScheme:a,routes:[],credentialQueryParams:[]}}function u(e){let{definition:t,servers:n}=e,r=_(t),i=Object.keys(r),a=d(t);if(i.length===0)return{...l(),credentialQueryParams:a};let o={schemes:r,defaultScheme:b(t.security,r)[0]??y(i,r)[0],routes:x(t,r,n),credentialQueryParams:a},s=g(t,i);return Object.keys(s).length>0&&(o.descriptions=s),o}function d(e){let t=/* @__PURE__ */ new Set;for(let n of Object.values(e.components?.securitySchemes??{}))S(n)&&n.type===`apiKey`&&n.in===`query`&&n.name&&t.add(n.name);return[...t]}function f(e){return[...new Set(Object.values(e).map(h))]}function p(e){return y(Object.keys(e),e)}function m(e,t){let n=/* @__PURE__ */ new Set;for(let r of e.routes)r.schemes?.includes(t)&&n.add(`${r.method} ${r.path}`);return[...n]}function h(e){return e.kind===`apiKey`?e.header:e.kind===`cookie`?`Cookie`:`Authorization`}function g(e,t){let n={};for(let r of t){let t=e.components?.securitySchemes?.[r],i=S(t)?t.description:void 0;if(typeof i!=`string`)continue;let a=i.split(`
|
|
2
|
+
`)[0].trim();a&&(n[r]=a.slice(0,120))}return n}function _(e){let t={};for(let[n,r]of Object.entries(e.components?.securitySchemes??{})){if(!S(r))continue;let e=v(r);e&&(t[n]=e)}return t}function v(e){if(e.type===`oauth2`){let t=e.flows?.clientCredentials;return t?{kind:`oauth2ClientCredentials`,tokenUrl:t.tokenUrl,scopes:Object.keys(t.scopes??{})}:{kind:`bearer`}}if(e.type===`openIdConnect`||e.type===`http`&&e.scheme?.toLowerCase()===`bearer`)return{kind:`bearer`};if(e.type===`apiKey`&&e.in===`header`)return{kind:`apiKey`,header:e.name||`X-Api-Key`};if(e.type===`apiKey`&&e.in===`cookie`&&e.name)return{kind:`cookie`,name:e.name}}function y(e,t){return[...e].sort((n,r)=>s.indexOf(t[n].kind)-s.indexOf(t[r].kind)||e.indexOf(n)-e.indexOf(r))}function b(e,t){let n=[];for(let r of e??[])for(let e of Object.keys(r))t[e]&&!n.includes(e)&&n.push(e);return n}function x(e,a,o){let s=t(o),l=[];for(let[t,i]of Object.entries(e.paths??{})){if(!i||typeof i!=`object`)continue;let o=r(s,t);if(o)for(let[r,s]of Object.entries(i)){if(!c.has(r.toLowerCase()))continue;let i=s?.security??e.security,u={pattern:o,path:t,method:n(r)};if(l.push(u),i===void 0)continue;let d=b(i,a);u.schemes=y(d,a);let f=i.map(e=>Object.keys(e)),p=d.length===0&&f.every(e=>e.length>0)?[...new Set(f.flat())]:[];p.length>0&&(u.unsupportedSchemes=p)}}return l.sort((e,t)=>i(e.path)-i(t.path))}function S(e){return typeof e==`object`&&!!e&&`type`in e}export{a as DEFAULT_SCHEME_NAME,f as credentialHeadersOf,m as operationsForScheme,p as orderedSchemesOf,u as resolveUpstreamApiAuth};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r}from"../constants.js";import{formatError as i}from"./tool-errors.js";import{auditToolCall as a,callAttribution as o}from"./audit.js";import{CODE_MODE_TOOL_NAMES as s,FETCH_TOOL_NAME as c}from"./codemode/constants.js";import{resolveMcpMode as l,resolveRequestMcpMode as u}from"./mode.js";import{sendMcpRequestError as d}from"./mcp-telemetry.js";import{availableTools as f,isToolAvailable as p,normalizeToolDisplayName as m}from"./tool-registry.js";import{mcpJsonSchemaValidator as h}from"./json-schema-validator.js";import{toToolListEntries as g}from"./codemode/tool-list.js";import{buildCodeModeInstructions as _,buildExecuteDescription as v,buildToolsModeInstructions as y}from"./codemode/prompts.js";import{composeExecuteAnnotations as b,getActiveCapabilities as x}from"./codemode/capabilities.js";import{discover as S,discoverSchema as C}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as w,executeToolTitle as
|
|
1
|
+
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r}from"../constants.js";import{formatError as i}from"./tool-errors.js";import{auditToolCall as a,callAttribution as o}from"./audit.js";import{CODE_MODE_TOOL_NAMES as s,FETCH_TOOL_NAME as c}from"./codemode/constants.js";import{resolveMcpMode as l,resolveRequestMcpMode as u}from"./mode.js";import{sendMcpRequestError as d}from"./mcp-telemetry.js";import{availableTools as f,isToolAvailable as p,normalizeToolDisplayName as m}from"./tool-registry.js";import{mcpJsonSchemaValidator as h}from"./json-schema-validator.js";import{toToolListEntries as g}from"./codemode/tool-list.js";import{buildCodeModeInstructions as _,buildExecuteDescription as v,buildToolsModeInstructions as y}from"./codemode/prompts.js";import{composeExecuteAnnotations as b,getActiveCapabilities as x}from"./codemode/capabilities.js";import{discover as S,discoverSchema as C}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as w,executeOutputSchema as T,executeToolTitle as E}from"./codemode/execute-schema.js";import{runCodeMode as D}from"./codemode/index.js";import{docsServerInfo as O}from"./server-info.js";import{loadSkillResources as k}from"./skills-resources.js";import{randomUUID as A}from"node:crypto";import{McpServer as j,createMcpHandler as M,fromJsonSchema as N,isCallToolResult as P,isInputRequiredResult as F}from"@modelcontextprotocol/server";const I=`text/markdown`,L={listChanged:!1};function R(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a}=m(e);return{title:t,description:n,inputSchema:N(r,h),outputSchema:i?N(i,h):void 0,annotations:a}}function z(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function B(t,n){if(P(t)||F(t))return t;let r=[{type:`text`,text:typeof t==`string`?t:JSON.stringify(t)}];return n===`code`&&e(t)?{content:r,structuredContent:t}:{content:r}}function V(e,t){return(n,r)=>a(e,t.schema.name,n,async()=>B(await t.execute(n,e,r),e.mcpMode))}function H(e,t){return new j(e,{capabilities:{logging:{},tools:L},maxToolInputElements:1e4,instructions:t})}async function U(e,i,o){let[l,u]=await Promise.all([f(o,i),x(i)]),d=u.some(e=>e.id===c),m=l.filter(e=>!s.has(e.schema.name)).map(e=>e.schema),h=l.filter(({schema:e})=>s.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),y=i.instructionsStyle!==`brief`,O=y?g(m,u):[],k=h.some(e=>e.schema.name===t),A=H(e,_(d,O,e.websiteUrl)),j=b(m,u,i.config.mcp);A.registerTool(r,R({...z(k,w),title:E(j),description:v(d,O,e.websiteUrl),outputSchema:T(d),annotations:j}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,s=t=>a(i,r,e,()=>D({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:o,ctx:i,hostFetch:t}));if(!d)return s();let{runExecuteWithGateway:c}=await import(`./gateway/index.js`);return c({ctx:i,sessionHandle:n,serverContext:t,run:s})});let M=S(m,async e=>{let t=o.get(e);return t!==void 0&&await p(t,i)},u,i);A.registerTool(n,R(C(m,u,y)),e=>a(i,n,e,()=>M(e)));for(let e of h)A.registerTool(e.schema.name,R(z(k,e.schema)),V(i,e));return A}async function W(e,t,n){let r=new Map((await f(n,t)).map(e=>[e.schema.name,e])),i=H(e,y(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,R({...n.schema,outputSchema:void 0}),V(t,n));r.has(n.schema.name)||a.disable()}return i}async function G(e,t,n){let r=O(e.config,e.request),i=e.mcpMode===`code`?await U(r,e,t):await W(r,e,t);n.length>0&&i.server.registerCapabilities({resources:L});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:I},async()=>({contents:[{uri:e.uri,mimeType:I,text:await e.read()}]}));return i}function K(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function q(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function J(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await k(n),i=await G(n,e.registry,r),a=M(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),K(o)}catch(r){if(e.onError)await e.onError(r);else{let a=n?o(n):{requestId:A()};e.logger?.error(`MCP request failed: ${i(r)}`,{request_id:a.requestId}),await d(r,u(t.url,l()),{logger:e.logger,caller:a})}return q()}}}export{J as createMcpRequestHandler,R as toRegisterToolConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r={ratePerMin:600,quotaPerDay:2e4},
|
|
1
|
+
import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r=86400,i={ratePerMin:600,quotaPerDay:2e4},a={ratePerMin:60,quotaPerDay:2e3},o={ratePerMin:60,quotaPerDay:2e3};function s(e,t){return e!==void 0&&/^[1-9]\d*$/.test(e)?Number(e):t}function c(e){return e===`oauth`?a:e===`card`?o:{ratePerMin:s(process.env.MCP_RATE_LIMIT_PER_MINUTE,i.ratePerMin),quotaPerDay:s(process.env.MCP_RATE_LIMIT_PER_DAY,i.quotaPerDay)}}const l={rate:`minute`,quota:`day`};function u(t){if(n(t)!==6)return t;let r=e(t);if(r)return r;let[i,a=``]=t.split(`%`)[0].split(`::`),o=i?i.split(`:`):[],s=a?a.split(`:`):[],c=8-o.length-s.length;return`${[...o,...Array(Math.max(0,c)).fill(`0`),...s].slice(0,4).map(e=>parseInt(e||`0`,16).toString(16)).join(`:`)}::/64`}const d=[{scope:`rate`,seconds:60},{scope:`quota`,seconds:r}];function f(e,t){return e===`mcp`?[`mcp`,`request-rl`,t]:[`mcp`,`request-rl`,e,t]}async function p(e){let{kv:t,bucket:n}=e,i=e.limits??c(n),a=Math.floor((e.now??Date.now())/1e3),o=f(n,u(e.ip)),s=await t.get(o),l={};for(let{scope:e,seconds:t}of d){let n=Math.floor(a/t),r=s?.[e],o=r?.id===n?r.count:0;if(o>=(e===`rate`?i.ratePerMin:i.quotaPerDay))return{limited:!0,scope:e,retryAfterSeconds:Math.max(1,(n+1)*t-a)};l[e]={id:n,count:o+1}}return await t.set(o,l,{ttlInSeconds:r}),{limited:!1}}function m(e,t){let n={jsonrpc:`2.0`,error:{code:-32029,message:`Rate limit exceeded (${e.scope}); retry after ${e.retryAfterSeconds}s`},id:null};return new Response(JSON.stringify(n),{status:429,headers:{...t,"Content-Type":`application/json`,"Cache-Control":`no-store`,"Retry-After":String(e.retryAfterSeconds)}})}async function h(e){if(!e.ip)return;let{bucket:n,logger:r}=e,i=c(n),a;try{a=await p({kv:e.kv,ip:e.ip,bucket:n,now:e.now,limits:i})}catch(e){r?.warn(`MCP rate-limit store error, failing open: ${String(e)}`);return}if(a.limited)return r?.warn(`MCP rate limit exceeded (${n}, ${l[a.scope]})`),await t({scope:a.scope,retryAfterSeconds:a.retryAfterSeconds,limit:a.scope===`rate`?i.ratePerMin:i.quotaPerDay},{logger:r,caller:{clientIp:e.ip}}),m(a,e.headers??{})}export{h as applyMcpRateLimit,p as checkMcpRateLimit,u as ipRateLimitKey};
|