@rspress/core 2.0.0-beta.8 → 2.0.0-rc.0

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 (595) hide show
  1. package/README.md +17 -1
  2. package/bin/rspress.js +15 -0
  3. package/dist/3~101.js +1786 -0
  4. package/dist/3~335.js +26 -0
  5. package/dist/3~395.js +74 -0
  6. package/dist/_private/react/index.js +2 -0
  7. package/dist/_private/react/reconciler.js +169 -0
  8. package/dist/_private/react/render.js +105 -0
  9. package/dist/cli/config/loadConfigFile.d.ts +6 -0
  10. package/dist/cli/config.d.ts +2 -0
  11. package/dist/cli/index.d.ts +1 -0
  12. package/dist/cli.js +259 -0
  13. package/dist/eject-theme/components/Badge/index.scss +52 -0
  14. package/dist/eject-theme/components/Badge/index.tsx +65 -0
  15. package/dist/eject-theme/components/Banner/index.scss +50 -0
  16. package/dist/eject-theme/components/Banner/index.tsx +119 -0
  17. package/dist/eject-theme/components/Button/index.scss +68 -0
  18. package/dist/eject-theme/components/Button/index.tsx +49 -0
  19. package/dist/eject-theme/components/Callout/index.scss +262 -0
  20. package/dist/eject-theme/components/Callout/index.tsx +47 -0
  21. package/dist/eject-theme/components/CodeBlock/index.scss +92 -0
  22. package/dist/eject-theme/components/CodeBlock/index.tsx +100 -0
  23. package/dist/eject-theme/components/CodeBlockRuntime/index.tsx +108 -0
  24. package/dist/eject-theme/components/CodeButtonGroup/CopyCodeButton.scss +23 -0
  25. package/dist/eject-theme/components/CodeButtonGroup/CopyCodeButton.tsx +75 -0
  26. package/dist/eject-theme/components/CodeButtonGroup/index.scss +62 -0
  27. package/dist/eject-theme/components/CodeButtonGroup/index.tsx +75 -0
  28. package/dist/eject-theme/components/DocContent/FallbackHeading.tsx +43 -0
  29. package/dist/eject-theme/components/DocContent/doc.scss +284 -0
  30. package/dist/eject-theme/components/DocContent/docComponents/a.tsx +6 -0
  31. package/dist/eject-theme/components/DocContent/docComponents/code.tsx +5 -0
  32. package/dist/eject-theme/components/DocContent/docComponents/hr.tsx +5 -0
  33. package/dist/eject-theme/components/DocContent/docComponents/img.tsx +6 -0
  34. package/dist/eject-theme/components/DocContent/docComponents/index.tsx +37 -0
  35. package/dist/eject-theme/components/DocContent/docComponents/list.tsx +13 -0
  36. package/dist/eject-theme/components/DocContent/docComponents/paragraph.tsx +13 -0
  37. package/dist/eject-theme/components/DocContent/docComponents/pre.tsx +27 -0
  38. package/dist/eject-theme/components/DocContent/docComponents/table.tsx +17 -0
  39. package/dist/eject-theme/components/DocContent/docComponents/title.tsx +32 -0
  40. package/dist/eject-theme/components/DocContent/index.tsx +39 -0
  41. package/dist/eject-theme/components/DocFooter/index.scss +14 -0
  42. package/dist/eject-theme/components/DocFooter/index.tsx +20 -0
  43. package/dist/eject-theme/components/EditLink/index.scss +11 -0
  44. package/dist/eject-theme/components/EditLink/index.tsx +19 -0
  45. package/dist/eject-theme/components/EditLink/useEditLink.ts +28 -0
  46. package/dist/eject-theme/components/HomeBackground/index.scss +14 -0
  47. package/dist/eject-theme/components/HomeBackground/index.tsx +18 -0
  48. package/dist/eject-theme/components/HomeBackground/useNavTransparent.tsx +44 -0
  49. package/dist/eject-theme/components/HomeFeature/index.scss +116 -0
  50. package/dist/eject-theme/components/HomeFeature/index.tsx +85 -0
  51. package/dist/eject-theme/components/HomeFeature/useCardAnimation.tsx +125 -0
  52. package/dist/eject-theme/components/HomeFooter/index.scss +23 -0
  53. package/dist/eject-theme/components/HomeFooter/index.tsx +23 -0
  54. package/dist/eject-theme/components/HomeHero/index.scss +155 -0
  55. package/dist/eject-theme/components/HomeHero/index.tsx +118 -0
  56. package/dist/eject-theme/components/HoverGroup/index.scss +78 -0
  57. package/dist/eject-theme/components/HoverGroup/index.tsx +59 -0
  58. package/dist/eject-theme/components/HoverGroup/useHoverGroup.tsx +68 -0
  59. package/dist/eject-theme/components/LastUpdated/index.scss +7 -0
  60. package/dist/eject-theme/components/LastUpdated/index.tsx +18 -0
  61. package/dist/eject-theme/components/Link/index.scss +3 -0
  62. package/dist/eject-theme/components/Link/index.tsx +121 -0
  63. package/dist/eject-theme/components/Link/useLinkNavigate.ts +94 -0
  64. package/dist/eject-theme/components/Nav/NavMenu.scss +93 -0
  65. package/dist/eject-theme/components/Nav/NavMenu.tsx +150 -0
  66. package/dist/eject-theme/components/Nav/NavTitle.tsx +59 -0
  67. package/dist/eject-theme/components/Nav/hooks.tsx +170 -0
  68. package/dist/eject-theme/components/Nav/index.scss +101 -0
  69. package/dist/eject-theme/components/Nav/index.tsx +56 -0
  70. package/dist/eject-theme/components/NavHamburger/index.scss +35 -0
  71. package/dist/eject-theme/components/NavHamburger/index.tsx +63 -0
  72. package/dist/eject-theme/components/NavHamburger/useNavScreen.ts +43 -0
  73. package/dist/eject-theme/components/NavScreen/NavScreenAppearance.scss +26 -0
  74. package/dist/eject-theme/components/NavScreen/NavScreenAppearance.tsx +23 -0
  75. package/dist/eject-theme/components/NavScreen/NavScreenLangs.scss +44 -0
  76. package/dist/eject-theme/components/NavScreen/NavScreenLangs.tsx +46 -0
  77. package/dist/eject-theme/components/NavScreen/NavScreenMenu.scss +5 -0
  78. package/dist/eject-theme/components/NavScreen/NavScreenMenu.tsx +13 -0
  79. package/dist/eject-theme/components/NavScreen/NavScreenMenuItem.scss +59 -0
  80. package/dist/eject-theme/components/NavScreen/NavScreenMenuItem.tsx +149 -0
  81. package/dist/eject-theme/components/NavScreen/NavScreenMenuOthers.tsx +26 -0
  82. package/dist/eject-theme/components/NavScreen/NavScreenVersions.scss +49 -0
  83. package/dist/eject-theme/components/NavScreen/NavScreenVersions.tsx +48 -0
  84. package/dist/eject-theme/components/NavScreen/index.scss +37 -0
  85. package/dist/eject-theme/components/NavScreen/index.tsx +66 -0
  86. package/dist/eject-theme/components/Outline/ScrollToTop.scss +13 -0
  87. package/dist/eject-theme/components/Outline/ScrollToTop.tsx +51 -0
  88. package/dist/eject-theme/components/Outline/index.scss +59 -0
  89. package/dist/eject-theme/components/Outline/index.tsx +35 -0
  90. package/dist/eject-theme/components/Overview/OverviewGroup.scss +132 -0
  91. package/dist/eject-theme/components/Overview/OverviewGroup.tsx +76 -0
  92. package/dist/eject-theme/components/Overview/icons/plugin.svg +3 -0
  93. package/dist/eject-theme/components/Overview/index.scss +75 -0
  94. package/dist/eject-theme/components/Overview/index.tsx +260 -0
  95. package/dist/eject-theme/components/Overview/utils.ts +94 -0
  96. package/dist/eject-theme/components/PackageManagerTabs/icons/Bun.tsx +101 -0
  97. package/dist/eject-theme/components/PackageManagerTabs/icons/Deno.tsx +18 -0
  98. package/dist/eject-theme/components/PackageManagerTabs/icons/Npm.tsx +16 -0
  99. package/dist/eject-theme/components/PackageManagerTabs/icons/Pnpm.tsx +22 -0
  100. package/dist/eject-theme/components/PackageManagerTabs/icons/Yarn.tsx +18 -0
  101. package/dist/eject-theme/components/PackageManagerTabs/index.tsx +260 -0
  102. package/dist/eject-theme/components/PageTabs/index.scss +60 -0
  103. package/dist/eject-theme/components/PageTabs/index.tsx +181 -0
  104. package/dist/eject-theme/components/PrevNextPage/index.scss +52 -0
  105. package/dist/eject-theme/components/PrevNextPage/index.tsx +55 -0
  106. package/dist/eject-theme/components/ReadPercent/ProgressCircle.tsx +57 -0
  107. package/dist/eject-theme/components/ReadPercent/index.scss +3 -0
  108. package/dist/eject-theme/components/ReadPercent/index.tsx +19 -0
  109. package/dist/eject-theme/components/ReadPercent/useReadPercent.ts +37 -0
  110. package/dist/eject-theme/components/Search/NoSearchResult.scss +20 -0
  111. package/dist/eject-theme/components/Search/NoSearchResult.tsx +20 -0
  112. package/dist/eject-theme/components/Search/SearchButton.scss +67 -0
  113. package/dist/eject-theme/components/Search/SearchButton.tsx +44 -0
  114. package/dist/eject-theme/components/Search/SearchPanel.scss +122 -0
  115. package/dist/eject-theme/components/Search/SearchPanel.tsx +556 -0
  116. package/dist/eject-theme/components/Search/SuggestItem.scss +95 -0
  117. package/dist/eject-theme/components/Search/SuggestItem.tsx +144 -0
  118. package/dist/eject-theme/components/Search/index.tsx +15 -0
  119. package/dist/eject-theme/components/Search/logic/Provider.ts +42 -0
  120. package/dist/eject-theme/components/Search/logic/providers/LocalProvider.ts +223 -0
  121. package/dist/eject-theme/components/Search/logic/search.ts +316 -0
  122. package/dist/eject-theme/components/Search/logic/types.ts +76 -0
  123. package/dist/eject-theme/components/Search/logic/util.test.ts +21 -0
  124. package/dist/eject-theme/components/Search/logic/util.ts +124 -0
  125. package/dist/eject-theme/components/Sidebar/SidebarDivider.scss +11 -0
  126. package/dist/eject-theme/components/Sidebar/SidebarDivider.tsx +23 -0
  127. package/dist/eject-theme/components/Sidebar/SidebarGroup.scss +3 -0
  128. package/dist/eject-theme/components/Sidebar/SidebarGroup.tsx +148 -0
  129. package/dist/eject-theme/components/Sidebar/SidebarItem.scss +89 -0
  130. package/dist/eject-theme/components/Sidebar/SidebarItem.tsx +131 -0
  131. package/dist/eject-theme/components/Sidebar/SidebarSectionHeader.scss +24 -0
  132. package/dist/eject-theme/components/Sidebar/SidebarSectionHeader.tsx +21 -0
  133. package/dist/eject-theme/components/Sidebar/index.tsx +89 -0
  134. package/dist/eject-theme/components/Sidebar/utils.ts +40 -0
  135. package/dist/eject-theme/components/SidebarMenu/index.scss +45 -0
  136. package/dist/eject-theme/components/SidebarMenu/index.tsx +137 -0
  137. package/dist/eject-theme/components/SidebarMenu/useClickOutside.ts +31 -0
  138. package/dist/eject-theme/components/SidebarMenu/useSidebarMenu.tsx +55 -0
  139. package/dist/eject-theme/components/SocialLinks/SocialLink.tsx +96 -0
  140. package/dist/eject-theme/components/SocialLinks/index.scss +39 -0
  141. package/dist/eject-theme/components/SocialLinks/index.tsx +67 -0
  142. package/dist/eject-theme/components/SourceCode/index.scss +34 -0
  143. package/dist/eject-theme/components/SourceCode/index.tsx +25 -0
  144. package/dist/eject-theme/components/Steps/index.scss +34 -0
  145. package/dist/eject-theme/components/Steps/index.tsx +6 -0
  146. package/dist/eject-theme/components/SvgWrapper/index.tsx +20 -0
  147. package/dist/eject-theme/components/SwitchAppearance/global.scss +15 -0
  148. package/dist/eject-theme/components/SwitchAppearance/index.scss +36 -0
  149. package/dist/eject-theme/components/SwitchAppearance/index.tsx +103 -0
  150. package/dist/eject-theme/components/Tabs/index.scss +88 -0
  151. package/dist/eject-theme/components/Tabs/index.tsx +210 -0
  152. package/dist/eject-theme/components/Tag/index.tsx +27 -0
  153. package/dist/eject-theme/components/Toc/TocItem.scss +35 -0
  154. package/dist/eject-theme/components/Toc/TocItem.tsx +53 -0
  155. package/dist/eject-theme/components/Toc/index.tsx +22 -0
  156. package/dist/index.d.ts +10 -192
  157. package/dist/index.js +2471 -1126
  158. package/dist/index.js.LICENSE.txt +10 -0
  159. package/dist/loader.js +38 -393
  160. package/dist/node/PluginDriver.d.ts +31 -0
  161. package/dist/node/auto-nav-sidebar/fixtures/docs/guide/c.d.ts +2 -0
  162. package/dist/node/auto-nav-sidebar/fixtures/docs-locales/en/guide/c.d.ts +2 -0
  163. package/dist/node/auto-nav-sidebar/fixtures/docs-locales/zh/guide/c.d.ts +2 -0
  164. package/dist/node/auto-nav-sidebar/index.d.ts +3 -0
  165. package/dist/node/auto-nav-sidebar/locales.d.ts +12 -0
  166. package/dist/node/auto-nav-sidebar/locales.test.d.ts +1 -0
  167. package/dist/node/auto-nav-sidebar/normalize.d.ts +3 -0
  168. package/dist/node/auto-nav-sidebar/type.d.ts +72 -0
  169. package/dist/node/auto-nav-sidebar/utils.d.ts +9 -0
  170. package/dist/node/auto-nav-sidebar/walk.d.ts +5 -0
  171. package/dist/node/auto-nav-sidebar/walk.test.d.ts +1 -0
  172. package/dist/node/build.d.ts +8 -0
  173. package/dist/node/constants.d.ts +20 -0
  174. package/dist/node/dev.d.ts +14 -0
  175. package/dist/node/eject.d.ts +13 -0
  176. package/dist/node/index.d.ts +5 -0
  177. package/dist/node/initRsbuild.d.ts +5 -0
  178. package/dist/node/last-updated/index.d.ts +5 -0
  179. package/dist/node/logger/hint.d.ts +19 -0
  180. package/dist/node/mdx/loader.d.ts +3 -0
  181. package/dist/node/mdx/options.d.ts +14 -0
  182. package/dist/node/mdx/processor.d.ts +20 -0
  183. package/dist/node/mdx/rehypePlugins/codeMeta.d.ts +3 -0
  184. package/dist/node/mdx/rehypePlugins/headerAnchor.d.ts +8 -0
  185. package/dist/node/mdx/rehypePlugins/headerAnchor.test.d.ts +1 -0
  186. package/dist/node/mdx/rehypePlugins/shiki.d.ts +4 -0
  187. package/dist/node/mdx/rehypePlugins/transformers/add-lang.d.ts +6 -0
  188. package/dist/node/mdx/rehypePlugins/transformers/add-line-numbers.d.ts +13 -0
  189. package/dist/node/mdx/rehypePlugins/transformers/add-title.d.ts +6 -0
  190. package/dist/node/mdx/rehypePlugins/transformers/add-wrap-code.d.ts +13 -0
  191. package/dist/node/mdx/rehypePlugins/transformers/index.d.ts +5 -0
  192. package/dist/node/mdx/rehypePlugins/transformers/meta-highlight.d.ts +25 -0
  193. package/dist/node/mdx/remarkPlugins/builtin.d.ts +10 -0
  194. package/dist/node/mdx/remarkPlugins/containerSyntax.d.ts +23 -0
  195. package/dist/node/mdx/remarkPlugins/containerSyntax.test.d.ts +1 -0
  196. package/dist/node/mdx/remarkPlugins/fileCodeBlock.d.ts +9 -0
  197. package/dist/node/mdx/remarkPlugins/fileCodeBlock.test.d.ts +1 -0
  198. package/dist/node/mdx/remarkPlugins/image.d.ts +3 -0
  199. package/dist/node/mdx/remarkPlugins/image.test.d.ts +1 -0
  200. package/dist/node/mdx/remarkPlugins/link.d.ts +16 -0
  201. package/dist/node/mdx/remarkPlugins/link.test.d.ts +1 -0
  202. package/dist/node/mdx/remarkPlugins/toc.d.ts +12 -0
  203. package/dist/node/mdx/types.d.ts +21 -0
  204. package/dist/node/medium-zoom/index.d.ts +11 -0
  205. package/dist/node/route/RoutePage.d.ts +17 -0
  206. package/dist/node/route/RouteService.d.ts +52 -0
  207. package/dist/node/route/RouteService.test.d.ts +1 -0
  208. package/dist/node/route/extractPageData.d.ts +12 -0
  209. package/dist/node/route/extractPageData.test.d.ts +1 -0
  210. package/dist/node/route/fixtures/basic/guide/c.d.ts +2 -0
  211. package/dist/node/route/normalizeRoutePath.d.ts +13 -0
  212. package/dist/node/route/normalizeRoutePath.test.d.ts +1 -0
  213. package/dist/node/runtimeModule/DEFAULT_I18N_TEXT.d.ts +128 -0
  214. package/dist/node/runtimeModule/globalStyles.d.ts +2 -0
  215. package/dist/node/runtimeModule/globalUIComponents.d.ts +2 -0
  216. package/dist/node/runtimeModule/i18n.d.ts +8 -0
  217. package/dist/node/runtimeModule/i18n.test.d.ts +1 -0
  218. package/dist/node/runtimeModule/pageData/createPageData.d.ts +8 -0
  219. package/dist/node/runtimeModule/pageData/rsbuildPlugin.d.ts +3 -0
  220. package/dist/node/runtimeModule/routeList.d.ts +2 -0
  221. package/dist/node/runtimeModule/searchHooks.d.ts +2 -0
  222. package/dist/node/runtimeModule/siteData/createSiteData.d.ts +4 -0
  223. package/dist/node/runtimeModule/siteData/normalizeThemeConfig.d.ts +2 -0
  224. package/dist/node/runtimeModule/siteData/rsbuildPlugin.d.ts +2 -0
  225. package/dist/node/runtimeModule/socialLinks.d.ts +2 -0
  226. package/dist/node/runtimeModule/types.d.ts +22 -0
  227. package/dist/node/serve.d.ts +10 -0
  228. package/dist/node/ssg/renderHtmlTemplate.d.ts +2 -0
  229. package/dist/node/ssg/renderPage.d.ts +2 -0
  230. package/dist/node/ssg/renderPageWorker.d.ts +9 -0
  231. package/dist/node/ssg/renderPages.d.ts +4 -0
  232. package/dist/node/ssg/rsbuildPluginCSR.d.ts +7 -0
  233. package/dist/node/ssg/rsbuildPluginSSG.d.ts +7 -0
  234. package/dist/node/ssg/ssgEnv.d.ts +10 -0
  235. package/dist/node/ssg-md/llms/emitLlmsTxt.d.ts +3 -0
  236. package/dist/node/ssg-md/llms/llmsTxt.d.ts +10 -0
  237. package/dist/node/ssg-md/react/index.d.ts +1 -0
  238. package/dist/node/ssg-md/react/reconciler.d.ts +18 -0
  239. package/dist/node/ssg-md/react/render.d.ts +1 -0
  240. package/dist/node/ssg-md/react/render.test.d.ts +1 -0
  241. package/dist/node/ssg-md/remarkSplitMdx.d.ts +39 -0
  242. package/dist/node/ssg-md/remarkSplitMdx.test.d.ts +4 -0
  243. package/dist/node/ssg-md/renderPage.d.ts +2 -0
  244. package/dist/node/ssg-md/renderPages.d.ts +2 -0
  245. package/dist/node/ssg-md/rsbuildPluginSSGMD.d.ts +7 -0
  246. package/dist/node/utils/applyReplaceRules.d.ts +2 -0
  247. package/dist/node/utils/checkLanguageParity.d.ts +5 -0
  248. package/dist/node/utils/checkLanguageParity.test.d.ts +1 -0
  249. package/dist/node/utils/createHash.d.ts +1 -0
  250. package/dist/node/utils/detectCustomIcon.d.ts +1 -0
  251. package/dist/node/utils/detectReactVersion.d.ts +3 -0
  252. package/dist/node/utils/escapeHeadingIds.d.ts +5 -0
  253. package/dist/node/utils/flattenMdxContent.d.ts +5 -0
  254. package/dist/node/utils/fs.d.ts +2 -0
  255. package/dist/node/utils/getImportAstNode.d.ts +3 -0
  256. package/dist/node/utils/getPageKey.d.ts +1 -0
  257. package/dist/node/utils/getSocialIcons.d.ts +2 -0
  258. package/dist/node/utils/index.d.ts +9 -0
  259. package/dist/node/utils/normalizePath.d.ts +3 -0
  260. package/dist/processor.js +4539 -0
  261. package/dist/renderPageWorker.js +196 -0
  262. package/dist/runtime/App.d.ts +0 -1
  263. package/dist/runtime/App.js +18 -18
  264. package/dist/runtime/ClientApp.d.ts +2 -2
  265. package/dist/runtime/ClientApp.js +21 -16
  266. package/dist/runtime/csrClientEntry.js +5 -5
  267. package/dist/runtime/initPageData.d.ts +3 -3
  268. package/dist/runtime/initPageData.js +33 -39
  269. package/dist/runtime/ssrClientEntry.js +17 -9
  270. package/dist/runtime/ssrMdServerEntry.d.ts +5 -0
  271. package/dist/runtime/ssrMdServerEntry.js +39 -0
  272. package/dist/runtime/ssrServerEntry.d.ts +2 -4
  273. package/dist/runtime/ssrServerEntry.js +40 -20
  274. package/dist/runtime.d.ts +2 -0
  275. package/dist/runtime.js +3 -0
  276. package/dist/shiki-transformers.d.ts +1 -0
  277. package/dist/shiki-transformers.js +120 -0
  278. package/dist/shiki-transformers.js.LICENSE.txt +5 -0
  279. package/dist/theme/assets/arrow-down.js +14 -0
  280. package/dist/theme/assets/arrow-right.js +14 -0
  281. package/dist/theme/assets/close.js +15 -0
  282. package/dist/theme/assets/copy.js +21 -0
  283. package/dist/theme/assets/down.js +14 -0
  284. package/dist/theme/assets/empty.js +24 -0
  285. package/dist/theme/assets/file.js +31 -0
  286. package/dist/theme/assets/github.js +13 -0
  287. package/dist/theme/assets/gitlab.js +13 -0
  288. package/dist/theme/assets/header.js +15 -0
  289. package/dist/theme/assets/jump.js +15 -0
  290. package/dist/theme/assets/loading.js +50 -0
  291. package/dist/theme/assets/menu.js +14 -0
  292. package/dist/theme/assets/moon.js +33 -0
  293. package/dist/theme/assets/right.js +14 -0
  294. package/dist/theme/assets/search.js +16 -0
  295. package/dist/theme/assets/small-menu.js +19 -0
  296. package/dist/theme/assets/success.js +14 -0
  297. package/dist/theme/assets/sun.js +16 -0
  298. package/dist/theme/assets/title.js +15 -0
  299. package/dist/theme/assets/translator.js +14 -0
  300. package/dist/theme/assets/wrap.js +15 -0
  301. package/dist/theme/assets/wrapped.js +15 -0
  302. package/dist/theme/components/Badge/index.css +53 -0
  303. package/dist/theme/components/Badge/index.d.ts +44 -0
  304. package/dist/theme/components/Badge/index.js +11 -0
  305. package/dist/theme/components/Banner/index.css +47 -0
  306. package/dist/theme/components/Banner/index.d.ts +48 -0
  307. package/dist/theme/components/Banner/index.js +48 -0
  308. package/dist/theme/components/Button/index.css +63 -0
  309. package/dist/theme/components/Button/index.d.ts +15 -0
  310. package/dist/theme/components/Button/index.js +16 -0
  311. package/dist/theme/components/Callout/index.css +234 -0
  312. package/dist/theme/components/Callout/index.d.ts +26 -0
  313. package/dist/theme/components/Callout/index.js +33 -0
  314. package/dist/theme/components/CodeBlock/index.css +90 -0
  315. package/dist/theme/components/CodeBlock/index.d.ts +54 -0
  316. package/dist/theme/components/CodeBlock/index.js +32 -0
  317. package/dist/theme/components/CodeBlockRuntime/index.d.ts +14 -0
  318. package/dist/theme/components/CodeBlockRuntime/index.js +64 -0
  319. package/dist/theme/components/CodeButtonGroup/CopyCodeButton.css +24 -0
  320. package/dist/theme/components/CodeButtonGroup/CopyCodeButton.d.ts +4 -0
  321. package/dist/theme/components/CodeButtonGroup/CopyCodeButton.js +52 -0
  322. package/dist/theme/components/CodeButtonGroup/index.css +61 -0
  323. package/dist/theme/components/CodeButtonGroup/index.d.ts +20 -0
  324. package/dist/theme/components/CodeButtonGroup/index.js +51 -0
  325. package/dist/theme/components/DocContent/FallbackHeading.d.ts +11 -0
  326. package/dist/theme/components/DocContent/FallbackHeading.js +32 -0
  327. package/dist/theme/components/DocContent/doc.css +231 -0
  328. package/dist/theme/components/DocContent/docComponents/a.d.ts +2 -0
  329. package/dist/theme/components/DocContent/docComponents/a.js +6 -0
  330. package/dist/theme/components/DocContent/docComponents/code.d.ts +2 -0
  331. package/dist/theme/components/DocContent/docComponents/code.js +7 -0
  332. package/dist/theme/components/DocContent/docComponents/hr.d.ts +2 -0
  333. package/dist/theme/components/DocContent/docComponents/hr.js +5 -0
  334. package/dist/theme/components/DocContent/docComponents/img.d.ts +2 -0
  335. package/dist/theme/components/DocContent/docComponents/img.js +7 -0
  336. package/dist/theme/components/DocContent/docComponents/index.d.ts +25 -0
  337. package/dist/theme/components/DocContent/docComponents/index.js +35 -0
  338. package/dist/theme/components/DocContent/docComponents/list.d.ts +4 -0
  339. package/dist/theme/components/DocContent/docComponents/list.js +11 -0
  340. package/dist/theme/components/DocContent/docComponents/paragraph.d.ts +4 -0
  341. package/dist/theme/components/DocContent/docComponents/paragraph.js +11 -0
  342. package/dist/theme/components/DocContent/docComponents/pre.d.ts +3 -0
  343. package/dist/theme/components/DocContent/docComponents/pre.js +16 -0
  344. package/dist/theme/components/DocContent/docComponents/table.d.ts +5 -0
  345. package/dist/theme/components/DocContent/docComponents/table.js +14 -0
  346. package/dist/theme/components/DocContent/docComponents/title.d.ts +7 -0
  347. package/dist/theme/components/DocContent/docComponents/title.js +45 -0
  348. package/dist/theme/components/DocContent/index.d.ts +6 -0
  349. package/dist/theme/components/DocContent/index.js +30 -0
  350. package/dist/theme/components/DocFooter/index.css +17 -0
  351. package/dist/theme/components/DocFooter/index.d.ts +2 -0
  352. package/dist/theme/components/DocFooter/index.js +26 -0
  353. package/dist/theme/components/EditLink/index.css +12 -0
  354. package/dist/theme/components/EditLink/index.d.ts +2 -0
  355. package/dist/theme/components/EditLink/index.js +15 -0
  356. package/dist/theme/components/EditLink/useEditLink.d.ts +4 -0
  357. package/dist/theme/components/EditLink/useEditLink.js +17 -0
  358. package/dist/theme/components/HomeBackground/index.css +13 -0
  359. package/dist/theme/components/HomeBackground/index.d.ts +3 -0
  360. package/dist/theme/components/HomeBackground/index.js +16 -0
  361. package/dist/theme/components/HomeBackground/useNavTransparent.d.ts +1 -0
  362. package/dist/theme/components/HomeBackground/useNavTransparent.js +35 -0
  363. package/dist/theme/components/HomeFeature/index.css +104 -0
  364. package/dist/theme/components/HomeFeature/index.d.ts +6 -0
  365. package/dist/theme/components/HomeFeature/index.js +75 -0
  366. package/dist/theme/components/HomeFeature/useCardAnimation.d.ts +11 -0
  367. package/dist/theme/components/HomeFeature/useCardAnimation.js +103 -0
  368. package/dist/theme/components/HomeFooter/index.css +26 -0
  369. package/dist/theme/components/HomeFooter/index.d.ts +2 -0
  370. package/dist/theme/components/HomeFooter/index.js +20 -0
  371. package/dist/theme/components/HomeHero/index.css +164 -0
  372. package/dist/theme/components/HomeHero/index.d.ts +8 -0
  373. package/dist/theme/components/HomeHero/index.js +108 -0
  374. package/dist/theme/components/HoverGroup/index.css +67 -0
  375. package/dist/theme/components/HoverGroup/index.d.ts +16 -0
  376. package/dist/theme/components/HoverGroup/index.js +29 -0
  377. package/dist/theme/components/HoverGroup/useHoverGroup.d.ts +14 -0
  378. package/dist/theme/components/HoverGroup/useHoverGroup.js +45 -0
  379. package/dist/theme/components/LastUpdated/index.css +8 -0
  380. package/dist/theme/components/LastUpdated/index.d.ts +2 -0
  381. package/dist/theme/components/LastUpdated/index.js +20 -0
  382. package/dist/theme/components/Link/index.css +4 -0
  383. package/dist/theme/components/Link/index.d.ts +18 -0
  384. package/dist/theme/components/Link/index.js +61 -0
  385. package/dist/theme/components/Link/useLinkNavigate.d.ts +12 -0
  386. package/dist/theme/components/Link/useLinkNavigate.js +59 -0
  387. package/dist/theme/components/Nav/NavMenu.css +95 -0
  388. package/dist/theme/components/Nav/NavMenu.d.ts +21 -0
  389. package/dist/theme/components/Nav/NavMenu.js +122 -0
  390. package/dist/theme/components/Nav/NavTitle.d.ts +1 -0
  391. package/dist/theme/components/Nav/NavTitle.js +57 -0
  392. package/dist/theme/components/Nav/hooks.d.ts +18 -0
  393. package/dist/theme/components/Nav/hooks.js +90 -0
  394. package/dist/theme/components/Nav/index.css +95 -0
  395. package/dist/theme/components/Nav/index.d.ts +9 -0
  396. package/dist/theme/components/Nav/index.js +51 -0
  397. package/dist/theme/components/NavHamburger/index.css +35 -0
  398. package/dist/theme/components/NavHamburger/index.d.ts +2 -0
  399. package/dist/theme/components/NavHamburger/index.js +65 -0
  400. package/dist/theme/components/NavHamburger/useNavScreen.d.ts +6 -0
  401. package/dist/theme/components/NavHamburger/useNavScreen.js +34 -0
  402. package/dist/theme/components/NavScreen/NavScreenAppearance.css +25 -0
  403. package/dist/theme/components/NavScreen/NavScreenAppearance.d.ts +2 -0
  404. package/dist/theme/components/NavScreen/NavScreenAppearance.js +27 -0
  405. package/dist/theme/components/NavScreen/NavScreenLangs.css +48 -0
  406. package/dist/theme/components/NavScreen/NavScreenLangs.d.ts +2 -0
  407. package/dist/theme/components/NavScreen/NavScreenLangs.js +52 -0
  408. package/dist/theme/components/NavScreen/NavScreenMenu.css +6 -0
  409. package/dist/theme/components/NavScreen/NavScreenMenu.d.ts +5 -0
  410. package/dist/theme/components/NavScreen/NavScreenMenu.js +11 -0
  411. package/dist/theme/components/NavScreen/NavScreenMenuItem.css +50 -0
  412. package/dist/theme/components/NavScreen/NavScreenMenuItem.d.ts +25 -0
  413. package/dist/theme/components/NavScreen/NavScreenMenuItem.js +110 -0
  414. package/dist/theme/components/NavScreen/NavScreenMenuOthers.d.ts +2 -0
  415. package/dist/theme/components/NavScreen/NavScreenMenuOthers.js +29 -0
  416. package/dist/theme/components/NavScreen/NavScreenVersions.css +51 -0
  417. package/dist/theme/components/NavScreen/NavScreenVersions.d.ts +2 -0
  418. package/dist/theme/components/NavScreen/NavScreenVersions.js +47 -0
  419. package/dist/theme/components/NavScreen/index.css +42 -0
  420. package/dist/theme/components/NavScreen/index.d.ts +7 -0
  421. package/dist/theme/components/NavScreen/index.js +63 -0
  422. package/dist/theme/components/Outline/ScrollToTop.css +14 -0
  423. package/dist/theme/components/Outline/ScrollToTop.d.ts +2 -0
  424. package/dist/theme/components/Outline/ScrollToTop.js +54 -0
  425. package/dist/theme/components/Outline/index.css +61 -0
  426. package/dist/theme/components/Outline/index.d.ts +2 -0
  427. package/dist/theme/components/Outline/index.js +38 -0
  428. package/dist/theme/components/Overview/OverviewGroup.css +124 -0
  429. package/dist/theme/components/Overview/OverviewGroup.d.ts +18 -0
  430. package/dist/theme/components/Overview/OverviewGroup.js +58 -0
  431. package/dist/theme/components/Overview/icons/plugin.js +17 -0
  432. package/dist/theme/components/Overview/index.css +70 -0
  433. package/dist/theme/components/Overview/index.d.ts +8 -0
  434. package/dist/theme/components/Overview/index.js +141 -0
  435. package/dist/theme/components/Overview/utils.d.ts +6 -0
  436. package/dist/theme/components/Overview/utils.js +34 -0
  437. package/dist/theme/components/PackageManagerTabs/icons/Bun.d.ts +2 -0
  438. package/dist/theme/components/PackageManagerTabs/icons/Bun.js +137 -0
  439. package/dist/theme/components/PackageManagerTabs/icons/Deno.d.ts +2 -0
  440. package/dist/theme/components/PackageManagerTabs/icons/Deno.js +15 -0
  441. package/dist/theme/components/PackageManagerTabs/icons/Npm.d.ts +2 -0
  442. package/dist/theme/components/PackageManagerTabs/icons/Npm.js +21 -0
  443. package/dist/theme/components/PackageManagerTabs/icons/Pnpm.d.ts +2 -0
  444. package/dist/theme/components/PackageManagerTabs/icons/Pnpm.js +21 -0
  445. package/dist/theme/components/PackageManagerTabs/icons/Yarn.d.ts +2 -0
  446. package/dist/theme/components/PackageManagerTabs/icons/Yarn.js +22 -0
  447. package/dist/theme/components/PackageManagerTabs/index.d.ts +31 -0
  448. package/dist/theme/components/PackageManagerTabs/index.js +163 -0
  449. package/dist/theme/components/PageTabs/index.css +37 -0
  450. package/dist/theme/components/PageTabs/index.d.ts +23 -0
  451. package/dist/theme/components/PageTabs/index.js +102 -0
  452. package/dist/theme/components/PrevNextPage/index.css +59 -0
  453. package/dist/theme/components/PrevNextPage/index.d.ts +2 -0
  454. package/dist/theme/components/PrevNextPage/index.js +64 -0
  455. package/dist/theme/components/ReadPercent/ProgressCircle.d.ts +12 -0
  456. package/dist/theme/components/ReadPercent/ProgressCircle.js +41 -0
  457. package/dist/theme/components/ReadPercent/index.css +4 -0
  458. package/dist/theme/components/ReadPercent/index.d.ts +4 -0
  459. package/dist/theme/components/ReadPercent/index.js +12 -0
  460. package/dist/theme/components/ReadPercent/useReadPercent.d.ts +1 -0
  461. package/dist/theme/components/ReadPercent/useReadPercent.js +36 -0
  462. package/dist/theme/components/Search/NoSearchResult.css +21 -0
  463. package/dist/theme/components/Search/NoSearchResult.d.ts +4 -0
  464. package/dist/theme/components/Search/NoSearchResult.js +36 -0
  465. package/dist/theme/components/Search/SearchButton.css +70 -0
  466. package/dist/theme/components/Search/SearchButton.d.ts +5 -0
  467. package/dist/theme/components/Search/SearchButton.js +58 -0
  468. package/dist/theme/components/Search/SearchPanel.css +116 -0
  469. package/dist/theme/components/Search/SearchPanel.d.ts +6 -0
  470. package/dist/theme/components/Search/SearchPanel.js +380 -0
  471. package/dist/theme/components/Search/SuggestItem.css +90 -0
  472. package/dist/theme/components/Search/SuggestItem.d.ts +11 -0
  473. package/dist/theme/components/Search/SuggestItem.js +115 -0
  474. package/dist/theme/components/Search/index.d.ts +1 -0
  475. package/dist/theme/components/Search/index.js +21 -0
  476. package/dist/theme/components/Search/logic/Provider.d.ts +29 -0
  477. package/dist/theme/components/Search/logic/Provider.js +13 -0
  478. package/dist/theme/components/Search/logic/providers/LocalProvider.d.ts +16 -0
  479. package/dist/theme/components/Search/logic/providers/LocalProvider.js +125 -0
  480. package/dist/theme/components/Search/logic/search.d.ts +11 -0
  481. package/dist/theme/components/Search/logic/search.js +191 -0
  482. package/dist/theme/components/Search/logic/types.d.ts +59 -0
  483. package/dist/theme/components/Search/logic/types.js +6 -0
  484. package/dist/theme/components/Search/logic/util.d.ts +16 -0
  485. package/dist/theme/components/Search/logic/util.js +74 -0
  486. package/dist/theme/components/Search/logic/util.test.d.ts +1 -0
  487. package/dist/theme/components/Search/logic/util.test.js +51 -0
  488. package/dist/theme/components/Sidebar/SidebarDivider.css +12 -0
  489. package/dist/theme/components/Sidebar/SidebarDivider.d.ts +6 -0
  490. package/dist/theme/components/Sidebar/SidebarDivider.js +13 -0
  491. package/dist/theme/components/Sidebar/SidebarGroup.css +4 -0
  492. package/dist/theme/components/Sidebar/SidebarGroup.d.ts +11 -0
  493. package/dist/theme/components/Sidebar/SidebarGroup.js +98 -0
  494. package/dist/theme/components/Sidebar/SidebarItem.css +79 -0
  495. package/dist/theme/components/Sidebar/SidebarItem.d.ts +21 -0
  496. package/dist/theme/components/Sidebar/SidebarItem.js +85 -0
  497. package/dist/theme/components/Sidebar/SidebarSectionHeader.css +25 -0
  498. package/dist/theme/components/Sidebar/SidebarSectionHeader.d.ts +5 -0
  499. package/dist/theme/components/Sidebar/SidebarSectionHeader.js +23 -0
  500. package/dist/theme/components/Sidebar/index.d.ts +6 -0
  501. package/dist/theme/components/Sidebar/index.js +45 -0
  502. package/dist/theme/components/Sidebar/utils.d.ts +5 -0
  503. package/dist/theme/components/Sidebar/utils.js +5 -0
  504. package/dist/theme/components/SidebarMenu/index.css +43 -0
  505. package/dist/theme/components/SidebarMenu/index.d.ts +7 -0
  506. package/dist/theme/components/SidebarMenu/index.js +103 -0
  507. package/dist/theme/components/SidebarMenu/useClickOutside.d.ts +2 -0
  508. package/dist/theme/components/SidebarMenu/useClickOutside.js +25 -0
  509. package/dist/theme/components/SidebarMenu/useSidebarMenu.d.ts +8 -0
  510. package/dist/theme/components/SidebarMenu/useSidebarMenu.js +55 -0
  511. package/dist/theme/components/SocialLinks/SocialLink.d.ts +11 -0
  512. package/dist/theme/components/SocialLinks/SocialLink.js +76 -0
  513. package/dist/theme/components/SocialLinks/index.css +44 -0
  514. package/dist/theme/components/SocialLinks/index.d.ts +5 -0
  515. package/dist/theme/components/SocialLinks/index.js +43 -0
  516. package/dist/theme/components/SourceCode/index.css +31 -0
  517. package/dist/theme/components/SourceCode/index.d.ts +7 -0
  518. package/dist/theme/components/SourceCode/index.js +31 -0
  519. package/dist/theme/components/Steps/index.css +35 -0
  520. package/dist/theme/components/Steps/index.d.ts +5 -0
  521. package/dist/theme/components/Steps/index.js +9 -0
  522. package/dist/theme/components/SvgWrapper/index.d.ts +8 -0
  523. package/dist/theme/components/SvgWrapper/index.js +13 -0
  524. package/dist/theme/components/SwitchAppearance/global.css +26 -0
  525. package/dist/theme/components/SwitchAppearance/index.css +27 -0
  526. package/dist/theme/components/SwitchAppearance/index.d.ts +5 -0
  527. package/dist/theme/components/SwitchAppearance/index.js +82 -0
  528. package/dist/theme/components/Tabs/index.css +84 -0
  529. package/dist/theme/components/Tabs/index.d.ts +36 -0
  530. package/dist/theme/components/Tabs/index.js +86 -0
  531. package/dist/theme/components/Tag/index.d.ts +3 -0
  532. package/dist/theme/components/Tag/index.js +26 -0
  533. package/dist/theme/components/Toc/TocItem.css +33 -0
  534. package/dist/theme/components/Toc/TocItem.d.ts +7 -0
  535. package/dist/theme/components/Toc/TocItem.js +38 -0
  536. package/dist/theme/components/Toc/index.d.ts +1 -0
  537. package/dist/theme/components/Toc/index.js +16 -0
  538. package/dist/theme/hooks/processTitleElement.d.ts +6 -0
  539. package/dist/theme/hooks/processTitleElement.js +22 -0
  540. package/dist/theme/hooks/useActiveAnchor.d.ts +8 -0
  541. package/dist/theme/hooks/useActiveAnchor.js +53 -0
  542. package/dist/theme/hooks/useDynamicToc.d.ts +11 -0
  543. package/dist/theme/hooks/useDynamicToc.js +110 -0
  544. package/dist/theme/index.d.ts +59 -0
  545. package/dist/theme/index.js +58 -0
  546. package/dist/theme/layout/DocLayout/index.css +191 -0
  547. package/dist/theme/layout/DocLayout/index.d.ts +16 -0
  548. package/dist/theme/layout/DocLayout/index.js +96 -0
  549. package/dist/theme/layout/HomeLayout/index.d.ts +9 -0
  550. package/dist/theme/layout/HomeLayout/index.js +21 -0
  551. package/dist/theme/layout/Layout/index.d.ts +12 -0
  552. package/dist/theme/layout/Layout/index.js +129 -0
  553. package/dist/theme/layout/NotFountLayout/index.css +56 -0
  554. package/dist/theme/layout/NotFountLayout/index.d.ts +2 -0
  555. package/dist/theme/layout/NotFountLayout/index.js +47 -0
  556. package/dist/theme/logic/mergeRefs.d.ts +1 -0
  557. package/dist/theme/logic/mergeRefs.js +9 -0
  558. package/dist/theme/logic/sideEffects.d.ts +1 -0
  559. package/dist/theme/logic/sideEffects.js +34 -0
  560. package/dist/theme/logic/useAppearance.d.ts +13 -0
  561. package/dist/theme/logic/useAppearance.js +64 -0
  562. package/dist/theme/logic/useFullTextSearch.d.ts +5 -0
  563. package/dist/theme/logic/useFullTextSearch.js +29 -0
  564. package/dist/theme/logic/useHandler.d.ts +6 -0
  565. package/dist/theme/logic/useHandler.js +7 -0
  566. package/dist/theme/logic/useMediaQuery.d.ts +4 -0
  567. package/dist/theme/logic/useMediaQuery.js +14 -0
  568. package/dist/theme/logic/usePrevNextPage.d.ts +5 -0
  569. package/dist/theme/logic/usePrevNextPage.js +26 -0
  570. package/dist/theme/logic/useRedirect4FirstVisit.d.ts +5 -0
  571. package/dist/theme/logic/useRedirect4FirstVisit.js +31 -0
  572. package/dist/theme/logic/useStorageValue.d.ts +5 -0
  573. package/dist/theme/logic/useStorageValue.js +50 -0
  574. package/dist/theme/logic/utils.d.ts +29 -0
  575. package/dist/theme/logic/utils.js +30 -0
  576. package/dist/theme/styles/base.css +57 -0
  577. package/dist/theme/styles/index.d.ts +12 -0
  578. package/dist/theme/styles/index.js +9 -0
  579. package/dist/theme/styles/preflight.css +146 -0
  580. package/dist/theme/styles/scrollbar.css +34 -0
  581. package/dist/theme/styles/shiki.css +69 -0
  582. package/dist/theme/styles/vars/base-vars.css +51 -0
  583. package/dist/theme/styles/vars/brand-vars.css +9 -0
  584. package/dist/theme/styles/vars/code-vars.css +16 -0
  585. package/dist/theme/styles/vars/home-vars.css +14 -0
  586. package/dist/theme/styles/vars/shiki-vars.css +32 -0
  587. package/index.html +2 -2
  588. package/meta-json-schema.json +424 -0
  589. package/nav-json-schema.json +118 -0
  590. package/package.json +75 -45
  591. package/static/MediumZoom.css +5 -0
  592. package/static/MediumZoom.tsx +29 -0
  593. package/dist/loader.d.ts +0 -85
  594. package/runtime.ts +0 -1
  595. package/theme.ts +0 -1
