@redocly/redoc-reef 0.141.0-next.12 → 0.141.0-next.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/server/constants/assets.d.ts +3 -0
  3. package/dist/server/constants/assets.js +1 -0
  4. package/dist/server/constants/common.d.ts +0 -3
  5. package/dist/server/constants/common.js +1 -1
  6. package/dist/server/constants/config-schema.d.ts +12 -0
  7. package/dist/server/constants/config-schema.js +1 -0
  8. package/dist/server/constants/project-plugins.d.ts +2 -0
  9. package/dist/server/constants/project-plugins.js +1 -0
  10. package/dist/server/constants/versions.d.ts +3 -0
  11. package/dist/server/constants/versions.js +1 -0
  12. package/dist/server/esbuild/plugins/assets-resolver.js +1 -1
  13. package/dist/server/external-plugins/resolve-external-plugins.js +1 -1
  14. package/dist/server/plugins/api-docs/utils/is-api-doc.js +1 -1
  15. package/dist/server/plugins/api-docs/utils/relative-path-to-base-slug.js +1 -1
  16. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.d.ts +1 -10
  17. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.js +1 -1
  18. package/dist/server/plugins/config-parser/loaders/index.d.ts +1 -1
  19. package/dist/server/plugins/config-parser/loaders/redocly-config-loader.js +1 -1
  20. package/dist/server/plugins/config-parser/loaders/utils/calculate-content-slugs.d.ts +32 -0
  21. package/dist/server/plugins/config-parser/loaders/utils/calculate-content-slugs.js +1 -0
  22. package/dist/server/plugins/config-parser/loaders/versions-config-loader.d.ts +0 -2
  23. package/dist/server/plugins/config-parser/loaders/versions-config-loader.js +1 -1
  24. package/dist/server/plugins/create-slugify.d.ts +1 -1
  25. package/dist/server/plugins/create-slugify.js +1 -1
  26. package/dist/server/plugins/get-reserved-routes.js +1 -1
  27. package/dist/server/plugins/lifecycle.js +1 -1
  28. package/dist/server/plugins/markdown/attribute-resolvers/resolve-link.js +1 -1
  29. package/dist/server/plugins/mcp/docs-mcp/tools/core/search.js +2 -2
  30. package/dist/server/plugins/mcp/handlers/docs-mcp-handler.js +1 -1
  31. package/dist/server/plugins/mcp/utils/route-reservation.d.ts +9 -0
  32. package/dist/server/plugins/mcp/utils/route-reservation.js +1 -0
  33. package/dist/server/plugins/nav-utils.js +1 -1
  34. package/dist/server/plugins/utils.d.ts +0 -4
  35. package/dist/server/plugins/utils.js +1 -1
  36. package/dist/server/utils/content/parse-base-name.d.ts +15 -0
  37. package/dist/server/utils/content/parse-base-name.js +1 -0
  38. package/dist/server/utils/rbac/can-access-feature.d.ts +5 -0
  39. package/dist/server/utils/rbac/can-access-feature.js +1 -0
  40. package/dist/server/utils/rbac/can-anonymous-access-mcp-feature.js +1 -1
  41. package/dist/server/utils/rbac/has-scope-access.d.ts +3 -0
  42. package/dist/server/utils/rbac/has-scope-access.js +1 -0
  43. package/dist/server/utils/rbac.d.ts +5 -3
  44. package/dist/server/utils/rbac.js +1 -1
  45. package/dist/server/web-server/routes/ask-ai.js +1 -1
  46. package/dist/server/web-server/routes/mcp-routes/mcp-client-metadata.js +1 -1
  47. package/dist/server/web-server/routes/semantic-search.js +1 -1
  48. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @redocly/redoc-reef
2
2
 
3
+ ## 0.141.0-next.13
4
+
5
+ ### Patch Changes
6
+
7
+ - ec214ff705a: Hardened validation of authorization requests.
8
+ - 4670a926cdf: Fixed an issue where a search term containing only spaces caused the "Clear filters" button to appear in the catalog, classic catalog, and scorecard when no filters were active.
9
+ - 4670a926cdf: Fixed an issue where the catalog date-range filter displayed its selection bar when the filter was expanded.
10
+
11
+ - 4670a926cdf: Improved the catalog filters: the selection bar uses the primary color of the theme, and you can change it with the `--catalog-filter-selected-indicator-color` CSS variable.
12
+ - 0f43878a651: Fixed an issue where the MCP server's search returned links on the Redocly domain instead of the project's custom domain.
13
+ - Updated dependencies [4670a926cdf]
14
+ - Updated dependencies [4670a926cdf]
15
+ - Updated dependencies [4670a926cdf]
16
+ - Updated dependencies [06b8cb141a7]
17
+ - @redocly/theme@0.73.0-next.9
18
+ - @redocly/api-docs@0.6.0-next.13
19
+
3
20
  ## 0.141.0-next.12
4
21
 
5
22
  ### Minor Changes
@@ -0,0 +1,3 @@
1
+ /** Paths the esbuild build resolves as assets: copied to the output, imported as their URL. */
2
+ export declare const ASSETS_FILTER: RegExp;
3
+ //# sourceMappingURL=assets.d.ts.map
@@ -0,0 +1 @@
1
+ const f=/\.(gif|jpe?g|tiff?|png|webp|bmp|eot|otf|woff|woff2|ttf|pdf|svg|mp4|webm)$/i;export{f as ASSETS_FILTER};
@@ -7,12 +7,9 @@ export declare const PUBLIC_API_DEFINITIONS_FOLDER = "/_bundle";
7
7
  export declare const PUBLIC_STATIC_FOLDER = "static";
8
8
  export declare const STATIC_DATA_FOLDER = "static-data";
9
9
  export declare const LINK_ORIGINAL_ATTR_NAME = "redocly:::linkOriginal";
10
- export declare const VERSION_SEPARATOR = "@";
11
10
  export declare const DEFAULT_VERSION_NAME = "default";
12
- export declare const VERSIONED_FOLDER_REGEXP_MATCH: RegExp;
13
11
  export declare const DEFAULT_THEME_PLUGIN_PATH = "@redocly/theme/plugin.js";
14
12
  export declare const STYLES_FILE = "styles.css";
15
- export declare const DEFAULT_PROJECT_PLUGIN_PATHS: string[];
16
13
  /** Public constant. A deployment that keeps it has no project-scoped secret to sign with. */
17
14
  export declare const FALLBACK_JWT_SECRET_KEY = "test_secret_key";
18
15
  export declare const JWT_SECRET_KEY: string;
