@redocly/redoc-revel 0.141.0-next.2 → 0.141.0-next.21

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 (183) hide show
  1. package/CHANGELOG.md +357 -0
  2. package/dist/cli/develop.js +1 -1
  3. package/dist/cli/utils/react-pages-check.d.ts +11 -0
  4. package/dist/cli/utils/react-pages-check.js +1 -0
  5. package/dist/client/App.js +1 -1
  6. package/dist/client/app/Sidebar/useSidebarItems.js +1 -1
  7. package/dist/client/app/hooks/products/useProducts.d.ts +2 -0
  8. package/dist/client/app/hooks/useBanner.js +1 -1
  9. package/dist/client/app/hooks/useUserClaims.js +1 -1
  10. package/dist/client/app/markdoc/custom-components/openapi/openapi-code-sample.d.ts +2 -1
  11. package/dist/client/app/markdoc/custom-components/openapi/openapi-code-sample.js +1 -1
  12. package/dist/client/app/markdoc/custom-components/openapi/openapi-example.d.ts +1 -1
  13. package/dist/client/app/markdoc/custom-components/openapi/openapi-example.js +1 -1
  14. package/dist/client/app/markdoc/custom-components/openapi/openapi-response-sample.d.ts +2 -1
  15. package/dist/client/app/markdoc/custom-components/openapi/openapi-response-sample.js +1 -1
  16. package/dist/client/app/markdoc/custom-components/openapi/replay-openapi.d.ts +2 -1
  17. package/dist/client/app/markdoc/custom-components/openapi/replay-openapi.js +1 -1
  18. package/dist/client/app/markdoc/hooks/use-store.d.ts +12 -0
  19. package/dist/client/app/markdoc/hooks/use-store.js +1 -1
  20. package/dist/client/app/webmcp/tools/shared.d.ts +2 -3
  21. package/dist/client/app/webmcp/tools/shared.js +1 -1
  22. package/dist/client/providers/post-message/PostMessageConnection.d.ts +2 -2
  23. package/dist/client/providers/post-message/PostMessageProvider.d.ts +2 -2
  24. package/dist/client/providers/post-message/use-post-message.d.ts +1 -1
  25. package/dist/client/runtime/errors/page-async-component-error.d.ts +4 -0
  26. package/dist/client/runtime/errors/page-async-component-error.js +1 -0
  27. package/dist/client/runtime/loader.js +1 -1
  28. package/dist/client/types/index.d.ts +0 -1
  29. package/dist/compiled/@redocly/platform-utils/pii/index.mjs +1 -0
  30. package/dist/compiled/@redocly/platform-utils/pii/package.json +1 -0
  31. package/dist/constants/l10n/langs/ar.js +1 -1
  32. package/dist/constants/l10n/langs/de.js +1 -1
  33. package/dist/constants/l10n/langs/en.js +1 -1
  34. package/dist/constants/l10n/langs/es.js +1 -1
  35. package/dist/constants/l10n/langs/fr.js +1 -1
  36. package/dist/constants/l10n/langs/hi.js +1 -1
  37. package/dist/constants/l10n/langs/it.js +1 -1
  38. package/dist/constants/l10n/langs/ja.js +1 -1
  39. package/dist/constants/l10n/langs/ko.js +1 -1
  40. package/dist/constants/l10n/langs/pl.js +1 -1
  41. package/dist/constants/l10n/langs/pt-BR.js +1 -1
  42. package/dist/constants/l10n/langs/pt.js +1 -1
  43. package/dist/constants/l10n/langs/ru.js +1 -1
  44. package/dist/constants/l10n/langs/uk.js +1 -1
  45. package/dist/constants/l10n/langs/zh.js +1 -1
  46. package/dist/markdoc/helpers/get-resolved-sample-code-block.js +4 -4
  47. package/dist/markdoc/nodes/fence/index.js +1 -1
  48. package/dist/markdoc/nodes/table.js +1 -1
  49. package/dist/markdoc/tags/index.d.ts +6 -18
  50. package/dist/markdoc/tags/openapi-code-sample.js +1 -1
  51. package/dist/markdoc/tags/openapi-response-sample.js +1 -1
  52. package/dist/markdoc/tags/replay-openapi.js +1 -1
  53. package/dist/server/api-routes/run-api-routes-worker.js +1 -1
  54. package/dist/server/config/env-config.d.ts +0 -2
  55. package/dist/server/config/env-schema.d.ts +0 -1
  56. package/dist/server/config/env-schemas/feature-flags.d.ts +0 -1
  57. package/dist/server/config/env-schemas/feature-flags.js +1 -1
  58. package/dist/server/constants/assets.d.ts +3 -0
  59. package/dist/server/constants/assets.js +1 -0
  60. package/dist/server/constants/common.d.ts +0 -3
  61. package/dist/server/constants/common.js +1 -1
  62. package/dist/server/constants/config-schema.d.ts +12 -0
  63. package/dist/server/constants/config-schema.js +1 -0
  64. package/dist/server/constants/plugins/search.d.ts +0 -1
  65. package/dist/server/constants/plugins/search.js +1 -1
  66. package/dist/server/constants/project-plugins.d.ts +2 -0
  67. package/dist/server/constants/project-plugins.js +1 -0
  68. package/dist/server/constants/versions.d.ts +3 -0
  69. package/dist/server/constants/versions.js +1 -0
  70. package/dist/server/esbuild/esbuild.js +2 -2
  71. package/dist/server/esbuild/plugins/assets-resolver.js +1 -1
  72. package/dist/server/esbuild/plugins/dependency-resolver.js +1 -1
  73. package/dist/server/external-plugins/resolve-external-plugins.js +1 -1
  74. package/dist/server/fs/fs.js +1 -1
  75. package/dist/server/plugins/api-docs/index.js +1 -1
  76. package/dist/server/plugins/api-docs/options.js +1 -1
  77. package/dist/server/plugins/api-docs/search/create-indexer.d.ts +1 -4
  78. package/dist/server/plugins/api-docs/search/create-indexer.js +1 -1
  79. package/dist/server/plugins/api-docs/search/get-ai-search-documents.js +22 -22
  80. package/dist/server/plugins/api-docs/search/search-resolver.js +1 -1
  81. package/dist/server/plugins/api-docs/spec-download.api.js +1 -1
  82. package/dist/server/plugins/api-docs/utils/is-api-doc.js +1 -1
  83. package/dist/server/plugins/api-docs/utils/relative-path-to-base-slug.js +1 -1
  84. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.d.ts +1 -10
  85. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.js +1 -1
  86. package/dist/server/plugins/config-parser/loaders/index.d.ts +1 -1
  87. package/dist/server/plugins/config-parser/loaders/redocly-config-loader.js +1 -1
  88. package/dist/server/plugins/config-parser/loaders/utils/calculate-content-slugs.d.ts +32 -0
  89. package/dist/server/plugins/config-parser/loaders/utils/calculate-content-slugs.js +1 -0
  90. package/dist/server/plugins/config-parser/loaders/versions-config-loader.d.ts +0 -2
  91. package/dist/server/plugins/config-parser/loaders/versions-config-loader.js +1 -1
  92. package/dist/server/plugins/create-slugify.d.ts +1 -1
  93. package/dist/server/plugins/create-slugify.js +1 -1
  94. package/dist/server/plugins/default-theme/resolve-products-config.d.ts +1 -0
  95. package/dist/server/plugins/default-theme/resolve-products-config.js +1 -1
  96. package/dist/server/plugins/get-reserved-routes.js +1 -1
  97. package/dist/server/plugins/lifecycle.js +1 -1
  98. package/dist/server/plugins/markdown/attribute-resolvers/helpers/load-openapi-bundle.d.ts +1 -0
  99. package/dist/server/plugins/markdown/attribute-resolvers/helpers/load-openapi-bundle.js +1 -1
  100. package/dist/server/plugins/markdown/attribute-resolvers/index.js +1 -1
  101. package/dist/server/plugins/markdown/attribute-resolvers/resolve-link.js +1 -1
  102. package/dist/server/plugins/markdown/attribute-resolvers/resolve-openapi-code-samples.js +1 -1
  103. package/dist/server/plugins/markdown/attribute-resolvers/resolve-openapi-operation.d.ts +10 -0
  104. package/dist/server/plugins/markdown/attribute-resolvers/resolve-openapi-operation.js +1 -0
  105. package/dist/server/plugins/markdown/compiler.js +1 -1
  106. package/dist/server/plugins/markdown/markdoc/markdoc-options.d.ts +1 -1
  107. package/dist/server/plugins/markdown/markdoc/markdoc-options.js +1 -1
  108. package/dist/server/plugins/markdown/runtime-transform.js +1 -1
  109. package/dist/server/plugins/markdown/utils/resolve-markdown-template.js +1 -1
  110. package/dist/server/plugins/mcp/codemode/tools/execute-schema.js +1 -1
  111. package/dist/server/plugins/mcp/codemode/tools/manage-credentials.js +2 -2
  112. package/dist/server/plugins/mcp/constants.d.ts +2 -2
  113. package/dist/server/plugins/mcp/constants.js +1 -1
  114. package/dist/server/plugins/mcp/docs-mcp/tools/core/create-anonymous-session.d.ts +1 -1
  115. package/dist/server/plugins/mcp/docs-mcp/tools/core/search.js +2 -2
  116. package/dist/server/plugins/mcp/docs-mcp/tools/index.d.ts +1 -1
  117. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/utils.d.ts +2 -2
  118. package/dist/server/plugins/mcp/gateway-mcp/subject.d.ts +2 -2
  119. package/dist/server/plugins/mcp/gateway-mcp/subject.js +1 -1
  120. package/dist/server/plugins/mcp/handlers/docs-mcp-handler.js +1 -1
  121. package/dist/server/plugins/mcp/utils/route-reservation.d.ts +9 -0
  122. package/dist/server/plugins/mcp/utils/route-reservation.js +1 -0
  123. package/dist/server/plugins/nav-utils.js +1 -1
  124. package/dist/server/plugins/pages/validators/validate-react-pages.d.ts +8 -1
  125. package/dist/server/plugins/pages/validators/validate-react-pages.js +1 -1
  126. package/dist/server/plugins/search/ai-indexer/prepare-semantic-documents.js +1 -1
  127. package/dist/server/plugins/search/engines/flexsearch/search-index.js +1 -1
  128. package/dist/server/plugins/search/engines/typesense/index.js +1 -1
  129. package/dist/server/plugins/search/llmstxt/create-llms-txt-generator.js +1 -1
  130. package/dist/server/plugins/search/llmstxt/index.js +4 -4
  131. package/dist/server/plugins/utils.d.ts +0 -4
  132. package/dist/server/plugins/utils.js +1 -1
  133. package/dist/server/ssr/index.js +1 -1
  134. package/dist/server/ssr/server-side-props/get-default-static-props.d.ts +1 -0
  135. package/dist/server/ssr/utils.js +11 -9
  136. package/dist/server/store.d.ts +2 -1
  137. package/dist/server/store.js +1 -1
  138. package/dist/server/tools/notifiers/formatter.js +1 -1
  139. package/dist/server/types/plugins/common.d.ts +2 -0
  140. package/dist/server/types/web-server.d.ts +5 -0
  141. package/dist/server/utils/content/parse-base-name.d.ts +15 -0
  142. package/dist/server/utils/content/parse-base-name.js +1 -0
  143. package/dist/server/utils/crypto/sha-dir-path-short.js +1 -1
  144. package/dist/server/utils/errors.d.ts +2 -1
  145. package/dist/server/utils/errors.js +1 -1
  146. package/dist/server/utils/llmstxt/resolve-llms-txt-md.d.ts +5 -0
  147. package/dist/server/utils/llmstxt/resolve-llms-txt-md.js +1 -1
  148. package/dist/server/utils/product.d.ts +1 -0
  149. package/dist/server/utils/rbac/can-access-feature.d.ts +5 -0
  150. package/dist/server/utils/rbac/can-access-feature.js +1 -0
  151. package/dist/server/utils/rbac/can-anonymous-access-mcp-feature.js +1 -1
  152. package/dist/server/utils/rbac/has-scope-access.d.ts +3 -0
  153. package/dist/server/utils/rbac/has-scope-access.js +1 -0
  154. package/dist/server/utils/rbac.d.ts +19 -11
  155. package/dist/server/utils/rbac.js +1 -1
  156. package/dist/server/web-server/auth.js +3 -3
  157. package/dist/server/web-server/routes/ask-ai.js +1 -1
  158. package/dist/server/web-server/routes/dynamic-route.js +1 -1
  159. package/dist/server/web-server/routes/error.js +1 -1
  160. package/dist/server/web-server/routes/index.js +1 -1
  161. package/dist/server/web-server/routes/mcp-routes/mcp-client-metadata.js +1 -1
  162. package/dist/server/web-server/routes/mcp-routes/mcp-oauth.d.ts +0 -1
  163. package/dist/server/web-server/routes/mcp-routes/mcp-oauth.js +1 -1
  164. package/dist/server/web-server/routes/page-data.d.ts +2 -1
  165. package/dist/server/web-server/routes/page-data.js +1 -1
  166. package/dist/server/web-server/routes/semantic-search.js +1 -1
  167. package/dist/server/web-server/utils.d.ts +1 -1
  168. package/dist/server/web-server/utils.js +1 -1
  169. package/dist/server/workers/worker-config.js +1 -1
  170. package/dist/utils/l10n/build-i18n-config.js +1 -1
  171. package/package.json +13 -11
  172. package/dist/client/app/ReviewComments/ReviewComments.d.ts +0 -4
  173. package/dist/client/app/ReviewComments/ReviewComments.js +0 -7
  174. package/dist/client/types/post-message.d.ts +0 -68
  175. package/dist/client/types/post-message.js +0 -0
  176. package/dist/compiled/@redocly/pii/index.mjs +0 -1
  177. package/dist/compiled/@redocly/pii/package.json +0 -1
  178. package/dist/server/utils/llmstxt/get-llms-txt-md-path-by-slug.d.ts +0 -19
  179. package/dist/server/utils/llmstxt/get-llms-txt-md-path-by-slug.js +0 -1
  180. package/dist/server/utils/search/highlight-text-for-search.d.ts +0 -3
  181. package/dist/server/utils/search/highlight-text-for-search.js +0 -1
  182. package/dist/server/utils/search/text-match.d.ts +0 -6
  183. package/dist/server/utils/search/text-match.js +0 -1