package/dist/index.js CHANGED
@@ -1,219 +1,127 @@
1
- import __rslib_shim_module__ from 'module';
2
- const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
3
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_plugin_container_syntax_12d3c700__ from "@rspress/plugin-container-syntax";
1
+ /*! For license information please see index.js.LICENSE.txt */
4
2
  import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
5
- import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__ from "node:fs/promises";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
6
5
  import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
7
6
  import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
8
- import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_plugin_react_7b149ee4__ from "@rsbuild/plugin-react";
9
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__ from "@rspress/shared/logger";
10
- import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
11
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__ from "@rspress/shared/constants";
12
- import * as __WEBPACK_EXTERNAL_MODULE_tinyglobby__ from "tinyglobby";
13
- import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
14
- import * as __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__ from "rspack-plugin-virtual-module";
15
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__ from "@rspress/shared/node-utils";
16
- import * as __WEBPACK_EXTERNAL_MODULE_lodash_es_18c59938__ from "lodash-es";
17
- import * as __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__ from "node:crypto";
18
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_mdx_rs_d2f3021f__ from "@rspress/mdx-rs";
19
- import * as __WEBPACK_EXTERNAL_MODULE_html_to_text_2c51ed38__ from "html-to-text";
20
- import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
21
- import * as __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__ from "@mdx-js/mdx";
22
- import * as __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__ from "enhanced-resolve";
23
- import * as __WEBPACK_EXTERNAL_MODULE__unhead_react_server_7e85c952__ from "@unhead/react/server";
24
- import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/core";
25
- import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
26
- export * from "@rspress/shared";
27
- class PluginDriver {
28
- #config;
29
- #plugins;
30
- #isProd;
31
- constructor(config, isProd){
32
- this.#config = config;
33
- this.#isProd = isProd;
34
- this.#plugins = [];
7
+ import { matchPath } from "@rspress/runtime/server";
8
+ import { logger } from "@rspress/shared/logger";
9
+ import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
10
+ import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
11
+ import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
12
+ import picocolors from "picocolors";
13
+ import { glob } from "tinyglobby";
14
+ import { createRequire } from "node:module";
15
+ import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
16
+ import { chunk, groupBy } from "lodash-es";
17
+ import { compile } from "@rspress/mdx-rs";
18
+ import { htmlToText } from "html-to-text";
19
+ import { createProcessor } from "@mdx-js/mdx";
20
+ import { mergeRsbuildConfig as core_mergeRsbuildConfig, rspack as core_rspack } from "@rsbuild/core";
21
+ import { createHash } from "node:crypto";
22
+ import { createHead, transformHtmlTemplate } from "@unhead/react/server";
23
+ import { visit } from "unist-util-visit";
24
+ var __webpack_modules__ = {
25
+ "@rspress/shared": function(module) {
26
+ module.exports = __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__;
27
+ },
28
+ "node:fs": function(module) {
29
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
30
+ },
31
+ "node:os": function(module) {
32
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__;
33
+ },
34
+ "node:path": function(module) {
35
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
36
+ },
37
+ "node:url": function(module) {
38
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__;
35
39
  }
36
- async init() {
37
- this.clearPlugins();
38
- const config = this.#config;
39
- const markdownConfig = config.markdown || {};
40
- const themeConfig = config?.themeConfig || {};
41
- const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
42
- const mediumZoomConfig = config?.mediumZoom ?? true;
43
- const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
44
- if (enableLastUpdated) {
45
- const { pluginLastUpdated } = await import("@rspress/plugin-last-updated");
46
- this.addPlugin(pluginLastUpdated());
47
- }
48
- if (mediumZoomConfig) {
49
- const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
50
- this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
51
- }
52
- this.addPlugin((0, __WEBPACK_EXTERNAL_MODULE__rspress_plugin_container_syntax_12d3c700__.pluginContainerSyntax)());
53
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isDevDebugMode)()) {
54
- const SourceBuildPlugin = await import("@rspress/theme-default/node/source-build-plugin.js").then((r)=>r.SourceBuildPlugin, ()=>null);
55
- if (SourceBuildPlugin) this.addPlugin(SourceBuildPlugin());
56
- }
57
- const { pluginShiki } = await import("@rspress/plugin-shiki");
58
- (config.plugins || []).forEach((plugin)=>{
59
- this.addPlugin(plugin);
40
+ };
41
+ var __webpack_module_cache__ = {};
42
+ function __webpack_require__(moduleId) {
43
+ var cachedModule = __webpack_module_cache__[moduleId];
44
+ if (void 0 !== cachedModule) return cachedModule.exports;
45
+ var module = __webpack_module_cache__[moduleId] = {
46
+ exports: {}
47
+ };
48
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
49
+ return module.exports;
50
+ }
51
+ __webpack_require__.m = __webpack_modules__;
52
+ (()=>{
53
+ __webpack_require__.d = (exports, definition)=>{
54
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
55
+ enumerable: true,
56
+ get: definition[key]
60
57
  });
61
- this.addPlugin(pluginShiki(markdownConfig.shiki));
62
- if (!haveNavSidebarConfig) {
63
- const { pluginAutoNavSidebar } = await import("@rspress/plugin-auto-nav-sidebar");
64
- this.addPlugin(pluginAutoNavSidebar());
65
- }
66
- }
67
- addPlugin(plugin) {
68
- const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
69
- if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
70
- this.#plugins.push(plugin);
71
- }
72
- getPlugins() {
73
- return this.#plugins;
74
- }
75
- clearPlugins() {
76
- this.#plugins = [];
77
- }
78
- removePlugin(pluginName) {
79
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
80
- if (-1 !== index) this.#plugins.splice(index, 1);
81
- }
82
- async modifyConfig() {
83
- let config = this.#config;
84
- for(let i = 0; i < this.#plugins.length; i++){
85
- const plugin = this.#plugins[i];
86
- if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
87
- addPlugin: this.addPlugin.bind(this),
88
- removePlugin: (pluginName)=>{
89
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
90
- this.removePlugin(pluginName);
91
- if (index <= i && index > 0) i--;
92
- }
93
- }, this.#isProd);
58
+ };
59
+ })();
60
+ (()=>{
61
+ __webpack_require__.f = {};
62
+ __webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
63
+ __webpack_require__.f[key](chunkId, promises);
64
+ return promises;
65
+ }, []));
66
+ })();
67
+ (()=>{
68
+ __webpack_require__.u = (chunkId)=>"3~" + chunkId + ".js";
69
+ })();
70
+ (()=>{
71
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
72
+ })();
73
+ (()=>{
74
+ var installedChunks = {
75
+ 410: 0
76
+ };
77
+ var installChunk = (data)=>{
78
+ var __webpack_ids__ = data.__webpack_ids__;
79
+ var __webpack_modules__ = data.__webpack_modules__;
80
+ var __webpack_runtime__ = data.__webpack_runtime__;
81
+ var moduleId, chunkId, i = 0;
82
+ for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
83
+ if (__webpack_runtime__) __webpack_runtime__(__webpack_require__);
84
+ for(; i < __webpack_ids__.length; i++){
85
+ chunkId = __webpack_ids__[i];
86
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
87
+ installedChunks[__webpack_ids__[i]] = 0;
94
88
  }
95
- this.#config = config;
96
- return this.#config;
97
- }
98
- async beforeBuild() {
99
- return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
100
- }
101
- async afterBuild() {
102
- return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
103
- }
104
- async modifySearchIndexData(pages) {
105
- return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
106
- }
107
- async extendPageData(pageData) {
108
- return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
109
- }
110
- async addPages() {
111
- const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
112
- return result.flat();
113
- }
114
- async routeGenerated(routes) {
115
- return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
116
- }
117
- async routeServiceGenerated(routeService) {
118
- return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
119
- }
120
- async addRuntimeModules() {
121
- const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
122
- return result.reduce((prev, current)=>({
123
- ...prev,
124
- ...current
125
- }), {});
126
- }
127
- async addSSGRoutes() {
128
- const result = await this._runParallelAsyncHook('addSSGRoutes', this.#config || {}, this.#isProd);
129
- return result.flat();
130
- }
131
- globalUIComponents() {
132
- const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
133
- return result.flat();
134
- }
135
- globalStyles() {
136
- return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
137
- }
138
- _runParallelAsyncHook(hookName, ...args) {
139
- return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
140
- }
141
- _runSerialAsyncHook(hookName, ...args) {
142
- return this.#plugins.reduce(async (prev, plugin)=>{
143
- if ('function' == typeof plugin[hookName]) {
144
- await prev;
145
- return plugin[hookName](...args);
146
- }
147
- return prev;
148
- }, Promise.resolve());
149
- }
150
- }
151
- const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
152
- const pluginVirtualModule = (pluginOptions = {})=>({
153
- name: PLUGIN_VIRTUAL_MODULE_NAME,
154
- async setup (api) {
155
- const TEMP_DIR = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(process.cwd(), 'node_modules/.rsbuild-virtual-module');
156
- const { virtualModules = {} } = pluginOptions;
157
- const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
158
- let absolutePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(TEMP_DIR, i);
159
- if (!(0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.extname)(absolutePath)) absolutePath = `${absolutePath}.js`;
160
- return [
161
- i,
162
- absolutePath
163
- ];
164
- });
165
- api.onBeforeCreateCompiler(async ()=>{
166
- await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.mkdir)(TEMP_DIR, {
167
- recursive: true
168
- });
169
- await Promise.all(virtualFileAbsolutePaths.map(([_, absolutePath])=>(0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.writeFile)(absolutePath, '', 'utf-8')));
170
- });
171
- api.modifyBundlerChain((chain)=>{
172
- chain.resolve.alias.merge(Object.fromEntries(virtualFileAbsolutePaths));
89
+ };
90
+ __webpack_require__.f.j = function(chunkId, promises) {
91
+ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
92
+ if (0 !== installedChunkData) if (installedChunkData) promises.push(installedChunkData[1]);
93
+ else {
94
+ var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, (e)=>{
95
+ if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
96
+ throw e;
173
97
  });
174
- for (const [moduleName, absolutePath] of virtualFileAbsolutePaths){
175
- const handler = virtualModules[moduleName];
176
- if (handler) api.transform({
177
- test: absolutePath
178
- }, handler);
179
- }
98
+ var promise = Promise.race([
99
+ promise,
100
+ new Promise((resolve)=>{
101
+ installedChunkData = installedChunks[chunkId] = [
102
+ resolve
103
+ ];
104
+ })
105
+ ]);
106
+ promises.push(installedChunkData[1] = promise);
180
107
  }
181
- });
182
- var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.8"}');
183
- const RSPRESS_VERSION = package_namespaceObject.i8;
184
- const isProduction = ()=>'production' === process.env.NODE_ENV;
185
- const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
186
- const inlineThemeScript = `{
187
- const saved = localStorage.getItem('${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.APPEARANCE_KEY}')
188
- const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
189
- const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
190
- document.documentElement.classList.toggle('dark', isDark)
191
- document.documentElement.classList.toggle('rp-dark', isDark)
192
- document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
193
- }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
194
- const dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(new URL(import.meta.url)));
195
- const PACKAGE_ROOT = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirname, '..');
196
- const TEMPLATE_PATH = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'index.html');
197
- const CSR_CLIENT_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
198
- const SSR_CLIENT_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
199
- const SSR_SERVER_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
200
- const OUTPUT_DIR = 'doc_build';
201
- const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
202
- const HEAD_MARKER = '<!--<?- HEAD ?>-->';
203
- const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
204
- const DEFAULT_TITLE = 'Rspress';
205
- const PUBLIC_DIR = 'public';
206
- const constants_TEMP_DIR = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR);
108
+ };
109
+ })();
110
+ var shared_ = __webpack_require__("@rspress/shared");
111
+ function defineConfig(config) {
112
+ return config;
113
+ }
114
+ var external_node_path_ = __webpack_require__("node:path");
207
115
  async function pathExists(path) {
208
116
  try {
209
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].access(path);
117
+ await node_fs_promises.access(path);
210
118
  return true;
211
119
  } catch {
212
120
  return false;
213
121
  }
214
122
  }
215
123
  async function readJson(path) {
216
- const raw = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(path, 'utf8');
124
+ const raw = await node_fs_promises.readFile(path, 'utf8');
217
125
  return JSON.parse(raw);
218
126
  }
219
127
  const THEME_DEFAULT_EXPORT_PATTERN = /export\s+default\s+\{/;
@@ -226,84 +134,162 @@ async function hintThemeBreakingChange(customThemeDir) {
226
134
  ];
227
135
  let useDefaultExportFilePath = null;
228
136
  for (const file of fileList){
229
- const filePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(customThemeDir, file);
137
+ const filePath = (0, external_node_path_.join)(customThemeDir, file);
230
138
  if (await pathExists(filePath)) {
231
- const content = await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.readFile)(filePath, {
139
+ const content = await readFile(filePath, {
232
140
  encoding: 'utf-8'
233
141
  });
234
142
  if (THEME_DEFAULT_EXPORT_PATTERN.test(content)) useDefaultExportFilePath = filePath;
235
143
  break;
236
144
  }
237
145
  }
238
- if (useDefaultExportFilePath) __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.warn(`[Rspress v2] Breaking Change: The "theme/index.tsx" is now using named export instead of default export, please update ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].greenBright(useDefaultExportFilePath)} (https://github.com/web-infra-dev/rspress/discussions/1891#discussioncomment-12422737).\n`, __WEBPACK_EXTERNAL_MODULE_picocolors__["default"].redBright(`
239
- - import Theme from '@rspress/theme-default';
146
+ if (useDefaultExportFilePath) logger.warn(`[Rspress v2] Breaking Change: The "theme/index.tsx" is now using named export instead of default export, please update ${picocolors.greenBright(useDefaultExportFilePath)} (https://github.com/web-infra-dev/rspress/discussions/1891#discussioncomment-12422737).\n`, picocolors.redBright(`
147
+ - import Theme from '@rspress/core/theme';
240
148
  - export default {
241
149
  - ...Theme,
242
150
  - Layout,
243
151
  - };
244
- - export * from 'rspress/theme';`) + __WEBPACK_EXTERNAL_MODULE_picocolors__["default"].greenBright(`
245
- + import { Layout } from '@rspress/theme-default';
152
+ - export * from '@rspress/core/theme';`) + picocolors.greenBright(`
153
+ + import { Layout } from '@rspress/core/theme';
246
154
 
247
155
  + export { Layout };
248
- + export * from 'rspress/theme';
156
+ + export * from '@rspress/core/theme';
249
157
  `));
250
158
  }
159
+ function hintBuilderPluginsBreakingChange(config) {
160
+ if ('builderPlugins' in config && Array.isArray(config.builderPlugins) && config.builderPlugins.length > 0) {
161
+ logger.error(`[Rspress v2] The "builderPlugins" option has been renamed to "builderConfig.plugins", please update your config accordingly (https://rspress.rs/api/config/config-build#builderconfigplugins).\n`, `
162
+ export default defineConfig({
163
+ ${picocolors.redBright(` builderPlugins: [
164
+ pluginFoo()
165
+ ],`)}
166
+ ${picocolors.greenBright(` builderConfig: {
167
+ plugins: [
168
+ pluginFoo()
169
+ ],
170
+ },`)}
171
+ });`);
172
+ process.exit(1);
173
+ }
174
+ }
251
175
  function hintSSGFailed() {
252
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info(`[Rspress v2] \`ssg: true\` requires the source code to support SSR. If the code is not compatible to SSR, the build process will fail. You can try:
176
+ logger.info(`[Rspress v2] \`ssg: true\` requires the source code to support SSR. If the code is not compatible to SSR, the build process will fail. You can try:
253
177
  1. Fix code to make it SSR-compatible.
254
- 2. Set \`ssg: false\`, but the SSG feature will be lost.`);
178
+ 2. Set \`ssg: false\` if the code in node_modules may be difficult to fix, but the SSG feature will be lost.`);
255
179
  }
256
180
  function hintSSGFalse() {
257
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('`ssg: false` detected, SSG will be disabled.');
181
+ logger.info('`ssg: false` detected, SSG will be disabled.');
258
182
  }
259
- const isWindows = 'win32' === __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__["default"].platform();
260
- function slash(p) {
261
- return p.replace(/\\/g, '/');
183
+ function hintReactVersion() {
184
+ logger.info('[Rspress v2] Rspress support React 18 and 19, please confirm that both react and react-dom are installed in package.json with the same version. ');
262
185
  }
263
- function normalizePath(id) {
264
- return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.normalize(isWindows ? slash(id) : id);
186
+ function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
187
+ if (metaJson.some((i)=>'object' == typeof i && ('activeMatch' in i || 'text' in i || 'link' in i || 'items' in i || 'icon' in i || 'ariaLabel' in i || 'target' in i))) {
188
+ const error = new Error('[Rspress v2] Detected that you are still using top level `_meta.json` to configure the nav, but it has been changed to `_nav.json` in Rspress v2. Please rename the top level `_meta.json` to `_nav.json` accordingly.');
189
+ logger.error(error);
190
+ const dir = (0, external_node_path_.relative)(docsDir, metaJsonDir);
191
+ logger.info(`Please rename "${picocolors.greenBright((0, external_node_path_.join)(dir, '_meta.json'))}" to "${picocolors.greenBright((0, external_node_path_.join)(dir, '_nav.json'))}".`);
192
+ process.exit(1);
193
+ }
194
+ }
195
+ let isLogged = false;
196
+ function hintRelativeMarkdownLink() {
197
+ if (isLogged) return;
198
+ isLogged = true;
199
+ logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
265
200
  }
266
201
  function getPageKey(route) {
267
- const cleanRoute = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.removeLeadingSlash)(route);
202
+ const cleanRoute = (0, shared_.removeLeadingSlash)(route);
268
203
  return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
269
204
  }