@@ -1 +1 @@
1
- import{ServerRoutes as n}from"../../constants/api.js";import{USER_THEME_ALIAS as A}from"../../constants/common.js";import{envConfig as _}from"../config/env-config.js";const N="runtime",x="_scorecard",a="page-data",M="/assets",U="/_spec",P="/_bundle",l="static",i="static-data",m="redocly:::linkOriginal",F="@",K="default",H=new RegExp("((?!@i18n\\/|@l10n\\/)\\/?@.*?(?=\\/))","g"),Y="@redocly/theme/plugin.js",d="styles.css",B=["@theme/plugin.js","@theme/plugin.cjs","@theme/plugin.mjs"],I="test_secret_key",G=_.JWT_SECRET_KEY||I,S=4096,L=196,u=S-L,g=3600,W=720*60*60,h=1440*60,c="@i18n",r="@l10n",k=[A,c,r,"@api","@mcp"],J="https://redocly.com/auth/aud",f="catalog.json",w="scorecard.json",X="page-count.json",j="sitemap.xml",V="llms.txt",o=_.PROJECT_ID,$=_.PROJECT_SLUG,R=_.ORGANIZATION_ID,v=_.ORG_SLUG,t=_.BH_API_URL,E=t&&R&&o?`${t}/orgs/${R}/projects/${o}`:void 0,C=t?`${t}/entitlements/.well-known/jwks`:"https://app.cloud.redocly.com/api/entitlements/.well-known/jwks",y=_.ENTITLEMENTS_JWKS_CDN_URL||C,b=E?`${E}/feedback`:"",Z=E?`${E}/ai-agentic-conversations`:"",q=E?`${E}/ai-assistant-escalations`:"",z=E?`${E}/ai-assistant-feedback`:"",Q=E?`${E}/semantic-search`:"",__="no-store",E_=365*24*60*60,t_="X-Redocly-Cache-Control",o_="no-cache",R_="public, s-maxage=86400, max-age=10, must-revalidate",e_=_.AUTH_URL,s_="Developer Documentation",e=_.REDOCLY_SSR_RENDER_MODE==="worker"?"worker":"main",T_=e==="main"?0:_.REDOCLY_SSR_WORKERS_MIN!=null?Number(_.REDOCLY_SSR_WORKERS_MIN):2,n_=e==="main"?1:_.REDOCLY_SSR_WORKERS_MAX!=null?Number(_.REDOCLY_SSR_WORKERS_MAX):5,A_="-----BEGIN CERTIFICATE-----",I_="-----END CERTIFICATE-----",S_=!_.isDevelopMode&&_.REDOCLY_TELEMETRY!=="off"||_.REDOCLY_TELEMETRY==="on",L_="http://localhost:4318/v1/traces",c_=[n.HEALTH],s=_.SERVER_EDITOR_APP_URL||"http://127.0.0.1:3000",r_=_.REDOCLY_CORS_ORIGINS?_.REDOCLY_CORS_ORIGINS.split(",").map(T=>T.trim()).filter(Boolean).concat(s):[s],C_="markdown/partials",O_="markdown/partials-deps";export{q as AI_ASSISTANT_ESCALATIONS_API_URL,z as AI_ASSISTANT_FEEDBACK_API_URL,r_ as ALLOWED_CORS_ORIGINS,J as ALTERNATIVE_AUD_CLAIM_NAME,Z as ASK_AI_API_URL,e_ as AUTH_URL,A_ as BEGIN_CERTIFICATE_DELIMITER,E as BH_API_PROJECTS_URL,__ as CACHE_CONTROL_NO_STORE_HEADER_VALUE,o_ as CACHE_CONTROL_PUBLIC_HTML,f as CATALOG_OUTPUT_FILE_NAME,E_ as DEFAULT_IMMUTABLE_CACHE_MAX_AGE,B as DEFAULT_PROJECT_PLUGIN_PATHS,Y as DEFAULT_THEME_PLUGIN_PATH,s_ as DEFAULT_TITLE,K as DEFAULT_VERSION_NAME,U as DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER,I_ as END_CERTIFICATE_DELIMITER,y as ENTITLEMENTS_JWKS_URL,I as FALLBACK_JWT_SECRET_KEY,b as FEEDBACK_API_URL,c as I18N_DIR_NAME,G as JWT_SECRET_KEY,r as L10N_DIR_NAME,m as LINK_ORIGINAL_ATTR_NAME,V as LLMS_TXT_FILE_NAME,C_ as MARKDOC_PARTIALS_DATA_KEY,O_ as MARKDOC_PARTIALS_DEPS_KEY,u as MAX_AUTH_TOKEN_COOKIE_BYTES,g as MCP_ACCESS_TOKEN_TTL_SEC,h as MCP_CLAIMS_ONLY_SESSION_LIFETIME_SEC,W as MCP_REFRESH_SESSION_LIFETIME_SEC,R as ORG_ID,v as ORG_SLUG,c_ as OTEL_EXCLUDED_ROUTES,L_ as OTEL_TRACES_DEV_URL,X as PAGE_COUNT_OUTPUT_FILE_NAME,a as PAGE_DATA_FOLDER,o as PROJECT_ID,$ as PROJECT_SLUG,P as PUBLIC_API_DEFINITIONS_FOLDER,M as PUBLIC_ASSETS_FOLDER,l as PUBLIC_STATIC_FOLDER,k as RESERVED_DIR_NAMES,N as RUNTIME_RESOURCES_DIR,x as SCORECARD_CLASSIC_FOLDER,w as SCORECARD_OUTPUT_FILE_NAME,Q as SEMANTIC_SEARCH_API_URL,s as SERVER_EDITOR_APP_URL,j as SITEMAP_FILE_NAME,e as SSR_RENDER_MODE,n_ as SSR_WORKERS_MAX,T_ as SSR_WORKERS_MIN,i as STATIC_DATA_FOLDER,d as STYLES_FILE,S_ as TELEMETRY_ENABLED,H as VERSIONED_FOLDER_REGEXP_MATCH,F as VERSION_SEPARATOR,t_ as X_REDOCLY_CACHE_CONTROL_HEADER,R_ as X_REDOCLY_CACHE_CONTROL_PUBLIC_HTML};
1
+ import{ServerRoutes as A}from"../../constants/api.js";import{USER_THEME_ALIAS as n}from"../../constants/common.js";import{envConfig as _}from"../config/env-config.js";const N="runtime",x="_scorecard",a="page-data",M="/assets",U="/_spec",P="/_bundle",l="static",i="static-data",m="redocly:::linkOriginal",F="default",K="@redocly/theme/plugin.js",Y="styles.css",I="test_secret_key",d=_.JWT_SECRET_KEY||I,S=4096,L=196,B=S-L,H=3600,G=720*60*60,u=1440*60,c="@i18n",r="@l10n",W=[n,c,r,"@api","@mcp"],k="https://redocly.com/auth/aud",f="catalog.json",J="scorecard.json",g="page-count.json",h="sitemap.xml",w="llms.txt",o=_.PROJECT_ID,X=_.PROJECT_SLUG,R=_.ORGANIZATION_ID,$=_.ORG_SLUG,t=_.BH_API_URL,E=t&&R&&o?`${t}/orgs/${R}/projects/${o}`:void 0,C=t?`${t}/entitlements/.well-known/jwks`:"https://app.cloud.redocly.com/api/entitlements/.well-known/jwks",V=_.ENTITLEMENTS_JWKS_CDN_URL||C,j=E?`${E}/feedback`:"",v=E?`${E}/ai-agentic-conversations`:"",y=E?`${E}/ai-assistant-escalations`:"",b=E?`${E}/ai-assistant-feedback`:"",Z=E?`${E}/semantic-search`:"",q="no-store",z=365*24*60*60,Q="X-Redocly-Cache-Control",__="no-cache",E_="public, s-maxage=86400, max-age=10, must-revalidate",t_=_.AUTH_URL,o_="Developer Documentation",e=_.REDOCLY_SSR_RENDER_MODE==="worker"?"worker":"main",R_=e==="main"?0:_.REDOCLY_SSR_WORKERS_MIN!=null?Number(_.REDOCLY_SSR_WORKERS_MIN):2,e_=e==="main"?1:_.REDOCLY_SSR_WORKERS_MAX!=null?Number(_.REDOCLY_SSR_WORKERS_MAX):5,T_="-----BEGIN CERTIFICATE-----",s_="-----END CERTIFICATE-----",A_=!_.isDevelopMode&&_.REDOCLY_TELEMETRY!=="off"||_.REDOCLY_TELEMETRY==="on",n_="http://localhost:4318/v1/traces",I_=[A.HEALTH],T=_.SERVER_EDITOR_APP_URL||"http://127.0.0.1:3000",S_=_.REDOCLY_CORS_ORIGINS?_.REDOCLY_CORS_ORIGINS.split(",").map(s=>s.trim()).filter(Boolean).concat(T):[T],L_="markdown/partials",c_="markdown/partials-deps";export{y as AI_ASSISTANT_ESCALATIONS_API_URL,b as AI_ASSISTANT_FEEDBACK_API_URL,S_ as ALLOWED_CORS_ORIGINS,k as ALTERNATIVE_AUD_CLAIM_NAME,v as ASK_AI_API_URL,t_ as AUTH_URL,T_ as BEGIN_CERTIFICATE_DELIMITER,E as BH_API_PROJECTS_URL,q as CACHE_CONTROL_NO_STORE_HEADER_VALUE,__ as CACHE_CONTROL_PUBLIC_HTML,f as CATALOG_OUTPUT_FILE_NAME,z as DEFAULT_IMMUTABLE_CACHE_MAX_AGE,K as DEFAULT_THEME_PLUGIN_PATH,o_ as DEFAULT_TITLE,F as DEFAULT_VERSION_NAME,U as DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER,s_ as END_CERTIFICATE_DELIMITER,V as ENTITLEMENTS_JWKS_URL,I as FALLBACK_JWT_SECRET_KEY,j as FEEDBACK_API_URL,c as I18N_DIR_NAME,d as JWT_SECRET_KEY,r as L10N_DIR_NAME,m as LINK_ORIGINAL_ATTR_NAME,w as LLMS_TXT_FILE_NAME,L_ as MARKDOC_PARTIALS_DATA_KEY,c_ as MARKDOC_PARTIALS_DEPS_KEY,B as MAX_AUTH_TOKEN_COOKIE_BYTES,H as MCP_ACCESS_TOKEN_TTL_SEC,u as MCP_CLAIMS_ONLY_SESSION_LIFETIME_SEC,G as MCP_REFRESH_SESSION_LIFETIME_SEC,R as ORG_ID,$ as ORG_SLUG,I_ as OTEL_EXCLUDED_ROUTES,n_ as OTEL_TRACES_DEV_URL,g as PAGE_COUNT_OUTPUT_FILE_NAME,a as PAGE_DATA_FOLDER,o as PROJECT_ID,X as PROJECT_SLUG,P as PUBLIC_API_DEFINITIONS_FOLDER,M as PUBLIC_ASSETS_FOLDER,l as PUBLIC_STATIC_FOLDER,W as RESERVED_DIR_NAMES,N as RUNTIME_RESOURCES_DIR,x as SCORECARD_CLASSIC_FOLDER,J as SCORECARD_OUTPUT_FILE_NAME,Z as SEMANTIC_SEARCH_API_URL,T as SERVER_EDITOR_APP_URL,h as SITEMAP_FILE_NAME,e as SSR_RENDER_MODE,e_ as SSR_WORKERS_MAX,R_ as SSR_WORKERS_MIN,i as STATIC_DATA_FOLDER,Y as STYLES_FILE,A_ as TELEMETRY_ENABLED,Q as X_REDOCLY_CACHE_CONTROL_HEADER,E_ as X_REDOCLY_CACHE_CONTROL_PUBLIC_HTML};
@@ -0,0 +1,12 @@
1
+ import { redocConfigSchema, rootRedoclyConfigSchema } from '@redocly/config';
2
+ type RootConfigSchema = Omit<typeof rootRedoclyConfigSchema, 'properties'> & {
3
+ properties: Omit<typeof rootRedoclyConfigSchema.properties, 'openapi'> & {
4
+ openapi: typeof redocConfigSchema;
5
+ };
6
+ };
7
+ /**
8
+ * The schema the root `redocly.yaml` is validated against, before project plugins add their own.
9
+ */
10
+ export declare const ROOT_CONFIG_SCHEMA: RootConfigSchema;
11
+ export {};
12
+ //# sourceMappingURL=config-schema.d.ts.map
@@ -0,0 +1 @@
1
+ import{redocConfigSchema as e,rootRedoclyConfigSchema as o}from"@redocly/config";const p={...o,properties:{...o.properties,openapi:e}};export{p as ROOT_CONFIG_SCHEMA};
@@ -0,0 +1,2 @@
1
+ export declare const DEFAULT_PROJECT_PLUGIN_PATHS: string[];
2
+ //# sourceMappingURL=project-plugins.d.ts.map
@@ -0,0 +1 @@
1
+ const e=["@theme/plugin.js","@theme/plugin.cjs","@theme/plugin.mjs"];export{e as DEFAULT_PROJECT_PLUGIN_PATHS};
@@ -0,0 +1,3 @@
1
+ export declare const VERSION_SEPARATOR = "@";
2
+ export declare const VERSIONED_FOLDER_REGEXP_MATCH: RegExp;
3
+ //# sourceMappingURL=versions.d.ts.map
@@ -0,0 +1 @@
1
+ const E="@",R=new RegExp("((?!@i18n\\/|@l10n\\/)\\/?@.*?(?=\\/))","g");export{R as VERSIONED_FOLDER_REGEXP_MATCH,E as VERSION_SEPARATOR};
@@ -1 +1 @@
1
- import*as i from"path";import{existsSync as d,readFileSync as v}from"fs";import{USER_THEME_ALIAS as w}from"../../../constants/common.js";import{setMapValue as m}from"../../../utils/collection/set-map-value.js";import{isLocalLink as S}from"../../../utils/path/is-local-link.js";import{reporter as E}from"../../tools/notifiers/reporter.js";import{envConfig as P}from"../../config/env-config.js";import{copyStaticFile as x}from"../../utils/index.js";import{reportEsbuildError as y}from"../esbuild-logger.js";const f=/\.(gif|jpe?g|tiff?|png|webp|bmp|eot|otf|woff|woff2|ttf|pdf|svg|mp4|webm)$/i,A=["require-call","dynamic-import"],L=(u,n)=>{const l=i.resolve(n,w),t=new Map,r=new Map;return{name:"esbuild-redocly-custom-assets-resolver",setup:a=>{a.onStart(()=>{r.clear(),E.clearEsbuildProblems()}),a.onResolve({filter:f},async e=>{if(!S(e.path))return{external:!0};const o=i.resolve(e.resolveDir,e.path);if(!d(o)){if(P.isDevelopMode&&!A.includes(e.kind)){r.has(e.importer)||r.set(e.importer,v(e.importer,"utf-8"));const p=r.get(e.importer),h=i.relative(n,e.importer);return y(`Could not resolve asset: ${e.path}`,h,p,{lineText:e.path}),{external:!0}}return}const s=e.kind+":"+o;if(t.has(s))return t.get(s);const c=await x(e.resolveDir,o,u.outdir);if(e.kind==="url-token")return m(t,s,{external:!0,path:c,watchDirs:[l]});{const p=i.relative(n,o);return m(t,s,{namespace:"assets-ns",path:p,pluginData:{assetPath:c},watchDirs:[l]})}}),a.onLoad({filter:f,namespace:"assets-ns"},({pluginData:e})=>({contents:e.assetPath,loader:"text"}))}}};export{L as AssetsResolver};
1
+ import*as i from"path";import{existsSync as d,readFileSync as v}from"fs";import{USER_THEME_ALIAS as S}from"../../../constants/common.js";import{ASSETS_FILTER as m}from"../../constants/assets.js";import{setMapValue as u}from"../../../utils/collection/set-map-value.js";import{isLocalLink as E}from"../../../utils/path/is-local-link.js";import{reporter as P}from"../../tools/notifiers/reporter.js";import{envConfig as x}from"../../config/env-config.js";import{copyStaticFile as y}from"../../utils/index.js";import{reportEsbuildError as A}from"../esbuild-logger.js";const D=["require-call","dynamic-import"],F=(f,n)=>{const p=i.resolve(n,S),t=new Map,r=new Map;return{name:"esbuild-redocly-custom-assets-resolver",setup:a=>{a.onStart(()=>{r.clear(),P.clearEsbuildProblems()}),a.onResolve({filter:m},async e=>{if(!E(e.path))return{external:!0};const o=i.resolve(e.resolveDir,e.path);if(!d(o)){if(x.isDevelopMode&&!D.includes(e.kind)){r.has(e.importer)||r.set(e.importer,v(e.importer,"utf-8"));const l=r.get(e.importer),h=i.relative(n,e.importer);return A(`Could not resolve asset: ${e.path}`,h,l,{lineText:e.path}),{external:!0}}return}const s=e.kind+":"+o;if(t.has(s))return t.get(s);const c=await y(e.resolveDir,o,f.outdir);if(e.kind==="url-token")return u(t,s,{external:!0,path:c,watchDirs:[p]});{const l=i.relative(n,o);return u(t,s,{namespace:"assets-ns",path:l,pluginData:{assetPath:c},watchDirs:[p]})}}),a.onLoad({filter:m,namespace:"assets-ns"},({pluginData:e})=>({contents:e.assetPath,loader:"text"}))}}};export{F as AssetsResolver};
@@ -1 +1 @@
1
- import{existsSync as m,readFileSync as F}from"node:fs";import{createRequire as k}from"node:module";import s from"node:path";import{resolvePlugins as A}from"@redocly/openapi-core";import{DEFAULT_PROJECT_PLUGIN_PATHS as d,DEFAULT_THEME_PLUGIN_PATH as c,STYLES_FILE as S}from"../constants/common.js";import{GATED_PLUGINS as v}from"../constants/entitlements.js";import{DEFAULT_THEME_NAME as h}from"../../constants/common.js";import{isDefined as _}from"../../utils/guards/is-defined.js";import{isPlainObject as g}from"../../utils/guards/is-plain-object.js";import{logger as C}from"../tools/notifiers/logger.js";import{reporter as L}from"../tools/notifiers/reporter.js";import{sha as w}from"../utils/crypto/sha.js";import{resolveModule as P}from"./resolve-module.js";import{EntitlementsProvider as I}from"../entitlements/entitlements-provider.js";const f={sha:"",value:Promise.resolve({resolvedPlugins:[],errors:[]})};async function ee(e,r=[]){const n=w(JSON.stringify(r));if(f.sha!==n){f.sha=n;const o=M(e),a=N(e,r,o),p=await A(a,e)||[];if(!a.some(i=>d.includes(i))){const i=d[0],l=s.join(e,i);p.push({id:"",absolutePath:l,path:i})}f.value=Promise.all(p.map(i=>b(i,i.path===o?c:i.path))).then(i=>{const l=i.filter(_),j=l.filter(u=>u?.type&&["error","warning"].includes(u.type)),D=l.filter(u=>u.type==="resolvedPlugin");return{errors:j,resolvedPlugins:D}})}const t=await f.value;if(t.errors.length)for(let o=0;o<t.errors.length;o++)await L.panicOnBuildContentError(t.errors[o].error);return t.resolvedPlugins}function M(e){const r=s.resolve(e,"package.json");if(!y(s.dirname(r)))return P(c)??c;const n=E(o=>k(r).resolve(o)),t=E(P);return n&&t&&n!==t&&C.warn("The project declares %s %s, and Realm uses it instead of the %s it was built with.",h,n,t),c}function y(e){const r=T(s.join(e,"package.json")),n=[r?.dependencies,r?.devDependencies].some(o=>g(o)&&h in o),t=s.dirname(e);return n||t!==e&&y(t)}function E(e){try{const r=e(`${h}/package.json`),n=r&&T(r)?.version;return typeof n=="string"?n:void 0}catch{return}}function T(e){try{const r=JSON.parse(F(e,"utf8"));return g(r)?r:void 0}catch{return}}function N(e,r=[],n){const t=[...r];for(const o of d)!t.includes(o)&&m(s.join(e,o))&&t.push(o);return t.includes(c)||t.unshift(n),t}async function b(e,r){if(!e.absolutePath||!r)return{type:"error",error:`Plugin with path "${e}" not found`};const n=s.dirname(e.absolutePath),{lifecyclePlugin:t,config:o}=R(e,r);return{name:s.dirname(r),type:"resolvedPlugin",isNpmPackage:O(r),pluginDirAbsolutePath:n,lifecyclePlugin:t,config:o,stylesFile:s.resolve(n,S),markdoc:U(n)}}function O(e){const r=s.dirname(e);return P(s.join(r,"package.json"))!=null}function R(e,r){const n=I.instance(),t=!n.canAccessFeature("customPlugins")&&!v.includes(r),o=e.requiredEntitlements&&v.includes(r)&&!e.requiredEntitlements.every(a=>n.canAccessFeature(a));return t||o?{lifecyclePlugin:{id:e.id},config:{}}:{lifecyclePlugin:{id:e.id,processContent:e.processContent,afterRoutesCreated:e.afterRoutesCreated,loaders:e.loaders,requiredEntitlements:e.requiredEntitlements},config:{schema:e.redoclyConfigSchema,ejectIgnore:e.ejectIgnore}}}function U(e){const r=s.resolve(e,"markdoc"),n=s.join(r,"schema.ts");if(!m(n))return null;const t=s.join(r,"components.tsx");return{schemaFile:n,componentsFile:m(t)?t:void 0}}export{ee as resolveExternalPlugins};
1
+ import{existsSync as m,readFileSync as F}from"node:fs";import{createRequire as k}from"node:module";import s from"node:path";import{resolvePlugins as A}from"@redocly/openapi-core";import{DEFAULT_THEME_PLUGIN_PATH as c,STYLES_FILE as S}from"../constants/common.js";import{DEFAULT_PROJECT_PLUGIN_PATHS as d}from"../constants/project-plugins.js";import{GATED_PLUGINS as v}from"../constants/entitlements.js";import{DEFAULT_THEME_NAME as h}from"../../constants/common.js";import{isDefined as _}from"../../utils/guards/is-defined.js";import{isPlainObject as g}from"../../utils/guards/is-plain-object.js";import{logger as C}from"../tools/notifiers/logger.js";import{reporter as L}from"../tools/notifiers/reporter.js";import{sha as w}from"../utils/crypto/sha.js";import{resolveModule as P}from"./resolve-module.js";import{EntitlementsProvider as I}from"../entitlements/entitlements-provider.js";const f={sha:"",value:Promise.resolve({resolvedPlugins:[],errors:[]})};async function re(e,r=[]){const n=w(JSON.stringify(r));if(f.sha!==n){f.sha=n;const o=M(e),a=N(e,r,o),p=await A(a,e)||[];if(!a.some(i=>d.includes(i))){const i=d[0],l=s.join(e,i);p.push({id:"",absolutePath:l,path:i})}f.value=Promise.all(p.map(i=>b(i,i.path===o?c:i.path))).then(i=>{const l=i.filter(_),j=l.filter(u=>u?.type&&["error","warning"].includes(u.type)),D=l.filter(u=>u.type==="resolvedPlugin");return{errors:j,resolvedPlugins:D}})}const t=await f.value;if(t.errors.length)for(let o=0;o<t.errors.length;o++)await L.panicOnBuildContentError(t.errors[o].error);return t.resolvedPlugins}function M(e){const r=s.resolve(e,"package.json");if(!y(s.dirname(r)))return P(c)??c;const n=E(o=>k(r).resolve(o)),t=E(P);return n&&t&&n!==t&&C.warn("The project declares %s %s, and Realm uses it instead of the %s it was built with.",h,n,t),c}function y(e){const r=T(s.join(e,"package.json")),n=[r?.dependencies,r?.devDependencies].some(o=>g(o)&&h in o),t=s.dirname(e);return n||t!==e&&y(t)}function E(e){try{const r=e(`${h}/package.json`),n=r&&T(r)?.version;return typeof n=="string"?n:void 0}catch{return}}function T(e){try{const r=JSON.parse(F(e,"utf8"));return g(r)?r:void 0}catch{return}}function N(e,r=[],n){const t=[...r];for(const o of d)!t.includes(o)&&m(s.join(e,o))&&t.push(o);return t.includes(c)||t.unshift(n),t}async function b(e,r){if(!e.absolutePath||!r)return{type:"error",error:`Plugin with path "${e}" not found`};const n=s.dirname(e.absolutePath),{lifecyclePlugin:t,config:o}=R(e,r);return{name:s.dirname(r),type:"resolvedPlugin",isNpmPackage:O(r),pluginDirAbsolutePath:n,lifecyclePlugin:t,config:o,stylesFile:s.resolve(n,S),markdoc:U(n)}}function O(e){const r=s.dirname(e);return P(s.join(r,"package.json"))!=null}function R(e,r){const n=I.instance(),t=!n.canAccessFeature("customPlugins")&&!v.includes(r),o=e.requiredEntitlements&&v.includes(r)&&!e.requiredEntitlements.every(a=>n.canAccessFeature(a));return t||o?{lifecyclePlugin:{id:e.id},config:{}}:{lifecyclePlugin:{id:e.id,processContent:e.processContent,afterRoutesCreated:e.afterRoutesCreated,loaders:e.loaders,requiredEntitlements:e.requiredEntitlements},config:{schema:e.redoclyConfigSchema,ejectIgnore:e.ejectIgnore}}}function U(e){const r=s.resolve(e,"markdoc"),n=s.join(r,"schema.ts");if(!m(n))return null;const t=s.join(r,"components.tsx");return{schemaFile:n,componentsFile:m(t)?t:void 0}}export{re as resolveExternalPlugins};
@@ -1 +1 @@
1
- import c from"node:path";import{CONFIG_FILE_NAME as O}from"../../../../constants/common.js";import{normalizeRouteSlug as l}from"../../../../utils/path/normalize-route-slug.js";import{removeLeadingSlash as x}from"../../../../utils/url/remove-leading-slash.js";import{parseBaseName as w}from"../../utils.js";const m=async(t,e)=>{if(!t.match(/(\.ya?ml|\.json)$/)||c.posix.basename(t)===O||await e.isPathIgnored(t))return null;const s=e.fs.getFileInfo(t);if(!s)return null;try{const{data:o}=await e.cache.load(s.realRelativePath,"yaml");return o??null}catch{return null}},L=async(t,e)=>{const s=await m(t,e);return!!(s?.openapi||s?.swagger)},j=async(t,e)=>!!(await m(t,e))?.asyncapi,F=t=>!!t.match(/(\.gql|\.graphql)$/),U=async(t,e,s,o)=>{const{getRouteBySlug:d,getRouteByFsPath:f}=s,i={isOpenapiDetected:!1,isOpenapiValid:!1},g={isOpenapiDetected:!0,isOpenapiValid:!1},h={isOpenapiDetected:!0,isOpenapiValid:!0};let r=t.toLowerCase();if(t.startsWith("/"))r=l(t);else if(t.startsWith("./")||t.startsWith("../")){const n=f(e)?.slug;if(!n)return i;const{isIndexFile:a}=w(e);r=a?l(c.posix.join(n,t)):l(c.posix.join(n,"../",t))}else return i;const p=r.toLowerCase().split("/");for(let n=p.length;n>=0;n--){const a=p.slice(0,n).join("/"),y=p.slice(n).join("/"),u=d(a)||f(x(a));if(u)return await L(u.fsPath,o)?y?g:h:i}return i};export{j as isAsyncapiDoc,F as isGraphqlDoc,U as isOpenApiURL,L as isOpenapiDoc};
1
+ import c from"node:path";import{CONFIG_FILE_NAME as O}from"../../../../constants/common.js";import{normalizeRouteSlug as l}from"../../../../utils/path/normalize-route-slug.js";import{removeLeadingSlash as x}from"../../../../utils/url/remove-leading-slash.js";import{parseBaseName as w}from"../../../utils/content/parse-base-name.js";const m=async(t,e)=>{if(!t.match(/(\.ya?ml|\.json)$/)||c.posix.basename(t)===O||await e.isPathIgnored(t))return null;const s=e.fs.getFileInfo(t);if(!s)return null;try{const{data:o}=await e.cache.load(s.realRelativePath,"yaml");return o??null}catch{return null}},L=async(t,e)=>{const s=await m(t,e);return!!(s?.openapi||s?.swagger)},j=async(t,e)=>!!(await m(t,e))?.asyncapi,F=t=>!!t.match(/(\.gql|\.graphql)$/),U=async(t,e,s,o)=>{const{getRouteBySlug:d,getRouteByFsPath:f}=s,i={isOpenapiDetected:!1,isOpenapiValid:!1},g={isOpenapiDetected:!0,isOpenapiValid:!1},h={isOpenapiDetected:!0,isOpenapiValid:!0};let r=t.toLowerCase();if(t.startsWith("/"))r=l(t);else if(t.startsWith("./")||t.startsWith("../")){const n=f(e)?.slug;if(!n)return i;const{isIndexFile:a}=w(e);r=a?l(c.posix.join(n,t)):l(c.posix.join(n,"../",t))}else return i;const p=r.toLowerCase().split("/");for(let n=p.length;n>=0;n--){const a=p.slice(0,n).join("/"),y=p.slice(n).join("/"),u=d(a)||f(x(a));if(u)return await L(u.fsPath,o)?y?g:h:i}return i};export{j as isAsyncapiDoc,F as isGraphqlDoc,U as isOpenApiURL,L as isOpenapiDoc};
@@ -1 +1 @@
1
- import i from"node:path";import{isL10nPath as m}from"../../../fs/utils/is-l10n-path.js";import{getLocaleFromRelativePath as n}from"../../../fs/utils/get-locale-from-relative-path.js";import{removeL10nPrefix as s}from"../../../fs/utils/remove-l10n-prefix.js";import{parseBaseName as p}from"../../utils.js";function h(r){const{baseName:t,isIndexFile:a}=p(r),e=i.posix.dirname(r),o=a?e==="."?"":e:e==="."?t:i.posix.join(e,t);return m(o)?("/"+n(o).toLowerCase()+"/"+s(o)).replace(/\/{2,}/g,"/"):("/"+o).replace(/\/{2,}/g,"/")}export{h as relativePathToBaseSlug};
1
+ import i from"node:path";import{isL10nPath as m}from"../../../fs/utils/is-l10n-path.js";import{getLocaleFromRelativePath as n}from"../../../fs/utils/get-locale-from-relative-path.js";import{removeL10nPrefix as s}from"../../../fs/utils/remove-l10n-prefix.js";import{parseBaseName as p}from"../../../utils/content/parse-base-name.js";function h(r){const{baseName:t,isIndexFile:a}=p(r),e=i.posix.dirname(r),o=a?e==="."?"":e:e==="."?t:i.posix.join(e,t);return m(o)?("/"+n(o).toLowerCase()+"/"+s(o)).replace(/\/{2,}/g,"/"):("/"+o).replace(/\/{2,}/g,"/")}export{h as relativePathToBaseSlug};
@@ -1,13 +1,4 @@
1
1
  import type { LoaderFn } from '../../../types';
2
- export type SlugCollisions = {
3
- pageVsPage: number;
4
- dirVsDir: number;
5
- };
6
- export type ContentSlugs = {
7
- fileSlugs: Map<string, string>;
8
- dirSlugs: Map<string, string>;
9
- collisions: SlugCollisions;
10
- };
11
- export declare const IGNORED_EXTS: Set<string>;
2
+ import type { ContentSlugs } from './utils/calculate-content-slugs.js';
12
3
  export declare const contentSlugsLoader: LoaderFn<ContentSlugs>;
13
4
  //# sourceMappingURL=content-slugs-loader.d.ts.map
@@ -1 +1 @@
1
- import f from"path";import{combineUrls as S}from"@redocly/theme/core/utils";import{VERSION_SEPARATOR as b}from"../../../constants/common.js";import{removeTrailingSlash as v}from"../../../../utils/url/remove-trailing-slash.js";import{slash as E}from"../../../../utils/path/slash.js";import{logger as m}from"../../../tools/notifiers/logger.js";import{getDefaultVersionByPath as I}from"./versions-config-loader.js";import{GithubSlugger as N,slug as h}from"../../../utils/index.js";import{isPartial as z}from"../../markdown/is-partial.js";import{parseBaseName as T}from"../../utils.js";const j=new Set([".jpg",".jpeg",".png",".gif",".webp",".svg",".ico",".avif",".mp3",".wav",".ogg",".m4a",".mp4",".avi",".mov",".webm",".pdf",".doc",".docx",".zip",".rar",".gz",".ttf",".woff",".woff2"]),U=async(i,{fs:s,cache:r,getConfig:l})=>{const t=m.startTiming(),g=(await r.load("versions-config","versions-config")).data,{markdown:u}=await l(),o=u?.partialsFolders??[],e=new Map,n=new Map,c=new Set,d={pageVsPage:0,dirVsDir:0},D=new N;n.set(".","/"),n.set("/","/");const w=s.scan().sort((a,p)=>p.relativePath.localeCompare(a.relativePath));for(const{relativePath:a}of w){if(j.has(f.posix.extname(a)))continue;const{data:p}=await r.load(a,"is-ignored");if(p||f.posix.extname(a)===".md"&&z(a,o))continue;const F=E(a).replace(new RegExp("^(@i18n|@l10n)\\/"),""),V=I(a,g);y(F,{defaultVersion:V,fileSlugs:e,dirSlugs:n,allFileSlugsList:c,githubSlugger:D,collisions:d})}return m.verboseTime(t,"Calculated slugs. Number of file paths processed: "+w.length),{fileSlugs:e,dirSlugs:n,collisions:d}};function y(i,s){const r=s.fileSlugs.get(i);if(r)return r;const l=f.posix.dirname(i),t=L(l,s)||"",{baseName:g,isIndexFile:u}=T(i),o=s.dirSlugs.has(f.posix.join(l,g));let e;if(!u&&o){const n=h(S(t,g));s.allFileSlugsList.has(n)||(e=n)}if(!e){const n=u?s.dirSlugs.get(l):void 0;if(n)e=n;else{const c=S(t,g),d=h(c);e=s.githubSlugger.slug(c),e!==d&&(s.collisions.pageVsPage++,m.verbose("File slug collision: %s wanted %s, assigned %s",i,d,e))}}e=v(e),s.fileSlugs.set(i,e),s.allFileSlugsList.add(e)}function L(i,s){if(s.dirSlugs.has(i))return s.dirSlugs.get(i);const r=v(f.posix.normalize(i)).split("/");let l="/",t="";for(const g of r){t=f.posix.join(t,g);const u=P(g,s.defaultVersion);let o=s.dirSlugs.get(t);if(!o){const e=S("/",l,u),n=h(e);o=s.githubSlugger.slug(e),o!==n&&(s.collisions.dirVsDir++,m.verbose("Directory slug collision: %s wanted %s, assigned %s",t,n,o))}o.endsWith("/")||(o=o+"/"),s.dirSlugs.set(t,o),l=o}return s.dirSlugs.get(i)}function P(i,s){if(!i.startsWith(b))return i;const r=i.substring(b.length);return r===s?"":r}export{j as IGNORED_EXTS,U as contentSlugsLoader};
1
+ import{logger as o}from"../../../tools/notifiers/logger.js";import{calculateContentSlugs as p}from"./utils/calculate-content-slugs.js";const f={pageVsPage:"File slug collision: %s wanted %s, assigned %s",dirVsDir:"Directory slug collision: %s wanted %s, assigned %s"},C=async(w,{fs:t,cache:a,getConfig:n})=>{const i=o.startTiming(),r=(await a.load("versions-config","versions-config")).data,{markdown:l}=await n(),c=l?.partialsFolders??[],e=t.scan().map(({relativePath:s})=>s),g=await p(e,{isIgnored:async s=>(await a.load(s,"is-ignored")).data,partialsFolders:c,versionsConfig:r,onCollision:({kind:s,relativePath:d,desiredSlug:m,assignedSlug:u})=>o.verbose(f[s],d,m,u)});return o.verboseTime(i,"Calculated slugs. Number of file paths processed: "+e.length),g};export{C as contentSlugsLoader};
@@ -3,7 +3,7 @@ export declare const DEFAULT_LOADERS: {
3
3
  'redocly-config': import("../../../types/fs.js").LoaderFn;
4
4
  'product-config': import("../../../types/fs.js").LoaderFn;
5
5
  'versions-config': import("../../../types/fs.js").LoaderFn;
6
- 'content-slugs': import("../../../types/fs.js").LoaderFn<import("./content-slugs-loader.js").ContentSlugs>;
6
+ 'content-slugs': import("../../../types/fs.js").LoaderFn<import("./utils/calculate-content-slugs.js").ContentSlugs>;
7
7
  'is-ignored': import("../../../types/fs.js").LoaderFn<boolean>;
8
8
  yaml: import("../../../types/fs.js").LoaderFn;
9
9
  };
