boltdocs 1.10.2 → 2.0.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 (250) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +21 -0
  3. package/dist/cache-7G6D532T.mjs +1 -0
  4. package/dist/chunk-A4HQPEPU.mjs +1 -0
  5. package/dist/chunk-BA5NH5HU.mjs +1 -0
  6. package/dist/chunk-BQCD3DWG.mjs +1 -0
  7. package/dist/chunk-H63UMKYF.mjs +1 -0
  8. package/dist/chunk-IWHRQHS7.mjs +1 -0
  9. package/dist/chunk-JZXLCA2E.mjs +1 -0
  10. package/dist/chunk-MFU7Q6WF.mjs +1 -0
  11. package/dist/chunk-QYPNX5UN.mjs +1 -0
  12. package/dist/chunk-XEAPSFMB.mjs +1 -0
  13. package/dist/client/components/mdx/index.d.mts +209 -0
  14. package/dist/client/components/mdx/index.d.ts +209 -0
  15. package/dist/client/components/mdx/index.js +1 -0
  16. package/dist/client/components/mdx/index.mjs +1 -0
  17. package/dist/client/hooks/index.d.mts +133 -0
  18. package/dist/client/hooks/index.d.ts +133 -0
  19. package/dist/client/hooks/index.js +1 -0
  20. package/dist/client/hooks/index.mjs +1 -0
  21. package/dist/client/index.d.mts +138 -298
  22. package/dist/client/index.d.ts +138 -298
  23. package/dist/client/index.js +1 -3630
  24. package/dist/client/index.mjs +1 -697
  25. package/dist/client/ssr.d.mts +7 -3
  26. package/dist/client/ssr.d.ts +7 -3
  27. package/dist/client/ssr.js +1 -2928
  28. package/dist/client/ssr.mjs +1 -33
  29. package/dist/{config-BsFQ-ErD.d.ts → config-CX4l-ZNp.d.mts} +42 -35
  30. package/dist/{config-BsFQ-ErD.d.mts → config-CX4l-ZNp.d.ts} +42 -35
  31. package/dist/node/index.d.mts +2 -4
  32. package/dist/node/index.d.ts +2 -4
  33. package/dist/node/index.js +31 -1161
  34. package/dist/node/index.mjs +31 -736
  35. package/dist/search-dialog-EB3N4TYM.mjs +1 -0
  36. package/dist/types-BuZWFT7r.d.ts +159 -0
  37. package/dist/types-CvT-SGbK.d.mts +159 -0
  38. package/dist/use-routes-5bAtAAYX.d.mts +30 -0
  39. package/dist/use-routes-BefRXY3v.d.ts +30 -0
  40. package/package.json +34 -12
  41. package/src/client/app/config-context.tsx +18 -0
  42. package/src/client/app/docs-layout.tsx +14 -0
  43. package/src/client/app/index.tsx +137 -262
  44. package/src/client/app/mdx-component.tsx +52 -0
  45. package/src/client/app/mdx-components-context.tsx +23 -0
  46. package/src/client/app/mdx-page.tsx +20 -0
  47. package/src/client/app/preload.tsx +38 -30
  48. package/src/client/app/router.tsx +30 -0
  49. package/src/client/app/scroll-handler.tsx +40 -0
  50. package/src/client/app/theme-context.tsx +75 -0
  51. package/src/client/components/default-layout.tsx +80 -0
  52. package/src/client/components/docs-layout.tsx +105 -0
  53. package/src/client/components/icons-dev.tsx +74 -0
  54. package/src/client/components/mdx/admonition.tsx +107 -0
  55. package/src/client/components/mdx/badge.tsx +41 -0
  56. package/src/client/components/mdx/button.tsx +35 -0
  57. package/src/client/components/mdx/card.tsx +124 -0
  58. package/src/client/components/mdx/code-block.tsx +119 -0
  59. package/src/client/components/mdx/component-preview.tsx +47 -0
  60. package/src/client/components/mdx/component-props.tsx +83 -0
  61. package/src/client/components/mdx/field.tsx +66 -0
  62. package/src/client/components/mdx/file-tree.tsx +287 -0
  63. package/src/client/components/mdx/hooks/use-code-block.ts +56 -0
  64. package/src/client/components/mdx/hooks/use-component-preview.ts +16 -0
  65. package/src/client/components/mdx/hooks/useTable.ts +74 -0
  66. package/src/client/components/mdx/hooks/useTabs.ts +68 -0
  67. package/src/client/components/mdx/image.tsx +23 -0
  68. package/src/client/components/mdx/index.ts +53 -0
  69. package/src/client/components/mdx/link.tsx +38 -0
  70. package/src/client/components/mdx/list.tsx +192 -0
  71. package/src/client/components/mdx/table.tsx +156 -0
  72. package/src/client/components/mdx/tabs.tsx +135 -0
  73. package/src/client/components/mdx/video.tsx +68 -0
  74. package/src/client/components/primitives/breadcrumbs.tsx +79 -0
  75. package/src/client/components/primitives/button-group.tsx +54 -0
  76. package/src/client/components/primitives/button.tsx +145 -0
  77. package/src/client/components/primitives/helpers/observer.ts +120 -0
  78. package/src/client/components/primitives/index.ts +17 -0
  79. package/src/client/components/primitives/link.tsx +122 -0
  80. package/src/client/components/primitives/menu.tsx +159 -0
  81. package/src/client/components/primitives/navbar.tsx +359 -0
  82. package/src/client/components/primitives/navigation-menu.tsx +116 -0
  83. package/src/client/components/primitives/on-this-page.tsx +461 -0
  84. package/src/client/components/primitives/page-nav.tsx +87 -0
  85. package/src/client/components/primitives/popover.tsx +47 -0
  86. package/src/client/components/primitives/search-dialog.tsx +183 -0
  87. package/src/client/components/primitives/sidebar.tsx +154 -0
  88. package/src/client/components/primitives/tabs.tsx +90 -0
  89. package/src/client/components/primitives/tooltip.tsx +83 -0
  90. package/src/client/components/primitives/types.ts +11 -0
  91. package/src/client/components/ui-base/breadcrumbs.tsx +42 -0
  92. package/src/client/components/ui-base/copy-markdown.tsx +112 -0
  93. package/src/client/components/ui-base/error-boundary.tsx +52 -0
  94. package/src/client/components/ui-base/github-stars.tsx +27 -0
  95. package/src/client/components/ui-base/head.tsx +69 -0
  96. package/src/client/components/ui-base/loading.tsx +87 -0
  97. package/src/client/components/ui-base/navbar.tsx +138 -0
  98. package/src/client/components/ui-base/not-found.tsx +24 -0
  99. package/src/client/components/ui-base/on-this-page.tsx +152 -0
  100. package/src/client/components/ui-base/page-nav.tsx +39 -0
  101. package/src/client/components/ui-base/powered-by.tsx +19 -0
  102. package/src/client/components/ui-base/progress-bar.tsx +67 -0
  103. package/src/client/components/ui-base/search-dialog.tsx +82 -0
  104. package/src/client/components/ui-base/sidebar.tsx +104 -0
  105. package/src/client/components/ui-base/tabs.tsx +65 -0
  106. package/src/client/components/ui-base/theme-toggle.tsx +32 -0
  107. package/src/client/hooks/index.ts +12 -0
  108. package/src/client/hooks/use-breadcrumbs.ts +22 -0
  109. package/src/client/hooks/use-i18n.ts +84 -0
  110. package/src/client/hooks/use-localized-to.ts +95 -0
  111. package/src/client/hooks/use-location.ts +5 -0
  112. package/src/client/hooks/use-navbar.ts +60 -0
  113. package/src/client/hooks/use-onthispage.ts +23 -0
  114. package/src/client/hooks/use-page-nav.ts +22 -0
  115. package/src/client/hooks/use-routes.ts +72 -0
  116. package/src/client/hooks/use-search.ts +71 -0
  117. package/src/client/hooks/use-sidebar.ts +49 -0
  118. package/src/client/hooks/use-tabs.ts +43 -0
  119. package/src/client/hooks/use-version.ts +78 -0
  120. package/src/client/index.ts +55 -17
  121. package/src/client/integrations/codesandbox.ts +179 -0
  122. package/src/client/ssr.tsx +27 -16
  123. package/src/client/theme/neutral.css +360 -0
  124. package/src/client/types.ts +131 -27
  125. package/src/client/utils/cn.ts +6 -0
  126. package/src/client/utils/copy-clipboard.ts +22 -0
  127. package/src/client/utils/get-base-file-path.ts +21 -0
  128. package/src/client/utils/github.ts +121 -0
  129. package/src/client/utils/use-on-change.ts +15 -0
  130. package/src/client/virtual.d.ts +24 -0
  131. package/src/node/cache.ts +156 -156
  132. package/src/node/config.ts +159 -103
  133. package/src/node/index.ts +13 -13
  134. package/src/node/mdx.ts +213 -61
  135. package/src/node/plugin/entry.ts +29 -18
  136. package/src/node/plugin/html.ts +11 -11
  137. package/src/node/plugin/index.ts +161 -84
  138. package/src/node/plugin/types.ts +2 -4
  139. package/src/node/routes/cache.ts +6 -6
  140. package/src/node/routes/index.ts +206 -113
  141. package/src/node/routes/parser.ts +102 -82
  142. package/src/node/routes/sorter.ts +15 -15
  143. package/src/node/routes/types.ts +24 -24
  144. package/src/node/ssg/index.ts +73 -47
  145. package/src/node/ssg/meta.ts +4 -4
  146. package/src/node/ssg/options.ts +5 -5
  147. package/src/node/ssg/sitemap.ts +14 -14
  148. package/src/node/utils.ts +54 -31
  149. package/tsconfig.json +25 -20
  150. package/tsup.config.ts +23 -14
  151. package/dist/PackageManagerTabs-NVT7G625.mjs +0 -99
  152. package/dist/SearchDialog-AGVF6JBO.mjs +0 -194
  153. package/dist/SearchDialog-YPDOM7Q6.css +0 -2847
  154. package/dist/Video-KNTY5BNO.mjs +0 -6
  155. package/dist/cache-KNL5B4EE.mjs +0 -12
  156. package/dist/chunk-7SFUJWTB.mjs +0 -211
  157. package/dist/chunk-FFBNU6IJ.mjs +0 -386
  158. package/dist/chunk-FMTOYQLO.mjs +0 -37
  159. package/dist/chunk-TKLQWU7H.mjs +0 -1920
  160. package/dist/chunk-Z7JHYNAS.mjs +0 -57
  161. package/dist/client/index.css +0 -2847
  162. package/dist/client/ssr.css +0 -2847
  163. package/dist/types-Dj-bfnC3.d.mts +0 -74
  164. package/dist/types-Dj-bfnC3.d.ts +0 -74
  165. package/src/client/theme/components/CodeBlock/CodeBlock.tsx +0 -61
  166. package/src/client/theme/components/CodeBlock/index.ts +0 -1
  167. package/src/client/theme/components/PackageManagerTabs/PackageManagerTabs.tsx +0 -131
  168. package/src/client/theme/components/PackageManagerTabs/index.ts +0 -1
  169. package/src/client/theme/components/PackageManagerTabs/pkg-tabs.css +0 -64
  170. package/src/client/theme/components/Playground/Playground.tsx +0 -180
  171. package/src/client/theme/components/Playground/index.ts +0 -1
  172. package/src/client/theme/components/Playground/playground.css +0 -238
  173. package/src/client/theme/components/Video/Video.tsx +0 -84
  174. package/src/client/theme/components/Video/index.ts +0 -1
  175. package/src/client/theme/components/Video/video.css +0 -41
  176. package/src/client/theme/components/mdx/Admonition.tsx +0 -80
  177. package/src/client/theme/components/mdx/Badge.tsx +0 -31
  178. package/src/client/theme/components/mdx/Button.tsx +0 -50
  179. package/src/client/theme/components/mdx/Card.tsx +0 -80
  180. package/src/client/theme/components/mdx/Field.tsx +0 -60
  181. package/src/client/theme/components/mdx/FileTree.tsx +0 -229
  182. package/src/client/theme/components/mdx/List.tsx +0 -57
  183. package/src/client/theme/components/mdx/Table.tsx +0 -151
  184. package/src/client/theme/components/mdx/Tabs.tsx +0 -123
  185. package/src/client/theme/components/mdx/index.ts +0 -27
  186. package/src/client/theme/components/mdx/mdx-components.css +0 -764
  187. package/src/client/theme/icons/bun.tsx +0 -62
  188. package/src/client/theme/icons/deno.tsx +0 -20
  189. package/src/client/theme/icons/discord.tsx +0 -12
  190. package/src/client/theme/icons/github.tsx +0 -15
  191. package/src/client/theme/icons/npm.tsx +0 -13
  192. package/src/client/theme/icons/pnpm.tsx +0 -72
  193. package/src/client/theme/icons/twitter.tsx +0 -12
  194. package/src/client/theme/styles/markdown.css +0 -394
  195. package/src/client/theme/styles/variables.css +0 -175
  196. package/src/client/theme/styles.css +0 -39
  197. package/src/client/theme/ui/Breadcrumbs/Breadcrumbs.tsx +0 -68
  198. package/src/client/theme/ui/Breadcrumbs/index.ts +0 -1
  199. package/src/client/theme/ui/CopyMarkdown/CopyMarkdown.tsx +0 -82
  200. package/src/client/theme/ui/CopyMarkdown/copy-markdown.css +0 -112
  201. package/src/client/theme/ui/CopyMarkdown/index.ts +0 -1
  202. package/src/client/theme/ui/ErrorBoundary/ErrorBoundary.tsx +0 -50
  203. package/src/client/theme/ui/ErrorBoundary/error-boundary.css +0 -55
  204. package/src/client/theme/ui/ErrorBoundary/index.ts +0 -1
  205. package/src/client/theme/ui/Footer/footer.css +0 -32
  206. package/src/client/theme/ui/Head/Head.tsx +0 -69
  207. package/src/client/theme/ui/Head/index.ts +0 -1
  208. package/src/client/theme/ui/LanguageSwitcher/LanguageSwitcher.tsx +0 -125
  209. package/src/client/theme/ui/LanguageSwitcher/index.ts +0 -1
  210. package/src/client/theme/ui/LanguageSwitcher/language-switcher.css +0 -98
  211. package/src/client/theme/ui/Layout/Layout.tsx +0 -203
  212. package/src/client/theme/ui/Layout/base.css +0 -106
  213. package/src/client/theme/ui/Layout/index.ts +0 -2
  214. package/src/client/theme/ui/Layout/pagination.css +0 -72
  215. package/src/client/theme/ui/Layout/responsive.css +0 -47
  216. package/src/client/theme/ui/Link/Link.tsx +0 -392
  217. package/src/client/theme/ui/Link/LinkPreview.tsx +0 -59
  218. package/src/client/theme/ui/Link/index.ts +0 -2
  219. package/src/client/theme/ui/Link/link-preview.css +0 -48
  220. package/src/client/theme/ui/Loading/Loading.tsx +0 -10
  221. package/src/client/theme/ui/Loading/index.ts +0 -1
  222. package/src/client/theme/ui/Loading/loading.css +0 -30
  223. package/src/client/theme/ui/Navbar/GithubStars.tsx +0 -27
  224. package/src/client/theme/ui/Navbar/Navbar.tsx +0 -193
  225. package/src/client/theme/ui/Navbar/Tabs.tsx +0 -99
  226. package/src/client/theme/ui/Navbar/index.ts +0 -2
  227. package/src/client/theme/ui/Navbar/navbar.css +0 -347
  228. package/src/client/theme/ui/NotFound/NotFound.tsx +0 -19
  229. package/src/client/theme/ui/NotFound/index.ts +0 -1
  230. package/src/client/theme/ui/NotFound/not-found.css +0 -64
  231. package/src/client/theme/ui/OnThisPage/OnThisPage.tsx +0 -244
  232. package/src/client/theme/ui/OnThisPage/index.ts +0 -1
  233. package/src/client/theme/ui/OnThisPage/toc.css +0 -152
  234. package/src/client/theme/ui/PoweredBy/PoweredBy.tsx +0 -18
  235. package/src/client/theme/ui/PoweredBy/index.ts +0 -1
  236. package/src/client/theme/ui/PoweredBy/powered-by.css +0 -76
  237. package/src/client/theme/ui/ProgressBar/ProgressBar.css +0 -17
  238. package/src/client/theme/ui/ProgressBar/ProgressBar.tsx +0 -51
  239. package/src/client/theme/ui/ProgressBar/index.ts +0 -1
  240. package/src/client/theme/ui/SearchDialog/SearchDialog.tsx +0 -209
  241. package/src/client/theme/ui/SearchDialog/index.ts +0 -1
  242. package/src/client/theme/ui/SearchDialog/search.css +0 -152
  243. package/src/client/theme/ui/Sidebar/Sidebar.tsx +0 -244
  244. package/src/client/theme/ui/Sidebar/index.ts +0 -1
  245. package/src/client/theme/ui/Sidebar/sidebar.css +0 -230
  246. package/src/client/theme/ui/ThemeToggle/ThemeToggle.tsx +0 -69
  247. package/src/client/theme/ui/ThemeToggle/index.ts +0 -1
  248. package/src/client/theme/ui/VersionSwitcher/VersionSwitcher.tsx +0 -136
  249. package/src/client/theme/ui/VersionSwitcher/index.ts +0 -1
  250. package/src/client/utils.ts +0 -49