270
- const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
271
- const hasTrailSlash = routePath.endsWith('/');
205
+ var external_node_os_ = __webpack_require__("node:os");
206
+ const isWindows = 'win32' === external_node_os_["default"].platform();
207
+ function slash(p) {
208
+ return p.replace(/\\/g, '/');
209
+ }
210
+ function normalizePath(id) {
211
+ return external_node_path_["default"].posix.normalize(isWindows ? slash(id) : id);
212
+ }
213
+ var external_node_url_ = __webpack_require__("node:url");
214
+ var package_namespaceObject = {
215
+ rE: "2.0.0-rc.0"
216
+ };
217
+ const RSPRESS_VERSION = package_namespaceObject.rE;
218
+ const APPEARANCE_KEY = 'rspress-theme-appearance';
219
+ const isProduction = ()=>'production' === process.env.NODE_ENV;
220
+ const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
221
+ const inlineThemeScript = `{
222
+ const saved = localStorage.getItem('${APPEARANCE_KEY}')
223
+ const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
224
+ const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
225
+ document.documentElement.classList.toggle('dark', isDark)
226
+ document.documentElement.classList.toggle('rp-dark', isDark)
227
+ document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
228
+ }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
229
+ const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
230
+ const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
231
+ const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
232
+ const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
233
+ const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
234
+ const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
235
+ const SSG_MD_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrMdServerEntry.js');
236
+ const OUTPUT_DIR = 'doc_build';
237
+ const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
238
+ const HEAD_MARKER = '<!--<?- HEAD ?>-->';
239
+ const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
240
+ const DEFAULT_TITLE = 'Rspress';
241
+ const PUBLIC_DIR = 'public';
242
+ const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
243
+ const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
244
+ const NODE_SSG_MD_BUNDLE_FOLDER = '__ssg_md__';
245
+ const NODE_SSG_MD_BUNDLE_NAME = 'rspress-ssg-md-entry.cjs';
246
+ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
247
+ const [versionPart, langPart, purePath] = splitRoutePathParts(relativePath, lang, version, langs, versions);
248
+ return [
249
+ versionPart === version ? '' : versionPart,
250
+ langPart === lang ? '' : langPart,
251
+ purePath
252
+ ];
253
+ };
254
+ const splitRoutePathParts = (relativePath, lang, version, langs, versions)=>{
255
+ const hasTrailSlash = relativePath.endsWith('/');
272
256
  let versionPart = '';
273
257
  let langPart = '';
274
258
  let purePathPart = '';
275
- const parts = routePath.split('/').filter(Boolean);
259
+ const parts = relativePath.split('/').filter(Boolean);
276
260
  if (version) {
277
261
  const versionToMatch = parts[0];
278
- if (versions.includes(versionToMatch)) {
279
- if (versionToMatch !== version) versionPart = versionToMatch;
280
- parts.shift();
281
- }
262
+ if (versions.includes(versionToMatch)) versionPart = parts.shift() ?? '';
282
263
  }
283
264
  if (lang) {
284
265
  const langToMatch = parts[0];
285
- if (langs.includes(langToMatch)) {
286
- if (langToMatch !== lang) langPart = langToMatch;
287
- parts.shift();
288
- }
266
+ if (langs.includes(langToMatch)) langPart = parts.shift() ?? '';
289
267
  }
290
268
  purePathPart = parts.join('/');
291
269
  return [
292
270
  versionPart,
293
271
  langPart,
294
- hasTrailSlash ? (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addTrailingSlash)(purePathPart) : purePathPart
272
+ hasTrailSlash ? (0, shared_.addTrailingSlash)(purePathPart) : purePathPart
295
273
  ];
296
274
  };
297
- const normalizeRoutePath = (routePath, base, lang, version, langs, versions, extensions = __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS)=>{
298
- const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
275
+ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
299
276
  const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
300
277
  const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
301
- const normalizedRoutePath = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)([
302
- versionPart,
303
- langPart
304
- ].filter(Boolean).join('/') + (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(purePathPart)).replace(cleanExtensionPattern, '').replace(/\.html$/, '').replace(/\/index$/, '/');
278
+ let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
279
+ if (routePath.endsWith('/')) routePath = `${routePath}index`;
280
+ const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
281
+ routePath = purePathPart.replace(/\/index$/, '/');
282
+ if ('index' === routePath) routePath = '';
283
+ const normalizedRoutePath = (0, shared_.addLeadingSlash)([
284
+ ...[
285
+ versionPart,
286
+ langPart
287
+ ].filter(Boolean),
288
+ routePath
289
+ ].join('/'));
305
290
  return {
306
- routePath: (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withBase)(normalizedRoutePath, base),
291
+ pureRoutePath: `/${routePath}`,
292
+ routePath: normalizedRoutePath,
307
293
  lang: langPart || lang,
308
294
  version: versionPart || version
309
295
  };
@@ -312,37 +298,60 @@ class RouteService {
312
298
  routeData = new Map();
313
299
  #scanDir;
314
300
  #defaultLang;
315
- #defaultVersion = '';
316
- #extensions = [];
317
- #langs = [];
318
- #versions = [];
319
- #include = [];
320
- #exclude = [];
321
- #base = '';
322
- #tempDir = '';
323
- #pluginDriver;
324
- constructor(scanDir, userConfig, tempDir, pluginDriver){
301
+ #defaultVersion;
302
+ #extensions;
303
+ #langs;
304
+ #versions;
305
+ #include;
306
+ #exclude;
307
+ #excludeConvention;
308
+ #tempDir;
309
+ #externalPages;
310
+ static __instance__ = null;
311
+ static getInstance() {
312
+ return RouteService.__instance__;
313
+ }
314
+ static async create(options) {
315
+ const { scanDir, config, externalPages } = options;
316
+ const runtimeAbsTempDir = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR, 'runtime');
317
+ await node_fs_promises.mkdir(runtimeAbsTempDir, {
318
+ recursive: true
319
+ });
320
+ const routeService = new RouteService(scanDir, config, externalPages || [], runtimeAbsTempDir);
321
+ RouteService.__instance__ = routeService;
322
+ await routeService.#init();
323
+ return routeService;
324
+ }
325
+ static async createSimple() {
326
+ return new RouteService('', {}, [], '');
327
+ }
328
+ constructor(scanDir, userConfig, externalPages, runtimeAbsTempDir){
325
329
  const routeOptions = userConfig?.route || {};
326
330
  this.#scanDir = scanDir;
327
- this.#extensions = routeOptions.extensions || __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS;
331
+ this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;
328
332
  this.#include = routeOptions.include || [];
329
333
  this.#exclude = routeOptions.exclude || [];
334
+ this.#excludeConvention = routeOptions.excludeConvention || [
335
+ '**/_[^_]*'
336
+ ];
330
337
  this.#defaultLang = userConfig?.lang || '';
331
338
  this.#langs = (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item)=>item.lang);
332
- this.#base = userConfig?.base || '';
333
- this.#tempDir = tempDir;
334
- this.#pluginDriver = pluginDriver;
339
+ this.#tempDir = runtimeAbsTempDir;
340
+ this.#externalPages = externalPages;
335
341
  if (userConfig.multiVersion) {
336
342
  this.#defaultVersion = userConfig.multiVersion.default || '';
337
343
  this.#versions = userConfig.multiVersion.versions || [];
344
+ } else {
345
+ this.#defaultVersion = '';
346
+ this.#versions = [];
338
347
  }
339
348
  }
340
349
  get extensions() {
341
350
  return this.#extensions;
342
351
  }
343
- async init() {
352
+ async #init() {
344
353
  const extensions = this.#extensions.map((i)=>i.slice(1));
345
- const files = (await (0, __WEBPACK_EXTERNAL_MODULE_tinyglobby__.glob)([
354
+ const files = (await glob([
346
355
  `**/*.{${extensions.join(',')}}`,
347
356
  ...this.#include
348
357
  ], {
@@ -351,180 +360,897 @@ class RouteService {
351
360
  onlyFiles: true,
352
361
  ignore: [
353
362
  ...this.#exclude,
363
+ ...this.#excludeConvention,
354
364
  '**/node_modules/**',
355
365
  '**/.eslintrc.js',
356
366
  '**/.nx/**',
357
- `./${PUBLIC_DIR}/**`
367
+ `./${PUBLIC_DIR}/**`,
368
+ '**/*.d.ts'
358
369
  ]
359
370
  })).sort();