@@ -1 +1 @@
1
- import{DEFAULT_SEARCH_ENGINE as p,redocConfigSchema as A,rootRedoclyConfigSchema as i}from"@redocly/config";import F from"is-glob";import{I18N_DIR_NAME as u,L10N_DIR_NAME as l}from"../../../constants/common.js";import{CONFIG_FILE_NAME as f}from"../../../../constants/common.js";import{deepMerge as C}from"../../../../utils/object/deep-merge.js";import{logger as o}from"../../../tools/notifiers/logger.js";import{EntitlementsProvider as b}from"../../../entitlements/entitlements-provider.js";import{readAndValidateConfig as h}from"./utils/read-and-validate-config.js";import{resolveExternalPlugins as y}from"../../../external-plugins/resolve-external-plugins.js";import{getPathForAllLocales as m}from"../../../fs/utils/get-path-for-all-locales.js";import{parseRbacConfig as E}from"../../../utils/rbac.js";import{RbacConfigLocation as S,validateRbacConfig as v}from"../../validate-rbac-config.js";const R=["**/_partials/**"],$=async(e,{fs:n},s)=>{const r=await h(e,n,s,async t=>e===f?L(n.cwd,t?.plugins||[]):void 0);if(r?.access?.rbac){const t=await E(r.access.rbac);r.access.rbac=t,v(t,e===f?S.RootRedoclyYaml:void 0)}(r?.l10n||r?.i18n)&&(r.l10n=w(r),r.i18n=void 0);const c=C(r||{},{markdown:{partialsFolders:(r?.markdown?.partialsFolders||R).flatMap(t=>m(t,n))}});return _({...c,configPath:e,ignore:g(r?.ignore,n)})};async function L(e,n){const s=await y(e,n),r=s.map(a=>a.config.schema?a.lifecyclePlugin.id:""),c={};for(const a of s){const d=a.lifecyclePlugin?.id;a.config.schema&&d&&i.properties&&(c[d]=a.config.schema)}return{...i,properties:{...c,...i.properties,openapi:A},$id:i.$id+r.join("")}}function _(e){const n=b.instance();if(n.canAccessFeature("apiFunctions")||(e.apiFunctions=void 0),n.canAccessFeature("products")||(e.products=void 0),n.canAccessFeature("breadcrumbs")||(e.breadcrumbs={hide:!0}),n.canAccessFeature("seo")||(e.seo={llmstxt:{hide:!0}}),n.canAccessFeature("redirects")||(e.redirects={}),n.canAccessFeature("l10n")||(e.l10n=void 0),n.canAccessFeature("rbac")||e.access&&(e.access.rbac=void 0),n.canAccessFeature("sso")||e.access&&(e.access.sso=void 0),n.canAccessFeature("ssoDirect")||(e.ssoDirect=void 0),n.canAccessFeature("catalogClassic")||(e.catalog=void 0,e.catalogClassic=void 0),n.canAccessFeature("scorecard")||(e.scorecard=void 0,e.scorecardClassic=void 0),n.canAccessFeature("scorecards")||(e.scorecards=void 0),n.canAccessFeature("devOnboarding")||(e.developerOnboarding=void 0),n.canAccessFeature("analytics")||(e.analytics=void 0),n.canAccessFeature("removeAttribution")||(e.removeAttribution=void 0),n.canAccessFeature("mockServer")||(e.mockServer={off:!0}),n.canAccessFeature("advancedSearch")||e.search&&(e.search.engine=p),n.canAccessFeature("banner")||(e.banner=void 0),e.consent){const s=n.entitlements;s&&!Object.prototype.hasOwnProperty.call(s,"cookieConsent")?o.warn("The plan gates token has no cookieConsent entry. The consent option stays on."):n.canAccessFeature("cookieConsent")||(o.error("The consent option requires the Enterprise+ plan. It is ignored, and analytics loads without consent."),e.consent=void 0)}return e}function g(e=[],n){return["static",...e].flatMap(s=>F(s)&&(s.startsWith("*")||s.startsWith(l)||s.startsWith("/"+l)||s.startsWith(u)||s.startsWith("/"+u))?s:m(s,n))}function w(e){return e.i18n&&o.warn("The `i18n` configuration is deprecated. Please use `l10n` instead."),e.l10n||e.i18n||{}}export{$ as redoclyConfigLoader};
1
+ import{DEFAULT_SEARCH_ENGINE as A,rootRedoclyConfigSchema as d}from"@redocly/config";import F from"is-glob";import{I18N_DIR_NAME as u,L10N_DIR_NAME as l}from"../../../constants/common.js";import{ROOT_CONFIG_SCHEMA as f}from"../../../constants/config-schema.js";import{CONFIG_FILE_NAME as m}from"../../../../constants/common.js";import{deepMerge as C}from"../../../../utils/object/deep-merge.js";import{logger as i}from"../../../tools/notifiers/logger.js";import{EntitlementsProvider as b}from"../../../entitlements/entitlements-provider.js";import{readAndValidateConfig as h}from"./utils/read-and-validate-config.js";import{resolveExternalPlugins as y}from"../../../external-plugins/resolve-external-plugins.js";import{getPathForAllLocales as p}from"../../../fs/utils/get-path-for-all-locales.js";import{parseRbacConfig as E}from"../../../utils/rbac.js";import{RbacConfigLocation as R,validateRbacConfig as S}from"../../validate-rbac-config.js";const _=["**/_partials/**"],$=async(e,{fs:n},s)=>{const r=await h(e,n,s,async t=>e===m?v(n.cwd,t?.plugins||[]):void 0);if(r?.access?.rbac){const t=await E(r.access.rbac);r.access.rbac=t,S(t,e===m?R.RootRedoclyYaml:void 0)}(r?.l10n||r?.i18n)&&(r.l10n=w(r),r.i18n=void 0);const c=C(r||{},{markdown:{partialsFolders:(r?.markdown?.partialsFolders||_).flatMap(t=>p(t,n))}});return I({...c,configPath:e,ignore:L(r?.ignore,n)})};async function v(e,n){const s=await y(e,n),r=s.map(a=>a.config.schema?a.lifecyclePlugin.id:""),c={};for(const a of s){const o=a.lifecyclePlugin?.id;a.config.schema&&o&&d.properties&&(c[o]=a.config.schema)}return{...f,properties:{...c,...f.properties},$id:d.$id+r.join("")}}function I(e){const n=b.instance();if(n.canAccessFeature("apiFunctions")||(e.apiFunctions=void 0),n.canAccessFeature("products")||(e.products=void 0),n.canAccessFeature("breadcrumbs")||(e.breadcrumbs={hide:!0}),n.canAccessFeature("seo")||(e.seo={llmstxt:{hide:!0}}),n.canAccessFeature("redirects")||(e.redirects={}),n.canAccessFeature("l10n")||(e.l10n=void 0),n.canAccessFeature("rbac")||e.access&&(e.access.rbac=void 0),n.canAccessFeature("sso")||e.access&&(e.access.sso=void 0),n.canAccessFeature("ssoDirect")||(e.ssoDirect=void 0),n.canAccessFeature("catalogClassic")||(e.catalog=void 0,e.catalogClassic=void 0),n.canAccessFeature("scorecard")||(e.scorecard=void 0,e.scorecardClassic=void 0),n.canAccessFeature("scorecards")||(e.scorecards=void 0),n.canAccessFeature("devOnboarding")||(e.developerOnboarding=void 0),n.canAccessFeature("analytics")||(e.analytics=void 0),n.canAccessFeature("removeAttribution")||(e.removeAttribution=void 0),n.canAccessFeature("mockServer")||(e.mockServer={off:!0}),n.canAccessFeature("advancedSearch")||e.search&&(e.search.engine=A),n.canAccessFeature("banner")||(e.banner=void 0),e.consent){const s=n.entitlements;s&&!Object.prototype.hasOwnProperty.call(s,"cookieConsent")?i.warn("The plan gates token has no cookieConsent entry. The consent option stays on."):n.canAccessFeature("cookieConsent")||(i.error("The consent option requires the Enterprise+ plan. It is ignored, and analytics loads without consent."),e.consent=void 0)}return e}function L(e=[],n){return["static",...e].flatMap(s=>F(s)&&(s.startsWith("*")||s.startsWith(l)||s.startsWith("/"+l)||s.startsWith(u)||s.startsWith("/"+u))?s:p(s,n))}function w(e){return e.i18n&&i.warn("The `i18n` configuration is deprecated. Please use `l10n` instead."),e.l10n||e.i18n||{}}export{$ as redoclyConfigLoader};
@@ -0,0 +1,32 @@
1
+ import type { VersionedFolderConfig } from '@redocly/config';
2
+ export type SlugCollisions = {
3
+ pageVsPage: number;
4
+ dirVsDir: number;
5
+ };
6
+ export type ContentSlugs = {
7
+ fileSlugs: Map<string, string>;
8
+ dirSlugs: Map<string, string>;
9
+ collisions: SlugCollisions;
10
+ };
11
+ export type SlugCollision = {
12
+ kind: keyof SlugCollisions;
13
+ relativePath: string;
14
+ desiredSlug: string;
15
+ assignedSlug: string;
16
+ };
17
+ export type ContentSlugsOptions = {
18
+ isIgnored: (relativePath: string) => boolean | Promise<boolean>;
19
+ partialsFolders: string[];
20
+ versionsConfig: Map<string, VersionedFolderConfig>;
21
+ onCollision?: (collision: SlugCollision) => void;
22
+ };
23
+ export declare const IGNORED_EXTS: Set<string>;
24
+ /**
25
+ * Assigns a route slug to each content file and folder. A file with an `IGNORED_EXTS` extension,
26
+ * an ignored file and a Markdown partial get none; a slug already held gets a numbered suffix.
27
+ *
28
+ * @param relativePaths - Paths relative to the content root, in any order; not modified.
29
+ * @returns The slug of each file and folder, and how many slugs got a numbered suffix.
30
+ */
31
+ export declare function calculateContentSlugs(relativePaths: readonly string[], { isIgnored, partialsFolders, versionsConfig, onCollision }: ContentSlugsOptions): Promise<ContentSlugs>;
32
+ //# sourceMappingURL=calculate-content-slugs.d.ts.map
@@ -0,0 +1 @@
1
+ import f from"path";import{combineUrls as m}from"@redocly/theme/core/utils/urls";import{VERSION_SEPARATOR as c}from"../../../../constants/versions.js";import{removeTrailingSlash as h}from"../../../../../utils/url/remove-trailing-slash.js";import{slash as w}from"../../../../../utils/path/slash.js";import{parsePathVersions as b}from"../../../../../utils/path/parse-path-versions.js";import{GithubSlugger as D,slug as p}from"../../../../../utils/slugger.js";import{parseBaseName as P}from"../../../../utils/content/parse-base-name.js";import{isPartial as E}from"../../../markdown/is-partial.js";const F=new Set([".jpg",".jpeg",".png",".gif",".webp",".svg",".ico",".avif",".mp3",".wav",".ogg",".m4a",".mp4",".avi",".mov",".webm",".pdf",".doc",".docx",".zip",".rar",".gz",".ttf",".woff",".woff2"]);async function A(e,{isIgnored:i,partialsFolders:o,versionsConfig:a,onCollision:l}){const g=new Map,u=new Map,n=new Set,s={pageVsPage:0,dirVsDir:0},t=new D;u.set(".","/"),u.set("/","/");const d=[...e].sort((r,S)=>S.localeCompare(r));for(const r of d){if(F.has(f.posix.extname(r))||await i(r)||f.posix.extname(r)===".md"&&E(r,o))continue;const S=w(r).replace(new RegExp("^(@i18n|@l10n)\\/"),""),V=z(r,a);I(S,{defaultVersion:V,fileSlugs:g,dirSlugs:u,allFileSlugsList:n,githubSlugger:t,collisions:s,onCollision:l})}return{fileSlugs:g,dirSlugs:u,collisions:s}}function z(e,i){const o=b(e);return o==null?null:i.get(o.versionFolderPath)?.defaultVersion}function I(e,i){const o=i.fileSlugs.get(e);if(o)return o;const a=f.posix.dirname(e),l=N(a,i)||"",{baseName:g,isIndexFile:u}=P(e),n=i.dirSlugs.has(f.posix.join(a,g));let s;if(!u&&n){const t=p(m(l,g));i.allFileSlugsList.has(t)||(s=t)}if(!s){const t=u?i.dirSlugs.get(a):void 0;if(t)s=t;else{const d=m(l,g),r=p(d);s=i.githubSlugger.slug(d),s!==r&&(i.collisions.pageVsPage++,i.onCollision?.({kind:"pageVsPage",relativePath:e,desiredSlug:r,assignedSlug:s}))}}s=h(s),i.fileSlugs.set(e,s),i.allFileSlugsList.add(s)}function N(e,i){if(i.dirSlugs.has(e))return i.dirSlugs.get(e);const o=h(f.posix.normalize(e)).split("/");let a="/",l="";for(const g of o){l=f.posix.join(l,g);const u=j(g,i.defaultVersion);let n=i.dirSlugs.get(l);if(!n){const s=m("/",a,u),t=p(s);n=i.githubSlugger.slug(s),n!==t&&(i.collisions.dirVsDir++,i.onCollision?.({kind:"dirVsDir",relativePath:l,desiredSlug:t,assignedSlug:n}))}n.endsWith("/")||(n=n+"/"),i.dirSlugs.set(l,n),a=n}return i.dirSlugs.get(e)}function j(e,i){if(!e.startsWith(c))return e;const o=e.substring(c.length);return o===i?"":o}export{F as IGNORED_EXTS,A as calculateContentSlugs};
@@ -1,5 +1,3 @@
1
- import type { VersionedFolderConfig } from '@redocly/config';
2
1
  import type { LoaderFn } from '../../../types';
3
2
  export declare const versionsConfigLoader: LoaderFn;
4
- export declare function getDefaultVersionByPath(path: string, versionsConfig: Map<string, VersionedFolderConfig>): string | null | undefined;
5
3
  //# sourceMappingURL=versions-config-loader.d.ts.map
