@redocly/framework 1.0.0-next.13 → 1.0.0-next.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/dist/bundler/build/output-metadata.js +1 -1
- package/dist/bundler/build/run.js +1 -1
- package/dist/cli/args.js +1 -1
- package/dist/cli/validate-react-pages.js +1 -1
- package/dist/content-layer/database/files.js +1 -1
- package/dist/content-layer/database/finalize.js +1 -1
- package/dist/content-layer/database/origins.js +1 -1
- package/dist/content-layer/ingest/finalize-phase.js +1 -1
- package/dist/content-layer/ingest/markdoc-schema-problem.js +1 -1
- package/dist/content-layer/ingest/run.js +1 -1
- package/dist/content-layer/ingest/search-sync.js +1 -1
- package/dist/content-layer/ingest/sync.js +1 -1
- package/dist/content-layer/link-checker/delta.js +1 -1
- package/dist/content-layer/link-checker/run-build.js +1 -1
- package/dist/content-layer/loaders/context.js +1 -1
- package/dist/content-layer/markdown/resolve/ast.d.ts +2 -0
- package/dist/content-layer/markdown/resolve/ast.js +1 -1
- package/dist/content-layer/markdown/search/to-markdown.js +1 -1
- package/dist/content-layer/markdown/utils/parse-cache.d.ts +5 -1
- package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
- package/dist/content-layer/materialization/entity.js +1 -1
- package/dist/content-layer/materialization/static-files.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/build-definition.d.ts +2 -1
- package/dist/content-layer/plugins/internal/api-docs/server/build-definition.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/agent-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/auth.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/custom-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/mcp-telemetry.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/client-metadata.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/skills-resources.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +2 -2
- package/dist/content-layer/plugins/internal/skills/server/routes.js +1 -1
- package/dist/content-layer/server/database.js +1 -1
- package/dist/content-layer/static/registry.js +1 -1
- package/dist/server/app.js +2 -2
- package/dist/server/ask-ai/feature-gate.js +1 -1
- package/dist/server/content.js +5 -5
- package/dist/server/page-handlers.js +2 -2
- package/dist/server/search/route.js +1 -1
- package/dist/server/static-files/serve.js +1 -1
- package/dist/server/subprocess/child-entry.js +1 -1
- package/dist/server/subprocess/host.js +1 -1
- package/package.json +3 -4
|
@@ -11,5 +11,5 @@ import{headingSlugger as e}from"../utils/heading-slugger.js";import{getInnerText
|
|
|
11
11
|
`)}\n\n`);return;case`strong`:t.push(`**${h(e.children,n)}**`);return;case`em`:t.push(`_${h(e.children,n)}_`);return;case`s`:t.push(`~~${h(e.children,n)}~~`);return;case`link`:{let i=typeof r.href==`string`?r.href:``;t.push(`[${h(e.children,n)}](${i})`);return}case`image`:{let e=typeof r.src==`string`?r.src:``,n=typeof r.alt==`string`?r.alt:``;t.push(``);return}case`list`:{let i=r.ordered===!0,a={...n,listDepth:n.listDepth+1,ordered:i,index:0};n.listDepth>0&&t.push(`
|
|
12
12
|
`);for(let n of e.children??[])g(n,t,a);n.listDepth===0&&t.push(`
|
|
13
13
|
`);return}case`item`:{n.index+=1;let r=n.ordered?`${n.index}.`:`-`,i=` `.repeat(Math.max(n.listDepth-1,0)),a=h(e.children,{...n,listDepth:n.listDepth,index:0});t.push(`${i}${r} ${a.split(`
|
|
14
|
-
`).join(`\n${i} `)}\n`);return}case`table`:t.push(`\n${_(e,n)}\n`);return;case`tag`:{let i=(e.tag===void 0?void 0:n.options.tags?.[e.tag]?.renderForLlms)?.(Object.assign(Object.create(Object.getPrototypeOf(e)),e,{attributes:m(r,n.options.variables)}),{getBody:()=>h(e.children,n),locale:n.options.locale??`en`,translate:n.options.translate??c}),a=e.inline!==!0;if(i!==void 0){i!==``&&t.push(a?`${i}\n\n`:i);return}let o=s.map(e=>r[e]).find(e=>typeof e==`string`);o!==void 0&&t.push(a?`**${o}**\n\n`:`**${o}**${e.children?.length?` `:``}`);break}}for(let r of Object.values(e.slots??{}))g(r,t,n);for(let r of e.children??[])g(r,t,n)}function _(e,t){let n=[],r=(e,i)=>{if(v(e)){if(e.type===`tr`){let r=(e.children??[]).filter(v).map(e=>h(e.children,t).replace(/\|/g,`\\|`).replace(/\n/g,` `));n.push({cells:r,header:i});return}for(let t of e.children??[])r(t,i||e.type===`thead`)}};r(e,!1);let i=[];for(let[e,t]of n.entries())i.push(`| ${t.cells.join(` | `)} |`),e===0&&t.header&&i.push(`| ${t.cells.map(()=>`---`).join(` | `)} |`);return`${i.join(`
|
|
14
|
+
`).join(`\n${i} `)}\n`);return}case`table`:t.push(`\n${_(e,n)}\n`);return;case`tag`:{let i=(e.tag===void 0?void 0:n.options.tags?.[e.tag]?.renderForLlms)?.(Object.assign(Object.create(Object.getPrototypeOf(e)),e,{attributes:m(r,n.options.variables)}),{getBody:()=>h(e.children,n),locale:n.options.locale??`en`,translate:n.options.translate??c}),a=e.inline!==!0;if(i!==void 0){i!==``&&t.push(a?`${i}\n\n`:i);return}let o=s.map(e=>r[e]).find(e=>typeof e==`string`);o!==void 0&&e.tag!==`html`&&t.push(a?`**${o}**\n\n`:`**${o}**${e.children?.length?` `:``}`);break}}for(let r of Object.values(e.slots??{}))g(r,t,n);for(let r of e.children??[])g(r,t,n)}function _(e,t){let n=[],r=(e,i)=>{if(v(e)){if(e.type===`tr`){let r=(e.children??[]).filter(v).map(e=>h(e.children,t).replace(/\|/g,`\\|`).replace(/\n/g,` `));n.push({cells:r,header:i});return}for(let t of e.children??[])r(t,i||e.type===`thead`)}};r(e,!1);let i=[];for(let[e,t]of n.entries())i.push(`| ${t.cells.join(` | `)} |`),e===0&&t.header&&i.push(`| ${t.cells.map(()=>`---`).join(` | `)} |`);return`${i.join(`
|
|
15
15
|
`)}\n`}function v(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{l as markdocAstToMarkdownChunks,u as markdocAstToMarkdownDoc};
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import Markdoc, { type Node as MarkdocNode } from '@redocly/markdoc';
|
|
2
2
|
export type ParsedMarkdown = ReturnType<typeof Markdoc.parse>;
|
|
3
|
+
export type MarkdownParseMode = {
|
|
4
|
+
/** `false` keeps raw HTML as literal text instead of `html` tags. Default `true`. */
|
|
5
|
+
html?: boolean;
|
|
6
|
+
};
|
|
3
7
|
export declare function parseMarkdown(rawSource: string): ParsedMarkdown;
|
|
4
8
|
/** A page's own AST, `{% markdoc-example %}` bodies included; the caller may change it. */
|
|
5
|
-
export declare function parseMarkdownDocument(rawSource: string): ParsedMarkdown;
|
|
9
|
+
export declare function parseMarkdownDocument(rawSource: string, mode?: MarkdownParseMode): ParsedMarkdown;
|
|
6
10
|
/** A parser with its own LRU cache. Default cost of 1 per entry → the budget is a max entry count. */
|
|
7
11
|
export declare function createCachedMarkdownParser(options: {
|
|
8
12
|
budget: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MARKDOC_ERROR_TAG as e}from"../tags/markdoc-error.js";import{hashBlobContent as t}from"../../materialization/data-ref.js";import{createLruCache as n}from"../../../shared/utils/lru-cache.js";import{reparseExampleFences as r}from"./reparse-example-fences.js";import i from"@redocly/markdoc";import{htmlTags as a}from"@redocly/markdoc/html";const o={html:a({errorTag:e,headings:!0}),allowIndentation:!0,allowComments:!0,slots:!0};function
|
|
1
|
+
import{MARKDOC_ERROR_TAG as e}from"../tags/markdoc-error.js";import{hashBlobContent as t}from"../../materialization/data-ref.js";import{createLruCache as n}from"../../../shared/utils/lru-cache.js";import{reparseExampleFences as r}from"./reparse-example-fences.js";import i from"@redocly/markdoc";import{htmlTags as a}from"@redocly/markdoc/html";const o={html:a({errorTag:e,headings:!0}),allowIndentation:!0,allowComments:!0,slots:!0},s={...o,html:void 0};function c(e){return i.parse(e,o)}function l(e,t){let n=t?.html===!1?s:o,a=e=>i.parse(e,n),c=a(e);return r(c,e,a),c}function u(e){let r=n(e);return e=>{let n=t(e),i=r.get(n);if(i!==void 0)return i;let a=l(e);return r.set(n,a),a}}function d(e,t){return i.parseFirstHeading(e,{...o,skip:t})}const f=u({budget:100});export{u as createCachedMarkdownParser,c as parseMarkdown,f as parseMarkdownCached,l as parseMarkdownDocument,d as parseMarkdownFirstHeading};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hashJsonValue as e}from"../database/utils/json.js";import{entities as t,entityDeps as n,files as r,loaderConfigDeps as i}from"../database/schema.js";import{timePluginWork as a}from"../plugins/work-time.js";import{collectDataRefMarkers as o}from"./data-ref.js";import{MaterializationError as s,ProblemError as c}from"../problems/problem-error.js";import{replaceBlobRefsForEntityTx as l}from"../database/blobs.js";import{dedupeRouteQueryDependencies as u}from"../plugins/utils/route-index.js";import{
|
|
1
|
+
import{hashJsonValue as e}from"../database/utils/json.js";import{entities as t,entityDeps as n,files as r,loaderConfigDeps as i}from"../database/schema.js";import{timePluginWork as a}from"../plugins/work-time.js";import{collectDataRefMarkers as o}from"./data-ref.js";import{MaterializationError as s,ProblemError as c}from"../problems/problem-error.js";import{replaceBlobRefsForEntityTx as l}from"../database/blobs.js";import{dedupeRouteQueryDependencies as u}from"../plugins/utils/route-index.js";import{problemRow as d,replaceEntityProblemsExceptCodesTx as f}from"../database/problems.js";import{replaceAssetRefsForEntityTx as p,upsertAssetsTx as m}from"../database/assets.js";import{createProblem as h}from"../problems/codes.js";import{replaceLinkRefsForEntityTx as g,upsertTargetInventoryTx as _}from"../database/link-refs.js";import{buildL10nAssetMap as v,dedupeAssetUsages as y,reconcileAsset as b,removeReplacedAssetFiles as x}from"./asset-reconcile.js";import{cutEntityRevisionTx as S}from"../revisions/cut.js";import{detectMarkdocPayloadFlag as C}from"../markdown/server/render.js";import{replaceRouteQueryDepsTx as w}from"../database/route-query-deps.js";import{replaceEntityRuntimeDeps as T}from"../database/origins.js";import{SEARCH_PROBLEM_CODES as E}from"../problems/producers.js";import{and as D,eq as O}from"drizzle-orm";const k=/* @__PURE__ */ new WeakMap;async function A(e){let t=await j(e.database,e.key);if(!t)throw Error(`Entity "${e.key}" is not registered.`);if(t.kind===`inline`){if(t.data===null)throw Error(`Inline entity "${e.key}" is missing its stored data.`);return t.data}if(t.status===`ready`&&t.data!==null)return t.data;let n=k.get(e.database);n===void 0&&(n=/* @__PURE__ */ new Map,k.set(e.database,n));let r=n.get(e.key);if(r!==void 0)return r;let i=M(e,t);n.set(e.key,i);try{return await i}finally{n.delete(e.key)}}async function j(e,n){let[r]=await e.db.select({id:t.id,key:t.key,kind:t.kind,pluginId:t.pluginId,loaderId:t.loaderId,loaderArgs:t.loaderArgs,type:t.type,metadata:t.metadata,status:t.status,data:t.data,markdoc:t.markdoc,dataHash:t.dataHash,version:t.version,revisionCreatedAt:t.revisionCreatedAt,isSystem:t.isSystem,invalidationSeq:t.invalidationSeq}).from(t).where(D(O(t.key,n),O(t.isCurrent,1))).limit(1);return r}async function M(i,c){if(!c.loaderId)throw Error(`Entity "${i.key}" is missing its loader id.`);let k=i.loaderRegistry.getEntityLoaderById(c.loaderId);if(!k)throw Error(`Entity loader "${c.loaderId}" is not registered.`);let[A]=await i.database.db.select({path:r.path,fileId:r.id}).from(n).leftJoin(r,O(n.originFileId,r.id)).where(O(n.entityId,c.id)).limit(1);if(!A&&!c.isSystem)throw Error(`Entity "${i.key}" has no origin dependency.`);let j=i.loaderContextFactory(k,c.loaderArgs,A?.path??``),M;try{M=await a(k.pluginId,`load`,async()=>k.definition.handler(j))}catch(e){throw await N(i,c.id,e),new s(`Entity "${i.key}" failed to load.`,{cause:e})}let F=JSON.stringify(M.value??null),I=JSON.parse(F),L=M.markdoc??C(F),R=L?v(M.assetUsages??[]):void 0,z=R?{...L,l10nAssets:R}:L,B=o(I),V=Array.from(new Set(B.map(e=>e.blobKey))),H=y(M.assetUsages??[]),{contentDir:U}=i,W=U?(await Promise.all(H.map(e=>b(j.io,{contentDir:U,usage:e})))).filter(e=>e!==null):[],G=[];return await i.database.db.transaction(async n=>{let r=Date.now(),a=e(I),o=(c.dataHash??null)!==a,s=c.revisionCreatedAt;if(o&&(s=Math.max(r,c.revisionCreatedAt+1)),(await n.update(t).set({status:`ready`,data:I,markdoc:z,type:M.type??c.type,metadata:M.metadata??c.metadata,dataHash:a,revisionCreatedAt:s}).where(D(O(t.id,c.id),O(t.invalidationSeq,c.invalidationSeq))).returning({id:t.id})).length===0)return;o&&c.data!==null&&i.revisions?.isTracked(A?.path??``)&&await S(n,{current:c,max:i.revisions.max});let v=j._trackedConfig;await P(n,c.id,v?.collectDependencies()??[]);let y=j._loadedEntityKeys,b=j._globPatterns;if((M.entityDeps!==void 0||y.length>0||b.length>0)&&await T(n,{entityId:c.id,originPluginId:k.pluginId,isSystem:!!c.isSystem,deps:[...M.entityDeps??[],...y.map(e=>({kind:`entity`,key:e})),...b.map(e=>({kind:`glob`,pattern:e}))]}),await w(n,{originPluginId:k.pluginId,hook:`loader`,entityId:c.id,dependencies:u(j._routeQueries)}),await f(n,c.id,E,(M.problems??[]).map(e=>d(h(e),{scope:`entity`,entityId:c.id}))),await l(n,{entityId:c.id,blobKeys:V}),G=await m(n,W),await p(n,{entityId:c.id,refs:H.map(({path:e,hash:t})=>({path:e,hash:t}))}),(M.linkRefs!==void 0||M.targetInventories!==void 0)&&A?.path&&(await g(n,{entityId:c.id,originFileId:A.fileId,originPluginId:k.pluginId,filePath:A.path,drafts:M.linkRefs??[]}),A.fileId!==null))for(let e of M.targetInventories??[])await _(n,{fileId:A.fileId,originPluginId:k.pluginId,draft:e})}),U&&G.length>0&&await x(j.io,{contentDir:U,filenames:G,logger:i.logger}),I}async function N(e,t,n){let r=n instanceof c?n.draft:{code:`plugin/loader-failed`,message:`Loader failed for entity "${e.key}": ${n instanceof Error?n.message:String(n)}`,data:{entityKey:e.key}};try{let n=d(h(r),{scope:`entity`,entityId:t});await e.database.db.transaction(async e=>{await f(e,t,E,[n])})}catch{}}async function P(e,t,n){await e.delete(i).where(O(i.entityId,t)),n.length!==0&&await e.insert(i).values(n.map(e=>({...e,entityId:t})))}export{A as materializeEntityByKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{compareStrings as e}from"../../shared/utils/compare-strings.js";import{getStaticFilesOutputDir as t,getStaticManifestPath as n}from"../../shared/constants/runtime-layout.js";import{isObject as r}from"../../shared/utils/is-object.js";import{isDataRefMarker as i}from"./data-ref.js";import{MaterializationError as a}from"../problems/problem-error.js";import{resolveDataRef as o}from"../database/blobs.js";import{loadEntityRecordByKey as s}from"../database/entities.js";import{updateStaticFileBodies as c}from"../database/static-files.js";import{
|
|
1
|
+
import{compareStrings as e}from"../../shared/utils/compare-strings.js";import{getStaticFilesOutputDir as t,getStaticManifestPath as n}from"../../shared/constants/runtime-layout.js";import{isObject as r}from"../../shared/utils/is-object.js";import{isDataRefMarker as i}from"./data-ref.js";import{MaterializationError as a}from"../problems/problem-error.js";import{resolveDataRef as o}from"../database/blobs.js";import{loadEntityRecordByKey as s}from"../database/entities.js";import{updateStaticFileBodies as c}from"../database/static-files.js";import{writeFileAtomically as l}from"./asset-reconcile.js";import{producerContentType as u,toStaticBodyBytes as d}from"../static/producer-value.js";import{join as f}from"node:path";function p(e){return new Set(e.flatMap(e=>e.kind===`producer`&&e.entityKey?[e.entityKey]:[]))}async function m(e){let t=/* @__PURE__ */ new Set;for(let n of e.staleProducers)try{await e.materializeEntity(n)}catch(r){if(!(r instanceof a))throw r;t.add(n.key),e.logger.debug(`Could not materialize the static producer ${n.key}; recorded the problem and moved on`)}let n=[];for(let r of e.rows){let i=e.resolveAudience(r);if(r.kind===`copy`){n.push(h(e.io,e.contentDir,r,i));continue}let a=await g(e.io,e.database,r,i,r.entityKey!==null&&t.has(r.entityKey));a&&n.push(a)}let r=await _(e.io,{contentDir:e.contentDir,entries:n}),i=new Map(e.rows.map(e=>[e.path,e]));return await c(e.database,r.manifest.files.filter(e=>{let t=i.get(e.path);return t?.hash!==e.hash||t.size!==e.size}).map(e=>({path:e.path,hash:e.hash,size:e.size}))),e.logger.info(`Static files: ${r.manifest.files.length} registered, ${r.written.length} written, ${r.removed.length} removed`),r.manifest}function h(e,t,n,r){if(!n.sourcePath||!n.hash)throw Error(`Static file "${n.path}" has no copy source.`);let i=f(t,n.sourcePath);return{path:n.path,hash:n.hash,contentType:n.contentType,audience:r,write:t=>e.copyFile(i,t)}}async function g(e,t,n,a,c){let l=n.entityKey?await s(t,n.entityKey):null;if(!l||l.status!==`ready`&&!c)throw Error(`Static file "${n.path}": producer entity "${n.entityKey}" is not ready.`);let f=l.data;if(!r(f)||!i(f.body)){if(c)return null;throw Error(`Static file "${n.path}": producer "${n.entityKey}" must return { body: BlobReference }.`)}let p=f.body;return{path:n.path,hash:p.blobKey,contentType:u(f,n),audience:a,write:async n=>e.writeFile(n,d(await o(t,p)))}}async function _(r,i){let a=t(i.contentDir),o=n(i.contentDir),s=new Map((await v(r,o))?.files.map(e=>[e.path,e])??[]),c=new Set(await y(r,a)),u=[],d=[];for(let e=0;e<i.entries.length;e+=16)await Promise.all(i.entries.slice(e,e+16).map(async e=>{let t=f(a,...e.path.split(`/`)),n=s.get(e.path),i=n?.hash===e.hash&&c.has(e.path)?n.size:null;i===null&&(await l(r,t,e.write),i=(await r.stat(t))?.size??0,u.push(e.path)),d.push({path:e.path,hash:e.hash,contentType:e.contentType,size:i,audience:e.audience})}));let p=new Set(i.entries.map(e=>e.path)),m=[...c].filter(e=>!p.has(e));await Promise.all(m.map(e=>r.unlink(f(a,...e.split(`/`))))),d.sort((t,n)=>e(t.path,n.path));let h={formatVersion:1,files:d};return await r.writeFile(o,JSON.stringify(h,null,2),{recursive:!0}),{manifest:h,written:u,removed:m}}async function v(e,t){try{let n=JSON.parse(await e.readFile(t));return Array.isArray(n.files)?n:null}catch{return null}}async function y(e,t,n=``){let r=[],i;try{i=await e.readdir(t)}catch{return r}for(let a of i){let i=`${n}${a.name}`;a.type===`directory`?r.push(...await y(e,f(t,a.name),`${i}/`)):a.type===`file`&&r.push(i)}return r}export{p as collectStaticProducerKeys,m as materializeStaticProducers,_ as reconcileStaticFiles};
|
|
@@ -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{isPlanFeatureGranted as d}from"../../../../shared/plan-gates.js";import{toPosixPath as f}from"../../../../shared/utils/to-posix-path.js";import{isObject as p}from"../../../../shared/utils/is-object.js";import{API_DOCS_MARKDOC_TAG_SET as m,resolveMarkdocTagSet as h}from"../../../markdown/constants/tag-sets.js";import{TRANSLATIONS_FILE_PATTERN as g}from"../../../../shared/constants/l10n/defaults.js";import{slugifySegment as _}from"../../../../shared/utils/routes/slugify-segment.js";import{notInPlanProblem as v}from"../../../plan-gates.js";import{filePathToRouteSlug as y}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{SPEC_KIND_ARAZZO as b,SPEC_KIND_ASYNCAPI as x,SPEC_KIND_GRAPHQL as S,SPEC_KIND_GRPC as C,SPEC_KIND_OPENAPI as w}from"../../../../shared/constants/api-spec-kinds.js";import{packMarkdocAstsDeep as T,unpackMarkdocAstsDeep as E}from"../../../../shared/utils/packed-ast.js";import{findVersionFolder as D}from"../../utils/version-path.js";import{toPublicVersionedSlug as O}from"../../../../shared/constants/versions.js";import{readVersionsYaml as ee,versionsYamlPath as te}from"../../../versions/version-groups.js";import{parseMarkdownCached as k}from"../../../markdown/utils/parse-cache.js";import{createApiEntityKey as A}from"../../utils/api-entity-key.js";import{API_DOCS_API_LOADER_ID as ne,API_DOCS_PLUGIN_ID as re,API_DOCS_RENDER_DEP_KEY as ie,API_DOCS_RENDER_LOADER_ID as ae,API_DOCS_SIDEBAR_LOADER_ID as oe,API_DOCS_TEMPLATE_ID as j,SPEC_DOWNLOAD_ROUTE_PATHS as M,SPEC_PATH_PARAM as se}from"./server/shared.js";import{resolveApiBundleConfig as ce,resolveApiOptions as le,resolveNestedFeedback as ue,schemaCatalogLink as de,withDownloadUrls as fe,withFeedbackOption as pe,withMockServerOption as me}from"./server/options.js";import{annotateApiDocsRbac as N}from"../../../../shared/rbac/api-docs.js";import{SERVER_ONLY_VALUE_KEY as P}from"../../../loaders/server-only-value.js";import{getLoadedProjectPlugins as F}from"../../project/loaded-set.js";import{API_OUTPUT_MANIFEST_KEY as I}from"../../../api-outputs.js";import{pageLocale as L}from"../../utils/page-locale.js";import{buildBundledApiDefinition as R,resolveLlmsDescriptions as z}from"./server/build-definition.js";import{collectSidebarSubpathTargets as he,toSidebarSubtree as ge,toSubpathTarget as _e}from"./server/build-sidebar.js";import{declaresProtoService as ve}from"./server/declares-proto-service.js";import{join as ye,relative as be,resolve as B}from"node:path";import xe from"@redocly/markdoc";async function Se(e,t){let n=t.originFilePath===null?null:D(t.originFilePath);if(n===null||t.version===null||t.versionGroup===null)return{slug:t.slug,entityDeps:[]};let r=await ee({io:{exists:t=>e.io.exists(B(e.contentDir,t)),readFile:t=>e.io.readFile(B(e.contentDir,t))},directory:n.parent}),i=typeof r?.default==`string`&&_(r.default)===t.version;return{slug:O(t.slug,t.versionGroup,t.version,i),entityDeps:[{kind:`file`,path:te(n.parent)}]}}const Ce=[`.yaml`,`.yml`,`.json`,`.gql`,`.graphql`,`.proto`],we={[w]:`OpenAPI`,[x]:`AsyncAPI`,[S]:`GraphQL`,[b]:`Arazzo`,[C]:`gRPC`},V=t(ae,async e=>{let{buildItems:t,descriptionOptions:n}=await import(`@redocly/api-docs/server`),r=W(e),i=await e.io.readFile(r.absolutePath),a=e.routes.byFilePath(e.file.path),o=a?.slug,s=a&&e.args.kind===`openapi`?await Se(e,a):{slug:void 0,entityDeps:[]},c=fe(e.args.options,e.file.path,e.args.kind),l=e.args.kind===`openapi`?me(c,e.config,s.slug):c,u={entityDeps:[],assetUsages:[],linkRefs:[],problems:[],pending:[]},d=U(e.contentDir),f={markdown:e.markdown,loader:{config:e.config,entities:e.entities,file:e.file,io:e.io,logger:e.logger,plugin:e.plugin},sink:u},h=await R({kind:e.args.kind,source:i,relativePath:r.relativePath,contentDir:e.contentDir,pagePath:e.file.path,options:l,importPaths:e.args.importPaths,bundle:G(e.args,d),metadata:Y(e.args.options),io:e.io,markdownResolution:f,rbac:{warn:t=>e.logger?.warn(t)}}),g={...p(h.document)&&p(h.document.info)?{infoDescription:h.document.info.description}:{},...await z(h.document,f,{contentDir:e.contentDir,specPath:r.relativePath,pagePath:e.file.path})};e.args.kind===`openapi`&&l.showSchemaCatalogLinks&&p(h.document)&&(h.document[`x-schema-catalog-link`]=de(e.file.path)),h.options={...pe(h.options,h.document,e.args.feedback??e.config.feedback),...n(e.args.kind,h.document,Y(e.args.options))};let _=o?.toLowerCase()??`/`,{items:v,store:y,specType:b}=await t({...h,basePath:_,markdownParser:e=>xe.compact(k(e))}),x=JSON.stringify({items:T(v),store:T(y),options:h.options,specType:b,basePath:_,title:Ae(h.document,e.args.kind,v),metadata:ke(h.document),[P]:{llms:g}});return{value:await e.createBlobRef(x,{format:`json`}),entityDeps:[...q(e.file.path,[...h.fileDependencies,...d.paths]),...u.entityDeps,...s.entityDeps],assetUsages:u.assetUsages,markdoc:{tagSet:m},linkRefs:u.linkRefs,problems:u.problems}},{async searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=E(e);if(n.specType===`grpc`)return{docs:[]};let r=await $(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=E(e),r=t.route.originFilePath??void 0,i=await $(t.entities,r),{tags:a}=await h(m,t.config),{buildApiDocsMarkdownCopies:o}=await import(`./server/markdown-copy.js`);return o(n,Oe(i,n[P]?.llms),{originFilePath:r,markdown:{tags:a,locale:L(t)},warn:e=>t.logger?.warn(e)})},usesProjectMarkdocSchema:!0}),H=t(ne,async e=>{let t=W(e),n=await e.io.readFile(t.absolutePath),r=U(e.contentDir),i=await R({kind:e.args.kind,source:n,relativePath:t.relativePath,contentDir:e.contentDir,importPaths:e.args.importPaths,bundle:G(e.args,r),metadata:Y(e.args.options),io:e.io}),a=e.args.kind===S,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:{...X(e.file.path,e.args.kind,e.args.options,e.args.rbac),...Ee(i.document,e.routes.byFilePath(e.file.path)?.slug)},entityDeps:q(e.file.path,[...i.fileDependencies,...r.paths]),problems:i.problems}});function U(e){let t=F(e)?.lintPlugins??[];return{plugins:t,paths:t.map(t=>f(be(e,t.path))).filter(e=>e!==``&&!e.startsWith(`../`))}}function W(e){let t=e.args.source?.path??e.file.path;return{relativePath:t,absolutePath:ye(e.contentDir,t)}}function Te(e){let t=e[I];return p(t)&&typeof t.root==`string`?t.root:void 0}function G(e,t){let{config:n,configDir:r}=e.bundleConfig??{config:{},configDir:``};return{config:n,configDir:r,plugins:t.plugins}}function Ee(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},...Z(n.version)?{version:String(n.version)}:{},...typeof r.apiId==`string`?{apiId:r.apiId}:{},description:i||void 0}}const K=t(oe,async e=>{let{buildNavItems:t,collectPreviousRouteSlugs:n}=await import(`@redocly/api-docs/server`),r=await e.entities.load(A(e.file.path)),i=e.args.kind===`graphql`?(await import(`graphql`)).parse(r):r,a=N(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:k}),s=ge(o),c=n(o).map(({from:e})=>_e(e));return{value:s,targetInventories:[{kind:`subpath`,exhaustive:!0,targets:[...he(s),...c]}]}});function q(e,t){return[{kind:`file`,path:e},...t.map(e=>({kind:`file`,path:e}))]}const De={arazzo:`Arazzo Docs`,asyncapi:`AsyncAPI Docs`,graphql:`GraphQL Docs`,grpc:`gRPC Docs`,openapi:`OpenAPI Docs`};function Oe(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 ke(e){let t=p(e)&&p(e.info)?e.info:{};return p(t[`x-metadata`])?t[`x-metadata`]:{}}function Ae(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:De[t]}const J=[`rbac`,`sidebar`,`excludeFromSearch`,`template`];function je(e,t){let n=p(e.manifest.info)?e.manifest.info:{},r={};typeof n.title==`string`&&(r.title=n.title),Z(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 J)delete r[e];return r}function Y(e){return p(e.metadata)?e.metadata:void 0}function Me(e){let t=Y(e)?.title;return typeof t==`string`&&t.length>0?t:void 0}function X(e,t,n,r){let i=Me(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 Z(e){return typeof e==`string`||typeof e==`number`}function Ne(e){if(e.ext===`.gql`||e.ext===`.graphql`)return S;let{openapi:t,swagger:n,asyncapi:r,arazzo:i}=e.manifest;return Z(t)||Z(n)?w:Z(r)?x:Z(i)?b:null}async function Pe(e,t){return t.config.grpcDocsEnabled===!0&&ve(await t.io.readFile(e.path))?C:null}const Fe=e({id:re,version:`0.54.0`,content:{filter:{extensions:Ce},async extractFile(e,t){if(g.test(e.path))return null;let n=e.ext===`.proto`?await Pe(e,t):Ne(e);if(n===null)return null;if(n!==`arazzo`&&n!==`grpc`&&!d(t.config,n))return{routes:[],problems:[v(`${we[n]} documents`)]};let r=e.path,i=Te(e.manifest),a=i??r,{rbac:o,importPaths:s,...c}=await le(t.io,t.config,r,n,a),l={filePath:r,kind:n,options:c,...o===void 0||!d(t.config,`rbac`)?{}:{rbac:o}};i!==void 0&&(l.source={path:i}),s!==void 0&&(l.importPaths=s);let u=await ue(t.io,t.config,a);if(u!==void 0&&(l.feedback=u),n!==`graphql`&&n!==`grpc`){let e=await ce(t.io,t.config,r,a);Object.keys(e.config).length>0&&(l.bundleConfig=e)}let f=H.withArgs(l,{stableKey:A(r),type:`api`,metadata:X(r,n,c,l.rbac)});if(n===`arazzo`)return{routes:[],entities:[f]};let p=je(e,c);c.excludeFromSearch===!0&&(p.excludeFromSearch=!0),p.type=n,l.rbac!==void 0&&(p.rbac=l.rbac);let m=V.withArgs(l,{stableKey:`api-docs:render:${r}`}),h=K.withArgs(l,{stableKey:`api-docs:sidebar:${r}`}),_=y(r);return{routes:[{deps:{[ie]:m},metadata:p,routeId:`page`,sidebarSubtree:h,slug:null,slugHint:_,template:j,wildcardPrefix:!0}],entities:[f,m,h]}}},loaders:[H,V,K],templates:{[j]:r(n(`./client/template.tsx`,import.meta.url))},server:{routes:[Q(M.bundle,`bundle`),Q(M.deprecatedBundle,`bundle`),Q(M.graphql,`graphql`)]}});function Q(e,t){return{method:`GET`,path:e+se,handler:{filePath:`./server/spec-download.ts`,importer:import.meta.url,exportName:t}}}async function $(e,t){if(t)try{return await e.load(A(t))}catch{return}}export{Fe 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{isPlanFeatureGranted as d}from"../../../../shared/plan-gates.js";import{toPosixPath as f}from"../../../../shared/utils/to-posix-path.js";import{isObject as p}from"../../../../shared/utils/is-object.js";import{API_DOCS_MARKDOC_TAG_SET as m,resolveMarkdocTagSet as h}from"../../../markdown/constants/tag-sets.js";import{TRANSLATIONS_FILE_PATTERN as g}from"../../../../shared/constants/l10n/defaults.js";import{slugifySegment as _}from"../../../../shared/utils/routes/slugify-segment.js";import{notInPlanProblem as v}from"../../../plan-gates.js";import{filePathToRouteSlug as y}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{SPEC_KIND_ARAZZO as b,SPEC_KIND_ASYNCAPI as x,SPEC_KIND_GRAPHQL as S,SPEC_KIND_GRPC as C,SPEC_KIND_OPENAPI as w}from"../../../../shared/constants/api-spec-kinds.js";import{packMarkdocAstsDeep as T,unpackMarkdocAstsDeep as E}from"../../../../shared/utils/packed-ast.js";import{findVersionFolder as D}from"../../utils/version-path.js";import{toPublicVersionedSlug as O}from"../../../../shared/constants/versions.js";import{readVersionsYaml as ee,versionsYamlPath as te}from"../../../versions/version-groups.js";import{parseMarkdownCached as k}from"../../../markdown/utils/parse-cache.js";import{createApiEntityKey as A}from"../../utils/api-entity-key.js";import{API_DOCS_API_LOADER_ID as ne,API_DOCS_PLUGIN_ID as re,API_DOCS_RENDER_DEP_KEY as ie,API_DOCS_RENDER_LOADER_ID as ae,API_DOCS_SIDEBAR_LOADER_ID as oe,API_DOCS_TEMPLATE_ID as j,SPEC_DOWNLOAD_ROUTE_PATHS as M,SPEC_PATH_PARAM as se}from"./server/shared.js";import{resolveApiBundleConfig as ce,resolveApiOptions as le,resolveNestedFeedback as ue,schemaCatalogLink as de,withDownloadUrls as fe,withFeedbackOption as pe,withMockServerOption as me}from"./server/options.js";import{annotateApiDocsRbac as N}from"../../../../shared/rbac/api-docs.js";import{SERVER_ONLY_VALUE_KEY as P}from"../../../loaders/server-only-value.js";import{getLoadedProjectPlugins as F}from"../../project/loaded-set.js";import{API_OUTPUT_MANIFEST_KEY as I}from"../../../api-outputs.js";import{pageLocale as L}from"../../utils/page-locale.js";import{buildBundledApiDefinition as R,resolveLlmsDescriptions as z}from"./server/build-definition.js";import{collectSidebarSubpathTargets as he,toSidebarSubtree as ge,toSubpathTarget as _e}from"./server/build-sidebar.js";import{declaresProtoService as ve}from"./server/declares-proto-service.js";import{join as ye,relative as be,resolve as B}from"node:path";import xe from"@redocly/markdoc";async function Se(e,t){let n=t.originFilePath===null?null:D(t.originFilePath);if(n===null||t.version===null||t.versionGroup===null)return{slug:t.slug,entityDeps:[]};let r=await ee({io:{exists:t=>e.io.exists(B(e.contentDir,t)),readFile:t=>e.io.readFile(B(e.contentDir,t))},directory:n.parent}),i=typeof r?.default==`string`&&_(r.default)===t.version;return{slug:O(t.slug,t.versionGroup,t.version,i),entityDeps:[{kind:`file`,path:te(n.parent)}]}}const Ce=[`.yaml`,`.yml`,`.json`,`.gql`,`.graphql`,`.proto`],we={[w]:`OpenAPI`,[x]:`AsyncAPI`,[S]:`GraphQL`,[b]:`Arazzo`,[C]:`gRPC`},V=t(ae,async e=>{let{buildItems:t,descriptionOptions:n}=await import(`@redocly/api-docs/server`),r=W(e),i=await e.io.readFile(r.absolutePath),a=e.routes.byFilePath(e.file.path),o=a?.slug,s=a&&e.args.kind===`openapi`?await Se(e,a):{slug:void 0,entityDeps:[]},c=fe(e.args.options,e.file.path,e.args.kind),l=e.args.kind===`openapi`?me(c,e.config,s.slug):c,u={entityDeps:[],assetUsages:[],linkRefs:[],problems:[],pending:[]},d=U(e.contentDir),f={markdown:e.markdown,loader:{config:e.config,entities:e.entities,file:e.file,io:e.io,logger:e.logger,plugin:e.plugin},sink:u},h=await R({kind:e.args.kind,source:i,relativePath:r.relativePath,contentDir:e.contentDir,pagePath:e.file.path,options:l,importPaths:e.args.importPaths,bundle:G(e.args,d),metadata:Y(e.args.options),io:e.io,markdownResolution:f,rbac:{warn:t=>e.logger?.warn(t)}}),g={...p(h.document)&&p(h.document.info)?{infoDescription:h.document.info.description}:{},...await z(h.document,f,{contentDir:e.contentDir,specPath:r.relativePath,pagePath:e.file.path})};e.args.kind===`openapi`&&l.showSchemaCatalogLinks&&p(h.document)&&(h.document[`x-schema-catalog-link`]=de(e.file.path)),h.options={...pe(h.options,h.document,e.args.feedback??e.config.feedback),...n(e.args.kind,h.document,Y(e.args.options))};let _=o?.toLowerCase()??`/`,{items:v,store:y,specType:b}=await t({...h,basePath:_,markdownParser:e=>xe.compact(k(e))}),x=JSON.stringify({items:T(v),store:T(y),options:h.options,specType:b,basePath:_,title:Ae(h.document,e.args.kind,v),metadata:ke(h.document),[P]:{llms:g}});return{value:await e.createBlobRef(x,{format:`json`}),entityDeps:[...q(e.file.path,[...h.fileDependencies,...d.paths]),...u.entityDeps,...s.entityDeps],assetUsages:u.assetUsages,markdoc:{tagSet:m},linkRefs:u.linkRefs,problems:u.problems}},{async searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=E(e);if(n.specType===`grpc`)return{docs:[]};let r=await $(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=E(e),r=t.route.originFilePath??void 0,i=await $(t.entities,r),{tags:a}=await h(m,t.config),{buildApiDocsMarkdownCopies:o}=await import(`./server/markdown-copy.js`);return o(n,Oe(i,n[P]?.llms),{originFilePath:r,markdown:{tags:a,locale:L(t)},warn:e=>t.logger?.warn(e)})},usesProjectMarkdocSchema:!0}),H=t(ne,async e=>{let t=W(e),n=await e.io.readFile(t.absolutePath),r=U(e.contentDir),i=await R({kind:e.args.kind,source:n,relativePath:t.relativePath,contentDir:e.contentDir,importPaths:e.args.importPaths,bundle:G(e.args,r),metadata:Y(e.args.options),io:e.io}),a=e.args.kind===S,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:{...X(e.file.path,e.args.kind,e.args.options,e.args.rbac),...Ee(i.document,e.routes.byFilePath(e.file.path)?.slug)},entityDeps:q(e.file.path,[...i.fileDependencies,...r.paths]),problems:i.problems}});function U(e){let t=F(e)?.lintPlugins??[];return{plugins:t,paths:t.map(t=>f(be(e,t.path))).filter(e=>e!==``&&!e.startsWith(`../`))}}function W(e){let t=e.args.source?.path??e.file.path;return{relativePath:t,absolutePath:ye(e.contentDir,t)}}function Te(e){let t=e[I];return p(t)&&typeof t.root==`string`?t.root:void 0}function G(e,t){let{config:n,configDir:r}=e.bundleConfig??{config:{},configDir:``};return{config:n,configDir:r,plugins:t.plugins}}function Ee(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},...Z(n.version)?{version:String(n.version)}:{},...typeof r.apiId==`string`?{apiId:r.apiId}:{},description:i||void 0}}const K=t(oe,async e=>{let{buildNavItems:t,collectPreviousRouteSlugs:n}=await import(`@redocly/api-docs/server`),r=await e.entities.load(A(e.file.path)),i=e.args.kind===`graphql`?(await import(`graphql`)).parse(r):r,a=N(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:k}),s=ge(o),c=n(o).map(({from:e})=>_e(e));return{value:s,targetInventories:[{kind:`subpath`,exhaustive:!0,targets:[...he(s),...c]}]}});function q(e,t){return[{kind:`file`,path:e},...t.map(e=>({kind:`file`,path:e}))]}const De={arazzo:`Arazzo Docs`,asyncapi:`AsyncAPI Docs`,graphql:`GraphQL Docs`,grpc:`gRPC Docs`,openapi:`OpenAPI Docs`};function Oe(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 ke(e){let t=p(e)&&p(e.info)?e.info:{};return p(t[`x-metadata`])?t[`x-metadata`]:{}}function Ae(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:De[t]}const J=[`rbac`,`sidebar`,`excludeFromSearch`,`template`];function je(e,t){let n=p(e.manifest.info)?e.manifest.info:{},r={};typeof n.title==`string`&&(r.title=n.title),Z(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 J)delete r[e];return r}function Y(e){return p(e.metadata)?e.metadata:void 0}function Me(e){let t=Y(e)?.title;return typeof t==`string`&&t.length>0?t:void 0}function X(e,t,n,r){let i=Me(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 Z(e){return typeof e==`string`||typeof e==`number`}function Ne(e){if(e.ext===`.gql`||e.ext===`.graphql`)return S;let{openapi:t,swagger:n,asyncapi:r,arazzo:i}=e.manifest;return Z(t)||Z(n)?w:Z(r)?x:Z(i)?b:null}async function Pe(e,t){return t.config.grpcDocsEnabled===!0&&ve(await t.io.readFile(e.path))?C:null}const Fe=e({id:re,version:`0.56.0`,content:{filter:{extensions:Ce},async extractFile(e,t){if(g.test(e.path))return null;let n=e.ext===`.proto`?await Pe(e,t):Ne(e);if(n===null)return null;if(n!==`arazzo`&&n!==`grpc`&&!d(t.config,n))return{routes:[],problems:[v(`${we[n]} documents`)]};let r=e.path,i=Te(e.manifest),a=i??r,{rbac:o,importPaths:s,...c}=await le(t.io,t.config,r,n,a),l={filePath:r,kind:n,options:c,...o===void 0||!d(t.config,`rbac`)?{}:{rbac:o}};i!==void 0&&(l.source={path:i}),s!==void 0&&(l.importPaths=s);let u=await ue(t.io,t.config,a);if(u!==void 0&&(l.feedback=u),n!==`graphql`&&n!==`grpc`){let e=await ce(t.io,t.config,r,a);Object.keys(e.config).length>0&&(l.bundleConfig=e)}let f=H.withArgs(l,{stableKey:A(r),type:`api`,metadata:X(r,n,c,l.rbac)});if(n===`arazzo`)return{routes:[],entities:[f]};let p=je(e,c);c.excludeFromSearch===!0&&(p.excludeFromSearch=!0),p.type=n,l.rbac!==void 0&&(p.rbac=l.rbac);let m=V.withArgs(l,{stableKey:`api-docs:render:${r}`}),h=K.withArgs(l,{stableKey:`api-docs:sidebar:${r}`}),_=y(r);return{routes:[{deps:{[ie]:m},metadata:p,routeId:`page`,sidebarSubtree:h,slug:null,slugHint:_,template:j,wildcardPrefix:!0}],entities:[f,m,h]}}},loaders:[H,V,K],templates:{[j]:r(n(`./client/template.tsx`,import.meta.url))},server:{routes:[Q(M.bundle,`bundle`),Q(M.deprecatedBundle,`bundle`),Q(M.graphql,`graphql`)]}});function Q(e,t){return{method:`GET`,path:e+se,handler:{filePath:`./server/spec-download.ts`,importer:import.meta.url,exportName:t}}}async function $(e,t){if(t)try{return await e.load(A(t))}catch{return}}export{Fe as apiDocsContentPlugin};
|
|
@@ -2,6 +2,7 @@ import type { createConfig as CreateConfigFn } from '@redocly/openapi-core';
|
|
|
2
2
|
import { type MarkdownUsageSink, type PendingMarkdownResolution } from './markdown-decorator.js';
|
|
3
3
|
import type { MarkdownService } from '../../../../markdown/types/service.js';
|
|
4
4
|
import type { MarkdocResolverContextBase } from '../../../../markdown/resolve/markdoc.js';
|
|
5
|
+
import type { MarkdownParseMode } from '../../../../markdown/utils/parse-cache.js';
|
|
5
6
|
import { type ApiSpecType } from '../../../types/api-entity.js';
|
|
6
7
|
import type { JsonObject } from '../../../../database/schema.js';
|
|
7
8
|
import type { ProblemDraft } from '../../../../problems/types.js';
|
|
@@ -106,4 +107,4 @@ export declare function resolveLlmsDescriptions(document: unknown, resolution: A
|
|
|
106
107
|
specPath: string;
|
|
107
108
|
pagePath: string;
|
|
108
109
|
}): Promise<LlmsDescriptions>;
|
|
109
|
-
export declare function resolvePendingMarkdown(resolution: ApiDocsMarkdownResolution, pendingList: readonly PendingMarkdownResolution[], contentDir: string, pagePath: string): Promise<void>;
|
|
110
|
+
export declare function resolvePendingMarkdown(resolution: ApiDocsMarkdownResolution, pendingList: readonly PendingMarkdownResolution[], contentDir: string, pagePath: string, parseMode?: MarkdownParseMode): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{toContainedContentPath as t}from"../../../../ingest/scan.js";import{ProblemError as n}from"../../../../problems/problem-error.js";import{SPEC_KIND_ARAZZO as r,SPEC_KIND_GRPC as i}from"../../../../../shared/constants/api-spec-kinds.js";import{annotateApiDocsRbac as a}from"../../../../../shared/rbac/api-docs.js";import{resolveMarkdownAst as o}from"../../../../markdown/resolve/ast.js";import{PLAIN_DESCRIPTION_SOURCE as s,REALM_MARKDOWN_DECORATOR_KEY as c,REALM_MARKDOWN_DECORATOR_NAME as l,createMarkdownDecoratorPlugin as u}from"./markdown-decorator.js";import{captureSnippet as d,splitSourceLines as f}from"../../../../../shared/utils/capture-snippet.js";import{existsSync as p}from"node:fs";import{join as m}from"node:path";async function h(e){if(e.kind===`grpc`){let{io:t}=e;if(t===void 0)throw Error(`A gRPC definition reads its imports through the loader io.`);return x({...e,io:t})}if(e.kind===`graphql`){let{parse:t}=await import(`graphql`),n;try{n=t(e.source)}catch(t){throw
|
|
1
|
+
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{toContainedContentPath as t}from"../../../../ingest/scan.js";import{ProblemError as n}from"../../../../problems/problem-error.js";import{SPEC_KIND_ARAZZO as r,SPEC_KIND_GRPC as i}from"../../../../../shared/constants/api-spec-kinds.js";import{annotateApiDocsRbac as a}from"../../../../../shared/rbac/api-docs.js";import{resolveMarkdownAst as o}from"../../../../markdown/resolve/ast.js";import{PLAIN_DESCRIPTION_SOURCE as s,REALM_MARKDOWN_DECORATOR_KEY as c,REALM_MARKDOWN_DECORATOR_NAME as l,createMarkdownDecoratorPlugin as u}from"./markdown-decorator.js";import{captureSnippet as d,splitSourceLines as f}from"../../../../../shared/utils/capture-snippet.js";import{existsSync as p}from"node:fs";import{join as m}from"node:path";async function h(e){if(e.kind===`grpc`){let{io:t}=e;if(t===void 0)throw Error(`A gRPC definition reads its imports through the loader io.`);return x({...e,io:t})}if(e.kind===`graphql`){let{parse:t}=await import(`graphql`),n;try{n=t(e.source)}catch(t){throw w(e.relativePath,t)}return{type:`graphql`,document:n,relativePath:e.relativePath,options:e.options??{},fileDependencies:[],problems:[]}}let{BaseResolver:t,bundleFromString:n,createConfig:i,getLineColLocation:o}=await import(`@redocly/openapi-core`),s=await T(i,{bundle:e.bundle??{config:{},configDir:``,plugins:[]},specRelativePath:e.relativePath,rootDir:e.contentDir,resolution:e.markdownResolution}),c=y(t,s.resolve,e.contentDir),l;try{l=await n({source:e.source,absoluteRef:m(e.contentDir,e.relativePath),config:s,externalRefResolver:c,dereference:e.kind===r})}catch(t){throw w(e.relativePath,t)}let u=l.bundle.parsed,d=k([...l.fileDependencies,...c.catalogLinkPaths],e.contentDir),f=b(l.problems,o,{contentDir:e.contentDir,specRelativePath:e.relativePath});e.markdownResolution&&await D(e.markdownResolution,e.markdownResolution.sink.pending,e.contentDir,e.pagePath??e.relativePath);let p;try{p=await g(e.kind,u)}catch(t){throw w(e.relativePath,t)}let h=_(p,e.metadata);return{type:e.kind,document:e.rbac?a(h,e.kind,e.rbac):h,relativePath:e.relativePath,options:e.options??{},fileDependencies:d,problems:f}}async function g(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return t;let n=t;if(e===`openapi`&&n.swagger!==void 0){let{convertSwaggerToOpenApi:e}=await import(`@redocly/api-docs/server`);return e(n)}if(e===`asyncapi`){let{normalizeAsyncApiDefinition:e}=await import(`@redocly/api-docs/server`);return e(n)}return t}function _(t,n){if(n===void 0||!e(t))return t;let r=e(t.info)?t.info:{},i=e(r[`x-metadata`])?r[`x-metadata`]:{};return{...t,info:{...r,"x-metadata":{...i,...n}}}}const v=/^https?:\/\/.*\/_bundle\/(.*\.(?:ya?ml|json))$/u;function y(e,n,r){class i extends e{catalogLinkPaths=/* @__PURE__ */ new Set;resolveExternalRef(e,n){let i=super.resolveExternalRef(e,n),a=v.exec(i)?.[1];if(a===void 0)return i;let o=m(r,a);return t(r,o)===null?i:(this.catalogLinkPaths.add(o),p(o)?o:i)}}return new i(n)}function b(e,n,r){return e.filter(e=>e.severity===`error`&&e.ignored!==!0).map(e=>{let i=e.message.replaceAll(`${r.contentDir}/`,``),a=e.location[0],o=a?.source?t(r.contentDir,a.source.absoluteRef):null;if(a===void 0||o===null)return{code:`spec/bundle-error`,message:i,location:{filePath:r.specRelativePath}};let{start:s,end:c}=n(a),l={start:{line:s.line,character:s.col},...c?{end:{line:c.line,character:c.col}}:{}};return{code:`spec/bundle-error`,message:i,location:{filePath:o,range:l,snippet:d(f(a.source.body),l)}}})}async function x(e){let{parseProto:t}=await import(`@redocly/api-docs/server`),r=/* @__PURE__ */ new Set,a=[],o;try{o=await t({entry:e.relativePath,importPaths:[...e.importPaths??[],``],read:async t=>{if(t===e.relativePath)return e.source;r.add(t);let n=m(e.contentDir,t);return await e.io.exists(n)?e.io.readFile(n):void 0},onMissingImport:({file:e,message:t})=>{a.push({code:`spec/bundle-error`,message:t,location:{filePath:e}})}})}catch(t){let r=t instanceof Error&&`file`in t?t.file:void 0,i=typeof r==`string`?r:e.relativePath;throw a.length===0?w(i,t):new n({code:`spec/bundle-error`,message:`${a.map(e=>e.message).join(` `)} ${C(t)}`,location:{filePath:i}})}return e.markdownResolution&&await D(e.markdownResolution,S(o),e.contentDir,e.pagePath??e.relativePath,{html:!1}),{type:i,document:o,relativePath:e.relativePath,options:e.options??{},fileDependencies:[...r].sort(),problems:a}}function S(e){let t=[],n=(e,n)=>{t.push({read:()=>e.description,sourceFilePath:n,writeBack:t=>{e.description=t}})};for(let t of e.services){n(t,t.file);for(let e of t.methods)n(e,t.file)}for(let t of e.messages){n(t,t.file);for(let e of t.fields)n(e,t.file)}for(let t of e.enums){n(t,t.file);for(let e of t.values)n(e,t.file)}return t}function C(e){return e instanceof Error?e.message:String(e)}function w(e,t){let r=C(t);return new n({code:`spec/parse-failed`,message:r,location:{filePath:e}})}function T(e,n){let{bundle:r,resolution:i}=n,a=m(n.rootDir,r.configDir,`redocly.yaml`),o={configPath:m(a,`redocly.yaml`)},s=async(t,n)=>{let r=await e(t,n);return r.configPath=a,r},d=r.plugins.map(({plugin:e,path:t})=>({...e,absolutePath:t}));if(i===void 0)return s({...r.config,plugins:d},o);let{sink:f}=i,p=u({specSourcePath:n.specRelativePath,sink:f,toContentRelative:e=>t(n.rootDir,e)});return s({...r.config,plugins:[...d,p],decorators:{...r.config.decorators,[c]:`on`,[l]:`on`}},o)}async function E(t,n,r){if(!e(t))return{};let i=[],a=(t,n)=>{if(!e(t)||!e(n))return;let a=n[s];i.push({read:()=>t.description,sourceFilePath:typeof a==`string`?a:r.specPath,writeBack:e=>{t.description=e}})},o={},c=t.servers;if(Array.isArray(c)||e(c)){o.servers=structuredClone(c);for(let[e,t]of Object.entries(c))a(o.servers[e],t)}let l=e(t.components)?t.components:void 0;if(e(l?.securitySchemes)){let e=l.securitySchemes;o.securitySchemes=structuredClone(e);for(let[t,n]of Object.entries(e))a(o.securitySchemes[t],n)}return await D(n,i,r.contentDir,r.pagePath),o}async function D(e,t,n,r,i){let{markdown:a,sink:s}=e,c={...e.loader,contentDir:n,markdown:a};await Promise.all(t.map(async e=>{let t=e.read();if(typeof t!=`string`||!a.looksLikeMarkdown(t))return;let{ast:n,entityDeps:l,assetUsages:u,linkRefs:d,problems:f}=await o(t,e.sourceFilePath,{resolverContext:c,parseMode:i});s.entityDeps.push(...l),s.assetUsages.push(...u);for(let t of d)t.raw.trim().startsWith(`#`)?s.linkRefs.push(O({...t,target:r})):e.sourceFilePath===r||t.filePath!==void 0?s.linkRefs.push(O(t)):s.linkRefs.push({...O(t),filePath:e.sourceFilePath});for(let t of f)s.problems.push({...t,location:{filePath:e.sourceFilePath}});e.writeBack(n)}))}function O(e){if(e.range===void 0)return e;let t={...e};return delete t.range,t}function k(e,n){let r=/* @__PURE__ */ new Set;for(let i of e){let e=t(n,i);e!==null&&r.add(e)}return[...r].sort()}export{h as buildBundledApiDefinition,T as createBundleConfig,E as resolveLlmsDescriptions,D as resolvePendingMarkdown};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{API_FUNCTION_ENTITY_TYPE as e}from"../constants.js";import{stripPathPrefix as t}from"../../../../../shared/path-prefix.js";import{compareApiFunctionRoutes as n}from"../route-path.js";import{
|
|
1
|
+
import{API_FUNCTION_ENTITY_TYPE as e}from"../constants.js";import{stripPathPrefix as t}from"../../../../../shared/path-prefix.js";import{compareApiFunctionRoutes as n}from"../route-path.js";import{isSubprocessError as r}from"../../../../../server/subprocess/runner.js";import{errorMessage as i}from"../../../../../shared/utils/error-message.js";import{resolveApiFunctionAccess as a,resolveRbacMatcher as o}from"./access.js";import{sendApiFunctionEvent as s}from"./api-function-telemetry.js";import{BodyTooLargeError as c,MAX_REQUEST_BODY_BYTES as l,MAX_RESPONSE_BODY_BYTES as u,deserializeResponse as d,serializeRequest as f}from"./serialize.js";import{invoke as p}from"./invoke.js";import{fileURLToPath as m}from"node:url";import{getCookie as h}from"hono/cookie";import{TrieRouter as g}from"hono/router/trie-router";import{getPath as _,tryDecodeURIComponent as v}from"hono/utils/url";const y=1048576,b=m(import.meta.url);function x(e){let{method:t,honoPath:n,sourcePath:r}=e.metadata??{};return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?{method:t,honoPath:n,sourcePath:r}:null}const S=/* @__PURE__ */ new WeakMap;function C(e){let t=S.get(e);if(!t){t=new g;let r=e.map(x).filter(e=>e!==null);for(let e of r.sort(n))t.add(e.method,e.honoPath,e);S.set(e,t)}return t}function w(e,t,n){let r=C(e),i=t.toUpperCase(),[[a]]=r.match(i===`HEAD`?`GET`:i,n);if(!a)return null;let[o,s]=a,c=Object.fromEntries(Object.entries(s).map(([e,t])=>{let n=v(t);return[e,o.honoPath.includes(`:${e}{.+}`)?n.split(`/`).filter(Boolean):n]}));return{sourcePath:o.sourcePath,params:c}}function T(e){let t={};for(let n of new Set(e.searchParams.keys())){let r=e.searchParams.getAll(n);t[n]=r.length===1?r[0]:r}return t}const E=1048576,D=`Request body size exceeded limit of ${l/E} MB.`,O=`Response size exceeded limit of ${u/E}MB`,k=1e4,A=`Promise timed out after ${k} ms`;function j(e,t){return Response.json({message:t},{status:e,headers:{"Cache-Control":`no-store`}})}function M(e,t){switch(e){case`timeout`:return N(504,`Timeout exceeded`,A);case`input-too-large`:return N(413,D);case`output-too-large`:case`response-too-large`:return N(500,O);default:return N(500,import.meta.env.DEV?t:`Internal server error`,t)}}function N(e,t,n=t){return{response:j(e,t),failure:n}}async function P(n,r,c){let l=t(_(n.req.raw));if(l===null)return r();let u=new URL(c.request.url),d=w(await c.entities.list({type:e}),c.request.method,l);if(!d)return r();n.set(`realmApiFunctionResponder`,`runtime`);let f=o(c.config);if(f){let e=a(f,{sourcePath:d.sourcePath,pathname:l,teams:c.request.teams});if(!e.allow)return j(e.status,e.status===401?`Unauthorized`:`Forbidden`)}let{subprocess:p}=c;if(!p)return j(501,`API functions do not run on this host.`);let m=(e,t)=>s({sourcePath:d.sourcePath,status:e,failure:t},{logger:c.logger}),h;try{h=await F(n,c,p,d,u)}catch(e){throw m(500,i(e)),e}return m(h.response.status,h.failure),h.response}async function F(e,t,n,i,a){let o;try{o={modulePath:n.resolveContentModule(i.sourcePath),request:await f(e.req.raw,l),params:i.params,query:T(a),cookies:h(e),user:{teams:t.request.teams,claims:{...t.request.viewer},email:t.request.viewer?.email,idpAccessToken:void 0,idpId:void 0,isAuthenticated:t.request.viewer?.isAuthenticated??!1},config:t.config,baseUrl:a.origin}}catch(e){if(e instanceof c)return M(`input-too-large`,e.message);throw e}let s;try{s=await n.run({modulePath:b,exportName:`invoke`,input:o,reuse:!import.meta.env.DEV,timeoutMs:k,maxInputBytes:Math.ceil(4/3*l)+y,maxOutputBytes:Math.ceil(4/3*u)+y})}catch(n){if(!r(n))throw n;return n.code===`output-too-large`&&e.set(`realmApiFunctionResponder`,`project`),t.logger?.error(`API function ${i.sourcePath} failed (${n.code}): ${n.message}`),M(n.code,n.message)}if(e.set(`realmApiFunctionResponder`,`project`),!s.ok)return t.logger?.error(`API function ${i.sourcePath} failed (${s.code}): ${s.stack??s.message}`),M(s.code,s.message);let p=d(s.response);return p.headers.has(`cache-control`)||p.headers.set(`Cache-Control`,`no-store`),{response:p}}export{P as dispatch,p as invoke,w as matchApiFunction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A2A_ROUTE as e,MCP_ROUTE as t,MCP_SERVER_CARD_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SLUG as i,skillMarkdownPath as a}from"../../../utils/skill-paths.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"./config-gate.js";import{SKILL_ENTITY_TYPE as l}from"../../../types/skill-entity.js";import{
|
|
1
|
+
import{A2A_ROUTE as e,MCP_ROUTE as t,MCP_SERVER_CARD_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SLUG as i,skillMarkdownPath as a}from"../../../utils/skill-paths.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"./config-gate.js";import{SKILL_ENTITY_TYPE as l}from"../../../types/skill-entity.js";import{publicBaseUrl as u}from"../../../utils/request-origin.js";import{isEntityScopeVisible as d}from"../../../../../shared/rbac/entity-scope.js";import{notFoundResponse as f}from"../../../../../server/plugin-context.js";import{CORS_ANY_ORIGIN as p,MCP_AUTH_SCHEMES as m}from"./oauth/constants.js";import"./auth.js";const h=[`text/plain`],g=[`text/plain`],_={streaming:!1,pushNotifications:!1},v={"Cache-Control":`no-store`};async function y(e,t){let n=!!e.request.viewer?.isAuthenticated;return o(c(e.config))&&!n?[]:(await e.entities.list({type:l})).flatMap(n=>{let{slug:i,title:o,description:s}=n.metadata??{};return typeof i!=`string`||!d(n,e.request.teams,t=>e.logger?.warn(t))?[]:[{id:i,name:o??i,description:s??``,tags:[],url:`${t}${r(a(i))}`}]})}async function b(n,i){if(s(i.config)||i.config.skills?.hide===!0)return f();n.set(`realmCacheControlOwned`,!0);let a=u(i.config,i.request),l=o(c(i.config)),d=i.config.seo;return n.json({name:d?.title||d?.projectTitle||`Developer Documentation`,description:d?.description||`Documentation agent card announcing this site's agent skills and MCP server.`,url:`${a}${r(e)}`,documentationUrl:`${a}${r(`/`)}`,version:`0.0.1`,protocolVersion:`0.3.0`,preferredTransport:`HTTP+JSON`,capabilities:{..._,extensions:[{uri:`https://modelcontextprotocol.io`,description:`Model Context Protocol server exposing the documentation tools and skills.`,params:{url:`${a}${r(t)}`,...l?{authentication:{required:!0,schemes:[...m]}}:{}}}]},defaultInputModes:h,defaultOutputModes:g,skills:await y(i,a)},200,{...v,...p})}function x(e,t){if(s(t.config))return f();let a=[`<${r(n)}>; rel="mcp-server-card"`];return t.config.skills?.hide!==!0&&a.push(`<${r(i)}>; rel="agent-skills"`),e.json({error:{code:`405`,message:`Method not allowed`}},405,{Link:a.join(`, `),...p,"Access-Control-Expose-Headers":`Link`})}export{x as a2a,b as agentCard};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../constants.js";import{isObject as e}from"../../../../../shared/utils/is-object.js";import{
|
|
1
|
+
import"../constants.js";import{isObject as e}from"../../../../../shared/utils/is-object.js";import{thrownErrorClass as t}from"./tool-errors.js";import{waitUntil as n}from"../../../../../server/wait-until.js";import{redactSecretShapes as r}from"./secret-patterns.js";import{maskBodyCredentials as i,maskCodeCredentials as a}from"./code-credentials.js";import{redactSecretsFromString as o}from"./gateway/fetch/redact.js";import{createHash as s}from"node:crypto";function c(e){return{client:e.client,clientVersion:e.clientVersion,requestId:e.requestId,messageId:e.messageId,callerSubject:e.callerSubject,clientIp:e.request.ip??void 0}}const l=`[mcp-audit]`,u=4096;function d(e){return s(`sha256`).update(e,`utf8`).digest(`hex`)}function f(e){if(e.length<=4096)return e;let t=e.slice(0,u),n=t.search(/\s\S*$/),r=n>0?t.slice(0,n):t;return`${r}…[truncated: kept ${r.length} of ${e.length} chars]`}function p(e,t=[]){return r(o(f(e),t))}const m=/(?<=^|[\s('"])(?:file:\/\/\/?|\/)(?:[^\s()/:'"]+\/)+/gm;function h(e){return p(e.replace(m,``))}function g(e){return{sha256:d(e),bytes:Buffer.byteLength(e,`utf8`)}}function _(e){return Object.keys(e??{}).map(e=>e.toLowerCase()).sort().join(`,`)}const v=/* @__PURE__ */ new Set([`access_token`,`api-key`,`api_key`,`apikey`,`assertion`,`auth`,`client_secret`,`code`,`code_verifier`,`id_token`,`id_token_hint`,`key`,`password`,`refresh_token`,`samlresponse`,`secret`,`session`,`sig`,`signature`,`token`,`x-amz-credential`,`x-amz-security-token`,`x-amz-signature`]);function y(e,t=[],n=[]){let r;try{r=new URL(e)}catch{return p(e,t)}let i=new Set(n.map(e=>e.toLowerCase()));for(let e of[...r.searchParams.keys()]){let t=e.toLowerCase();(v.has(t)||i.has(t))&&r.searchParams.set(e,`redacted`)}return r.username=``,r.password=``,p(r.href,t)}function b(e,t,n){let r=Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0&&e!==``));try{e?.info(`${l} ${t}`,r)}catch{}}const x=/(169\.254\.169\.254|metadata\.google\.internal|\.consul\b|\.internal\b|localhost|127\.0\.0\.1|\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|\b192\.168\.\d{1,3}\.\d{1,3}\b|\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b)/i,S=/(process\s*(?:\.\s*env\b|\[)|globalThis|require\s*\(|__proto__)/;function C(e){let t=[];return S.test(e)&&t.push(`env_probe`),x.test(e)&&t.push(`internal_target`),{sha256:d(e),length:e.length,flags:t.sort().join(`,`)}}function w(e){try{return JSON.stringify(e)??String(e)}catch{return`«[unserializable]»`}}function T(e,{tool:t,mode:n,args:r,result:a,errorClass:o,client:s,clientVersion:c,requestId:l,messageId:u,callerSubject:f,clientIp:m}){if(t===`execute`||t===`call-api_write`)return;let h=w(r),_=a===void 0?void 0:g(a),v=r?.sessionHandle,y=typeof v==`string`&&v!==``?v:void 0,x=f??y;b(e,`Record MCP tool call`,{tool:t,mode:n,server_type:`docs`,error_class:o,client:s,client_version:c,request_id:l,message_id:u,subject_sha256:x?d(x):void 0,client_ip:m,args_sha256:d(h),args:p(i(h),y?[y]:[]),result_sha256:_?.sha256,result_bytes:_?.bytes})}async function E(e,r,i,a){let o={tool:r,mode:e.mcpMode,args:i,...c(e)},s=Date.now(),l;try{l=await a()}catch(i){throw T(e.logger,{...o,errorClass:t(i)}),e.telemetry?.toolThrew(r,Date.now()-s,i),e.telemetry&&n(e.telemetry.flush()),i}let u=O(l)&&l.isError===!0;return T(e.logger,{...o,result:j(l),errorClass:u?`tool_error`:void 0}),e.telemetry?.toolReturned(r,Date.now()-s,l),e.telemetry&&n(e.telemetry.flush()),l}const D=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function O(t){return e(t)&&Array.isArray(t.content)&&t.content.every(t=>e(t)&&D.has(t.type))}function k(t){return e(t)&&t.resultType===`input_required`}function A(e,t=``){return e.content.map(e=>e.type===`text`?e.text:``).join(t)}function j(e){if(typeof e==`string`)return e;if(O(e))return A(e);if(k(e))return``;try{return JSON.stringify(e)??``}catch{return``}}function M(e,{audit:t,code:n,description:r,sessionHandle:i,toolNames:o,fetchBudget:s,fetchCapable:c,requestId:l,messageId:u,callerSubject:f,clientIp:m}){let h=f??i;b(e,`Record code execution input`,{code_sha256:t.sha256,code_length:t.length,request_id:l,message_id:u,flags:t.flags,subject_sha256:h?d(h):void 0,client_ip:m,description:p(r),tools:[...o].sort().join(`,`),fetch_capable:c,fetch_budget:s,code:p(a(n))})}function N(e,{rawUrl:t,method:n,host:r,outcome:a,durationMs:o,injectedSecretValues:s,credentialQueryParams:c,path:l,api:u,status:f,injectedScheme:m,requestHeaders:h,requestBody:v,responseHeaders:x,responseBody:S,caller:C={}}){let{requestId:w,callerSubject:T,clientIp:E}=C,D=S===void 0?void 0:g(S);b(e,`Record gateway fetch`,{url_sha256:d(t),host:r,method:n,path:l,api:u,outcome:a,status:f,injected_scheme:m,duration_ms:o,request_id:w,subject_sha256:T?d(T):void 0,client_ip:E,url:y(t,s,c),request_header_names:_(h),request_body:v===void 0?void 0:p(i(v),s),response_header_names:_(x),response_sha256:D?.sha256,response_bytes:D?.bytes})}export{u as AUDIT_FIELD_MAX_CHARS,l as AUDIT_LOG_PREFIX,C as auditCode,_ as auditHeaderNames,p as auditInput,d as auditSha256,h as auditStack,E as auditToolCall,y as auditUrl,c as callAttribution,O as isCallToolResult,b as logAuditRecord,M as logCodeExecutionAudit,N as logGatewayFetchAudit,T as logMcpToolCallAudit,j as toolOutputText,A as toolResultText,f as truncateAuditField};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_PROTECTED_RESOURCE_ROUTE as t,PUBLIC_MCP_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as i}from"../../../../../shared/types/auth.js";import{canAccessMcpFeature as a,isMcpContentProtected as o,isPublicEndpointServed as s,resolveMcpAccess as c}from"./config-gate.js";import{
|
|
1
|
+
import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_PROTECTED_RESOURCE_ROUTE as t,PUBLIC_MCP_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as i}from"../../../../../shared/types/auth.js";import{canAccessMcpFeature as a,isMcpContentProtected as o,isPublicEndpointServed as s,resolveMcpAccess as c}from"./config-gate.js";import{publicOrigin as l}from"../../../utils/request-origin.js";import{getBearerVerifier as u,getSessionIssuer as d}from"../../../../../server/auth/middleware.js";import{isAssistantAnonymousToken as f}from"../../../../../server/ask-ai/assistant-anonymous-token.js";import{CORS_ANY_ORIGIN as p,CORS_EXPOSE_CHALLENGE as m,SUPPORTED_MCP_SCOPES as h}from"./oauth/constants.js";function g(e){let t=/^Bearer\s+(\S+)$/i.exec((e??``).trim());return t?t[1]:null}function _(n,i){let a=i?[`error="${i.code}"`,`error_description="${i.description}"`]:[];return a.push(`resource_metadata="${n}${r(t)}"`,`scope="${h.join(` `)}"`,`authorization_uri="${n}${r(e)}"`),`Bearer ${a.join(`, `)}`}function v(e,t){return t?`${e}. A public endpoint that serves anonymous-accessible content is available at ${t}.`:e}function y(e,t,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,...n}})}function b(e,t){return y(401,{error:`unauthorized`,message:v(`Authentication required`,t)},{"WWW-Authenticate":_(e),...m})}function x(e,t){return y(401,{error:`invalid_token`,message:v(`Invalid or expired token`,t)},{"WWW-Authenticate":_(e,{code:`invalid_token`,description:`Invalid or expired token`}),...m})}function S(){return y(403,{error:`forbidden`,message:`You do not have access to this MCP server`},{...p})}async function C(e){let{c:t,ctx:p}=e,m=e=>p.logger?.warn(e),h=c(p.config),_=o(h);if(e.forceAnonymous){let e=await p.withViewer(i);return a(h,e.request.teams,!1,m)?{kind:`allow`,ctx:e,isProtected:_}:{kind:`deny`,response:S()}}let v=e=>{let t=l(p.request);return{kind:`deny`,response:e(t,s(p.config,h)?`${t}${r(n)}`:void 0)}},y=p.request.viewer??i,C,w,T=p,E=g(t.req.header(`authorization`)),D=d(t)?.artifactSecret,O=E!==null&&D!==void 0&&await f(E,D);if(!_)w=O||E===null?void 0:E;else if(O)y=i,T=await p.withViewer(i);else if(E!==null){let e=await u(t)?.(E);if(!e)return v(x);y=e.viewer,C=e.claims,w=E,T=await p.withViewer(y)}else if(!y.isAuthenticated)return v(b);return a(h,T.request.teams,y.isAuthenticated,m)?{kind:`allow`,ctx:T,isProtected:_,accessToken:w,claims:C}:{kind:`deny`,response:S()}}export{C as authorizeMcpRequest,o as isMcpContentProtected,s as isPublicEndpointServed,g as readBearerToken,c as resolveMcpAccess};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MCP_TOOLS_ENTITY_TYPE as e}from"../constants.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{
|
|
1
|
+
import{MCP_TOOLS_ENTITY_TYPE as e}from"../constants.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{isSubprocessError as n}from"../../../../../server/subprocess/runner.js";import{errorMessage as r}from"../../../../../shared/utils/error-message.js";import{ToolHandlerError as i}from"./tool-errors.js";import{fileURLToPath as a}from"node:url";import{parse as o}from"hono/utils/cookie";const s=a(import.meta.url);function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l(e){return`MCP tool "${e}" is not registered or its module does not export a handler for "${e}". Expected \`export default { '${e}': handler }\` or a single tool definition with \`description\` and \`execute\` as the default export.`}function u(e,t){if(c(e))return typeof e.execute==`function`&&typeof e.description==`string`?e:e[t]}const d=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function f(e){return c(e)&&Array.isArray(e.content)&&e.content.every(e=>c(e)&&d.has(e.type))}function p(e,t){if(f(t))return t;if(typeof t==`string`)return{content:[{type:`text`,text:t}]};let n;try{n=JSON.stringify(t)}catch(t){throw Error(`MCP tool "${e}" returned a value that cannot be serialized to JSON: ${S(t)}`)}if(n===void 0)throw Error(`MCP tool "${e}" returned an invalid result.`);return{content:[{type:`text`,text:n}]}}const m={readFile:async()=>{throw Error(`Project files are not available in this environment.`)}};async function h(e,t){let n=u((await t.loadModule(e.handlerModulePath)).default,e.toolName),i=typeof n==`function`?n:n?.execute;if(typeof i!=`function`)return{ok:!1,code:`no-handler-export`,message:l(e.toolName)};let a={...e.context,fs:m};try{if(e.mode===`isAvailable`){let e=typeof n==`function`?void 0:n?.isAvailable;return{ok:!0,output:!e||await e(a)}}let t=await i(e.args,a,e.extra);return{ok:!0,output:p(e.toolName,t)}}catch(e){return{ok:!1,code:`handler-error`,message:r(e),stack:e instanceof Error?e.stack:void 0}}}function g(e){let n=e.request.viewer;return{user:{teams:e.request.teams,claims:e.claims??{...n},email:n?.email,idpAccessToken:void 0,idpId:void 0,isAuthenticated:n?.isAuthenticated??!1},config:e.config,baseUrl:t(e.request),params:{},query:Object.fromEntries(new URL(e.request.url).searchParams),cookies:o(e.request.headers.cookie??``),products:Object.values(e.config.products??{}).map(e=>e.name),accessToken:e.accessToken,metadata:e.metadata}}function _(e,t,n){if(!c(e)||e.type!==`object`)return null;let r=`Invalid arguments for tool "${n}":`;if(!c(t))return`${r} expected an object.`;let i=Array.isArray(e.required)?e.required:[];for(let e of i)if(typeof e==`string`&&!(e in t))return`${r} missing required field "${e}".`;let a=c(e.properties)?e.properties:{};for(let[e,n]of Object.entries(t)){let t=a[e];if(c(t)){if(typeof t.type==`string`&&!v(n,t.type))return`${r} field "${e}" must be ${t.type}.`;if(Array.isArray(t.enum)&&!t.enum.includes(n))return`${r} field "${e}" must be one of ${JSON.stringify(t.enum)}.`}}return null}function v(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&Number.isFinite(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`object`:return c(e);case`array`:return Array.isArray(e);case`null`:return e===null;default:return!0}}function y(e,t,n,r,i){if(!t.subprocess)throw Error(`MCP tool "${e.toolName}" cannot run on this host: no subprocess.`);return t.subprocess.run({modulePath:s,exportName:`invokeCustomTool`,input:{handlerModulePath:t.subprocess.resolveContentModule(e.handlerFilePath),toolName:e.toolName,mode:n,args:r,context:g(t),extra:{sessionId:i?.sessionId,requestId:i?.mcpReq.id??t.requestId,_meta:i?.mcpReq._meta}},reuse:!import.meta.env.DEV,timeoutMs:3e4})}function b(e,t){return{schema:e,isAvailable:t.hasAvailabilityGate?async n=>{if(!n.subprocess)return!1;let r=n.isAvailableMemo?.get(e.name);if(r)return r;let i=(async()=>{try{let e=await y(t,n,`isAvailable`);return e.ok&&e.output===!0}catch(t){return n.logger?.warn(`MCP tool "${e.name}" isAvailable failed: ${S(t)}`),!1}})();return n.isAvailableMemo?.set(e.name,i),i}:void 0,async execute(n,r,a){let o=_(t.argsSchema,n,e.name);if(o)throw Error(o);let s=await y(t,r,`execute`,n,a?.serverContext);if(!s.ok){let e=new i(s.message);throw e.stack=s.stack??e.stack,e}return s.output}}}function x(e){let{declaration:t}=e;return b({name:t.name,title:t.title,description:t.description,schema:t.schema,outputSchema:t.outputSchema,annotations:t.annotations},{toolName:t.name,handlerFilePath:e.handler.filePath,argsSchema:t.schema,hasAvailabilityGate:!0})}function S(e){return n(e)?`${e.code}: ${e.message}`:r(e)}function C(e,t){if(!c(t))return{ok:!1,errors:["the default export must be an object with `description` and `execute` properties. Move shared helper code outside the `@mcp` folder."]};let{description:n,inputSchema:r,outputSchema:i,annotations:a,isAvailable:o,execute:s}=t,l=[];return(typeof n!=`string`||n.trim()===``)&&l.push("`description` must be a non-empty string."),typeof s!=`function`&&l.push("`execute` must be a function."),r!==void 0&&(c(r)?r.type!==void 0&&r.type!==`object`&&l.push('`inputSchema.type` must be "object" because MCP tool arguments are named.'):l.push("`inputSchema` must be a JSON Schema object.")),i!==void 0&&!c(i)&&l.push("`outputSchema` must be a JSON Schema object."),a!==void 0&&!c(a)&&l.push("`annotations` must be an object."),o!==void 0&&typeof o!=`function`&&l.push("`isAvailable` must be a function."),l.length>0||typeof n!=`string`?{ok:!1,errors:l}:{ok:!0,schema:{name:e,description:n,schema:Object.assign({type:`object`},r??{properties:{}}),outputSchema:i,annotations:a},hasAvailabilityGate:typeof o==`function`}}async function w(t){let n=[],r=[];for(let i of await t.entities.list({type:e})){let{name:e,sourcePath:a}=i.metadata,o=e=>r.push(`Invalid MCP tool file "${a}": ${e}`);if(t.reservedNames.has(e)){o(`the tool name "${e}" is already used by a built-in MCP tool. Rename the file.`);continue}let s;try{s=(await t.loadContentModule(a)).default}catch(e){o(`the file failed to load: ${S(e)}. Tool files must not have module-level side effects.`);continue}let c=C(e,s);if(!c.ok){o(c.errors.join(` `));continue}n.push({schema:c.schema,sourcePath:a,hasAvailabilityGate:c.hasAvailabilityGate})}return{tools:n,errors:r}}function T(e){return`MCP tool "${e.schema.name}" in ${e.sourcePath} declares no \`outputSchema\`. Add one that describes the returned value.`}const E=/* @__PURE__ */ new Set;function D(e,t){e&&!E.has(t)&&(E.add(t),e.warn(t))}async function O(e){let{loadContentModule:t,logger:n}=e;if(!t)return[];let{tools:r,errors:i}=await w({entities:e.entities,loadContentModule:t,reservedNames:e.reservedNames});for(let e of i)D(n,e);for(let e of r)e.schema.outputSchema===void 0&&D(n,T(e));return r.map(e=>b(e.schema,{toolName:e.schema.name,handlerFilePath:e.sourcePath,argsSchema:e.schema.schema,hasAvailabilityGate:e.hasAvailabilityGate}))}export{O as buildMcpFileTools,x as createCustomTool,h as invokeCustomTool,w as loadMcpFileTools,T as missingOutputSchemaWarning,C as validateToolDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AI_METADATA_HEADER as e}from"../constants.js";import{isMcpHidden as t,isPublicEndpointServed as n,resolveMcpAccess as r}from"./config-gate.js";import{
|
|
1
|
+
import{AI_METADATA_HEADER as e}from"../constants.js";import{isMcpHidden as t,isPublicEndpointServed as n,resolveMcpAccess as r}from"./config-gate.js";import{publicOrigin as i}from"../../../utils/request-origin.js";import{formatError as a,jsonRpcErrorResponse as o}from"./tool-errors.js";import{buildMcpFileTools as s,createCustomTool as c,invokeCustomTool as l}from"./custom-tools.js";import{notFoundResponse as u}from"../../../../../server/plugin-context.js";import{authorizeMcpRequest as d}from"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p,resolveRequestInstructionsStyle as m,resolveRequestMcpMode as h}from"./mode.js";import{narrowMcpConfigForCaller as g}from"./gateway/caller-api-calls.js";import{isGatewayEnabled as _}from"./gateway/env.js";import{userSubject as v}from"./gateway/subject.js";import{parseUserAgent as y}from"./mcp-client.js";import{createMcpTelemetry as b}from"./mcp-telemetry.js";import{applyMcpRateLimit as x}from"./rate-limit.js";import{createToolRegistry as S}from"./tool-registry.js";import{mcpToolRegistry as C}from"./registry-instance.js";const w=`POST`;function T(e){return(e??``).split(`,`).some(e=>{let[t,...n]=e.split(`;`).map(e=>e.trim().toLowerCase());if(t!==`text/html`)return!1;let r=n.find(e=>e.startsWith(`q=`));return r===void 0||Number(r.slice(2))>0})}function E(){return o(405,`Method not allowed`,{Allow:w})}function D(e){let t={error:`Method Not Allowed`,message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${e}`};return new Response(JSON.stringify(t),{status:405,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,Allow:w}})}function O(){return o(501,`MCP transport is not available in this environment`)}function k(e){if(!e)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function A(t,n,r,i){let a=k(t.headers.get(e)),{userAgent:o}=n.request,{client:s,clientVersion:c}=y(o),l=h(t.url,p()),u=crypto.randomUUID(),d=v(n.request.viewer),f=n.request.ip??void 0;return{config:{...n.config,mcp:g(n.config.mcp,a)},entities:n.entities,hasRoute:e=>n.hasRoute(e),isSlugVisible:(e,t)=>n.isSlugVisible(e,t),kv:n.kv,gatewaySecretSeed:n.gatewaySecretSeed,logger:n.logger,pageMarkdown:n.pageMarkdown,search:n.search,request:n.request,metadata:a,mcpMode:l,instructionsStyle:m(t.url),requestId:u,executeDeadline:i,messageId:typeof a.messageId==`string`?a.messageId:void 0,callerSubject:d,client:s,clientVersion:c,accessToken:r.accessToken,isProtected:r.isProtected??!1,isAvailableMemo:/* @__PURE__ */ new Map,subprocess:n.subprocess,claims:r.claims,telemetry:b({userAgent:o,request:t,metadata:a,mode:l,requestId:u,callerSubject:d,clientIp:f,logger:n.logger})}}async function j(e){let t=_(e.config)?(await import(`./gateway/tool-list.js`)).gatewayTools():[],n=e.subprocess?e.mcpToolEntries??[]:[],r=C.list(),i=/* @__PURE__ */ new Set([...r.map(e=>e.schema.name),...t.map(e=>e.schema.name),...n.map(e=>e.declaration.name)]),a=e.subprocess?await s({entities:e.entities,loadContentModule:e.loadContentModule,reservedNames:i,logger:e.logger}):[];if(t.length===0&&n.length===0&&a.length===0)return C;let o=S();for(let e of r)o.register(e);for(let e of t)o.register(e);for(let e of n)o.register(c(e));for(let e of a)o.register(e);return o}async function M(e,t,n,r={}){let i=await j(e),o;try{o=await import(`./mcp-server.js`)}catch(t){return e.logger?.error(`MCP transport failed to load: ${a(t)}`),async()=>O()}let s;return o.createMcpRequestHandler({registry:i,logger:e.logger,buildToolContext:r=>s??=A(r,e,t,n),onError:r.onError})}function N(e={}){return async(a,o,s)=>{let c=Date.now()+f;if(t(s.config)||e.publicEndpoint&&!n(s.config,r(s.config)))return u();if(a.req.method===`GET`&&T(a.req.header(`accept`)))return o();let l=await x({kv:s.kv,ip:s.request.ip,bucket:`mcp`,logger:s.logger});if(l)return l;let p=await d({c:a,ctx:s,forceAnonymous:e.forceAnonymous});return p.kind===`deny`?p.response:a.req.method===`GET`?D(`${i(s.request)}${new URL(s.request.url).pathname}`):a.req.method===`POST`?(await M(p.ctx,{isProtected:p.isProtected,accessToken:p.accessToken,claims:p.claims},c))(a.req.raw):E()}}const P=N(),F=N({forceAnonymous:!0,publicEndpoint:!0});export{A as buildToolContext,N as createMcpHandler,M as createServedMcpRequestHandler,l as invokeCustomTool,P as mcp,F as mcpPublic};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../constants.js";import{errorMessage as e}from"../../../../../shared/utils/error-message.js";import{
|
|
1
|
+
import"../constants.js";import{errorMessage as e}from"../../../../../shared/utils/error-message.js";import{innerToolErrorClass as t,thrownErrorClass as n}from"./tool-errors.js";import{isServerTelemetryEnabled as r}from"../../../../../server/telemetry/collector.js";import{sendServerEvent as i,sendServerEvents as a}from"../../../../../server/telemetry/sender.js";import{auditCode as o,auditInput as s,auditSha256 as c,auditStack as l,isCallToolResult as u,toolOutputText as d,toolResultText as f}from"./audit.js";import{SANDBOX_FAILURE as p}from"./codemode/constants.js";import{parseUserAgent as m,readListingSource as h}from"./mcp-client.js";import{randomUUID as g}from"node:crypto";import{ulid as _}from"ulid";const v={id:`docs`,object:`mcpServer`,uri:`urn:redocly:realm:mcp:server:docs`};function y(e){if(e===void 0)return;let t=c(e);return{id:t,object:`user`,uri:`urn:redocly:realm:mcp:subject:${t}`}}function b(i){let{mode:c,requestId:g,callerSubject:_,clientIp:b,logger:x}=i,S=i.env??process.env,C=r(S),w=y(_),{client:T,clientVersion:E}=m(i.userAgent),D=i.metadata.messageId,O={client:T,client_version:E,message_id:typeof D==`string`?D:void 0,listing_source:h(i.request)},j=[],M=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new WeakSet,P=(e,t)=>{j.push({type:e,data:[t],requestId:g,time:/* @__PURE__ */ new Date,actor:w,clientIp:b})},F=t=>{try{t()}catch(t){x?.warn(`MCP telemetry failed: ${e(t)}`)}},I=(e,t,n)=>P(`com.redocly.mcpServer.toolCalled`,{...v,tool:e,mode:c,output_length:n,duration_ms:t,...O}),L=(e,t,n)=>{n.stack&&x?.error(`MCP tool ${e} failed (${n.error_class})`,{request_id:g,stack:n.stack}),P(`com.redocly.mcpServer.error`,{...v,tool:e,mode:c,duration_ms:t,message:s(n.message),stack:l(n.stack),error_class:n.error_class,...O})},R=async(n,r,i)=>{let a=Date.now(),o;try{o=await r()}catch(r){let o=t(r),s=o===`server_error`;throw i.set(e(r),{tool:n,reason:s?`server_error`:`inner_tool_error`}),F(()=>L(n,Date.now()-a,{message:e(r),stack:s&&r instanceof Error?r.stack??``:``,error_class:o})),r}return F(()=>I(n,Date.now()-a,d(o).length)),o};return{toolReturned(e,t,n){F(()=>{if(!u(n)||n.isError!==!0){I(e,t,d(n).length);return}N.has(n)||L(e,t,{message:f(n,` `),stack:``,error_class:e===`execute`?`sandbox_error`:`tool_error`})})},toolThrew(t,r,i){F(()=>{let a=n(i);L(t,r,{message:e(i),stack:a===`server_error`&&i instanceof Error?i.stack??``:``,error_class:a})})},trackCodeExecution(t,n){let r=Date.now(),i=o(t),a=/* @__PURE__ */ new Map,s=0;return{hostFetch:n&&(t=>(s+=1,n(t).catch(t=>{throw a.set(e(t),{reason:`runtime_error`}),t}))),innerToolCall(e,t){let n=R(e,t,a),r=n.then(()=>void 0,()=>void 0);return M.add(r),r.then(()=>M.delete(r)),n},finish(e,t,n){let o=e.failure===p.HostError&&e.error!==void 0?a.get(e.error):void 0;o?.tool&&N.add(t);let c=e.error===void 0?`ok`:`error`,l=Date.now()-r,u=k(e.failure,o,n),d=o?.tool;F(()=>P(`com.redocly.mcpServer.codeExecuted`,{...v,code_sha256:i.sha256,code_length:i.length,fetch_count:s,outcome:c,flags:i.flags,duration_ms:l,failure_reason:u,failed_tool:d,...O})),x?.info(`Gateway MCP code executed [${i.sha256.slice(0,12)}] outcome=${c} codeLength=${i.length} fetchCount=${s}`+(i.flags?` flags=${i.flags}`:``)+` durationMs=${l}`+(u?` failureReason=${u}`:``)+(d?` failedTool=${d}`:``))}}},gatewayFetchPerformed({host:e,method:t,outcome:n,durationMs:r,path:i,api:a,status:o,bytes:s,injectedScheme:c}){F(()=>P(`com.redocly.mcpServer.gatewayFetchPerformed`,{...v,host:e,method:t,outcome:n,path:i,api:a,status:o,injected_scheme:c,bytes:s,duration_ms:r})),x?.info(`Gateway MCP fetch [${t} ${e}] outcome=${n}`+(i===void 0?``:` path=${i}`)+(a===void 0?``:` api=${a}`)+(o===void 0?``:` status=${o}`)+(c===void 0?``:` injectedScheme=${c}`)+(s===void 0?``:` bytes=${s}`)+` durationMs=${r}`)},gatewayFetchRateLimited({scope:e,limit:t,retryAfterSeconds:n}){F(()=>P(`com.redocly.mcpServer.gatewayFetchRateLimited`,{...v,scope:e,retry_after_seconds:n,limit:t}))},async flush(){if(!C){j=[];return}await A(M,300);let e=j;j=[],await a(e,{env:S,fetcher:i.fetcher,logger:x})}}}function x(e,t){let{requestId:n=g(),callerSubject:r,clientIp:a}=t.caller??{};return i({...e,requestId:n,actor:y(r),clientIp:a},t)}function S(e,t,n={}){return x({type:`com.redocly.mcpServer.error`,data:[{...v,message:s(e instanceof Error?e.message:``),stack:l(e instanceof Error?e.stack??``:``),error_class:`server_error`,mode:t}]},n)}function C({scope:e,retryAfterSeconds:t,limit:n},r={}){return x({type:`com.redocly.mcpServer.rateLimited`,data:[{...v,scope:e,retry_after_seconds:t,limit:n}]},r)}function w(e){let t=e||_(),n=t.startsWith(`mcp_`)?t:`mcp_${t}`;return{id:n,object:`mcpSession`,uri:`urn:redocly:realm:mcp:session:${n}`}}function T(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.started`,data:[{...w(e),redirect_uri:t}]},n)}function E(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.completed`,data:[{...w(e),redirect_uri:t}]},n)}function D(e,t,n,r,i={}){return x({type:`com.redocly.mcpServerAuthorization.failed`,data:[{...w(e),error:n,error_details:r,error_class:t}]},i)}function O(e,t={}){return x({type:`com.redocly.mcpServerCard.served`,data:{id:`mcpServerCardId`,object:`mcpServerCard`,uri:`urn:redocly:realm:api:mcpServerCard:mcpServerCardId`,...e},signal:`trace`},t)}function k(e,t,n){return e===p.HostError?t?.reason??p.RuntimeError:e===p.RuntimeError&&n!==void 0?`unknown_tool`:e}async function A(e,t){if(e.size===0)return;let n;await Promise.race([Promise.allSettled(e),new Promise(e=>{n=setTimeout(e,t)})]),clearTimeout(n)}export{b as createMcpTelemetry,E as sendMcpAuthorizationCompleted,D as sendMcpAuthorizationFailed,T as sendMcpAuthorizationStarted,C as sendMcpRateLimited,S as sendMcpRequestError,O as sendMcpServerCardServed};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isBlockedIp as e}from"../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../server/ssrf/ssrf-safe-lookup.js";import{isLoopbackRedirect as n}from"./redirect-uri.js";import{isIP as r}from"node:net";import{Agent as i}from"undici";const a=65536;let o;function s(e){if(!e)return!1;try{return new URL(e).protocol===`https:`}catch{return!1}}function c(e,t){if(t.includes(e))return!0;let n=l(e);return n!==null&&t.some(e=>l(e)===n)}function l(e){let t=URL.parse(e);return!t||!n(t)?null:(t.port=``,t.href)}async function u(n){if(!s(n))throw Error(`client_id must be an https URL`);let a=new URL(n).hostname.replace(/^\[|\]$/g,``);if(r(a)!==0&&e(a))throw Error(`client_id must not be a private network address`);let c={method:`GET`,redirect:`error`,headers:{Accept:`application/json`},signal:AbortSignal.timeout(5e3),dispatcher:o??=new i({connect:{lookup:t()}})},l=await fetch(n,c);if(!l.ok)throw Error(`Failed to fetch client metadata: HTTP ${l.status}`);let u=l.headers.get(`content-type`)??``;if(!/^application\/(.+\+)?json/i.test(u))throw Error(`Unexpected content-type for client metadata: ${u}`);return f(await d(l))}async function d(e){let t=e.body;if(!t)throw Error(`Client metadata response has no body`);let n=t.getReader(),r=[],i=0;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(i+=t.byteLength,i>a)throw Error(`Client metadata exceeds maximum size of ${a/1024} KB`);r.push(t)}}finally{await n.cancel().catch(()=>{})}return Buffer.concat(r).toString(`utf8`)}function f(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`Invalid JSON in client metadata: ${e.message}`)}let n=t,r=n?.redirect_uris;if(!Array.isArray(r)||r.length===0||!r.every(e=>typeof e==`string`&&e!==``))throw Error(`Invalid client metadata: /redirect_uris must be a non-empty array of strings`);return{redirect_uris:r,...typeof n?.client_name==`string`?{client_name:n.client_name}:{}}}export{u as fetchClientMetadataDocument,s as isClientMetadataDocumentUrl,c as isRedirectUriRegistered};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_AUTHORIZE_ROUTE as t,MCP_REGISTER_ROUTE as n,MCP_ROUTE as r,MCP_TOKEN_ROUTE as i}from"../../constants.js";import{withPathPrefix as a}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"../config-gate.js";import{
|
|
1
|
+
import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_AUTHORIZE_ROUTE as t,MCP_REGISTER_ROUTE as n,MCP_ROUTE as r,MCP_TOKEN_ROUTE as i}from"../../constants.js";import{withPathPrefix as a}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"../config-gate.js";import{publicOrigin as l}from"../../../../utils/request-origin.js";import{notFoundResponse as u}from"../../../../../../server/plugin-context.js";import{CORS_ANY_ORIGIN as d,SUPPORTED_MCP_GRANT_TYPES as f,SUPPORTED_MCP_SCOPES as p}from"./constants.js";import"../auth.js";function m(e){return!s(e.config)&&o(c(e.config))}function h(t,n){if(!m(n))return u();let i=l(n.request);return t.json({resource:`${i}${a(r)}`,authorization_servers:[i],bearer_methods_supported:[`header`],resource_documentation:`${i}${a(e)}`,scopes_supported:[...p],bearer_token_types_supported:[`Bearer`]},200,{...d})}function g(e,r){if(!m(r))return u();let o=l(r.request);return e.json({issuer:o,authorization_endpoint:`${o}${a(t)}`,token_endpoint:`${o}${a(i)}`,scopes_supported:[...p],registration_endpoint:`${o}${a(n)}`,response_types_supported:[`code`],grant_types_supported:[...f],subject_types_supported:[`public`],id_token_signing_alg_values_supported:[`RS256`],code_challenge_methods_supported:[`S256`],token_endpoint_auth_methods_supported:[`none`],client_id_metadata_document_supported:!0},200,{...d})}export{g as oauthAuthorizationServer,h as oauthProtectedResource};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MCP_ROUTE as e}from"../constants.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as n}from"../../../../../shared/types/auth.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"./config-gate.js";import{
|
|
1
|
+
import{MCP_ROUTE as e}from"../constants.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as n}from"../../../../../shared/types/auth.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"./config-gate.js";import{publicBaseUrl as o,publicOrigin as s}from"../../../utils/request-origin.js";import{formatError as c}from"./tool-errors.js";import{notFoundResponse as l}from"../../../../../server/plugin-context.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p}from"./mode.js";import{sendMcpServerCardServed as m}from"./mcp-telemetry.js";import{applyMcpRateLimit as h}from"./rate-limit.js";import{createServedMcpRequestHandler as g}from"./handler.js";import{docsServerInfo as _}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as v,CLIENT_INFO_META_KEY as y,LATEST_PROTOCOL_VERSION as b,PROTOCOL_VERSION_META_KEY as x}from"@modelcontextprotocol/server";const S=`2026-07-28`,C=[`dynamic`],w={capabilities:{},tools:C};async function T(e,t,n){let r=await e(new Request(t,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,"mcp-protocol-version":S,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[x]:S,[y]:{name:`server-card`,version:`1.0`},[v]:{}}}})}));if(r.ok)return(await r.json()).result}function E(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${c(t)}`)}async function D(r,i){let a=await r.withViewer(n),o=await g(a,{isProtected:i},Date.now()+f,{onError:e=>E(r,e)}),c=new URL(t(e),s(r.request)).href,[l,u]=await Promise.all([T(o,c,`server/discover`),i?void 0:T(o,c,`tools/list`)]);if(!l)return;if(i)return{capabilities:l.capabilities,tools:C};if(!u)return;let d=u.tools.map(({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a})=>({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a}));return{capabilities:l.capabilities,instructions:l.instructions,tools:d.length>0?d:C}}async function O(n,s){if(i(s.config))return l();n.set(`realmCacheControlOwned`,!0);let c=await h({kv:s.kv,ip:s.request.ip,bucket:`card`,headers:u,logger:s.logger});if(c)return c;let f=_(s.config,s.request),g=r(a(s.config)),v=await D(s,g).catch(e=>{E(s,e)}),{capabilities:y,instructions:x,tools:S}=v??w;return m({mode:p(),toolsCount:S===C?0:S.length,authRequired:g},{logger:s.logger}),n.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:b,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:o(s.config,s.request),transport:{type:`streamable-http`,endpoint:t(e)},capabilities:y,authentication:g?{required:!0,schemes:[...d]}:void 0,instructions:x,tools:S},200,{...u,"Cache-Control":v?`public, max-age=3600`:`no-store`})}export{O as mcpServerCard};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{SKILL_ENTITY_TYPE as n}from"../../../types/skill-entity.js";import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{SKILL_ENTITY_TYPE as n}from"../../../types/skill-entity.js";import{publicOrigin as r}from"../../../utils/request-origin.js";import{isEntityScopeVisible as i}from"../../../../../shared/rbac/entity-scope.js";async function a(a){if(a.config.skills?.hide===!0)return[];let o=await a.entities.list({type:n}),s=r(a.request),c=e=>i(e,a.request.teams,e=>a.logger?.warn(e));return o.flatMap(n=>{let{slug:r,title:i,description:o}=n.metadata??{};return typeof r!=`string`||!c(n)?[]:[{slug:r,title:i??r,description:o??``,uri:`${s}${e(t(r))}`,read:async()=>(await a.entities.load(n.key)).content}]})}export{a as loadSkillResources};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{normalizeL10nConfig as e}from"../../../../../../shared/utils/l10n.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{readIgnoredRouteSlugs as n}from"../../ignored-routes.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as i}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as a,fetchSemanticSearchDocuments as o,filterSemanticSearchDocuments as s}from"../semantic-search.js";import{SEARCH_SCHEMA as
|
|
1
|
+
import{normalizeL10nConfig as e}from"../../../../../../shared/utils/l10n.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{readIgnoredRouteSlugs as n}from"../../ignored-routes.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as i}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as a,fetchSemanticSearchDocuments as o,filterSemanticSearchDocuments as s}from"../semantic-search.js";import{resolveDocsSiteUrl as c}from"../docs-site-url.js";import{SEARCH_SCHEMA as l,searchSchema as u}from"./schemas.js";const d=`No results found.`;function f(e,n){let r=e=>{try{return new URL(t(e),n).toString()}catch{return e}};return e.map(e=>`### [${e.title}](${r(e.url)})\n\n${e.content}\n`).join(`
|
|
2
2
|
|
|
3
|
-
`).trim()}const
|
|
3
|
+
`).trim()}const p=[{schema:l,schemaFor:t=>u(Object.values(t.config.products??{}).map(e=>e.name),e(t.config.l10n).locales?.map(e=>e.code)??[]),isAvailable:()=>i()!==``,async execute(t,i){let{query:l,product:u,locale:p}=t??{},m;try{m=await o({query:l,product:u||void 0,locale:p||e(i.config.l10n).defaultLocale})}catch(e){throw e instanceof a?(i.logger?.warn(`MCP search: ${e.message} ${e.detail}`),Error(`The search service failed. Try the call again later.`)):e}let h=await n(i.entities),g=await s(m,async e=>!h.has(e)&&i.isSlugVisible(e)&&await i.hasRoute(e));if(g.length===0)return d;let _=r(i.request);return f(g,process.env.REDOCLY_ENV===`production`?c(i.config.seo?.siteUrl,_):_)||d}}];export{p as searchTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hashString as e}from"../../../../database/utils/json.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SCHEMA_URL as n,skillMarkdownPath as r}from"../../../utils/skill-paths.js";import{SKILL_ENTITY_TYPE as i,skillEntityKey as a}from"../../../types/skill-entity.js";import{
|
|
1
|
+
import{hashString as e}from"../../../../database/utils/json.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SCHEMA_URL as n,skillMarkdownPath as r}from"../../../utils/skill-paths.js";import{SKILL_ENTITY_TYPE as i,skillEntityKey as a}from"../../../types/skill-entity.js";import{publicOrigin as o}from"../../../utils/request-origin.js";import{isEntityScopeVisible as s}from"../../../../../shared/rbac/entity-scope.js";import{notFoundResponse as c}from"../../../../../server/plugin-context.js";const l={"Cache-Control":`no-store`,"Access-Control-Allow-Origin":`*`};function u(e){return e.config.skills?.hide===!0}async function d(a,d){if(u(d))return c();let f=o(d.request),p=await d.entities.list({type:i}),m=await Promise.all(p.map(async n=>{let{slug:i,title:a,description:o}=n.metadata??{};if(typeof i!=`string`||!s(n,d.request.teams,e=>d.logger?.warn(e)))return[];let{content:c}=await d.entities.load(n.key);return[{name:a??i,type:`skill-md`,description:o??``,url:`${f}${t(r(i))}`,digest:`sha256:${e(c)}`}]}));return a.json({$schema:n,skills:m.flat()},200,l)}async function f(e,t){if(u(t))return c();let n=e.req.param(`slug`)??``,r=a(n),i=await t.entities.get(r);if(!i||!s(i,t.request.teams,e=>t.logger?.warn(e)))return c();let{content:o}=await t.entities.load(r);return e.body(o,200,{"Content-Type":`text/markdown; charset=utf-8`,...l})}export{f as skillMarkdown,d as skillsIndex};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadSiteConfig as e,resolveSiteConfig as t}from"../database/site-config.js";import{isRemoteDatabaseUrl as n}from"../database/utils/is-remote-database-url.js";import{openContentLayerDatabase as r,resolveLocalDatabasePath as i}from"../database/connection.js";import{garbageCollectOrphanBlobs as a,getBlob as o}from"../database/blobs.js";import{createEntityStore as s,loadCurrentEntityMetadata as c}from"../database/entity-store.js";import{
|
|
1
|
+
import{loadSiteConfig as e,resolveSiteConfig as t}from"../database/site-config.js";import{isRemoteDatabaseUrl as n}from"../database/utils/is-remote-database-url.js";import{openContentLayerDatabase as r,resolveLocalDatabasePath as i}from"../database/connection.js";import{garbageCollectOrphanBlobs as a,getBlob as o}from"../database/blobs.js";import{createEntityStore as s,loadCurrentEntityMetadata as c}from"../database/entity-store.js";import{listProblemsForEntity as l}from"../database/problems.js";import{listAssetSourcePaths as u}from"../database/assets.js";import{loadEntityRecordByKey as d,loadSiteStart as f}from"../database/entities.js";import{listRoutePagesByFile as p}from"../database/files.js";import{listStaticFileRecords as m}from"../database/static-files.js";import{createKvStore as h}from"../database/kv.js";export{s as createEntityStore,h as createKvStore,a as garbageCollectOrphanBlobs,o as getBlob,n as isRemoteDatabaseUrl,u as listAssetSourcePaths,l as listProblemsForEntity,p as listRoutePagesByFile,m as listStaticFileRecords,c as loadCurrentEntityMetadata,d as loadEntityRecordByKey,e as loadSiteConfig,f as loadSiteStart,r as openContentLayerDatabase,i as resolveLocalDatabasePath,t as resolveSiteConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeRouteSlug as e}from"../../shared/utils/routes/normalize-route-slug.js";import{resolveContentPath as t}from"../../shared/utils/resolve-content-path.js";import{ENGINE_ROUTE_PREFIXES as n,SystemRoute as r}from"../../shared/constants/system-routes.js";import{getContentType as i}from"../../shared/mime.js";import{
|
|
1
|
+
import{normalizeRouteSlug as e}from"../../shared/utils/routes/normalize-route-slug.js";import{resolveContentPath as t}from"../../shared/utils/resolve-content-path.js";import{ENGINE_ROUTE_PREFIXES as n,SystemRoute as r}from"../../shared/constants/system-routes.js";import{getContentType as i}from"../../shared/mime.js";import{staticFileConflictProblem as a,staticFileInvalidProblem as o}from"../problems/producers.js";import{normalizeStaticPath as s}from"./normalize-path.js";import{SYSTEM_SLUGS as c}from"../ingest/slugger/resolve-final-slugs.js";function l(n){let r=[],a=(e,t)=>n.problems.push(o({path:e,pluginId:n.pluginId,message:t}));for(let o of n.declarations){let c=s(o.path);if(c===null){a(o.path,`The path must be relative to the site root and must not leave it.`);continue}let l={path:c,contentType:i(c),size:null};if(`copyFrom`in o){let e=t(o.copyFrom,``);if(!e){a(o.path,`The copy source "${o.copyFrom}" is not a content file.`);continue}let i=n.filesByPath.get(e);if(n.recordFileDependency({source:`file`,accessType:i?`value`:`presence`,path:e,valueHash:i?.hash??`absent`}),!i){a(o.path,`The copy source "${o.copyFrom}" is not a content file.`);continue}r.push({...l,kind:`copy`,sourcePath:e,entityKey:null,hash:i.hash,audience:null});continue}let u=o.audience??`public`;r.push({...l,kind:`producer`,sourcePath:null,entityKey:n.registerProducer(o),hash:null,audience:u===`public`?`public`:{routeSlug:e(u.routeSlug)}})}return r}function u(t){let i=/* @__PURE__ */ new Map,s=e=>{let n=i.get(e.path)??i.get(`${e.path}/`)??l(e.path);if(n!==void 0)return t.problems.push(a({path:e.path,ownerPluginId:n,pluginId:e.ownerPluginId})),!1;i.set(e.path,e.ownerPluginId);for(let t=e.path.indexOf(`/`);t!==-1;t=e.path.indexOf(`/`,t+1))i.set(`${e.path.slice(0,t)}/`,e.ownerPluginId);return!0},l=e=>{for(let t=e.indexOf(`/`);t!==-1;t=e.indexOf(`/`,t+1)){let n=i.get(e.slice(0,t));if(n!==void 0)return n}},u=e=>c.has(e)&&e!==r.Favicon||t.reservedSlugs.has(e)||n.some(t=>e===t||e.startsWith(`${t}/`)),d=n=>{let r=e(`/${n.path}`),i=t.routeBySlug.get(r),a=u(r)?`The path is served by the engine or a plugin route.`:i?`The page ${r} (${i.originFilePath??`plugin route`}) has the same path.`:null;a&&t.problems.push(o({path:n.path,pluginId:n.ownerPluginId,message:a}))};for(let e of t.kept)s(e),d(e);let f=/* @__PURE__ */ new Map;for(let[e,n]of t.collected){let t=[];for(let r of n){let n={path:r.path,ownerPluginId:e};s(n)&&(d(n),t.push(r))}f.set(e,t)}return f}export{l as collectStaticFileRows,u as settleStaticFileClaims};
|