360
371
  files.forEach((filePath)=>{
361
- const fileRelativePath = normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(this.#scanDir, filePath));
362
- const { routePath, lang, version } = this.normalizeRoutePath(fileRelativePath);
363
- const absolutePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(this.#scanDir, fileRelativePath);
364
- const routeInfo = {
365
- routePath,
366
- absolutePath: normalizePath(absolutePath),
367
- relativePath: fileRelativePath,
368
- pageName: getPageKey(fileRelativePath),
369
- lang,
370
- version
371
- };
372
- this.addRoute(routeInfo);
372
+ const routePage = RoutePage.create(filePath, this.#scanDir);
373
+ this.addRoute(routePage);
373
374
  });
374
- const externalPages = await this.#pluginDriver.addPages();
375
+ const externalPages = this.#externalPages;
375
376
  await Promise.all(externalPages.map(async (route, index)=>{
376
377
  const { routePath, content, filepath } = route;
377
378
  if (filepath) {
378
- const routeInfo = this.#generateRouteInfo(routePath, filepath);
379
- this.addRoute(routeInfo);
379
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
380
+ this.addRoute(routePage);
380
381
  return;
381
382
  }
382
383
  if (content) {
383
384
  const filepath = await this.#writeTempFile(index, content);
384
- const routeInfo = this.#generateRouteInfo(routePath, filepath);
385
- this.addRoute(routeInfo);
385
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
386
+ this.addRoute(routePage);
386
387
  }
387
388
  }));
388
- await this.#pluginDriver.routeGenerated(this.getRoutes());
389
389
  }
390
- addRoute(routeInfo) {
391
- const { routePath, absolutePath } = routeInfo;
392
- if (this.routeData.has(routePath)) {
393
- const preRouteExtIndex = this.#extensions.indexOf(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(this.routeData.get(routePath).absolutePath));
394
- const currRouteExtIndex = this.#extensions.indexOf(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(absolutePath));
395
- if (-1 !== currRouteExtIndex && (currRouteExtIndex < preRouteExtIndex || -1 === preRouteExtIndex)) this.routeData.set(routePath, routeInfo);
396
- } else this.routeData.set(routePath, routeInfo);
397
- }
398
- removeRoute(filePath) {
399
- const fileRelativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(this.#scanDir, filePath);
400
- const { routePath } = this.normalizeRoutePath(fileRelativePath);
401
- this.routeData.delete(routePath);
390
+ async addRoute(routePage) {
391
+ const { routeMeta: { routePath } } = routePage;
392
+ if (this.routeData.has(routePath)) throw new Error(`routePath ${routePath} has already been added`);
393
+ this.routeData.set(routePath, routePage);
402
394
  }
403
395
  getRoutes() {
404
- return Array.from(this.routeData.values());
396
+ return Array.from(this.routeData.values()).map((i)=>i.routeMeta);
405
397
  }
406
- isExistRoute(routePath) {
407
- const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);
408
- return Boolean(this.routeData.get(normalizedRoute));
398
+ getRoutePages() {
399
+ return Array.from(this.routeData.values());
409
400
  }
410
- isEmpty() {
411
- return 0 === this.routeData.size;
401
+ isExistRoute(link) {
402
+ function linkToRoutePath(routePath) {
403
+ return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
404
+ }
405
+ const cleanLinkPath = linkToRoutePath(link);
406
+ if (!this.routeData.has((0, shared_.removeTrailingSlash)(cleanLinkPath)) && !this.routeData.has((0, shared_.addTrailingSlash)(cleanLinkPath))) return false;
407
+ return true;
412
408
  }
413
- generateRoutesCode(isStaticImport = false) {
414
- return this.generateRoutesCodeByRouteMeta(this.getRoutes(), isStaticImport);
409
+ generateRoutesCode() {
410
+ return this.generateRoutesCodeByRouteMeta(this.getRoutes());
415
411
  }
416
- generateRoutesCodeByRouteMeta(routeMeta, isStaticImport) {
412
+ generateRoutesCodeByRouteMeta(routeMeta) {
417
413
  return `
418
414
  import React from 'react';
419
415
  import { lazyWithPreload } from "react-lazy-with-preload";
420
- ${routeMeta.map((route, index)=>isStaticImport ? `import * as Route${index} from '${route.absolutePath}';` : `const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`).join('\n')}
416
+ ${routeMeta.map((route, index)=>`const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`).join('\n')}
421
417
  export const routes = [
422
418
  ${routeMeta.map((route, index)=>{
423
- const preload = isStaticImport ? `() => Route${index}` : `async () => {
419
+ const preload = `async () => {
424
420
  await Route${index}.preload();
425
421
  return import("${route.absolutePath}");
426
422
  }`;
427
- const component = isStaticImport ? `Route${index}.default` : `Route${index}`;
423
+ const component = `Route${index}`;
428
424
  return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;
429
425
  }).join(',\n')}
430
426
  ];
431
427
  `;
432
428
  }
433
- getRoutePathParts(routePath) {
434
- return getRoutePathParts(routePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
429
+ getRoutePathParts(relativePath) {
430
+ return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
431
+ }
432
+ splitRoutePathParts(relativePath) {
433
+ return splitRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
435
434
  }
436
- normalizeRoutePath(routePath) {
437
- return normalizeRoutePath(routePath, this.#base, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
435
+ normalizeRoutePath(relativePath) {
436
+ return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
437
+ }
438
+ absolutePathToRoutePath(absolutePath) {
439
+ return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
440
+ }
441
+ isInDocsDir(absolutePath) {
442
+ const relativePath = external_node_path_["default"].relative(this.#scanDir, absolutePath);
443
+ return !relativePath.startsWith('..') && !external_node_path_["default"].isAbsolute(relativePath);
444
+ }
445
+ absolutePathToRelativePath(absolutePath) {
446
+ return absolutePathToRelativePath(absolutePath, this.#scanDir);
438
447
  }
439
448
  async #writeTempFile(index, content) {
440
- const tempFilePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(this.#tempDir, `temp-${index}.mdx`);
441
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(tempFilePath, content);
449
+ const tempFilePath = external_node_path_["default"].join(this.#tempDir, `temp-${index}.mdx`);
450
+ await node_fs_promises.writeFile(tempFilePath, content);
442
451
  return tempFilePath;
443
452
  }
444
- #generateRouteInfo(routePath, filepath) {
445
- const { routePath: normalizedPath, lang, version } = this.normalizeRoutePath(routePath);
453
+ getRoutePageByRoutePath(routePath) {
454
+ return this.routeData.get(routePath);
455
+ }
456
+ getDocsDir() {
457
+ return this.#scanDir;
458
+ }
459
+ getLangs() {
460
+ return this.#langs;
461
+ }
462
+ getDefaultLang() {
463
+ return this.#defaultLang;
464
+ }
465
+ }
466
+ class RoutePage {
467
+ routeMeta;
468
+ #docDir;
469
+ static create(absolutePath, docsDir) {
470
+ const routeMeta = absolutePathToRouteMeta(absolutePath, docsDir, RouteService.getInstance());
471
+ return new RoutePage(routeMeta, docsDir);
472
+ }
473
+ static createFromExternal(routePath, filepath, docDir) {
474
+ const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
475
+ return new RoutePage(routeMeta, external_node_path_["default"].dirname(filepath));
476
+ }
477
+ constructor(routeMeta, docDir){
478
+ this.routeMeta = routeMeta;
479
+ this.#docDir = docDir;
480
+ }
481
+ static generateRouteMeta(routePath, filepath, docDir) {
482
+ const routeService = RouteService.getInstance();
483
+ const { routePath: normalizedPath, lang, version } = routeService.normalizeRoutePath(routePath);
446
484
  return {
447
485
  routePath: normalizedPath,
448
486
  absolutePath: normalizePath(filepath),
449
- relativePath: normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(this.#scanDir, filepath)),
487
+ relativePath: absolutePathToRelativePath(filepath, docDir),
450
488
  pageName: getPageKey(routePath),
451
489
  lang,
452
490
  version
453
491
  };
454
492
  }
455
493
  }
456
- let init_routeService = null;
457
- async function initRouteService(options) {
458
- const { scanDir, config, runtimeTempDir, pluginDriver } = options;
459
- init_routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
460
- await init_routeService.init();
461
- await pluginDriver.routeServiceGenerated(init_routeService);
462
- return init_routeService;
463
- }
464
- function createHash(str) {
465
- return (0, __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__.createHash)('sha256').update(str).digest('hex').slice(0, 8);
466
- }
467
- var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
468
- RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
469
- RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
470
- RuntimeModuleID["RouteForClient"] = "virtual-routes";
471
- RuntimeModuleID["RouteForSSR"] = "virtual-routes-ssr";
472
- RuntimeModuleID["SiteData"] = "virtual-site-data";
473
- RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
474
- RuntimeModuleID["I18nText"] = "virtual-i18n-text";
475
- RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
476
- return RuntimeModuleID;
477
- }({});
478
- let flattenMdxContent_resolver;
479
- let startFlatten = false;
480
- const processor = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)();
481
- const { CachedInputFileSystem, ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
482
- const fileSystem = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"];
483
- async function resolveDepPath(importPath, importer, alias) {
484
- if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
485
- fileSystem: new CachedInputFileSystem(fileSystem, 0),
486
- extensions: [
487
- '.mdx',
488
- '.md'
489
- ],
490
- alias
491
- });
492
- const resolveResult = await new Promise((resolve, reject)=>{
493
- flattenMdxContent_resolver.resolve({
494
- importer
495
- }, importer, importPath, {}, (err, filePath)=>{
496
- if (err) return reject(err);
497
- if (!filePath) return reject(new Error(`Empty result when resolving ${importPath} from ${importer}`));
498
- return resolve(filePath);
499
- });
500
- });
501
- return resolveResult;
494
+ function absolutePathToRelativePath(absolutePath, docsDir) {
495
+ return slash(external_node_path_["default"].relative(docsDir, absolutePath));
502
496
  }
503
- async function flattenMdxContent(content, basePath, alias) {
504
- const deps = [];
505
- const regex = new RegExp(importStatementRegex);
506
- if (!regex.test(content)) return {
507
- flattenContent: content,
508
- deps
497
+ function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
498
+ const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
499
+ const { lang, routePath, version } = routeService.normalizeRoutePath(relativePath);
500
+ return {
501
+ pageName: getPageKey(relativePath),
502
+ absolutePath,
503
+ lang,
504
+ version,
505
+ routePath,
506
+ relativePath
509
507
  };
510
- if (!startFlatten) {
511
- flattenMdxContent_resolver = ResolverFactory.createResolver({
512
- fileSystem: new CachedInputFileSystem(fileSystem, 0),
513
- extensions: [
514
- '.mdx',
515
- '.md',
516
- '.js'
517
- ],
518
- alias
519
- });
520
- startFlatten = true;
508
+ }
509
+ function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteService.getInstance()) {
510
+ return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
511
+ }
512
+ function absolutePathToRoutePrefix(absolutePath, docsDir) {
513
+ const relativePath = slash(external_node_path_["default"].relative(docsDir, absolutePath.replace(external_node_path_["default"].extname(absolutePath), '')));
514
+ const routeService = RouteService.getInstance();
515
+ const [versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
516
+ return `${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
517
+ }
518
+ function addRoutePrefix(workDir, docsDir, link) {
519
+ const routePrefix = absolutePathToRoutePrefix(workDir, docsDir);
520
+ return `${routePrefix.replace(/\/$/, '')}/${link.replace(/^\//, '')}`;
521
+ }
522
+ async function utils_pathExists(path) {
523
+ try {
524
+ await node_fs_promises.access(path);
525
+ return true;
526
+ } catch {
527
+ return false;
521
528
  }
522
- let ast;
523
- let result = content;
529
+ }
530
+ async function utils_readJson(path) {
531
+ const raw = await node_fs_promises.readFile(path, 'utf8');
532
+ return JSON.parse(raw);
533
+ }
534
+ async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir) {
535
+ const fileHandle = await node_fs_promises.open(absolutePath, 'r');
524
536
  try {
525
- ast = processor.parse(content);
526
- } catch (e) {
527
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug('flattenMdxContent parse failed: \n', e);
537
+ const buffer = Buffer.alloc(2048);
538
+ let content = '';
539
+ let bytesRead = 0;
540
+ let hasFrontmatter = false;
541
+ let frontmatterEnd = -1;
542
+ let h1Match = null;
543
+ let frontmatter = {};
544
+ do {
545
+ const result = await fileHandle.read(buffer, 0, buffer.length, bytesRead);
546
+ if (0 === result.bytesRead) break;
547
+ content += buffer.subarray(0, result.bytesRead).toString('utf-8');
548
+ bytesRead += result.bytesRead;
549
+ if (bytesRead <= buffer.length) if (content.startsWith('---')) {
550
+ hasFrontmatter = true;
551
+ const secondDelimiter = content.indexOf('\n---\n', 4);
552
+ if (-1 !== secondDelimiter) {
553
+ frontmatterEnd = secondDelimiter + 5;
554
+ const { frontmatter: fm } = loadFrontMatter(content.slice(0, frontmatterEnd + 100), absolutePath, rootDir);
555
+ frontmatter = fm;
556
+ }
557
+ } else hasFrontmatter = false;
558
+ if (!h1Match) {
559
+ const searchStart = hasFrontmatter && frontmatterEnd > -1 ? frontmatterEnd : 0;
560
+ const h1RegExp = /^#\s+(.*?)\n$/m;
561
+ h1Match = content.slice(searchStart).match(h1RegExp);
562
+ }
563
+ if (hasFrontmatter && frontmatterEnd > -1 && h1Match) break;
564
+ if (!hasFrontmatter && h1Match) break;
565
+ if (hasFrontmatter && frontmatterEnd > -1 && bytesRead > 16384) break;
566
+ }while (bytesRead < 65536);
567
+ if (hasFrontmatter && -1 === frontmatterEnd) {
568
+ const { frontmatter: fm } = loadFrontMatter(content, absolutePath, rootDir);
569
+ frontmatter = fm;
570
+ }
571
+ if (!h1Match) {
572
+ const h1RegExp = /^#\s+(.*)$/m;
573
+ h1Match = content.match(h1RegExp);
574
+ }
575
+ const fileNameWithoutExt = external_node_path_["default"].basename(absolutePath, external_node_path_["default"].extname(absolutePath));
576
+ return {
577
+ title: extractTextAndId(frontmatter.title || h1Match?.[1] || fileNameWithoutExt)[0],
578
+ overviewHeaders: frontmatter.overviewHeaders,
579
+ context: frontmatter.context,
580
+ tag: frontmatter.tag,
581
+ description: frontmatter.description
582
+ };
583
+ } finally{
584
+ await fileHandle.close();
585
+ }
586
+ }
587
+ function getFileKey(realPath, docsDir) {
588
+ return realPath ? (0, shared_.slash)((0, external_node_path_.relative)(docsDir, realPath).replace((0, external_node_path_.extname)(realPath), '')) : '';
589
+ }
590
+ async function fsDirToMetaItems(workDir, docsDir, extensions) {
591
+ let subItems;
592
+ try {
593
+ subItems = await readdir(workDir);
594
+ } catch (e) {
595
+ logger.error(`Failed to read directory: ${workDir}, maybe it does not exist. Please check it in "_meta.json".`);
596
+ throw e;
597
+ }
598
+ subItems = subItems.filter((item)=>{
599
+ const hasExtension = extensions.some((ext)=>item.endsWith(ext));
600
+ const hasSameBaseName = subItems.some((elem)=>{
601
+ const baseName = elem.replace(/\.[^/.]+$/, '');
602
+ return baseName === item.replace(/\.[^/.]+$/, '') && elem !== item;
603
+ });
604
+ return !(hasExtension && hasSameBaseName);
605
+ });
606
+ const sideMeta = (await Promise.all(subItems.map(async (item)=>{
607
+ if ('_meta.json' === item) return null;
608
+ const stat = await promises_stat((0, external_node_path_.join)(workDir, item));
609
+ if (stat.isDirectory()) {
610
+ if ('public' === item && workDir === docsDir) return null;
611
+ return {
612
+ type: 'dir',
613
+ name: item
614
+ };
615
+ }
616
+ return extensions.some((ext)=>item.endsWith(ext)) ? item : null;
617
+ }))).filter(Boolean);
618
+ return sideMeta;
619
+ }
620
+ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, metaFileSet, mdFileSet) {
621
+ if ('string' == typeof metaItem) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions, mdFileSet);
622
+ const { type } = metaItem;
623
+ if ('file' === type) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions, mdFileSet);
624
+ if ('dir' === type) return metaDirItemToSidebarItem(metaItem, workDir, docsDir, extensions, metaFileSet, mdFileSet, false);
625
+ if ('dir-section-header' === type) return metaDirSectionHeaderItemToSidebarItem(metaItem, workDir, docsDir, extensions, metaFileSet, mdFileSet);
626
+ if ('custom-link' === type) return metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir);
627
+ if ('divider' === type) return metaDividerToSidebarItem(metaItem);
628
+ if ('section-header' === type) return metaSectionHeaderToSidebarItem(metaItem);
629
+ throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
630
+ }
631
+ async function detectFilePath(absolutePath, extensions) {
632
+ const ext = (0, external_node_path_.extname)(absolutePath);
633
+ if (ext && extensions.includes(ext)) return absolutePath;
634
+ for (const extension of extensions){
635
+ const realPath = absolutePath + extension;
636
+ if (await utils_pathExists(realPath)) return realPath;
637
+ }
638
+ throw new Error(`The file extension "${ext}" is not supported, please use one of the following extensions: ${extensions.join(', ')}`);
639
+ }
640
+ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensions, mdFileSet) {
641
+ let metaItem = null;
642
+ metaItem = 'string' == typeof metaItemRaw ? {
643
+ name: metaItemRaw,
644
+ type: 'file'
645
+ } : metaItemRaw;
646
+ const { name, context, label, overviewHeaders, tag } = metaItem;
647
+ if ('string' != typeof name) throw new Error(`The file name "${name}" is not a string, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
648
+ const absolutePath = (0, external_node_path_.join)(workDir, name);
649
+ let absolutePathWithExt;
650
+ try {
651
+ absolutePathWithExt = await detectFilePath(absolutePath, extensions);
652
+ } catch {
653
+ throw new Error(`The file "${absolutePath}" does not exist, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
654
+ }
655
+ const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
656
+ const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
657
+ const title = label || info.title;
658
+ mdFileSet.add(absolutePathWithExt);
659
+ return {
660
+ text: title,
661
+ link,
662
+ tag: info.tag || tag,
663
+ overviewHeaders: info.overviewHeaders || overviewHeaders,
664
+ context: info.context || context,
665
+ _fileKey: getFileKey(absolutePathWithExt, docsDir)
666
+ };
667
+ }
668
+ async function metaDirItemToSidebarItem(metaItem, workDir, docsDir, extensions, metaFileSet, mdFileSet, forceIndexFileAsItem) {
669
+ const { name, label, collapsible, collapsed, tag: metaJsonTag, context: metaJsonContext, overviewHeaders: metaJsonOverviewHeaders } = metaItem;
670
+ const dirAbsolutePath = (0, external_node_path_.join)(workDir, name);
671
+ const dirMetaJsonPath = (0, external_node_path_.join)(dirAbsolutePath, '_meta.json');
672
+ const isMetaJsonExist = await utils_pathExists(dirMetaJsonPath);
673
+ let dirMetaJson = [];
674
+ if (isMetaJsonExist) {
675
+ metaFileSet.add(dirMetaJsonPath);
676
+ dirMetaJson = await utils_readJson(dirMetaJsonPath);
677
+ } else dirMetaJson = await fsDirToMetaItems(dirAbsolutePath, docsDir, extensions);
678
+ async function getItems(withoutIndex = false) {
679
+ const items = await Promise.all((withoutIndex ? dirMetaJson.filter((i)=>{
680
+ let name;
681
+ if ('object' == typeof i && 'type' in i && 'file' === i.type) name = i.name;
682
+ else {
683
+ if ('string' != typeof i) return true;
684
+ name = i;
685
+ }
686
+ return 'index.md' !== name && 'index.mdx' !== i && 'index' !== i;
687
+ }) : dirMetaJson).map((item)=>metaItemToSidebarItem(item, dirAbsolutePath, docsDir, extensions, metaFileSet, mdFileSet)));
688
+ return items.flat();
689
+ }
690
+ try {
691
+ const sameNameFile = await metaFileItemToSidebarItem(name, workDir, docsDir, extensions, mdFileSet);
692
+ const { link, text, _fileKey, context, overviewHeaders, tag } = sameNameFile;
693
+ return {
694
+ text: label || text || name,
695
+ collapsible,
696
+ collapsed,
697
+ items: await getItems(),
698
+ link,
699
+ tag: metaJsonTag || tag,
700
+ overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
701
+ context: metaJsonContext || context,
702
+ _fileKey
703
+ };
704
+ } catch (e) {
705
+ logger.debug(e);
706
+ const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
707
+ if ('string' == typeof i) return 'index' === i.replace((0, external_node_path_.extname)(i), '');
708
+ return false;
709
+ });
710
+ const isIndexFileExists = await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.mdx')) || await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.md'));
711
+ if (isMetaJsonExist && isIndexInMetaJsonIndex || !isIndexFileExists) return {
712
+ text: label || name,
713
+ collapsible,
714
+ collapsed,
715
+ items: await getItems(),
716
+ overviewHeaders: metaJsonOverviewHeaders,
717
+ context: metaJsonContext,
718
+ _fileKey: getFileKey(dirAbsolutePath, docsDir)
719
+ };
720
+ {
721
+ const indexFile = await metaFileItemToSidebarItem('index', dirAbsolutePath, docsDir, extensions, mdFileSet);
722
+ const { link, text, _fileKey, context, overviewHeaders, tag } = indexFile;
723
+ return {
724
+ text: label || text || name,
725
+ collapsible,
726
+ collapsed,
727
+ items: await getItems(!forceIndexFileAsItem),
728
+ link,
729
+ tag: metaJsonTag || tag,
730
+ overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
731
+ context: metaJsonContext || context,
732
+ _fileKey
733
+ };
734
+ }
735
+ }
736
+ }
737
+ async function metaDirSectionHeaderItemToSidebarItem(metaItem, workDir, docsDir, extensions, metaFileSet, mdFileSet) {
738
+ const fakeDirMetaItem = {
739
+ ...metaItem,
740
+ type: 'dir'
741
+ };
742
+ const fakeSectionHeaderMetaItem = {
743
+ label: metaItem.label,
744
+ tag: metaItem.tag,
745
+ type: 'section-header'
746
+ };
747
+ const dirSideGroup = await metaDirItemToSidebarItem(fakeDirMetaItem, workDir, docsDir, extensions, metaFileSet, mdFileSet, true);
748
+ const sectionHeaderSideItem = metaSectionHeaderToSidebarItem(fakeSectionHeaderMetaItem);
749
+ return [
750
+ sectionHeaderSideItem,
751
+ ...dirSideGroup.items.length >= 1 ? dirSideGroup.items : []
752
+ ];
753
+ }
754
+ function metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir) {
755
+ if ('items' in metaItem && Array.isArray(metaItem.items) && metaItem.items.length > 0) {
756
+ const { label, link, context, items, tag, collapsed, collapsible, overviewHeaders } = metaItem;
757
+ return {
758
+ text: label ?? link,
759
+ context,
760
+ tag,
761
+ link,
762
+ items: items.map((subItem)=>metaCustomLinkItemToSidebarItem(Object.assign(subItem, {
763
+ type: 'custom-link'
764
+ }), workDir, docsDir)),
765
+ collapsed,
766
+ collapsible,
767
+ overviewHeaders
768
+ };
769
+ }
770
+ if ('link' in metaItem && 'string' == typeof metaItem.link) {
771
+ const { label, link, context, tag } = metaItem;
772
+ if ((0, shared_.isExternalUrl)(link)) return {
773
+ text: label ?? link,
774
+ link,
775
+ tag,
776
+ context
777
+ };
778
+ return {
779
+ text: label ?? link,
780
+ link: addRoutePrefix(workDir, docsDir, link),
781
+ tag,
782
+ context
783
+ };
784
+ }
785
+ const { label } = metaItem;
786
+ throw new Error(`The custom link "${label}" does not have a link, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
787
+ }
788
+ function metaDividerToSidebarItem(metaItem) {
789
+ const { dashed } = metaItem;
790
+ return {
791
+ dividerType: dashed ? 'dashed' : 'solid'
792
+ };
793
+ }
794
+ function metaSectionHeaderToSidebarItem(metaItem) {
795
+ const { label, tag } = metaItem;
796
+ return {
797
+ sectionHeaderText: label ?? '',
798
+ tag
799
+ };
800
+ }
801
+ async function scanSideMeta(workDir, docsDir, extensions, metaFileSet, mdFileSet) {
802
+ const dir = await metaDirItemToSidebarItem({
803
+ type: 'dir',
804
+ name: ''
805
+ }, workDir, docsDir, extensions, metaFileSet, mdFileSet, true);
806
+ return dir.items;
807
+ }
808
+ async function scanNav(workDir, docsDir, metaFileSet) {
809
+ let navConfig;
810
+ const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
811
+ try {
812
+ navConfig = await utils_readJson(rootNavJson);
813
+ metaFileSet.add(rootNavJson);
814
+ } catch (_e) {
815
+ logger.error('[auto-nav-sidebar]', `Generate nav meta error: ${rootNavJson} failed`);
816
+ navConfig = [];
817
+ }
818
+ navConfig.forEach((navItem)=>{
819
+ if ('items' in navItem) navItem.items.forEach((item)=>{
820
+ if ('link' in item && !(0, shared_.isExternalUrl)(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
821
+ });
822
+ if ('link' in navItem && !(0, shared_.isExternalUrl)(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
823
+ });
824
+ return navConfig;
825
+ }
826
+ async function walk(workDir, docsDir, extensions, metaFileSet, mdFileSet) {
827
+ const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
828
+ const rootMetaJson = external_node_path_["default"].resolve(workDir, '_meta.json');
829
+ const isRootNavJsonExist = await pathExists(rootNavJson);
830
+ const isRootMetaJsonExist = await pathExists(rootMetaJson);
831
+ if (isRootMetaJsonExist) {
832
+ const metaConfig = await utils_readJson(rootMetaJson);
833
+ hintNavJsonChangeThenPanic(metaConfig, workDir, docsDir);
834
+ }
835
+ if (isRootMetaJsonExist && isRootNavJsonExist) {
836
+ const navConfig = await scanNav(workDir, docsDir, metaFileSet);
837
+ return {
838
+ nav: navConfig,
839
+ sidebar: {
840
+ '/': await scanSideMeta(workDir, docsDir, extensions, metaFileSet, mdFileSet)
841
+ }
842
+ };
843
+ }
844
+ if (isRootNavJsonExist) {
845
+ const navConfig = await scanNav(workDir, docsDir, metaFileSet);
846
+ const subDirs = (await Promise.all((await node_fs_promises.readdir(workDir)).map((v)=>node_fs_promises.stat(external_node_path_["default"].join(workDir, v)).then((s)=>{
847
+ if (s.isDirectory() && 'node_modules' !== v) return v;
848
+ return false;
849
+ })))).filter(Boolean);
850
+ const sidebarConfig = {};
851
+ await Promise.all(subDirs.map(async (subDir)=>{
852
+ const sidebarGroupKey = addRoutePrefix(workDir, docsDir, subDir);
853
+ sidebarConfig[sidebarGroupKey] = await scanSideMeta(external_node_path_["default"].join(workDir, subDir), docsDir, extensions, metaFileSet, mdFileSet);
854
+ }));
855
+ return {
856
+ nav: navConfig,
857
+ sidebar: sidebarConfig
858
+ };
859
+ }
860
+ return {
861
+ nav: [],
862
+ sidebar: {
863
+ '/': await scanSideMeta(workDir, docsDir, extensions, metaFileSet, mdFileSet)
864
+ }
865
+ };
866
+ }
867
+ function combineWalkResult(walks, versions) {
868
+ return walks.reduce((acc, cur, curIndex)=>({
869
+ nav: {
870
+ ...acc.nav,
871
+ [versions[curIndex] || 'default']: cur.nav
872
+ },
873
+ sidebar: {
874
+ ...acc.sidebar,
875
+ ...cur.sidebar
876
+ }
877
+ }), {
878
+ nav: {},
879
+ sidebar: {}
880
+ });
881
+ }
882
+ function processLocales(langs, versions, root, extensions, metaFileSet, mdFileSet) {
883
+ return Promise.all(langs.map(async (lang)=>{
884
+ const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(root, version, lang), root, extensions, metaFileSet, mdFileSet))) : [
885
+ await walk(external_node_path_["default"].join(root, lang), root, extensions, metaFileSet, mdFileSet)
886
+ ];
887
+ return combineWalkResult(walks, versions);
888
+ }));
889
+ }
890
+ async function runAutoNavSide(config, metaFileSet, mdFileSet) {
891
+ config.themeConfig = config.themeConfig || {};
892
+ config.themeConfig.locales = config.themeConfig.locales || config.locales || [];
893
+ const langs = config.themeConfig.locales.map((locale)=>locale.lang);
894
+ const hasLocales = langs.length > 0;
895
+ const versions = config.multiVersion?.versions || [];
896
+ const { extensions = DEFAULT_PAGE_EXTENSIONS } = config?.route || {};
897
+ if (hasLocales) {
898
+ const metaInfo = await processLocales(langs, versions, config.root, extensions, metaFileSet, mdFileSet);
899
+ return metaInfo;
900
+ }
901
+ const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(config.root, version), config.root, extensions, metaFileSet, mdFileSet))) : [
902
+ await walk(config.root, config.root, extensions, metaFileSet, mdFileSet)
903
+ ];
904
+ const combined = combineWalkResult(walks, versions);
905
+ return combined;
906
+ }
907
+ function auto_nav_sidebar_haveNavSidebarConfig(config) {
908
+ const themeConfig = config.themeConfig || {};
909
+ const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
910
+ return Boolean(haveNavSidebarConfig);
911
+ }
912
+ async function modifyConfigWithAutoNavSide(config, metaFileSet = new Set(), mdFileSet = new Set(), force = false) {
913
+ if (auto_nav_sidebar_haveNavSidebarConfig(config) && !force) return;
914
+ const autoNavSide = await runAutoNavSide(config, metaFileSet, mdFileSet);
915
+ if (null === autoNavSide) return;
916
+ if (Array.isArray(autoNavSide)) {
917
+ config.themeConfig = config.themeConfig || {};
918
+ config.themeConfig.locales = config.themeConfig.locales || [];
919
+ config.themeConfig.locales = config.themeConfig.locales.map((item, index)=>({
920
+ ...item,
921
+ ...autoNavSide[index]
922
+ }));
923
+ return;
924
+ }
925
+ config.themeConfig = config.themeConfig || {};
926
+ config.themeConfig.nav = autoNavSide.nav;
927
+ config.themeConfig.sidebar = autoNavSide.sidebar;
928
+ }
929
+ const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
930
+ const pluginVirtualModule = (pluginOptions = {})=>({
931
+ name: PLUGIN_VIRTUAL_MODULE_NAME,
932
+ async setup (api) {
933
+ const { virtualModules = {}, tempDir: virtualFolderName = '.rsbuild-virtual-module' } = pluginOptions;
934
+ const TEMP_DIR = (0, external_node_path_.join)(api.context.rootPath, virtualFolderName);
935
+ const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
936
+ let absolutePath = (0, external_node_path_.join)(TEMP_DIR, i);
937
+ if (!(0, external_node_path_.extname)(absolutePath)) absolutePath = `${absolutePath}.js`;
938
+ return [
939
+ i,
940
+ absolutePath
941
+ ];
942
+ });
943
+ api.modifyBundlerChain((chain, { rspack })=>{
944
+ const pluginId = 'RSBUILD_VIRTUAL_MODULE_PLUGIN';
945
+ const virtualModules = Object.fromEntries(virtualFileAbsolutePaths.map((i)=>[
946
+ i[1],
947
+ ''
948
+ ]));
949
+ if (chain.plugins.has(pluginId)) chain.plugin(pluginId).tap((options)=>{
950
+ const existingPaths = new Set(Object.keys(options[0] ?? {}));
951
+ const conflictPath = virtualFileAbsolutePaths.find(([, path])=>existingPaths.has(path));
952
+ if (conflictPath) throw new Error(`Virtual module name conflicted: ${conflictPath[0]}`);
953
+ return [
954
+ {
955
+ ...options[0],
956
+ ...virtualModules
957
+ }
958
+ ];
959
+ });
960
+ else chain.plugin(pluginId).use(rspack.experiments.VirtualModulesPlugin, [
961
+ virtualModules
962
+ ]);
963
+ chain.resolve.alias.merge(Object.fromEntries(virtualFileAbsolutePaths));
964
+ });
965
+ for (const [moduleName, absolutePath] of virtualFileAbsolutePaths){
966
+ const handler = virtualModules[moduleName];
967
+ if (handler) api.transform({
968
+ test: absolutePath
969
+ }, handler);
970
+ }
971
+ }
972
+ });
973
+ const globalStylesVMPlugin = (context)=>({
974
+ ["virtual-global-styles"]: ()=>{
975
+ const { config, pluginDriver } = context;
976
+ const globalStylesByPlugins = pluginDriver.globalStyles();
977
+ const moduleContent = [
978
+ config?.globalStyles,
979
+ ...globalStylesByPlugins
980
+ ].filter(Boolean).map((source)=>`import ${JSON.stringify(source)};`).join('');
981
+ return moduleContent;
982
+ }
983
+ });
984
+ const globalUIComponentsVMPlugin = (context)=>({
985
+ ["virtual-global-components"]: ()=>{
986
+ const { config, pluginDriver } = context;
987
+ let index = 0;
988
+ const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();
989
+ const globalComponents = [
990
+ ...config?.globalUIComponents || [],
991
+ ...globalUIComponentsByPlugins
992
+ ];
993
+ const moduleContent = globalComponents.map((source)=>{
994
+ const name = `Comp_${index}`;
995
+ if (Array.isArray(source)) return `import ${name} from ${JSON.stringify(source[0])};
996
+ const Props_${index++} = ${JSON.stringify(source[1])};\n`;
997
+ index++;
998
+ return `import ${name} from ${JSON.stringify(source)};\n`;
999
+ }).concat(`export default [${Array.from({
1000
+ length: index
1001
+ }, (_, i)=>{
1002
+ if (Array.isArray(globalComponents[i])) return `[Comp_${i}, Props_${i}]`;
1003
+ return `Comp_${i}`;
1004
+ }).join(', ')}];`).join('');
1005
+ return moduleContent;
1006
+ }
1007
+ });
1008
+ const DEFAULT_I18N_TEXT = {
1009
+ languagesText: {
1010
+ zh: '语言',
1011
+ en: 'Languages',
1012
+ ja: '言語',
1013
+ ko: '언어'
1014
+ },
1015
+ themeText: {
1016
+ zh: '主题',
1017
+ en: 'Theme',
1018
+ ja: 'テーマ',
1019
+ ko: '테마'
1020
+ },
1021
+ versionsText: {
1022
+ zh: '版本',
1023
+ en: 'Versions',
1024
+ ja: 'バージョン',
1025
+ ko: '버전'
1026
+ },
1027
+ menuTitle: {
1028
+ zh: '菜单',
1029
+ en: 'Menu',
1030
+ ja: 'メニュー',
1031
+ ko: '사이드바 메뉴'
1032
+ },
1033
+ outlineTitle: {
1034
+ zh: '目录',
1035
+ en: 'ON THIS PAGE',
1036
+ ja: '目次',
1037
+ ko: '이 페이지 목차'
1038
+ },
1039
+ scrollToTopText: {
1040
+ en: 'Back to top',
1041
+ zh: '回到顶部',
1042
+ ja: 'トップに戻る',
1043
+ ko: '맨 위로'
1044
+ },
1045
+ lastUpdatedText: {
1046
+ en: 'Last Updated',
1047
+ zh: '最后更新于',
1048
+ ja: '最終更新',
1049
+ ko: '업데이트 날짜'
1050
+ },
1051
+ prevPageText: {
1052
+ en: 'Previous page',
1053
+ zh: '上一页',
1054
+ ja: '前のページ',
1055
+ ko: '이전 페이지'
1056
+ },
1057
+ nextPageText: {
1058
+ en: 'Next page',
1059
+ zh: '下一页',
1060
+ ja: '次のページ',
1061
+ ko: '다음 페이지'
1062
+ },
1063
+ sourceCodeText: {
1064
+ en: 'Source Code',
1065
+ zh: '源码',
1066
+ ja: 'ソースコード',
1067
+ ko: '소스 코드'
1068
+ },
1069
+ searchPlaceholderText: {
1070
+ en: 'Search',
1071
+ zh: '搜索',
1072
+ ja: '検索',
1073
+ ko: '검색'
1074
+ },
1075
+ searchPanelCancelText: {
1076
+ en: 'Cancel',
1077
+ zh: '取消',
1078
+ ja: 'キャンセル',
1079
+ ko: '취소'
1080
+ },
1081
+ searchNoResultsText: {
1082
+ en: 'No matching results',
1083
+ zh: '未找到与之匹配的结果',
1084
+ ja: '一致する結果が見つかりません',
1085
+ ko: '일치하는 결과가 없습니다'
1086
+ },
1087
+ searchSuggestedQueryText: {
1088
+ en: 'Try searching for different keywords',
1089
+ zh: '试试搜索不同关键词',
1090
+ ja: '別のキーワードで検索してみてください',
1091
+ ko: '다른 키워드로 검색해 보세요'
1092
+ },
1093
+ 'overview.filterNameText': {
1094
+ en: 'Filter',
1095
+ zh: '筛选',
1096
+ ja: 'フィルター',
1097
+ ko: '필터'
1098
+ },
1099
+ 'overview.filterPlaceholderText': {
1100
+ en: 'Search API',
1101
+ zh: '搜索 API',
1102
+ ja: 'API を検索',
1103
+ ko: 'API 검색'
1104
+ },
1105
+ 'overview.filterNoResultText': {
1106
+ en: 'No matching API found',
1107
+ zh: '未找到匹配的 API',
1108
+ ja: '一致する API が見つかりません',
1109
+ ko: '일치하는 API가 없습니다'
1110
+ },
1111
+ editLinkText: {
1112
+ en: '📝 Edit this page',
1113
+ zh: '📝 编辑此页面',
1114
+ ja: '📝 このページを編集',
1115
+ ko: '📝 이 페이지 편집'
1116
+ },
1117
+ codeButtonGroupCopyButtonText: {
1118
+ en: 'Copy code',
1119
+ zh: '复制代码',
1120
+ ja: 'コードをコピー',
1121
+ ko: '코드 복사'
1122
+ },
1123
+ notFoundText: {
1124
+ en: 'PAGE NOT FOUND',
1125
+ zh: '页面未找到',
1126
+ ja: 'ページが見つかりません',
1127
+ ko: '페이지를 찾을 수 없음'
1128
+ },
1129
+ takeMeHomeText: {
1130
+ en: 'Take me home',
1131
+ zh: '返回首页',
1132
+ ja: 'ホームに連れてって',
1133
+ ko: '홈으로 이동'
1134
+ }
1135
+ };
1136
+ const i18n_require = createRequire(import.meta.url);
1137
+ const DEFAULT_I18N_SOURCE_PATH = (0, external_node_path_.join)(process.cwd(), 'i18n.json');
1138
+ function mergeI18nData(...sources) {
1139
+ const result = {};
1140
+ for (const source of sources)for(const key in source){
1141
+ if (!result[key]) result[key] = {};
1142
+ Object.assign(result[key], source[key]);
1143
+ }
1144
+ return result;
1145
+ }
1146
+ const logPrefix = '[i18n]';
1147
+ const logKeys = new Set();
1148
+ let logged = false;
1149
+ async function getI18nData(docConfig, pluginDriver) {
1150
+ const { i18nSourcePath = DEFAULT_I18N_SOURCE_PATH, i18nSource = {}, themeConfig, locales } = docConfig;
1151
+ let langs = (locales ?? themeConfig?.locales)?.map((locale)=>locale.lang) ?? [];
1152
+ if (0 === langs.length) langs = [
1153
+ docConfig.lang ?? 'en'
1154
+ ];
1155
+ let i18nSourceFull = JSON.parse(JSON.stringify(DEFAULT_I18N_TEXT));
1156
+ const i18nSourceFromPlugin = await pluginDriver?.i18nSource(i18nSourceFull);
1157
+ if (i18nSourceFromPlugin) i18nSourceFull = i18nSourceFromPlugin;
1158
+ let i18nSourceFromJson = {};
1159
+ try {
1160
+ delete i18n_require.cache[i18nSourcePath];
1161
+ i18nSourceFromJson = i18n_require(i18nSourcePath);
1162
+ } catch (e) {
1163
+ logger.debug('getI18nData from i18n.json Failed: \n', e);
1164
+ }
1165
+ i18nSourceFull = mergeI18nData(i18nSourceFull, i18nSourceFromJson);
1166
+ if ('function' == typeof i18nSource) try {
1167
+ i18nSourceFull = await i18nSource(i18nSourceFull);
1168
+ } catch (e) {
1169
+ logger.error(`${logPrefix} getI18nData Failed to execute \`i18nSource\` function in \`rspress.config.ts\`: \n`, e);
1170
+ throw e;
1171
+ }
1172
+ else i18nSourceFull = mergeI18nData(i18nSourceFull, i18nSource);
1173
+ const cyan = picocolors.cyan;
1174
+ const filteredI18nSource = {};
1175
+ for(const key in i18nSourceFull){
1176
+ filteredI18nSource[key] = {};
1177
+ for (const lang of langs)if (i18nSourceFull[key][lang]) filteredI18nSource[key][lang] = i18nSourceFull[key][lang];
1178
+ else {
1179
+ const enText = i18nSourceFull[key].en;
1180
+ logKeys.add(key);
1181
+ if (enText) filteredI18nSource[key][lang] = enText;
1182
+ else {
1183
+ logger.error(`${logPrefix} i18n key ${cyan(key)} has no text for lang ${cyan(lang)}, and no fallback ${cyan('en')} text either.`);
1184
+ throw new Error(`i18n text missing for ${picocolors.cyan(key)}`);
1185
+ }
1186
+ }
1187
+ }
1188
+ if (logKeys.size > 0 && !logged) {
1189
+ logger.warn(`${logPrefix} The following i18n keys are missing for some languages and have fallen back to 'en':
1190
+ ${picocolors.gray(JSON.stringify(Object.fromEntries([
1191
+ ...logKeys.keys()
1192
+ ].map((i)=>[
1193
+ i,
1194
+ '...'
1195
+ ])), null, 2))}`);
1196
+ logged = true;
1197
+ }
1198
+ return filteredI18nSource;
1199
+ }
1200
+ const i18nVMPlugin = (context)=>{
1201
+ const { config, pluginDriver } = context;
1202
+ return {
1203
+ ["virtual-i18n-text"]: async ({ addDependency, addMissingDependency })=>{
1204
+ const configPath = config.i18nSourcePath || DEFAULT_I18N_SOURCE_PATH;
1205
+ const isExist = await pathExists(configPath);
1206
+ if (isExist) addDependency(configPath);
1207
+ else addMissingDependency(configPath);
1208
+ const i18nData = await getI18nData(config, pluginDriver);
1209
+ return `export default ${JSON.stringify(i18nData, null, 2)}`;
1210
+ }
1211
+ };
1212
+ };
1213
+ var external_node_fs_ = __webpack_require__("node:fs");
1214
+ const RspackResolveFactory = core_rspack.experiments.resolver.ResolverFactory;
1215
+ let startFlatten = false;
1216
+ let flattenMdxContent_resolver;
1217
+ const processor = createProcessor();
1218
+ async function resolveDepPath(moduleSpecifier, importer, alias) {
1219
+ if (!flattenMdxContent_resolver) flattenMdxContent_resolver = new RspackResolveFactory({
1220
+ extensions: [
1221
+ '.mdx',
1222
+ '.md'
1223
+ ],
1224
+ alias
1225
+ });
1226
+ const resolved = await flattenMdxContent_resolver.async(importer, moduleSpecifier);
1227
+ if (resolved.path) return resolved.path;
1228
+ throw new Error(`Empty result when resolving ${moduleSpecifier} from ${importer}`);
1229
+ }
1230
+ async function flattenMdxContent(content, basePath, alias) {
1231
+ const deps = [];
1232
+ const regex = new RegExp(importStatementRegex);
1233
+ if (!regex.test(content)) return {
1234
+ flattenContent: content,
1235
+ deps
1236
+ };
1237
+ if (!startFlatten) {
1238
+ flattenMdxContent_resolver = new RspackResolveFactory({
1239
+ extensions: [
1240
+ '.mdx',
1241
+ '.md',
1242
+ '.js'
1243
+ ],
1244
+ alias
1245
+ });
1246
+ startFlatten = true;
1247
+ }
1248
+ let ast;
1249
+ let result = content;
1250
+ try {
1251
+ ast = processor.parse(content);
1252
+ } catch (e) {
1253
+ logger.debug('flattenMdxContent parse failed: \n', e);
528
1254
  return {
529
1255
  flattenContent: content,
530
1256
  deps
@@ -536,12 +1262,12 @@ async function flattenMdxContent(content, basePath, alias) {
536
1262
  const importPath = importNode.source.value;
537
1263
  let absoluteImportPath;
538
1264
  try {
539
- absoluteImportPath = await resolveDepPath(importPath, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(basePath), alias);
1265
+ absoluteImportPath = await resolveDepPath(importPath, external_node_path_["default"].dirname(basePath), alias);
540
1266
  } catch (_e) {
541
1267
  continue;
542
1268
  }
543
- if (__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
544
- const importedContent = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(absoluteImportPath, 'utf-8');
1269
+ if (shared_.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
1270
+ const importedContent = external_node_fs_["default"].readFileSync(absoluteImportPath, 'utf-8');
545
1271
  const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
546
1272
  result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
547
1273
  deps.push(...subDeps, absoluteImportPath);
@@ -562,178 +1288,273 @@ function applyReplaceRulesToNestedObject(obj, replaceRules) {
562
1288
  else if ('object' == typeof obj[key] && null !== obj[key]) obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
563
1289
  return obj;
564
1290
  }
565
- async function extractPageData(replaceRules, alias, domain, root, routeService, highlighterLangs, searchCodeBlocks) {
566
- const pageData = await Promise.all(routeService.getRoutes().map(async (route, index)=>{
567
- const defaultIndexInfo = {
568
- id: index,
569
- title: '',
570
- content: '',
571
- _flattenContent: '',
572
- _html: '',
573
- routePath: route.routePath,
574
- lang: route.lang,
575
- toc: [],
576
- domain,
577
- frontmatter: {},
578
- version: route.version,
579
- _filepath: route.absolutePath,
580
- _relativePath: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, route.absolutePath).split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/')
581
- };
582
- if (!__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
583
- let content = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(route.absolutePath, 'utf8');
584
- const { frontmatter, content: contentWithoutFrontMatter } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(content, route.absolutePath, root);
585
- applyReplaceRulesToNestedObject(frontmatter, replaceRules);
586
- const { flattenContent } = await flattenMdxContent(applyReplaceRules(contentWithoutFrontMatter, replaceRules), route.absolutePath, alias);
587
- content = flattenContent.replace(importStatementRegex, '');
588
- const { html: rawHtml, title, toc: rawToc, languages } = await (0, __WEBPACK_EXTERNAL_MODULE__rspress_mdx_rs_d2f3021f__.compile)({
589
- value: content,
590
- filepath: route.absolutePath,
591
- development: 'production' !== process.env.NODE_ENV,
592
- root
1291
+ async function getPageIndexInfoByRoute(route, options) {
1292
+ const { alias, replaceRules, root, searchCodeBlocks } = options;
1293
+ const defaultIndexInfo = {
1294
+ title: '',
1295
+ content: '',
1296
+ _html: '',
1297
+ _flattenContent: '',
1298
+ routePath: route.routePath,
1299
+ lang: route.lang,
1300
+ toc: [],
1301
+ frontmatter: {},
1302
+ version: route.version,
1303
+ _filepath: route.absolutePath,
1304
+ _relativePath: external_node_path_["default"].relative(root, route.absolutePath).split(external_node_path_["default"].sep).join('/')
1305
+ };
1306
+ if (!shared_.MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
1307
+ let content = await node_fs_promises.readFile(route.absolutePath, 'utf8');
1308
+ const { frontmatter, content: contentWithoutFrontMatter } = loadFrontMatter(content, route.absolutePath, root);
1309
+ applyReplaceRulesToNestedObject(frontmatter, replaceRules);
1310
+ const { flattenContent } = await flattenMdxContent(applyReplaceRules(contentWithoutFrontMatter, replaceRules), route.absolutePath, alias);
1311
+ content = flattenContent.replace(importStatementRegex, '');
1312
+ const { html: rawHtml, title, toc: rawToc } = await compile({
1313
+ value: content,
1314
+ filepath: route.absolutePath,
1315
+ development: 'production' !== process.env.NODE_ENV,
1316
+ root
1317
+ });
1318
+ function encodeHtml(html) {
1319
+ return html.replace(/<code>([\s\S]*?)<\/\s?code>/gm, function(_match, innerContent) {
1320
+ return `<code>${innerContent.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`;
593
1321
  });
594
- function encodeHtml(html) {
595
- return html.replace(/<code>([\s\S]*?)<\/\s?code>/gm, function(_match, innerContent) {
596
- return `<code>${innerContent.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`;
597
- });
598
- }
599
- const html = encodeHtml(String(rawHtml));
600
- content = (0, __WEBPACK_EXTERNAL_MODULE_html_to_text_2c51ed38__.htmlToText)(html, {
601
- wordwrap: 80,
602
- selectors: [
603
- {
604
- selector: 'a',
1322
+ }
1323
+ const html = encodeHtml(String(rawHtml));
1324
+ content = htmlToText(html, {
1325
+ wordwrap: 80,
1326
+ selectors: [
1327
+ {
1328
+ selector: 'a',
1329
+ options: {
1330
+ ignoreHref: true
1331
+ }
1332
+ },
1333
+ {
1334
+ selector: 'img',
1335
+ format: 'skip'
1336
+ },
1337
+ {
1338
+ selector: 'pre > code',
1339
+ format: searchCodeBlocks ? 'block' : 'skip'
1340
+ },
1341
+ ...[
1342
+ 'h1',
1343
+ 'h2',
1344
+ 'h3',
1345
+ 'h4',
1346
+ 'h5',
1347
+ 'h6'
1348
+ ].map((tag)=>({
1349
+ selector: tag,
605
1350
  options: {
606
- ignoreHref: true
1351
+ uppercase: false
607
1352
  }
608
- },
609
- {
610
- selector: 'img',
611
- format: 'skip'
612
- },
613
- {
614
- selector: 'pre > code',
615
- format: searchCodeBlocks ? 'block' : 'skip'
616
- },
617
- ...[
618
- 'h1',
619
- 'h2',
620
- 'h3',
621
- 'h4',
622
- 'h5',
623
- 'h6'
624
- ].map((tag)=>({
625
- selector: tag,
626
- options: {
627
- uppercase: false
628
- }
629
- }))
630
- ],
631
- tables: true,
632
- longWordSplit: {
633
- forceWrapOnLimit: true
634
- }
635
- });
636
- if (content.startsWith(title)) content = content.slice(title.length);
637
- languages.forEach((lang)=>highlighterLangs.add(lang));
638
- const toc = rawToc.map((item)=>{
639
- const match = item.id.match(/-(\d+)$/);
640
- let position = -1;
641
- if (match) for(let i = 0; i < Number(match[1]); i++){
642
- position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
643
- if (-1 === position) break;
644
- }
645
- return {
646
- ...item,
647
- charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
648
- };
649
- });
1353
+ }))
1354
+ ],
1355
+ tables: true,
1356
+ longWordSplit: {
1357
+ forceWrapOnLimit: true
1358
+ }
1359
+ });
1360
+ if (content.startsWith(title)) content = content.slice(title.length);
1361
+ const toc = rawToc.map((item)=>{
1362
+ const match = item.id.match(/-(\d+)$/);
1363
+ let position = -1;
1364
+ if (match) for(let i = 0; i < Number(match[1]); i++){
1365
+ position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
1366
+ if (-1 === position) break;
1367
+ }
650
1368
  return {
651
- ...defaultIndexInfo,
652
- title: frontmatter.title || title,
653
- toc,
654
- content,
655
- _flattenContent: flattenContent,
656
- _html: html,
657
- frontmatter: {
658
- ...frontmatter,
659
- __content: void 0
660
- }
1369
+ ...item,
1370
+ charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
661
1371
  };
662
- }));
663
- return pageData.filter(Boolean);
1372
+ });
1373
+ return {
1374
+ ...defaultIndexInfo,
1375
+ title: frontmatter.title || title,
1376
+ toc,
1377
+ content,
1378
+ _html: html,
1379
+ _flattenContent: flattenContent,
1380
+ frontmatter: {
1381
+ ...frontmatter,
1382
+ __content: void 0
1383
+ }
1384
+ };
664
1385
  }
665
- const DEFAULT_I18N_SOURCE = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(process.cwd(), 'i18n.json');
666
- function getI18nData(docConfig) {
667
- const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
668
- try {
669
- delete require.cache[i18nSourcePath];
670
- const i18nSource = require(i18nSourcePath);
671
- return i18nSource;
672
- } catch (e) {
673
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug('getI18nData Failed: \n', e);
674
- return {};
675
- }
1386
+ async function extractPageData(routeService, options) {
1387
+ const pageData = await Promise.all(routeService.getRoutes().map((routeMeta)=>getPageIndexInfoByRoute(routeMeta, options)));
1388
+ return pageData;
676
1389
  }
677
- const i18nVMPlugin = (context)=>{
678
- const { config } = context;
1390
+ function createHash_createHash(str) {
1391
+ return createHash('sha256').update(str).digest('hex').slice(0, 8);
1392
+ }
1393
+ function deletePrivateField(obj) {
1394
+ if ('object' != typeof obj || null === obj) return obj;
1395
+ const newObj = {
1396
+ ...obj
1397
+ };
1398
+ for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
1399
+ return newObj;
1400
+ }
1401
+ async function createPageData(context) {
1402
+ const { config, alias, userDocRoot, routeService, pluginDriver } = context;
1403
+ const userConfig = config;
1404
+ const tempSearchObj = Object.assign({}, userConfig.search);
1405
+ if (tempSearchObj) tempSearchObj.searchHooks = void 0;
1406
+ const replaceRules = userConfig?.replaceRules || [];
1407
+ const searchConfig = userConfig?.search || {};
1408
+ const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
1409
+ const pages = await extractPageData(routeService, {
1410
+ replaceRules,
1411
+ alias,
1412
+ root: userDocRoot,
1413
+ searchCodeBlocks
1414
+ });
1415
+ await pluginDriver.modifySearchIndexData(pages);
1416
+ const versioned = 'boolean' != typeof userConfig.search && userConfig.search?.versioned;
1417
+ const groupedPages = groupBy(pages, (page)=>{
1418
+ if (page.frontmatter?.pageType === 'home') return 'noindex';
1419
+ const version = versioned ? page.version : '';
1420
+ const lang = page.lang || '';
1421
+ return `${version}###${lang}`;
1422
+ });
1423
+ delete groupedPages.noindex;
1424
+ const indexHashByGroup = {};
1425
+ const searchIndex = {};
1426
+ await Promise.all(Object.keys(groupedPages).map(async (group)=>{
1427
+ const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
1428
+ const indexHash = createHash_createHash(stringifiedIndex);
1429
+ indexHashByGroup[group] = indexHash;
1430
+ const [version, lang] = group.split('###');
1431
+ const indexVersion = version ? `.${version.replace('.', '_')}` : '';
1432
+ const indexLang = lang ? `.${lang}` : '';
1433
+ const filename = `${shared_.SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`;
1434
+ searchIndex[filename] = stringifiedIndex;
1435
+ }));
1436
+ await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
1437
+ const filepaths = [];
1438
+ const pageData = {
1439
+ pages: pages.map((page)=>{
1440
+ const { content: _content, _filepath, _html, _flattenContent, ...rest } = page;
1441
+ filepaths.push(_filepath);
1442
+ return rest;
1443
+ })
1444
+ };
679
1445
  return {
680
- [types_RuntimeModuleID.I18nText]: ({ addDependency, addMissingDependency })=>{
681
- addDependency(config.i18nSourcePath || DEFAULT_I18N_SOURCE);
682
- addMissingDependency(config.i18nSourcePath || DEFAULT_I18N_SOURCE);
683
- const i18nData = getI18nData(config);
684
- return `export default ${JSON.stringify(i18nData, null, 2)}`;
1446
+ filepaths,
1447
+ pageData,
1448
+ searchIndex,
1449
+ indexHashByGroup
1450
+ };
1451
+ }
1452
+ const rsbuildPluginDocVM = async ({ config, userDocRoot, routeService, pluginDriver })=>{
1453
+ const ref = {
1454
+ pageData: null,
1455
+ searchIndex: null,
1456
+ indexHashByGroup: null,
1457
+ filepaths: []
1458
+ };
1459
+ const searchIndexRsbuildPlugin = {
1460
+ name: 'rsbuild-plugin-searchIndex',
1461
+ async setup (api) {
1462
+ api.modifyBundlerChain(async (bundlerChain)=>{
1463
+ const alias = bundlerChain.resolve.alias.entries();
1464
+ const { pageData, indexHashByGroup, searchIndex, filepaths } = await createPageData({
1465
+ config,
1466
+ alias: alias,
1467
+ userDocRoot,
1468
+ routeService,
1469
+ pluginDriver
1470
+ });
1471
+ ref.pageData = pageData;
1472
+ ref.searchIndex = searchIndex;
1473
+ ref.indexHashByGroup = indexHashByGroup;
1474
+ ref.filepaths = filepaths;
1475
+ api.processAssets({
1476
+ stage: 'report',
1477
+ environments: [
1478
+ 'web'
1479
+ ]
1480
+ }, ({ compilation, compiler })=>{
1481
+ for (const [filename, stringifiedIndex] of Object.entries(searchIndex))compilation.emitAsset(`static/${filename}`, new compiler.webpack.sources.RawSource(stringifiedIndex));
1482
+ });
1483
+ });
685
1484
  }
686
1485
  };
1486
+ return [
1487
+ searchIndexRsbuildPlugin,
1488
+ pluginVirtualModule({
1489
+ tempDir: '.rspress',
1490
+ virtualModules: {
1491
+ ["virtual-page-data"]: async ({ addDependency })=>{
1492
+ for (const file of ref.filepaths)addDependency(file);
1493
+ return `export const pageData = ${JSON.stringify(ref.pageData, null, 2)};
1494
+ export const searchIndexHash = ${JSON.stringify(ref.indexHashByGroup, null, 2)};`;
1495
+ }
1496
+ }
1497
+ })
1498
+ ];
687
1499
  };
688
- function normalizeThemeConfig(docConfig, pages = []) {
689
- const { locales: siteLocales, base = '', lang, replaceRules = [], multiVersion } = docConfig;
1500
+ const routeListVMPlugin = (context)=>{
1501
+ const { routeService } = context;
1502
+ return {
1503
+ ["virtual-routes"]: ()=>routeService.generateRoutesCode()
1504
+ };
1505
+ };
1506
+ const searchHookVMPlugin = (context)=>({
1507
+ ["virtual-search-hooks"]: ()=>{
1508
+ const { config } = context;
1509
+ let content = 'export const onSearch = () => {};';
1510
+ const searchHooks = 'object' == typeof config.search && config.search?.searchHooks;
1511
+ if (searchHooks) content = `export * from ${JSON.stringify(external_node_path_["default"].posix.normalize(searchHooks))}`;
1512
+ return content;
1513
+ }
1514
+ });
1515
+ async function normalizeThemeConfig(docConfig) {
1516
+ const { locales: siteLocales, lang, replaceRules = [], multiVersion } = docConfig;
690
1517
  const { versions = [] } = multiVersion || {};
691
1518
  const hasMultiVersion = versions.length > 0;
692
1519
  docConfig.themeConfig = docConfig.themeConfig || {};
693
1520
  const { themeConfig } = docConfig;
694
1521
  const locales = siteLocales ?? (themeConfig?.locales || []);
695
- const i18nTextData = getI18nData(docConfig);
696
- const normalizeLinkPrefix = (link = '', currentLang = '')=>{
697
- const normalizedLink = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(link);
698
- if (!currentLang || !link || (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withoutBase)(normalizedLink, base).startsWith(`/${currentLang}`) || (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(normalizedLink) || hasMultiVersion) return normalizedLink;
699
- return lang === currentLang ? normalizedLink : `/${currentLang}${(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(normalizedLink)}`;
1522
+ const i18nTextData = await getI18nData(docConfig);
1523
+ const normalizeLinkPrefix = (link, currentLang)=>{
1524
+ const normalizedLink = (0, shared_.slash)(link);
1525
+ if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || (0, shared_.isExternalUrl)(normalizedLink) || hasMultiVersion) return normalizedLink;
1526
+ return lang === currentLang ? normalizedLink : `/${currentLang}${(0, shared_.addLeadingSlash)(normalizedLink)}`;
700
1527
  };
701
- const getI18nText = (key = '', currentLang = '')=>{
1528
+ const getI18nText = (key, currentLang)=>{
702
1529
  const text = i18nTextData[key]?.[currentLang];
703
1530
  return text || key;
704
1531
  };
705
- const normalizeSidebar = (sidebar, currentLang = '')=>{
1532
+ const cleanUrls = false;
1533
+ const transformLink = (link, currentLang)=>(0, shared_.normalizeHref)(normalizeLinkPrefix(link, currentLang), cleanUrls);
1534
+ const textReplace = (text, currentLang)=>applyReplaceRules(getI18nText(text, currentLang), replaceRules);
1535
+ const normalizeSidebar = (sidebar, currentLang)=>{
706
1536
  const normalizedSidebar = {};
707
1537
  if (!sidebar) return {};
708
1538
  const normalizeSidebarItem = (item)=>{
709
1539
  if ('object' == typeof item && 'dividerType' in item) return item;
710
1540
  if ('object' == typeof item && 'sectionHeaderText' in item) {
711
- item.sectionHeaderText = applyReplaceRules(getI18nText(item.sectionHeaderText, currentLang), replaceRules);
1541
+ item.sectionHeaderText = textReplace(item.sectionHeaderText, currentLang);
712
1542
  return item;
713
1543
  }
714
1544
  if ('object' == typeof item && 'items' in item) return {
715
1545
  ...item,
716
- text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
717
- link: normalizeLinkPrefix(item.link),
1546
+ text: textReplace(item.text, currentLang),
1547
+ ...'link' in item && item.link ? {
1548
+ link: transformLink(item.link, currentLang)
1549
+ } : {},
718
1550
  collapsed: item.collapsed ?? false,
719
1551
  collapsible: item.collapsible ?? true,
720
- tag: item.tag,
721
1552
  items: item.items.map((subItem)=>normalizeSidebarItem(subItem))
722
1553
  };
723
- if ('string' == typeof item) {
724
- const normalizedItem = normalizeLinkPrefix(item, currentLang);
725
- const page = pages.find((page)=>page.routePath === (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withBase)(normalizedItem, base));
726
- return {
727
- text: applyReplaceRules(page?.title || '', replaceRules),
728
- link: normalizedItem,
729
- _fileKey: page?._relativePath.replace(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(page._relativePath), '')
730
- };
731
- }
732
1554
  return {
733
1555
  ...item,
734
- text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
735
- link: normalizeLinkPrefix(item.link),
736
- tag: item.tag
1556
+ text: textReplace(item.text, currentLang),
1557
+ link: transformLink(item.link, currentLang)
737
1558
  };
738
1559
  };
739
1560
  const normalizeSidebar = (sidebar)=>{
@@ -747,24 +1568,18 @@ function normalizeThemeConfig(docConfig, pages = []) {
747
1568
  };
748
1569
  const normalizeNav = (nav, currentLang)=>{
749
1570
  if (!nav) return [];
750
- const transformNavItem = (navItem)=>{
751
- const text = applyReplaceRules(getI18nText(navItem.text, currentLang), replaceRules);
752
- if ('link' in navItem) return {
1571
+ const transformNavItem = (navItem)=>({
753
1572
  ...navItem,
754
- text,
755
- link: normalizeLinkPrefix(navItem.link, currentLang)
756
- };
757
- if ('items' in navItem) return {
758
- ...navItem,
759
- text,
760
- items: navItem.items.map((item)=>({
761
- ...item,
762
- text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
763
- link: normalizeLinkPrefix(item.link, currentLang)
764
- }))
765
- };
766
- return navItem;
767
- };
1573
+ ...navItem.text ? {
1574
+ text: textReplace(navItem.text, currentLang)
1575
+ } : {},
1576
+ ...'link' in navItem ? {
1577
+ link: transformLink(navItem.link, currentLang)
1578
+ } : {},
1579
+ ...'items' in navItem ? {
1580
+ items: navItem.items.map((item)=>transformNavItem(item))
1581
+ } : {}
1582
+ });
768
1583
  if (Array.isArray(nav)) return nav.map(transformNavItem);
769
1584
  return Object.entries(nav).reduce((acc, [key, value])=>{
770
1585
  acc[key] = value.map(transformNavItem);
@@ -776,237 +1591,199 @@ function normalizeThemeConfig(docConfig, pages = []) {
776
1591
  return {
777
1592
  lang: currentLang,
778
1593
  label,
779
- ...localeInThemeConfig || {},
1594
+ ...localeInThemeConfig,
780
1595
  sidebar: normalizeSidebar(localeInThemeConfig?.sidebar ?? themeConfig.sidebar, currentLang),
781
1596
  nav: normalizeNav(localeInThemeConfig?.nav ?? themeConfig.nav, currentLang)
782
1597
  };
783
1598
  });
784
1599
  else {
785
- themeConfig.sidebar = normalizeSidebar(themeConfig?.sidebar);
786
- themeConfig.nav = normalizeNav(themeConfig?.nav);
1600
+ themeConfig.sidebar = normalizeSidebar(themeConfig?.sidebar, '');
1601
+ themeConfig.nav = normalizeNav(themeConfig?.nav, '');
787
1602
  }
788
1603
  return themeConfig;
789
1604
  }
790
- function deletePrivateField(obj) {
791
- if ('object' != typeof obj || null === obj) return obj;
792
- const newObj = {
793
- ...obj
794
- };
795
- for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
796
- return newObj;
797
- }
798
- async function siteDataVMPlugin(context) {
799
- const { config, alias, userDocRoot, routeService, pluginDriver } = context;
800
- const userConfig = config;
1605
+ async function createSiteData(userConfig) {
801
1606
  const tempSearchObj = Object.assign({}, userConfig.search);
802
1607
  if (tempSearchObj) tempSearchObj.searchHooks = void 0;
803
- const highlightLanguages = new Set();
804
- const replaceRules = userConfig?.replaceRules || [];
805
- const searchConfig = userConfig?.search || {};
806
- const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
807
- const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
808
- const pages = await extractPageData(replaceRules, alias, domain, userDocRoot, routeService, highlightLanguages, searchCodeBlocks);
809
- await pluginDriver.modifySearchIndexData(pages);
810
- const versioned = userConfig.search && 'remote' !== userConfig.search.mode && userConfig.search.versioned;
811
- const groupedPages = (0, __WEBPACK_EXTERNAL_MODULE_lodash_es_18c59938__.groupBy)(pages, (page)=>{
812
- if (page.frontmatter?.pageType === 'home') return 'noindex';
813
- const version = versioned ? page.version : '';
814
- const lang = page.lang || '';
815
- return `${version}###${lang}`;
816
- });
817
- delete groupedPages.noindex;
818
- const indexHashByGroup = {};
819
- await Promise.all(Object.keys(groupedPages).map(async (group)=>{
820
- const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
821
- const indexHash = createHash(stringifiedIndex);
822
- indexHashByGroup[group] = indexHash;
823
- const [version, lang] = group.split('###');
824
- const indexVersion = version ? `.${version.replace('.', '_')}` : '';
825
- const indexLang = lang ? `.${lang}` : '';
826
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(constants_TEMP_DIR, {
827
- recursive: true
828
- });
829
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(constants_TEMP_DIR, `${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
830
- }));
831
- await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
832
1608
  const siteData = {
833
- title: userConfig?.title || '',
834
- description: userConfig?.description || '',
835
- icon: (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.getIconUrlPath)(userConfig?.icon) || '',
836
- route: userConfig?.route || {},
837
- themeConfig: normalizeThemeConfig(userConfig, pages),
838
- base: userConfig?.base || '/',
839
- lang: userConfig?.lang || '',
840
- locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
841
- logo: userConfig?.logo || '',
842
- logoText: userConfig?.logoText || '',
843
- ssg: Boolean(userConfig?.ssg ?? true),
844
- multiVersion: {
845
- default: userConfig?.multiVersion?.default || '',
846
- versions: userConfig?.multiVersion?.versions || []
847
- },
848
- search: tempSearchObj ?? {
849
- mode: 'local'
850
- },
851
- pages: pages.map((page)=>{
852
- const { content, id, domain, _filepath, _html, _flattenContent, ...rest } = page;
853
- return isProduction() ? rest : {
854
- ...rest,
855
- _filepath
856
- };
857
- }),
858
- markdown: {
859
- showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,
860
- defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,
861
- shiki: {}
862
- }
863
- };
864
- if (Array.isArray(siteData.pages[0]?.extraHighlightLanguages)) siteData.pages[0].extraHighlightLanguages.forEach((lang)=>highlightLanguages.add(lang));
865
- return {
866
- [`${types_RuntimeModuleID.SiteData}.mjs`]: `export default ${JSON.stringify(siteData, null, 2)}`,
867
- [types_RuntimeModuleID.SearchIndexHash]: `export default ${JSON.stringify(indexHashByGroup, null, 2)}`
868
- };
869
- }
870
- const runtimeModuleFactory = [
871
- siteDataVMPlugin
872
- ];
873
- function rsbuildPluginDocVM(factoryContext) {
874
- const { pluginDriver } = factoryContext;
875
- return {
876
- name: 'rsbuild-plugin-doc-vm',
877
- setup (api) {
878
- api.modifyBundlerChain(async (bundlerChain)=>{
879
- const alias = bundlerChain.resolve.alias.entries();
880
- const runtimeModule = {};
881
- for (const factory of runtimeModuleFactory){
882
- const moduleResult = await factory({
883
- ...factoryContext,
884
- alias: alias
885
- });
886
- Object.assign(runtimeModule, moduleResult);
887
- }
888
- const modulesByPlugin = await pluginDriver.addRuntimeModules();
889
- Object.keys(modulesByPlugin).forEach((key)=>{
890
- if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
891
- runtimeModule[key] = modulesByPlugin[key];
892
- });
893
- bundlerChain.plugin('rspress-runtime-module').use(new __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__.RspackVirtualModulePlugin(runtimeModule, factoryContext.runtimeTempDir));
894
- });
895
- }
896
- };
897
- }
898
- const globalStylesVMPlugin = (context)=>({
899
- [types_RuntimeModuleID.GlobalStyles]: ()=>{
900
- const { config, pluginDriver } = context;
901
- const globalStylesByPlugins = pluginDriver.globalStyles();
902
- const moduleContent = [
903
- config?.globalStyles,
904
- ...globalStylesByPlugins
905
- ].filter(Boolean).map((source)=>`import ${JSON.stringify(source)};`).join('');
906
- return moduleContent;
907
- }
908
- });
909
- const globalUIComponentsVMPlugin = (context)=>({
910
- [types_RuntimeModuleID.GlobalComponents]: ()=>{
911
- const { config, pluginDriver } = context;
912
- let index = 0;
913
- const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();
914
- const globalComponents = [
915
- ...config?.globalUIComponents || [],
916
- ...globalUIComponentsByPlugins
917
- ];
918
- const moduleContent = globalComponents.map((source)=>{
919
- const name = `Comp_${index}`;
920
- if (Array.isArray(source)) return `import ${name} from ${JSON.stringify(source[0])};
921
- const Props_${index++} = ${JSON.stringify(source[1])};\n`;
922
- index++;
923
- return `import ${name} from ${JSON.stringify(source)};\n`;
924
- }).concat(`export default [${Array.from({
925
- length: index
926
- }, (_, i)=>{
927
- if (Array.isArray(globalComponents[i])) return `[Comp_${i}, Props_${i}]`;
928
- return `Comp_${i}`;
929
- }).join(', ')}];`).join('');
930
- return moduleContent;
1609
+ base: userConfig.base ?? '/',
1610
+ title: userConfig?.title || '',
1611
+ description: userConfig?.description || '',
1612
+ icon: getIconUrlPath(userConfig?.icon) || '',
1613
+ route: userConfig?.route || {},
1614
+ themeConfig: await normalizeThemeConfig(userConfig),
1615
+ lang: userConfig?.lang || '',
1616
+ locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
1617
+ logo: userConfig?.logo || '',
1618
+ logoText: userConfig?.logoText || '',
1619
+ multiVersion: {
1620
+ default: userConfig?.multiVersion?.default || '',
1621
+ versions: userConfig?.multiVersion?.versions || []
1622
+ },
1623
+ search: tempSearchObj ?? {
1624
+ mode: 'local'
1625
+ },
1626
+ markdown: {
1627
+ showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,
1628
+ defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,
1629
+ shiki: {}
931
1630
  }
932
- });
933
- const routeListVMPlugin = (context)=>{
934
- const { routeService } = context;
1631
+ };
935
1632
  return {
936
- [types_RuntimeModuleID.RouteForClient]: ()=>routeService.generateRoutesCode(false),
937
- [types_RuntimeModuleID.RouteForSSR]: ({ environment })=>'node' === environment.name ? routeService.generateRoutesCode(true) : ''
1633
+ siteData
938
1634
  };
939
- };
940
- const searchHookVMPlugin = (context)=>({
941
- [`${types_RuntimeModuleID.SearchHooks}`]: ()=>{
942
- const { config } = context;
943
- let content = 'export const onSearch = () => {};';
944
- if ('object' == typeof config.search && 'string' == typeof config.search.searchHooks) content = `export * from '${config.search.searchHooks}'`;
945
- return content;
946
- }
947
- });
948
- async function writeSearchIndex(config) {
949
- if (config?.search === false) return;
950
- const cwd = process.cwd();
951
- const searchIndexFiles = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readdir(constants_TEMP_DIR);
952
- const outDir = config?.outDir ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, OUTPUT_DIR);
953
- const targetDir = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outDir, 'static');
954
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(targetDir, {
955
- recursive: true
956
- });
957
- let searchIndexData = '[]';
958
- let scanning = false;
959
- for (const searchIndexFile of searchIndexFiles){
960
- if (!searchIndexFile.includes(__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
961
- const source = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(constants_TEMP_DIR, searchIndexFile);
962
- const target = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(targetDir, searchIndexFile);
963
- const searchIndex = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(constants_TEMP_DIR, searchIndexFile), 'utf-8');
964
- searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? ',' : ''}${searchIndex.slice(1)}`;
965
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].rename(source, target);
966
- scanning = true;
967
- }
968
- if (isProduction() && (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isSCM)() && config?.search?.mode === 'remote') {
969
- const { apiUrl, indexName } = config.search;
970
- try {
971
- await fetch(`${apiUrl}?index=${indexName}`, {
972
- method: 'PUT',
973
- body: searchIndexData,
974
- headers: {
975
- 'Content-Type': 'application/json'
976
- }
977
- });
978
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info(__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].green(`[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`));
979
- } catch (e) {
980
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info(__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].red(`[doc-tools] Upload search index \`${indexName}\` failed:\n ${e}`));
1635
+ }
1636
+ const siteDataVMPlugin = (context)=>{
1637
+ const { config, pluginDriver } = context;
1638
+ return {
1639
+ ["virtual-site-data"]: async ({ addDependency })=>{
1640
+ const force = !pluginDriver.haveNavSidebarConfig;
1641
+ const metaFileSet = new Set();
1642
+ const mdFileSet = new Set();
1643
+ const now = performance.now();
1644
+ try {
1645
+ await modifyConfigWithAutoNavSide(config, metaFileSet, mdFileSet, force);
1646
+ } finally{
1647
+ for (const metaFile of metaFileSet)addDependency(metaFile);
1648
+ for (const mdFile of mdFileSet)addDependency(mdFile);
1649
+ logger.debug(`modifyConfigWithAutoNavSide - size: ${mdFileSet.size} cost: ${performance.now() - now}ms`);
1650
+ }
1651
+ const { siteData } = await createSiteData(config);
1652
+ return `export default ${JSON.stringify(siteData, null, 2)}`;
981
1653
  }
1654
+ };
1655
+ };
1656
+ const presetIcons = {
1657
+ discord: '<path fill="currentColor" d="M20.317 4.37a19.8 19.8 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.3 18.3 0 0 0-5.487 0a13 13 0 0 0-.617-1.25a.08.08 0 0 0-.079-.037A19.7 19.7 0 0 0 3.677 4.37a.1.1 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.08.08 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.08.08 0 0 0 .084-.028a14 14 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13 13 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10 10 0 0 0 .372-.292a.07.07 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.07.07 0 0 1 .078.01q.181.149.373.292a.077.077 0 0 1-.006.127a12.3 12.3 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.08.08 0 0 0 .084.028a19.8 19.8 0 0 0 6.002-3.03a.08.08 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.06.06 0 0 0-.031-.03M8.02 15.33c-1.182 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418m7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418"/>',
1658
+ facebook: '<path fill="currentColor" d="M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978c.401 0 .955.042 1.468.103a9 9 0 0 1 1.141.195v3.325a9 9 0 0 0-.653-.036a27 27 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.7 1.7 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103l-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647"/>',
1659
+ github: '<path fill="currentColor" d="M12 .297c-6.63 0-12 5.373-12 12c0 5.303 3.438 9.8 8.205 11.385c.6.113.82-.258.82-.577c0-.285-.01-1.04-.015-2.04c-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729c1.205.084 1.838 1.236 1.838 1.236c1.07 1.835 2.809 1.305 3.495.998c.108-.776.417-1.305.76-1.605c-2.665-.3-5.466-1.332-5.466-5.93c0-1.31.465-2.38 1.235-3.22c-.135-.303-.54-1.523.105-3.176c0 0 1.005-.322 3.3 1.23c.96-.267 1.98-.399 3-.405c1.02.006 2.04.138 3 .405c2.28-1.552 3.285-1.23 3.285-1.23c.645 1.653.24 2.873.12 3.176c.765.84 1.23 1.91 1.23 3.22c0 4.61-2.805 5.625-5.475 5.92c.42.36.81 1.096.81 2.22c0 1.606-.015 2.896-.015 3.286c0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/>',
1660
+ gitlab: '<path fill="currentColor" d="m23.6 9.593l-.033-.086L20.3.98a.85.85 0 0 0-.336-.405a.875.875 0 0 0-1 .054a.9.9 0 0 0-.29.44L16.47 7.818H7.537L5.333 1.07a.86.86 0 0 0-.29-.441a.875.875 0 0 0-1-.054a.86.86 0 0 0-.336.405L.433 9.502l-.032.086a6.066 6.066 0 0 0 2.012 7.01l.01.009l.03.021l4.977 3.727l2.462 1.863l1.5 1.132a1.01 1.01 0 0 0 1.22 0l1.499-1.132l2.461-1.863l5.006-3.75l.013-.01a6.07 6.07 0 0 0 2.01-7.002"/>',
1661
+ instagram: '<path fill="currentColor" d="M7.03.084c-1.277.06-2.149.264-2.91.563a5.9 5.9 0 0 0-2.124 1.388a5.9 5.9 0 0 0-1.38 2.127C.321 4.926.12 5.8.064 7.076s-.069 1.688-.063 4.947s.021 3.667.083 4.947c.061 1.277.264 2.149.563 2.911c.308.789.72 1.457 1.388 2.123a5.9 5.9 0 0 0 2.129 1.38c.763.295 1.636.496 2.913.552c1.278.056 1.689.069 4.947.063s3.668-.021 4.947-.082c1.28-.06 2.147-.265 2.91-.563a5.9 5.9 0 0 0 2.123-1.388a5.9 5.9 0 0 0 1.38-2.129c.295-.763.496-1.636.551-2.912c.056-1.28.07-1.69.063-4.948c-.006-3.258-.02-3.667-.081-4.947c-.06-1.28-.264-2.148-.564-2.911a5.9 5.9 0 0 0-1.387-2.123a5.9 5.9 0 0 0-2.128-1.38c-.764-.294-1.636-.496-2.914-.55C15.647.009 15.236-.006 11.977 0S8.31.021 7.03.084m.14 21.693c-1.17-.05-1.805-.245-2.228-.408a3.7 3.7 0 0 1-1.382-.895a3.7 3.7 0 0 1-.9-1.378c-.165-.423-.363-1.058-.417-2.228c-.06-1.264-.072-1.644-.08-4.848c-.006-3.204.006-3.583.061-4.848c.05-1.169.246-1.805.408-2.228c.216-.561.477-.96.895-1.382a3.7 3.7 0 0 1 1.379-.9c.423-.165 1.057-.361 2.227-.417c1.265-.06 1.644-.072 4.848-.08c3.203-.006 3.583.006 4.85.062c1.168.05 1.804.244 2.227.408c.56.216.96.475 1.382.895s.681.817.9 1.378c.165.422.362 1.056.417 2.227c.06 1.265.074 1.645.08 4.848c.005 3.203-.006 3.583-.061 4.848c-.051 1.17-.245 1.805-.408 2.23c-.216.56-.477.96-.896 1.38a3.7 3.7 0 0 1-1.378.9c-.422.165-1.058.362-2.226.418c-1.266.06-1.645.072-4.85.079s-3.582-.006-4.848-.06m9.783-16.192a1.44 1.44 0 1 0 1.437-1.442a1.44 1.44 0 0 0-1.437 1.442M5.839 12.012a6.161 6.161 0 1 0 12.323-.024a6.162 6.162 0 0 0-12.323.024M8 12.008A4 4 0 1 1 12.008 16A4 4 0 0 1 8 12.008"/>',
1662
+ linkedin: '<path fill="currentColor" d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037c-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85c3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.06 2.06 0 0 1-2.063-2.065a2.064 2.064 0 1 1 2.063 2.065m1.782 13.019H3.555V9h3.564zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0z"/>',
1663
+ slack: '<path fill="currentColor" d="M5.042 15.165a2.53 2.53 0 0 1-2.52 2.523A2.53 2.53 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52a2.527 2.527 0 0 1 2.521 2.52v6.313A2.53 2.53 0 0 1 8.834 24a2.53 2.53 0 0 1-2.521-2.522zM8.834 5.042a2.53 2.53 0 0 1-2.521-2.52A2.53 2.53 0 0 1 8.834 0a2.53 2.53 0 0 1 2.521 2.522v2.52zm0 1.271a2.53 2.53 0 0 1 2.521 2.521a2.53 2.53 0 0 1-2.521 2.521H2.522A2.53 2.53 0 0 1 0 8.834a2.53 2.53 0 0 1 2.522-2.521zm10.122 2.521a2.53 2.53 0 0 1 2.522-2.521A2.53 2.53 0 0 1 24 8.834a2.53 2.53 0 0 1-2.522 2.521h-2.522zm-1.268 0a2.53 2.53 0 0 1-2.523 2.521a2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.53 2.53 0 0 1 2.523 2.522zm-2.523 10.122a2.53 2.53 0 0 1 2.523 2.522A2.53 2.53 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522zm0-1.268a2.527 2.527 0 0 1-2.52-2.523a2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.53 2.53 0 0 1-2.522 2.523z"/>',
1664
+ youtube: '<path fill="currentColor" d="M23.498 6.186a3.02 3.02 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.02 3.02 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.02 3.02 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.02 3.02 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814M9.545 15.568V8.432L15.818 12z"/>',
1665
+ juejin: '<path fill="currentColor" d="m12 14.316l7.454-5.88l-2.022-1.625L12 11.1l-.004.003l-5.432-4.288l-2.02 1.624l7.452 5.88Zm0-7.247l2.89-2.298L12 2.453l-.004-.005l-2.884 2.318l2.884 2.3Zm0 11.266l-.005.002l-9.975-7.87L0 12.088l.194.156l11.803 9.308l7.463-5.885L24 12.085l-2.023-1.624Z"/>',
1666
+ qq: '<path fill="currentColor" d="M21.395 15.035a40 40 0 0 0-.803-2.264l-1.079-2.695c.001-.032.014-.562.014-.836C19.526 4.632 17.351 0 12 0S4.474 4.632 4.474 9.241c0 .274.013.804.014.836l-1.08 2.695a39 39 0 0 0-.802 2.264c-1.021 3.283-.69 4.643-.438 4.673c.54.065 2.103-2.472 2.103-2.472c0 1.469.756 3.387 2.394 4.771c-.612.188-1.363.479-1.845.835c-.434.32-.379.646-.301.778c.343.578 5.883.369 7.482.189c1.6.18 7.14.389 7.483-.189c.078-.132.132-.458-.301-.778c-.483-.356-1.233-.646-1.846-.836c1.637-1.384 2.393-3.302 2.393-4.771c0 0 1.563 2.537 2.103 2.472c.251-.03.581-1.39-.438-4.673"/>',
1667
+ wechat: '<path fill="currentColor" d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213c0 .163.13.295.29.295a.33.33 0 0 0 .167-.054l1.903-1.114a.86.86 0 0 1 .717-.098a10.2 10.2 0 0 0 2.837.403c.276 0 .543-.027.811-.05c-.857-2.578.157-4.972 1.932-6.446c1.703-1.415 3.882-1.98 5.853-1.838c-.576-3.583-4.196-6.348-8.596-6.348M5.785 5.991c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178A1.17 1.17 0 0 1 4.623 7.17c0-.651.52-1.18 1.162-1.18zm5.813 0c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178a1.17 1.17 0 0 1-1.162-1.178c0-.651.52-1.18 1.162-1.18m5.34 2.867c-1.797-.052-3.746.512-5.28 1.786c-1.72 1.428-2.687 3.72-1.78 6.22c.942 2.453 3.666 4.229 6.884 4.229c.826 0 1.622-.12 2.361-.336a.72.72 0 0 1 .598.082l1.584.926a.3.3 0 0 0 .14.047c.134 0 .24-.111.24-.247c0-.06-.023-.12-.038-.177l-.327-1.233a.6.6 0 0 1-.023-.156a.49.49 0 0 1 .201-.398C23.024 18.48 24 16.82 24 14.98c0-3.21-2.931-5.837-6.656-6.088V8.89c-.135-.01-.27-.027-.407-.03zm-2.53 3.274c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.97-.982zm4.844 0c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.969-.982"/>',
1668
+ weibo: '<path fill="currentColor" d="M17.525 11.378c1.263.392 2.669 1.336 2.669 3.004c0 2.763-3.98 6.239-9.964 6.239c-4.565 0-9.23-2.213-9.23-5.852c0-1.902 1.204-4.102 3.277-6.177c2.773-2.77 6.004-4.033 7.219-2.816c.537.537.588 1.464.244 2.572c-.178.557.525.25.525.25c2.24-.938 4.196-.994 4.909.027c.38.543.343 1.306-.008 2.19c-.163.407.048.471.36.563zm-7.282 7.939c3.641-.362 6.401-2.592 6.167-4.983c-.237-2.391-3.382-4.038-7.023-3.677c-3.64.36-6.403 2.59-6.167 4.98c.237 2.394 3.382 4.039 7.023 3.68zM6.16 14.438c.754-1.527 2.712-2.39 4.446-1.94c1.793.463 2.707 2.154 1.976 3.8c-.744 1.682-2.882 2.578-4.695 1.993c-1.752-.566-2.493-2.294-1.727-3.853zm1.446 2.587c.568.257 1.325.013 1.676-.55c.346-.568.163-1.217-.407-1.459c-.563-.237-1.291.008-1.64.553c-.354.547-.189 1.202.371 1.456zm2.206-1.808c.219.092.501-.012.628-.231c.123-.22.044-.466-.178-.548c-.216-.084-.486.018-.613.232c-.123.214-.054.458.163.547zM19.873 9.5a.725.725 0 1 1-1.378-.451a1.38 1.38 0 0 0-.288-1.357a1.395 1.395 0 0 0-1.321-.425a.723.723 0 1 1-.303-1.416a2.836 2.836 0 0 1 3.29 3.649zm-3.916-6.575A5.831 5.831 0 0 1 21.5 4.72a5.836 5.836 0 0 1 1.22 5.704a.838.838 0 0 1-1.06.54a.844.844 0 0 1-.542-1.062a4.143 4.143 0 0 0-4.807-5.327a.845.845 0 0 1-.354-1.65z"/>',
1669
+ zhihu: '<path fill="currentColor" d="M5.721 0C2.251 0 0 2.25 0 5.719V18.28C0 21.751 2.252 24 5.721 24h12.56C21.751 24 24 21.75 24 18.281V5.72C24 2.249 21.75 0 18.281 0zm1.964 4.078q-.408 1.096-.68 2.11h4.587c.545-.006.445 1.168.445 1.171H9.384a58 58 0 0 1-.112 3.797h2.712c.388.023.393 1.251.393 1.266H9.183a9.2 9.2 0 0 1-.408 2.102l.757-.604c.452.456 1.512 1.712 1.906 2.177c.473.681.063 2.081.063 2.081l-2.794-3.382c-.653 2.518-1.845 3.607-1.845 3.607c-.523.468-1.58.82-2.64.516c2.218-1.73 3.44-3.917 3.667-6.497H4.491c0-.015.197-1.243.806-1.266h2.71c.024-.32.086-3.254.086-3.797H6.598c-.136.406-.158.447-.268.753c-.594 1.095-1.603 1.122-1.907 1.155c.906-1.821 1.416-3.6 1.591-4.064c.425-1.124 1.671-1.125 1.671-1.125M13.078 6h6.377v11.33h-2.573l-2.184 1.373l-.401-1.373h-1.219zm1.313 1.219v8.86h.623l.263.937l1.455-.938h1.456v-8.86z"/>',
1670
+ bilibili: '<path fill="currentColor" d="M17.813 4.653h.854q2.266.08 3.773 1.574Q23.946 7.72 24 9.987v7.36q-.054 2.266-1.56 3.773c-1.506 1.507-2.262 1.524-3.773 1.56H5.333q-2.266-.054-3.773-1.56C.053 19.614.036 18.858 0 17.347v-7.36q.054-2.267 1.56-3.76t3.773-1.574h.774l-1.174-1.12a1.23 1.23 0 0 1-.373-.906q0-.534.373-.907l.027-.027q.4-.373.92-.373t.92.373L9.653 4.44q.107.106.187.213h4.267a.8.8 0 0 1 .16-.213l2.853-2.747q.4-.373.92-.373c.347 0 .662.151.929.4s.391.551.391.907q0 .532-.373.906zM5.333 7.24q-1.12.027-1.88.773q-.76.748-.786 1.894v7.52q.026 1.146.786 1.893t1.88.773h13.334q1.12-.026 1.88-.773t.786-1.893v-7.52q-.026-1.147-.786-1.894t-1.88-.773zM8 11.107q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q0-.56.386-.947q.387-.386.947-.386m8 0q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q.025-.586.4-.96q.373-.373.933-.373"/>',
1671
+ lark: '<path d="M6.14 3.8a28.88 28.88 0 0 1 6.6 7.63l1.7-1.67a8.37 8.37 0 0 1 2.82-1.83 12.23 12.23 0 0 0-2.32-4.28.67.67 0 0 0-.53-.25H6.28c-.21 0-.3.27-.14.4Z" fill="currentColor"></path><path d="m20.57 14.2.01-.02.04-.07-.05.08Z" fill="currentColor"></path><path d="M11.04 14.56c1.23.52 2.34.97 3.65 1.32a4.75 4.75 0 0 0 5.63-2.4l1.32-2.63c.3-.64.67-1.23 1.12-1.78a6.2 6.2 0 0 0-2.3-.44c-1.9 0-3.7.73-5.06 2.06l-2.02 2c-.72.7-1.5 1.33-2.34 1.87Z" fill="currentColor"></path><path d="M20.8 13.78v-.02l.01-.01s0 .02-.02.03Z" fill="currentColor"></path><path d="M1.63 9.75a.23.23 0 0 0-.4.16v7.96c0 .23.12.44.3.56a12.95 12.95 0 0 0 14.08.2c.78-.5 1.39-.92 2.04-1.55-1.05.3-2.2.33-3.37.01A28.99 28.99 0 0 1 1.63 9.75Z" fill="currentColor"></path>',
1672
+ x: '<path fill="currentColor" d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584l-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/>',
1673
+ bluesky: '<path fill="currentColor" d="M12 10.8c-1.087-2.114-4.046-6.053-6.798-7.995C2.566.944 1.561 1.266.902 1.565C.139 1.908 0 3.08 0 3.768c0 .69.378 5.65.624 6.479c.815 2.736 3.713 3.66 6.383 3.364q.204-.03.415-.056q-.207.033-.415.056c-3.912.58-7.387 2.005-2.83 7.078c5.013 5.19 6.87-1.113 7.823-4.308c.953 3.195 2.05 9.271 7.733 4.308c4.267-4.308 1.172-6.498-2.74-7.078a9 9 0 0 1-.415-.056q.21.026.415.056c2.67.297 5.568-.628 6.383-3.364c.246-.828.624-5.79.624-6.478c0-.69-.139-1.861-.902-2.206c-.659-.298-1.664-.62-4.3 1.24C16.046 4.748 13.087 8.687 12 10.8"/>',
1674
+ npm: '<path fill="currentColor" d="M1.763 0C.786 0 0 .786 0 1.763v20.474C0 23.214.786 24 1.763 24h20.474c.977 0 1.763-.786 1.763-1.763V1.763C24 .786 23.214 0 22.237 0zM5.13 5.323l13.837.019l-.009 13.836h-3.464l.01-10.382h-3.456L12.04 19.17H5.113z"/>'
1675
+ };
1676
+ const formatIconName = (icon)=>icon.toLowerCase();
1677
+ function getSocialIcons(socialLinks = []) {
1678
+ const icons = {};
1679
+ for (const link of socialLinks)if ('string' == typeof link.icon) {
1680
+ const pathContent = presetIcons[formatIconName(link.icon)];
1681
+ if (!pathContent) throw new Error(`Icon "${link.icon}" not found in preset icons.`);
1682
+ icons[link.icon] = `<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 24 24">${pathContent}</svg>`;
982
1683
  }
1684
+ return icons;
983
1685
  }
984
- function serveSearchIndexMiddleware(config) {
985
- return (req, res, next)=>{
986
- const searchIndexRequestMatch = `/${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.SEARCH_INDEX_NAME}.`;
987
- if (req.url?.includes(searchIndexRequestMatch)) {
988
- res.setHeader('Content-Type', 'application/json');
989
- const outDir = config?.outDir ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(process.cwd(), OUTPUT_DIR);
990
- const searchIndexFile = req.url.split('/').pop();
991
- (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.createReadStream)((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
992
- end: true
993
- });
994
- } else next?.();
1686
+ const socialLinksVMPlugin = (context)=>{
1687
+ const { config } = context;
1688
+ return {
1689
+ ["virtual-social-links"]: ()=>`export default ${JSON.stringify(getSocialIcons(config.themeConfig?.socialLinks), null, 2)}`
995
1690
  };
996
- }
997
- async function renderFrontmatterHead(route) {
998
- if (!isRouteMeta(route)) return '';
999
- const content = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(route.absolutePath, {
1000
- encoding: 'utf-8'
1691
+ };
1692
+ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true, signal } = {}) {
1693
+ return new Promise((resolve_, reject_)=>{
1694
+ if (void 0 === iterable[Symbol.iterator] && void 0 === iterable[Symbol.asyncIterator]) throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
1695
+ if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
1696
+ if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === 1 / 0)) throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
1697
+ const result = [];
1698
+ const errors = [];
1699
+ const skippedIndexesMap = new Map();
1700
+ let isRejected = false;
1701
+ let isResolved = false;
1702
+ let isIterableDone = false;
1703
+ let resolvingCount = 0;
1704
+ let currentIndex = 0;
1705
+ const iterator = void 0 === iterable[Symbol.iterator] ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
1706
+ const signalListener = ()=>{
1707
+ reject(signal.reason);
1708
+ };
1709
+ const cleanup = ()=>{
1710
+ signal?.removeEventListener('abort', signalListener);
1711
+ };
1712
+ const resolve = (value)=>{
1713
+ resolve_(value);
1714
+ cleanup();
1715
+ };
1716
+ const reject = (reason)=>{
1717
+ isRejected = true;
1718
+ isResolved = true;
1719
+ reject_(reason);
1720
+ cleanup();
1721
+ };
1722
+ if (signal) {
1723
+ if (signal.aborted) reject(signal.reason);
1724
+ signal.addEventListener('abort', signalListener, {
1725
+ once: true
1726
+ });
1727
+ }
1728
+ const next = async ()=>{
1729
+ if (isResolved) return;
1730
+ const nextItem = await iterator.next();
1731
+ const index = currentIndex;
1732
+ currentIndex++;
1733
+ if (nextItem.done) {
1734
+ isIterableDone = true;
1735
+ if (0 === resolvingCount && !isResolved) {
1736
+ if (!stopOnError && errors.length > 0) return void reject(new AggregateError(errors));
1737
+ isResolved = true;
1738
+ if (0 === skippedIndexesMap.size) return void resolve(result);
1739
+ const pureResult = [];
1740
+ for (const [index, value] of result.entries())if (skippedIndexesMap.get(index) !== pMapSkip) pureResult.push(value);
1741
+ resolve(pureResult);
1742
+ }
1743
+ return;
1744
+ }
1745
+ resolvingCount++;
1746
+ (async ()=>{
1747
+ try {
1748
+ const element = await nextItem.value;
1749
+ if (isResolved) return;
1750
+ const value = await mapper(element, index);
1751
+ if (value === pMapSkip) skippedIndexesMap.set(index, value);
1752
+ result[index] = value;
1753
+ resolvingCount--;
1754
+ await next();
1755
+ } catch (error) {
1756
+ if (stopOnError) reject(error);
1757
+ else {
1758
+ errors.push(error);
1759
+ resolvingCount--;
1760
+ try {
1761
+ await next();
1762
+ } catch (error) {
1763
+ reject(error);
1764
+ }
1765
+ }
1766
+ }
1767
+ })();
1768
+ };
1769
+ (async ()=>{
1770
+ for(let index = 0; index < concurrency; index++){
1771
+ try {
1772
+ await next();
1773
+ } catch (error) {
1774
+ reject(error);
1775
+ break;
1776
+ }
1777
+ if (isIterableDone || isRejected) break;
1778
+ }
1779
+ })();
1001
1780
  });
1002
- const { frontmatter: { head } } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(content, route.absolutePath, '', true);
1003
- if (!head || 0 === head.length) return '';
1004
- return head.map(([tag, attrs])=>`<${tag} ${renderAttrs(attrs)}>`).join('');
1005
1781
  }
1006
- async function renderConfigHead(config, route) {
1782
+ const pMapSkip = Symbol('skip');
1783
+ async function renderConfigHead(head, route) {
1007
1784
  if (!isRouteMeta(route)) return '';
1008
- if (!config.head || 0 === config.head.length) return '';
1009
- return config.head.map((head)=>{
1785
+ if (!head || 0 === head.length) return '';
1786
+ return head.map((head)=>{
1010
1787
  if ('string' == typeof head) return head;
1011
1788
  if ('function' == typeof head) {
1012
1789
  const resultHead = head(route);
@@ -1017,6 +1794,12 @@ async function renderConfigHead(config, route) {
1017
1794
  return `<${head[0]} ${renderAttrs(head[1])}>`;
1018
1795
  }).join('');
1019
1796
  }
1797
+ async function renderHtmlTemplate(htmlTemplate, head, route, appHtml = '') {
1798
+ const replacedHtmlTemplate = htmlTemplate.replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
1799
+ await renderConfigHead(head, route)
1800
+ ].join(''));
1801
+ return replacedHtmlTemplate;
1802
+ }
1020
1803
  function renderAttrs(attrs) {
1021
1804
  return Object.entries(attrs).map(([key, value])=>{
1022
1805
  if ('boolean' == typeof value) return key;
@@ -1027,83 +1810,203 @@ function renderAttrs(attrs) {
1027
1810
  function isRouteMeta(route) {
1028
1811
  return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
1029
1812
  }
1030
- async function renderPages(routeService, config, pluginDriver, ssrBundlePath, htmlTemplate, emitAsset) {
1031
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Rendering pages...');
1032
- const startTime = Date.now();
1813
+ async function renderPage(route, htmlTemplate, configHead, ssrBundlePath) {
1033
1814
  let render;
1034
1815
  try {
1035
- const { default: ssrExports } = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(ssrBundlePath).toString());
1036
- ({ render } = ssrExports);
1816
+ const { default: ssrExports } = await import((0, external_node_url_.pathToFileURL)(ssrBundlePath).toString());
1817
+ render = await ssrExports.render;
1037
1818
  } catch (e) {
1038
1819
  if (e instanceof Error) {
1039
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Failed to load SSG bundle: ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(ssrBundlePath)}: ${e.message}`);
1040
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
1820
+ logger.error(`Failed to load SSG bundle: ${picocolors.yellow(ssrBundlePath)}: ${e.message}`);
1821
+ logger.debug(e);
1041
1822
  hintSSGFailed();
1042
1823
  }
1043
1824
  throw e;
1044
1825
  }
1826
+ const head = createHead();
1827
+ const { routePath, absolutePath } = route;
1828
+ let appHtml = '';
1829
+ if (render) try {
1830
+ ({ appHtml } = await render(routePath, head));
1831
+ } catch (e) {
1832
+ if (e instanceof Error) {
1833
+ logger.error(`Page "${picocolors.yellow(routePath)}" SSG rendering failed.
1834
+ ${absolutePath ? picocolors.gray(` File: ${absolutePath}\n`) : ''} ${picocolors.gray(e.toString())}`);
1835
+ throw e;
1836
+ }
1837
+ }
1838
+ const replacedHtmlTemplate = await renderHtmlTemplate(htmlTemplate, configHead, route, appHtml);
1839
+ const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
1840
+ return html;
1841
+ }
1842
+ /**
1843
+ * these codes are copied from
1844
+ * @link https://github.com/facebook/docusaurus/blob/45065e8d2b5831117b8d69fec1be28f5520cf105/packages/docusaurus/src/ssg/ssgEnv.ts#L11
1845
+ * @license MIT
1846
+ */ function SSGWorkerThreadTaskSize() {
1847
+ return process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE, 10) : 10;
1848
+ }
1849
+ function SSGWorkerThreadRecyclerMaxMemory() {
1850
+ return process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY, 10) : 1000000000;
1851
+ }
1852
+ function inferNumberOfThreads({ pageCount, cpuCount, minPagesPerCpu }) {
1853
+ const threadsByWorkload = Math.ceil(pageCount / minPagesPerCpu);
1854
+ return Math.max(1, Math.min(threadsByWorkload, cpuCount));
1855
+ }
1856
+ function SSGWorkerThreadCount() {
1857
+ return process.env.RSPRESS_SSG_WORKER_THREAD_COUNT ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_COUNT, 10) : void 0;
1858
+ }
1859
+ function getNumberOfThreads(pathnamesLength) {
1860
+ const workerCount = SSGWorkerThreadCount();
1861
+ if (void 0 !== workerCount) return workerCount;
1862
+ const cpuCount = 'function' == typeof external_node_os_["default"].availableParallelism ? external_node_os_["default"].availableParallelism() : external_node_os_["default"].cpus().length;
1863
+ return inferNumberOfThreads({
1864
+ pageCount: pathnamesLength,
1865
+ cpuCount,
1866
+ minPagesPerCpu: 100
1867
+ });
1868
+ }
1869
+ function SSGConcurrency() {
1870
+ return process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32;
1871
+ }
1872
+ const routePath2HtmlFileName = (routePath)=>{
1873
+ let fileName = routePath;
1874
+ fileName = fileName.endsWith('/') ? `${routePath}index.html` : `${routePath}.html`;
1875
+ return fileName.replace(/^\/+/, '');
1876
+ };
1877
+ async function renderPages(routeService, config, ssrBundlePath, htmlTemplate, emitAsset) {
1878
+ logger.info('Rendering pages...');
1879
+ const startTime = Date.now();
1880
+ const ssg = config.ssg || true;
1045
1881
  try {
1046
1882
  const routes = routeService.getRoutes();
1047
- const base = config?.base ?? '';
1048
- const additionalRoutes = (await pluginDriver.addSSGRoutes()).map((route)=>({
1049
- routePath: (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withBase)(route.path, base)
1050
- }));
1051
- const allRoutes = [
1052
- ...routes,
1053
- ...additionalRoutes
1054
- ];
1055
- const is404RouteInRoutes = allRoutes.some((route)=>'/404' === route.routePath);
1056
- if (!is404RouteInRoutes) allRoutes.push({
1883
+ if (!routeService.isExistRoute('/404')) routes.push({
1057
1884
  routePath: '/404'
1058
1885
  });
1059
- await Promise.all(allRoutes.filter((route)=>!route.routePath.includes(':')).map(async (route)=>{
1060
- const head = (0, __WEBPACK_EXTERNAL_MODULE__unhead_react_server_7e85c952__.createHead)();
1061
- const { routePath } = route;
1062
- let appHtml = '';
1063
- if (render) try {
1064
- ({ appHtml } = await render(routePath, head));
1065
- } catch (e) {
1066
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Page "${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(routePath)}" SSG rendering failed.`);
1067
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
1068
- throw e;
1886
+ if ('object' == typeof ssg && Array.isArray(ssg?.experimentalExcludeRoutePaths) && ssg.experimentalExcludeRoutePaths.length > 0) {
1887
+ const shouldIgnoreRoutePaths = new Set();
1888
+ const shouldIgnoreRoutePathsRegExp = [];
1889
+ for (const routePath of ssg.experimentalExcludeRoutePaths)if ('string' == typeof routePath) shouldIgnoreRoutePaths.add(routePath);
1890
+ else if (routePath instanceof RegExp) shouldIgnoreRoutePathsRegExp.push(routePath);
1891
+ const promiseList = [];
1892
+ const csrRoutes = [];
1893
+ const ssgRoutes = [];
1894
+ for (const route of routes)if (shouldIgnoreRoutePaths.has(route.routePath) || shouldIgnoreRoutePathsRegExp.some((reg)=>reg.test(route.routePath))) {
1895
+ csrRoutes.push(route);
1896
+ promiseList.push(renderCSRPage(config.head, route, htmlTemplate, emitAsset));
1897
+ } else ssgRoutes.push(route);
1898
+ if (csrRoutes.length > 0) {
1899
+ logger.warn(`Some routes are ignored in SSG and fallback to CSR via \`ssg.experimentalExcludeRoutePaths\`: ${picocolors.yellow(csrRoutes.map((r)=>r.routePath).join(', '))}`);
1900
+ await Promise.all(promiseList);
1901
+ routes.length = 0;
1902
+ routes.push(...ssgRoutes);
1069
1903
  }
1070
- const replacedHtmlTemplate = htmlTemplate.replace(/<title>(.*?)<\/title>/gi, '').replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
1071
- await renderConfigHead(config, route),
1072
- await renderFrontmatterHead(route)
1073
- ].join(''));
1074
- const html = await (0, __WEBPACK_EXTERNAL_MODULE__unhead_react_server_7e85c952__.transformHtmlTemplate)(head, replacedHtmlTemplate);
1075
- const normalizeHtmlFilePath = (path)=>{
1076
- const normalizedBase = `${(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeSlash)(config?.base || '/')}/`;
1077
- if (path.endsWith('/')) return `${path}index.html`.replace(normalizedBase, '');
1078
- return `${path}.html`.replace(normalizedBase, '');
1079
- };
1080
- const fileName = normalizeHtmlFilePath(routePath);
1904
+ }
1905
+ if ('object' == typeof ssg && ssg?.experimentalWorker) {
1906
+ const numberOfThreads = getNumberOfThreads(routes.length);
1907
+ const Tinypool = await import("tinypool").then((m)=>m.default);
1908
+ const pool = new Tinypool({
1909
+ filename: new URL('./renderPageWorker.js', import.meta.url).href,
1910
+ concurrentTasksPerWorker: 1,
1911
+ minThreads: numberOfThreads,
1912
+ maxThreads: numberOfThreads,
1913
+ /**
1914
+ * https://github.com/facebook/docusaurus/blob/0306d182407bb98f140cd5ec7481fa9608fe0297/packages/docusaurus/src/ssg/ssgExecutor.ts#L123
1915
+ * @license MIT
1916
+ */ maxMemoryLimitBeforeRecycle: SSGWorkerThreadRecyclerMaxMemory(),
1917
+ isolateWorkers: false,
1918
+ workerData: {
1919
+ params: {
1920
+ htmlTemplate,
1921
+ head: config.head,
1922
+ ssrBundlePath
1923
+ }
1924
+ }
1925
+ });
1926
+ await Promise.all(chunk(routes, SSGWorkerThreadTaskSize()).map(async (routes)=>{
1927
+ const htmlList = await pool.run({
1928
+ routes
1929
+ });
1930
+ for(let i = 0; i < routes.length; i++){
1931
+ const route = routes[i];
1932
+ const html = htmlList[i];
1933
+ const fileName = routePath2HtmlFileName(route.routePath);
1934
+ emitAsset(fileName, html);
1935
+ }
1936
+ }));
1937
+ await pool.destroy();
1938
+ } else await pMap(routes, async (route)=>{
1939
+ const html = await renderPage(route, htmlTemplate, config.head, ssrBundlePath);
1940
+ const fileName = routePath2HtmlFileName(route.routePath);
1081
1941
  emitAsset(fileName, html);
1082
- }));
1942
+ }, {
1943
+ concurrency: SSGConcurrency()
1944
+ });
1083
1945
  const totalTime = Date.now() - startTime;
1084
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.success(`Pages rendered in ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(totalTime)} ms.`);
1946
+ logger.success(`Pages rendered in ${picocolors.yellow(totalTime)} ms.`);
1085
1947
  } catch (e) {
1086
1948
  if (e instanceof Error) {
1087
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Pages render error: ${e.message}`);
1088
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
1949
+ logger.error(`Pages render error: ${e.message}`);
1950
+ logger.debug(e);
1089
1951
  hintSSGFailed();
1090
1952
  }
1091
1953
  throw e;
1092
1954
  }
1093
1955
  }
1094
- const NODE_SSR_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
1095
- const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1956
+ async function renderCSRPage(head, route, htmlTemplate, emitAsset) {
1957
+ const html = await renderHtmlTemplate(htmlTemplate, head, route, '');
1958
+ const fileName = routePath2HtmlFileName(route.routePath);
1959
+ emitAsset(fileName, html);
1960
+ }
1961
+ async function renderCSRPages(routeService, config, htmlTemplate, emitAsset) {
1962
+ const routes = routeService.getRoutes();
1963
+ if (!routeService.isExistRoute('/404')) routes.push({
1964
+ routePath: '/404'
1965
+ });
1966
+ await Promise.all(routes.map((route)=>renderCSRPage(config.head, route, htmlTemplate, emitAsset)));
1967
+ }
1968
+ const rsbuildPluginCSR = ({ routeService, config })=>({
1969
+ name: 'rspress-inner-rsbuild-plugin-csr',
1970
+ async setup (api) {
1971
+ api.onBeforeBuild(()=>{
1972
+ api.processAssets({
1973
+ stage: 'report',
1974
+ environments: [
1975
+ 'web'
1976
+ ]
1977
+ }, async ({ assets, compilation, compiler })=>{
1978
+ if (compilation.errors.length > 0) return;
1979
+ const emitAsset = (assetName, content)=>{
1980
+ compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
1981
+ };
1982
+ let htmlTemplate = '';
1983
+ for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
1984
+ htmlTemplate = assetSource.source().toString();
1985
+ compilation.deleteAsset(assetName);
1986
+ break;
1987
+ }
1988
+ await renderCSRPages(routeService, config, htmlTemplate, emitAsset);
1989
+ });
1990
+ });
1991
+ }
1992
+ });
1993
+ const rsbuildPluginSSG = ({ routeService, config })=>({
1096
1994
  name: 'rspress-inner-rsbuild-plugin-ssg',
1097
1995
  async setup (api) {
1098
1996
  api.onBeforeBuild(()=>{
1099
1997
  let htmlTemplate = '';
1998
+ let hasError = false;
1100
1999
  const indexHtmlEmittedInWeb = new Promise((resolve, reject)=>{
1101
2000
  api.processAssets({
1102
2001
  stage: 'report',
1103
- targets: [
2002
+ environments: [
1104
2003
  'web'
1105
2004
  ]
1106
2005
  }, ({ assets, compilation })=>{
2006
+ if (compilation.errors.length > 0) {
2007
+ hasError = true;
2008
+ return;
2009
+ }
1107
2010
  for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
1108
2011
  htmlTemplate = assetSource.source().toString();
1109
2012
  compilation.deleteAsset(assetName);
@@ -1114,43 +2017,281 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1114
2017
  });
1115
2018
  }).catch(()=>{
1116
2019
  const message = 'SSG requires an `index.html` as entry, but this file is not emitted successfully in the web target.';
1117
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(message);
2020
+ logger.error(message);
1118
2021
  const error = new Error(message);
1119
2022
  throw error;
1120
2023
  });
1121
2024
  api.processAssets({
1122
2025
  stage: 'optimize-transfer',
1123
- targets: [
2026
+ environments: [
1124
2027
  'node'
1125
2028
  ]
1126
2029
  }, async ({ assets, compilation, environment, compiler })=>{
2030
+ if (compilation.errors.length > 0) {
2031
+ hasError = true;
2032
+ return;
2033
+ }
2034
+ if (hasError) return;
2035
+ const emitAsset = (assetName, content)=>{
2036
+ compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
2037
+ };
1127
2038
  const distPath = environment.distPath;
1128
- await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.mkdir)(distPath, {
2039
+ const ssgFolderPath = (0, external_node_path_.join)(distPath, NODE_SSG_BUNDLE_FOLDER);
2040
+ const mainCjsAbsolutePath = (0, external_node_path_.join)(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
2041
+ await mkdir(ssgFolderPath, {
1129
2042
  recursive: true
1130
2043
  });
1131
- let mainCjsAbsolutePath = '';
1132
- for (const [assetName, assetSource] of Object.entries(assets))if (assetName.includes(NODE_SSR_BUNDLE_NAME)) {
1133
- mainCjsAbsolutePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(distPath, assetName);
1134
- await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.writeFile)(mainCjsAbsolutePath, assetSource.source().toString());
1135
- compilation.deleteAsset(assetName);
1136
- break;
2044
+ await Promise.all(Object.entries(assets).map(async ([assetName, assetSource])=>{
2045
+ if (assetName.startsWith(`${NODE_SSG_BUNDLE_FOLDER}/`)) {
2046
+ const fileAbsolutePath = (0, external_node_path_.join)(distPath, assetName);
2047
+ await writeFile(fileAbsolutePath, assetSource.source().toString());
2048
+ compilation.deleteAsset(assetName);
2049
+ }
2050
+ }));
2051
+ await indexHtmlEmittedInWeb;
2052
+ await renderPages(routeService, config, mainCjsAbsolutePath, htmlTemplate, emitAsset);
2053
+ if (!(0, shared_.isDebugMode)()) await rm(ssgFolderPath, {
2054
+ recursive: true
2055
+ });
2056
+ });
2057
+ });
2058
+ }
2059
+ });
2060
+ function routePathToMdPath(routePath, base) {
2061
+ let url = routePath;
2062
+ url = (0, shared_.normalizeHref)(url, false);
2063
+ url = url.replace(/\.html$/, '.md');
2064
+ return (0, shared_.withBase)(url, base);
2065
+ }
2066
+ async function generateLlmsTxt(routeGroups, others, navList, title, description, base, routeService) {
2067
+ const lines = [];
2068
+ const summary = `# ${title}${description ? `\n\n> ${description}` : ''}`;
2069
+ async function genH2Part(nav, routes) {
2070
+ const lines = [];
2071
+ const { text } = nav;
2072
+ if (0 === routes.length) return lines;
2073
+ const routeLines = (await Promise.all(routes.map(async (route)=>{
2074
+ const routePage = routeService.getRoutePageByRoutePath(route);
2075
+ const { lang, routePath, absolutePath } = routePage.routeMeta;
2076
+ if ('/' === routePath || routePath === `/${lang}/`) return;
2077
+ const { title, description } = await extractInfoFromFrontmatterWithAbsolutePath(absolutePath, routeService.getDocsDir());
2078
+ return `- [${title}](${routePathToMdPath(routePath, base)})${description ? `: ${description}` : ''}`;
2079
+ }))).filter((i)=>Boolean(i));
2080
+ if (routeLines.length > 0) {
2081
+ const title = text;
2082
+ lines.push(`\n## ${title}\n`);
2083
+ lines.push(...routeLines);
2084
+ }
2085
+ return lines;
2086
+ }
2087
+ const h2Parts = await Promise.all(navList.map(async (nav, i)=>{
2088
+ const routes = routeGroups[i];
2089
+ const h2Part = await genH2Part(nav, routes);
2090
+ return h2Part;
2091
+ }));
2092
+ lines.push(...h2Parts.flat());
2093
+ const otherLines = await genH2Part({
2094
+ text: 'Others'
2095
+ }, others);
2096
+ lines.push(...otherLines);
2097
+ const llmsTxt = `${summary}\n${lines.join('\n')}`;
2098
+ return llmsTxt;
2099
+ }
2100
+ function generateLlmsFullTxt(routeGroups, navList, others, base, mdContents) {
2101
+ const lines = [];
2102
+ for(let i = 0; i < navList.length; i++){
2103
+ const routeGroup = routeGroups[i];
2104
+ if (0 !== routeGroup.length) for (const routePath of routeGroup){
2105
+ lines.push(`---
2106
+ url: ${routePathToMdPath(routePath, base)}
2107
+ ---
2108
+ `);
2109
+ lines.push(mdContents.get(routePath) ?? '');
2110
+ lines.push('\n');
2111
+ }
2112
+ }
2113
+ for (const routePath of others){
2114
+ lines.push(`---
2115
+ url: ${routePathToMdPath(routePath, base)}
2116
+ ---
2117
+ `);
2118
+ lines.push(mdContents.get(routePath) ?? '');
2119
+ lines.push('\n');
2120
+ }
2121
+ return lines.join('\n');
2122
+ }
2123
+ async function emitLlmsTxt(config, routeService, emitAsset, mdContents) {
2124
+ const base = config.base ?? '/';
2125
+ const locales = config.themeConfig?.locales;
2126
+ const isMultiLang = locales && locales.length > 0;
2127
+ const nav = isMultiLang ? locales.filter((i)=>Boolean(i.nav)).map((i)=>({
2128
+ nav: i.nav,
2129
+ lang: i.lang
2130
+ })) : [
2131
+ {
2132
+ nav: config.themeConfig?.nav,
2133
+ lang: config.lang ?? ''
2134
+ }
2135
+ ];
2136
+ const sidebars = isMultiLang ? locales.map((i)=>i.sidebar) : [
2137
+ config.themeConfig?.sidebar
2138
+ ];
2139
+ const sidebar = sidebars.reduce((prev, curr)=>{
2140
+ Object.assign(prev, curr);
2141
+ return prev;
2142
+ }, {});
2143
+ const noVersionNav = Array.isArray(nav) ? nav.map((i)=>{
2144
+ const nav = i.nav.default || i.nav;
2145
+ const lang = i.lang;
2146
+ return nav.map((i)=>({
2147
+ ...i,
2148
+ lang
2149
+ }));
2150
+ }).flat().filter((i)=>i.activeMatch || i.link) : [];
2151
+ const defaultLang = routeService.getDefaultLang();
2152
+ await Promise.all(routeService.getLangs().map(async (lang)=>{
2153
+ const navList = noVersionNav.filter((i)=>i.lang === lang);
2154
+ const routeGroups = new Array(navList.length).fill(0).map(()=>[]);
2155
+ const others = [];
2156
+ routeService.getRoutes().forEach((routeMeta)=>{
2157
+ if (routeMeta.lang !== lang) return;
2158
+ const { routePath } = routeMeta;
2159
+ for(let i = 0; i < routeGroups.length; i++){
2160
+ const routeGroup = routeGroups[i];
2161
+ const navItem = navList[i];
2162
+ if (lang === navItem.lang && new RegExp(navItem.activeMatch ?? navItem.link).test(routePath)) return void routeGroup.push(routePath);
2163
+ }
2164
+ others.push(routePath);
2165
+ });
2166
+ for (const routeGroup of routeGroups)organizeBySidebar(sidebar, routeGroup);
2167
+ const llmsTxtContent = await generateLlmsTxt(routeGroups, others, navList, config.title, config.description, config.base, routeService);
2168
+ const llmsFullTxtContent = generateLlmsFullTxt(routeGroups, navList, others, base, mdContents);
2169
+ const prefix = defaultLang === lang ? '' : `${lang}/`;
2170
+ emitAsset(`${prefix}llms.txt`, llmsTxtContent);
2171
+ emitAsset(`${prefix}llms-full.txt`, llmsFullTxtContent);
2172
+ }));
2173
+ }
2174
+ function flatSidebar(sidebar) {
2175
+ if (!sidebar) return [];
2176
+ return sidebar.flatMap((i)=>{
2177
+ if ('string' == typeof i) return i;
2178
+ if ('link' in i && 'string' == typeof i.link) return [
2179
+ i.link,
2180
+ ...flatSidebar(i?.items ?? [])
2181
+ ];
2182
+ if ('items' in i && Array.isArray(i.items)) return flatSidebar(i.items);
2183
+ }).filter(Boolean);
2184
+ }
2185
+ function organizeBySidebar(sidebar, routes) {
2186
+ if (0 === routes.length) return;
2187
+ const route = routes[0];
2188
+ const currSidebar = (0, shared_.getSidebarDataGroup)(sidebar, route);
2189
+ if (0 === currSidebar.length) return;
2190
+ const orderList = flatSidebar(currSidebar);
2191
+ routes.sort((a, b)=>{
2192
+ let aIndex = orderList.findIndex((order)=>matchPath(order, a));
2193
+ if (-1 === aIndex) aIndex = Number.MAX_SAFE_INTEGER;
2194
+ let bIndex = orderList.findIndex((order)=>matchPath(order, b));
2195
+ if (-1 === bIndex) bIndex = Number.MAX_SAFE_INTEGER;
2196
+ return aIndex - bIndex;
2197
+ });
2198
+ }
2199
+ async function renderPage_renderPage(route, ssrBundlePath) {
2200
+ let render;
2201
+ try {
2202
+ const { default: ssrExports } = await import((0, external_node_url_.pathToFileURL)(ssrBundlePath).toString());
2203
+ render = await ssrExports.render;
2204
+ } catch (e) {
2205
+ if (e instanceof Error) {
2206
+ logger.error(`Failed to load SSG bundle: ${picocolors.yellow(ssrBundlePath)}: ${e.message}`);
2207
+ logger.debug(e);
2208
+ hintSSGFailed();
2209
+ }
2210
+ throw e;
2211
+ }
2212
+ const head = createHead();
2213
+ const { routePath, absolutePath } = route;
2214
+ let appMd = '';
2215
+ if (render) try {
2216
+ ({ appMd } = await render(routePath, head));
2217
+ } catch (e) {
2218
+ if (e instanceof Error) {
2219
+ logger.error(`Page "${picocolors.yellow(routePath)}" SSG-MD rendering failed.
2220
+ ${absolutePath ? picocolors.gray(` File: ${absolutePath}\n`) : ''} ${picocolors.gray(e.toString())}`);
2221
+ throw e;
2222
+ }
2223
+ }
2224
+ return appMd;
2225
+ }
2226
+ const routePage2MdFilename = (routePath)=>{
2227
+ let fileName = routePath;
2228
+ fileName = fileName.endsWith('/') ? `${routePath}index.md` : `${routePath}.md`;
2229
+ return fileName.replace(/^\/+/, '');
2230
+ };
2231
+ async function renderPages_renderPages(routeService, ssrBundlePath, emitAsset) {
2232
+ logger.info('Rendering md pages...');
2233
+ const startTime = Date.now();
2234
+ const result = new Map();
2235
+ const routes = routeService.getRoutes();
2236
+ await pMap(routes, async (route)=>{
2237
+ const html = await renderPage_renderPage(route, ssrBundlePath);
2238
+ const fileName = routePage2MdFilename(route.routePath);
2239
+ emitAsset(fileName, html);
2240
+ result.set(route.routePath, html);
2241
+ }, {
2242
+ concurrency: SSGConcurrency()
2243
+ });
2244
+ const totalTime = Date.now() - startTime;
2245
+ logger.success(`Markdown rendered in ${picocolors.yellow(totalTime)} ms.`);
2246
+ return result;
2247
+ }
2248
+ const rsbuildPluginSSGMD = ({ routeService, config })=>({
2249
+ name: 'rspress-inner-rsbuild-plugin-ssg',
2250
+ async setup (api) {
2251
+ api.onBeforeBuild(()=>{
2252
+ let hasError = false;
2253
+ api.processAssets({
2254
+ stage: 'optimize-transfer',
2255
+ environments: [
2256
+ 'node_md'
2257
+ ]
2258
+ }, async ({ assets, compilation, environment, compiler })=>{
2259
+ if (compilation.errors.length > 0) {
2260
+ hasError = true;
2261
+ return;
1137
2262
  }
2263
+ if (hasError) return;
1138
2264
  const emitAsset = (assetName, content)=>{
1139
2265
  compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
1140
2266
  };
1141
- await indexHtmlEmittedInWeb;
1142
- await renderPages(routeService, config, pluginDriver, mainCjsAbsolutePath, htmlTemplate, emitAsset);
1143
- if (!(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isDebugMode)()) await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.rm)(mainCjsAbsolutePath);
2267
+ const distPath = environment.distPath;
2268
+ const ssgFolderPath = (0, external_node_path_.join)(distPath, NODE_SSG_MD_BUNDLE_FOLDER);
2269
+ const mainCjsAbsolutePath = (0, external_node_path_.join)(ssgFolderPath, NODE_SSG_MD_BUNDLE_NAME);
2270
+ await mkdir(ssgFolderPath, {
2271
+ recursive: true
2272
+ });
2273
+ await Promise.all(Object.entries(assets).map(async ([assetName, assetSource])=>{
2274
+ if (assetName.startsWith(`${NODE_SSG_MD_BUNDLE_FOLDER}/`)) {
2275
+ const fileAbsolutePath = (0, external_node_path_.join)(distPath, assetName);
2276
+ await writeFile(fileAbsolutePath, assetSource.source().toString());
2277
+ compilation.deleteAsset(assetName);
2278
+ }
2279
+ }));
2280
+ const mdContents = await renderPages_renderPages(routeService, mainCjsAbsolutePath, emitAsset);
2281
+ await emitLlmsTxt(config, routeService, emitAsset, mdContents);
2282
+ if (!(0, shared_.isDebugMode)()) await rm(ssgFolderPath, {
2283
+ recursive: true
2284
+ });
1144
2285
  });
1145
2286
  });
1146
2287
  }
1147
2288
  });
1148
- const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
2289
+ const Resolver = core_rspack.experiments.resolver.ResolverFactory;
1149
2290
  async function detectPackageMajorVersion(name) {
1150
2291
  const cwd = process.cwd();
1151
- const pkgPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'node_modules', name);
2292
+ const pkgPath = external_node_path_["default"].join(cwd, 'node_modules', name);
1152
2293
  if (await pathExists(pkgPath)) {
1153
- const pkgJson = await readJson(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(pkgPath, 'package.json'));
2294
+ const pkgJson = await readJson(external_node_path_["default"].join(pkgPath, 'package.json'));
1154
2295
  const version = Number(pkgJson.version?.split('.')[0]);
1155
2296
  return version;
1156
2297
  }
@@ -1161,8 +2302,7 @@ async function detectReactVersion() {
1161
2302
  }
1162
2303
  async function resolveReactRouterDomAlias() {
1163
2304
  const alias = {};
1164
- const resolver = detectReactVersion_ResolverFactory.createResolver({
1165
- fileSystem: new detectReactVersion_CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
2305
+ const resolver = new Resolver({
1166
2306
  mainFields: [
1167
2307
  'browser',
1168
2308
  'module',
@@ -1174,19 +2314,14 @@ async function resolveReactRouterDomAlias() {
1174
2314
  alias
1175
2315
  });
1176
2316
  try {
1177
- const pkgPath = await new Promise((resolve, reject)=>{
1178
- resolver.resolve({
1179
- importer: PACKAGE_ROOT
1180
- }, PACKAGE_ROOT, 'react-router-dom', {}, (err, filePath)=>{
1181
- if (err || !filePath) return reject(err);
1182
- return resolve(filePath);
1183
- });
1184
- });
2317
+ const resolved = await resolver.async(PACKAGE_ROOT, 'react-router-dom');
2318
+ if (resolved.error) throw Error(resolved.error);
2319
+ if (!resolved.path) throw Error("'react-router-dom' resolved to empty path");
1185
2320
  return {
1186
- 'react-router-dom': pkgPath
2321
+ 'react-router-dom': resolved.path
1187
2322
  };
1188
2323
  } catch (e) {
1189
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.warn('react-router-dom not found: \n', e);
2324
+ logger.warn('react-router-dom not found: \n', e);
1190
2325
  }
1191
2326
  return {};
1192
2327
  }
@@ -1201,93 +2336,72 @@ async function resolveReactAlias(reactVersion, isSSR) {
1201
2336
  'react-dom/server'
1202
2337
  ];
1203
2338
  const alias = {};
1204
- const resolver = detectReactVersion_ResolverFactory.createResolver({
1205
- fileSystem: new detectReactVersion_CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
2339
+ const resolver = new Resolver({
1206
2340
  extensions: [
1207
2341
  '.js'
1208
- ],
1209
- alias,
1210
- conditionNames: isSSR ? [
1211
- '...'
1212
- ] : [
1213
- 'browser',
1214
- '...'
1215
- ]
1216
- });
1217
- await Promise.all(libPaths.map(async (lib)=>{
1218
- try {
1219
- alias[lib] = await new Promise((resolve, reject)=>{
1220
- resolver.resolve({
1221
- importer: basedir
1222
- }, basedir, lib, {}, (err, filePath)=>{
1223
- if (err || !filePath) return reject(err);
1224
- return resolve(filePath);
1225
- });
1226
- });
1227
- } catch (e) {
1228
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.warn(`${lib} not found: \n`, e);
1229
- }
1230
- }));
1231
- return alias;
1232
- }
1233
- const detectCustomIcon = async (customThemeDir)=>{
1234
- const assetsDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(customThemeDir, 'assets');
1235
- const alias = {};
1236
- if (!(0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(assetsDir)) return alias;
1237
- const files = await (0, __WEBPACK_EXTERNAL_MODULE_tinyglobby__.glob)('*.svg', {
1238
- cwd: assetsDir
1239
- });
1240
- files.forEach((file)=>{
1241
- const name = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].basename(file, '.svg');
1242
- alias[`@theme-assets/${name}`] = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(assetsDir, file);
1243
- });
1244
- return alias;
1245
- };
1246
- const presetIcons = {
1247
- discord: '<path fill="currentColor" d="M20.317 4.37a19.8 19.8 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.3 18.3 0 0 0-5.487 0a13 13 0 0 0-.617-1.25a.08.08 0 0 0-.079-.037A19.7 19.7 0 0 0 3.677 4.37a.1.1 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.08.08 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.08.08 0 0 0 .084-.028a14 14 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13 13 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10 10 0 0 0 .372-.292a.07.07 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.07.07 0 0 1 .078.01q.181.149.373.292a.077.077 0 0 1-.006.127a12.3 12.3 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.08.08 0 0 0 .084.028a19.8 19.8 0 0 0 6.002-3.03a.08.08 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.06.06 0 0 0-.031-.03M8.02 15.33c-1.182 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418m7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418"/>',
1248
- facebook: '<path fill="currentColor" d="M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978c.401 0 .955.042 1.468.103a9 9 0 0 1 1.141.195v3.325a9 9 0 0 0-.653-.036a27 27 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.7 1.7 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103l-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647"/>',
1249
- github: '<path fill="currentColor" d="M12 .297c-6.63 0-12 5.373-12 12c0 5.303 3.438 9.8 8.205 11.385c.6.113.82-.258.82-.577c0-.285-.01-1.04-.015-2.04c-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729c1.205.084 1.838 1.236 1.838 1.236c1.07 1.835 2.809 1.305 3.495.998c.108-.776.417-1.305.76-1.605c-2.665-.3-5.466-1.332-5.466-5.93c0-1.31.465-2.38 1.235-3.22c-.135-.303-.54-1.523.105-3.176c0 0 1.005-.322 3.3 1.23c.96-.267 1.98-.399 3-.405c1.02.006 2.04.138 3 .405c2.28-1.552 3.285-1.23 3.285-1.23c.645 1.653.24 2.873.12 3.176c.765.84 1.23 1.91 1.23 3.22c0 4.61-2.805 5.625-5.475 5.92c.42.36.81 1.096.81 2.22c0 1.606-.015 2.896-.015 3.286c0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/>',
1250
- gitlab: '<path fill="currentColor" d="m23.6 9.593l-.033-.086L20.3.98a.85.85 0 0 0-.336-.405a.875.875 0 0 0-1 .054a.9.9 0 0 0-.29.44L16.47 7.818H7.537L5.333 1.07a.86.86 0 0 0-.29-.441a.875.875 0 0 0-1-.054a.86.86 0 0 0-.336.405L.433 9.502l-.032.086a6.066 6.066 0 0 0 2.012 7.01l.01.009l.03.021l4.977 3.727l2.462 1.863l1.5 1.132a1.01 1.01 0 0 0 1.22 0l1.499-1.132l2.461-1.863l5.006-3.75l.013-.01a6.07 6.07 0 0 0 2.01-7.002"/>',
1251
- instagram: '<path fill="currentColor" d="M7.03.084c-1.277.06-2.149.264-2.91.563a5.9 5.9 0 0 0-2.124 1.388a5.9 5.9 0 0 0-1.38 2.127C.321 4.926.12 5.8.064 7.076s-.069 1.688-.063 4.947s.021 3.667.083 4.947c.061 1.277.264 2.149.563 2.911c.308.789.72 1.457 1.388 2.123a5.9 5.9 0 0 0 2.129 1.38c.763.295 1.636.496 2.913.552c1.278.056 1.689.069 4.947.063s3.668-.021 4.947-.082c1.28-.06 2.147-.265 2.91-.563a5.9 5.9 0 0 0 2.123-1.388a5.9 5.9 0 0 0 1.38-2.129c.295-.763.496-1.636.551-2.912c.056-1.28.07-1.69.063-4.948c-.006-3.258-.02-3.667-.081-4.947c-.06-1.28-.264-2.148-.564-2.911a5.9 5.9 0 0 0-1.387-2.123a5.9 5.9 0 0 0-2.128-1.38c-.764-.294-1.636-.496-2.914-.55C15.647.009 15.236-.006 11.977 0S8.31.021 7.03.084m.14 21.693c-1.17-.05-1.805-.245-2.228-.408a3.7 3.7 0 0 1-1.382-.895a3.7 3.7 0 0 1-.9-1.378c-.165-.423-.363-1.058-.417-2.228c-.06-1.264-.072-1.644-.08-4.848c-.006-3.204.006-3.583.061-4.848c.05-1.169.246-1.805.408-2.228c.216-.561.477-.96.895-1.382a3.7 3.7 0 0 1 1.379-.9c.423-.165 1.057-.361 2.227-.417c1.265-.06 1.644-.072 4.848-.08c3.203-.006 3.583.006 4.85.062c1.168.05 1.804.244 2.227.408c.56.216.96.475 1.382.895s.681.817.9 1.378c.165.422.362 1.056.417 2.227c.06 1.265.074 1.645.08 4.848c.005 3.203-.006 3.583-.061 4.848c-.051 1.17-.245 1.805-.408 2.23c-.216.56-.477.96-.896 1.38a3.7 3.7 0 0 1-1.378.9c-.422.165-1.058.362-2.226.418c-1.266.06-1.645.072-4.85.079s-3.582-.006-4.848-.06m9.783-16.192a1.44 1.44 0 1 0 1.437-1.442a1.44 1.44 0 0 0-1.437 1.442M5.839 12.012a6.161 6.161 0 1 0 12.323-.024a6.162 6.162 0 0 0-12.323.024M8 12.008A4 4 0 1 1 12.008 16A4 4 0 0 1 8 12.008"/>',
1252
- linkedin: '<path fill="currentColor" d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037c-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85c3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.06 2.06 0 0 1-2.063-2.065a2.064 2.064 0 1 1 2.063 2.065m1.782 13.019H3.555V9h3.564zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0z"/>',
1253
- slack: '<path fill="currentColor" d="M5.042 15.165a2.53 2.53 0 0 1-2.52 2.523A2.53 2.53 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52a2.527 2.527 0 0 1 2.521 2.52v6.313A2.53 2.53 0 0 1 8.834 24a2.53 2.53 0 0 1-2.521-2.522zM8.834 5.042a2.53 2.53 0 0 1-2.521-2.52A2.53 2.53 0 0 1 8.834 0a2.53 2.53 0 0 1 2.521 2.522v2.52zm0 1.271a2.53 2.53 0 0 1 2.521 2.521a2.53 2.53 0 0 1-2.521 2.521H2.522A2.53 2.53 0 0 1 0 8.834a2.53 2.53 0 0 1 2.522-2.521zm10.122 2.521a2.53 2.53 0 0 1 2.522-2.521A2.53 2.53 0 0 1 24 8.834a2.53 2.53 0 0 1-2.522 2.521h-2.522zm-1.268 0a2.53 2.53 0 0 1-2.523 2.521a2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.53 2.53 0 0 1 2.523 2.522zm-2.523 10.122a2.53 2.53 0 0 1 2.523 2.522A2.53 2.53 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522zm0-1.268a2.527 2.527 0 0 1-2.52-2.523a2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.53 2.53 0 0 1-2.522 2.523z"/>',
1254
- youtube: '<path fill="currentColor" d="M23.498 6.186a3.02 3.02 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.02 3.02 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.02 3.02 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.02 3.02 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814M9.545 15.568V8.432L15.818 12z"/>',
1255
- juejin: '<path fill="currentColor" d="m12 14.316l7.454-5.88l-2.022-1.625L12 11.1l-.004.003l-5.432-4.288l-2.02 1.624l7.452 5.88Zm0-7.247l2.89-2.298L12 2.453l-.004-.005l-2.884 2.318l2.884 2.3Zm0 11.266l-.005.002l-9.975-7.87L0 12.088l.194.156l11.803 9.308l7.463-5.885L24 12.085l-2.023-1.624Z"/>',
1256
- qq: '<path fill="currentColor" d="M21.395 15.035a40 40 0 0 0-.803-2.264l-1.079-2.695c.001-.032.014-.562.014-.836C19.526 4.632 17.351 0 12 0S4.474 4.632 4.474 9.241c0 .274.013.804.014.836l-1.08 2.695a39 39 0 0 0-.802 2.264c-1.021 3.283-.69 4.643-.438 4.673c.54.065 2.103-2.472 2.103-2.472c0 1.469.756 3.387 2.394 4.771c-.612.188-1.363.479-1.845.835c-.434.32-.379.646-.301.778c.343.578 5.883.369 7.482.189c1.6.18 7.14.389 7.483-.189c.078-.132.132-.458-.301-.778c-.483-.356-1.233-.646-1.846-.836c1.637-1.384 2.393-3.302 2.393-4.771c0 0 1.563 2.537 2.103 2.472c.251-.03.581-1.39-.438-4.673"/>',
1257
- wechat: '<path fill="currentColor" d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213c0 .163.13.295.29.295a.33.33 0 0 0 .167-.054l1.903-1.114a.86.86 0 0 1 .717-.098a10.2 10.2 0 0 0 2.837.403c.276 0 .543-.027.811-.05c-.857-2.578.157-4.972 1.932-6.446c1.703-1.415 3.882-1.98 5.853-1.838c-.576-3.583-4.196-6.348-8.596-6.348M5.785 5.991c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178A1.17 1.17 0 0 1 4.623 7.17c0-.651.52-1.18 1.162-1.18zm5.813 0c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178a1.17 1.17 0 0 1-1.162-1.178c0-.651.52-1.18 1.162-1.18m5.34 2.867c-1.797-.052-3.746.512-5.28 1.786c-1.72 1.428-2.687 3.72-1.78 6.22c.942 2.453 3.666 4.229 6.884 4.229c.826 0 1.622-.12 2.361-.336a.72.72 0 0 1 .598.082l1.584.926a.3.3 0 0 0 .14.047c.134 0 .24-.111.24-.247c0-.06-.023-.12-.038-.177l-.327-1.233a.6.6 0 0 1-.023-.156a.49.49 0 0 1 .201-.398C23.024 18.48 24 16.82 24 14.98c0-3.21-2.931-5.837-6.656-6.088V8.89c-.135-.01-.27-.027-.407-.03zm-2.53 3.274c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.97-.982zm4.844 0c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.969-.982"/>',
1258
- weibo: '<path fill="currentColor" d="M17.525 11.378c1.263.392 2.669 1.336 2.669 3.004c0 2.763-3.98 6.239-9.964 6.239c-4.565 0-9.23-2.213-9.23-5.852c0-1.902 1.204-4.102 3.277-6.177c2.773-2.77 6.004-4.033 7.219-2.816c.537.537.588 1.464.244 2.572c-.178.557.525.25.525.25c2.24-.938 4.196-.994 4.909.027c.38.543.343 1.306-.008 2.19c-.163.407.048.471.36.563zm-7.282 7.939c3.641-.362 6.401-2.592 6.167-4.983c-.237-2.391-3.382-4.038-7.023-3.677c-3.64.36-6.403 2.59-6.167 4.98c.237 2.394 3.382 4.039 7.023 3.68zM6.16 14.438c.754-1.527 2.712-2.39 4.446-1.94c1.793.463 2.707 2.154 1.976 3.8c-.744 1.682-2.882 2.578-4.695 1.993c-1.752-.566-2.493-2.294-1.727-3.853zm1.446 2.587c.568.257 1.325.013 1.676-.55c.346-.568.163-1.217-.407-1.459c-.563-.237-1.291.008-1.64.553c-.354.547-.189 1.202.371 1.456zm2.206-1.808c.219.092.501-.012.628-.231c.123-.22.044-.466-.178-.548c-.216-.084-.486.018-.613.232c-.123.214-.054.458.163.547zM19.873 9.5a.725.725 0 1 1-1.378-.451a1.38 1.38 0 0 0-.288-1.357a1.395 1.395 0 0 0-1.321-.425a.723.723 0 1 1-.303-1.416a2.836 2.836 0 0 1 3.29 3.649zm-3.916-6.575A5.831 5.831 0 0 1 21.5 4.72a5.836 5.836 0 0 1 1.22 5.704a.838.838 0 0 1-1.06.54a.844.844 0 0 1-.542-1.062a4.143 4.143 0 0 0-4.807-5.327a.845.845 0 0 1-.354-1.65z"/>',
1259
- zhihu: '<path fill="currentColor" d="M5.721 0C2.251 0 0 2.25 0 5.719V18.28C0 21.751 2.252 24 5.721 24h12.56C21.751 24 24 21.75 24 18.281V5.72C24 2.249 21.75 0 18.281 0zm1.964 4.078q-.408 1.096-.68 2.11h4.587c.545-.006.445 1.168.445 1.171H9.384a58 58 0 0 1-.112 3.797h2.712c.388.023.393 1.251.393 1.266H9.183a9.2 9.2 0 0 1-.408 2.102l.757-.604c.452.456 1.512 1.712 1.906 2.177c.473.681.063 2.081.063 2.081l-2.794-3.382c-.653 2.518-1.845 3.607-1.845 3.607c-.523.468-1.58.82-2.64.516c2.218-1.73 3.44-3.917 3.667-6.497H4.491c0-.015.197-1.243.806-1.266h2.71c.024-.32.086-3.254.086-3.797H6.598c-.136.406-.158.447-.268.753c-.594 1.095-1.603 1.122-1.907 1.155c.906-1.821 1.416-3.6 1.591-4.064c.425-1.124 1.671-1.125 1.671-1.125M13.078 6h6.377v11.33h-2.573l-2.184 1.373l-.401-1.373h-1.219zm1.313 1.219v8.86h.623l.263.937l1.455-.938h1.456v-8.86z"/>',
1260
- bilibili: '<path fill="currentColor" d="M17.813 4.653h.854q2.266.08 3.773 1.574Q23.946 7.72 24 9.987v7.36q-.054 2.266-1.56 3.773c-1.506 1.507-2.262 1.524-3.773 1.56H5.333q-2.266-.054-3.773-1.56C.053 19.614.036 18.858 0 17.347v-7.36q.054-2.267 1.56-3.76t3.773-1.574h.774l-1.174-1.12a1.23 1.23 0 0 1-.373-.906q0-.534.373-.907l.027-.027q.4-.373.92-.373t.92.373L9.653 4.44q.107.106.187.213h4.267a.8.8 0 0 1 .16-.213l2.853-2.747q.4-.373.92-.373c.347 0 .662.151.929.4s.391.551.391.907q0 .532-.373.906zM5.333 7.24q-1.12.027-1.88.773q-.76.748-.786 1.894v7.52q.026 1.146.786 1.893t1.88.773h13.334q1.12-.026 1.88-.773t.786-1.893v-7.52q-.026-1.147-.786-1.894t-1.88-.773zM8 11.107q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q0-.56.386-.947q.387-.386.947-.386m8 0q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q.025-.586.4-.96q.373-.373.933-.373"/>',
1261
- lark: `<path d="M8.813 5.477c1.038.836 2.286 2.045 3.3 3.495.171.23.377.576.457.71l.034.056a8.803 8.803 0 0 0-.922 1.3l-.271-.494C9.655 7.53 6.3 5.477 6.137 5.377a.447.447 0 0 1-.006-.004l-.666-.393-.107-.086a.499.499 0 0 1 .306-.885L6.084 4h7.997c.159.006.318.037.47.092.174.064.317.174.458.308.134.143.272.296.403.448.622.675 1.324 1.688 1.324 1.688-.573.193-1.349.736-1.349.736a5.095 5.095 0 0 0-.348-.54 20.665 20.665 0 0 0-1.037-1.255H8.813Z" fill="currentColor"/>
1262
- <path d="M18.482 7.507a5.42 5.42 0 0 1 4.04.717c.248.168.788.635.242 1.233-1.7 1.67-2.194 3.225-2.63 4.599-.278.873-.541 1.697-1.066 2.424-1.813 2.508-4.114 4-6.837 4.434-.561.089-1.132.131-1.7.131-3.958 0-7.498-2.035-8.75-2.844h.003l-.161-.107c-.534-.378-.61-.723-.623-.989V7.055a.486.486 0 0 1 .827-.317l.482.589c5.082 6.201 9.126 8.063 11.626 8.53 2.246.424 3.631-.165 4.022-.37.333-.51.534-1.143.764-1.865l.006-.021c.406-1.276.898-2.821 2.322-4.477a3.93 3.93 0 0 0-2.28-.168c-1.761.394-3.403 1.96-4.89 4.643a8.27 8.27 0 0 0-.341.671c-.724-.107-1.334-.65-1.334-.65.128-.269.22-.455.345-.672 1.718-3.125 3.714-4.962 5.933-5.441ZM2.477 16.889c1.145.744 5.341 3.232 9.532 2.563 1.56-.247 2.963-.915 4.196-1.99-2.771.254-7.557-.753-13.728-7.666v7.093Z" fill="currentColor"/>`,
1263
- x: '<path fill="currentColor" d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584l-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/>',
1264
- bluesky: '<path fill="currentColor" d="M12 10.8c-1.087-2.114-4.046-6.053-6.798-7.995C2.566.944 1.561 1.266.902 1.565C.139 1.908 0 3.08 0 3.768c0 .69.378 5.65.624 6.479c.815 2.736 3.713 3.66 6.383 3.364q.204-.03.415-.056q-.207.033-.415.056c-3.912.58-7.387 2.005-2.83 7.078c5.013 5.19 6.87-1.113 7.823-4.308c.953 3.195 2.05 9.271 7.733 4.308c4.267-4.308 1.172-6.498-2.74-7.078a9 9 0 0 1-.415-.056q.21.026.415.056c2.67.297 5.568-.628 6.383-3.364c.246-.828.624-5.79.624-6.478c0-.69-.139-1.861-.902-2.206c-.659-.298-1.664-.62-4.3 1.24C16.046 4.748 13.087 8.687 12 10.8"/>'
1265
- };
1266
- const formatIconName = (icon)=>icon.toLowerCase();
1267
- function getSocialIcons(socialLinks = []) {
1268
- const icons = {};
1269
- for (const link of socialLinks)if ('string' == typeof link.icon) {
1270
- const pathContent = presetIcons[formatIconName(link.icon)];
1271
- icons[link.icon] = `<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 24 24">${pathContent}</svg>`;
1272
- }
1273
- return icons;
2342
+ ],
2343
+ alias,
2344
+ conditionNames: isSSR ? [
2345
+ '...'
2346
+ ] : [
2347
+ 'browser',
2348
+ '...'
2349
+ ]
2350
+ });
2351
+ await Promise.all(libPaths.map(async (lib)=>{
2352
+ try {
2353
+ const resolved = await resolver.async(basedir, lib);
2354
+ if (resolved.error || !resolved.path) throw Error(resolved.error);
2355
+ alias[lib] = resolved.path;
2356
+ } catch (e) {
2357
+ if (e instanceof Error) {
2358
+ logger.warn(`${lib} not found: \n ${picocolors.gray(e.toString())}`);
2359
+ hintReactVersion();
2360
+ }
2361
+ }
2362
+ }));
2363
+ return alias;
1274
2364
  }
2365
+ const detectCustomIcon = async (customThemeDir)=>{
2366
+ const assetsDir = external_node_path_["default"].join(customThemeDir, 'assets');
2367
+ const alias = {};
2368
+ if (!(0, external_node_fs_.existsSync)(assetsDir)) return alias;
2369
+ const files = await glob('*.svg', {
2370
+ cwd: assetsDir
2371
+ });
2372
+ files.forEach((file)=>{
2373
+ const name = external_node_path_["default"].basename(file, '.svg');
2374
+ alias[`@theme-assets/${name}`] = external_node_path_["default"].join(assetsDir, file);
2375
+ });
2376
+ return alias;
2377
+ };
1275
2378
  function isPluginIncluded(config, pluginName) {
1276
- return Boolean(config.builderPlugins?.some((plugin)=>plugin.name === pluginName) || config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
2379
+ return Boolean(config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
1277
2380
  }
1278
- async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver, runtimeTempDir) {
1279
- const cwd = process.cwd();
1280
- const CUSTOM_THEME_DIR = config?.themeDir ?? __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'theme');
2381
+ const initRsbuild_require = createRequire(import.meta.url);
2382
+ const initRsbuild_filename = (0, external_node_url_.fileURLToPath)(import.meta.url);
2383
+ const initRsbuild_dirname = external_node_path_["default"].dirname(initRsbuild_filename);
2384
+ async function getVirtualModulesFromPlugins(pluginDriver) {
2385
+ const runtimeModule = {};
2386
+ const modulesByPlugin = await pluginDriver.addRuntimeModules();
2387
+ Object.keys(modulesByPlugin).forEach((key)=>{
2388
+ if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
2389
+ runtimeModule[key] = ()=>modulesByPlugin[key];
2390
+ });
2391
+ return runtimeModule;
2392
+ }
2393
+ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
2394
+ const CUSTOM_THEME_DIR = config?.themeDir ?? external_node_path_["default"].join(process.cwd(), 'theme');
1281
2395
  const outDir = config?.outDir ?? OUTPUT_DIR;
1282
- const DEFAULT_THEME = require.resolve('@rspress/theme-default');
2396
+ const DEFAULT_THEME = external_node_path_["default"].join(initRsbuild_dirname, 'theme');
1283
2397
  const base = config?.base ?? '';
1284
- const assetPrefix = isProduction() ? (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
2398
+ const assetPrefix = isProduction() ? (0, shared_.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1285
2399
  const reactVersion = await detectReactVersion();
1286
2400
  const normalizeIcon = (icon)=>{
1287
2401
  if (!icon) return;
1288
2402
  icon = icon.toString();
1289
- if (icon.startsWith('file://')) icon = (0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(icon);
1290
- else if (__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].isAbsolute(icon)) return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(userDocRoot, PUBLIC_DIR, icon);
2403
+ if (icon.startsWith('file://')) icon = (0, external_node_url_.fileURLToPath)(icon);
2404
+ else if (external_node_path_["default"].isAbsolute(icon)) return external_node_path_["default"].join(userDocRoot, PUBLIC_DIR, icon);
1291
2405
  return icon;
1292
2406
  };
1293
2407
  await hintThemeBreakingChange(CUSTOM_THEME_DIR);
@@ -1295,53 +2409,62 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1295
2409
  detectCustomIcon(CUSTOM_THEME_DIR),
1296
2410
  resolveReactAlias(reactVersion, false),
1297
2411
  enableSSG ? resolveReactAlias(reactVersion, true) : Promise.resolve({}),
2412
+ resolveReactAlias(reactVersion, true),
1298
2413
  resolveReactRouterDomAlias()
1299
2414
  ]);
1300
2415
  const context = {
1301
2416
  userDocRoot,
1302
2417
  config,
1303
- runtimeTempDir,
1304
2418
  routeService,
1305
2419
  pluginDriver
1306
2420
  };
1307
2421
  return {
1308
2422
  plugins: [
1309
- ...isPluginIncluded(config, __WEBPACK_EXTERNAL_MODULE__rsbuild_plugin_react_7b149ee4__.PLUGIN_REACT_NAME) ? [] : [
1310
- (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_plugin_react_7b149ee4__.pluginReact)()
2423
+ ...isPluginIncluded(config, PLUGIN_REACT_NAME) ? [] : [
2424
+ pluginReact()
1311
2425
  ],
1312
- rsbuildPluginDocVM(context),
2426
+ rsbuildPluginDocVM({
2427
+ config,
2428
+ pluginDriver,
2429
+ routeService,
2430
+ userDocRoot
2431
+ }),
1313
2432
  pluginVirtualModule({
2433
+ tempDir: '.rspress/runtime',
1314
2434
  virtualModules: {
2435
+ ...socialLinksVMPlugin(context),
1315
2436
  ...i18nVMPlugin(context),
1316
2437
  ...globalUIComponentsVMPlugin(context),
1317
2438
  ...globalStylesVMPlugin(context),
1318
2439
  ...searchHookVMPlugin(context),
1319
- ...routeListVMPlugin(context)
2440
+ ...routeListVMPlugin(context),
2441
+ ...await getVirtualModulesFromPlugins(pluginDriver),
2442
+ ...siteDataVMPlugin(context)
1320
2443
  }
1321
2444
  }),
1322
- ...enableSSG ? [
1323
- rsbuildPluginSSG({
1324
- routeService,
1325
- config,
1326
- pluginDriver
1327
- })
1328
- ] : []
2445
+ enableSSG && config.ssg ? rsbuildPluginSSG({
2446
+ routeService,
2447
+ config
2448
+ }) : rsbuildPluginCSR({
2449
+ routeService,
2450
+ config
2451
+ }),
2452
+ enableSSG && config.llms ? rsbuildPluginSSGMD({
2453
+ routeService,
2454
+ config
2455
+ }) : null
1329
2456
  ],
1330
2457
  server: {
1331
2458
  port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1332
- printUrls: ({ urls })=>urls.map((url)=>`${url}/${(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.removeLeadingSlash)(base)}`),
1333
2459
  publicDir: {
1334
- name: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(userDocRoot, PUBLIC_DIR)
1335
- }
2460
+ name: external_node_path_["default"].join(userDocRoot, PUBLIC_DIR)
2461
+ },
2462
+ ...base.length > 0 ? {
2463
+ base: (0, shared_.removeTrailingSlash)(base)
2464
+ } : {}
1336
2465
  },
1337
2466
  dev: {
1338
2467
  lazyCompilation: 'false' !== process.env.RSPRESS_LAZY_COMPILATION,
1339
- progressBar: false,
1340
- setupMiddlewares: [
1341
- (middlewares)=>{
1342
- middlewares.unshift(serveSearchIndexMiddleware(config));
1343
- }
1344
- ],
1345
2468
  cliShortcuts: {
1346
2469
  custom: (shortcuts)=>shortcuts.filter(({ key })=>'r' !== key)
1347
2470
  }
@@ -1367,27 +2490,51 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1367
2490
  resolve: {
1368
2491
  alias: {
1369
2492
  ...detectCustomIconAlias,
1370
- '@mdx-js/react': require.resolve('@mdx-js/react'),
2493
+ '@mdx-js/react': initRsbuild_require.resolve('@mdx-js/react'),
1371
2494
  '@theme': [
1372
2495
  CUSTOM_THEME_DIR,
1373
2496
  DEFAULT_THEME
1374
2497
  ],
1375
- '@theme-assets': __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(DEFAULT_THEME, '../assets'),
1376
- '@rspress/core': PACKAGE_ROOT,
1377
- 'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
2498
+ '@theme-assets': external_node_path_["default"].join(DEFAULT_THEME, './assets'),
2499
+ 'react-lazy-with-preload': initRsbuild_require.resolve('react-lazy-with-preload'),
2500
+ '@rspress/core/theme': DEFAULT_THEME,
2501
+ '@rspress/core/runtime': external_node_path_["default"].join(initRsbuild_dirname, 'runtime.js'),
2502
+ '@rspress/core/shiki-transformers': external_node_path_["default"].join(initRsbuild_dirname, 'shiki-transformers.js')
1378
2503
  }
1379
2504
  },
1380
2505
  source: {
2506
+ preEntry: [
2507
+ external_node_path_["default"].join(DEFAULT_THEME, './styles/index.js'),
2508
+ 'virtual-global-styles',
2509
+ '@theme'
2510
+ ],
1381
2511
  include: [
1382
- PACKAGE_ROOT,
1383
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR)
2512
+ PACKAGE_ROOT
1384
2513
  ],
1385
2514
  define: {
1386
- 'process.env.TEST': JSON.stringify(process.env.TEST),
1387
- 'process.env.RSPRESS_SOCIAL_ICONS': JSON.stringify(getSocialIcons(config.themeConfig?.socialLinks))
2515
+ 'process.env.TEST': JSON.stringify(process.env.TEST)
1388
2516
  }
1389
2517
  },
1390
2518
  performance: {
2519
+ ...'false' !== process.env.RSPRESS_PERSISTENT_CACHE ? {
2520
+ buildCache: {
2521
+ buildDependencies: [
2522
+ initRsbuild_filename,
2523
+ pluginDriver.getConfigFilePath()
2524
+ ],
2525
+ cacheDigest: [
2526
+ routeService.generateRoutesCode(),
2527
+ JSON.stringify(config.themeConfig?.locales?.map((i)=>({
2528
+ nav: i.nav,
2529
+ sidebar: i.sidebar
2530
+ })) ?? {
2531
+ nav: config.themeConfig?.nav,
2532
+ sidebar: config.themeConfig?.sidebar
2533
+ }),
2534
+ package_namespaceObject.rE
2535
+ ]
2536
+ }
2537
+ } : {},
1391
2538
  chunkSplit: {
1392
2539
  override: {
1393
2540
  cacheGroups: {
@@ -1403,26 +2550,34 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1403
2550
  }
1404
2551
  },
1405
2552
  tools: {
1406
- bundlerChain (chain, { CHAIN_ID, target }) {
1407
- const isServer = 'node' === target;
2553
+ bundlerChain (chain, { CHAIN_ID, environment }) {
2554
+ const isSsg = 'node' === environment.name;
2555
+ const isSsgMd = 'node_md' === environment.name;
1408
2556
  const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
1409
2557
  const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
1410
- const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
1411
- chain.module.rule('MDX').type("javascript/auto").test(__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP).resolve.merge({
2558
+ chain.module.rule('MDX').type("javascript/auto").test(shared_.MDX_OR_MD_REGEXP).resolve.merge({
1412
2559
  conditionNames: jsModuleRule.resolve.conditionNames.values(),
1413
2560
  mainFields: jsModuleRule.resolve.mainFields.values()
1414
- }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
2561
+ }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(initRsbuild_require.resolve('./loader.js')).options({
1415
2562
  config,
1416
2563
  docDirectory: userDocRoot,
1417
- checkDeadLinks,
1418
2564
  routeService,
1419
- pluginDriver
2565
+ pluginDriver,
2566
+ isSsgMd
1420
2567
  }).end();
2568
+ chain.experiments({
2569
+ ...chain.get('experiments'),
2570
+ nativeWatcher: 'false' !== process.env.RSPRESS_NATIVE_WATCHER
2571
+ });
1421
2572
  if (chain.plugins.has(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH)) chain.plugin(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH).tap((options)=>{
1422
2573
  options[0] ??= {};
2574
+ options[0].test = [
2575
+ /\.([cm]js|[jt]sx?|flow)$/i,
2576
+ shared_.MDX_OR_MD_REGEXP
2577
+ ];
1423
2578
  options[0].include = [
1424
2579
  /\.([cm]js|[jt]sx?|flow)$/i,
1425
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP
2580
+ shared_.MDX_OR_MD_REGEXP
1426
2581
  ];
1427
2582
  return options;
1428
2583
  });
@@ -1430,7 +2585,14 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1430
2585
  chain.module.rule('css-virtual-module').test(/\.rspress[\\/]runtime[\\/]virtual-global-styles/).merge({
1431
2586
  sideEffects: true
1432
2587
  });
1433
- if (isServer) chain.output.filename(NODE_SSR_BUNDLE_NAME);
2588
+ if (isSsg || isSsgMd) chain.optimization.splitChunks({});
2589
+ if (isSsg) {
2590
+ chain.output.filename(`${NODE_SSG_BUNDLE_FOLDER}/${NODE_SSG_BUNDLE_NAME}`);
2591
+ chain.output.chunkFilename(`${NODE_SSG_BUNDLE_FOLDER}/[name].cjs`);
2592
+ } else if (isSsgMd) {
2593
+ chain.output.filename(`${NODE_SSG_MD_BUNDLE_FOLDER}/${NODE_SSG_MD_BUNDLE_NAME}`);
2594
+ chain.output.chunkFilename(`${NODE_SSG_MD_BUNDLE_FOLDER}/[name].cjs`);
2595
+ }
1434
2596
  }
1435
2597
  },
1436
2598
  environments: {
@@ -1438,8 +2600,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1438
2600
  resolve: {
1439
2601
  alias: {
1440
2602
  ...reactCSRAlias,
1441
- ...reactRouterDomAlias,
1442
- __VIRTUAL_ROUTES__: 'virtual-routes'
2603
+ ...reactRouterDomAlias
1443
2604
  }
1444
2605
  },
1445
2606
  source: {
@@ -1447,7 +2608,8 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1447
2608
  index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
1448
2609
  },
1449
2610
  define: {
1450
- 'process.env.__SSR__': JSON.stringify(false)
2611
+ 'process.env.__SSR__': JSON.stringify(false),
2612
+ 'process.env.__SSR_MD__': JSON.stringify(false)
1451
2613
  }
1452
2614
  },
1453
2615
  output: {
@@ -1457,28 +2619,58 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1457
2619
  }
1458
2620
  }
1459
2621
  },
1460
- ...enableSSG ? {
2622
+ ...enableSSG && config.ssg ? {
1461
2623
  node: {
1462
2624
  resolve: {
1463
2625
  alias: {
1464
2626
  ...reactSSRAlias,
1465
- ...reactRouterDomAlias,
1466
- __VIRTUAL_ROUTES__: 'virtual-routes-ssr'
2627
+ ...reactRouterDomAlias
2628
+ }
2629
+ },
2630
+ source: {
2631
+ entry: {
2632
+ index: SSR_SERVER_ENTRY
2633
+ },
2634
+ define: {
2635
+ 'process.env.__SSR__': JSON.stringify(true),
2636
+ 'process.env.__SSR_MD__': JSON.stringify(false)
2637
+ }
2638
+ },
2639
+ performance: {
2640
+ printFileSize: {
2641
+ compressed: true
2642
+ }
2643
+ },
2644
+ output: {
2645
+ emitAssets: false,
2646
+ target: 'node',
2647
+ minify: false
2648
+ }
2649
+ }
2650
+ } : {},
2651
+ ...enableSSG && config.llms ? {
2652
+ node_md: {
2653
+ resolve: {
2654
+ alias: {
2655
+ ...reactSSRAlias,
2656
+ ...reactRouterDomAlias
1467
2657
  }
1468
2658
  },
1469
2659
  tools: {
1470
2660
  rspack: {
1471
- output: {
1472
- asyncChunks: false
2661
+ optimization: {
2662
+ moduleIds: 'named',
2663
+ chunkIds: 'named'
1473
2664
  }
1474
2665
  }
1475
2666
  },
1476
2667
  source: {
1477
2668
  entry: {
1478
- index: SSR_SERVER_ENTRY
2669
+ index: SSG_MD_SERVER_ENTRY
1479
2670
  },
1480
2671
  define: {
1481
- 'process.env.__SSR__': JSON.stringify(true)
2672
+ 'process.env.__SSR__': JSON.stringify(true),
2673
+ 'process.env.__SSR_MD__': JSON.stringify(true)
1482
2674
  }
1483
2675
  },
1484
2676
  performance: {
@@ -1496,59 +2688,181 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1496
2688
  }
1497
2689
  };
1498
2690
  }
1499
- async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuildConfig) {
2691
+ async function initRsbuild(rootDir, config, pluginDriver, routeService, enableSSG, extraRsbuildConfig) {
1500
2692
  const cwd = process.cwd();
1501
- const userDocRoot = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(rootDir || config?.root || cwd);
1502
- const builderPlugins = config?.builderPlugins ?? [];
1503
- const runtimeTempDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR, 'runtime');
1504
- const runtimeAbsTempDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'node_modules', runtimeTempDir);
1505
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(runtimeAbsTempDir, {
1506
- recursive: true
1507
- });
1508
- const routeService = await initRouteService({
1509
- config,
1510
- runtimeTempDir: runtimeAbsTempDir,
1511
- scanDir: userDocRoot,
1512
- pluginDriver
1513
- });
2693
+ const userDocRoot = external_node_path_["default"].resolve(rootDir || config?.root || cwd);
2694
+ hintBuilderPluginsBreakingChange(config);
1514
2695
  const { createRsbuild, mergeRsbuildConfig } = await import("@rsbuild/core");
1515
- const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver, runtimeTempDir);
2696
+ const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver);
1516
2697
  const rsbuild = await createRsbuild({
1517
2698
  callerName: 'rspress',
1518
- rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], config?.builderConfig || {}, extraRsbuildConfig || {})
2699
+ rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], config.builderConfig || {}, extraRsbuildConfig || {})
1519
2700
  });
1520
- rsbuild.addPlugins(builderPlugins);
1521
2701
  return rsbuild;
1522
2702
  }
2703
+ class PluginDriver {
2704
+ #config;
2705
+ #configFilePath;
2706
+ #plugins;
2707
+ #isProd;
2708
+ haveNavSidebarConfig = false;
2709
+ static async create(config, configFilePath, isProd) {
2710
+ const pluginDriver = new PluginDriver(config, configFilePath, isProd);
2711
+ await pluginDriver.init();
2712
+ return pluginDriver;
2713
+ }
2714
+ constructor(config, configFilePath, isProd){
2715
+ this.#config = config;
2716
+ this.#configFilePath = configFilePath;
2717
+ this.#isProd = isProd;
2718
+ this.#plugins = [];
2719
+ }
2720
+ getConfigFilePath() {
2721
+ return this.#configFilePath;
2722
+ }
2723
+ async init() {
2724
+ this.clearPlugins();
2725
+ const config = this.#config;
2726
+ const themeConfig = config?.themeConfig || {};
2727
+ const enableLastUpdated = themeConfig?.lastUpdated;
2728
+ const mediumZoomConfig = config?.mediumZoom ?? true;
2729
+ if (enableLastUpdated) {
2730
+ const { pluginLastUpdated } = await Promise.all([
2731
+ __webpack_require__.e("101"),
2732
+ __webpack_require__.e("395")
2733
+ ]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
2734
+ this.addPlugin(pluginLastUpdated());
2735
+ }
2736
+ if (mediumZoomConfig) {
2737
+ const { pluginMediumZoom } = await __webpack_require__.e("335").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
2738
+ this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
2739
+ }
2740
+ (config.plugins || []).forEach((plugin)=>{
2741
+ this.addPlugin(plugin);
2742
+ });
2743
+ }
2744
+ addPlugin(plugin) {
2745
+ const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
2746
+ if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
2747
+ this.#plugins.push(plugin);
2748
+ }
2749
+ getPlugins() {
2750
+ return this.#plugins;
2751
+ }
2752
+ clearPlugins() {
2753
+ this.#plugins = [];
2754
+ }
2755
+ removePlugin(pluginName) {
2756
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2757
+ if (-1 !== index) this.#plugins.splice(index, 1);
2758
+ }
2759
+ async normalizeConfig() {
2760
+ this.#config.ssg ??= true;
2761
+ this.#config.llms ??= false;
2762
+ this.#config.base = (0, shared_.addTrailingSlash)((0, shared_.addLeadingSlash)(this.#config.base ?? '/'));
2763
+ this.#config.lang ??= 'en';
2764
+ }
2765
+ async modifyConfig() {
2766
+ this.normalizeConfig();
2767
+ let config = this.#config;
2768
+ for(let i = 0; i < this.#plugins.length; i++){
2769
+ const plugin = this.#plugins[i];
2770
+ if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
2771
+ addPlugin: this.addPlugin.bind(this),
2772
+ removePlugin: (pluginName)=>{
2773
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2774
+ this.removePlugin(pluginName);
2775
+ if (index <= i && index > 0) i--;
2776
+ }
2777
+ }, this.#isProd);
2778
+ }
2779
+ this.#config = config;
2780
+ this.haveNavSidebarConfig = auto_nav_sidebar_haveNavSidebarConfig(config);
2781
+ return this.#config;
2782
+ }
2783
+ async beforeBuild() {
2784
+ return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
2785
+ }
2786
+ async afterBuild() {
2787
+ return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
2788
+ }
2789
+ async modifySearchIndexData(pages) {
2790
+ return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
2791
+ }
2792
+ async extendPageData(pageData) {
2793
+ return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
2794
+ }
2795
+ async addPages() {
2796
+ const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
2797
+ return result.flat();
2798
+ }
2799
+ async routeGenerated(routes) {
2800
+ return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
2801
+ }
2802
+ async routeServiceGenerated(routeService) {
2803
+ return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
2804
+ }
2805
+ async addRuntimeModules() {
2806
+ const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
2807
+ return result.reduce((prev, current)=>({
2808
+ ...prev,
2809
+ ...current
2810
+ }), {});
2811
+ }
2812
+ async i18nSource(defaultSource) {
2813
+ let i18nSource = defaultSource;
2814
+ for (const plugin of this.#plugins)if ('function' == typeof plugin.i18nSource) i18nSource = await plugin.i18nSource(i18nSource) || i18nSource;
2815
+ return i18nSource;
2816
+ }
2817
+ globalUIComponents() {
2818
+ const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
2819
+ return result.flat();
2820
+ }
2821
+ globalStyles() {
2822
+ return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
2823
+ }
2824
+ _runParallelAsyncHook(hookName, ...args) {
2825
+ return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
2826
+ }
2827
+ _runSerialAsyncHook(hookName, ...args) {
2828
+ return this.#plugins.reduce(async (prev, plugin)=>{
2829
+ if ('function' == typeof plugin[hookName]) {
2830
+ await prev;
2831
+ return plugin[hookName](...args);
2832
+ }
2833
+ return prev;
2834
+ }, Promise.resolve());
2835
+ }
2836
+ }
1523
2837
  function checkLanguageParity_normalizePath(filePath) {
1524
- return filePath.split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/');
2838
+ return filePath.split(external_node_path_["default"].sep).join('/');
1525
2839
  }
1526
2840
  async function getAllMarkdownFilesFrom(dirPath) {
1527
- const files = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readdir(dirPath, {
2841
+ const files = await node_fs_promises.readdir(dirPath, {
1528
2842
  withFileTypes: true
1529
2843
  });
1530
2844
  const allFiles = [];
1531
2845
  for (const file of files){
1532
- const fullPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirPath, file.name);
2846
+ const fullPath = external_node_path_["default"].join(dirPath, file.name);
1533
2847
  if (file.isDirectory()) {
1534
2848
  const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
1535
2849
  allFiles.push(...nestedFiles);
1536
2850
  } else if ([
1537
2851
  '.md',
1538
2852
  '.mdx'
1539
- ].includes(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(file.name))) allFiles.push(fullPath);
2853
+ ].includes(external_node_path_["default"].extname(file.name))) allFiles.push(fullPath);
1540
2854
  }
1541
2855
  return allFiles;
1542
2856
  }
1543
2857
  async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
1544
- const langDirPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(contentPath, lang);
1545
- const langModuleDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(langDirPath, includedDir);
2858
+ const langDirPath = external_node_path_["default"].join(contentPath, lang);
2859
+ const langModuleDir = external_node_path_["default"].join(langDirPath, includedDir);
1546
2860
  try {
1547
- const moduleDirStats = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].stat(langModuleDir);
2861
+ const moduleDirStats = await node_fs_promises.stat(langModuleDir);
1548
2862
  if (!moduleDirStats.isDirectory()) return fileLangMap;
1549
2863
  const files = await getAllMarkdownFilesFrom(langModuleDir);
1550
2864
  for (const file of files){
1551
- const relativePath = checkLanguageParity_normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(langDirPath, file));
2865
+ const relativePath = checkLanguageParity_normalizePath(external_node_path_["default"].relative(langDirPath, file));
1552
2866
  if (excludedDirs.some((excludedDir)=>{
1553
2867
  const isFilePath = /\.(md|mdx)$/.test(excludedDir);
1554
2868
  return relativePath.includes(excludedDir + (isFilePath ? '' : '/'));
@@ -1558,21 +2872,21 @@ async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs,
1558
2872
  fileLangMap[baseName].add(lang);
1559
2873
  }
1560
2874
  } catch (e) {
1561
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(e);
2875
+ logger.error(e);
1562
2876
  throw new Error(`Failed to access directory: ${checkLanguageParity_normalizePath(langModuleDir)}`);
1563
2877
  }
1564
2878
  return fileLangMap;
1565
2879
  }
1566
2880
  async function checkLanguageParity(config) {
1567
2881
  if (!config?.languageParity || false === config.languageParity.enabled) return;
1568
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Checking language parity...');
1569
- const contentPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(config.root);
2882
+ logger.info('Checking language parity...');
2883
+ const contentPath = external_node_path_["default"].resolve(config.root);
1570
2884
  const includedDirs = config.languageParity.include?.length ? config.languageParity.include : [
1571
2885
  ''
1572
2886
  ];
1573
2887
  const excludedDirs = config.languageParity.exclude ?? [];
1574
2888
  const supportedLanguages = (config.locales ?? config.themeConfig?.locales)?.map((locale)=>locale.lang) || [];
1575
- if (!supportedLanguages.length) return void __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error('No supported languages found in the configuration.');
2889
+ if (!supportedLanguages.length) return void logger.error('No supported languages found in the configuration.');
1576
2890
  const missingLanguagesFile = [];
1577
2891
  try {
1578
2892
  for (const includedDir of includedDirs){
@@ -1582,28 +2896,59 @@ async function checkLanguageParity(config) {
1582
2896
  for (const [baseName, langs] of Object.entries(curFileLangMap)){
1583
2897
  const missingLangs = supportedLanguages.filter((lang)=>!langs.has(lang));
1584
2898
  missingLangs.forEach((lang)=>{
1585
- const missingPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(lang, baseName);
2899
+ const missingPath = external_node_path_["default"].join(lang, baseName);
1586
2900
  missingLanguagesFile.push(missingPath);
1587
2901
  });
1588
2902
  }
1589
2903
  }
1590
2904
  if (missingLanguagesFile.length > 0) throw new Error(`Check language parity failed! Missing content:\n${missingLanguagesFile.map((file)=>` - ${checkLanguageParity_normalizePath(file)}`).join('\n')}`);
1591
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.success('Language parity checked successfully.');
2905
+ logger.success('Language parity checked successfully.');
1592
2906
  } catch (err) {
1593
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error('Error during language parity check: \n', err);
2907
+ logger.error('Error during language parity check: \n', err);
1594
2908
  throw err;
1595
2909
  }
1596
2910
  }
2911
+ async function build(options) {
2912
+ const { docDirectory, config, configFilePath } = options;
2913
+ const pluginDriver = await PluginDriver.create(config, configFilePath, true);
2914
+ const modifiedConfig = await pluginDriver.modifyConfig();
2915
+ const enableSSG = Boolean((modifiedConfig.ssg || modifiedConfig.llms) ?? true);
2916
+ const additionalPages = await pluginDriver.addPages();
2917
+ const routeService = await RouteService.create({
2918
+ config: modifiedConfig,
2919
+ scanDir: docDirectory,
2920
+ externalPages: additionalPages
2921
+ });
2922
+ await pluginDriver.routeGenerated(routeService.getRoutes());
2923
+ await pluginDriver.routeServiceGenerated(routeService);
2924
+ await modifyConfigWithAutoNavSide(modifiedConfig);
2925
+ try {
2926
+ await pluginDriver.beforeBuild();
2927
+ const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, routeService, enableSSG);
2928
+ await rsbuild.build();
2929
+ } finally{
2930
+ await checkLanguageParity(config);
2931
+ }
2932
+ await pluginDriver.afterBuild();
2933
+ if (!enableSSG) hintSSGFalse();
2934
+ }
1597
2935
  async function dev(options) {
1598
- const { docDirectory, config, extraBuilderConfig } = options;
2936
+ const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
1599
2937
  const isProd = false;
1600
- const pluginDriver = new PluginDriver(config, isProd);
1601
- await pluginDriver.init();
2938
+ const pluginDriver = await PluginDriver.create(config, configFilePath, isProd);
1602
2939
  const modifiedConfig = await pluginDriver.modifyConfig();
1603
2940
  try {
2941
+ const additionalPages = await pluginDriver.addPages();
2942
+ const routeService = await RouteService.create({
2943
+ config: modifiedConfig,
2944
+ scanDir: docDirectory,
2945
+ externalPages: additionalPages
2946
+ });
2947
+ await pluginDriver.routeGenerated(routeService.getRoutes());
2948
+ await pluginDriver.routeServiceGenerated(routeService);
1604
2949
  await pluginDriver.beforeBuild();
1605
- const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
1606
- rsbuild.onDevCompileDone(async ()=>{
2950
+ const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, routeService, false, extraBuilderConfig);
2951
+ rsbuild.onAfterDevCompile(async ()=>{
1607
2952
  await pluginDriver.afterBuild();
1608
2953
  });
1609
2954
  const { server } = await rsbuild.startDevServer({
@@ -1611,179 +2956,179 @@ async function dev(options) {
1611
2956
  });
1612
2957
  return server;
1613
2958
  } finally{
1614
- await writeSearchIndex(modifiedConfig);
1615
2959
  await checkLanguageParity(modifiedConfig);
1616
2960
  }
1617
2961
  }
1618
- async function bundle(docDirectory, config, pluginDriver, enableSSG) {
1619
- try {
1620
- const rsbuild = await initRsbuild(docDirectory, config, pluginDriver, enableSSG);
1621
- await rsbuild.build();
1622
- } finally{
1623
- await writeSearchIndex(config);
1624
- await checkLanguageParity(config);
2962
+ const ERROR_PREFIX = '[remarkFileCodeBlock]';
2963
+ function parseFileFromMeta(meta) {
2964
+ if (!meta) return '';
2965
+ const kvList = meta.split(' ').filter(Boolean);
2966
+ for (const item of kvList){
2967
+ const [k, v = ''] = item.split('=');
2968
+ if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
1625
2969
  }
2970
+ return '';
1626
2971
  }
1627
- function emptyDir(path) {
1628
- return __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].rm(path, {
1629
- force: true,
1630
- recursive: true
2972
+ const remarkFileCodeBlock = ({ filepath, addDependency })=>async (tree)=>{
2973
+ const promiseList = [];
2974
+ visit(tree, 'code', (node)=>{
2975
+ const { meta, value, lang } = node;
2976
+ const file = parseFileFromMeta(meta ?? '');
2977
+ if (!file) return;
2978
+ const originalMetaForErrorInfo = picocolors.cyan(`\`\`\`${lang} ${meta}`);
2979
+ if (file.startsWith('./') || file.startsWith('../')) {
2980
+ const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
2981
+ if ('' !== value.trim()) {
2982
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
2983
+
2984
+ \`\`\`tsx file="./filename"
2985
+ content
2986
+ \`\`\`
2987
+
2988
+ this usage is not allowed, please use below:
2989
+
2990
+ \`\`\`tsx file="./filename"
2991
+ \`\`\`
2992
+ `);
2993
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
2994
+ }
2995
+ const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
2996
+ addDependency?.(resolvedFilePath);
2997
+ node.value = fileContent;
2998
+ }).catch((e)=>{
2999
+ const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
3000
+ logger.error(message);
3001
+ e.message = `${message}\n${e.message}`;
3002
+ throw e;
3003
+ });
3004
+ promiseList.push(promise);
3005
+ return;
3006
+ }
3007
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
3008
+ Please use below:
3009
+
3010
+ \`\`\`tsx file="./filename"
3011
+ \`\`\`
3012
+ `);
3013
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
3014
+ });
3015
+ await Promise.all(promiseList);
3016
+ };
3017
+ function link_checkDeadLinks(checkDeadLinks, internalLinks, file, lint) {
3018
+ const errorInfos = [];
3019
+ const excludes = 'object' == typeof checkDeadLinks ? checkDeadLinks.excludes : void 0;
3020
+ const excludesUrl = Array.isArray(excludes) ? new Set(excludes) : void 0;
3021
+ const excludesFn = 'function' == typeof excludes ? excludes : void 0;
3022
+ let possibleBreakingChange = false;
3023
+ [
3024
+ ...internalLinks.entries()
3025
+ ].forEach(([nodeUrl, link])=>{
3026
+ if (excludesUrl?.has(nodeUrl)) return;
3027
+ if (excludesFn?.(nodeUrl)) return;
3028
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
3029
+ errorInfos.push([
3030
+ nodeUrl,
3031
+ link
3032
+ ]);
1631
3033
  });
3034
+ if (errorInfos.length > 0) {
3035
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
3036
+ const message = `Dead links found${lint ? '' : ` in ${picocolors.cyan(file.path)}`}:
3037
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`;
3038
+ if (lint) file.message(message);
3039
+ else {
3040
+ logger.error(message);
3041
+ if ((0, shared_.isProduction)()) throw new Error('Dead link found');
3042
+ }
3043
+ }
1632
3044
  }
1633
- async function build(options) {
1634
- const { docDirectory, config } = options;
1635
- const pluginDriver = new PluginDriver(config, true);
1636
- await pluginDriver.init();
1637
- const modifiedConfig = await pluginDriver.modifyConfig();
1638
- await pluginDriver.beforeBuild();
1639
- const ssgConfig = modifiedConfig.ssg ?? true;
1640
- await emptyDir(constants_TEMP_DIR);
1641
- await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
1642
- if (!ssgConfig) hintSSGFalse();
1643
- await pluginDriver.afterBuild();
3045
+ function looseMarkdownLink(url, routeService, filePath) {
3046
+ if (!routeService.isInDocsDir(filePath)) return url;
3047
+ const [versionPart, langPart, pureRoute] = routeService.splitRoutePathParts(url);
3048
+ const relativePath = routeService.absolutePathToRelativePath(filePath);
3049
+ const [versionPartCurrFile, langPartCurrFile] = routeService.getRoutePathParts(relativePath);
3050
+ if ('' === versionPart) {
3051
+ if ('' === langPart) return (0, shared_.addLeadingSlash)(`${[
3052
+ versionPartCurrFile,
3053
+ langPartCurrFile
3054
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
3055
+ return (0, shared_.addLeadingSlash)(`${[
3056
+ versionPartCurrFile,
3057
+ langPart
3058
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
3059
+ }
3060
+ return url;
3061
+ }
3062
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, autoPrefix, deadLinks, __base) {
3063
+ if (!nodeUrl) return '';
3064
+ if (nodeUrl.startsWith('#')) return nodeUrl;
3065
+ if ((0, shared_.isExternalUrl)(nodeUrl)) return nodeUrl;
3066
+ if (!routeService) return nodeUrl;
3067
+ let { url, hash, search } = (0, shared_.parseUrl)(nodeUrl);
3068
+ if (url.startsWith('/')) {
3069
+ if (autoPrefix) url = looseMarkdownLink(url, routeService, filePath);
3070
+ const { routePath } = routeService.normalizeRoutePath(url);
3071
+ url = routePath;
3072
+ } else {
3073
+ const anotherFileAbsolutePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filePath), url);
3074
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
3075
+ }
3076
+ if ('boolean' == typeof cleanUrls) {
3077
+ url = (0, shared_.normalizeHref)(url, cleanUrls);
3078
+ if (!routeService.isExistRoute(url)) {
3079
+ deadLinks.set(nodeUrl, url);
3080
+ return nodeUrl;
3081
+ }
3082
+ } else {
3083
+ url = (0, shared_.normalizeHref)(url, false);
3084
+ if (!routeService.isExistRoute(url)) {
3085
+ deadLinks.set(nodeUrl, url);
3086
+ return nodeUrl;
3087
+ }
3088
+ url = url.replace(/\.html$/, cleanUrls);
3089
+ }
3090
+ if (search) url += `?${search}`;
3091
+ if (hash) url += `#${hash}`;
3092
+ if (__base) url = (0, shared_.withBase)(url, __base);
3093
+ return url;
1644
3094
  }
3095
+ const remarkLink = ({ cleanUrls, routeService, remarkLinkOptions, lint, __base })=>(tree, file)=>{
3096
+ const { checkDeadLinks: shouldCheckDeadLinks = true, autoPrefix = true } = remarkLinkOptions ?? {};
3097
+ const deadLinks = new Map();
3098
+ visit(tree, 'link', (node)=>{
3099
+ const { url: nodeUrl } = node;
3100
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, deadLinks, __base);
3101
+ node.url = link;
3102
+ });
3103
+ visit(tree, 'definition', (node)=>{
3104
+ const { url: nodeUrl } = node;
3105
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, deadLinks, __base);
3106
+ node.url = link;
3107
+ });
3108
+ if (shouldCheckDeadLinks && routeService) link_checkDeadLinks(shouldCheckDeadLinks, deadLinks, file, lint);
3109
+ };
1645
3110
  async function serve(options) {
1646
- const { config, port: userPort, host: userHost } = options;
3111
+ const { config, port: userPort, host: userHost, configFilePath } = options;
1647
3112
  const envPort = process.env.PORT;
1648
3113
  const envHost = process.env.HOST;
1649
- const { builderConfig } = config;
3114
+ const { builderConfig = {} } = config;
1650
3115
  const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
1651
3116
  const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
1652
- config.builderConfig = (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.mergeRsbuildConfig)(builderConfig, {
3117
+ config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
1653
3118
  server: {
1654
3119
  port,
1655
3120
  host
1656
3121
  }
1657
3122
  });
1658
- const pluginDriver = new PluginDriver(config, true);
1659
- await pluginDriver.init();
3123
+ const pluginDriver = await PluginDriver.create(config, configFilePath, true);
1660
3124
  const modifiedConfig = await pluginDriver.modifyConfig();
1661
- const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
3125
+ const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, await RouteService.createSimple(), false);
1662
3126
  return rsbuild.preview();
1663
3127
  }
1664
- const getASTNodeImport = (name, from)=>({
1665
- type: 'mdxjsEsm',
1666
- value: `import ${name} from ${JSON.stringify(from)}`,
1667
- data: {
1668
- estree: {
1669
- type: 'Program',
1670
- sourceType: 'module',
1671
- body: [
1672
- {
1673
- type: 'ImportDeclaration',
1674
- specifiers: [
1675
- {
1676
- type: 'ImportDefaultSpecifier',
1677
- local: {
1678
- type: 'Identifier',
1679
- name
1680
- }
1681
- }
1682
- ],
1683
- source: {
1684
- type: 'Literal',
1685
- value: from,
1686
- raw: `${JSON.stringify(from)}`
1687
- }
1688
- }
1689
- ]
1690
- }
1691
- }
1692
- });
1693
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
1694
- if (!nodeUrl) return '';
1695
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
1696
- let { url, hash } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.parseUrl)(nodeUrl);
1697
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
1698
- const extname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(url);
1699
- if ((routeService?.extensions ?? __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
1700
- if (url.startsWith('.')) url = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(relativePath)), url);
1701
- else if (routeService) {
1702
- const [pathVersion, pathLang] = routeService.getRoutePathParts((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(relativePath));
1703
- const [urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
1704
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(urlPath);
1705
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
1706
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
1707
- }
1708
- if ('boolean' == typeof cleanUrls) url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
1709
- else {
1710
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, false);
1711
- url = url.replace(/\.html$/, cleanUrls);
1712
- }
1713
- if (hash) url += `#${hash}`;
1714
- return url;
1715
- }
1716
- const normalizeImageUrl = (imageUrl)=>{
1717
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
1718
- return imageUrl;
1719
- };
1720
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
1721
- const images = [];
1722
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
1723
- const { url: nodeUrl } = node;
1724
- const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, file.path);
1725
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
1726
- });
1727
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'definition', (node)=>{
1728
- const { url: nodeUrl } = node;
1729
- const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, file.path);
1730
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
1731
- });
1732
- const getMdxSrcAttribute = (tempVar)=>({
1733
- type: 'mdxJsxAttribute',
1734
- name: 'src',
1735
- value: {
1736
- type: 'mdxJsxAttributeValueExpression',
1737
- value: tempVar,
1738
- data: {
1739
- estree: {
1740
- type: 'Program',
1741
- sourceType: 'module',
1742
- body: [
1743
- {
1744
- type: 'ExpressionStatement',
1745
- expression: {
1746
- type: 'Identifier',
1747
- name: tempVar
1748
- }
1749
- }
1750
- ]
1751
- }
1752
- }
1753
- }
1754
- });
1755
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'image', (node)=>{
1756
- const { alt, url } = node;
1757
- if (!url) return;
1758
- const imagePath = normalizeImageUrl(url);
1759
- if (!imagePath) return;
1760
- const tempVariableName = `image${images.length}`;
1761
- Object.assign(node, {
1762
- type: 'mdxJsxFlowElement',
1763
- name: 'img',
1764
- children: [],
1765
- attributes: [
1766
- alt && {
1767
- type: 'mdxJsxAttribute',
1768
- name: 'alt',
1769
- value: alt
1770
- },
1771
- getMdxSrcAttribute(tempVariableName)
1772
- ].filter(Boolean)
1773
- });
1774
- images.push(getASTNodeImport(tempVariableName, imagePath));
1775
- });
1776
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>{
1777
- if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
1778
- const srcAttr = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.getNodeAttribute)(node, 'src', true);
1779
- if ('string' != typeof srcAttr?.value) return;
1780
- const imagePath = normalizeImageUrl(srcAttr.value);
1781
- if (!imagePath) return;
1782
- const tempVariableName = `image${images.length}`;
1783
- Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
1784
- images.push(getASTNodeImport(tempVariableName, imagePath));
1785
- });
1786
- tree.children.unshift(...images);
1787
- };
1788
- var __webpack_exports__mergeDocConfig = __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.mergeDocConfig;
1789
- export { build, dev, remarkPluginNormalizeLink, serve, __webpack_exports__mergeDocConfig as mergeDocConfig };
3128
+ var __webpack_exports__RSPRESS_TEMP_DIR = shared_.RSPRESS_TEMP_DIR;
3129
+ var __webpack_exports__getSidebarDataGroup = shared_.getSidebarDataGroup;
3130
+ var __webpack_exports__normalizeHref = shared_.normalizeHref;
3131
+ var __webpack_exports__normalizePosixPath = shared_.normalizePosixPath;
3132
+ var __webpack_exports__removeTrailingSlash = shared_.removeTrailingSlash;
3133
+ var __webpack_exports__withBase = shared_.withBase;
3134
+ export { PluginDriver, RouteService, build, defineConfig, dev, getIconUrlPath, getNodeAttribute, logger, matchPath, mergeDocConfig, remarkFileCodeBlock, remarkLink, serve, __webpack_exports__RSPRESS_TEMP_DIR as RSPRESS_TEMP_DIR, __webpack_exports__getSidebarDataGroup as getSidebarDataGroup, __webpack_exports__normalizeHref as normalizeHref, __webpack_exports__normalizePosixPath as normalizePosixPath, __webpack_exports__removeTrailingSlash as removeTrailingSlash, __webpack_exports__withBase as withBase };