@@ -1 +1 @@
1
- import v from"path";import{I18N_DIR_NAME as c,L10N_DIR_NAME as p,RESERVED_DIR_NAMES as u,VERSION_SEPARATOR as V,VERSIONED_FOLDER_REGEXP_MATCH as P}from"../../../constants/common.js";import{parsePathVersions as l}from"../../../../utils/path/parse-path-versions.js";import{compareVersions as g}from"../../../../utils/version/compare-versions.js";import{reporter as h}from"../../../tools/notifiers/reporter.js";import{logger as y}from"../../../tools/notifiers/logger.js";const A=async(r,{cache:i,fs:s})=>{const e=new Map,a=s.scan();await E(a);for(const{relativePath:n}of a){if(v.posix.basename(n)==="versions.yaml"){await F(n,e,i);continue}const o=l(n);if(o==null||u.includes(V+o.versionName))continue;const t=e.get(o.versionFolderPath)||{versionedFiles:new Map,versions:[]},f=t.versionedFiles.get(o.filePathInVersion)||new Set,d={version:o.versionName};f.add(d.version),!t.hasVersionsConfig&&t.versions.findIndex(m=>m.version===o.versionName)===-1&&t.versions.push(d),t.versionedFiles.set(o.filePathInVersion,f),e.set(o.versionFolderPath,t)}return I(e)};async function F(r,i,s){let e=v.posix.dirname(r);e==="."?e="/":e=e.endsWith("/")?e:e+"/",e.startsWith(c+"/")&&(e=e.slice(c.length+1)),e.startsWith(p+"/")&&(e=e.slice(p.length+1));const n=(await s.load(r,"yaml")).data;n.versions&&!Array.isArray(n.versions)?(await h.panicOnBuild(`Property 'versions' must be an array at %rp. Got '${typeof n.versions}'.`,r),n.versions=[]):(!n.versions||n.versions.length===0)&&y.warn("Property 'versions' is empty at %rp. This is likely a mistake.",r);const o=i.get(e)||{versionedFiles:new Map,versions:[]};o.hasVersionsConfig=!0,o.versions=n.versions||[],n.default&&(o.defaultVersion=n.default),i.set(e,o)}async function E(r){const i=new Set;for(const{relativePath:s}of r){const e=l(s);if(!(e?.versionFolderPath&&u.includes(e?.versionFolderPath))){if(e?.versionFolderPath==null){(s.match(P)?.length||0)>1&&await h.panicOnBuild(`Nested versions are not supported. Detected nested versions in path: "${s}".`);continue}i.has(e.versionFolderPath)||i.add(e.versionFolderPath)}}}function I(r){for(const[i,s]of r){const e=s.hasVersionsConfig?s.versions:s.versions.sort((o,t)=>g(t.version,o.version)),a=s.hasVersionsConfig?e[e.length-1]:e[0],n=s.defaultVersion||a?.version;r.set(i,{...s,versions:e,defaultVersion:n})}return r}function S(r,i){const s=l(r);return s==null?null:i.get(s.versionFolderPath)?.defaultVersion}export{S as getDefaultVersionByPath,A as versionsConfigLoader};
1
+ import d from"path";import{I18N_DIR_NAME as v,L10N_DIR_NAME as c,RESERVED_DIR_NAMES as p}from"../../../constants/common.js";import{VERSION_SEPARATOR as V,VERSIONED_FOLDER_REGEXP_MATCH as P}from"../../../constants/versions.js";import{parsePathVersions as h}from"../../../../utils/path/parse-path-versions.js";import{compareVersions as g}from"../../../../utils/version/compare-versions.js";import{reporter as u}from"../../../tools/notifiers/reporter.js";import{logger as y}from"../../../tools/notifiers/logger.js";const S=async(i,{cache:r,fs:n})=>{const e=new Map,a=n.scan();await E(a);for(const{relativePath:s}of a){if(d.posix.basename(s)==="versions.yaml"){await F(s,e,r);continue}const o=h(s);if(o==null||p.includes(V+o.versionName))continue;const t=e.get(o.versionFolderPath)||{versionedFiles:new Map,versions:[]},l=t.versionedFiles.get(o.filePathInVersion)||new Set,f={version:o.versionName};l.add(f.version),!t.hasVersionsConfig&&t.versions.findIndex(m=>m.version===o.versionName)===-1&&t.versions.push(f),t.versionedFiles.set(o.filePathInVersion,l),e.set(o.versionFolderPath,t)}return I(e)};async function F(i,r,n){let e=d.posix.dirname(i);e==="."?e="/":e=e.endsWith("/")?e:e+"/",e.startsWith(v+"/")&&(e=e.slice(v.length+1)),e.startsWith(c+"/")&&(e=e.slice(c.length+1));const s=(await n.load(i,"yaml")).data;s.versions&&!Array.isArray(s.versions)?(await u.panicOnBuild(`Property 'versions' must be an array at %rp. Got '${typeof s.versions}'.`,i),s.versions=[]):(!s.versions||s.versions.length===0)&&y.warn("Property 'versions' is empty at %rp. This is likely a mistake.",i);const o=r.get(e)||{versionedFiles:new Map,versions:[]};o.hasVersionsConfig=!0,o.versions=s.versions||[],s.default&&(o.defaultVersion=s.default),r.set(e,o)}async function E(i){const r=new Set;for(const{relativePath:n}of i){const e=h(n);if(!(e?.versionFolderPath&&p.includes(e?.versionFolderPath))){if(e?.versionFolderPath==null){(n.match(P)?.length||0)>1&&await u.panicOnBuild(`Nested versions are not supported. Detected nested versions in path: "${n}".`);continue}r.has(e.versionFolderPath)||r.add(e.versionFolderPath)}}}function I(i){for(const[r,n]of i){const e=n.hasVersionsConfig?n.versions:n.versions.sort((o,t)=>g(t.version,o.version)),a=n.hasVersionsConfig?e[e.length-1]:e[0],s=n.defaultVersion||a?.version;i.set(r,{...n,versions:e,defaultVersion:s})}return i}export{S as versionsConfigLoader};
@@ -1,4 +1,4 @@
1
- import type { ContentSlugs } from './config-parser/loaders/content-slugs-loader.js';
1
+ import type { ContentSlugs } from './config-parser/loaders/utils/calculate-content-slugs.js';
2
2
  /**
3
3
  * Creates the canonical fsPath -> route slug function backed by the
4
4
  * precalculated `content-slugs` cache. The cache is the single place where
@@ -1 +1 @@
1
- import s from"path";import{combineUrls as n}from"@redocly/theme/core/utils";import{removeTrailingSlash as a}from"../../utils/url/remove-trailing-slash.js";import{slash as p}from"../../utils/path/slash.js";import{slug as f}from"../utils/index.js";import{parseBaseName as u}from"./utils.js";function b(i){return function(r){const o=p(r).replace(new RegExp("^(@i18n|@l10n)\\/"),""),l=i?.fileSlugs.get(o)||i?.dirSlugs.get(a(o));if(l)return l;const{baseName:t,isIndexFile:m}=u(r);let e=s.dirname(r.replace(new RegExp("^(@i18n|@l10n)\\/"),""));return e=e==="."?"/":e,n("/",f(m?e:n(e,t)),"/")}}export{b as createSlugify};
1
+ import s from"path";import{combineUrls as n}from"@redocly/theme/core/utils";import{removeTrailingSlash as a}from"../../utils/url/remove-trailing-slash.js";import{slash as p}from"../../utils/path/slash.js";import{slug as f}from"../utils/index.js";import{parseBaseName as u}from"../utils/content/parse-base-name.js";function b(i){return function(r){const o=p(r).replace(new RegExp("^(@i18n|@l10n)\\/"),""),l=i?.fileSlugs.get(o)||i?.dirSlugs.get(a(o));if(l)return l;const{baseName:t,isIndexFile:m}=u(r);let e=s.dirname(r.replace(new RegExp("^(@i18n|@l10n)\\/"),""));return e=e==="."?"/":e,n("/",f(m?e:n(e,t)),"/")}}export{b as createSlugify};
@@ -1 +1 @@
1
- import{MCP_ROUTE as i,PUBLIC_MCP_ROUTE as r}from"@redocly/theme/core/constants/mcp";import{EntitlementsProvider as m}from"../entitlements/entitlements-provider.js";import{getPublicMcpEndpointStatus as p}from"./mcp/utils/public-endpoint.js";const t={mcp:i,mcpPublic:r};function s(){return!!m.instance().canAccessFeature("mcp")}const E=[{slug:t.mcp,isEnabled:e=>!e?.mcp?.hide&&!e?.mcp?.docs?.hide&&s()},{slug:t.mcpPublic,isEnabled:e=>s()&&p(e)==="served"}];function l(e,n,o=[]){return[...E,...o].some(c=>c.slug===e&&c.isEnabled(n))}export{t as RESERVED_ROUTES,l as isRouteReserved};
1
+ import{MCP_ROUTE as t,PUBLIC_MCP_ROUTE as r}from"@redocly/theme/core/constants/mcp";import{EntitlementsProvider as E}from"../entitlements/entitlements-provider.js";import{isMcpRouteServedByConfig as m,isPublicMcpRouteServedByConfig as p}from"./mcp/utils/route-reservation.js";const o={mcp:t,mcpPublic:r};function n(){return!!E.instance().canAccessFeature("mcp")}const u=[{slug:o.mcp,isEnabled:e=>m(e)&&n()},{slug:o.mcpPublic,isEnabled:e=>n()&&p(e)}];function d(e,i,s=[]){return[...u,...s].some(c=>c.slug===e&&c.isEnabled(i))}export{o as RESERVED_ROUTES,d as isRouteReserved};
@@ -1,2 +1,2 @@
1
- import B from"@redocly/portal-plugin-mock-server";import{REDOCLY_ROUTE_RBAC as x}from"@redocly/config";import{combineUrls as E,withPathPrefix as L}from"@redocly/theme/core/utils";import{VERSION_SEPARATOR as k}from"../constants/common.js";import{removeTrailingSlash as N}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as j}from"../../utils/url/remove-leading-slash.js";import{isTruthy as $}from"../../utils/guards/is-truthy.js";import{normalizeRouteSlug as D}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as V}from"../../utils/path/parse-path-versions.js";import{reporter as v}from"../tools/notifiers/reporter.js";import{logger as P}from"../tools/notifiers/logger.js";import{envConfig as S}from"../config/env-config.js";import{shaDirPathShort as M}from"../utils/crypto/sha-dir-path-short.js";import{writeServerRebuildTrigger as _,generateBrowserPluginsModule as q,generateClientRoutes as z,generateTemplatesModule as H}from"../esbuild/generate.js";import{customPagesPlugin as U}from"../../server/plugins/pages/index.js";import{apiDocsPlugin as G}from"../../server/plugins/api-docs/index.js";import{configParserPlugin as I}from"./config-parser/index.js";import{createSlugify as W}from"./create-slugify.js";import{markdownPlugin as K}from"./markdown/index.js";import{searchPlugin as Y}from"./search/index.js";import{skillsPlugin as J}from"./skills/index.js";import{defaultThemePlugin as Q}from"./default-theme/index.js";import{apiKeyMgmtPlugin as X}from"./dev-onboarding/index.js";import{apiFunctionsPlugin as Z}from"./api-functions/index.js";import{scorecardClassicPlugin as ee}from"./scorecard-classic/index.js";import{lintPlugin as te}from"./lint/index.js";import{resolveExternalPlugins as oe}from"../external-plugins/resolve-external-plugins.js";import{sidebarsPlugin as ie}from"./sidebars/index.js";import{l10nPlugin as re}from"./l10n/index.js";import{validateRedirects as ne}from"../utils/redirects/validate-redirects.js";import{analyticsPlugins as se}from"./analytics/index.js";import{consentPlugin as ae}from"./consent/index.js";import{sitemapPlugin as le}from"./sitemap/index.js";import{entitlementsPlugin as ce}from"./entitlements/index.js";import{getBilledPagesCount as ue}from"../utils/index.js";import{telemetry as fe}from"../../cli/telemetry/index.js";import{telemetryTraceStep as b}from"../../cli/telemetry/helpers/trace-step.js";import{EntitlementsProvider as A}from"../entitlements/entitlements-provider.js";import{enforceLoginPlugin as me}from"./enforce-login/index.js";import{ssoPlugin as de}from"./sso/index.js";import{Cache as ge}from"../fs/cache.js";import{ContentFs as pe}from"../fs/content-fs.js";import{findProductBySlug as Pe}from"../utils/product.js";import{isRouteReserved as ye}from"./get-reserved-routes.js";import{catalogClassicPlugin as he}from"./catalog-classic/index.js";import{arazzoDocsPlugin as Re}from"./arazzo-docs/index.js";const Ce=[I,me,de,Q,re,K,G,Re,ee,te,Z,U,X,he,{importPath:"./catalog-entities/plugin.js",loadCondition:()=>S.NEW_CATALOG_ENABLED??!1},{importPath:"./scorecards/plugin.js",loadCondition:()=>S.NEW_SCORECARDS_ENABLED??!1},{importPath:"./mcp/index.js",loadCondition:()=>A.instance().canAccessFeature("mcp")},ie,le,ce,Y,J,B,ae,...se];async function Pt(t,e=Ce){return await b("com.redocly.build.pluginsInit",async()=>{const r=[],R=A.instance(),y={};for(const s of e){let u;if("loadCondition"in s){if(!s.loadCondition())continue;const i=await import(s.importPath);if(!i.default||typeof i.default!="function"){await v.panicOnBuild(`Dynamic plugin ${s.importPath} does not export a default export or it is not a function`);continue}u=i.default}else u=s;const h=await u(t);for(const[i,f]of Object.entries(h.loaders||{}))y[i]&&await v.panicOnBuild(`Duplicate loader with name ${i}`),y[i]=f;(!h.requiredEntitlements||h.requiredEntitlements?.every(i=>R.canAccessFeature(i)))&&r.push(h)}const l=new pe(t.contentDir);await l.ready;const c=new ge(l);return c.setLoaders(y),P.verbose("All plugins instantiated"),{pluginInstances:r,lifecycleContext:be(l,c)}})}function O(t){P.verbose("Generating templates"),b("com.redocly.build.writeClientEntries",()=>{H(t),q(t),z(t)})}async function ve(t){const e=t.getAllRoutes();ue(e)||await v.panicOnBuild("No routes created by plugins. Please check your project configuration.")}async function yt(t,e,r,R={}){const y=A.instance();try{await b("com.redocly.build.pluginsRun",async()=>{e.startPluginsRun();const l=S.isDevelopMode&&e.buildRevision>0,c=l?F(e):"";let s=[];await b("com.redocly.build.pluginsProcessContent",async i=>{for(const o of t){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}s=(await oe(e.contentDir,e.config.plugins)).map(o=>o.lifecyclePlugin).filter(o=>$(o)&&(!o.requiredEntitlements||o.requiredEntitlements?.every(a=>y.canAccessFeature(a)))),r.cache.setLoaders(Object.fromEntries(s.flatMap(o=>Object.entries(o.loaders||{}))));for(const o of s){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}i?.setAttribute("externalPluginsProcessed",s.length.toString())});const u=await we(e,r),h=[...t,...s];O(e),S.isDevelopMode?await e.userCodeReady:e.buildRevision++,await b("com.redocly.build.pluginsAfterRoutesCreated",async()=>{for(const i of h){const f=P.startTiming();await i.afterRoutesCreated?.(e,u),P.verboseTime(f,`afterRoutesCreated for ${i.id}`)}}),ne(e),await e.reportUnsetEnvVars(),await ve(e),O(e),l&&c!==F(e)&&(e.markRequestHandlersEntryOutdated(),_(e.serverOutDir))})}catch(l){const c="Unhandled error in plugin. "+l.message+`
1
+ import B from"@redocly/portal-plugin-mock-server";import{REDOCLY_ROUTE_RBAC as x}from"@redocly/config";import{combineUrls as E,withPathPrefix as L}from"@redocly/theme/core/utils";import{VERSION_SEPARATOR as k}from"../constants/versions.js";import{removeTrailingSlash as N}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as j}from"../../utils/url/remove-leading-slash.js";import{isTruthy as $}from"../../utils/guards/is-truthy.js";import{normalizeRouteSlug as D}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as V}from"../../utils/path/parse-path-versions.js";import{reporter as v}from"../tools/notifiers/reporter.js";import{logger as P}from"../tools/notifiers/logger.js";import{envConfig as S}from"../config/env-config.js";import{shaDirPathShort as M}from"../utils/crypto/sha-dir-path-short.js";import{writeServerRebuildTrigger as _,generateBrowserPluginsModule as q,generateClientRoutes as z,generateTemplatesModule as H}from"../esbuild/generate.js";import{customPagesPlugin as U}from"../../server/plugins/pages/index.js";import{apiDocsPlugin as G}from"../../server/plugins/api-docs/index.js";import{configParserPlugin as I}from"./config-parser/index.js";import{createSlugify as W}from"./create-slugify.js";import{markdownPlugin as K}from"./markdown/index.js";import{searchPlugin as Y}from"./search/index.js";import{skillsPlugin as J}from"./skills/index.js";import{defaultThemePlugin as Q}from"./default-theme/index.js";import{apiKeyMgmtPlugin as X}from"./dev-onboarding/index.js";import{apiFunctionsPlugin as Z}from"./api-functions/index.js";import{scorecardClassicPlugin as ee}from"./scorecard-classic/index.js";import{lintPlugin as te}from"./lint/index.js";import{resolveExternalPlugins as oe}from"../external-plugins/resolve-external-plugins.js";import{sidebarsPlugin as ie}from"./sidebars/index.js";import{l10nPlugin as re}from"./l10n/index.js";import{validateRedirects as ne}from"../utils/redirects/validate-redirects.js";import{analyticsPlugins as se}from"./analytics/index.js";import{consentPlugin as ae}from"./consent/index.js";import{sitemapPlugin as le}from"./sitemap/index.js";import{entitlementsPlugin as ce}from"./entitlements/index.js";import{getBilledPagesCount as ue}from"../utils/index.js";import{telemetry as fe}from"../../cli/telemetry/index.js";import{telemetryTraceStep as b}from"../../cli/telemetry/helpers/trace-step.js";import{EntitlementsProvider as A}from"../entitlements/entitlements-provider.js";import{enforceLoginPlugin as me}from"./enforce-login/index.js";import{ssoPlugin as de}from"./sso/index.js";import{Cache as ge}from"../fs/cache.js";import{ContentFs as pe}from"../fs/content-fs.js";import{findProductBySlug as Pe}from"../utils/product.js";import{isRouteReserved as ye}from"./get-reserved-routes.js";import{catalogClassicPlugin as he}from"./catalog-classic/index.js";import{arazzoDocsPlugin as Re}from"./arazzo-docs/index.js";const Ce=[I,me,de,Q,re,K,G,Re,ee,te,Z,U,X,he,{importPath:"./catalog-entities/plugin.js",loadCondition:()=>S.NEW_CATALOG_ENABLED??!1},{importPath:"./scorecards/plugin.js",loadCondition:()=>S.NEW_SCORECARDS_ENABLED??!1},{importPath:"./mcp/index.js",loadCondition:()=>A.instance().canAccessFeature("mcp")},ie,le,ce,Y,J,B,ae,...se];async function Pt(t,e=Ce){return await b("com.redocly.build.pluginsInit",async()=>{const r=[],R=A.instance(),y={};for(const s of e){let u;if("loadCondition"in s){if(!s.loadCondition())continue;const i=await import(s.importPath);if(!i.default||typeof i.default!="function"){await v.panicOnBuild(`Dynamic plugin ${s.importPath} does not export a default export or it is not a function`);continue}u=i.default}else u=s;const h=await u(t);for(const[i,f]of Object.entries(h.loaders||{}))y[i]&&await v.panicOnBuild(`Duplicate loader with name ${i}`),y[i]=f;(!h.requiredEntitlements||h.requiredEntitlements?.every(i=>R.canAccessFeature(i)))&&r.push(h)}const l=new pe(t.contentDir);await l.ready;const c=new ge(l);return c.setLoaders(y),P.verbose("All plugins instantiated"),{pluginInstances:r,lifecycleContext:be(l,c)}})}function O(t){P.verbose("Generating templates"),b("com.redocly.build.writeClientEntries",()=>{H(t),q(t),z(t)})}async function ve(t){const e=t.getAllRoutes();ue(e)||await v.panicOnBuild("No routes created by plugins. Please check your project configuration.")}async function yt(t,e,r,R={}){const y=A.instance();try{await b("com.redocly.build.pluginsRun",async()=>{e.startPluginsRun();const l=S.isDevelopMode&&e.buildRevision>0,c=l?F(e):"";let s=[];await b("com.redocly.build.pluginsProcessContent",async i=>{for(const o of t){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}s=(await oe(e.contentDir,e.config.plugins)).map(o=>o.lifecyclePlugin).filter(o=>$(o)&&(!o.requiredEntitlements||o.requiredEntitlements?.every(a=>y.canAccessFeature(a)))),r.cache.setLoaders(Object.fromEntries(s.flatMap(o=>Object.entries(o.loaders||{}))));for(const o of s){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}i?.setAttribute("externalPluginsProcessed",s.length.toString())});const u=await we(e,r),h=[...t,...s];O(e),S.isDevelopMode?await e.userCodeReady:e.buildRevision++,await b("com.redocly.build.pluginsAfterRoutesCreated",async()=>{for(const i of h){const f=P.startTiming();await i.afterRoutesCreated?.(e,u),P.verboseTime(f,`afterRoutesCreated for ${i.id}`)}}),ne(e),await e.reportUnsetEnvVars(),await ve(e),O(e),l&&c!==F(e)&&(e.markRequestHandlersEntryOutdated(),_(e.serverOutDir))})}catch(l){const c="Unhandled error in plugin. "+l.message+`
2
2
  `+l.stack;fe.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:c}]),R.failFast?await v.panic(c):await v.panicOnBuild(c)}finally{e.finishPluginsRun()}}async function we(t,e){const{cache:r,fs:R}=e,y=await e.getConfig(),l=Object.values(y.products||{}),c=(await r.load("versions-config","versions-config")).data,s=(await r.load("content-slugs","content-slugs")).data,u=W(s);for(const{duplicateInAllLocales:i,slugSuffix:f,sharedData:o=[],redirectFrom:a=[],...d}of t.newRoutes){const w=D(d.slug?d.slug:u(d.fsPath)),g=N(f?E(w,f):w),n={...d,[x]:{slug:g,fsPath:d.fsPath},slug:g,baseSlug:w,versions:h(d.fsPath,f),product:Pe(l,g,u)};ye(g,y)&&await v.panicOnBuildContentError(`Route "${g}" is reserved and cannot be used. Please choose a different slug for "${d.fsPath}".`),t.routesByFsPath.set(n.fsPath,n.slug),t.routesBySlug.set(n.slug,n);for(const{key:p,id:m}of o)t.addRouteSharedData(n.slug,p,m);for(const p of a)t.addRedirect(p.from,{type:p.type,to:n.slug});if(i)for(const p of R.localeFolders){const m={...n,slug:"/"+p.toLowerCase()+n.slug};t.routesByFsPath.set(m.fsPath,m.slug),t.routesBySlug.set(m.slug,m);for(const{key:C,id:T}of o)t.addRouteSharedData(m.slug,C,T);for(const C of a){const T=E(R.localizationFolder,p,C.from);t.addRedirect(T,{type:C.type,to:m.slug},{trackOriginalSource:!1})}}}return t.newRoutes=[],{...e,slugify:u};function h(i,f=""){const o=V(i);if(!o?.versionName)return;const{versionFolderPath:a,filePathInVersion:d,versionName:w}=o,g=c.get(a);if(g)return g.versions.map(n=>{const p=g.defaultVersion===n.version,m=j(E(a,k+n.version,d)),C=u(m);return{version:n.version,label:n.name||n.version,link:D(E(C,f)),default:p,active:w===n.version,folderId:M(`${a}`)}})}}function be(t,e){return{fs:t,cache:e,getConfig:async(r=".")=>(await e.load(r,"nearest-redocly-config",t.localeFolders)).data,isPathIgnored:async r=>(await e.load(r,"is-ignored")).data,withPathPrefix:L,logger:P}}function F(t){return[...t.apiRoutesRequestHandlers.keys(),...t.getMcpTools().map(e=>`${e.name}:${e.importPath}`)].sort().join(",")}export{Ce as INTERNAL_PLUGINS,be as createLifecycleContext,Pt as initPlugins,yt as runPlugins,O as writeClientEntries};
@@ -1 +1 @@
1
- import l from"node:path";import{API_DOCS_TEMPLATE_ID as O,ASYNC_API_DOCS_TEMPLATE_ID as y,GRAPHQL_TEMPLATE_ID as M,OPENAPI_DOCS_TEMPLATE_ID as U}from"../../../../constants/common.js";import{isLocalLink as C}from"../../../../utils/path/is-local-link.js";import{normalizeRouteSlug as P}from"../../../../utils/path/normalize-route-slug.js";import{removeFragment as B}from"../../../../utils/path/remove-fragment.js";import{getInnerText as W}from"../../../../markdoc/helpers/get-inner-text.js";import{getNodeAttribute as j}from"../../../../markdoc/helpers/get-node-attribute.js";import{setNodeAttributeValue as p}from"../../../../markdoc/helpers/set-node-attribute-value.js";import{isAuthRoutePath as $}from"../../../../utils/auth/is-auth-route-path.js";import{isApiDownloadLink as b}from"../../../utils/is-api-download-link.js";import{isTranslationFallback as V}from"../../../fs/utils/is-translation-fallback.js";import{removeL10nPrefix as z}from"../../../fs/utils/remove-l10n-prefix.js";import{MdResolveError as A}from"./md-resolve-error.js";import{getLinkOriginalAttrName as G}from"./utils.js";import{isOpenApiURL as N}from"../../api-docs/utils/is-api-doc.js";import{parseBaseName as q}from"../../utils.js";import{isMarkdownPage as H}from"../is-markdown-page.js";import{copyStaticFile as K}from"../../../utils/fs.js";async function ht(i,s,u,{actions:I,context:m}){const{contentDir:T,outdir:v,getRouteByFsPath:d,getRouteBySlug:k,hasRouteOrRedirectBySlug:w}=I,x=G(s),o=i[x]||j(i,s);if(i[x]=o,!C(o)||b(o)||$(o))return;const[Q,t="",R,L]=/^([^?#]+)?([^#]+)?(.+)?/.exec(o)||[],g=i.type==="image"?"IMAGE":"LINK",h=String(i.attributes.title||i.attributes.alt||W([i])||""),c=B(u);if(i.type!=="image"){const{isOpenapiDetected:e,isOpenapiValid:r}=await N(t,c,I,m);if(e&&!r)throw new A(`OpenAPI route ${o} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g})}if(l.extname(t)===""){if(t.startsWith("/")){const e=P(t),r=w(e)?t:_(e,k);if(!r)throw new A(`Route ${t} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g});p(i,s,r+(R||"")+(L||""))}if(!o.startsWith("#")&&!t.startsWith("/")&&H(c)){const e=d(c)?.slug;if(!e)return;const{isIndexFile:r}=q(c),a=r?P(l.posix.join(e,t)):P(l.posix.join(e,"../",t)),E=w(P(a))?a:_(a,k);if(!E)throw new A(`Route ${t} does not exist`,{rawLink:o,link:a,title:h,brokenLinkType:g});p(i,s,E+(R||"")+(L||""))}return}const n=t.startsWith("/")?t.substring(1):l.posix.join(l.posix.dirname(c),decodeURI(t)),D=t.startsWith("/")?l.posix.join("static",t.substring(1)):"",S=m.fs.exists(n),F=m.fs.exists(D),f=d(n);if(!S&&!f&&!F)throw p(i,s,"#"),new A(`File ${n} does not exist`,{rawLink:o,link:n,title:h,brokenLinkType:g});if(f){const e=[U,M,y].includes(f.templateId);p(i,s,(e?f.baseSlug:f.slug)+(L||""))}else if(S){const e=m.fs.getFileInfo(n),r=V(e)?m.fs.getFileInfo(z(n)):e;if(!r||r.isVirtual)return;const a=await K(T,r.realRelativePath,v);p(i,s,a)}}function _(i,s){const u=s(i.toLowerCase());return u?.templateId===O?u.slug:void 0}export{ht as resolveLink};
1
+ import l from"node:path";import{API_DOCS_TEMPLATE_ID as O,ASYNC_API_DOCS_TEMPLATE_ID as y,GRAPHQL_TEMPLATE_ID as M,OPENAPI_DOCS_TEMPLATE_ID as U}from"../../../../constants/common.js";import{isLocalLink as C}from"../../../../utils/path/is-local-link.js";import{normalizeRouteSlug as P}from"../../../../utils/path/normalize-route-slug.js";import{removeFragment as B}from"../../../../utils/path/remove-fragment.js";import{getInnerText as W}from"../../../../markdoc/helpers/get-inner-text.js";import{getNodeAttribute as j}from"../../../../markdoc/helpers/get-node-attribute.js";import{setNodeAttributeValue as p}from"../../../../markdoc/helpers/set-node-attribute-value.js";import{isAuthRoutePath as $}from"../../../../utils/auth/is-auth-route-path.js";import{isApiDownloadLink as b}from"../../../utils/is-api-download-link.js";import{isTranslationFallback as V}from"../../../fs/utils/is-translation-fallback.js";import{removeL10nPrefix as z}from"../../../fs/utils/remove-l10n-prefix.js";import{parseBaseName as G}from"../../../utils/content/parse-base-name.js";import{MdResolveError as A}from"./md-resolve-error.js";import{getLinkOriginalAttrName as N}from"./utils.js";import{isOpenApiURL as q}from"../../api-docs/utils/is-api-doc.js";import{isMarkdownPage as H}from"../is-markdown-page.js";import{copyStaticFile as K}from"../../../utils/fs.js";async function ht(i,s,u,{actions:I,context:m}){const{contentDir:T,outdir:v,getRouteByFsPath:d,getRouteBySlug:k,hasRouteOrRedirectBySlug:w}=I,x=N(s),o=i[x]||j(i,s);if(i[x]=o,!C(o)||b(o)||$(o))return;const[Q,t="",R,L]=/^([^?#]+)?([^#]+)?(.+)?/.exec(o)||[],g=i.type==="image"?"IMAGE":"LINK",h=String(i.attributes.title||i.attributes.alt||W([i])||""),c=B(u);if(i.type!=="image"){const{isOpenapiDetected:e,isOpenapiValid:r}=await q(t,c,I,m);if(e&&!r)throw new A(`OpenAPI route ${o} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g})}if(l.extname(t)===""){if(t.startsWith("/")){const e=P(t),r=w(e)?t:_(e,k);if(!r)throw new A(`Route ${t} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g});p(i,s,r+(R||"")+(L||""))}if(!o.startsWith("#")&&!t.startsWith("/")&&H(c)){const e=d(c)?.slug;if(!e)return;const{isIndexFile:r}=G(c),a=r?P(l.posix.join(e,t)):P(l.posix.join(e,"../",t)),E=w(P(a))?a:_(a,k);if(!E)throw new A(`Route ${t} does not exist`,{rawLink:o,link:a,title:h,brokenLinkType:g});p(i,s,E+(R||"")+(L||""))}return}const n=t.startsWith("/")?t.substring(1):l.posix.join(l.posix.dirname(c),decodeURI(t)),D=t.startsWith("/")?l.posix.join("static",t.substring(1)):"",S=m.fs.exists(n),F=m.fs.exists(D),f=d(n);if(!S&&!f&&!F)throw p(i,s,"#"),new A(`File ${n} does not exist`,{rawLink:o,link:n,title:h,brokenLinkType:g});if(f){const e=[U,M,y].includes(f.templateId);p(i,s,(e?f.baseSlug:f.slug)+(L||""))}else if(S){const e=m.fs.getFileInfo(n),r=V(e)?m.fs.getFileInfo(z(n)):e;if(!r||r.isVirtual)return;const a=await K(T,r.realRelativePath,v);p(i,s,a)}}function _(i,s){const u=s(i.toLowerCase());return u?.templateId===O?u.slug:void 0}export{ht as resolveLink};
@@ -1,6 +1,6 @@
1
- import{removeTrailingSlash as g,withPathPrefix as y,withoutPathPrefix as E}from"@redocly/theme/core/utils";import{ServerRoutes as L}from"../../../../../../constants/api.js";import{DEFAULT_LOCALE_PLACEHOLDER as S}from"../../../../../../constants/common.js";const w=async(n,t)=>{const{query:e,product:o,locale:l}=n,u=t.config.l10n?.defaultLocale||S,h=JSON.stringify({query:e,...o?{product:o}:{},locale:l||u}),f=`${t.internalBaseUrl||t.baseUrl}${y(L.SEMANTIC_SEARCH)}`,s=t.accessToken?`authorization=${String(t.accessToken).replace(/^Bearer /,"")}`:"";try{const a=await fetch(f,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...s?{Cookie:s}:{}},body:h});if(!a.ok)return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0};const p=await a.json(),d=new Set(t.searchIgnoredRoutes??[]),i=(p||[]).filter(r=>!R(r.url,d));if(i.length===0)return{content:[{type:"text",text:"No results found."}]};const m=r=>{try{return new URL(r,t.baseUrl).toString()}catch{return r}},c=i.map(r=>`### [${r.title}](${m(r.url)})
1
+ import{removeTrailingSlash as y,withPathPrefix as U,withoutPathPrefix as E}from"@redocly/theme/core/utils";import{envConfig as S}from"../../../../../config/env-config.js";import{resolveDocsSiteUrl as v}from"../../../../../plugins/mcp/utils/docs-site-url.js";import{ServerRoutes as L}from"../../../../../../constants/api.js";import{DEFAULT_LOCALE_PLACEHOLDER as w}from"../../../../../../constants/common.js";const C=async(n,t)=>{const{query:e,product:o,locale:l}=n,u=t.config.l10n?.defaultLocale||w,h=JSON.stringify({query:e,...o?{product:o}:{},locale:l||u}),f=`${t.internalBaseUrl||t.baseUrl}${U(L.SEMANTIC_SEARCH)}`,s=t.accessToken?`authorization=${String(t.accessToken).replace(/^Bearer /,"")}`:"";try{const i=await fetch(f,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...s?{Cookie:s}:{}},body:h});if(!i.ok)return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0};const p=await i.json(),m=new Set(t.searchIgnoredRoutes??[]),a=(p||[]).filter(r=>!R(r.url,m));if(a.length===0)return{content:[{type:"text",text:"No results found."}]};const d=S.isProductionEnv?v(t.config?.seo?.siteUrl,t.baseUrl):t.baseUrl,g=r=>{try{return new URL(r,d).toString()}catch{return r}},c=a.map(r=>`### [${r.title}](${g(r.url)})
2
2
 
3
3
  ${r.content}
4
4
  `).join(`
5
5
 
6
- `).trim();return{content:[{type:"text",text:c.length?c:"No results found."}]}}catch{return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0}}};function R(n,t){if(t.size===0)return!1;let e;try{e=new URL(n,"https://relative.invalid").pathname}catch{return!1}e=g(E(e));try{e=decodeURI(e)}catch{}return t.has(e)}var v={search:w};export{v as default};
6
+ `).trim();return{content:[{type:"text",text:c.length?c:"No results found."}]}}catch{return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0}}};function R(n,t){if(t.size===0)return!1;let e;try{e=new URL(n,"https://relative.invalid").pathname}catch{return!1}e=y(E(e));try{e=decodeURI(e)}catch{}return t.has(e)}var b={search:C};export{b as default};
@@ -1 +1 @@
1
- import{logger as A}from"../../../tools/notifiers/logger.js";import{getFeedbackClientIp as v}from"../../../web-server/utils/feedback-ip.js";import{getForwardedOrigin as M,getInternalOrigin as N}from"../../../web-server/utils/get-request-origin.js";import{GATEWAY_FETCH_LIMIT_DEFAULTS as L,DEFAULT_ANONYMOUS_VISITOR_TEAM as B,RbacFeatures as H}from"../../../../constants/common.js";import{isObject as j}from"../../../../utils/guards/is-object.js";import{getAccessibleSkills as V}from"../../../utils/skills/get-accessible-skills.js";import{getSkillUrl as $}from"../../../utils/skills/get-skill-url.js";import{createMcpHandler as Y}from"@modelcontextprotocol/server";import{createDocsMcpServer as G}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as J,filterGraphqlDescriptionsByRbac as K}from"../utils.js";import{userSubject as z}from"../gateway-mcp/subject.js";import{ipRateLimitKey as X}from"../gateway-mcp/rate-limit/utils/ip-key.js";import{createMethodNotAllowedError as Q,withErrorHandling as W}from"./errors.js";import{constructForbiddenResponse as Z,constructInvalidTokenResponse as q,constructUnauthorizedResponse as x,handleMcpAuth as ee}from"../auth/auth-handlers.js";import{isAssistantAnonymousToken as oe}from"../auth/assistant-anonymous-token.js";import{shouldHandleMcpAuth as re}from"../../../utils/rbac/should-handle-mcp-auth.js";import{extractTokenFromAuthHeader as se}from"../utils/jwt.js";import{resolveMcpClient as ie}from"../utils/mcp-client.js";import{randomUUID as ne}from"../../../utils/crypto/random-uuid.js";import{getPublicMcpEndpointStatus as te}from"../utils/public-endpoint.js";import{narrowMcpConfigForCaller as ce}from"../gateway-mcp/caller-api-calls.js";import{DEFAULT_DOCS_MCP_SERVER_NAME as ae,SSE_KEEPALIVE_INTERVAL_MS as pe}from"../constants.js";import{withPathPrefix as de}from"@redocly/theme/core/utils";import{PUBLIC_MCP_ROUTE as le}from"@redocly/theme/core/constants/mcp";import{canAccessFeature as me}from"../../../utils/rbac.js";import{ANONYMOUS_AUTH_DETAILS as fe}from"../../../constants/rbac.js";const E="X-Redocly-AI-Metadata",ue=1024*1024;function ge(o){if(o)try{const e=JSON.parse(o);if(j(e))return e;A.warn(`Ignoring ${E} header: not a JSON object.`)}catch{A.warn(`Ignoring ${E} header: invalid JSON.`)}}function he(o,e){return new URL(o).searchParams.get("mode")==="tools"?"tools":e}function b(){return{...fe,email:"",idpAccessToken:void 0,idpId:void 0}}const Ae=async(o,e,n)=>{const t=!!e?.config?.access?.requiresLogin,c=e?.config?.access?.rbac||{},I=n?.props?.config?.mcpMode??"tools",p=he(o.url,I),U=n?.props?.config?.gatewayFetchBudgetPerExec??L.budgetPerExec,R=n?.props?.config?.searchIgnoredRoutes??[],r=n,C=!!r?.props?.config?.isPublicEndpoint;let u;const T=o.headers.get("Authorization");if(C)e.user=b();else if(re(t,c)){const{isAuthenticated:i,isTokenValid:d,isFirstPartyAnonymous:g,currentUser:l,accessToken:h}=await ee(o,e);if(g)e.user=b();else if(i)l&&(e.user=l),u=h;else{const a=M(o),m=te(e.config)==="served"?`${a}${de(le)}`:void 0;return d===!1?q(a,m):x(a,m)}}else if(T){const i=se(T)??void 0;u=(i?await oe(i):!1)?void 0:i}const _={isAuthenticated:!!e.user?.isAuthenticated,teams:e.user?.teams||[B],claims:e.user?.claims??{}};return me(H.MCP,_,c,t)?await W(async()=>{const i=p==="code"&&(n?.props?.config?.elicitationEnabled??!1);if(o.method==="GET")return new Response(JSON.stringify({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: ${o.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(o.method!=="POST")return Q();const d=r?.props?.config?.apiDescriptionsMap||{},g=r?.props?.config?.graphqlDescriptions||[],l=r?.props?.config?.mcpDocsServerName||ae,{config:{mcp:h={}}}=e,a=J(d,e.user,c,t),m=K(g,e.user,c,t),y=e.config.products?Object.values(e.config.products).map(s=>s?.name):[],D=h.docs?.name||l,f=ge(o.headers.get(E)),P=r?.props?.tools||[],O=r?.props?.skillsBaseUrl||M(o),w=V(r?.props?.skills||[],e.user,c,t).map(s=>({slug:s.slug,name:s.name,description:s.description,content:s.content,uri:$(O,s.slug)})),S=r?.props?.fetchCountSecret,F={name:D,tools:P,skills:w,context:{...e,config:{...e.config,mcp:ce(e.config.mcp,f)},configFile:r?.props?.configFile,accessToken:u,outdir:e.outdir||"",baseUrl:e.baseUrl||M(o),internalBaseUrl:N(o),apiDescriptionsMap:a,graphqlDescriptions:m,products:y,metadata:f,mcpMode:p,elicitationEnabled:i,gatewayFetchBudgetPerExec:U,fetchCountRequest:p==="code"&&S?{caller:{subject:z(e.user),ip:X(o)},secret:S}:void 0,searchIgnoredRoutes:R,clientIp:v(o),...ie(o),requestId:ne(),messageId:typeof f?.messageId=="string"?f.messageId:void 0}},k=await G({...F,getKv:e.getKv});return await Y(async()=>k,{keepAliveMs:pe,maxRequestBodySize:ue,onerror:s=>A.warn(`MCP handler: ${s.message}`)}).fetch(o)},p):Z()};var Je=Ae;export{Je as default};
1
+ import{logger as A}from"../../../tools/notifiers/logger.js";import{getFeedbackClientIp as v}from"../../../web-server/utils/feedback-ip.js";import{getForwardedOrigin as M,getInternalOrigin as N}from"../../../web-server/utils/get-request-origin.js";import{GATEWAY_FETCH_LIMIT_DEFAULTS as L,DEFAULT_ANONYMOUS_VISITOR_TEAM as B,RbacFeatures as H}from"../../../../constants/common.js";import{isObject as j}from"../../../../utils/guards/is-object.js";import{getAccessibleSkills as V}from"../../../utils/skills/get-accessible-skills.js";import{getSkillUrl as $}from"../../../utils/skills/get-skill-url.js";import{createMcpHandler as Y}from"@modelcontextprotocol/server";import{createDocsMcpServer as G}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as J,filterGraphqlDescriptionsByRbac as K}from"../utils.js";import{userSubject as z}from"../gateway-mcp/subject.js";import{ipRateLimitKey as X}from"../gateway-mcp/rate-limit/utils/ip-key.js";import{createMethodNotAllowedError as Q,withErrorHandling as W}from"./errors.js";import{constructForbiddenResponse as Z,constructInvalidTokenResponse as q,constructUnauthorizedResponse as x,handleMcpAuth as ee}from"../auth/auth-handlers.js";import{isAssistantAnonymousToken as oe}from"../auth/assistant-anonymous-token.js";import{shouldHandleMcpAuth as re}from"../../../utils/rbac/should-handle-mcp-auth.js";import{extractTokenFromAuthHeader as se}from"../utils/jwt.js";import{resolveMcpClient as ie}from"../utils/mcp-client.js";import{randomUUID as ne}from"../../../utils/crypto/random-uuid.js";import{getPublicMcpEndpointStatus as te}from"../utils/public-endpoint.js";import{narrowMcpConfigForCaller as ce}from"../gateway-mcp/caller-api-calls.js";import{DEFAULT_DOCS_MCP_SERVER_NAME as ae,SSE_KEEPALIVE_INTERVAL_MS as pe}from"../constants.js";import{withPathPrefix as de}from"@redocly/theme/core/utils";import{PUBLIC_MCP_ROUTE as le}from"@redocly/theme/core/constants/mcp";import{canAccessFeature as me}from"../../../utils/rbac/can-access-feature.js";import{ANONYMOUS_AUTH_DETAILS as fe}from"../../../constants/rbac.js";const E="X-Redocly-AI-Metadata",ue=1024*1024;function ge(o){if(o)try{const e=JSON.parse(o);if(j(e))return e;A.warn(`Ignoring ${E} header: not a JSON object.`)}catch{A.warn(`Ignoring ${E} header: invalid JSON.`)}}function he(o,e){return new URL(o).searchParams.get("mode")==="tools"?"tools":e}function b(){return{...fe,email:"",idpAccessToken:void 0,idpId:void 0}}const Ae=async(o,e,n)=>{const t=!!e?.config?.access?.requiresLogin,c=e?.config?.access?.rbac||{},I=n?.props?.config?.mcpMode??"tools",p=he(o.url,I),U=n?.props?.config?.gatewayFetchBudgetPerExec??L.budgetPerExec,R=n?.props?.config?.searchIgnoredRoutes??[],r=n,C=!!r?.props?.config?.isPublicEndpoint;let u;const T=o.headers.get("Authorization");if(C)e.user=b();else if(re(t,c)){const{isAuthenticated:i,isTokenValid:d,isFirstPartyAnonymous:g,currentUser:l,accessToken:h}=await ee(o,e);if(g)e.user=b();else if(i)l&&(e.user=l),u=h;else{const a=M(o),m=te(e.config)==="served"?`${a}${de(le)}`:void 0;return d===!1?q(a,m):x(a,m)}}else if(T){const i=se(T)??void 0;u=(i?await oe(i):!1)?void 0:i}const _={isAuthenticated:!!e.user?.isAuthenticated,teams:e.user?.teams||[B],claims:e.user?.claims??{}};return me(H.MCP,_,c,t)?await W(async()=>{const i=p==="code"&&(n?.props?.config?.elicitationEnabled??!1);if(o.method==="GET")return new Response(JSON.stringify({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: ${o.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(o.method!=="POST")return Q();const d=r?.props?.config?.apiDescriptionsMap||{},g=r?.props?.config?.graphqlDescriptions||[],l=r?.props?.config?.mcpDocsServerName||ae,{config:{mcp:h={}}}=e,a=J(d,e.user,c,t),m=K(g,e.user,c,t),y=e.config.products?Object.values(e.config.products).map(s=>s?.name):[],D=h.docs?.name||l,f=ge(o.headers.get(E)),P=r?.props?.tools||[],O=r?.props?.skillsBaseUrl||M(o),w=V(r?.props?.skills||[],e.user,c,t).map(s=>({slug:s.slug,name:s.name,description:s.description,content:s.content,uri:$(O,s.slug)})),S=r?.props?.fetchCountSecret,F={name:D,tools:P,skills:w,context:{...e,config:{...e.config,mcp:ce(e.config.mcp,f)},configFile:r?.props?.configFile,accessToken:u,outdir:e.outdir||"",baseUrl:e.baseUrl||M(o),internalBaseUrl:N(o),apiDescriptionsMap:a,graphqlDescriptions:m,products:y,metadata:f,mcpMode:p,elicitationEnabled:i,gatewayFetchBudgetPerExec:U,fetchCountRequest:p==="code"&&S?{caller:{subject:z(e.user),ip:X(o)},secret:S}:void 0,searchIgnoredRoutes:R,clientIp:v(o),...ie(o),requestId:ne(),messageId:typeof f?.messageId=="string"?f.messageId:void 0}},k=await G({...F,getKv:e.getKv});return await Y(async()=>k,{keepAliveMs:pe,maxRequestBodySize:ue,onerror:s=>A.warn(`MCP handler: ${s.message}`)}).fetch(o)},p):Z()};var Je=Ae;export{Je as default};
@@ -0,0 +1,9 @@
1
+ import type { RedoclyConfig } from '@redocly/config';
2
+ /** Whether the config serves the docs MCP server at `/mcp`. Ignores the `mcp` entitlement. */
3
+ export declare function isMcpRouteServedByConfig(config: Pick<RedoclyConfig, 'mcp'>): boolean;
4
+ /**
5
+ * Whether the config serves the public docs MCP endpoint at `/mcp-public`.
6
+ * Ignores the `mcp` entitlement.
7
+ */
8
+ export declare function isPublicMcpRouteServedByConfig(config: Pick<RedoclyConfig, 'mcp' | 'access'>): boolean;
9
+ //# sourceMappingURL=route-reservation.d.ts.map
@@ -0,0 +1 @@
1
+ import{getPublicMcpEndpointStatus as t}from"./public-endpoint.js";function o(e){return!e?.mcp?.hide&&!e?.mcp?.docs?.hide}function r(e){return t(e)==="served"}export{o as isMcpRouteServedByConfig,r as isPublicMcpRouteServedByConfig};
@@ -1 +1 @@
1
- import*as h from"path";import{REDOCLY_ROUTE_RBAC as b,REDOCLY_TEAMS_RBAC as p}from"@redocly/config";import{VERSION_SEPARATOR as x}from"../constants/common.js";import{DEFAULT_LOCALE_PLACEHOLDER as M}from"../../constants/common.js";import{removeTrailingSlash as j}from"../../utils/url/remove-trailing-slash.js";import{isPrimitive as W}from"../../utils/guards/is-primitive.js";import{slash as w}from"../../utils/path/slash.js";import{isAbsoluteUrl as z}from"../../utils/url/is-absolute-url.js";import{normalizeRouteSlug as J}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as C}from"../../utils/path/parse-path-versions.js";import{logger as A}from"../tools/notifiers/logger.js";import{reporter as F}from"../tools/notifiers/reporter.js";import{shaDirPathShort as R}from"../utils/crypto/sha-dir-path-short.js";import{copyStaticFile as U,FileNotFoundError as D}from"../utils/fs.js";import{isIconPath as H,resolveAssetPath as Y}from"../utils/index.js";import{resolveSrcSet as G}from"../utils/resolve-src-set.js";import{isL10nPath as E}from"../fs/utils/is-l10n-path.js";import{getLocaleFromRelativePath as q}from"../fs/utils/get-locale-from-relative-path.js";async function B(e,i,n,s,a){if(!e)return;const f={...a,ignoreCustomSidebar:!0};if(W(e)){if(typeof e=="string"){const r=I(n.contentDir,i,a,e,s.fs);if(s.fs.exists(r)){if(n.getRouteByFsPath(r))return K({page:e},i,n,s,f);{const g=s.fs.getFileInfo(r);return g?U(n.contentDir,g.realRelativePath,n.outdir):void 0}}}return e}return Array.isArray(e)?k(N(e),i,n,s,f):Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,l])=>[r,await B(l,i,n,s,a)])))}function N(e){return e.map(i=>({...i,items:i.items?N(i.items):void 0}))}async function k(e,i,n,s,a){if(Array.isArray(e))return(await Promise.all(e.map(f=>K(f,i,n,s,a)))).flatMap(f=>f)}async function y(e,i,n,s){let a,f;if(typeof e.icon=="object"){if("srcSet"in e.icon)try{a=await G(e.icon.srcSet,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`):await F.panicOnBuild(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`)}}else if(typeof e.icon=="string")if(z(e.icon)||H(e.icon))try{f=await Y(e.icon,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon" from ${s.navFile}: file ${f} does not exist`):await F.panicOnBuild(`Cannot resolve "item.icon" from ${s.navFile}: ${d.message}`)}else f=e.icon;return{icon:f,srcSet:a}}function Q(e){return i=>{if(i.type==="link"||i.type==="group"){const n=i.metadata;return n?Object.entries(e).every(([s,a])=>Array.isArray(a)?a.some(f=>n[s]===f):n[s]===a):!1}return!0}}async function K(e,i,n,s,a){if(e?.tab!==void 0||e?.menu!==void 0){const t=`Navigation tabs ("tab"/"menu") are only allowed at the top level of a sidebars.yaml file: ${JSON.stringify(e)}`;return await F.panicOnBuildContentError(`Invalid nav item in %rp. ${t}`,a.navFile),{type:"error",label:t}}if(e?.directory&&e.items?.length)return{type:"error",label:`Can't have both "directory" and "items" in the nav item: ${JSON.stringify(e)}`};e?.directory&&e?.group&&(e={...e,directory:void 0,items:[{directory:e.directory}]});const f=e?.directory?I(n.contentDir,i,a,e.directory,s.fs):void 0;if(f!==void 0){const t=f===""?"":f+"/",{locale:u,ignoredRoutes:o}=a,v=n.getAllRoutesForLocale(u).filter(c=>!o?.has(c.baseSlug||"")&&c.fsPath.startsWith(t)&&!c.excludeFromSidebar).sort((c,P)=>c.fsPath===P.fsPath?0:c.baseSlug.localeCompare(P.baseSlug,void 0,{numeric:!0})),L=e.includeByMetadata?Q(e.includeByMetadata):Boolean;if(!v.length)return[];const T=(await Promise.all(v.map(async c=>{const P=c.versions?.find(_=>_.active),S=P&&{version:P.version,isDefault:P.default,versionFolderId:P.folderId},V=ee(h.posix.relative(f,c.fsPath)),O=c.getSidebar?.(c);return!a.ignoreCustomSidebar&&O?.length?{type:"group",fsPath:c.fsPath,metadata:c.metadata,link:c.slug,routeSlug:c.slug,label:await c.getNavText?.()||c.slug,[p]:c[p],[b]:c[b],sidebarItems:m(O,S,c[p],c[b]),version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:h.relative(f,c.fsPath).replace(/@(?<!@[^/]*?@)[^/]+\//,"")}:{type:"link",fsPath:c.fsPath,metadata:c.metadata,[p]:c[p],[b]:c[b],label:await c.getNavText?.()||c.slug,link:c.slug,routeSlug:c.slug,version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:V}}))).filter(L);return e.flatten?$(T,a):Z(T,a)}let d=typeof e=="string"?e:e?.page,r,l;if(d){if(d.includes("#")){const[t,u]=d.split("#");u?l=u:A.warn(`Invalid heading anchor format in sidebar: "${u}". Heading anchors should contain only alphanumeric characters, hyphens, and underscores.`),d=t}if(d=j(d),a.locale&&a.locale!==M){const t=J(h.join(a.locale.toLowerCase(),d));r=n.getRouteBySlug(t)}r||(r=n.getRouteBySlug(d)),r||(r=n.getRouteByFsPath(I(n.contentDir,i,a,d,s.fs)))}const g=r?.metadata;if(e?.$ref){let t=I(n.contentDir,i,a,e.$ref,s.fs);if(a.ref!==void 0&&(t=h.posix.join(a.ref,e.$ref)),!s.fs.exists(t))return await F.panicOnBuildContentError(`Failed to load ${t} file. Make sure sidebar $ref path is correct.`),[];const u=await s.cache.load(t,"yaml"),o=h.dirname(t);return await k(u.data,i,n,s,{...a,navFile:t,ref:o})||[]}if(!r){const t=a.excludedFromLinkCheckerPatterns?.catalog.some(o=>o.test(d||"")),u=a.excludedFromLinkCheckerPatterns?.apiFunctions.some(o=>o.test(d||e.href||""));(u||t)&&(e={...e,href:d||e.href,page:void 0,target:e.target??(u?"_blank":void 0)}),await X(e,a,s,i)}if(r&&!e.disconnect&&!a.ignoreCustomSidebar&&(l||r?.getSidebar)){const t=r.versions?.find(o=>o.active),u=t&&{version:t.version,isDefault:t.default,versionFolderId:t.folderId};if(l){let o=[];if(r.getSidebar&&(o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),o&&o.length>0)){const v=o[0];v&&v.link&&(v.link=`${v.link}#${l}`)}if(!o||o.length===0){const v=e.group||e.label||l;o=[{type:"link",fsPath:r.fsPath,metadata:r.metadata,link:`${r.slug}#${l}`,routeSlug:r.slug,label:v,labelTranslationKey:e.labelTranslationKey,...await y(e,n,s,a),[p]:r[p],[b]:{slug:r.slug,fsPath:r.fsPath},...u}]}return m(o,u,r[p],r[b])}if(r?.getSidebar){const o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),v=e.group&&o?.[0]?.routeSlug===r.slug?o.slice(1):o;return m(a.groupCustomSidebars||e.group?[{type:"group",fsPath:r.fsPath,link:r.slug,routeSlug:r.slug,label:e.group||e.label||await r.getNavText?.()||r.slug,items:v,labelTranslationKey:e.labelTranslationKey,metadata:g,badges:e.badges,...await y(e,n,s,a)}]:o,u,r[p],r[b])}}if(r&&!e.group){const t=l?`${r.slug}#${l}`:r.slug;let u=e.label||l||"";u||(u=await r.getNavText?.()||r.slug);const o=r.versions?.find(L=>L.active),v=o&&{version:o.version,isDefault:o.default,versionFolderId:o.folderId};return{type:"link",fsPath:r.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,[p]:e?.rbac||r[p],[b]:{slug:r.slug,fsPath:r.fsPath},label:u,labelTranslationKey:e.labelTranslationKey,link:t,items:await k(e.items,i,n,s,a),separatorLine:e.separatorLine,linePosition:e.linePosition,routeSlug:e.disconnect?void 0:t,external:e.external,target:e.target,badges:e.badges,...await y(e,n,s,a),...v,additionalProps:e.additionalProps}}else if(e?.group){const t=r?.versions?.find(o=>o.active),u=C(a?.navFile);return{type:"group",fsPath:r?.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,version:t?.version||u?.versionName,versionFolderId:t?.folderId||(u?.versionFolderPath?R(u.versionFolderPath):void 0),label:e.group,link:r?.slug,routeSlug:r?.slug,badges:e.badges,labelTranslationKey:e.groupTranslationKey,items:await k(e.items,i,n,s,a),expanded:e.expanded?e.expanded.toString():void 0,selectFirstItemOnExpand:e.selectFirstItemOnExpand,menuStyle:e.menuStyle,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,[b]:{slug:r?.slug||"",fsPath:r?.fsPath||""},additionalProps:e.additionalProps}}else{if(e?.href||e?.label)return{type:"link",metadata:g,link:e.href||"",label:e?.label||e?.href||"",labelTranslationKey:e.labelTranslationKey,external:e.external,target:e.target,separatorLine:e.separatorLine,linePosition:e.linePosition,badges:e.badges,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps};if(e?.separator!=null||e?.separatorLine!=null){const t=C(a?.navFile);return{type:"separator",metadata:g,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0,label:e.separator,labelTranslationKey:e.separatorTranslationKey,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps}}else{const t=C(a?.navFile);return{type:"error",label:`Can't resolve page: ${JSON.stringify(e)}`,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0}}}}async function X(e,i,n,s){const{href:a,page:f}=e;if(a||!f)return;const d=I(n.fs.cwd,s,i,f,n.fs),r=n.fs.exists(d),l=await n.isPathIgnored(d),g=(r?"The page is ignored: ":"Can't resolve page: ")+f;(!r||l)&&F.reportBrokenLink({type:"BROKEN_LINK",brokenLinkType:"LINK",title:e.label||e.group||"",link:d,rawLink:f,message:g,sourceFileRelativePath:i.navFile,sourceFileLocation:{line:0}})}function I(e,i,n,s="",a){if(n.ref!==void 0)return w(h.relative(e,h.resolve(e,h.join(n.ref,s))));if(s.startsWith("/")){const f=E(i)?q(i):void 0,d=f?`${a.localizationFolder}/${f}/`:"",r=s.slice(1);return E(r)?r:d+w(r)}return w(h.relative(e,h.resolve(e,i,s)))}function Z(e,i){const n={};for(const r of e){const l=h.dirname(r.relativePathFromDirectory),g=r.version?x+r.version:"",t=h.basename(r.relativePathFromDirectory)+g;d(l,r,t)}const s=f(a(n));return $(s,i);function a(r){const l=[];for(const g of Object.keys(r)){const t=r[g];l.push({...t,items:t.items?a(t.items):void 0})}return l}function f(r){return r.sort((l,g)=>{const t=typeof l=="string"?l.toLowerCase():l.relativePathFromDirectory||l.label||"",u=typeof g=="string"?g.toLowerCase():g.relativePathFromDirectory||g.label||"";return t.startsWith("index.")?-1:u.startsWith("index.")?1:t.localeCompare(u,void 0,{numeric:!0})})}function d(r,l,g){r==="."&&(r="");const t=r.split("/").filter(Boolean);let u=n;for(const o of t){const v=o+(l?.version||"");u[v]||(u[v]={type:"group",version:l?.version,label:o,isDefault:l?.isDefault,versionFolderId:l.versionFolderId,items:{}}),u=u[v].items}u[g]=l}}function $(e,i){return e.flatMap(n=>n?.sidebarItems?i.groupCustomSidebars?{...n,items:n.sidebarItems,sidebarItems:void 0,relativePathFromDirectory:void 0}:n.sidebarItems:{...n,items:n.items?$(n.items,i):void 0})}function m(e,i,n,s){return e.map(a=>({...a,...i,[p]:a[p]||n,[b]:a[b]||s,items:a.type==="group"&&a.items?m(a.items,i,n):a.items}))}function ee(e){return e.replace(/@(?<!@[^/]*?@)[^/]+\//,"")}async function ye(e,i,n,s){const a=(e?.items||[]).filter(r=>r.linkedSidebars?.length).map(({items:r,...l})=>l),f=await B(a,i.contentDir,i,n,s),d=new Map;for(const r of f)if(r.linkedSidebars?.length)for(const l of r.linkedSidebars){if(d.has(l)){A.warn(`Only one navbar item can belong to sidebar. "${l}" on 'linkedSidebars' property on "${r.label}" will be ignored.`);continue}d.set(l,{label:r.label,link:r.link})}return d}export{ye as collectItemsLinkedToSidebars,N as normalizeItems,K as resolveItem,k as resolveItems,B as resolveLinksFromConfig};
1
+ import*as h from"path";import{REDOCLY_ROUTE_RBAC as b,REDOCLY_TEAMS_RBAC as p}from"@redocly/config";import{VERSION_SEPARATOR as x}from"../constants/versions.js";import{DEFAULT_LOCALE_PLACEHOLDER as M}from"../../constants/common.js";import{removeTrailingSlash as j}from"../../utils/url/remove-trailing-slash.js";import{isPrimitive as W}from"../../utils/guards/is-primitive.js";import{slash as w}from"../../utils/path/slash.js";import{isAbsoluteUrl as z}from"../../utils/url/is-absolute-url.js";import{normalizeRouteSlug as J}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as C}from"../../utils/path/parse-path-versions.js";import{logger as A}from"../tools/notifiers/logger.js";import{reporter as F}from"../tools/notifiers/reporter.js";import{shaDirPathShort as R}from"../utils/crypto/sha-dir-path-short.js";import{copyStaticFile as U,FileNotFoundError as D}from"../utils/fs.js";import{isIconPath as H,resolveAssetPath as Y}from"../utils/index.js";import{resolveSrcSet as G}from"../utils/resolve-src-set.js";import{isL10nPath as E}from"../fs/utils/is-l10n-path.js";import{getLocaleFromRelativePath as q}from"../fs/utils/get-locale-from-relative-path.js";async function B(e,i,n,s,a){if(!e)return;const f={...a,ignoreCustomSidebar:!0};if(W(e)){if(typeof e=="string"){const r=I(n.contentDir,i,a,e,s.fs);if(s.fs.exists(r)){if(n.getRouteByFsPath(r))return K({page:e},i,n,s,f);{const g=s.fs.getFileInfo(r);return g?U(n.contentDir,g.realRelativePath,n.outdir):void 0}}}return e}return Array.isArray(e)?k(N(e),i,n,s,f):Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,l])=>[r,await B(l,i,n,s,a)])))}function N(e){return e.map(i=>({...i,items:i.items?N(i.items):void 0}))}async function k(e,i,n,s,a){if(Array.isArray(e))return(await Promise.all(e.map(f=>K(f,i,n,s,a)))).flatMap(f=>f)}async function y(e,i,n,s){let a,f;if(typeof e.icon=="object"){if("srcSet"in e.icon)try{a=await G(e.icon.srcSet,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`):await F.panicOnBuild(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`)}}else if(typeof e.icon=="string")if(z(e.icon)||H(e.icon))try{f=await Y(e.icon,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon" from ${s.navFile}: file ${f} does not exist`):await F.panicOnBuild(`Cannot resolve "item.icon" from ${s.navFile}: ${d.message}`)}else f=e.icon;return{icon:f,srcSet:a}}function Q(e){return i=>{if(i.type==="link"||i.type==="group"){const n=i.metadata;return n?Object.entries(e).every(([s,a])=>Array.isArray(a)?a.some(f=>n[s]===f):n[s]===a):!1}return!0}}async function K(e,i,n,s,a){if(e?.tab!==void 0||e?.menu!==void 0){const t=`Navigation tabs ("tab"/"menu") are only allowed at the top level of a sidebars.yaml file: ${JSON.stringify(e)}`;return await F.panicOnBuildContentError(`Invalid nav item in %rp. ${t}`,a.navFile),{type:"error",label:t}}if(e?.directory&&e.items?.length)return{type:"error",label:`Can't have both "directory" and "items" in the nav item: ${JSON.stringify(e)}`};e?.directory&&e?.group&&(e={...e,directory:void 0,items:[{directory:e.directory}]});const f=e?.directory?I(n.contentDir,i,a,e.directory,s.fs):void 0;if(f!==void 0){const t=f===""?"":f+"/",{locale:u,ignoredRoutes:o}=a,v=n.getAllRoutesForLocale(u).filter(c=>!o?.has(c.baseSlug||"")&&c.fsPath.startsWith(t)&&!c.excludeFromSidebar).sort((c,P)=>c.fsPath===P.fsPath?0:c.baseSlug.localeCompare(P.baseSlug,void 0,{numeric:!0})),L=e.includeByMetadata?Q(e.includeByMetadata):Boolean;if(!v.length)return[];const T=(await Promise.all(v.map(async c=>{const P=c.versions?.find(_=>_.active),S=P&&{version:P.version,isDefault:P.default,versionFolderId:P.folderId},V=ee(h.posix.relative(f,c.fsPath)),O=c.getSidebar?.(c);return!a.ignoreCustomSidebar&&O?.length?{type:"group",fsPath:c.fsPath,metadata:c.metadata,link:c.slug,routeSlug:c.slug,label:await c.getNavText?.()||c.slug,[p]:c[p],[b]:c[b],sidebarItems:m(O,S,c[p],c[b]),version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:h.relative(f,c.fsPath).replace(/@(?<!@[^/]*?@)[^/]+\//,"")}:{type:"link",fsPath:c.fsPath,metadata:c.metadata,[p]:c[p],[b]:c[b],label:await c.getNavText?.()||c.slug,link:c.slug,routeSlug:c.slug,version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:V}}))).filter(L);return e.flatten?$(T,a):Z(T,a)}let d=typeof e=="string"?e:e?.page,r,l;if(d){if(d.includes("#")){const[t,u]=d.split("#");u?l=u:A.warn(`Invalid heading anchor format in sidebar: "${u}". Heading anchors should contain only alphanumeric characters, hyphens, and underscores.`),d=t}if(d=j(d),a.locale&&a.locale!==M){const t=J(h.join(a.locale.toLowerCase(),d));r=n.getRouteBySlug(t)}r||(r=n.getRouteBySlug(d)),r||(r=n.getRouteByFsPath(I(n.contentDir,i,a,d,s.fs)))}const g=r?.metadata;if(e?.$ref){let t=I(n.contentDir,i,a,e.$ref,s.fs);if(a.ref!==void 0&&(t=h.posix.join(a.ref,e.$ref)),!s.fs.exists(t))return await F.panicOnBuildContentError(`Failed to load ${t} file. Make sure sidebar $ref path is correct.`),[];const u=await s.cache.load(t,"yaml"),o=h.dirname(t);return await k(u.data,i,n,s,{...a,navFile:t,ref:o})||[]}if(!r){const t=a.excludedFromLinkCheckerPatterns?.catalog.some(o=>o.test(d||"")),u=a.excludedFromLinkCheckerPatterns?.apiFunctions.some(o=>o.test(d||e.href||""));(u||t)&&(e={...e,href:d||e.href,page:void 0,target:e.target??(u?"_blank":void 0)}),await X(e,a,s,i)}if(r&&!e.disconnect&&!a.ignoreCustomSidebar&&(l||r?.getSidebar)){const t=r.versions?.find(o=>o.active),u=t&&{version:t.version,isDefault:t.default,versionFolderId:t.folderId};if(l){let o=[];if(r.getSidebar&&(o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),o&&o.length>0)){const v=o[0];v&&v.link&&(v.link=`${v.link}#${l}`)}if(!o||o.length===0){const v=e.group||e.label||l;o=[{type:"link",fsPath:r.fsPath,metadata:r.metadata,link:`${r.slug}#${l}`,routeSlug:r.slug,label:v,labelTranslationKey:e.labelTranslationKey,...await y(e,n,s,a),[p]:r[p],[b]:{slug:r.slug,fsPath:r.fsPath},...u}]}return m(o,u,r[p],r[b])}if(r?.getSidebar){const o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),v=e.group&&o?.[0]?.routeSlug===r.slug?o.slice(1):o;return m(a.groupCustomSidebars||e.group?[{type:"group",fsPath:r.fsPath,link:r.slug,routeSlug:r.slug,label:e.group||e.label||await r.getNavText?.()||r.slug,items:v,labelTranslationKey:e.labelTranslationKey,metadata:g,badges:e.badges,...await y(e,n,s,a)}]:o,u,r[p],r[b])}}if(r&&!e.group){const t=l?`${r.slug}#${l}`:r.slug;let u=e.label||l||"";u||(u=await r.getNavText?.()||r.slug);const o=r.versions?.find(L=>L.active),v=o&&{version:o.version,isDefault:o.default,versionFolderId:o.folderId};return{type:"link",fsPath:r.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,[p]:e?.rbac||r[p],[b]:{slug:r.slug,fsPath:r.fsPath},label:u,labelTranslationKey:e.labelTranslationKey,link:t,items:await k(e.items,i,n,s,a),separatorLine:e.separatorLine,linePosition:e.linePosition,routeSlug:e.disconnect?void 0:t,external:e.external,target:e.target,badges:e.badges,...await y(e,n,s,a),...v,additionalProps:e.additionalProps}}else if(e?.group){const t=r?.versions?.find(o=>o.active),u=C(a?.navFile);return{type:"group",fsPath:r?.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,version:t?.version||u?.versionName,versionFolderId:t?.folderId||(u?.versionFolderPath?R(u.versionFolderPath):void 0),label:e.group,link:r?.slug,routeSlug:r?.slug,badges:e.badges,labelTranslationKey:e.groupTranslationKey,items:await k(e.items,i,n,s,a),expanded:e.expanded?e.expanded.toString():void 0,selectFirstItemOnExpand:e.selectFirstItemOnExpand,menuStyle:e.menuStyle,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,[b]:{slug:r?.slug||"",fsPath:r?.fsPath||""},additionalProps:e.additionalProps}}else{if(e?.href||e?.label)return{type:"link",metadata:g,link:e.href||"",label:e?.label||e?.href||"",labelTranslationKey:e.labelTranslationKey,external:e.external,target:e.target,separatorLine:e.separatorLine,linePosition:e.linePosition,badges:e.badges,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps};if(e?.separator!=null||e?.separatorLine!=null){const t=C(a?.navFile);return{type:"separator",metadata:g,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0,label:e.separator,labelTranslationKey:e.separatorTranslationKey,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps}}else{const t=C(a?.navFile);return{type:"error",label:`Can't resolve page: ${JSON.stringify(e)}`,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0}}}}async function X(e,i,n,s){const{href:a,page:f}=e;if(a||!f)return;const d=I(n.fs.cwd,s,i,f,n.fs),r=n.fs.exists(d),l=await n.isPathIgnored(d),g=(r?"The page is ignored: ":"Can't resolve page: ")+f;(!r||l)&&F.reportBrokenLink({type:"BROKEN_LINK",brokenLinkType:"LINK",title:e.label||e.group||"",link:d,rawLink:f,message:g,sourceFileRelativePath:i.navFile,sourceFileLocation:{line:0}})}function I(e,i,n,s="",a){if(n.ref!==void 0)return w(h.relative(e,h.resolve(e,h.join(n.ref,s))));if(s.startsWith("/")){const f=E(i)?q(i):void 0,d=f?`${a.localizationFolder}/${f}/`:"",r=s.slice(1);return E(r)?r:d+w(r)}return w(h.relative(e,h.resolve(e,i,s)))}function Z(e,i){const n={};for(const r of e){const l=h.dirname(r.relativePathFromDirectory),g=r.version?x+r.version:"",t=h.basename(r.relativePathFromDirectory)+g;d(l,r,t)}const s=f(a(n));return $(s,i);function a(r){const l=[];for(const g of Object.keys(r)){const t=r[g];l.push({...t,items:t.items?a(t.items):void 0})}return l}function f(r){return r.sort((l,g)=>{const t=typeof l=="string"?l.toLowerCase():l.relativePathFromDirectory||l.label||"",u=typeof g=="string"?g.toLowerCase():g.relativePathFromDirectory||g.label||"";return t.startsWith("index.")?-1:u.startsWith("index.")?1:t.localeCompare(u,void 0,{numeric:!0})})}function d(r,l,g){r==="."&&(r="");const t=r.split("/").filter(Boolean);let u=n;for(const o of t){const v=o+(l?.version||"");u[v]||(u[v]={type:"group",version:l?.version,label:o,isDefault:l?.isDefault,versionFolderId:l.versionFolderId,items:{}}),u=u[v].items}u[g]=l}}function $(e,i){return e.flatMap(n=>n?.sidebarItems?i.groupCustomSidebars?{...n,items:n.sidebarItems,sidebarItems:void 0,relativePathFromDirectory:void 0}:n.sidebarItems:{...n,items:n.items?$(n.items,i):void 0})}function m(e,i,n,s){return e.map(a=>({...a,...i,[p]:a[p]||n,[b]:a[b]||s,items:a.type==="group"&&a.items?m(a.items,i,n):a.items}))}function ee(e){return e.replace(/@(?<!@[^/]*?@)[^/]+\//,"")}async function ye(e,i,n,s){const a=(e?.items||[]).filter(r=>r.linkedSidebars?.length).map(({items:r,...l})=>l),f=await B(a,i.contentDir,i,n,s),d=new Map;for(const r of f)if(r.linkedSidebars?.length)for(const l of r.linkedSidebars){if(d.has(l)){A.warn(`Only one navbar item can belong to sidebar. "${l}" on 'linkedSidebars' property on "${r.label}" will be ignored.`);continue}d.set(l,{label:r.label,link:r.link})}return d}export{ye as collectItemsLinkedToSidebars,N as normalizeItems,K as resolveItem,k as resolveItems,B as resolveLinksFromConfig};
@@ -1,10 +1,6 @@
1
1
  import type { ContentFs } from '../fs/content-fs.js';
2
2
  import type { LifecycleContext } from '../types';
3
3
  export declare function resolveFrontmatterSlugs(slugs: unknown, relativePath: string): string[];
4
- export declare function parseBaseName(relativePath: string): {
5
- baseName: string;
6
- isIndexFile: boolean;
7
- };
8
4
  export declare function findFrontmatterSlugs(relativePath: string, loaderName: string, frontmatter: Record<string, any> | undefined, context: LifecycleContext): Promise<string[] | undefined>;
9
5
  export declare function getSidebarSharedDataId(sidebar: string | {
10
6
  path: string;
@@ -1 +1 @@
1
- import a from"path";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../../constants/common.js";import{normalizeRouteSlug as l}from"../../utils/path/normalize-route-slug.js";import{slash as i}from"../../utils/path/slash.js";import{logger as u}from"../tools/notifiers/logger.js";import{getLocaleFromRelativePath as f}from"../fs/utils/get-locale-from-relative-path.js";import{isL10nPath as p}from"../fs/utils/is-l10n-path.js";import{removeL10nPrefix as c}from"../fs/utils/remove-l10n-prefix.js";import{resolveSidebarId as d}from"./sidebars/index.js";function b(e,r){return(Array.isArray(e)?e:e?[e]:[]).map(o=>g(o,r))}function g(e,r){const t=f(r).toLowerCase(),o=l(e);return t!==m?`/${t}${o}`:o}function I(e){const r=e.endsWith(".page.tsx")?".page.tsx":a.posix.extname(e),t=a.posix.basename(e,r);return{baseName:t,isIndexFile:t==="index"}}async function P(e,r,t,o){if(t?.slug||!p(e))return t?.slug;const n=c(e);if(!o.fs.exists(n))return;const{data:s}=await o.cache.load(n,r);return s?.frontmatter?.slug}async function w(e,r,t){const o=typeof e=="string",n=o?e:e.path;return o&&u.warnForRealFile("The 'sidebar' property in the front matter of %rp is deprecated. Use 'sidebar.path' instead.",r,t),n?d(r,n,t):null}function C(e,r){return e.filter(t=>i(t.fsPath)===i(r)).map(t=>t.slug)}export{P as findFrontmatterSlugs,C as getRouteSlugsForPath,w as getSidebarSharedDataId,I as parseBaseName,b as resolveFrontmatterSlugs};
1
+ import{DEFAULT_LOCALE_PLACEHOLDER as s}from"../../constants/common.js";import{normalizeRouteSlug as l}from"../../utils/path/normalize-route-slug.js";import{slash as n}from"../../utils/path/slash.js";import{logger as u}from"../tools/notifiers/logger.js";import{getLocaleFromRelativePath as f}from"../fs/utils/get-locale-from-relative-path.js";import{isL10nPath as m}from"../fs/utils/is-l10n-path.js";import{removeL10nPrefix as p}from"../fs/utils/remove-l10n-prefix.js";import{resolveSidebarId as c}from"./sidebars/index.js";function E(r,e){return(Array.isArray(r)?r:r?[r]:[]).map(o=>d(o,e))}function d(r,e){const t=f(e).toLowerCase(),o=l(r);return t!==s?`/${t}${o}`:o}async function P(r,e,t,o){if(t?.slug||!m(r))return t?.slug;const a=p(r);if(!o.fs.exists(a))return;const{data:i}=await o.cache.load(a,e);return i?.frontmatter?.slug}async function R(r,e,t){const o=typeof r=="string",a=o?r:r.path;return o&&u.warnForRealFile("The 'sidebar' property in the front matter of %rp is deprecated. Use 'sidebar.path' instead.",e,t),a?c(e,a,t):null}function v(r,e){return r.filter(t=>n(t.fsPath)===n(e)).map(t=>t.slug)}export{P as findFrontmatterSlugs,v as getRouteSlugsForPath,R as getSidebarSharedDataId,E as resolveFrontmatterSlugs};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Splits a content file path into the name its route is built from and whether it is an index.
3
+ *
4
+ * @param relativePath - Path relative to the content root; `.page.tsx` counts as one extension.
5
+ * @returns The file name without its extension, and `isIndexFile` when that name is `index`.
6
+ *
7
+ * @example
8
+ * parseBaseName('docs/index.page.tsx');
9
+ * // Returns: { baseName: 'index', isIndexFile: true }
10
+ */
11
+ export declare function parseBaseName(relativePath: string): {
12
+ baseName: string;
13
+ isIndexFile: boolean;
14
+ };
15
+ //# sourceMappingURL=parse-base-name.d.ts.map
@@ -0,0 +1 @@
1
+ import n from"path";function i(e){const x=e.endsWith(".page.tsx")?".page.tsx":n.posix.extname(e),s=n.posix.basename(e,x);return{baseName:s,isIndexFile:s==="index"}}export{i as parseBaseName};
@@ -0,0 +1,5 @@
1
+ import type { RbacConfig } from '@redocly/config';
2
+ import type { AuthDetails } from '../../types';
3
+ import type { RbacFeatures } from '../../../constants/common.js';
4
+ export declare function canAccessFeature(feature: RbacFeatures, auth: AuthDetails, rbacConfig?: RbacConfig, requiresLogin?: boolean): boolean;
5
+ //# sourceMappingURL=can-access-feature.d.ts.map
@@ -0,0 +1 @@
1
+ import{hasScopeAccess as n}from"./has-scope-access.js";function a(s,e,t={},c=!1){if(c&&Object.keys(t).length===0)return e.isAuthenticated;const r=t.features?.[s];return r?n(r,e.teams):!0}export{a as canAccessFeature};
@@ -1 +1 @@
1
- import{RbacFeatures as o}from"../../../constants/common.js";import{ANONYMOUS_AUTH_DETAILS as c}from"../../constants/rbac.js";import{canAccessFeature as t}from"../rbac.js";function s(r,e){return t(o.MCP,c,r,e)}export{s as canAnonymousAccessMcpFeature};
1
+ import{RbacFeatures as o}from"../../../constants/common.js";import{ANONYMOUS_AUTH_DETAILS as c}from"../../constants/rbac.js";import{canAccessFeature as t}from"./can-access-feature.js";function s(r,e){return t(o.MCP,c,r,e)}export{s as canAnonymousAccessMcpFeature};
@@ -0,0 +1,3 @@
1
+ import type { RbacScopeItems } from '@redocly/config';
2
+ export declare function hasScopeAccess(scopeItems: RbacScopeItems, teams: string[], email?: string): boolean;
3
+ //# sourceMappingURL=has-scope-access.d.ts.map
@@ -0,0 +1 @@
1
+ import{RBAC_ALL_OTHER_TEAMS as e}from"../../../constants/common.js";function c(r,f,n){const t=n?[...f,n]:f,s=[];for(const o of t)r[o]?s.push(r[o]):r[e]&&o!==n&&s.push(r[e]);return s.some(o=>o.toLowerCase()!=="none")}export{c as hasScopeAccess};
@@ -4,7 +4,6 @@ import type { RbacConfig, RbacScopeItems, RedoclyConfig, SsoConfig } from '@redo
4
4
  import type { AuthDetails } from '../types';
5
5
  import type { ApiDefinitionAccess } from '../plugins/api-docs/definition-access.js';
6
6
  import type { ContentFs } from '../fs/content-fs.js';
7
- import type { RbacFeatures } from '../../constants/common.js';
8
7
  export type ProjectRole = 'NONE' | 'READ' | 'TRIAGE' | 'WRITE' | 'MAINTAIN' | 'ADMIN';
9
8
  export declare const PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL: string[];
10
9
  export declare function getHigherRole(a: ProjectRole, b: ProjectRole): ProjectRole;
@@ -12,12 +11,15 @@ export declare function getScopeItemsForResource(rbacConfig: RbacConfig | undefi
12
11
  fsPath?: string;
13
12
  slug?: string;
14
13
  }): RbacScopeItems;
15
- export declare function hasScopeAccess(scopeItems: RbacScopeItems, teams: string[], email?: string): boolean;
16
- export declare function canAccessFeature(feature: RbacFeatures, auth: AuthDetails, rbacConfig?: RbacConfig, requiresLogin?: boolean): boolean;
17
14
  export declare function isResourcePubliclyAccessible(resource: {
18
15
  slug: string;
19
16
  [REDOCLY_TEAMS_RBAC]?: Record<string, string>;
20
17
  }, config: RedoclyConfig): boolean;
18
+ /**
19
+ * Whether the content rules give anonymous visitors at least one page. A rule for an API
20
+ * function (`@api`) is not a rule for a page. Reads only the config, not the pages.
21
+ */
22
+ export declare function areAnyPagesOpenToAnonymous(rbacConfig: RbacConfig | undefined): boolean;
21
23
  export declare function canAccessResource(resource: {
22
24
  slug?: string;
23
25
  [REDOCLY_TEAMS_RBAC]?: RbacScopeItems;
@@ -1 +1 @@
1
- import y from"path";import O from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as T,REDOCLY_ROUTE_RBAC as R}from"@redocly/config";import{MCP_ROUTE as U,PUBLIC_MCP_ROUTE as k}from"@redocly/theme/core/constants/mcp";import{ServerRoutes as w}from"../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as D,PUBLIC_RBAC_SCOPE_ITEM as _,RBAC_ALL_OTHER_TEAMS as l,DEFAULT_RBAC_SCOPE as x,GRAPHQL_SPEC_SLUG as B}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as g,PUBLIC_API_DEFINITIONS_FOLDER as I,PUBLIC_ASSETS_FOLDER as b,RUNTIME_RESOURCES_DIR as $,SCORECARD_CLASSIC_FOLDER as W,SITEMAP_FILE_NAME as v,LLMS_TXT_FILE_NAME as Y}from"../constants/common.js";import{MCP_CREDENTIALS_ROUTE as G}from"../constants/mcp.js";import{ANONYMOUS_AUTH_DETAILS as H}from"../constants/rbac.js";import{removeTrailingSlash as S}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as z}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as K}from"../../utils/path/parse-path-versions.js";import{reporter as V}from"../tools/notifiers/reporter.js";import{bold as J}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as Q}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as X}from"../../utils/guards/is-truthy.js";import{isPathInFolder as C}from"../../utils/path/is-path-in-folder.js";import{canExpandConfig as Z,expandRbacConfig as q,getTeamFolderDefaults as tt,parseTeamFoldersTemplate as et,parseTeamNameTemplate as rt}from"./rbac-expand.js";import{getUserParamsFromCookies as nt}from"../web-server/auth.js";import{getDeeperGlobPattern as ot}from"./globs.js";import{EntitlementsProvider as st}from"../entitlements/entitlements-provider.js";const j=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],ct=new Set(["x-parsed-md-description","x-parsed-md-summary"]),at=new Set(Object.values(w).map(t=>S(t.split(":")[0])));function wt(t,e){const r=j.indexOf(t.toUpperCase()),n=j.indexOf(e.toUpperCase());return r>n?t:e}const P={};function F(t,e){if(!t?.content)return _;const r=t.content,{slug:n,fsPath:o}=e;if(!n&&!o)return _;const s=f=>{const E=`slug:${f}`,p=P[E]??O(f);P[E]=p;const A=`fsPath:${f}`,L=P[A]??O(z(f));return P[A]=L,!!(n&&p(n))||!!(o&&L(o))};if(ut(n||o||"")&&Object.keys(r).filter(p=>s(p)).length===0)return r[x]||_;const i=Object.keys(r).filter(f=>s(f));if(i.length==0)return _;const u=i.map(f=>O.scan(f,{tokens:!0,parts:!0}));let h=u[0];for(let f=1;f<u.length;f++)h=ot(h,u[f]);return r[h.input]}function N(t,e,r){const n=r?[...e,r]:e,o=[];for(const s of n)t[s]?o.push(t[s]):t[l]&&s!==r&&o.push(t[l]);return o.some(s=>s.toLowerCase()!=="none")}function Bt(t,e,r={},n=!1){if(n&&Object.keys(r).length===0)return e.isAuthenticated;const o=r.features?.[t];return o?N(o,e.teams):!0}function bt(t,e){return d(t,H,e.access?.rbac||{},e.access?.requiresLogin||!1)}function d(t,e={},r={},n=!1){if(t.slug&&typeof t.slug=="string"&&at.has(S(t.slug))||(t.slug===U||t.slug===k||t.slug===G)&&st.instance().canAccessFeature("mcp"))return!0;if(n&&Object.keys(r).length===0)return!!e.isAuthenticated;const o=q(r,e.teams||[]),s=t[T]||F(o,t[R]||{});return Object.keys(s||{}).length===0?!1:Object.keys(s).length===1&&s[l]&&s[l].toLowerCase()!=="none"?!0:N(s,e?.teams||[],e?.email)}function $t(t,e,r,n,o){if(!t.startsWith(I)&&!t.startsWith(g))return!0;if(o){const u={[T]:o.rbac,[R]:{slug:o.slug,fsPath:o.sourcePath}};return d(u,n,e,r)}const s=t.replace(new RegExp(`^${I}/`),"").replace(new RegExp(`^${g}/`),"").replace(new RegExp(`^${B}/`),""),a=s==="."?"":s,i={[R]:{slug:t,fsPath:a},slug:t};return d(i,n,e,r)}function Wt(t,e,r,n,o){if(!C(t,b))return[`/${v}`,`/${Y}`].includes(t)||[$,W].some(A=>C(t,A));const s=t.match(/\..{64}\.([A-Fa-f0-9]{8})\.[^.]+$/)?.[1];if(!s)return!0;const c=n[s];if(!c)return!0;const{base:a,ext:i}=y.parse(t),u=a.split(".")[0],h=i.split(".").join(""),E=c==="."?"":c,p={[R]:{slug:t,fsPath:y.posix.join(E,`${u}.${h}`)},slug:t};return d(p,o,e,r)}async function vt(t,e){const{isAuthenticated:r=!1,idpAccessToken:n,federatedAccessToken:o,federatedIdToken:s,...c}=await nt(t,e),{teams:a=[]}=c;let i;return r?i=a.filter(u=>u!==D):i=[D],{isAuthenticated:r,idpAccessToken:n,teams:i,claims:c}}function M(t,e,r={},n=!1){if(!t)return t;if(Array.isArray(t)){const o=[];for(const s of t){const c=M(s,e,r,n);c!==void 0&&o.push(c)}return o}if(typeof t=="object"){if(!d(t,e,r,n))return;let o=!1;const s={};for(const c in t){if(c===T||c===R)continue;if(ct.has(c)){s[c]=t[c];continue}const a=M(t[c],e,r,n);if(!t.link&&(c==="items"||c==="menu"&&t.type==="tab")&&Array.isArray(a)&&a.length===0&&t[c].length!==0){o=!0;continue}a!==void 0&&(s[c]=a),c==="paths"&&it(a)&&ft(a)}return o?void 0:s}return t}function Yt(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function Gt(t,e){if(!e)return;const r=e.content;if(!r)return e;const n=Object.entries(r).flatMap(([s,c])=>s===x?[[s,c]]:[[s,c]].concat(t.localeFolders.map(a=>[s.startsWith("/")?`/${a.toLocaleLowerCase()}${s}`:y.posix.join(t.localizationFolder,a,s),c]))),o=Object.fromEntries(n);return{...e,content:o}}async function Ht(t,e){if(!e)return{};const r={},n=new Set(t.scan().flatMap(({relativePath:o})=>{const{versionFolderPath:s}=K(o)||{},c=y.dirname(o);return s?[s,c]:c}));for(const o of n)r[Q(o)]=o;return r}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function it(t){return m(t)&&Object.keys(t).length>0}function ft(t){for(const e of Object.keys(t)){const r=t[e];m(r)&&Object.keys(r).length===0&&delete t[e]}}function ut(t){return t?t.split("/").filter(Boolean).some(r=>r.startsWith(".")):!1}const lt=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"platform"in t&&m(t.platform)||"features"in t&&m(t.features)||t.teamFolders&&t.teamNamePatterns)){const e=Object.values(t.content||{});if(e.length===0)return!0;if(e.every(m))return e.every(r=>Object.values(r).every(n=>typeof n=="string"))}return!1},zt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(lt(t))return mt(t);await V.panicOnContentError(`You are using an incorrect format of ${J("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},mt=t=>{const e={...t};if(e.content){const r={};for(const n in e.content)if(e.content[n]!==void 0){const o=S(n);r[o]=e.content[n]}e.content=r}return e};function Kt(t,e){const r=t.fsPath,n=t.slug,o=[],s=Z(e)&&(r||n)?et(e,[r,n].filter(X)):null;if(s){const a=e?.teamNamePatterns?.map(i=>i.replace("{teamPathSegment}",s.teamPathSegment).replace("{projectRole}","read"))??[];o.push(...a)}const c=F(s?{content:{...tt(e),...e.content}}:e,t);return o.push(...pt(c)),ht(e,o)}function pt(t){if(!t)return[];const e=[],r=l in t?{authenticated:t[l],anonymous:t[l]}:{};for(const[n,o]of Object.entries({...r,...t}))o.toLowerCase()!=="none"&&n!==l&&e.push(n);return e}function ht(t,e){return e.map(n=>rt(t,n)??{teamName:n}).map(n=>n.projectRole&&n.projectRole!=="READ"?n.teamName?.toLowerCase().replace(n.projectRole?.toLowerCase?.()??"","read")??"":n.teamName?.toLowerCase()??"")}export{j as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,Gt as applyL10nToRbacConfig,Wt as canAccessAsset,Bt as canAccessFeature,d as canAccessResource,$t as canDownloadApiDefinition,ht as expandTeamsForRead,pt as extractTeamsFromScopeItems,M as filterDataByAccessDeep,vt as getAuthDetailsFromCookies,wt as getHigherRole,Kt as getRbacTeamsListForResource,F as getScopeItemsForResource,N as hasScopeAccess,lt as isRbacConfigValid,bt as isResourcePubliclyAccessible,mt as normalizeRbacConfig,zt as parseRbacConfig,Yt as parseTeamClaimToArray,Ht as resolveDirectoryHashes};
1
+ import _ from"path";import O from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as T,REDOCLY_ROUTE_RBAC as E}from"@redocly/config";import{MCP_ROUTE as M,PUBLIC_MCP_ROUTE as k}from"@redocly/theme/core/constants/mcp";import{ServerRoutes as w}from"../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as S,PUBLIC_RBAC_SCOPE_ITEM as d,RBAC_ALL_OTHER_TEAMS as p,DEFAULT_RBAC_SCOPE as D,GRAPHQL_SPEC_SLUG as B}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as x,PUBLIC_API_DEFINITIONS_FOLDER as g,PUBLIC_ASSETS_FOLDER as b,RUNTIME_RESOURCES_DIR as $,SCORECARD_CLASSIC_FOLDER as W,SITEMAP_FILE_NAME as v,LLMS_TXT_FILE_NAME as Y}from"../constants/common.js";import{MCP_CREDENTIALS_ROUTE as G}from"../constants/mcp.js";import{ANONYMOUS_AUTH_DETAILS as H}from"../constants/rbac.js";import{removeTrailingSlash as L}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as z}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as K}from"../../utils/path/parse-path-versions.js";import{reporter as V}from"../tools/notifiers/reporter.js";import{bold as J}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as Q}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as X}from"../../utils/guards/is-truthy.js";import{isPathInFolder as C}from"../../utils/path/is-path-in-folder.js";import{canExpandConfig as Z,expandRbacConfig as q,getTeamFolderDefaults as tt,parseTeamFoldersTemplate as et,parseTeamNameTemplate as rt}from"./rbac-expand.js";import{getUserParamsFromCookies as nt}from"../web-server/auth.js";import{getDeeperGlobPattern as ot}from"./globs.js";import{hasScopeAccess as j}from"./rbac/has-scope-access.js";import{EntitlementsProvider as st}from"../entitlements/entitlements-provider.js";const N=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],ct=new Set(["x-parsed-md-description","x-parsed-md-summary"]),at="@api",it=new Set(Object.values(w).map(t=>L(t.split(":")[0])));function bt(t,e){const n=N.indexOf(t.toUpperCase()),r=N.indexOf(e.toUpperCase());return n>r?t:e}const P={};function F(t,e){if(!t?.content)return d;const n=t.content,{slug:r,fsPath:o}=e;if(!r&&!o)return d;const s=f=>{const R=`slug:${f}`,u=P[R]??O(f);P[R]=u;const y=`fsPath:${f}`,I=P[y]??O(z(f));return P[y]=I,!!(r&&u(r))||!!(o&&I(o))};if(mt(r||o||"")&&Object.keys(n).filter(u=>s(u)).length===0)return n[D]||d;const i=Object.keys(n).filter(f=>s(f));if(i.length==0)return d;const l=i.map(f=>O.scan(f,{tokens:!0,parts:!0}));let h=l[0];for(let f=1;f<l.length;f++)h=ot(h,l[f]);return n[h.input]}function $t(t,e){return A(t,H,e.access?.rbac||{},e.access?.requiresLogin||!1)}function Wt(t){const e={[D]:d,...t?.content};return Object.entries(e).some(([n,r])=>!n.split("/").includes(at)&&j(r,[S]))}function A(t,e={},n={},r=!1){if(t.slug&&typeof t.slug=="string"&&it.has(L(t.slug))||(t.slug===M||t.slug===k||t.slug===G)&&st.instance().canAccessFeature("mcp"))return!0;if(r&&Object.keys(n).length===0)return!!e.isAuthenticated;const o=q(n,e.teams||[]),s=t[T]||F(o,t[E]||{});return Object.keys(s||{}).length===0?!1:Object.keys(s).length===1&&s[p]&&s[p].toLowerCase()!=="none"?!0:j(s,e?.teams||[],e?.email)}function vt(t,e,n,r,o){if(!t.startsWith(g)&&!t.startsWith(x))return!0;if(o){const l={[T]:o.rbac,[E]:{slug:o.slug,fsPath:o.sourcePath}};return A(l,r,e,n)}const s=t.replace(new RegExp(`^${g}/`),"").replace(new RegExp(`^${x}/`),"").replace(new RegExp(`^${B}/`),""),a=s==="."?"":s,i={[E]:{slug:t,fsPath:a},slug:t};return A(i,r,e,n)}function Yt(t,e,n,r,o){if(!C(t,b))return[`/${v}`,`/${Y}`].includes(t)||[$,W].some(y=>C(t,y));const s=t.match(/\..{64}\.([A-Fa-f0-9]{8})\.[^.]+$/)?.[1];if(!s)return!0;const c=r[s];if(!c)return!0;const{base:a,ext:i}=_.parse(t),l=a.split(".")[0],h=i.split(".").join(""),R=c==="."?"":c,u={[E]:{slug:t,fsPath:_.posix.join(R,`${l}.${h}`)},slug:t};return A(u,o,e,n)}async function Gt(t,e){const{isAuthenticated:n=!1,idpAccessToken:r,federatedAccessToken:o,federatedIdToken:s,...c}=await nt(t,e),{teams:a=[]}=c;let i;return n?i=a.filter(l=>l!==S):i=[S],{isAuthenticated:n,idpAccessToken:r,teams:i,claims:c}}function U(t,e,n={},r=!1){if(!t)return t;if(Array.isArray(t)){const o=[];for(const s of t){const c=U(s,e,n,r);c!==void 0&&o.push(c)}return o}if(typeof t=="object"){if(!A(t,e,n,r))return;let o=!1;const s={};for(const c in t){if(c===T||c===E)continue;if(ct.has(c)){s[c]=t[c];continue}const a=U(t[c],e,n,r);if(!t.link&&(c==="items"||c==="menu"&&t.type==="tab")&&Array.isArray(a)&&a.length===0&&t[c].length!==0){o=!0;continue}a!==void 0&&(s[c]=a),c==="paths"&&ft(a)&&lt(a)}return o?void 0:s}return t}function Ht(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function zt(t,e){if(!e)return;const n=e.content;if(!n)return e;const r=Object.entries(n).flatMap(([s,c])=>s===D?[[s,c]]:[[s,c]].concat(t.localeFolders.map(a=>[s.startsWith("/")?`/${a.toLocaleLowerCase()}${s}`:_.posix.join(t.localizationFolder,a,s),c]))),o=Object.fromEntries(r);return{...e,content:o}}async function Kt(t,e){if(!e)return{};const n={},r=new Set(t.scan().flatMap(({relativePath:o})=>{const{versionFolderPath:s}=K(o)||{},c=_.dirname(o);return s?[s,c]:c}));for(const o of r)n[Q(o)]=o;return n}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ft(t){return m(t)&&Object.keys(t).length>0}function lt(t){for(const e of Object.keys(t)){const n=t[e];m(n)&&Object.keys(n).length===0&&delete t[e]}}function mt(t){return t?t.split("/").filter(Boolean).some(n=>n.startsWith(".")):!1}const ut=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"platform"in t&&m(t.platform)||"features"in t&&m(t.features)||t.teamFolders&&t.teamNamePatterns)){const e=Object.values(t.content||{});if(e.length===0)return!0;if(e.every(m))return e.every(n=>Object.values(n).every(r=>typeof r=="string"))}return!1},Vt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(ut(t))return pt(t);await V.panicOnContentError(`You are using an incorrect format of ${J("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},pt=t=>{const e={...t};if(e.content){const n={};for(const r in e.content)if(e.content[r]!==void 0){const o=L(r);n[o]=e.content[r]}e.content=n}return e};function Jt(t,e){const n=t.fsPath,r=t.slug,o=[],s=Z(e)&&(n||r)?et(e,[n,r].filter(X)):null;if(s){const a=e?.teamNamePatterns?.map(i=>i.replace("{teamPathSegment}",s.teamPathSegment).replace("{projectRole}","read"))??[];o.push(...a)}const c=F(s?{content:{...tt(e),...e.content}}:e,t);return o.push(...ht(c)),Rt(e,o)}function ht(t){if(!t)return[];const e=[],n=p in t?{authenticated:t[p],anonymous:t[p]}:{};for(const[r,o]of Object.entries({...n,...t}))o.toLowerCase()!=="none"&&r!==p&&e.push(r);return e}function Rt(t,e){return e.map(r=>rt(t,r)??{teamName:r}).map(r=>r.projectRole&&r.projectRole!=="READ"?r.teamName?.toLowerCase().replace(r.projectRole?.toLowerCase?.()??"","read")??"":r.teamName?.toLowerCase()??"")}export{N as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,zt as applyL10nToRbacConfig,Wt as areAnyPagesOpenToAnonymous,Yt as canAccessAsset,A as canAccessResource,vt as canDownloadApiDefinition,Rt as expandTeamsForRead,ht as extractTeamsFromScopeItems,U as filterDataByAccessDeep,Gt as getAuthDetailsFromCookies,bt as getHigherRole,Jt as getRbacTeamsListForResource,F as getScopeItemsForResource,ut as isRbacConfigValid,$t as isResourcePubliclyAccessible,pt as normalizeRbacConfig,Vt as parseRbacConfig,Ht as parseTeamClaimToArray,Kt as resolveDirectoryHashes};
@@ -1 +1 @@
1
- import{RbacFeatures as d}from"../../../constants/common.js";import{ASK_AI_API_URL as h,AI_ASSISTANT_ESCALATIONS_API_URL as l,AI_ASSISTANT_FEEDBACK_API_URL as T}from"../../constants/common.js";import{fetchWithClient as S}from"../../utils/fetch-with-client.js";import{canAccessFeature as m}from"../../utils/rbac.js";import{handleUnauthorizedApiRequest as I}from"../utils.js";import{isAiSearchEnabled as _}from"../../plugins/search/utils.js";import{createAssistantAnonymousToken as y}from"../../plugins/mcp/auth/assistant-anonymous-token.js";import{isMcpContentProtected as g}from"../../plugins/mcp/auth/auth-handlers.js";function E(e,i){const t=i.getConfig();return _(t)?m(d.AI_SEARCH,e.get("auth"),t.access?.rbac,t.access?.requiresLogin)?null:I(e):e.newResponse(null,403,{})}async function R(e,{mintsAnonymousMcpToken:i}){const t=e.get("auth"),r={"Content-Type":"application/json"},n=[];t.claims?.authCookie&&n.push(`authorization=${t.claims.authCookie}`),t.idpAccessToken&&n.push(`accessToken=${t.idpAccessToken}`),n.length>0&&(r.Cookie=n.join("; "));const s=e.req.header(p);s&&(r[p]=s);const a=e.req.header("Authorization");if(a)r.Authorization=a;else if(i&&n.length===0&&!s){const o=await y();o&&(r.Authorization=`Bearer ${o}`)}return r}const k="x-redocly-ai-assistant-origin",p="x-redocly-ai-assistant-identity",f="x-redocly-ai-assistant-identity-status";function C(e){const i=e.req.header("Origin");if(i)return i;const t=e.req.header("Referer");if(t)try{return new URL(t).origin}catch{}return new URL(e.req.url).origin}function u({store:e,apiUrl:i,successContentType:t="application/json",reachesMcp:r=!1}){return async n=>{if(!i)return n.newResponse(null,404);const s=E(n,e);if(s)return s;const a=r&&g(e),o=await R(n,{mintsAnonymousMcpToken:a});o[k]=C(n);const c=await S(i,{method:"POST",body:JSON.stringify(await n.req.json()),headers:o}),A=c.headers.get(f);return n.newResponse(c.body,c.status,{"Content-Type":c.ok?t:"application/json",...A?{[f]:A}:{}})}}function D(e){return u({store:e,apiUrl:h,successContentType:"text/event-stream",reachesMcp:!0})}function O(e){return u({store:e,apiUrl:l})}function P(e){return u({store:e,apiUrl:T})}export{f as AI_ASSISTANT_IDENTITY_STATUS_HEADER,O as aiAssistantEscalationsHandler,P as aiAssistantFeedbackHandler,D as askAiHandler};
1
+ import{RbacFeatures as p}from"../../../constants/common.js";import{ASK_AI_API_URL as h,AI_ASSISTANT_ESCALATIONS_API_URL as l,AI_ASSISTANT_FEEDBACK_API_URL as T}from"../../constants/common.js";import{fetchWithClient as m}from"../../utils/fetch-with-client.js";import{areAnyPagesOpenToAnonymous as S}from"../../utils/rbac.js";import{canAccessFeature as I}from"../../utils/rbac/can-access-feature.js";import{handleUnauthorizedApiRequest as _}from"../utils.js";import{isAiSearchEnabled as y}from"../../plugins/search/utils.js";import{createAssistantAnonymousToken as g}from"../../plugins/mcp/auth/assistant-anonymous-token.js";import{isMcpContentProtected as C}from"../../plugins/mcp/auth/auth-handlers.js";function E(e,r){const n=r.getConfig();if(!y(n))return e.newResponse(null,403,{});const o=e.get("auth"),t=n.access?.rbac;return!(!t?.features?.[p.AI_SEARCH]&&!o.isAuthenticated&&!e.req.header(u)&&!S(t))&&I(p.AI_SEARCH,o,t,n.access?.requiresLogin)?null:_(e)}async function R(e,{mintsAnonymousMcpToken:r}){const n=e.get("auth"),o={"Content-Type":"application/json"},t=[];n.claims?.authCookie&&t.push(`authorization=${n.claims.authCookie}`),n.idpAccessToken&&t.push(`accessToken=${n.idpAccessToken}`),t.length>0&&(o.Cookie=t.join("; "));const s=e.req.header(u);s&&(o[u]=s);const i=e.req.header("Authorization");if(i)o.Authorization=i;else if(r&&t.length===0&&!s){const a=await g();a&&(o.Authorization=`Bearer ${a}`)}return o}const k="x-redocly-ai-assistant-origin",u="x-redocly-ai-assistant-identity",f="x-redocly-ai-assistant-identity-status";function w(e){const r=e.req.header("Origin");if(r)return r;const n=e.req.header("Referer");if(n)try{return new URL(n).origin}catch{}return new URL(e.req.url).origin}function A({store:e,apiUrl:r,successContentType:n="application/json",reachesMcp:o=!1}){return async t=>{if(!r)return t.newResponse(null,404);const s=E(t,e);if(s)return s;const i=o&&C(e),a=await R(t,{mintsAnonymousMcpToken:i});a[k]=w(t);const c=await m(r,{method:"POST",body:JSON.stringify(await t.req.json()),headers:a}),d=c.headers.get(f);return t.newResponse(c.body,c.status,{"Content-Type":c.ok?n:"application/json",...d?{[f]:d}:{}})}}function D(e){return A({store:e,apiUrl:h,successContentType:"text/event-stream",reachesMcp:!0})}function j(e){return A({store:e,apiUrl:l})}function F(e){return A({store:e,apiUrl:T})}export{f as AI_ASSISTANT_IDENTITY_STATUS_HEADER,j as aiAssistantEscalationsHandler,F as aiAssistantFeedbackHandler,D as askAiHandler};
@@ -1 +1 @@
1
- import l from"@redocly/ajv";import{readStreamWithSizeLimit as p}from"../../../api-routes/helpers/read-stream-with-size-limit.js";import{ResponseSizeLimitError as u}from"../../../api-routes/errors/response-size-limit.js";const m=new l({allErrors:!0,strictSchema:!1,strictTypes:!1}),d={type:"object",properties:{redirect_uris:{type:"array",items:{type:"string",minLength:1},minItems:1},client_name:{type:"string",nullable:!0},grant_types:{type:"array",items:{type:"string"},nullable:!0},response_types:{type:"array",items:{type:"string"},nullable:!0},scope:{type:"string",nullable:!0},token_endpoint_auth_method:{type:"string",nullable:!0}},required:["redirect_uris"],additionalProperties:!0},o=m.compile(d),f=5e3,i=.0625,h=new Set(["127.0.0.1","localhost","[::1]"]);function y(e){return e.protocol==="http:"&&h.has(e.hostname)}function b(e,t){if(t.includes(e))return!0;const r=s(e);return r!==null&&t.some(n=>s(n)===r)}function s(e){const t=URL.parse(e);return!t||!y(t)?null:(t.port="",t.href)}function w(e){if(!e)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"}async function M(e){if(!w(e))throw new Error("client_id must be an https URL");const t=await fetch(e,{method:"GET",redirect:"error",headers:{Accept:"application/json"},signal:AbortSignal.timeout(f)});if(!t.ok)throw new Error(`Failed to fetch client metadata: HTTP ${t.status}`);const r=t.headers.get("content-type")||"";if(!/^application\/(.+\+)?json/i.test(r))throw new Error(`Unexpected content-type for client metadata: ${r}`);if(!t.body)throw new Error("Client metadata response has no body");const n=await p({stream:t.body,maxSizeMB:i,onSizeExceededErrorHandler:()=>{throw new u(`Client metadata exceeds maximum size of ${i*1024} KB`)}});let a;try{a=JSON.parse(n.toString("utf-8"))}catch(c){throw new Error(`Invalid JSON in client metadata: ${c.message}`)}return E(a)}function E(e){if(!o(e)){const t=o.errors?.[0],r=t?`${t.instancePath||"/"} ${t.message}`.trim():"Validation failed";throw new Error(`Invalid client metadata: ${r}`)}return e}export{M as fetchClientMetadataDocument,w as isClientMetadataDocumentUrl,y as isLoopbackRedirect,b as isRedirectUriRegistered};
1
+ import{isIP as m}from"node:net";import u from"@redocly/ajv";import{Agent as d}from"undici";import{readStreamWithSizeLimit as f}from"../../../api-routes/helpers/read-stream-with-size-limit.js";import{ResponseSizeLimitError as h}from"../../../api-routes/errors/response-size-limit.js";import{isBlockedIp as y}from"../../../web-server/utils/ssrf-blocklist.js";import{createSsrfSafeLookup as w}from"../../../web-server/utils/ssrf-safe-lookup.js";const S=new u({allErrors:!0,strictSchema:!1,strictTypes:!1}),g={type:"object",properties:{redirect_uris:{type:"array",items:{type:"string",minLength:1},minItems:1},client_name:{type:"string",nullable:!0},grant_types:{type:"array",items:{type:"string"},nullable:!0},response_types:{type:"array",items:{type:"string"},nullable:!0},scope:{type:"string",nullable:!0},token_endpoint_auth_method:{type:"string",nullable:!0}},required:["redirect_uris"],additionalProperties:!0},i=S.compile(g),E=5e3,s=.0625,_=new d({connect:{lookup:w()}}),b=new Set(["127.0.0.1","localhost","[::1]"]);function M(t){return t.protocol==="http:"&&b.has(t.hostname)}function P(t,e){if(e.includes(t))return!0;const n=c(t);return n!==null&&e.some(r=>c(r)===n)}function c(t){const e=URL.parse(t);return!e||!M(e)?null:(e.port="",e.href)}function L(t){if(!t)return!1;let e;try{e=new URL(t)}catch{return!1}return e.protocol==="https:"}async function z(t){if(!L(t))throw new Error("client_id must be an https URL");const e=new URL(t).hostname.replace(/^\[|\]$/g,"");if(m(e)!==0&&y(e))throw new Error("client_id must not be a private network address");const n={method:"GET",redirect:"error",headers:{Accept:"application/json"},signal:AbortSignal.timeout(E),dispatcher:_},r=await fetch(t,n);if(!r.ok)throw new Error(`Failed to fetch client metadata: HTTP ${r.status}`);const o=r.headers.get("content-type")||"";if(!/^application\/(.+\+)?json/i.test(o))throw new Error(`Unexpected content-type for client metadata: ${o}`);if(!r.body)throw new Error("Client metadata response has no body");const l=await f({stream:r.body,maxSizeMB:s,onSizeExceededErrorHandler:()=>{throw new h(`Client metadata exceeds maximum size of ${s*1024} KB`)}});let a;try{a=JSON.parse(l.toString("utf-8"))}catch(p){throw new Error(`Invalid JSON in client metadata: ${p.message}`)}return x(a)}function x(t){if(!i(t)){const e=i.errors?.[0],n=e?`${e.instancePath||"/"} ${e.message}`.trim():"Validation failed";throw new Error(`Invalid client metadata: ${n}`)}return t}export{z as fetchClientMetadataDocument,L as isClientMetadataDocumentUrl,M as isLoopbackRedirect,P as isRedirectUriRegistered};
@@ -1 +1 @@
1
- import{withPathPrefix as p}from"@redocly/theme/core/utils";import{SEMANTIC_SEARCH_API_URL as s}from"../../constants/common.js";import{fetchWithClient as d}from"../../utils/fetch-with-client.js";import{handleUnauthorizedApiRequest as h}from"../utils.js";function y(i){return async e=>{if(!s)return e.newResponse(null,404);const n=e.get("auth");if(i.getConfig().access?.requiresLogin&&!n.isAuthenticated)return h(e);const o={"Content-Type":"application/json"};n.idpAccessToken&&(o.Cookie=`accessToken=${n.idpAccessToken}`);const a=await e.req.json();try{const t=await d(s,{method:"POST",body:JSON.stringify(a),headers:o});if(t.ok){const u=(await t.json()).documents.map(r=>({...r,url:p(r.url)}));return e.json(u)}const c=await t.text();return e.newResponse(c,t.status,{"Content-Type":"application/json"})}catch(t){return e.json({error:"Failed to fetch semantic search results",details:String(t)},500)}}}export{y as semanticSearchHandler};
1
+ import{withPathPrefix as p}from"@redocly/theme/core/utils";import{SEMANTIC_SEARCH_API_URL as i}from"../../constants/common.js";import{fetchWithClient as d}from"../../utils/fetch-with-client.js";import{handleUnauthorizedApiRequest as f}from"../utils.js";function w(a){return async e=>{if(!i)return e.newResponse(null,404);const o=e.get("auth");if(a.getConfig().access?.requiresLogin&&!o.isAuthenticated)return f(e);const n={"Content-Type":"application/json"};o.idpAccessToken&&(n.Cookie=`accessToken=${o.idpAccessToken}`);const c=await e.req.json();try{const t=await d(i,{method:"POST",body:JSON.stringify(c),headers:n});if(t.ok){const r=await t.json();for(const s of r.documents)s.url=p(s.url);return e.json(r.documents)}const u=await t.text();return e.newResponse(u,t.status,{"Content-Type":"application/json"})}catch(t){return e.json({error:"Failed to fetch semantic search results",details:String(t)},500)}}}export{w as semanticSearchHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redocly/redoc-reef",
3
- "version": "0.141.0-next.12",
3
+ "version": "0.141.0-next.13",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "bin": {
@@ -33,14 +33,14 @@
33
33
  "@opentelemetry/sdk-trace-web": "2.8.0",
34
34
  "@opentelemetry/semantic-conventions": "1.40.0",
35
35
  "@redocly/ajv": "8.18.0",
36
- "@redocly/api-docs": "0.6.0-next.12",
36
+ "@redocly/api-docs": "0.6.0-next.13",
37
37
  "@redocly/config": "0.75.0",
38
38
  "@redocly/markdoc": "0.7.1",
39
39
  "@redocly/openapi-core": "2.78.0",
40
40
  "@redocly/portal-legacy-ui": "0.19.0",
41
41
  "@redocly/portal-plugin-mock-server": "0.26.0-next.4",
42
42
  "@redocly/realm-asyncapi-sdk": "0.18.0-next.1",
43
- "@redocly/theme": "0.73.0-next.8",
43
+ "@redocly/theme": "0.73.0-next.9",
44
44
  "@shikijs/transformers": "3.21.0",
45
45
  "@tanstack/react-query": "5.62.3",
46
46
  "@tanstack/react-table": "8.21.3",