@@ -1,13 +1,13 @@
1
- import d from"picomatch";import{dirname as T,resolve as $}from"node:path";import{access as x,readFile as E,constants as F}from"fs/promises";import{removeTrailingSlash as w}from"../../../../utils/url/remove-trailing-slash.js";import{logger as g}from"../../../tools/notifiers/logger.js";import{withPathPrefix as U}from"@redocly/theme/core/utils";import{envConfig as y}from"../../../config/env-config.js";import{getLlmsTxtMdPathBySlug as I}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";const a="llms.txt",u="Table of contents";async function v(e,i,n={title:a,description:void 0},r){if(!i)return{title:n.title||a,description:n.description,details:void 0,sections:[{title:u,description:void 0,llmstxts:e}]};const s=i.title||n.title||a,l=i.description||n.description,t=await D(i,r),o=i.sections?.map(c=>{const{title:f,description:h,excludeFiles:m,includeFiles:L}=c,P=p(e,{excludeFiles:m,includeFiles:L});return{title:f,description:h,llmstxts:P}});return{title:s,description:l,details:t,sections:o||[{title:u,description:void 0,llmstxts:p(e,{includeFiles:["**/*"],excludeFiles:[]})}]}}async function D(e,i){const n=await i.getConfig();if(e?.details?.path&&n.configPath)try{const r=i.fs.getFileInfo(n.configPath);if(!r)throw new Error(`Config file ${n.configPath} not found`);const s=$(i.fs.cwd,T(r.relativePath),e.details.path);return await x(s,F.R_OK),E(s,"utf-8")}catch{throw new Error(`${e.details.path} is not accessible`)}if(e?.details?.content)return e.details.content}function p(e,i){const{excludeFiles:n,includeFiles:r}=i,s=n?.map(t=>d(t)),l=r?.map(t=>d(t));return e.filter(t=>s?.some(c=>c(t.fsPath))?!1:l?.some(c=>c(t.fsPath)))}async function b(e,i,n={title:a,description:void 0,siteUrl:void 0},r){const s=await v(e,i,n,r),l=n.siteUrl,t=[`# ${s.title}
1
+ import d from"picomatch";import{dirname as T,resolve as $}from"node:path";import{access as w,readFile as x,constants as E}from"fs/promises";import{removeTrailingSlash as F}from"../../../../utils/url/remove-trailing-slash.js";import{logger as U}from"../../../tools/notifiers/logger.js";import{getMarkdownCopyPath as g,withPathPrefix as y}from"@redocly/theme/core/utils";import{envConfig as I}from"../../../config/env-config.js";const a="llms.txt",u="Table of contents";async function v(e,i,n={title:a,description:void 0},r){if(!i)return{title:n.title||a,description:n.description,details:void 0,sections:[{title:u,description:void 0,llmstxts:e}]};const s=i.title||n.title||a,l=i.description||n.description,t=await D(i,r),o=i.sections?.map(c=>{const{title:f,description:h,excludeFiles:m,includeFiles:L}=c,P=p(e,{excludeFiles:m,includeFiles:L});return{title:f,description:h,llmstxts:P}});return{title:s,description:l,details:t,sections:o||[{title:u,description:void 0,llmstxts:p(e,{includeFiles:["**/*"],excludeFiles:[]})}]}}async function D(e,i){const n=await i.getConfig();if(e?.details?.path&&n.configPath)try{const r=i.fs.getFileInfo(n.configPath);if(!r)throw new Error(`Config file ${n.configPath} not found`);const s=$(i.fs.cwd,T(r.relativePath),e.details.path);return await w(s,E.R_OK),x(s,"utf-8")}catch{throw new Error(`${e.details.path} is not accessible`)}if(e?.details?.content)return e.details.content}function p(e,i){const{excludeFiles:n,includeFiles:r}=i,s=n?.map(t=>d(t)),l=r?.map(t=>d(t));return e.filter(t=>s?.some(c=>c(t.fsPath))?!1:l?.some(c=>c(t.fsPath)))}async function b(e,i,n={title:a,description:void 0,siteUrl:void 0},r){const s=await v(e,i,n,r),l=n.siteUrl,t=[`# ${s.title}
2
2
 
3
3
  `];return s.description&&t.push(`> ${s.description}
4
4
 
5
5
  `),s.details&&t.push(`${s.details}
6
6
 
7
- `),s.sections.forEach(o=>{if(!o.llmstxts.length){g.warn(`llms.txt: No links found for section "${o.title}". Please check the includeFiles/excludeFiles patterns.`);return}t.push(`## ${o.title}
7
+ `),s.sections.forEach(o=>{if(!o.llmstxts.length){U.warn(`llms.txt: No links found for section "${o.title}". Please check the includeFiles/excludeFiles patterns.`);return}t.push(`## ${o.title}
8
8
  `),o.description?t.push(`${o.description.replace(/(?<!\n)\n+$/,"")}
9
9
 
10
10
  `):t.push(`