@@ -1,948 +1,37 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // src/node/utils.ts
34
- function normalizePath(p) {
35
- return p.replace(/\\/g, "/");
36
- }
37
- function stripNumberPrefix(name) {
38
- return name.replace(/^\d+\./, "");
39
- }
40
- function extractNumberPrefix(name) {
41
- const match = name.match(/^(\d+)\./);
42
- return match ? parseInt(match[1], 10) : void 0;
43
- }
44
- function isDocFile(filePath) {
45
- return /\.mdx?$/.test(filePath);
46
- }
47
- function getFileMtime(filePath) {
48
- try {
49
- return import_fs.default.statSync(filePath).mtimeMs;
50
- } catch {
51
- return 0;
52
- }
53
- }
54
- function parseFrontmatter(filePath) {
55
- const raw = import_fs.default.readFileSync(filePath, "utf-8");
56
- const { data, content } = (0, import_gray_matter.default)(raw);
57
- return { data, content };
58
- }
59
- function escapeHtml(str) {
60
- return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
61
- }
62
- function escapeXml(str) {
63
- return escapeHtml(str);
64
- }
65
- function fileToRoutePath(relativePath) {
66
- let cleanedPath = relativePath.split("/").map(stripNumberPrefix).join("/");
67
- let routePath = cleanedPath.replace(/\/$/, "");
68
- routePath = routePath.replace(/\.mdx?$/, "");
69
- if (routePath === "index" || routePath.endsWith("/index")) {
70
- routePath = routePath.replace(/index$/, "");
71
- }
72
- if (!routePath.startsWith("/")) {
73
- routePath = "/" + routePath;
74
- }
75
- if (routePath.length > 1 && routePath.endsWith("/")) {
76
- routePath = routePath.slice(0, -1);
77
- }
78
- return routePath;
79
- }
80
- function capitalize(str) {
81
- return str.charAt(0).toUpperCase() + str.slice(1);
82
- }
83
- var import_fs, import_gray_matter;
84
- var init_utils = __esm({
85
- "src/node/utils.ts"() {
86
- "use strict";
87
- import_fs = __toESM(require("fs"));
88
- import_gray_matter = __toESM(require("gray-matter"));
89
- }
90
- });
91
-
92
- // src/node/cache.ts
93
- var cache_exports = {};
94
- __export(cache_exports, {
95
- AssetCache: () => AssetCache,
96
- FileCache: () => FileCache,
97
- TransformCache: () => TransformCache,
98
- flushCache: () => flushCache
99
- });
100
- async function flushCache() {
101
- await backgroundQueue.flush();
102
- }
103
- var import_fs2, import_path, import_crypto, import_zlib, import_util, writeFile, readFile, mkdir, rename, unlink, CACHE_DIR, ASSETS_DIR, SHARDS_DIR, DEFAULT_LRU_LIMIT, DEFAULT_COMPRESS, LRUCache, BackgroundQueue, backgroundQueue, FileCache, TransformCache, AssetCache;
104
- var init_cache = __esm({
105
- "src/node/cache.ts"() {
106
- "use strict";
107
- import_fs2 = __toESM(require("fs"));
108
- import_path = __toESM(require("path"));
109
- import_crypto = __toESM(require("crypto"));
110
- import_zlib = __toESM(require("zlib"));
111
- import_util = require("util");
112
- init_utils();
113
- writeFile = (0, import_util.promisify)(import_fs2.default.writeFile);
114
- readFile = (0, import_util.promisify)(import_fs2.default.readFile);
115
- mkdir = (0, import_util.promisify)(import_fs2.default.mkdir);
116
- rename = (0, import_util.promisify)(import_fs2.default.rename);
117
- unlink = (0, import_util.promisify)(import_fs2.default.unlink);
118
- CACHE_DIR = process.env.BOLTDOCS_CACHE_DIR || ".boltdocs";
119
- ASSETS_DIR = "assets";
120
- SHARDS_DIR = "shards";
121
- DEFAULT_LRU_LIMIT = parseInt(
122
- process.env.BOLTDOCS_CACHE_LRU_LIMIT || "2000",
123
- 10
124
- );
125
- DEFAULT_COMPRESS = process.env.BOLTDOCS_CACHE_COMPRESS !== "0";
126
- LRUCache = class {
127
- constructor(limit) {
128
- this.limit = limit;
129
- }
130
- cache = /* @__PURE__ */ new Map();
131
- get(key) {
132
- const val = this.cache.get(key);
133
- if (val !== void 0) {
134
- this.cache.delete(key);
135
- this.cache.set(key, val);
136
- }
137
- return val;
138
- }
139
- set(key, value) {
140
- if (this.cache.has(key)) {
141
- this.cache.delete(key);
142
- } else if (this.cache.size >= this.limit) {
143
- const firstKey = this.cache.keys().next().value;
144
- if (firstKey !== void 0) {
145
- this.cache.delete(firstKey);
146
- }
147
- }
148
- this.cache.set(key, value);
149
- }
150
- get size() {
151
- return this.cache.size;
152
- }
153
- clear() {
154
- this.cache.clear();
155
- }
156
- };
157
- BackgroundQueue = class {
158
- queue = Promise.resolve();
159
- pendingCount = 0;
160
- add(task) {
161
- this.pendingCount++;
162
- this.queue = this.queue.then(task).finally(() => {
163
- this.pendingCount--;
164
- });
165
- }
166
- async flush() {
167
- await this.queue;
168
- }
169
- get pending() {
170
- return this.pendingCount;
171
- }
172
- };
173
- backgroundQueue = new BackgroundQueue();
174
- FileCache = class {
175
- entries = /* @__PURE__ */ new Map();
176
- cachePath = null;
177
- compress;
178
- constructor(options = {}) {
179
- this.compress = options.compress !== void 0 ? options.compress : DEFAULT_COMPRESS;
180
- if (options.name) {
181
- const root = options.root || process.cwd();
182
- const ext = this.compress ? "json.gz" : "json";
183
- this.cachePath = import_path.default.resolve(root, CACHE_DIR, `${options.name}.${ext}`);
184
- }
185
- }
186
- /**
187
- * Loads the cache. Synchronous for startup simplicity but uses fast I/O.
188
- */
189
- load() {
190
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
191
- if (!this.cachePath || !import_fs2.default.existsSync(this.cachePath)) return;
192
- try {
193
- let raw = import_fs2.default.readFileSync(this.cachePath);
194
- if (this.cachePath.endsWith(".gz")) {
195
- raw = import_zlib.default.gunzipSync(raw);
196
- }
197
- const data = JSON.parse(raw.toString("utf-8"));
198
- this.entries = new Map(Object.entries(data));
199
- } catch (e) {
200
- }
201
- }
202
- /**
203
- * Saves the cache in the background.
204
- */
205
- save() {
206
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
207
- if (!this.cachePath) return;
208
- const data = Object.fromEntries(this.entries);
209
- const content = JSON.stringify(data);
210
- const target = this.cachePath;
211
- const useCompress = this.compress;
212
- backgroundQueue.add(async () => {
213
- try {
214
- await mkdir(import_path.default.dirname(target), { recursive: true });
215
- let buffer = Buffer.from(content);
216
- if (useCompress) {
217
- buffer = import_zlib.default.gzipSync(buffer);
218
- }
219
- const tempPath = `${target}.${import_crypto.default.randomBytes(4).toString("hex")}.tmp`;
220
- await writeFile(tempPath, buffer);
221
- await rename(tempPath, target);
222
- } catch (e) {
223
- }
224
- });
225
- }
226
- get(filePath) {
227
- const entry = this.entries.get(filePath);
228
- if (!entry) return null;
229
- if (getFileMtime(filePath) !== entry.mtime) return null;
230
- return entry.data;
231
- }
232
- set(filePath, data) {
233
- this.entries.set(filePath, {
234
- data,
235
- mtime: getFileMtime(filePath)
236
- });
237
- }
238
- isValid(filePath) {
239
- const entry = this.entries.get(filePath);
240
- if (!entry) return false;
241
- return getFileMtime(filePath) === entry.mtime;
242
- }
243
- invalidate(filePath) {
244
- this.entries.delete(filePath);
245
- }
246
- invalidateAll() {
247
- this.entries.clear();
248
- }
249
- pruneStale(currentFiles) {
250
- for (const key of this.entries.keys()) {
251
- if (!currentFiles.has(key)) {
252
- this.entries.delete(key);
253
- }
254
- }
255
- }
256
- get size() {
257
- return this.entries.size;
258
- }
259
- async flush() {
260
- await backgroundQueue.flush();
261
- }
262
- };
263
- TransformCache = class {
264
- index = /* @__PURE__ */ new Map();
265
- // key -> hash
266
- memoryCache = new LRUCache(DEFAULT_LRU_LIMIT);
267
- baseDir;
268
- shardsDir;
269
- indexPath;
270
- constructor(name, root = process.cwd()) {
271
- this.baseDir = import_path.default.resolve(root, CACHE_DIR, `transform-${name}`);
272
- this.shardsDir = import_path.default.resolve(this.baseDir, SHARDS_DIR);
273
- this.indexPath = import_path.default.resolve(this.baseDir, "index.json");
274
- }
275
- /**
276
- * Loads the index into memory.
277
- */
278
- load() {
279
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
280
- if (!import_fs2.default.existsSync(this.indexPath)) return;
281
- try {
282
- const data = import_fs2.default.readFileSync(this.indexPath, "utf-8");
283
- this.index = new Map(Object.entries(JSON.parse(data)));
284
- } catch (e) {
285
- }
286
- }
287
- /**
288
- * Persists the index in background.
289
- */
290
- save() {
291
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
292
- const data = JSON.stringify(Object.fromEntries(this.index));
293
- const target = this.indexPath;
294
- backgroundQueue.add(async () => {
295
- await mkdir(import_path.default.dirname(target), { recursive: true });
296
- await writeFile(target, data);
297
- });
298
- }
299
- /**
300
- * Batch Read: Retrieves multiple transformation results concurrently.
301
- */
302
- async getMany(keys) {
303
- const results = /* @__PURE__ */ new Map();
304
- const toLoad = [];
305
- for (const key of keys) {
306
- const mem = this.memoryCache.get(key);
307
- if (mem) results.set(key, mem);
308
- else if (this.index.has(key)) toLoad.push(key);
309
- }
310
- if (toLoad.length > 0) {
311
- const shards = await Promise.all(
312
- toLoad.map(async (key) => {
313
- const hash = this.index.get(key);
314
- const shardPath = import_path.default.resolve(this.shardsDir, `${hash}.gz`);
315
- try {
316
- const compressed = await readFile(shardPath);
317
- const decompressed = import_zlib.default.gunzipSync(compressed).toString("utf-8");
318
- this.memoryCache.set(key, decompressed);
319
- return { key, val: decompressed };
320
- } catch (e) {
321
- return null;
322
- }
323
- })
324
- );
325
- for (const s of shards) {
326
- if (s) results.set(s.key, s.val);
327
- }
328
- }
329
- return results;
330
- }
331
- /**
332
- * Retrieves a cached transformation. Fast lookup via index, lazy loading from disk.
333
- */
334
- get(key) {
335
- const mem = this.memoryCache.get(key);
336
- if (mem) return mem;
337
- const hash = this.index.get(key);
338
- if (!hash) return null;
339
- const shardPath = import_path.default.resolve(this.shardsDir, `${hash}.gz`);
340
- if (!import_fs2.default.existsSync(shardPath)) return null;
341
- try {
342
- const compressed = import_fs2.default.readFileSync(shardPath);
343
- const decompressed = import_zlib.default.gunzipSync(compressed).toString("utf-8");
344
- this.memoryCache.set(key, decompressed);
345
- return decompressed;
346
- } catch (e) {
347
- return null;
348
- }
349
- }
350
- /**
351
- * Stores a transformation result.
352
- */
353
- set(key, result) {
354
- const hash = import_crypto.default.createHash("md5").update(result).digest("hex");
355
- this.index.set(key, hash);
356
- this.memoryCache.set(key, result);
357
- const shardPath = import_path.default.resolve(this.shardsDir, `${hash}.gz`);
358
- backgroundQueue.add(async () => {
359
- if (import_fs2.default.existsSync(shardPath)) return;
360
- await mkdir(this.shardsDir, { recursive: true });
361
- const compressed = import_zlib.default.gzipSync(Buffer.from(result));
362
- const tempPath = `${shardPath}.${import_crypto.default.randomBytes(4).toString("hex")}.tmp`;
363
- await writeFile(tempPath, compressed);
364
- await rename(tempPath, shardPath);
365
- });
366
- }
367
- get size() {
368
- return this.index.size;
369
- }
370
- async flush() {
371
- await backgroundQueue.flush();
372
- }
373
- };
374
- AssetCache = class {
375
- assetsDir;
376
- constructor(root = process.cwd()) {
377
- this.assetsDir = import_path.default.resolve(root, CACHE_DIR, ASSETS_DIR);
378
- }
379
- getFileHash(filePath) {
380
- return import_crypto.default.createHash("md5").update(import_fs2.default.readFileSync(filePath)).digest("hex");
381
- }
382
- get(sourcePath, cacheKey) {
383
- if (!import_fs2.default.existsSync(sourcePath)) return null;
384
- const sourceHash = this.getFileHash(sourcePath);
385
- const cachedPath = this.getCachedPath(
386
- sourcePath,
387
- `${cacheKey}-${sourceHash}`
388
- );
389
- return import_fs2.default.existsSync(cachedPath) ? cachedPath : null;
390
- }
391
- set(sourcePath, cacheKey, content) {
392
- const sourceHash = this.getFileHash(sourcePath);
393
- const cachedPath = this.getCachedPath(
394
- sourcePath,
395
- `${cacheKey}-${sourceHash}`
396
- );
397
- backgroundQueue.add(async () => {
398
- await mkdir(this.assetsDir, { recursive: true });
399
- const tempPath = `${cachedPath}.${import_crypto.default.randomBytes(4).toString("hex")}.tmp`;
400
- await writeFile(tempPath, content);
401
- await rename(tempPath, cachedPath);
402
- });
403
- }
404
- getCachedPath(sourcePath, cacheKey) {
405
- const ext = import_path.default.extname(sourcePath);
406
- const name = import_path.default.basename(sourcePath, ext);
407
- const safeKey = cacheKey.replace(/[^a-z0-9]/gi, "-").toLowerCase();
408
- return import_path.default.join(this.assetsDir, `${name}.${safeKey}${ext}`);
409
- }
410
- clear() {
411
- if (import_fs2.default.existsSync(this.assetsDir)) {
412
- import_fs2.default.rmSync(this.assetsDir, { recursive: true, force: true });
413
- }
414
- }
415
- async flush() {
416
- await backgroundQueue.flush();
417
- }
418
- };
419
- }
420
- });
421
-
422
- // src/node/index.ts
423
- var node_exports = {};
424
- __export(node_exports, {
425
- default: () => boltdocs,
426
- generateStaticPages: () => generateStaticPages
427
- });
428
- module.exports = __toCommonJS(node_exports);
429
-
430
- // src/node/plugin/index.ts
431
- var import_vite = require("vite");
432
-
433
- // src/node/routes/index.ts
434
- var import_fast_glob = __toESM(require("fast-glob"));
435
- init_utils();
436
-
437
- // src/node/routes/cache.ts
438
- init_cache();
439
- var docCache = new FileCache({ name: "routes" });
440
- function invalidateRouteCache() {
441
- docCache.invalidateAll();
442
- }
443
- function invalidateFile(filePath) {
444
- docCache.invalidate(filePath);
445
- }
446
-
447
- // src/node/routes/parser.ts
448
- var import_path2 = __toESM(require("path"));
449
- var import_github_slugger = __toESM(require("github-slugger"));
450
- init_utils();
451
- function parseDocFile(file, docsDir, basePath, config) {
452
- const decodedFile = decodeURIComponent(file);
453
- const absoluteFile = import_path2.default.resolve(decodedFile);
454
- const absoluteDocsDir = import_path2.default.resolve(docsDir);
455
- const relativePath = normalizePath(
456
- import_path2.default.relative(absoluteDocsDir, absoluteFile)
457
- );
458
- if (relativePath.startsWith("../") || relativePath === ".." || absoluteFile.includes("\0")) {
459
- throw new Error(
460
- `Security breach: File is outside of docs directory or contains null bytes: ${file}`
461
- );
462
- }
463
- const { data, content } = parseFrontmatter(file);
464
- let parts = relativePath.split("/");
465
- let locale;
466
- let version;
467
- if (config?.versions && parts.length > 0) {
468
- const potentialVersion = parts[0];
469
- if (config.versions.versions[potentialVersion]) {
470
- version = potentialVersion;
471
- parts = parts.slice(1);
472
- }
473
- }
474
- if (config?.i18n && parts.length > 0) {
475
- const potentialLocale = parts[0];
476
- if (config.i18n.locales[potentialLocale]) {
477
- locale = potentialLocale;
478
- parts = parts.slice(1);
479
- }
480
- }
481
- let inferredTab;
482
- if (parts.length > 0) {
483
- const tabMatch = parts[0].match(/^\((.+)\)$/);
484
- if (tabMatch) {
485
- inferredTab = tabMatch[1].toLowerCase();
486
- parts = parts.slice(1);
487
- }
488
- }
489
- const cleanRelativePath = parts.join("/");
490
- let cleanRoutePath;
491
- if (data.permalink) {
492
- cleanRoutePath = data.permalink.startsWith("/") ? data.permalink : `/${data.permalink}`;
493
- } else {
494
- cleanRoutePath = fileToRoutePath(cleanRelativePath || "index.md");
495
- }
496
- let finalPath = basePath;
497
- if (version) {
498
- finalPath += "/" + version;
499
- }
500
- if (locale) {
501
- finalPath += "/" + locale;
502
- }
503
- finalPath += cleanRoutePath === "/" ? "" : cleanRoutePath;
504
- if (!finalPath || finalPath === "") finalPath = "/";
505
- const rawFileName = parts[parts.length - 1];
506
- const cleanFileName = stripNumberPrefix(rawFileName);
507
- const inferredTitle = stripNumberPrefix(
508
- import_path2.default.basename(file, import_path2.default.extname(file))
509
- );
510
- const sidebarPosition = data.sidebarPosition ?? extractNumberPrefix(rawFileName);
511
- const rawDirName = parts.length >= 2 ? parts[0] : void 0;
512
- const cleanDirName = rawDirName ? stripNumberPrefix(rawDirName) : void 0;
513
- const isGroupIndex = parts.length >= 2 && /^index\.mdx?$/.test(cleanFileName);
514
- const headings = [];
515
- const slugger = new import_github_slugger.default();
516
- const headingsRegex = /^(#{2,4})\s+(.+)$/gm;
517
- let match;
518
- while ((match = headingsRegex.exec(content)) !== null) {
519
- const level = match[1].length;
520
- const text = match[2].replace(/\[([^\]]+)\]\([^\)]+\)/g, "$1").replace(/[_*`]/g, "").trim();
521
- const id = slugger.slug(text);
522
- headings.push({ level, text, id });
523
- }
524
- const sanitizedTitle = data.title ? data.title : inferredTitle;
525
- let sanitizedDescription = data.description ? data.description : "";
526
- if (!sanitizedDescription && content) {
527
- const summary = content.replace(/^#+.*$/gm, "").replace(/\[([^\]]+)\]\([^\)]+\)/g, "$1").replace(/[_*`]/g, "").replace(/\n+/g, " ").trim().slice(0, 160);
528
- sanitizedDescription = summary;
529
- }
530
- const sanitizedBadge = data.badge ? data.badge : void 0;
531
- const icon = data.icon ? String(data.icon) : void 0;
532
- const plainText = content.replace(/^#+.*$/gm, "").replace(/\[([^\]]+)\]\([^\)]+\)/g, "$1").replace(/<[^>]+>/g, "").replace(/\{[^\}]+\}/g, "").replace(/[_*`]/g, "").replace(/\n+/g, " ").trim();
533
- return {
534
- route: {
535
- path: finalPath,
536
- componentPath: file,
537
- filePath: relativePath,
538
- title: sanitizedTitle,
539
- description: sanitizedDescription,
540
- sidebarPosition,
541
- headings,
542
- locale,
543
- version,
544
- badge: sanitizedBadge,
545
- icon,
546
- tab: inferredTab,
547
- _content: plainText,
548
- _rawContent: content
549
- },
550
- relativeDir: cleanDirName,
551
- isGroupIndex,
552
- inferredTab,
553
- groupMeta: isGroupIndex ? {
554
- title: data.groupTitle || data.title || (cleanDirName ? capitalize(cleanDirName) : ""),
555
- position: data.groupPosition ?? data.sidebarPosition ?? (rawDirName ? extractNumberPrefix(rawDirName) : void 0),
556
- icon
557
- } : void 0,
558
- inferredGroupPosition: rawDirName ? extractNumberPrefix(rawDirName) : void 0
559
- };
560
- }
561
-
562
- // src/node/routes/sorter.ts
563
- function sortRoutes(routes) {
564
- return routes.sort((a, b) => {
565
- if (!a.group && !b.group) return compareByPosition(a, b);
566
- if (!a.group) return -1;
567
- if (!b.group) return 1;
568
- if (a.group !== b.group) {
569
- return compareByGroupPosition(a, b);
570
- }
571
- return compareByPosition(a, b);
572
- });
573
- }
574
- function compareByPosition(a, b) {
575
- if (a.sidebarPosition !== void 0 && b.sidebarPosition !== void 0)
576
- return a.sidebarPosition - b.sidebarPosition;
577
- if (a.sidebarPosition !== void 0) return -1;
578
- if (b.sidebarPosition !== void 0) return 1;
579
- return a.title.localeCompare(b.title);
580
- }
581
- function compareByGroupPosition(a, b) {
582
- if (a.groupPosition !== void 0 && b.groupPosition !== void 0)
583
- return a.groupPosition - b.groupPosition;
584
- if (a.groupPosition !== void 0) return -1;
585
- if (b.groupPosition !== void 0) return 1;
586
- return (a.groupTitle || a.group).localeCompare(b.groupTitle || b.group);
587
- }
588
-
589
- // src/node/routes/index.ts
590
- async function generateRoutes(docsDir, config, basePath = "/docs") {
591
- docCache.load();
592
- docCache.invalidateAll();
593
- const files = await (0, import_fast_glob.default)(["**/*.md", "**/*.mdx"], {
594
- cwd: docsDir,
595
- absolute: true
596
- });
597
- docCache.pruneStale(new Set(files));
598
- if (config?.i18n) {
599
- docCache.invalidateAll();
600
- }
601
- let cacheHits = 0;
602
- const parsed = await Promise.all(
603
- files.map(async (file) => {
604
- const cached = docCache.get(file);
605
- if (cached) {
606
- cacheHits++;
607
- return cached;
608
- }
609
- const result = parseDocFile(file, docsDir, basePath, config);
610
- docCache.set(file, result);
611
- return result;
612
- })
613
- );
614
- if (files.length > 0) {
615
- console.log(
616
- `[boltdocs] Routes generated: ${files.length} files (${cacheHits} from cache, ${files.length - cacheHits} parsed)`
617
- );
618
- }
619
- docCache.save();
620
- const groupMeta = /* @__PURE__ */ new Map();
621
- for (const p of parsed) {
622
- if (p.relativeDir) {
623
- if (!groupMeta.has(p.relativeDir)) {
624
- groupMeta.set(p.relativeDir, {
625
- title: capitalize(p.relativeDir),
626
- position: p.inferredGroupPosition,
627
- icon: p.route.icon
628
- });
629
- } else {
630
- const entry = groupMeta.get(p.relativeDir);
631
- if (entry.position === void 0 && p.inferredGroupPosition !== void 0) {
632
- entry.position = p.inferredGroupPosition;
633
- }
634
- if (!entry.icon && p.route.icon) {
635
- entry.icon = p.route.icon;
636
- }
637
- }
638
- }
639
- if (p.isGroupIndex && p.relativeDir && p.groupMeta) {
640
- const entry = groupMeta.get(p.relativeDir);
641
- entry.title = p.groupMeta.title;
642
- if (p.groupMeta.position !== void 0) {
643
- entry.position = p.groupMeta.position;
644
- }
645
- if (p.groupMeta.icon) {
646
- entry.icon = p.groupMeta.icon;
647
- }
648
- }
649
- }
650
- const routes = parsed.map((p) => {
651
- const dir = p.relativeDir;
652
- const meta = dir ? groupMeta.get(dir) : void 0;
653
- return {
654
- ...p.route,
655
- group: dir,
656
- groupTitle: meta?.title || (dir ? capitalize(dir) : void 0),
657
- groupPosition: meta?.position,
658
- groupIcon: meta?.icon
659
- };
660
- });
661
- if (config?.i18n) {
662
- const defaultLocale = config.i18n.defaultLocale;
663
- const allLocales = Object.keys(config.i18n.locales);
664
- const fallbackRoutes = [];
665
- const defaultRoutes = routes.filter(
666
- (r) => (r.locale || defaultLocale) === defaultLocale
667
- );
668
- for (const locale of allLocales) {
669
- if (locale === defaultLocale) continue;
670
- const localeRoutePaths = new Set(
671
- routes.filter((r) => r.locale === locale).map((r) => r.path)
672
- );
673
- for (const defRoute of defaultRoutes) {
674
- let prefix = basePath;
675
- if (defRoute.version) {
676
- prefix += "/" + defRoute.version;
677
- }
678
- let pathAfterVersion = defRoute.path.substring(prefix.length);
679
- if (pathAfterVersion.startsWith("/" + defaultLocale + "/")) {
680
- pathAfterVersion = pathAfterVersion.substring(
681
- defaultLocale.length + 1
682
- );
683
- } else if (pathAfterVersion === "/" + defaultLocale) {
684
- pathAfterVersion = "/";
685
- }
686
- const targetPath = prefix + "/" + locale + (pathAfterVersion === "/" || pathAfterVersion === "" ? "" : pathAfterVersion);
687
- if (!localeRoutePaths.has(targetPath)) {
688
- fallbackRoutes.push({
689
- ...defRoute,
690
- path: targetPath,
691
- locale
692
- });
693
- }
694
- }
695
- }
696
- return sortRoutes([...routes, ...fallbackRoutes]);
697
- }
698
- return sortRoutes(routes);
699
- }
700
-
701
- // src/node/plugin/index.ts
702
- var import_vite_plugin_image_optimizer = require("vite-plugin-image-optimizer");
703
-
704
- // src/node/config.ts
705
- var import_path3 = __toESM(require("path"));
706
- var import_url = require("url");
707
- var import_fs3 = __toESM(require("fs"));
708
- var CONFIG_FILES = [
709
- "boltdocs.config.js",
710
- "boltdocs.config.mjs",
711
- "boltdocs.config.ts"
712
- ];
713
- async function resolveConfig(docsDir, root = process.cwd()) {
714
- const projectRoot = root;
715
- const defaults = {
716
- docsDir: import_path3.default.resolve(docsDir),
717
- themeConfig: {
718
- title: "Boltdocs",
719
- description: "A Vite documentation framework",
720
- navbar: [
721
- { text: "Home", link: "/" },
722
- { text: "Documentation", link: "/docs" }
723
- ]
724
- }
725
- };
726
- for (const filename of CONFIG_FILES) {
727
- const configPath = import_path3.default.resolve(projectRoot, filename);
728
- if (import_fs3.default.existsSync(configPath)) {
729
- try {
730
- const isTest = process.env.NODE_ENV === "test" || global.__vitest_worker__;
731
- const fileUrl = (0, import_url.pathToFileURL)(configPath).href + (isTest ? "" : "?t=" + Date.now());
732
- const mod = await import(fileUrl);
733
- const userConfig = mod.default || mod;
734
- const userThemeConfig = userConfig.themeConfig || userConfig;
735
- return {
736
- docsDir: import_path3.default.resolve(docsDir),
737
- themeConfig: {
738
- ...defaults.themeConfig,
739
- ...userThemeConfig
740
- },
741
- i18n: userConfig.i18n,
742
- versions: userConfig.versions,
743
- siteUrl: userConfig.siteUrl,
744
- plugins: userConfig.plugins || []
745
- };
746
- } catch (e) {
747
- console.warn(`[boltdocs] Failed to load config from ${filename}:`, e);
748
- }
749
- }
750
- }
751
- return defaults;
752
- }
753
-
754
- // src/node/ssg/index.ts
755
- var import_fs4 = __toESM(require("fs"));
756
- var import_path4 = __toESM(require("path"));
757
- init_utils();
758
- var import_url2 = require("url");
759
- var import_module = require("module");
760
-
761
- // src/node/ssg/meta.ts
762
- init_utils();
763
- function replaceMetaTags(html, meta) {
764
- const title = escapeHtml(meta.title);
765
- const description = escapeHtml(meta.description);
766
- return html.replace(/<title>.*?<\/title>/, `<title>${title}</title>`).replace(
767
- /(<meta name="description" content=")[^"]*(")/,
768
- `$1${description}$2`
769
- ).replace(/(<meta property="og:title" content=")[^"]*(")/, `$1${title}$2`).replace(
770
- /(<meta property="og:description" content=")[^"]*(")/,
771
- `$1${description}$2`
772
- ).replace(/(<meta name="twitter:title" content=")[^"]*(")/, `$1${title}$2`).replace(
773
- /(<meta name="twitter:description" content=")[^"]*(")/,
774
- `$1${description}$2`
775
- );
776
- }
777
-
778
- // src/node/ssg/sitemap.ts
779
- init_utils();
780
- function generateSitemap(routePaths, config) {
781
- const baseUrl = config?.siteUrl?.replace(/\/$/, "") || "https://example.com";
782
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
783
- const rootEntries = [{ url: "/", priority: "1.0", changefreq: "daily" }];
784
- if (config?.i18n) {
785
- const defaultLocale = config.i18n.defaultLocale;
786
- for (const locale of Object.keys(config.i18n.locales)) {
787
- if (locale !== defaultLocale) {
788
- rootEntries.push({
789
- url: `/${locale}/`,
790
- priority: "1.0",
791
- changefreq: "daily"
792
- });
793
- }
794
- }
795
- }
796
- const entries = [
797
- ...rootEntries,
798
- ...routePaths.map((p) => ({
799
- url: p,
800
- priority: "0.8",
801
- changefreq: "weekly"
802
- }))
803
- ];
804
- return `<?xml version="1.0" encoding="UTF-8"?>
1
+ "use strict";var ye=Object.create;var Z=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty;var ut=(o,t)=>()=>(o&&(t=o(o=0)),t);var Mt=(o,t)=>{for(var e in t)Z(o,e,{get:t[e],enumerable:!0})},kt=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ve(t))!Pe.call(o,n)&&n!==e&&Z(o,n,{get:()=>t[n],enumerable:!(r=xe(t,n))||r.enumerable});return o};var v=(o,t,e)=>(e=o!=null?ye(be(o)):{},kt(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o)),Ce=o=>kt(Z({},"__esModule",{value:!0}),o);var we,b,g=ut(()=>{"use strict";we=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,b=we()});function D(o){return o.replace(/\\/g,"/")}function N(o){return o.replace(/^\d+\./,"")}function Q(o){let t=o.match(/^(\d+)\./);return t?parseInt(t[1],10):void 0}function Tt(o){return/\.mdx?$/.test(o)}function Y(o){try{return pt.default.statSync(o).mtimeMs}catch{return 0}}function Ot(o){let t=pt.default.readFileSync(o,"utf-8"),{data:e,content:r}=(0,_t.default)(t);return{data:e,content:r}}function E(o){return o.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gt(o){return E(o)}function Ft(o){let e=o.split("/").map(N).join("/").replace(/\/$/,"");return e=e.replace(/\.mdx?$/,""),(e==="index"||e.endsWith("/index"))&&(e=e.replace(/index$/,"")),e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function A(o){return mt.default.sanitize(o)}function ft(o){return mt.default.sanitize(o,{ALLOWED_TAGS:[],KEEP_CONTENT:!0})}function G(o){return o.charAt(0).toUpperCase()+o.slice(1)}var pt,_t,mt,k=ut(()=>{"use strict";g();pt=v(require("fs")),_t=v(require("gray-matter")),mt=v(require("isomorphic-dompurify"))});var Pt={};Mt(Pt,{AssetCache:()=>xt,FileCache:()=>U,TransformCache:()=>q,flushCache:()=>Me});async function Me(){await T.flush()}var P,C,H,L,I,tt,$e,et,vt,Ue,bt,Se,De,Re,Be,ht,yt,T,U,q,xt,V=ut(()=>{"use strict";g();P=v(require("fs")),C=v(require("path")),H=v(require("crypto")),L=v(require("zlib")),I=require("util");k();tt=(0,I.promisify)(P.default.writeFile),$e=(0,I.promisify)(P.default.readFile),et=(0,I.promisify)(P.default.mkdir),vt=(0,I.promisify)(P.default.rename),Ue=(0,I.promisify)(P.default.unlink),bt=process.env.BOLTDOCS_CACHE_DIR||".boltdocs",Se="assets",De="shards",Re=parseInt(process.env.BOLTDOCS_CACHE_LRU_LIMIT||"2000",10),Be=process.env.BOLTDOCS_CACHE_COMPRESS!=="0",ht=class{constructor(t){this.limit=t}cache=new Map;get(t){let e=this.cache.get(t);return e!==void 0&&(this.cache.delete(t),this.cache.set(t,e)),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.limit){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(t,e)}get size(){return this.cache.size}clear(){this.cache.clear()}},yt=class{queue=Promise.resolve();pendingCount=0;add(t){this.pendingCount++,this.queue=this.queue.then(t).finally(()=>{this.pendingCount--})}async flush(){await this.queue}get pending(){return this.pendingCount}},T=new yt,U=class{entries=new Map;cachePath=null;compress;constructor(t={}){if(this.compress=t.compress!==void 0?t.compress:Be,t.name){let e=t.root||process.cwd(),r=this.compress?"json.gz":"json";this.cachePath=C.default.resolve(e,bt,`${t.name}.${r}`)}}load(){if(process.env.BOLTDOCS_NO_CACHE!=="1"&&!(!this.cachePath||!P.default.existsSync(this.cachePath)))try{let t=P.default.readFileSync(this.cachePath);this.cachePath.endsWith(".gz")&&(t=L.default.gunzipSync(t));let e=JSON.parse(t.toString("utf-8"));this.entries=new Map(Object.entries(e))}catch{}}save(){if(process.env.BOLTDOCS_NO_CACHE==="1"||!this.cachePath)return;let t=Object.fromEntries(this.entries),e=JSON.stringify(t),r=this.cachePath,n=this.compress;T.add(async()=>{try{await et(C.default.dirname(r),{recursive:!0});let s=Buffer.from(e);n&&(s=L.default.gzipSync(s));let l=`${r}.${H.default.randomBytes(4).toString("hex")}.tmp`;await tt(l,s),await vt(l,r)}catch{}})}get(t){let e=this.entries.get(t);return!e||Y(t)!==e.mtime?null:e.data}set(t,e){this.entries.set(t,{data:e,mtime:Y(t)})}isValid(t){let e=this.entries.get(t);return e?Y(t)===e.mtime:!1}invalidate(t){this.entries.delete(t)}invalidateAll(){this.entries.clear()}pruneStale(t){for(let e of this.entries.keys())t.has(e)||this.entries.delete(e)}get size(){return this.entries.size}async flush(){await T.flush()}},q=class{index=new Map;memoryCache=new ht(Re);baseDir;shardsDir;indexPath;constructor(t,e=process.cwd()){this.baseDir=C.default.resolve(e,bt,`transform-${t}`),this.shardsDir=C.default.resolve(this.baseDir,De),this.indexPath=C.default.resolve(this.baseDir,"index.json")}load(){if(process.env.BOLTDOCS_NO_CACHE!=="1"&&P.default.existsSync(this.indexPath))try{let t=P.default.readFileSync(this.indexPath,"utf-8");this.index=new Map(Object.entries(JSON.parse(t)))}catch{}}save(){if(process.env.BOLTDOCS_NO_CACHE==="1")return;let t=JSON.stringify(Object.fromEntries(this.index)),e=this.indexPath;T.add(async()=>{await et(C.default.dirname(e),{recursive:!0}),await tt(e,t)})}async getMany(t){let e=new Map,r=[];for(let n of t){let s=this.memoryCache.get(n);s?e.set(n,s):this.index.has(n)&&r.push(n)}if(r.length>0){let n=await Promise.all(r.map(async s=>{let l=this.index.get(s),p=C.default.resolve(this.shardsDir,`${l}.gz`);try{let i=await $e(p),a=L.default.gunzipSync(i).toString("utf-8");return this.memoryCache.set(s,a),{key:s,val:a}}catch{return null}}));for(let s of n)s&&e.set(s.key,s.val)}return e}get(t){let e=this.memoryCache.get(t);if(e)return e;let r=this.index.get(t);if(!r)return null;let n=C.default.resolve(this.shardsDir,`${r}.gz`);if(!P.default.existsSync(n))return null;try{let s=P.default.readFileSync(n),l=L.default.gunzipSync(s).toString("utf-8");return this.memoryCache.set(t,l),l}catch{return null}}set(t,e){let r=H.default.createHash("md5").update(e).digest("hex");this.index.set(t,r),this.memoryCache.set(t,e);let n=C.default.resolve(this.shardsDir,`${r}.gz`);T.add(async()=>{if(P.default.existsSync(n))return;await et(this.shardsDir,{recursive:!0});let s=L.default.gzipSync(Buffer.from(e)),l=`${n}.${H.default.randomBytes(4).toString("hex")}.tmp`;await tt(l,s),await vt(l,n)})}get size(){return this.index.size}async flush(){await T.flush()}},xt=class{assetsDir;constructor(t=process.cwd()){this.assetsDir=C.default.resolve(t,bt,Se)}getFileHash(t){return H.default.createHash("md5").update(P.default.readFileSync(t)).digest("hex")}get(t,e){if(!P.default.existsSync(t))return null;let r=this.getFileHash(t),n=this.getCachedPath(t,`${e}-${r}`);return P.default.existsSync(n)?n:null}set(t,e,r){let n=this.getFileHash(t),s=this.getCachedPath(t,`${e}-${n}`);T.add(async()=>{await et(this.assetsDir,{recursive:!0});let l=`${s}.${H.default.randomBytes(4).toString("hex")}.tmp`;await tt(l,r),await vt(l,s)})}getCachedPath(t,e){let r=C.default.extname(t),n=C.default.basename(t,r),s=e.replace(/[^a-z0-9]/gi,"-").toLowerCase();return C.default.join(this.assetsDir,`${n}.${s}${r}`)}clear(){P.default.existsSync(this.assetsDir)&&P.default.rmSync(this.assetsDir,{recursive:!0,force:!0})}async flush(){await T.flush()}}});var He={};Mt(He,{default:()=>le,generateStaticPages:()=>rt});module.exports=Ce(He);g();g();var Zt=require("vite");g();var It=v(require("fast-glob"));k();g();V();var _=new U({name:"routes"});function Ct(){_.invalidateAll()}function wt(o){_.invalidate(o)}g();var z=v(require("path")),Et=v(require("github-slugger"));k();function jt(o,t,e,r){let n=decodeURIComponent(o),s=z.default.resolve(n),l=z.default.resolve(t),p=D(z.default.relative(l,s));if(p.startsWith("../")||p===".."||s.includes("\0"))throw new Error(`Security breach: File is outside of docs directory or contains null bytes: ${o}`);let{data:i,content:a}=Ot(o),c=p.split("/"),d,h;if(r?.versions&&c.length>0){let S=c[0];r.versions.versions[S]&&(h=S,c=c.slice(1))}if(r?.i18n&&c.length>0){let S=c[0];r.i18n.locales[S]&&(d=S,c=c.slice(1))}let $;if(c.length>0){let S=c[0].match(/^\((.+)\)$/);S&&($=S[1].toLowerCase(),c=c.slice(1))}let u=c.join("/"),m;i.permalink?m=i.permalink.startsWith("/")?i.permalink:`/${i.permalink}`:m=Ft(u||"index.md");let f=e;h&&(f+="/"+h),d&&(f+="/"+d),f+=m==="/"?"":m,(!f||f==="")&&(f="/");let x=c[c.length-1],M=N(x),w=N(z.default.basename(o,z.default.extname(o))),y=i.sidebarPosition??Q(x),R=c.length>=2?c[0]:void 0,F=R?N(R):void 0,X=c.length>=2&&/^index\.mdx?$/.test(M),de=new Et.default,Dt=[],ue=/^(#{2,4})\s+(.+)$/gm,lt;for(;(lt=ue.exec(a))!==null;){let S=lt[1].length,fe=lt[2].replace(/\[([^\]]+)\]\([^\)]+\)/g,"$1").replace(/[_*`]/g,"").trim(),Bt=A(fe).trim(),he=de.slug(Bt);Dt.push({level:S,text:Bt,id:he})}let pe=i.title?A(String(i.title)):w,dt=i.description?A(String(i.description)):"";!dt&&a&&(dt=ft(a.replace(/^#+.*$/gm,"").replace(/\[([^\]]+)\]\([^\)]+\)/g,"$1").replace(/[_*`]/g,"").replace(/\s+/g," ")).trim().slice(0,160));let me=i.badge?A(String(i.badge)):void 0,Rt=i.icon?String(i.icon):void 0,ge=ke(a);return{route:{path:f,componentPath:o,filePath:p,title:pe,description:dt,sidebarPosition:y,headings:Dt,locale:d,version:h,badge:me,icon:Rt,tab:$,_content:ge,_rawContent:a},relativeDir:F,isGroupIndex:X,inferredTab:$,groupMeta:X?{title:i.groupTitle||i.title||(F?G(F):""),position:i.groupPosition??i.sidebarPosition??(R?Q(R):void 0),icon:Rt}:void 0,inferredGroupPosition:R?Q(R):void 0}}function ke(o){let t=o.replace(/^#+.*$/gm,"").replace(/\[([^\]]+)\]\([^\)]+\)/g,"$1").replace(/\{[^\}]+\}/g,"").replace(/[_*`]/g,"").replace(/\s+/g," ");return ft(t).trim()}g();function Ht(o){return o.sort((t,e)=>!t.group&&!e.group?Lt(t,e):t.group?e.group?t.group!==e.group?_e(t,e):Lt(t,e):1:-1)}function Lt(o,t){return o.sidebarPosition!==void 0&&t.sidebarPosition!==void 0?o.sidebarPosition-t.sidebarPosition:o.sidebarPosition!==void 0?-1:t.sidebarPosition!==void 0?1:o.title.localeCompare(t.title)}function _e(o,t){return o.groupPosition!==void 0&&t.groupPosition!==void 0?o.groupPosition-t.groupPosition:o.groupPosition!==void 0?-1:t.groupPosition!==void 0?1:(o.groupTitle||o.group).localeCompare(t.groupTitle||t.group)}var W=new Map;async function K(o,t,e="/docs"){let r=performance.now();_.load(),W.clear(),(process.env.BOLTDOCS_FORCE_REPARSE==="true"||t?.i18n)&&_.invalidateAll();let n=await(0,It.default)(["**/*.md","**/*.mdx"],{cwd:o,absolute:!0,suppressErrors:!0,followSymbolicLinks:!1});_.pruneStale(new Set(n));let s=50,l=[],p=0;for(let u=0;u<n.length;u+=s){let m=n.slice(u,u+s),f=await Promise.all(m.map(async x=>{let M=_.get(x);if(M)return p++,M;let w=jt(x,o,e,t);return _.set(x,w),w}));l.push(...f),u+s<n.length&&await new Promise(x=>setImmediate(x))}_.save();let i=new Map,a=[];for(let u of l)if(u.isGroupIndex&&u.relativeDir&&a.push(u),u.relativeDir){let m=i.get(u.relativeDir);m?(m.position===void 0&&u.inferredGroupPosition!==void 0&&(m.position=u.inferredGroupPosition),!m.icon&&u.route.icon&&(m.icon=u.route.icon)):(m={title:G(u.relativeDir),position:u.inferredGroupPosition,icon:u.route.icon},i.set(u.relativeDir,m))}for(let u of a){let m=i.get(u.relativeDir);u.groupMeta&&(m.title=u.groupMeta.title,u.groupMeta.position!==void 0&&(m.position=u.groupMeta.position),u.groupMeta.icon&&(m.icon=u.groupMeta.icon))}let c=new Array(l.length);for(let u=0;u<l.length;u++){let m=l[u],f=m.relativeDir,x=f?i.get(f):void 0;c[u]={...m.route,group:f,groupTitle:x?.title||(f?G(f):void 0),groupPosition:x?.position,groupIcon:x?.icon}}let d=c;if(t?.i18n){let u=Te(c,t,e);d=[...c,...u]}let h=Ht(d),$=performance.now()-r;return console.log(`[boltdocs] Route generation: ${$.toFixed(2)}ms (${n.length} files, ${p} cache hits)`),h}function Te(o,t,e){let r=t.i18n.defaultLocale,n=Object.keys(t.i18n.locales),s=[],l=new Map,p=[];for(let i of o){let a=i.locale||r;l.has(a)||l.set(a,new Set),l.get(a).add(i.path),a===r&&p.push(i)}for(let i of n){if(i===r)continue;let a=l.get(i)||new Set;for(let c of p){let d=Oe(c.path,r,i,e);a.has(d)||s.push({...c,path:d,locale:i})}}return s}function Oe(o,t,e,r){let n=`${o}:${e}`,s=W.get(n);if(s)return s;let l=r,p=o.match(new RegExp(`^${r}/(v[0-9]+)`));p&&(l+="/"+p[1]);let i=o.substring(l.length),a=`/${t}`;if(i.startsWith(a+"/"))i="/"+e+"/"+i.substring(a.length+1);else if(i===a)i="/"+e;else if(i==="/"||i==="")i="/"+e;else{let d=i.startsWith("/")?"":"/";i="/"+e+d+i}let c=l+i;return W.size>2e3&&W.clear(),W.set(n,c),c}var Qt=require("vite-plugin-image-optimizer");g();var ot=v(require("path")),zt=v(require("fs")),Nt=require("vite"),it=["boltdocs.config.js","boltdocs.config.mjs","boltdocs.config.ts"];async function nt(o,t=process.cwd()){let e=t,r={docsDir:ot.default.resolve(o),themeConfig:{title:"Boltdocs",description:"A Vite documentation framework",navbar:[{label:"Home",href:"/"},{label:"Documentation",href:"/docs"}],codeTheme:{light:"github-light",dark:"github-dark"},poweredBy:!0,breadcrumbs:!0}},n={};for(let i of it){let a=ot.default.resolve(e,i);if(zt.default.existsSync(a))try{let c=await(0,Nt.loadConfigFromFile)({command:"serve",mode:"development"},a,e);if(c){n=c.config;break}}catch(c){console.warn(`[boltdocs] Failed to load config from ${i}:`,c)}}let l={...{title:n.title,description:n.description,logo:n.logo,navbar:n.navbar,sidebar:n.sidebar,socialLinks:n.socialLinks,footer:n.footer,githubRepo:n.githubRepo,tabs:n.tabs},...n.themeConfig||{}},p=Object.fromEntries(Object.entries(l).filter(([i,a])=>a!==void 0));return p.navbar&&(p.navbar=p.navbar.map(i=>({label:i.label||i.text||"",href:i.href||i.link||i.to||"",items:i.items?.map(a=>({label:a.label||a.text||"",href:a.href||a.link||a.to||""}))}))),{docsDir:ot.default.resolve(o),themeConfig:{...r.themeConfig,...p,codeTheme:p.codeTheme||(n.themeConfig||n).codeTheme||r.themeConfig?.codeTheme},i18n:n.i18n,versions:n.versions,siteUrl:n.siteUrl,plugins:n.plugins||[],external:n.external,integrations:n.integrations}}g();var j=v(require("fs")),O=v(require("path"));k();var Vt=require("url"),Wt=require("module");g();k();function At(o,t){let e=E(t.title),r=E(t.description);return o.replace(/<title>.*?<\/title>/,`<title>${e}</title>`).replace(/(<meta name="description" content=")[^"]*(")/,`$1${r}$2`).replace(/(<meta property="og:title" content=")[^"]*(")/,`$1${e}$2`).replace(/(<meta property="og:description" content=")[^"]*(")/,`$1${r}$2`).replace(/(<meta name="twitter:title" content=")[^"]*(")/,`$1${e}$2`).replace(/(<meta name="twitter:description" content=")[^"]*(")/,`$1${r}$2`)}g();k();function Gt(o,t){let e=t?.siteUrl?.replace(/\/$/,"")||"https://example.com",r=new Date().toISOString().split("T")[0],n=[{url:"/",priority:"1.0",changefreq:"daily"}];if(t?.i18n){let l=t.i18n.defaultLocale;for(let p of Object.keys(t.i18n.locales))p!==l&&n.push({url:`/${p}/`,priority:"1.0",changefreq:"daily"})}return`<?xml version="1.0" encoding="UTF-8"?>
805
2
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
806
- ${entries.map(
807
- (e) => ` <url>
808
- <loc>${escapeXml(baseUrl)}${escapeXml(e.url)}</loc>
809
- <lastmod>${today}</lastmod>
810
- <changefreq>${e.changefreq}</changefreq>
811
- <priority>${e.priority}</priority>
812
- </url>`
813
- ).join("\n")}
814
- </urlset>`;
815
- }
816
-
817
- // src/node/ssg/index.ts
818
- var import_meta2 = {};
819
- var _filename = (0, import_url2.fileURLToPath)(import_meta2.url);
820
- var _dirname = import_path4.default.dirname(_filename);
821
- var _require = (0, import_module.createRequire)(import_meta2.url);
822
- async function generateStaticPages(options) {
823
- const { docsDir, docsDirName, outDir, config } = options;
824
- const routes = await generateRoutes(docsDir, config);
825
- const siteTitle = config?.themeConfig?.title || "Boltdocs";
826
- const siteDescription = config?.themeConfig?.description || "";
827
- const ssrModulePath = import_path4.default.resolve(_dirname, "../client/ssr.js");
828
- if (!import_fs4.default.existsSync(ssrModulePath)) {
829
- console.error(
830
- "[boltdocs] SSR module not found at",
831
- ssrModulePath,
832
- "- Did you build the core package?"
833
- );
834
- return;
835
- }
836
- const { render } = _require(ssrModulePath);
837
- const templatePath = import_path4.default.join(outDir, "index.html");
838
- if (!import_fs4.default.existsSync(templatePath)) {
839
- console.warn("[boltdocs] No index.html found in outDir, skipping SSG.");
840
- return;
841
- }
842
- const template = import_fs4.default.readFileSync(templatePath, "utf-8");
843
- await Promise.all(
844
- routes.map(async (route) => {
845
- const pageTitle = `${route.title} | ${siteTitle}`;
846
- const pageDescription = route.description || siteDescription;
847
- const fakeModules = {};
848
- fakeModules[route.componentPath] = { default: () => {
849
- } };
850
- try {
851
- const appHtml = await render({
852
- path: route.path,
853
- routes,
854
- config: config || {},
855
- docsDirName,
856
- modules: fakeModules,
857
- homePage: void 0
858
- // No custom home page for now
859
- });
860
- const html = replaceMetaTags(template, {
861
- title: escapeHtml(pageTitle),
862
- description: escapeHtml(pageDescription)
863
- }).replace("<!--app-html-->", appHtml).replace(`<div id="root"></div>`, `<div id="root">${appHtml}</div>`);
864
- const routeDir = import_path4.default.join(outDir, route.path);
865
- await import_fs4.default.promises.mkdir(routeDir, { recursive: true });
866
- await import_fs4.default.promises.writeFile(
867
- import_path4.default.join(routeDir, "index.html"),
868
- html,
869
- "utf-8"
870
- );
871
- } catch (e) {
872
- console.error(`[boltdocs] Error SSR rendering route ${route.path}:`, e);
873
- }
874
- })
875
- );
876
- const sitemap = generateSitemap(
877
- routes.map((r) => r.path),
878
- config
879
- );
880
- import_fs4.default.writeFileSync(import_path4.default.join(outDir, "sitemap.xml"), sitemap, "utf-8");
881
- console.log(
882
- `[boltdocs] Generated ${routes.length} static pages + sitemap.xml`
883
- );
884
- const { flushCache: flushCache2 } = await Promise.resolve().then(() => (init_cache(), cache_exports));
885
- await flushCache2();
886
- }
887
-
888
- // src/node/plugin/index.ts
889
- init_utils();
890
- var import_path6 = __toESM(require("path"));
891
-
892
- // src/node/plugin/entry.ts
893
- init_utils();
894
- var import_path5 = __toESM(require("path"));
895
- function generateEntryCode(options, config) {
896
- const homeImport = options.homePage ? `import HomePage from '${normalizePath(options.homePage)}';` : "";
897
- const homeOption = options.homePage ? "homePage: HomePage," : "";
898
- const customCssImport = options.customCss ? `import '${normalizePath(options.customCss)}';` : "";
899
- const pluginComponents = config?.plugins?.flatMap((p) => Object.entries(p.components || {})) || [];
900
- const componentImports = pluginComponents.map(
901
- ([
902
- name,
903
- path7
904
- ]) => `import * as _comp_${name} from '${normalizePath(path7)}';
905
- const ${name} = _comp_${name}.default || _comp_${name}['${name}'] || _comp_${name};`
906
- ).join("\n");
907
- const componentMap = pluginComponents.map(([name]) => name).join(", ");
908
- const docsDirName = import_path5.default.basename(options.docsDir || "docs");
909
- return `
3
+ ${[...n,...o.map(l=>({url:l,priority:"0.8",changefreq:"weekly"}))].map(l=>` <url>
4
+ <loc>${gt(e)}${gt(l.url)}</loc>
5
+ <lastmod>${r}</lastmod>
6
+ <changefreq>${l.changefreq}</changefreq>
7
+ <priority>${l.priority}</priority>
8
+ </url>`).join(`
9
+ `)}
10
+ </urlset>`}var Fe=(0,Vt.fileURLToPath)(b),Ut=O.default.dirname(Fe),qt=(0,Wt.createRequire)(b);async function rt(o){let{docsDir:t,docsDirName:e,outDir:r,config:n}=o,s=await K(t,n),l=n?.themeConfig?.title||"Boltdocs",p=n?.themeConfig?.description||"",i=O.default.resolve(Ut,"../client/ssr.js");if(!j.default.existsSync(i)){console.error("[boltdocs] SSR module not found at",i,"- Did you build the core package?");return}let a=qt("module"),c=a.prototype.require;a.prototype.require=function(f,...x){return f==="virtual:boltdocs-layout"?{__esModule:!0,default:function(w){try{let R=c.apply(this,[O.default.resolve(Ut,"../client/index.js")]).DefaultLayout||(({children:X})=>X);return c.apply(this,["react"]).createElement(R,w)}catch{return w.children}}}:c.apply(this,[f,...x])};let{render:d}=qt(i);a.prototype.require=c;let h=O.default.join(r,"index.html");if(!j.default.existsSync(h)){console.warn("[boltdocs] No index.html found in outDir, skipping SSG.");return}let $=j.default.readFileSync(h,"utf-8");await Promise.all(s.map(async f=>{let x=`${f.title} | ${l}`,M=f.description||p,w={};w[`/${e}/${f.filePath}`]={default:()=>null};try{let y=await d({path:f.path,routes:s,config:n||{},docsDirName:e,modules:w,homePage:void 0}),R=At($,{title:E(x),description:E(M)}).replace("<!--app-html-->",y).replace('<div id="root"></div>',`<div id="root">${y}</div>`),F=O.default.join(r,f.path);await j.default.promises.mkdir(F,{recursive:!0}),await j.default.promises.writeFile(O.default.join(F,"index.html"),R,"utf-8")}catch(y){console.error(`[boltdocs] Error SSR rendering route ${f.path}:`,y&&(y.stack||y))}}));let u=Gt(s.map(f=>f.path),n);j.default.writeFileSync(O.default.join(r,"sitemap.xml"),u,"utf-8"),console.log(`[boltdocs] Generated ${s.length} static pages + sitemap.xml`);let{flushCache:m}=await Promise.resolve().then(()=>(V(),Pt));await m()}k();var B=v(require("path"));g();k();var Kt=v(require("path"));function Jt(o,t){let e=o.homePage?`import HomePage from '${D(o.homePage)}';`:"",r=o.homePage?"homePage: HomePage,":"",n=t?.plugins?.flatMap(d=>Object.entries(d.components||{}))||[],s=n.map(([d,h])=>`import * as _comp_${d} from '${D(h)}';
11
+ const ${d} = _comp_${d}.default || _comp_${d}['${d}'] || _comp_${d};`).join(`
12
+ `),l=n.map(([d])=>d).join(", "),p=Kt.default.basename(o.docsDir||"docs"),i=Object.entries(t?.external||{}),a=i.map(([d,h],$)=>`import _ext_${$} from '${D(h)}';`).join(`
13
+ `),c=i.length>0?`externalPages: { ${i.map(([d],h)=>`"${d}": _ext_${h}`).join(", ")} },`:"";return`
910
14
  import { createBoltdocsApp as _createApp } from 'boltdocs/client';
911
- import 'boltdocs/style.css';
912
- ${customCssImport}
913
15
  import _routes from 'virtual:boltdocs-routes';
914
16
  import _config from 'virtual:boltdocs-config';
915
- ${homeImport}
916
- ${componentImports}
17
+ import _user_mdx_components from 'virtual:boltdocs-mdx-components';
18
+ ${e}
19
+ ${s}
20
+ ${a}
917
21
 
918
22
  _createApp({
919
23
  target: '#root',
920
24
  routes: _routes,
921
- docsDirName: '${docsDirName}',
25
+ docsDirName: '${p}',
922
26
  config: _config,
923
- modules: import.meta.glob('/${docsDirName}/**/*.{md,mdx}'),
27
+ modules: import.meta.glob('/${p}/**/*.{md,mdx}'),
924
28
  hot: import.meta.hot,
925
- ${homeOption}
926
- components: { ${componentMap} },
29
+ ${r}
30
+ ${c}
31
+ components: { ${l}${l?", ":""} ...(_user_mdx_components || {}) },
927
32
  });
928
- `;
929
- }
930
-
931
- // src/node/plugin/html.ts
932
- function injectHtmlMeta(html, config) {
933
- const title = config.themeConfig?.title || "Boltdocs";
934
- const description = config.themeConfig?.description || "";
935
- const seoTags = [
936
- `<meta name="description" content="${description}">`,
937
- `<meta property="og:title" content="${title}">`,
938
- `<meta property="og:description" content="${description}">`,
939
- `<meta property="og:type" content="website">`,
940
- `<meta name="twitter:card" content="summary">`,
941
- `<meta name="twitter:title" content="${title}">`,
942
- `<meta name="twitter:description" content="${description}">`,
943
- `<meta name="generator" content="Boltdocs">`
944
- ].join("\n ");
945
- const themeScript = `
33
+ `}g();function Xt(o,t){let e=t.themeConfig?.title||"Boltdocs",r=t.themeConfig?.description||"",n=[`<meta name="description" content="${r}">`,`<meta property="og:title" content="${e}">`,`<meta property="og:description" content="${r}">`,'<meta property="og:type" content="website">','<meta name="twitter:card" content="summary">',`<meta name="twitter:title" content="${e}">`,`<meta name="twitter:description" content="${r}">`,'<meta name="generator" content="Boltdocs">'].join(`
34
+ `),s=`
946
35
  <script>
947
36
  (function() {
948
37
  try {
@@ -958,230 +47,11 @@ function injectHtmlMeta(html, config) {
958
47
  } catch (e) {}
959
48
  })();
960
49
  </script>
961
- `;
962
- html = html.replace(/<title>.*?<\/title>/, `<title>${title}</title>`);
963
- html = html.replace("</head>", ` ${seoTags}
964
- ${themeScript} </head>`);
965
- if (!html.includes("src/main")) {
966
- html = html.replace(
967
- "</body>",
968
- ' <script type="module">import "virtual:boltdocs-entry";</script>\n </body>'
969
- );
970
- }
971
- return html;
972
- }
973
-
974
- // src/node/plugin/index.ts
975
- function boltdocsPlugin(options = {}, passedConfig) {
976
- const docsDir = import_path6.default.resolve(process.cwd(), options.docsDir || "docs");
977
- const normalizedDocsDir = normalizePath(docsDir);
978
- let config = passedConfig;
979
- let viteConfig;
980
- let isBuild = false;
981
- const extraVitePlugins = config?.plugins?.flatMap((p) => p.vitePlugins || []) || [];
982
- return [
983
- {
984
- name: "vite-plugin-boltdocs",
985
- enforce: "pre",
986
- async config(userConfig, env) {
987
- isBuild = env.command === "build";
988
- const envDir = userConfig.envDir || process.cwd();
989
- const envs = (0, import_vite.loadEnv)(env.mode, envDir, "");
990
- Object.assign(process.env, envs);
991
- if (!config) {
992
- config = await resolveConfig(docsDir);
993
- }
994
- if (!options.customCss && config.themeConfig?.customCss) {
995
- options.customCss = config.themeConfig.customCss;
996
- }
997
- return {
998
- optimizeDeps: { include: ["react", "react-dom"] }
999
- };
1000
- },
1001
- configResolved(resolved) {
1002
- viteConfig = resolved;
1003
- },
1004
- configureServer(server) {
1005
- const configPaths = CONFIG_FILES.map(
1006
- (c) => import_path6.default.resolve(process.cwd(), c)
1007
- );
1008
- server.watcher.add(configPaths);
1009
- const handleFileEvent = async (file, type) => {
1010
- const normalized = normalizePath(file);
1011
- if (CONFIG_FILES.some((c) => normalized.endsWith(c))) {
1012
- server.restart();
1013
- return;
1014
- }
1015
- if (!normalized.startsWith(normalizedDocsDir) || !isDocFile(normalized))
1016
- return;
1017
- if (type === "add" || type === "unlink") {
1018
- invalidateRouteCache();
1019
- } else {
1020
- invalidateFile(file);
1021
- }
1022
- const newRoutes = await generateRoutes(docsDir, config);
1023
- const routesMod = server.moduleGraph.getModuleById(
1024
- "\0virtual:boltdocs-routes"
1025
- );
1026
- if (routesMod) server.moduleGraph.invalidateModule(routesMod);
1027
- server.ws.send({
1028
- type: "custom",
1029
- event: "boltdocs:routes-update",
1030
- data: newRoutes
1031
- });
1032
- };
1033
- server.watcher.on("add", (f) => handleFileEvent(f, "add"));
1034
- server.watcher.on("unlink", (f) => handleFileEvent(f, "unlink"));
1035
- server.watcher.on("change", (f) => handleFileEvent(f, "change"));
1036
- },
1037
- resolveId(id) {
1038
- if (id === "virtual:boltdocs-routes" || id === "virtual:boltdocs-config" || id === "virtual:boltdocs-entry") {
1039
- return "\0" + id;
1040
- }
1041
- },
1042
- async load(id) {
1043
- if (id === "\0virtual:boltdocs-routes") {
1044
- const routes = await generateRoutes(docsDir, config);
1045
- return `export default ${JSON.stringify(routes, null, 2)};`;
1046
- }
1047
- if (id === "\0virtual:boltdocs-config") {
1048
- const clientConfig = {
1049
- themeConfig: config?.themeConfig,
1050
- i18n: config?.i18n,
1051
- versions: config?.versions,
1052
- siteUrl: config?.siteUrl
1053
- };
1054
- return `export default ${JSON.stringify(clientConfig, null, 2)};`;
1055
- }
1056
- if (id === "\0virtual:boltdocs-entry") {
1057
- const code = generateEntryCode(options, config);
1058
- return code;
1059
- }
1060
- },
1061
- transformIndexHtml: {
1062
- order: "pre",
1063
- handler(html) {
1064
- return injectHtmlMeta(html, config);
1065
- }
1066
- },
1067
- async closeBundle() {
1068
- if (!isBuild) return;
1069
- const outDir = viteConfig?.build?.outDir ? import_path6.default.resolve(viteConfig.root, viteConfig.build.outDir) : import_path6.default.resolve(process.cwd(), "dist");
1070
- const docsDirName = import_path6.default.basename(docsDir || "docs");
1071
- await generateStaticPages({ docsDir, docsDirName, outDir, config });
1072
- const { flushCache: flushCache2 } = await Promise.resolve().then(() => (init_cache(), cache_exports));
1073
- await flushCache2();
1074
- }
1075
- },
1076
- (0, import_vite_plugin_image_optimizer.ViteImageOptimizer)({
1077
- includePublic: true,
1078
- png: { quality: 80 },
1079
- jpeg: { quality: 80 },
1080
- jpg: { quality: 80 },
1081
- webp: { quality: 80 },
1082
- avif: { quality: 80 },
1083
- svg: {
1084
- multipass: true,
1085
- plugins: [
1086
- {
1087
- name: "preset-default",
1088
- params: { overrides: { removeViewBox: false } }
1089
- }
1090
- ]
1091
- }
1092
- }),
1093
- ...extraVitePlugins.filter((p) => !!p)
1094
- ];
1095
- }
1096
-
1097
- // src/node/mdx.ts
1098
- var import_rollup = __toESM(require("@mdx-js/rollup"));
1099
- var import_remark_gfm = __toESM(require("remark-gfm"));
1100
- var import_remark_frontmatter = __toESM(require("remark-frontmatter"));
1101
- var import_rehype_slug = __toESM(require("rehype-slug"));
1102
- var import_rehype_pretty_code = __toESM(require("rehype-pretty-code"));
1103
- var import_crypto2 = __toESM(require("crypto"));
1104
- init_cache();
1105
- var mdxCache = new TransformCache("mdx");
1106
- var mdxCacheLoaded = false;
1107
- function boltdocsMdxPlugin(config, compiler = import_rollup.default) {
1108
- const extraRemarkPlugins = config?.plugins?.flatMap((p) => p.remarkPlugins || []) || [];
1109
- const extraRehypePlugins = config?.plugins?.flatMap((p) => p.rehypePlugins || []) || [];
1110
- const baseMdxPlugin = compiler({
1111
- remarkPlugins: [import_remark_gfm.default, import_remark_frontmatter.default, ...extraRemarkPlugins],
1112
- rehypePlugins: [
1113
- import_rehype_slug.default,
1114
- ...extraRehypePlugins,
1115
- [
1116
- import_rehype_pretty_code.default,
1117
- {
1118
- theme: config?.themeConfig?.codeTheme || "one-dark-pro",
1119
- keepBackground: false
1120
- }
1121
- ]
1122
- ],
1123
- jsxRuntime: "automatic",
1124
- providerImportSource: "@mdx-js/react"
1125
- });
1126
- if (baseMdxPlugin.isMock) {
1127
- console.log("MDX PLUGIN IS MOCKED");
1128
- }
1129
- return {
1130
- ...baseMdxPlugin,
1131
- name: "vite-plugin-boltdocs-mdx",
1132
- async buildStart() {
1133
- hits = 0;
1134
- total = 0;
1135
- if (!mdxCacheLoaded) {
1136
- mdxCache.load();
1137
- mdxCacheLoaded = true;
1138
- }
1139
- if (baseMdxPlugin.buildStart) {
1140
- await baseMdxPlugin.buildStart.call(this);
1141
- }
1142
- },
1143
- async transform(code, id, options) {
1144
- if (!id.endsWith(".md") && !id.endsWith(".mdx")) {
1145
- return baseMdxPlugin.transform?.call(this, code, id, options);
1146
- }
1147
- total++;
1148
- const contentHash = import_crypto2.default.createHash("md5").update(code).digest("hex");
1149
- const cacheKey = `${id}:${contentHash}`;
1150
- const cached = mdxCache.get(cacheKey);
1151
- if (cached) {
1152
- hits++;
1153
- return { code: cached, map: null };
1154
- }
1155
- const result = await baseMdxPlugin.transform.call(
1156
- this,
1157
- code,
1158
- id,
1159
- options
1160
- );
1161
- if (result && typeof result === "object" && result.code) {
1162
- mdxCache.set(cacheKey, result.code);
1163
- }
1164
- return result;
1165
- },
1166
- async buildEnd() {
1167
- mdxCache.save();
1168
- await mdxCache.flush();
1169
- if (baseMdxPlugin.buildEnd) {
1170
- await baseMdxPlugin.buildEnd.call(this);
1171
- }
1172
- }
1173
- };
1174
- }
1175
- var hits = 0;
1176
- var total = 0;
1177
-
1178
- // src/node/index.ts
1179
- async function boltdocs(options) {
1180
- const docsDir = options?.docsDir || "docs";
1181
- const config = await resolveConfig(docsDir);
1182
- return [...boltdocsPlugin(options, config), boltdocsMdxPlugin(config)];
1183
- }
1184
- // Annotate the CommonJS export names for ESM import in node:
1185
- 0 && (module.exports = {
1186
- generateStaticPages
1187
- });
50
+ `;return o=o.replace(/<title>.*?<\/title>/,`<title>${e}</title>`),o=o.replace("</head>",` ${n}
51
+ ${s} </head>`),o.includes("src/main")||(o=o.replace("</body>",` <script type="module">import "virtual:boltdocs-entry";</script>
52
+ </body>`)),o}var $t=v(require("fs"));g();function Yt(o={},t){let e=B.default.resolve(process.cwd(),o.docsDir||"docs"),r=D(e),n=t,s,l=!1,p=n?.plugins?.flatMap(i=>i.vitePlugins||[])||[];return[{name:"vite-plugin-boltdocs",enforce:"pre",async config(i,a){l=a.command==="build";let c=i.envDir||process.cwd(),d=(0,Zt.loadEnv)(a.mode,c,"");return Object.assign(process.env,d),n||(n=await nt(e)),{optimizeDeps:{include:["react","react-dom"]}}},configResolved(i){s=i},configureServer(i){let a=it.map(m=>B.default.resolve(process.cwd(),m)),c=["tsx","jsx"],d=c.map(m=>B.default.resolve(e,`layout.${m}`)),h=["tsx","ts","jsx","js"],$=h.map(m=>B.default.resolve(e,`mdx-components.${m}`));i.watcher.add([...a,...$,...d]);let u=async(m,f)=>{let x=D(m);if(it.some(y=>x.endsWith(y))){i.restart();return}if(h.some(y=>x.endsWith(`mdx-components.${y}`))){let y=i.moduleGraph.getModuleById("\0virtual:boltdocs-mdx-components");y&&i.moduleGraph.invalidateModule(y),i.ws.send({type:"full-reload"});return}if(c.some(y=>x.endsWith(`layout.${y}`))){let y=i.moduleGraph.getModuleById("\0virtual:boltdocs-layout");y&&i.moduleGraph.invalidateModule(y),i.ws.send({type:"full-reload"});return}if(!x.startsWith(r)||!Tt(x))return;f==="add"||f==="unlink"?Ct():wt(m);let M=await K(e,n),w=i.moduleGraph.getModuleById("\0virtual:boltdocs-routes");w&&i.moduleGraph.invalidateModule(w),i.ws.send({type:"custom",event:"boltdocs:routes-update",data:M})};i.watcher.on("add",m=>u(m,"add")),i.watcher.on("unlink",m=>u(m,"unlink")),i.watcher.on("change",m=>u(m,"change"))},resolveId(i){if(i==="virtual:boltdocs-routes"||i==="virtual:boltdocs-config"||i==="virtual:boltdocs-entry"||i==="virtual:boltdocs-mdx-components"||i==="virtual:boltdocs-layout")return"\0"+i},async load(i){if(i==="\0virtual:boltdocs-routes"){let a=await K(e,n);return`export default ${JSON.stringify(a,null,2)};`}if(i==="\0virtual:boltdocs-config"){let a={themeConfig:n?.themeConfig,integrations:n?.integrations,i18n:n?.i18n,versions:n?.versions,siteUrl:n?.siteUrl};return`export default ${JSON.stringify(a,null,2)};`}if(i==="\0virtual:boltdocs-entry")return Jt(o,n);if(i==="\0virtual:boltdocs-mdx-components"){let a=["tsx","ts","jsx","js"],c=null;for(let d of a){let h=B.default.resolve(e,`mdx-components.${d}`);if($t.default.existsSync(h)){c=h;break}}if(c){let d=D(c);return`import * as components from '${d}';
53
+ const mdxComponents = components.default || components;
54
+ export default mdxComponents;
55
+ export * from '${d}';`}return"export default {};"}if(i==="\0virtual:boltdocs-layout"){let a=["tsx","jsx"],c=null;for(let d of a){let h=B.default.resolve(e,`layout.${d}`);if($t.default.existsSync(h)){c=h;break}}return c?`import UserLayout from '${D(c)}';
56
+ export default UserLayout;`:`import { DefaultLayout } from 'boltdocs/client';
57
+ export default DefaultLayout;`}},transformIndexHtml:{order:"pre",handler(i){return Xt(i,n)}},async closeBundle(){if(!l)return;let i=s?.build?.outDir?B.default.resolve(s.root,s.build.outDir):B.default.resolve(process.cwd(),"dist"),a=B.default.basename(e||"docs");await rt({docsDir:e,docsDirName:a,outDir:i,config:n});let{flushCache:c}=await Promise.resolve().then(()=>(V(),Pt));await c()}},(0,Qt.ViteImageOptimizer)({includePublic:!0,png:{quality:80},jpeg:{quality:80},jpg:{quality:80},webp:{quality:80},avif:{quality:80},svg:{multipass:!0,plugins:[{name:"preset-default"}]}}),...p.filter(i=>!!i)]}g();var ee=v(require("@mdx-js/rollup")),oe=v(require("remark-gfm")),ie=v(require("remark-frontmatter")),ne=v(require("rehype-slug")),re=v(require("crypto")),St=require("unist-util-visit"),se=require("shiki");V();var st=null;async function ae(o){if(st)return st;let t=typeof o=="object"?[o.light,o.dark]:[o??"github-dark"];return["github-light","github-dark"].forEach(e=>{t.includes(e)||t.push(e)}),st=await(0,se.createHighlighter)({themes:t,langs:["tsx","jsx","ts","js","json","md","mdx","css","html","bash","sh","yaml","yml"]}),st}function Ee(o){return async t=>{let e=o?.themeConfig?.codeTheme??{light:"github-light",dark:"github-dark"},r=await ae(e);(0,St.visit)(t,["mdxJsxFlowElement","mdxJsxTextElement"],n=>{if(n.name!=="ComponentPreview")return;let s=n.attributes?.find(a=>a.name==="code"),l="";if(s){if(typeof s.value=="string")l=s.value;else if(s.value?.type==="mdxJsxAttributeValueExpression"){let a=s.value.value??"";l=a.match(/^[`'"](.+)[`'"]$/)?.[1]??a}}if(!l)return;let p=typeof e=="object"?{themes:{light:e.light,dark:e.dark},lang:"tsx"}:{theme:e,lang:"tsx"},i=r.codeToHtml(l,p);n.attributes=(n.attributes??[]).filter(a=>a.name!=="highlightedHtml"),n.attributes.push({type:"mdxJsxAttribute",name:"highlightedHtml",value:i})})}}function je(o){return async t=>{let e=o?.themeConfig?.codeTheme||{light:"github-light",dark:"github-dark"},r=await ae(e);(0,St.visit)(t,"element",n=>{if(n.tagName==="pre"&&n.children?.[0]?.tagName==="code"){let s=n.children[0],p=(s.properties?.className||[]).find(h=>h.startsWith("language-")),i=p?p.slice(9):"text",a=s.children[0]?.value||"",c={lang:i};typeof e=="object"?c.themes={light:e.light,dark:e.dark}:c.theme=e;let d=r.codeToHtml(a,c);n.properties.dataHighlighted="true",n.properties.highlightedHtml=d,n.children=[]}})}}var Le="v3",J=new q("mdx"),te=!1;function ce(o,t=ee.default){let e=o?.plugins?.flatMap(s=>s.remarkPlugins||[])||[],r=o?.plugins?.flatMap(s=>s.rehypePlugins||[])||[],n=t({remarkPlugins:[oe.default,ie.default,[Ee,o],...e],rehypePlugins:[ne.default,[je,o],...r],jsxRuntime:"automatic",providerImportSource:"@mdx-js/react"});return n.isMock&&console.log("MDX PLUGIN IS MOCKED"),{...n,name:"vite-plugin-boltdocs-mdx",async buildStart(){at=0,ct=0,te||(J.load(),te=!0),n.buildStart&&await n.buildStart.call(this)},async transform(s,l,p){if(!l.endsWith(".md")&&!l.endsWith(".mdx"))return n.transform?.call(this,s,l,p);console.log(`[boltdocs] Transforming MDX: ${l}`),ct++;let i=re.default.createHash("md5").update(s).digest("hex"),a=`${l}:${i}:${Le}`,c=J.get(a);if(c)return at++,{code:c,map:null};let d=await n.transform.call(this,s,l,p);return d&&typeof d=="object"&&d.code&&J.set(a,d.code),d},async buildEnd(){console.log(`[boltdocs] MDX Cache Performance: ${at}/${ct} hits (${Math.round(at/ct*100)||0}%)`),J.save(),await J.flush(),n.buildEnd&&await n.buildEnd.call(this)}}}var at=0,ct=0;async function le(o){let t=o?.docsDir||"docs",e=await nt(t);return[...Yt(o,e),ce(e)]}0&&(module.exports={generateStaticPages});