11
- `),o.llmstxts.forEach(c=>{t.push(` - ${M({title:c.title,description:c.description,slug:I(c.slug),siteUrl:l})}`)}),t.push(`
12
- `)}),t.join("")}function M({title:e,description:i,slug:n,siteUrl:r}){const l=`${w(r?.trim()||y.REDOCLY_PUBLIC_URL||"")}${encodeURI(U(n))}`,t=i?.replace(/\s+/g," ").trim();return`[${e}](${l})${t?`: ${t}`:""}
11
+ `),o.llmstxts.forEach(c=>{t.push(` - ${M({title:c.title,description:c.description,slug:g(c.slug),siteUrl:l})}`)}),t.push(`
12
+ `)}),t.join("")}function M({title:e,description:i,slug:n,siteUrl:r}){const l=`${F(r?.trim()||I.REDOCLY_PUBLIC_URL||"")}${encodeURI(y(n))}`,t=i?.replace(/\s+/g," ").trim();return`[${e}](${l})${t?`: ${t}`:""}
13
13
  `}function j(e){if(e?.details?.path&&e?.details?.content)throw new Error('"details.path" and "details.content" are mutually exclusive. Please use only one of them.')}export{b as generateLLMsTxt,M as llmsTxtLink,j as validateLLMsTxtConfig};
@@ -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};
@@ -1 +1 @@
1
- import{withPathPrefix as O}from"@redocly/theme/core/utils";import{SSR_RENDER_MODE as y}from"../constants/common.js";import{logger as b}from"../tools/notifiers/logger.js";import{canAccessResource as L,filterDataByAccessDeep as d,isResourcePubliclyAccessible as _}from"../utils/rbac.js";import{readSharedData as x}from"../utils/index.js";import{render as C}from"./render.js";import{getServerProps as T}from"./server-side-props/get-server-props.js";import{ssrWorkers as $,SSR_WORKER_KEY as j}from"../workers/ssr-worker-pool.js";async function G(e,s,a,r,o,c=!1){const w=b.startTiming(),E=r.routesSharedData.get(e.slug)||{},S=s.sharedDataIds||{},m={...E,...S},{isAuthenticated:g,teams:u,claims:{name:q,picture:I,email:f}}=a?.get("auth")||{claims:{}},t={isAuthenticated:g,email:f,teams:u},R=Object.fromEntries(await Promise.all(Object.entries(m).map(async([H,D])=>[D,await x(D,r.outdir)]))),P=d(R,t,r.config.access?.rbac,r.config.access?.requiresLogin),v=d(r.globalData,t,r.config.access?.rbac,r.config.access?.requiresLogin),p=L(e,t,r.config.access?.rbac,r.config.access?.requiresLogin),A=!!r.compilationErrors?.length?{templateId:"compilation-error",props:{compilationErrors:r.compilationErrors},sharedDataIds:{}}:null,h={page:{templateId:e.templateId,isPublic:_(e,r.config),slug:O(e.slug),versions:d(e.versions,t,r.config.access?.rbac,r.config.access?.requiresLogin),props:s,sharedDataIds:p?m:{},product:e.product,request:{search:a?.req.raw.context.url?.search||"",url:a?.req.raw.context.url?.href||""},userInfo:{isAuthenticated:g,name:q,picture:I,email:f,teams:u},...A},store:{globalData:v,config:r.config,ssr:r.ssr,hasSitemap:r.hasSitemap},sharedData:p?P:{},serverOutDir:r.serverOutDir,outdir:r.outdir,ssrHref:k(a),userAgent:a?.req.raw.headers.get("user-agent")||"",telemetry:o,omitSuspense:c};let i,n,l;return y==="worker"?{html:i,statusCode:n,error:l}=await $.exec(j,[h]):{html:i,statusCode:n,error:l}=await C(h),b.verboseTime(w,`Page rendered ${e.slug}`),{html:i,props:s,statusCode:n,error:l}}function k(e){const s=e?.req.raw.url;if(!s)return"";const a=new URL(s),r=e?.req.raw.headers,o=r?.get("x-forwarded-proto")||a.protocol.replace(":",""),c=r?.get("x-forwarded-host")||a.host;return`${o}://${c}`}export{T as getServerProps,G as renderPage};
1
+ import{withPathPrefix as y}from"@redocly/theme/core/utils";import{SSR_RENDER_MODE as _}from"../constants/common.js";import{logger as S}from"../tools/notifiers/logger.js";import{canAccessResource as b,filterDataByAccessDeep as g,isResourcePubliclyAccessible as x}from"../utils/rbac.js";import{readSharedData as C}from"../utils/index.js";import{render as T}from"./render.js";import{getServerProps as $}from"./server-side-props/get-server-props.js";import{ssrWorkers as j,SSR_WORKER_KEY as k}from"../workers/ssr-worker-pool.js";async function J(r,s,a,e,o,i=!1){const w=S.startTiming(),E=e.routesSharedData.get(r.slug)||{},R=s.sharedDataIds||{},u={...E,...R},{isAuthenticated:m,teams:f,claims:{name:q,picture:I,email:h}}=a?.get("auth")||{claims:{}},t={isAuthenticated:m,email:h,teams:f},p=b(r,t,e.config.access?.rbac,e.config.access?.requiresLogin),P=p&&b({},t,e.config.access?.rbac,e.config.access?.requiresLogin)?await Promise.all(Object.values(u).map(async c=>{const O=g(await C(c,e.outdir),t,e.config.access?.rbac,e.config.access?.requiresLogin);return[c,O]})):[],v=Object.fromEntries(P.filter(([,c])=>c!==void 0)),A=g(e.globalData,t,e.config.access?.rbac,e.config.access?.requiresLogin),L=!!e.compilationErrors?.length?{templateId:"compilation-error",props:{compilationErrors:e.compilationErrors},sharedDataIds:{}}:null,D={page:{templateId:r.templateId,isPublic:x(r,e.config),slug:y(r.slug),versions:g(r.versions,t,e.config.access?.rbac,e.config.access?.requiresLogin),props:s,sharedDataIds:p?u:{},product:r.product,request:{search:a?.req.raw.context.url?.search||"",url:a?.req.raw.context.url?.href||""},userInfo:{isAuthenticated:m,name:q,picture:I,email:h,teams:f},...L},store:{globalData:A,config:e.config,ssr:e.ssr,hasSitemap:e.hasSitemap},sharedData:v,serverOutDir:e.serverOutDir,outdir:e.outdir,ssrHref:B(a),userAgent:a?.req.raw.headers.get("user-agent")||"",telemetry:o,omitSuspense:i};let n,l,d;return _==="worker"?{html:n,statusCode:l,error:d}=await j.exec(k,[D]):{html:n,statusCode:l,error:d}=await T(D),S.verboseTime(w,`Page rendered ${r.slug}`),{html:n,props:s,statusCode:l,error:d}}function B(r){const s=r?.req.raw.url;if(!s)return"";const a=new URL(s),e=r?.req.raw.headers,o=e?.get("x-forwarded-proto")||a.protocol.replace(":",""),i=e?.get("x-forwarded-host")||a.host;return`${o}://${i}`}export{$ as getServerProps,J as renderPage};
@@ -5,6 +5,7 @@ export declare function getDefaultStaticProps({ staticData, variables, }: {
5
5
  }): {
6
6
  metadata?: Record<string, unknown>;
7
7
  seo?: import("@redocly/config").SeoConfig;
8
+ markdownUrl?: string;
8
9
  sharedDataIds?: Record<string, string>;
9
10
  frontmatter?: Omit<import("@redocly/config").PageProps, 'frontmatter'> & {
10
11
  settings?: any;
@@ -1,21 +1,23 @@
1
- import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../utils/url/remove-trailing-slash.js";import{slash as f}from"../../utils/path/slash.js";import{getClientPageDataUrl as h}from"../../utils/url/get-client-page-data-url.js";import{getSharedDataFetchUrl as g}from"../../utils/url/get-shared-data-fetch-url.js";import{DEFAULT_COLOR_MODES as l}from"@redocly/theme/core/constants";import{envConfig as m}from"../config/env-config.js";function q(t){const o=t?.colorMode,{modes:e=[l.LIGHT,l.DARK],hide:r,ignoreDetection:s}=o||{},a=e&&`'${e[0]}'`,n=e?.[0],d=e?.some(c=>c===n)?`'${n}'`:void 0;return r||!a?"":`
1
+ import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../utils/url/remove-trailing-slash.js";import{slash as f}from"../../utils/path/slash.js";import{getClientPageDataUrl as h}from"../../utils/url/get-client-page-data-url.js";import{getSharedDataFetchUrl as g}from"../../utils/url/get-shared-data-fetch-url.js";import{DEFAULT_COLOR_MODES as l}from"@redocly/theme/core/constants";import{envConfig as m}from"../config/env-config.js";function q(t){const o=t?.colorMode,{modes:e=[l.LIGHT,l.DARK],hide:r,ignoreDetection:n}=o||{},a=e&&`'${e[0]}'`,s=e?.[0],d=e?.some(i=>i===s)?`'${s}'`:void 0;return r||!a?"":`
2
2
  <script>
3
3
  if(window&&document.documentElement)
4
4
  {
5
5
  const q=new URLSearchParams(window.location.search).get("colorSchema");
6
- const e=q || window.localStorage.getItem("colorSchema");
6
+ let s;
7
+ try { s=window.localStorage.getItem("colorSchema"); } catch(_) {}
8
+ const e=q || s;
7
9
  if(e) {
8
- const modeToSet = [${e.map(c=>`'${c}'`)}].some((mode) => mode === e) ? e : 'light';
9
- ${i("modeToSet",e)}
10
+ const modeToSet = [${e.map(i=>`'${i}'`)}].some((mode) => mode === e) ? e : 'light';
11
+ ${c("modeToSet",e)}
10
12
  } else {
11
13
  if (window.matchMedia) {
12
- ${S(s,d,a,e)}
14
+ ${S(n,d,a,e)}
13
15
  } else {
14
- ${i(a,e)}
16
+ ${c(a,e)}
15
17
  }
16
18
  }
17
19
  }
18
- </script>`}function S(t,o,e,r=["light","dark"]){return t?o?i(o,r):e?i(e,r):"return":$(o,r)}function i(t=`'${l.LIGHT}'`,o=["light","dark"]){return`(function() {
20
+ </script>`}function S(t,o,e,r=["light","dark"]){return t?o?c(o,r):e?c(e,r):"return":$(o,r)}function c(t=`'${l.LIGHT}'`,o=["light","dark"]){return`(function() {
19
21
  var root = document.documentElement;
20
22
  var modes = [${o.map(r=>`'${r}'`).join(", ")}];
21
23
  var value = ${t};
@@ -23,7 +25,7 @@ import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../u
23
25
  root.classList.remove(className);
24
26
  });
25
27
  root.classList.add(value);
26
- })();`}function $(t,o=["light","dark"]){const e=o.map(s=>`'${s}'`).join(", "),r=t?`root.classList.add(${t});`:"";return`(function() {
28
+ })();`}function $(t,o=["light","dark"]){const e=o.map(n=>`'${n}'`).join(", "),r=t?`root.classList.add(${t});`:"";return`(function() {
27
29
  var root = document.documentElement;
28
30
  var modes = [${e}];
29
31
  modes.forEach(function(className) {
@@ -36,4 +38,4 @@ import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../u
36
38
  }${r?` else {
37
39
  ${r}
38
40
  }`:""}
39
- })();`}async function T(t){try{return m.isRuntimeMode?await import("@portal/server-props"):await import(u(`${f(t)}/server-props-entry.js`)+"?"+new Date)}catch{return{}}}function j(t){const o=t.split("/").map(encodeURIComponent).join("/"),e=o==="/"?o:p(o);return`<link rel="preload" as="fetch" crossorigin="anonymous" href="${h(e)}" />`}function x(t={}){const o=new Set;for(const e of Object.values(t))e&&o.add(g(e,m.isDevelopMode));return[...o].map(e=>`<link rel="preload" as="fetch" crossorigin="anonymous" href="${w(e)}" />`)}function w(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}const y=(t,o)=>{if(!o)return{params:[],queries:{}};const e=t.slug||"",s=o.req.path.split(e.endsWith("/")?e:`${e}/`)[1]||"",a=o.req.query(),n=s.replace("data.json","");return!n||n==="/"?{params:[],queries:a}:{params:n.split("/").filter(Boolean),queries:a}};export{q as detectColorSchemaScript,j as generatePreloadPageData,x as generatePreloadSharedData,y as getPathParams,T as importServerProps};
41
+ })();`}async function T(t){try{return m.isRuntimeMode?await import("@portal/server-props"):await import(u(`${f(t)}/server-props-entry.js`)+"?"+new Date)}catch{return{}}}function y(t){const o=t.split("/").map(encodeURIComponent).join("/"),e=o==="/"?o:p(o);return`<link rel="preload" as="fetch" crossorigin="anonymous" href="${h(e)}" />`}function j(t={}){const o=new Set;for(const e of Object.values(t))e&&o.add(g(e,m.isDevelopMode));return[...o].map(e=>`<link rel="preload" as="fetch" crossorigin="anonymous" href="${w(e)}" />`)}function w(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}const x=(t,o)=>{if(!o)return{params:[],queries:{}};const e=t.slug||"",n=o.req.path.split(e.endsWith("/")?e:`${e}/`)[1]||"",a=o.req.query(),s=n.replace("data.json","");return!s||s==="/"?{params:[],queries:a}:{params:s.split("/").filter(Boolean),queries:a}};export{q as detectColorSchemaScript,y as generatePreloadPageData,j as generatePreloadSharedData,x as getPathParams,T as importServerProps};
@@ -84,7 +84,8 @@ export declare class Store {
84
84
  finishEsbuildRun(): void;
85
85
  markRequestHandlersEntryOutdated(): void;
86
86
  noteRequestHandlersEntryBuildStart(): void;
87
- markRequestHandlersEntryUpdated(): void;
87
+ /** Returns false when the handlers changed after the server build started, so one more build is needed. */
88
+ markRequestHandlersEntryUpdated(): boolean;
88
89
  get contentDir(): string;
89
90
  markUserCodeReady(): void;
90
91
  reloadMarkdocOptions(): Promise<void>;
@@ -1 +1 @@
1
- import T from"@redocly/markdoc";import{writeFileSync as w}from"node:fs";import{readFile as R}from"node:fs/promises";import{join as g}from"node:path";import{parseAndResolveMarkdoc as M}from"./plugins/markdown/compiler.js";import{getPathnameForLocale as k}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../constants/common.js";import{DEFAULT_TITLE as F,MARKDOC_PARTIALS_DATA_KEY as y,MARKDOC_PARTIALS_DEPS_KEY as L}from"./constants/common.js";import{isObject as H}from"../utils/guards/is-object.js";import{mapObject as N}from"../utils/object/map-object.js";import{getValueDeep as S}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as G}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as d}from"../utils/path/normalize-route-slug.js";import{isLocalLink as v}from"../utils/path/is-local-link.js";import{reporter as E}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as _}from"./utils/crypto/sha1.js";import{FileNotFoundError as B}from"./utils/fs.js";import{resolveAssetPath as I}from"./utils/resolve-asset-path.js";import{envConfig as j,setEnv as V}from"./config/env-config.js";import{KvService as q}from"./persistence/kv/services/kv-service.js";import{SandboxContext as J}from"./utils/sandbox-context.js";import{isAllowedEnv as U}from"./utils/envs/get-api-route-allowed-env-variables.js";import{ensureDir as x,writeSharedData as K}from"./utils/index.js";import{renderComponents as $}from"./ssr/render.js";import{readStaticData as W,writeStaticData as z}from"./utils/static-data.js";import{getMarkdocOptions as Y}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as Z}from"./entitlements/entitlements-provider.js";import{getPlanDeniedMarkdocTags as Q}from"./entitlements/plan-denied-markdoc-tags.js";import{isRouteReserved as X}from"./plugins/get-reserved-routes.js";import{isL10nPath as ee}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as te}from"./utils/globs.js";import{createDefaultStoreConfig as se,resolveConfigEntries as re,resolveStoreConfig as oe}from"./store-config.js";import{findRedirect as ae}from"./utils/redirects/find-redirect.js";import{followRedirectChain as ie}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as ne}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as le}from"../cli/telemetry/helpers/trace-step.js";const P={routesBySlug:"map",staticFilePaths:"object",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map",devLogin:"object"},C="store.json",A="store-config.json",b="PLAN_GATES",ce=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],We="userDefinedApiFunctions";class D{routesBySlug=new Map;routeAliases=new Map;staticFilePaths={};replacedEnvVars={};unsetEnvVars=new Set;lifecycleContext;newRoutes=[];#t={};routesByFsPath=new Map;apiRoutes=[];middleware=[];routesSharedData=new Map;sharedDataDeps=new Map;sharedDataMarkdocComponents=new Map;routesDynamicComponents=new Map;routesPartials=new Map;ssr={preBodyTags:[],postBodyTags:[],headTags:[]};searchFacets=new Map;searchEngine;templates=new Map;browserPlugins=new Set;apiRoutesRequestHandlers=new Map;mcpToolHandlers=new Map;skills=new Map;serverPropsGetters=new Map;pagePropsGetters=new Map;listeners=new Map;globalData={};devLogin=!1;#a=void 0;#i={};config=se();configFile;#n;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#l;userCodeReady;#s=Promise.resolve();#c;#d=Promise.resolve();#h;#u=Promise.resolve();#f;#e=!1;#r=0;#p=0;#o=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:r}){this.#n=t,this.outdir=e,this.serverMode=s,this.serverOutDir=r,J.register({serverOutDir:r,readRoots:[e,process.cwd()]}),this.userCodeReady=new Promise(o=>{this.#l=o})}on(e,t){const s=this.listeners.get(e);s?s.add(t):this.listeners.set(e,new Set([t]))}queueEvent=(e,t,...s)=>{this.#o.set(e+String(t),[e,t,...s])};runListeners=(e,t,...s)=>{for(const r of this.listeners.get(e)||new Set)t?r(t,...s):r(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#c=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#d,this.#u])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#c?.();for(const e of this.#o.values())this.runListeners(...e);this.#o.clear()}startEsbuildRun(){this.#d=new Promise(e=>{this.#h=e})}finishEsbuildRun(){this.#h?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#u=new Promise(e=>{this.#f=e}))}noteRequestHandlersEntryBuildStart(){this.#p=this.#r}markRequestHandlersEntryUpdated(){this.#e&&(this.#r>this.#p||(this.#e=!1,this.#f?.()))}get contentDir(){if(this.serverMode)throw new Error("contentDir should not be used in server mode");return this.#n}markUserCodeReady(){this.#l?.(!0)}async reloadMarkdocOptions(){await le("com.redocly.build.reloadMarkdocOptions",async()=>{const{userTagNames:e,...t}=await Y(this.serverOutDir),s=Q(e),r=Object.fromEntries(Object.entries(t.tags).filter(([o])=>!(o in s)));this.#a={...t,tags:r},this.#i=s})}get markdocOptions(){return{...this.#a,partials:this.getGlobalConfig(y),themeConfig:this.config.markdown,planDeniedTags:this.#i}}setGlobalData=e=>{const t=this.globalData,s={...this.globalData,...e};this.globalData=s,JSON.stringify(s)!==JSON.stringify(t)&&this.queueEvent("global-data-updated",void 0,s)};getGlobalData=()=>this.globalData;getKv=async()=>q.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:r})=>{const{data:{info:o,ast:a},compoundHash:l}=await M(e,this.markdocOptions,{actions:this,context:t},r);for(const i of o.sharedDataDeps||[]){for(const n of s?.routeSlugs||[])this.addRouteSharedData(n,i,i);for(const n of s?.sharedDataIds||[]){const c=this.sharedDataDeps.get(n)||new Set;c.add(i),this.sharedDataDeps.set(n,c)}}for(const i of o.dynamicMarkdocComponents||[]){for(const n of s?.routeSlugs||[]){const c=this.routesDynamicComponents.get(n)||new Set;c.add(i),this.routesDynamicComponents.set(n,c)}for(const n of s?.sharedDataIds||[]){const c=this.sharedDataMarkdocComponents.get(n)||new Set;c.add(i),this.sharedDataMarkdocComponents.set(n,c)}}if(s?.routeSlugs&&o.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of o.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:o,ast:a,compoundHash:l}};async loadApiDocuments(e){return(await e.cache.load(".","api-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=e};setStaticFilePaths=e=>{this.staticFilePaths=e};setGlobalConfig=e=>{const t=Object.keys(e);for(const a of t)for(const l in this.replacedEnvVars)if(l===a||l.startsWith(`${a}:`)){const i=l.split(":"),{error:n,value:c}=S(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{config:s,unsetEnvVars:r,replacedValues:o}=re(e);for(const a of r)this.unsetEnvVars.add(a);Object.assign(this.replacedEnvVars,o),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!Z.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const a=d(e).toLowerCase();this.config.redirects[a]=t;const{trackOriginalSource:l=!0}=s,i=this.getGlobalConfig("originalRedirectSources");l&&Array.isArray(i)&&!i.includes(a)&&i.push(a),a.endsWith("*")&&ne(this.config.wildcardRedirectsTree,a)};getRedirect=e=>{const t=d(e).toLowerCase(),s=ae(t,this.config.redirects,this.config.wildcardRedirectsTree,this.staticFilePaths);if(!s)return null;if(v(s.to)){const r=d(s.to).toLowerCase();if(!r.endsWith("*")&&ie(r,[t],this.config.redirects,this.config.wildcardRedirectsTree).type==="cycle")return null}return{to:s.to,type:s.type}};createSharedData=async(e,t,s)=>{if(s&&this.#t[e]===s)return e;const r=JSON.stringify(t),o=s??_(r);return this.#t[e]===o||(this.#t[e]=o,await K(e,r,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const r=G(e),o=this.routesSharedData.get(r)||{};o[t]=s,this.routesSharedData.set(r,o),u.verbose(`Adding shared data to ${e}, ${t}, ${s}`)};getRouteSharedDataByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.routesSharedData.get(t)||{}:{}};getPartialsForRoute=e=>{const t=this.getGlobalConfig(y)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const r=this.getGlobalConfig(L)||{},o=new Set(s),a=Array.from(s);for(let i=0;i<a.length;i++){const n=a[i],c=r[n]?.partials??[];for(const h of c)o.has(h)||(o.add(h),a.push(h))}const l={};for(const i of o)t[i]&&(l[i]=t[i]);return l};addRoute=e=>{const s={...te(e.fsPath,this.config.metadataGlobs),...e.metadata||{}};this.newRoutes.push({...e,metadata:s}),u.verbose("Created route %s",e.slug)};addRouteSharedDataToAllLocales=(e,t,s)=>{const r=[m,...this.lifecycleContext?.fs.localeFolders||[]].map(o=>({code:o,name:o}));for(const o of r){const a=k(e,m,o.code,r);this.addRouteSharedData(a,t,s)}};addApiRoute=e=>{this.apiRoutes.push(e),u.verbose("Created API route %s",e.slug)};addMcpTools=(e,t)=>{for(const s of t){const r=this.mcpToolHandlers.get(s.name);r&&r.importPath!==e&&u.warn('MCP tool "%s" from %s overwrites the tool registered from %s',s.name,e,r.importPath);const o=s.hasAvailabilityGate??(r?.importPath===e?r.hasAvailabilityGate:void 0);this.mcpToolHandlers.set(s.name,{...s,importPath:e,hasAvailabilityGate:o}),u.verbose("Created MCP tool %s",s.name)}};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());markGatedMcpTools=e=>{for(const t of e){const s=this.mcpToolHandlers.get(t);s&&this.mcpToolHandlers.set(t,{...s,hasAvailabilityGate:!0})}};addSkills=e=>{for(const t of e)this.skills.set(t.slug,t),u.verbose("Discovered skill %s",t.slug)};getSkills=()=>Array.from(this.skills.values());removeMcpTools=e=>{for(const t of e)this.mcpToolHandlers.delete(t)};addMiddleware=e=>{this.middleware.push(e),u.verbose("Created middleware %s",e.id)};setResourceResponseHeaders=(e,t)=>{this.config.responseHeaders||(this.config.responseHeaders={});const s=new Set(t.map(a=>a.name.toLowerCase())),o=[...(this.config.responseHeaders[e]??[]).filter(a=>!s.has(a.name.toLowerCase())),...t];this.config.responseHeaders[e]=o};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,r=this.getRedirect(e);if(s&&r)return this.routesBySlug.get(d(r.to));const o=s?this.routeAliases.get(d(e).toLowerCase()):void 0;return this.routesBySlug.get(o??e)};addRouteAlias=(e,t)=>{this.routeAliases.set(d(e).toLowerCase(),d(t))};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e)||this.routeAliases.has(d(e).toLowerCase())||X(e,this.getConfig()))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!v(t.to))return!0;const s=d(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=m)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(r=>e===m?!ee(r.fsPath):r.slug.startsWith(`/${s}`))};getAllRoutes=()=>Array.from(this.routesBySlug.values());getAllApiRoutes=()=>this.apiRoutes;getAllMiddleware=()=>this.middleware;getTemplate=e=>this.templates.get(e);getRequestHandler=e=>this.apiRoutesRequestHandlers.get(e);createTemplate=(e,t)=>(this.templates.set(e,t),e);addBrowserPlugin=e=>{this.browserPlugins.add(e)};copyAsset=async(e,t)=>{const s=this.lifecycleContext?.fs;if(!s)throw new Error(`Cannot copy asset ${e}: the content file system is not ready`);try{const r=await I(e,s,{fromFileRelativePath:t,contentDir:this.contentDir,outdir:this.outdir});if(!r)throw new Error(`Cannot copy asset ${e}`);return r}catch(r){if(r instanceof B)return null;throw r}};createRequestHandler=(e,t)=>(this.apiRoutesRequestHandlers.set(e,t),e);clearRequestHandlersByPrefix=e=>{for(const t of this.apiRoutesRequestHandlers.keys())t.startsWith(e)&&this.apiRoutesRequestHandlers.delete(t)};registerServerPropsGetter=(e,t)=>(this.serverPropsGetters.set(e,t),e);registerPagePropsGetter=(e,t)=>{this.pagePropsGetters.set(e,t)};async writeRouteStaticData(e,t){const s=await this.resolveRouteStaticData(e,t,!1);s&&z(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return W(e.slug,this.outdir);const r={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:h,resource:f})=>this.parseMarkdoc({input:c,context:h,deps:{routeSlugs:[e.slug]},resource:f})},o=await e.getStaticData?.(e,r)||{},a=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const h=this.sharedDataMarkdocComponents.get(c);h&&h.forEach(p=>a.add(p));const f=this.sharedDataDeps.get(c);f&&f.forEach(p=>this.addRouteSharedData(e.slug,p,p))}const i=this.getGlobalConfig("seo"),n=o?.frontmatter||{};return{...o,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...o.props,dynamicMarkdocComponents:Array.from(a),metadata:{...o?.props?.metadata,...e.metadata},seo:{title:F,...i,...o.props?.seo,siteUrl:i?.siteUrl},compilationErrors:this.compilationErrors},lastModified:s||!e.fsPath?null:await this.lifecycleContext?.fs.getLastModified(e.fsPath)}}addSsrComponents(e,t){if(!e?.length)return;const s=typeof e[0]=="string"?e.join(""):$(e);s&&(t==="head"?this.ssr.headTags.push(s):t==="preBody"?this.ssr.preBodyTags.push(s):this.ssr.postBodyTags.push(s))}clear=()=>{this.routesByFsPath.clear(),this.templates.clear(),this.newRoutes=[],this.routesBySlug.clear(),this.routeAliases.clear(),this.apiRoutes=[],this.middleware=[],this.routesSharedData.clear(),this.sharedDataDeps.clear(),this.sharedDataMarkdocComponents.clear(),this.routesDynamicComponents.clear(),this.routesPartials.clear(),this.skills.clear(),this.config.redirects={},this.config.wildcardRedirectsTree={},this.config.directoryPermissions={},this.ssr={preBodyTags:[],postBodyTags:[],headTags:[]}};#g(){const e=[];for(const[s,r]of Object.entries(P))switch(r){case"map":{const o=Array.from(this[s].entries());e.push([s,o]);break}case"object":e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[b]=j.PLAN_GATES,t}static#m(e,t){const s=new D(t);for(const[o,a]of Object.entries(P))switch(a){case"map":s[o]=new Map(e[o]);break;case"object":s[o]=e[o];break;default:throw new Error("Invalid format")}const r=e[b];return r&&V("PLAN_GATES",r),s}async writeServerFiles(){x(this.serverOutDir),w(g(this.serverOutDir,C),JSON.stringify(this.#g())),w(g(this.serverOutDir,A),JSON.stringify(await this.getConfigWithEnvPlaceholders()))}static async fromServerFiles(e){const t=g(e.serverOutDir,A),{config:s,env:r}=oe(JSON.parse(await R(t,"utf8")));s[y]=de(s[y]);const o=JSON.parse(await R(g(e.serverOutDir,C),"utf8")),a=D.#m(o,e);a.config=s;const l=Object.fromEntries(Object.entries(r).filter(([i])=>U(i)));return a.configFile={path:t,env:l,config:{...s}},a}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],r=t.split(":"),o=r.pop(),{error:a,value:l}=S(e,r);if(a||!H(l)&&!Array.isArray(l)){await E.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[o]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!ce.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await E.panicOnBuildContentError(t)}}function de(O){return N(O,e=>T.Ast.fromJSON(JSON.stringify(e)))}export{D as Store,We as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
1
+ import T from"@redocly/markdoc";import{writeFileSync as w}from"node:fs";import{readFile as R}from"node:fs/promises";import{join as g}from"node:path";import{parseAndResolveMarkdoc as M}from"./plugins/markdown/compiler.js";import{getPathnameForLocale as k}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../constants/common.js";import{DEFAULT_TITLE as F,MARKDOC_PARTIALS_DATA_KEY as y,MARKDOC_PARTIALS_DEPS_KEY as L}from"./constants/common.js";import{isObject as H}from"../utils/guards/is-object.js";import{mapObject as N}from"../utils/object/map-object.js";import{getValueDeep as S}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as G}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as d}from"../utils/path/normalize-route-slug.js";import{isLocalLink as v}from"../utils/path/is-local-link.js";import{reporter as E}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as _}from"./utils/crypto/sha1.js";import{FileNotFoundError as B}from"./utils/fs.js";import{resolveAssetPath as I}from"./utils/resolve-asset-path.js";import{envConfig as j,setEnv as V}from"./config/env-config.js";import{KvService as q}from"./persistence/kv/services/kv-service.js";import{SandboxContext as J}from"./utils/sandbox-context.js";import{isAllowedEnv as U}from"./utils/envs/get-api-route-allowed-env-variables.js";import{ensureDir as x,writeSharedData as K}from"./utils/index.js";import{renderComponents as $}from"./ssr/render.js";import{readStaticData as W,writeStaticData as z}from"./utils/static-data.js";import{getMarkdocOptions as Y}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as Z}from"./entitlements/entitlements-provider.js";import{getPlanDeniedMarkdocTags as Q}from"./entitlements/plan-denied-markdoc-tags.js";import{isRouteReserved as X}from"./plugins/get-reserved-routes.js";import{isL10nPath as ee}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as te}from"./utils/globs.js";import{createDefaultStoreConfig as se,resolveConfigEntries as re,resolveStoreConfig as oe}from"./store-config.js";import{findRedirect as ae}from"./utils/redirects/find-redirect.js";import{followRedirectChain as ie}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as ne}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as le}from"../cli/telemetry/helpers/trace-step.js";const P={routesBySlug:"map",staticFilePaths:"object",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map",devLogin:"object"},C="store.json",A="store-config.json",b="PLAN_GATES",ce=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],We="userDefinedApiFunctions";class D{routesBySlug=new Map;routeAliases=new Map;staticFilePaths={};replacedEnvVars={};unsetEnvVars=new Set;lifecycleContext;newRoutes=[];#t={};routesByFsPath=new Map;apiRoutes=[];middleware=[];routesSharedData=new Map;sharedDataDeps=new Map;sharedDataMarkdocComponents=new Map;routesDynamicComponents=new Map;routesPartials=new Map;ssr={preBodyTags:[],postBodyTags:[],headTags:[]};searchFacets=new Map;searchEngine;templates=new Map;browserPlugins=new Set;apiRoutesRequestHandlers=new Map;mcpToolHandlers=new Map;skills=new Map;serverPropsGetters=new Map;pagePropsGetters=new Map;listeners=new Map;globalData={};devLogin=!1;#a=void 0;#i={};config=se();configFile;#n;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#l;userCodeReady;#s=Promise.resolve();#c;#d=Promise.resolve();#h;#u=Promise.resolve();#f;#e=!1;#r=0;#p=0;#o=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:r}){this.#n=t,this.outdir=e,this.serverMode=s,this.serverOutDir=r,J.register({serverOutDir:r,readRoots:[e,process.cwd()]}),this.userCodeReady=new Promise(o=>{this.#l=o})}on(e,t){const s=this.listeners.get(e);s?s.add(t):this.listeners.set(e,new Set([t]))}queueEvent=(e,t,...s)=>{this.#o.set(e+String(t),[e,t,...s])};runListeners=(e,t,...s)=>{for(const r of this.listeners.get(e)||new Set)t?r(t,...s):r(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#c=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#d,this.#u])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#c?.();for(const e of this.#o.values())this.runListeners(...e);this.#o.clear()}startEsbuildRun(){this.#d=new Promise(e=>{this.#h=e})}finishEsbuildRun(){this.#h?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#u=new Promise(e=>{this.#f=e}))}noteRequestHandlersEntryBuildStart(){this.#p=this.#r}markRequestHandlersEntryUpdated(){return this.#e?this.#r>this.#p?!1:(this.#e=!1,this.#f?.(),!0):!0}get contentDir(){if(this.serverMode)throw new Error("contentDir should not be used in server mode");return this.#n}markUserCodeReady(){this.#l?.(!0)}async reloadMarkdocOptions(){await le("com.redocly.build.reloadMarkdocOptions",async()=>{const{userTagNames:e,...t}=await Y(this.serverOutDir),s=Q(e),r=Object.fromEntries(Object.entries(t.tags).filter(([o])=>!(o in s)));this.#a={...t,tags:r},this.#i=s})}get markdocOptions(){return{...this.#a,partials:this.getGlobalConfig(y),themeConfig:this.config.markdown,planDeniedTags:this.#i}}setGlobalData=e=>{const t=this.globalData,s={...this.globalData,...e};this.globalData=s,JSON.stringify(s)!==JSON.stringify(t)&&this.queueEvent("global-data-updated",void 0,s)};getGlobalData=()=>this.globalData;getKv=async()=>q.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:r})=>{const{data:{info:o,ast:a},compoundHash:l}=await M(e,this.markdocOptions,{actions:this,context:t},r);for(const i of o.sharedDataDeps||[]){for(const n of s?.routeSlugs||[])this.addRouteSharedData(n,i,i);for(const n of s?.sharedDataIds||[]){const c=this.sharedDataDeps.get(n)||new Set;c.add(i),this.sharedDataDeps.set(n,c)}}for(const i of o.dynamicMarkdocComponents||[]){for(const n of s?.routeSlugs||[]){const c=this.routesDynamicComponents.get(n)||new Set;c.add(i),this.routesDynamicComponents.set(n,c)}for(const n of s?.sharedDataIds||[]){const c=this.sharedDataMarkdocComponents.get(n)||new Set;c.add(i),this.sharedDataMarkdocComponents.set(n,c)}}if(s?.routeSlugs&&o.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of o.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:o,ast:a,compoundHash:l}};async loadApiDocuments(e){return(await e.cache.load(".","api-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=e};setStaticFilePaths=e=>{this.staticFilePaths=e};setGlobalConfig=e=>{const t=Object.keys(e);for(const a of t)for(const l in this.replacedEnvVars)if(l===a||l.startsWith(`${a}:`)){const i=l.split(":"),{error:n,value:c}=S(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{config:s,unsetEnvVars:r,replacedValues:o}=re(e);for(const a of r)this.unsetEnvVars.add(a);Object.assign(this.replacedEnvVars,o),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!Z.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const a=d(e).toLowerCase();this.config.redirects[a]=t;const{trackOriginalSource:l=!0}=s,i=this.getGlobalConfig("originalRedirectSources");l&&Array.isArray(i)&&!i.includes(a)&&i.push(a),a.endsWith("*")&&ne(this.config.wildcardRedirectsTree,a)};getRedirect=e=>{const t=d(e).toLowerCase(),s=ae(t,this.config.redirects,this.config.wildcardRedirectsTree,this.staticFilePaths);if(!s)return null;if(v(s.to)){const r=d(s.to).toLowerCase();if(!r.endsWith("*")&&ie(r,[t],this.config.redirects,this.config.wildcardRedirectsTree).type==="cycle")return null}return{to:s.to,type:s.type}};createSharedData=async(e,t,s)=>{if(s&&this.#t[e]===s)return e;const r=JSON.stringify(t),o=s??_(r);return this.#t[e]===o||(this.#t[e]=o,await K(e,r,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const r=G(e),o=this.routesSharedData.get(r)||{};o[t]=s,this.routesSharedData.set(r,o),u.verbose(`Adding shared data to ${e}, ${t}, ${s}`)};getRouteSharedDataByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.routesSharedData.get(t)||{}:{}};getPartialsForRoute=e=>{const t=this.getGlobalConfig(y)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const r=this.getGlobalConfig(L)||{},o=new Set(s),a=Array.from(s);for(let i=0;i<a.length;i++){const n=a[i],c=r[n]?.partials??[];for(const h of c)o.has(h)||(o.add(h),a.push(h))}const l={};for(const i of o)t[i]&&(l[i]=t[i]);return l};addRoute=e=>{const s={...te(e.fsPath,this.config.metadataGlobs),...e.metadata||{}};this.newRoutes.push({...e,metadata:s}),u.verbose("Created route %s",e.slug)};addRouteSharedDataToAllLocales=(e,t,s)=>{const r=[m,...this.lifecycleContext?.fs.localeFolders||[]].map(o=>({code:o,name:o}));for(const o of r){const a=k(e,m,o.code,r);this.addRouteSharedData(a,t,s)}};addApiRoute=e=>{this.apiRoutes.push(e),u.verbose("Created API route %s",e.slug)};addMcpTools=(e,t)=>{for(const s of t){const r=this.mcpToolHandlers.get(s.name);r&&r.importPath!==e&&u.warn('MCP tool "%s" from %s overwrites the tool registered from %s',s.name,e,r.importPath);const o=s.hasAvailabilityGate??(r?.importPath===e?r.hasAvailabilityGate:void 0);this.mcpToolHandlers.set(s.name,{...s,importPath:e,hasAvailabilityGate:o}),u.verbose("Created MCP tool %s",s.name)}};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());markGatedMcpTools=e=>{for(const t of e){const s=this.mcpToolHandlers.get(t);s&&this.mcpToolHandlers.set(t,{...s,hasAvailabilityGate:!0})}};addSkills=e=>{for(const t of e)this.skills.set(t.slug,t),u.verbose("Discovered skill %s",t.slug)};getSkills=()=>Array.from(this.skills.values());removeMcpTools=e=>{for(const t of e)this.mcpToolHandlers.delete(t)};addMiddleware=e=>{this.middleware.push(e),u.verbose("Created middleware %s",e.id)};setResourceResponseHeaders=(e,t)=>{this.config.responseHeaders||(this.config.responseHeaders={});const s=new Set(t.map(a=>a.name.toLowerCase())),o=[...(this.config.responseHeaders[e]??[]).filter(a=>!s.has(a.name.toLowerCase())),...t];this.config.responseHeaders[e]=o};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,r=this.getRedirect(e);if(s&&r)return this.routesBySlug.get(d(r.to));const o=s?this.routeAliases.get(d(e).toLowerCase()):void 0;return this.routesBySlug.get(o??e)};addRouteAlias=(e,t)=>{this.routeAliases.set(d(e).toLowerCase(),d(t))};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e)||this.routeAliases.has(d(e).toLowerCase())||X(e,this.getConfig()))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!v(t.to))return!0;const s=d(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=m)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(r=>e===m?!ee(r.fsPath):r.slug.startsWith(`/${s}`))};getAllRoutes=()=>Array.from(this.routesBySlug.values());getAllApiRoutes=()=>this.apiRoutes;getAllMiddleware=()=>this.middleware;getTemplate=e=>this.templates.get(e);getRequestHandler=e=>this.apiRoutesRequestHandlers.get(e);createTemplate=(e,t)=>(this.templates.set(e,t),e);addBrowserPlugin=e=>{this.browserPlugins.add(e)};copyAsset=async(e,t)=>{const s=this.lifecycleContext?.fs;if(!s)throw new Error(`Cannot copy asset ${e}: the content file system is not ready`);try{const r=await I(e,s,{fromFileRelativePath:t,contentDir:this.contentDir,outdir:this.outdir});if(!r)throw new Error(`Cannot copy asset ${e}`);return r}catch(r){if(r instanceof B)return null;throw r}};createRequestHandler=(e,t)=>(this.apiRoutesRequestHandlers.set(e,t),e);clearRequestHandlersByPrefix=e=>{for(const t of this.apiRoutesRequestHandlers.keys())t.startsWith(e)&&this.apiRoutesRequestHandlers.delete(t)};registerServerPropsGetter=(e,t)=>(this.serverPropsGetters.set(e,t),e);registerPagePropsGetter=(e,t)=>{this.pagePropsGetters.set(e,t)};async writeRouteStaticData(e,t){const s=await this.resolveRouteStaticData(e,t,!1);s&&z(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return W(e.slug,this.outdir);const r={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:h,resource:f})=>this.parseMarkdoc({input:c,context:h,deps:{routeSlugs:[e.slug]},resource:f})},o=await e.getStaticData?.(e,r)||{},a=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const h=this.sharedDataMarkdocComponents.get(c);h&&h.forEach(p=>a.add(p));const f=this.sharedDataDeps.get(c);f&&f.forEach(p=>this.addRouteSharedData(e.slug,p,p))}const i=this.getGlobalConfig("seo"),n=o?.frontmatter||{};return{...o,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...o.props,dynamicMarkdocComponents:Array.from(a),metadata:{...o?.props?.metadata,...e.metadata},seo:{title:F,...i,...o.props?.seo,siteUrl:i?.siteUrl},compilationErrors:this.compilationErrors},lastModified:s||!e.fsPath?null:await this.lifecycleContext?.fs.getLastModified(e.fsPath)}}addSsrComponents(e,t){if(!e?.length)return;const s=typeof e[0]=="string"?e.join(""):$(e);s&&(t==="head"?this.ssr.headTags.push(s):t==="preBody"?this.ssr.preBodyTags.push(s):this.ssr.postBodyTags.push(s))}clear=()=>{this.routesByFsPath.clear(),this.templates.clear(),this.newRoutes=[],this.routesBySlug.clear(),this.routeAliases.clear(),this.apiRoutes=[],this.middleware=[],this.routesSharedData.clear(),this.sharedDataDeps.clear(),this.sharedDataMarkdocComponents.clear(),this.routesDynamicComponents.clear(),this.routesPartials.clear(),this.skills.clear(),this.config.redirects={},this.config.wildcardRedirectsTree={},this.config.directoryPermissions={},this.ssr={preBodyTags:[],postBodyTags:[],headTags:[]}};#g(){const e=[];for(const[s,r]of Object.entries(P))switch(r){case"map":{const o=Array.from(this[s].entries());e.push([s,o]);break}case"object":e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[b]=j.PLAN_GATES,t}static#m(e,t){const s=new D(t);for(const[o,a]of Object.entries(P))switch(a){case"map":s[o]=new Map(e[o]);break;case"object":s[o]=e[o];break;default:throw new Error("Invalid format")}const r=e[b];return r&&V("PLAN_GATES",r),s}async writeServerFiles(){x(this.serverOutDir),w(g(this.serverOutDir,C),JSON.stringify(this.#g())),w(g(this.serverOutDir,A),JSON.stringify(await this.getConfigWithEnvPlaceholders()))}static async fromServerFiles(e){const t=g(e.serverOutDir,A),{config:s,env:r}=oe(JSON.parse(await R(t,"utf8")));s[y]=de(s[y]);const o=JSON.parse(await R(g(e.serverOutDir,C),"utf8")),a=D.#m(o,e);a.config=s;const l=Object.fromEntries(Object.entries(r).filter(([i])=>U(i)));return a.configFile={path:t,env:l,config:{...s}},a}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],r=t.split(":"),o=r.pop(),{error:a,value:l}=S(e,r);if(a||!H(l)&&!Array.isArray(l)){await E.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[o]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!ce.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await E.panicOnBuildContentError(t)}}function de(O){return N(O,e=>T.Ast.fromJSON(JSON.stringify(e)))}export{D as Store,We as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
@@ -1,3 +1,3 @@
1
- import*as E from"node:path";import{envConfig as R}from"../../config/env-config.js";import{maskEmail as T,maskSubject as C,removePii as w,removePiiFromUrl as $}from"../../../compiled/@redocly/pii/index.mjs";import{red as x,green as A,bold as F,blue as l,gray as r,yellow as b,cyan as v}from"./helpers/colors.js";function P(e,s){return s?e:w(e)}var n;(function(e){e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR",e.SUCCESS="SUCCESS",e.VERBOSE="VERBOSE",e.HTTP="HTTP"})(n||(n={}));const I={[n.VERBOSE]:0,[n.HTTP]:1,[n.INFO]:2,[n.SUCCESS]:2,[n.WARN]:3,[n.ERROR]:4};function J(e,s){return I[e]>=I[s]}function W(e){if(!e)return;const s=e.toUpperCase();if(s in n)return s}const H={[n.INFO]:l,[n.SUCCESS]:A,[n.WARN]:b,[n.ERROR]:x,[n.HTTP]:v,[n.VERBOSE]:r},N={"%ap":e=>l(E.resolve(e)),"%rp":e=>l(E.relative(process.cwd(),e)),"%s":e=>e?.toString(),"%c":e=>l(e)},M={format(e){return R.REDOCLY_LOG_FORMAT==="JSON"?y(e):U(e)},interpolate(e,...s){const u=Object.keys(N).map(a=>`(${a})`).join("|"),o=new RegExp(u,"g");let i,c=e;for(;(i=o.exec(e))!==null;){i.index===o.lastIndex&&o.lastIndex++;const a=s.shift();if(a===void 0)break;const t=i[0];c=c.replace(t,N[t](a))}return c}};var z=M;const U=e=>{const{level:s,message:u,duration:o,context:i,preSanitized:c}=e,a=R.isRuntimeMode,t=[H[s](F(`[${s.toLowerCase()}]`))];if(a&&t.push(r(`time="${j()}"`)),i){const{email:m,ipAddress:f,subject:d,method:S,pathname:p,statusCode:h,teams:g,apiFunction:O}=i;O&&t.push(l(`fn="${O}"`)),h&&t.push(D(h)),e.level===n.HTTP&&(S&&t.push(r(`method="${S}"`)),p&&t.push(r(`path="${$(p)}"`))),f&&t.push(r(`ip="${f}"`)),m&&t.push(r(`email="${T(m)}"`)),d&&t.push(r(`sub="${C(d)}"`)),g?.length&&t.push(r(`teams="${g.join(", ")}"`))}if(u){const m=a?`msg="${String(P(u,c)).replaceAll?.('"','\\"')}"`:String(u);t.push(m)}return e.level===n.HTTP&&i?.userAgent&&t.push(r(`agent="${i.userAgent}"`)),o&&t.push(V(o)),t.join(" ")+`
1
+ import*as E from"node:path";import{envConfig as R}from"../../config/env-config.js";import{maskEmail as T,maskSubject as C,removePii as w,removePiiFromUrl as $}from"../../../compiled/@redocly/platform-utils/pii/index.mjs";import{red as x,green as A,bold as F,blue as l,gray as r,yellow as b,cyan as v}from"./helpers/colors.js";function P(e,s){return s?e:w(e)}var n;(function(e){e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR",e.SUCCESS="SUCCESS",e.VERBOSE="VERBOSE",e.HTTP="HTTP"})(n||(n={}));const I={[n.VERBOSE]:0,[n.HTTP]:1,[n.INFO]:2,[n.SUCCESS]:2,[n.WARN]:3,[n.ERROR]:4};function J(e,s){return I[e]>=I[s]}function W(e){if(!e)return;const s=e.toUpperCase();if(s in n)return s}const H={[n.INFO]:l,[n.SUCCESS]:A,[n.WARN]:b,[n.ERROR]:x,[n.HTTP]:v,[n.VERBOSE]:r},N={"%ap":e=>l(E.resolve(e)),"%rp":e=>l(E.relative(process.cwd(),e)),"%s":e=>e?.toString(),"%c":e=>l(e)},M={format(e){return R.REDOCLY_LOG_FORMAT==="JSON"?y(e):U(e)},interpolate(e,...s){const u=Object.keys(N).map(a=>`(${a})`).join("|"),o=new RegExp(u,"g");let i,c=e;for(;(i=o.exec(e))!==null;){i.index===o.lastIndex&&o.lastIndex++;const a=s.shift();if(a===void 0)break;const t=i[0];c=c.replace(t,N[t](a))}return c}};var z=M;const U=e=>{const{level:s,message:u,duration:o,context:i,preSanitized:c}=e,a=R.isRuntimeMode,t=[H[s](F(`[${s.toLowerCase()}]`))];if(a&&t.push(r(`time="${j()}"`)),i){const{email:m,ipAddress:f,subject:d,method:S,pathname:p,statusCode:h,teams:g,apiFunction:O}=i;O&&t.push(l(`fn="${O}"`)),h&&t.push(D(h)),e.level===n.HTTP&&(S&&t.push(r(`method="${S}"`)),p&&t.push(r(`path="${$(p)}"`))),f&&t.push(r(`ip="${f}"`)),m&&t.push(r(`email="${T(m)}"`)),d&&t.push(r(`sub="${C(d)}"`)),g?.length&&t.push(r(`teams="${g.join(", ")}"`))}if(u){const m=a?`msg="${String(P(u,c)).replaceAll?.('"','\\"')}"`:String(u);t.push(m)}return e.level===n.HTTP&&i?.userAgent&&t.push(r(`agent="${i.userAgent}"`)),o&&t.push(V(o)),t.join(" ")+`
2
2
  `},y=({context:e,message:s,preSanitized:u,...o})=>{const{method:i,pathname:c,statusCode:a,userAgent:t,subject:m,email:f,teams:d,apiFunction:S}=e||{},p={...o,email:f&&T(f),subject:m&&C(m),teams:d,apiFunction:S,...o.level===n.HTTP?{method:i,pathname:String($(c)),statusCode:a,userAgent:t}:{message:String(P(String(s??""),u))}};return R.isRuntimeMode&&(p.time=j()),JSON.stringify(p,["time","level","scope","message","duration","method","pathname","statusCode","userAgent","subject","ipAddress","email","apiFunction"])+`
3
3
  `},D=e=>(e%500<100?x:e%400<100?b:A)(`status="${e}"`),j=()=>{const e=new Date().getTimezoneOffset()*6e4;return new Date(Date.now()-e).toISOString().slice(0,-1)},V=e=>r(`dur="${Math.round(e)}ms"`);export{n as LogLevel,z as default,W as parseLogLevel,J as shouldLog};
@@ -121,6 +121,8 @@ export type ApiRouteMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all'
121
121
  export type ApiRoute = RouteDetails & {
122
122
  httpMethod: ApiRouteMethod;
123
123
  requestHandlerId: string;
124
+ timeoutMs?: number;
125
+ maxResponseSizeMB?: number;
124
126
  };
125
127
  export type McpToolSchema = {
126
128
  name: string;
@@ -60,6 +60,11 @@ declare module 'hono' {
60
60
  }
61
61
  }
62
62
  export type LlmsTxtGenerator = {
63
+ /**
64
+ * Whether `getPageMarkdown` would answer for this path, without rendering anything. A sub-path
65
+ * of a route with client routes answers for the owner route.
66
+ */
67
+ hasPageMarkdown(mdPathname: string): boolean;
63
68
  getPageMarkdown(mdPathname: string): Promise<{
64
69
  route: PageRouteDetails;
65
70
  content: string;
@@ -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};
@@ -1 +1 @@
1
- import{normalizePathPrefix as t}from"@redocly/theme/core/utils";import{shaHexShort as h}from"./sha-hex-short.js";function n(r){const o=r==="."?"/":t(r);return h(o)}export{n as shaDirPathShort};
1
+ import{addLeadingSlash as a,removeTrailingSlash as t}from"@redocly/theme/core/utils";import{shaHexShort as h}from"./sha-hex-short.js";function m(r){const o=r==="."?"/":a(t(r));return h(o)}export{m as shaDirPathShort};
@@ -3,6 +3,7 @@ export declare class HttpError extends Error {
3
3
  constructor(status: number, message: string);
4
4
  }
5
5
  export declare class OidcDiscoveryError extends Error {
6
- constructor(url: string, status: number, contentType: string | null);
6
+ /** `reason` completes the sentence "<host> ...", e.g. "answered HTTP 503 (text/html)". */
7
+ constructor(url: string, reason: string);
7
8
  }
8
9
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- class r extends Error{status;constructor(t,e){super(e),this.status=t,Object.setPrototypeOf(this,r.prototype)}}class s extends Error{constructor(t,e,o){super(`OIDC discovery failed: ${new URL(t).host} answered HTTP ${e} (${o??"no content type"})`),this.name="OidcDiscoveryError",Object.setPrototypeOf(this,s.prototype)}}export{r as HttpError,s as OidcDiscoveryError};
1
+ class s extends Error{status;constructor(t,r){super(r),this.status=t,Object.setPrototypeOf(this,s.prototype)}}class e extends Error{constructor(t,r){super(`OIDC discovery failed: ${new URL(t).host} ${r}`),this.name="OidcDiscoveryError",Object.setPrototypeOf(this,e.prototype)}}export{s as HttpError,e as OidcDiscoveryError};
@@ -6,5 +6,10 @@ type ResolvedLlmsTxtMd = {
6
6
  route: PageRouteDetails | undefined;
7
7
  };
8
8
  export declare function resolveLlmsTxtMd(mdPathname: string, store: Store, generator?: LlmsTxtGenerator): Promise<ResolvedLlmsTxtMd>;
9
+ /**
10
+ * The prefixed URL of the Markdown copy of the page at `slug`, or `undefined` when the site
11
+ * has no copy of it: the build wrote none, or develop mode generates none.
12
+ */
13
+ export declare function resolvePageMarkdownUrl(slug: string, store: Store, generator?: LlmsTxtGenerator): Promise<string | undefined>;
9
14
  export {};
10
15
  //# sourceMappingURL=resolve-llms-txt-md.d.ts.map
@@ -1 +1 @@
1
- import n from"path";import{removeLeadingSlash as s}from"../../../utils/url/remove-leading-slash.js";import{fileExistsAsync as l}from"../index.js";async function f(e,o,r){if(r){const t=await r.getPageMarkdown(e);return{exists:t!==void 0,content:t?.content,route:t?.route}}const i=e==="/index.html.md"?"/":e.replace(/\.md$/i,"");return{exists:await l(n.resolve(o.outdir,s(e))),content:void 0,route:o.getRouteBySlug(i,{followRedirect:!1})}}export{f as resolveLlmsTxtMd};
1
+ import s from"path";import{getMarkdownCopyPath as a,getSlugFromMarkdownCopyPath as d,withPathPrefix as u}from"@redocly/theme/core/utils";import{isPathInFolder as f}from"../../../utils/path/is-path-in-folder.js";import{removeLeadingSlash as l}from"../../../utils/url/remove-leading-slash.js";import{fileExistsAsync as c}from"../index.js";async function y(t,o,e){if(e){const r=await e.getPageMarkdown(t);return{exists:r!==void 0,content:r?.content,route:r?.route}}const n=d(t);return{exists:await i(t,o),content:void 0,route:n===null?void 0:o.getRouteBySlug(n,{followRedirect:!1})}}async function M(t,o,e){const n=a(t);return(e?e.hasPageMarkdown(n):await i(n,o))?encodeURI(u(n)):void 0}async function i(t,o){if(/[\\\0]/.test(t))return!1;const e=s.resolve(o.outdir,l(t));return f(e,o.outdir)&&c(e)}export{y as resolveLlmsTxtMd,M as resolvePageMarkdownUrl};
@@ -3,5 +3,6 @@ export declare function findProductBySlug(products: ProductConfig[], slug: strin
3
3
  folder: string;
4
4
  icon?: string | undefined;
5
5
  name: string;
6
+ nameTranslationKey?: string | undefined;
6
7
  } | undefined;
7
8
  //# sourceMappingURL=product.d.ts.map
@@ -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;
@@ -41,18 +43,23 @@ export declare function canAccessAsset(pathname: string, rbacConfig: RbacConfig,
41
43
  teams?: string[];
42
44
  }): boolean;
43
45
  export declare function getAuthDetailsFromCookies(ssoConfig: SsoConfig, cookies: Record<string, string>): Promise<AuthDetails>;
46
+ type FilterUser = {
47
+ isAuthenticated?: boolean;
48
+ email?: string;
49
+ teams?: string[];
50
+ };
44
51
  /**
45
- * Maps the input deep and removes objects that have a 'permission' prop
46
- * but do not match the input permissions list
52
+ * Removes, at any depth, the objects the user cannot access and strips RBAC annotations.
53
+ * Never mutates `input`, which must not change after the first call; callers must not mutate the
54
+ * result, which may be cached shared data.
55
+ * Every user denied nothing gets one shared object for the same `input`: `input` itself when it
56
+ * has nothing to strip. A user denied something gets a copy that shares no array or object with
57
+ * `input` or with another result, except `x-parsed-md-*` values, so a cache keyed by object
58
+ * identity never serves data filtered for one user to another.
47
59
  * @param input can be object, array, string or any other value
48
60
  * @param user - user object with email and teams
49
- * @returns
50
61
  */
51
- export declare function filterDataByAccessDeep(input: any, user?: {
52
- isAuthenticated?: boolean;
53
- email?: string;
54
- teams?: string[];
55
- }, rbacConfig?: RbacConfig, requiresLogin?: boolean): any;
62
+ export declare function filterDataByAccessDeep(input: any, user?: FilterUser, rbacConfig?: RbacConfig, requiresLogin?: boolean): any;
56
63
  export declare function parseTeamClaimToArray(claimValue: unknown): string[];
57
64
  /**
58
65
  * Extends RBAC config rules to include all supported languages
@@ -164,4 +171,5 @@ export declare function getRbacTeamsListForResource(resource: {
164
171
  }, rbacConfig: RbacConfig): string[];
165
172
  export declare function extractTeamsFromScopeItems(scopeItems: RbacScopeItems | undefined): string[];
166
173
  export declare function expandTeamsForRead(rbacConfig: RbacConfig, teamNames: string[]): string[];
174
+ export {};
167
175
  //# sourceMappingURL=rbac.d.ts.map
@@ -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 O from"path";import _ from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as g,REDOCLY_ROUTE_RBAC as E}from"@redocly/config";import{MCP_ROUTE as w,PUBLIC_MCP_ROUTE as B}from"@redocly/theme/core/constants/mcp";import{ServerRoutes as W}from"../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as T,PUBLIC_RBAC_SCOPE_ITEM as R,RBAC_ALL_OTHER_TEAMS as p,DEFAULT_RBAC_SCOPE as S,GRAPHQL_SPEC_SLUG as $}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as j,PUBLIC_API_DEFINITIONS_FOLDER as N,PUBLIC_ASSETS_FOLDER as Y,RUNTIME_RESOURCES_DIR as H,SCORECARD_CLASSIC_FOLDER as z,SITEMAP_FILE_NAME as G,LLMS_TXT_FILE_NAME as K}from"../constants/common.js";import{MCP_CREDENTIALS_ROUTE as V}from"../constants/mcp.js";import{ANONYMOUS_AUTH_DETAILS as q}from"../constants/rbac.js";import{removeTrailingSlash as D}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as J}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as Q}from"../../utils/path/parse-path-versions.js";import{reporter as X}from"../tools/notifiers/reporter.js";import{bold as v}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as Z}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as tt}from"../../utils/guards/is-truthy.js";import{isPathInFolder as F}from"../../utils/path/is-path-in-folder.js";import{canExpandConfig as et,expandRbacConfig as rt,getTeamFolderDefaults as nt,parseTeamFoldersTemplate as ot,parseTeamNameTemplate as st}from"./rbac-expand.js";import{getUserParamsFromCookies as ct}from"../web-server/auth.js";import{getDeeperGlobPattern as it}from"./globs.js";import{hasScopeAccess as U}from"./rbac/has-scope-access.js";import{EntitlementsProvider as at}from"../entitlements/entitlements-provider.js";const b=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],M=new Set(["x-parsed-md-description","x-parsed-md-summary"]),ft="@api",lt=new Set(Object.values(W).map(t=>D(t.split(":")[0])));function $t(t,e){const r=b.indexOf(t.toUpperCase()),n=b.indexOf(e.toUpperCase());return r>n?t:e}const P={};function k(t,e){if(!t?.content)return R;const r=t.content,{slug:n,fsPath:s}=e;if(!n&&!s)return R;const o=i=>{const d=`slug:${i}`,u=P[d]??_(i);P[d]=u;const A=`fsPath:${i}`,C=P[A]??_(J(i));return P[A]=C,!!(n&&u(n))||!!(s&&C(s))};if(pt(n||s||"")&&Object.keys(r).filter(u=>o(u)).length===0)return r[S]||R;const a=Object.keys(r).filter(i=>o(i));if(a.length==0)return R;const l=a.map(i=>_.scan(i,{tokens:!0,parts:!0}));let h=l[0];for(let i=1;i<l.length;i++)h=it(h,l[i]);return r[h.input]}function Yt(t,e){return y(t,q,e.access?.rbac||{},e.access?.requiresLogin||!1)}function Ht(t){const e={[S]:R,...t?.content};return Object.entries(e).some(([r,n])=>!r.split("/").includes(ft)&&U(n,[T]))}function y(t,e={},r={},n=!1){if(t.slug&&typeof t.slug=="string"&&lt.has(D(t.slug))||(t.slug===w||t.slug===B||t.slug===V)&&at.instance().canAccessFeature("mcp"))return!0;if(n&&Object.keys(r).length===0)return!!e.isAuthenticated;const s=rt(r,e.teams||[]),o=t[g]||k(s,t[E]||{});return Object.keys(o||{}).length===0?!1:Object.keys(o).length===1&&o[p]&&o[p].toLowerCase()!=="none"?!0:U(o,e?.teams||[],e?.email)}function zt(t,e,r,n,s){if(!t.startsWith(N)&&!t.startsWith(j))return!0;if(s){const l={[g]:s.rbac,[E]:{slug:s.slug,fsPath:s.sourcePath}};return y(l,n,e,r)}const o=t.replace(new RegExp(`^${N}/`),"").replace(new RegExp(`^${j}/`),"").replace(new RegExp(`^${$}/`),""),f=o==="."?"":o,a={[E]:{slug:t,fsPath:f},slug:t};return y(a,n,e,r)}function Gt(t,e,r,n,s){if(!F(t,Y))return[`/${G}`,`/${K}`].includes(t)||[H,z].some(A=>F(t,A));const o=t.match(/\..{64}\.([A-Fa-f0-9]{8})\.[^.]+$/)?.[1];if(!o)return!0;const c=n[o];if(!c)return!0;const{base:f,ext:a}=O.parse(t),l=f.split(".")[0],h=a.split(".").join(""),d=c==="."?"":c,u={[E]:{slug:t,fsPath:O.posix.join(d,`${l}.${h}`)},slug:t};return y(u,s,e,r)}async function Kt(t,e){const{isAuthenticated:r=!1,idpAccessToken:n,federatedAccessToken:s,federatedIdToken:o,...c}=await ct(t,e),{teams:f=[]}=c;let a;return r?a=f.filter(l=>l!==T):a=[T],{isAuthenticated:r,idpAccessToken:n,teams:a,claims:c}}const L=new WeakMap;function Vt(t,e,r={},n=!1){const s={user:e,rbacConfig:r,requiresLogin:n,denied:!1},o=x(t,s);return s.denied?I(o):o===t?t:(L.has(t)||L.set(t,o),L.get(t))}function x(t,e){if(!t)return t;if(Array.isArray(t)){let r;for(let n=0;n<t.length;n++){const s=t[n],o=x(s,e);!r&&(o!==s||o===void 0)&&(r=t.slice(0,n)),r&&o!==void 0&&r.push(o)}return r??t}if(typeof t=="object"){if(!y(t,e.user,e.rbacConfig,e.requiresLogin)){e.denied=!0;return}const r=Object.getPrototypeOf(t);let n=r!==Object.prototype&&r!==null;const s={};for(const o in t){if(o===g||o===E){n=!0;continue}if(M.has(o)){s[o]=t[o];continue}let c=x(t[o],e);if(!t.link&&(o==="items"||o==="menu"&&t.type==="tab")&&Array.isArray(c)&&c.length===0&&t[o].length!==0)return;o==="paths"&&mt(c)&&(c=ut(c)),c===void 0?n=!0:(n||=c!==t[o],s[o]=c)}return n?s:t}return t}function qt(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function Jt(t,e){if(!e)return;const r=e.content;if(!r)return e;const n=Object.entries(r).flatMap(([o,c])=>o===S?[[o,c]]:[[o,c]].concat(t.localeFolders.map(f=>[o.startsWith("/")?`/${f.toLocaleLowerCase()}${o}`:O.posix.join(t.localizationFolder,f,o),c]))),s=Object.fromEntries(n);return{...e,content:s}}async function Qt(t,e){if(!e)return{};const r={},n=new Set(t.scan().flatMap(({relativePath:s})=>{const{versionFolderPath:o}=Q(s)||{},c=O.dirname(s);return o?[o,c]:c}));for(const s of n)r[Z(s)]=s;return r}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function mt(t){return m(t)&&Object.keys(t).length>0}function I(t){if(Array.isArray(t))return t.map(I);if(!t||typeof t!="object")return t;const e={};for(const r in t)e[r]=M.has(r)?t[r]:I(t[r]);return e}function ut(t){const e=r=>m(r)&&Object.keys(r).length===0;return Object.values(t).some(e)?Object.fromEntries(Object.entries(t).filter(([,r])=>!e(r))):t}function pt(t){return t?t.split("/").filter(Boolean).some(r=>r.startsWith(".")):!1}const ht=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},Xt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(ht(t))return dt(t);await X.panicOnContentError(`You are using an incorrect format of ${v("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},dt=t=>{const e={...t};if(e.content){const r={};for(const n in e.content)if(e.content[n]!==void 0){const s=D(n);r[s]=e.content[n]}e.content=r}return e};function vt(t,e){const r=t.fsPath,n=t.slug,s=[],o=et(e)&&(r||n)?ot(e,[r,n].filter(tt)):null;if(o){const f=e?.teamNamePatterns?.map(a=>a.replace("{teamPathSegment}",o.teamPathSegment).replace("{projectRole}","read"))??[];s.push(...f)}const c=k(o?{content:{...nt(e),...e.content}}:e,t);return s.push(...Et(c)),Rt(e,s)}function Et(t){if(!t)return[];const e=[],r=p in t?{authenticated:t[p],anonymous:t[p]}:{};for(const[n,s]of Object.entries({...r,...t}))s.toLowerCase()!=="none"&&n!==p&&e.push(n);return e}function Rt(t,e){return e.map(n=>st(t,n)??{teamName:n}).map(n=>n.projectRole&&n.projectRole!=="READ"?n.teamName?.toLowerCase().replace(n.projectRole?.toLowerCase?.()??"","read")??"":n.teamName?.toLowerCase()??"")}export{b as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,Jt as applyL10nToRbacConfig,Ht as areAnyPagesOpenToAnonymous,Gt as canAccessAsset,y as canAccessResource,zt as canDownloadApiDefinition,Rt as expandTeamsForRead,Et as extractTeamsFromScopeItems,Vt as filterDataByAccessDeep,Kt as getAuthDetailsFromCookies,$t as getHigherRole,vt as getRbacTeamsListForResource,k as getScopeItemsForResource,ht as isRbacConfigValid,Yt as isResourcePubliclyAccessible,dt as normalizeRbacConfig,Xt as parseRbacConfig,qt as parseTeamClaimToArray,Qt as resolveDirectoryHashes};