@viteplus/versions 1.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.
package/LICENSE ADDED
@@ -0,0 +1,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # @viteplus/versions
2
+
3
+ [![Documentation](https://img.shields.io/badge/Documentation-orange?logo=typescript&logoColor=f5f5f5)](https://vitepulse.github.io/versions/)
4
+ [![npm version](https://img.shields.io/npm/v/@vitepulse/versions.svg)](https://www.npmjs.com/package/@vitepulse/versions)
5
+ [![License: MPL 2.0](https://img.shields.io/badge/License-MPL_2.0-brightgreen.svg)](https://opensource.org/licenses/MPL-2.0)
6
+ [![Node.js CI](https://github.com/vitepulse/versions/actions/workflows/node.js.yml/badge.svg)](https://github.com/vitepulse/versions/actions/workflows/node.js.yml)
7
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/vitepulse/versions)
8
+
9
+ A plugin for VitePress that enables versioned documentation, including automatic versioned routes, sidebars, navigation, and a version switcher component.
10
+
11
+ ## Installation
12
+
13
+ Install the plugin using your preferred package manager:
14
+ ```bash
15
+ pnpm install @viteplus/versions
16
+ # or
17
+ npm install @viteplus/versions
18
+ # or
19
+ yarn add @viteplus/versions
20
+ ```
21
+
22
+ ## Basic Setup
23
+ 1. Ensure Relative Links
24
+
25
+ All links in your `markdown` files must be relative.
26
+ This is critical because the plugin relies on relative paths to determine the correct versioned file to link to.
27
+
28
+ - Example: Linking `docs/guide/advanced-setup.md` from `docs/guide/getting-started.md`:
29
+ ```markdown
30
+ ./advanced-setup.md
31
+ ```
32
+
33
+ - Example: Linking `docs/help/faq.md` from `docs/guide/getting-started.md`:
34
+ ```markdown
35
+ ../help/faq.md
36
+ ```
37
+
38
+ > [!CAUTION]
39
+ > Absolute links like /guide/getting-started will break versioned navigation.
40
+
41
+ 2. Configure Versioning
42
+
43
+ Replace defineConfig in .vitepress/config.ts with `defineVersionedConfig`:
44
+
45
+ ```ts
46
+ import { defineVersionedConfig } from '@viteplus/versions';
47
+
48
+ export default defineVersionedConfig({
49
+ root: 'docs', // root folder
50
+ title: 'SomeProject',
51
+ base: '/SomeProject/', // in case github page that have prefix
52
+ srcDir: 'src',
53
+ versioning: {
54
+ latestVersion: '1.0.0',
55
+ }
56
+ });
57
+ ```
58
+
59
+ 3. Version Switcher Component
60
+
61
+ To use a custom version switcher component:
62
+
63
+ 1. Import and register it in your theme config:
64
+
65
+ ```ts
66
+ /**
67
+ * Import will remove at compile time
68
+ */
69
+
70
+ import type { VNode } from '@vue/runtime-core';
71
+ import type { Awaitable, Theme } from 'vitepress';
72
+
73
+ /**
74
+ * Styles
75
+ */
76
+
77
+ import './style.css';
78
+
79
+ /**
80
+ * Imports
81
+ */
82
+
83
+ import { h } from 'vue';
84
+ import DefaultTheme from 'vitepress/theme';
85
+ import VersionSwitcher from '@viteplus/versions/components/version-switcher.component.vue';
86
+
87
+ export default {
88
+ extends: DefaultTheme,
89
+ Layout: (): VNode => {
90
+ return h(DefaultTheme.Layout, null, {
91
+ });
92
+ },
93
+ enhanceApp({ app }): Awaitable<void> {
94
+ app.component('VersionSwitcher', VersionSwitcher);
95
+ }
96
+ } satisfies Theme;
97
+ ```
98
+
99
+ 2. Add it to your navbar:
100
+
101
+ ```ts
102
+ themeConfig: {
103
+ versionSwitcher: false, // hide default switcher
104
+ nav: [
105
+ ...,
106
+ {
107
+ component: 'VersionSwitcher',
108
+ },
109
+ ]
110
+ }
111
+ ```
112
+
113
+ ## Troubleshooting
114
+ 1. Sidebar Cannot Be an Array
115
+
116
+ ```ts
117
+ // ❌ Incorrect
118
+ sidebar: [
119
+ { text: '1.0.0', link: '/' },
120
+ ]
121
+
122
+ // ✅ Correct
123
+ sidebar: {
124
+ '/': [
125
+ { text: '1.0.0', link: '/' },
126
+ ]
127
+ }
128
+ ```
129
+
130
+ ## Acknowledgments
131
+
132
+ I would like to express my gratitude to those who inspired and supported this project:
133
+ - `@IMB11`, for the original vitepress-versioning-plugin
134
+
135
+
136
+ ## Documentation
137
+
138
+ For complete API documentation, examples, and guides, visit: [Documentation](https://vitepulse.github.io/versions/)
139
+
140
+ ## Compatibility
141
+
142
+ - Node.js 20+
143
+ - All modern browsers (via bundlers)
144
+ - TypeScript 4.5+
145
+ -
146
+ ## Contributing
147
+
148
+ Contributions are welcome!\
149
+ Please see our [Contributing Guide](CONTRIBUTING.md) for details.
150
+
151
+ ## License
152
+
153
+ This project is licensed under the Mozilla Public License 2.0 see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,201 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * Imports
4
+ */
5
+
6
+ import { computed, ref } from 'vue';
7
+ import { useData, useRouter } from 'vitepress';
8
+
9
+ /**
10
+ * Imports from VitePress
11
+ */
12
+
13
+ import VPFlyout from 'vitepress/dist/client/theme-default/components/VPFlyout.vue';
14
+ import VPMenuLink from 'vitepress/dist/client/theme-default/components/VPMenuLink.vue';
15
+
16
+ interface VersioningPlugin {
17
+ versions: Array<string>,
18
+ latestVersion: string
19
+ }
20
+
21
+ const props = defineProps<{
22
+ versioningPlugin: VersioningPlugin
23
+ screenMenu?: boolean
24
+ }>()
25
+
26
+ const router = useRouter()
27
+ const { site } = useData()
28
+
29
+ // Optimize version detection using find() instead of for loop
30
+ const currentVersion = computed(() => {
31
+ const basePath = site.value.base
32
+ const { versions, latestVersion } = props.versioningPlugin
33
+
34
+ // Find the first version that matches the current path
35
+ const matchedVersion = versions.find(version =>
36
+ router.route.path.startsWith(`${ basePath }${ version }/`)
37
+ )
38
+
39
+ return matchedVersion || latestVersion
40
+ })
41
+
42
+ // Create a reusable menu item generator to DRY up template
43
+ const createVersionMenuItem = (version: string) => ({
44
+ text: version,
45
+ link: version === props.versioningPlugin.latestVersion ? '/' : `/${ version }/`
46
+ })
47
+
48
+ const isOpen = ref(false)
49
+ const toggle = () => {
50
+ isOpen.value = !isOpen.value
51
+ }
52
+ </script>
53
+
54
+ <template>
55
+ <!-- Desktop version flyout -->
56
+ <VPFlyout
57
+ v-if="!screenMenu"
58
+ class="VPVersionSwitcher"
59
+ icon="vpi-versioning"
60
+ :button="currentVersion"
61
+ label="Switch Version"
62
+ >
63
+ <div class="items">
64
+ <!-- Only show latest version link if we're not already on latest -->
65
+ <VPMenuLink
66
+ v-if="currentVersion !== versioningPlugin.latestVersion"
67
+ :item="createVersionMenuItem(versioningPlugin.latestVersion)"
68
+ />
69
+ <!-- Show all version links except current version -->
70
+ <template v-for="version in versioningPlugin.versions" :key="version">
71
+ <VPMenuLink
72
+ v-if="currentVersion !== version"
73
+ :item="createVersionMenuItem(version)"
74
+ />
75
+ </template>
76
+ </div>
77
+ </VPFlyout>
78
+
79
+ <!-- Mobile version dropdown -->
80
+ <div v-else class="VPScreenVersionSwitcher" :class="{ open: isOpen }">
81
+ <button
82
+ class="button"
83
+ aria-controls="navbar-group-version"
84
+ :aria-expanded="isOpen"
85
+ @click="toggle"
86
+ >
87
+ <span class="button-text">
88
+ <span class="vpi-versioning icon"/>Switch Version
89
+ </span>
90
+ <span class="vpi-plus button-icon"/>
91
+ </button>
92
+
93
+ <div id="navbar-group-version" class="items">
94
+ <!-- Always show latest version link -->
95
+ <VPMenuLink :item="createVersionMenuItem(versioningPlugin.latestVersion)"/>
96
+ <!-- Show all version links -->
97
+ <VPMenuLink
98
+ v-for="version in versioningPlugin.versions"
99
+ :key="version"
100
+ :item="createVersionMenuItem(version)"
101
+ />
102
+ </div>
103
+ </div>
104
+ </template>
105
+
106
+ <style>
107
+ /* Versioning icon styling */
108
+ .vpi-versioning.option-icon {
109
+ margin-right: 2px !important;
110
+ }
111
+
112
+ .vpi-versioning {
113
+ --icon: url("data:image/svg+xml;charset=utf-8;base64,PHN2ZyB3aWR0aD0iNjRweCIgaGVpZ2h0PSI2NHB4IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHN0cm9rZS13aWR0aD0iMi4yIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGNvbG9yPSIjMDAwMDAwIj48cGF0aCBkPSJNMTcgN0MxOC4xMDQ2IDcgMTkgNi4xMDQ1NyAxOSA1QzE5IDMuODk1NDMgMTguMTA0NiAzIDE3IDNDMTUuODk1NCAzIDE1IDMuODk1NDMgMTUgNUMxNSA2LjEwNDU3IDE1Ljg5NTQgNyAxNyA3WiIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2Utd2lkdGg9IjIuMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48L3BhdGg+PHBhdGggZD0iTTcgN0M4LjEwNDU3IDcgOSA2LjEwNDU3IDkgNUM5IDMuODk1NDMgOC4xMDQ1NyAzIDcgM0M1Ljg5NTQzIDMgNSAzLjg5NTQzIDUgNUM1IDYuMTA0NTcgNS44OTU0MyA3IDcgN1oiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLXdpZHRoPSIyLjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PC9wYXRoPjxwYXRoIGQ9Ik03IDIxQzguMTA0NTcgMjEgOSAyMC4xMDQ2IDkgMTlDOSAxNy44OTU0IDguMTA0NTcgMTcgNyAxN0M1Ljg5NTQzIDE3IDUgMTcuODk1NCA1IDE5QzUgMjAuMTA0NiA1Ljg5NTQzIDIxIDcgMjFaIiBzdHJva2U9IiMwMDAwMDAiIHN0cm9rZS13aWR0aD0iMi4yIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjwvcGF0aD48cGF0aCBkPSJNNyA3VjE3IiBzdHJva2U9IiMwMDAwMDAiIHN0cm9rZS13aWR0aD0iMi4yIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjwvcGF0aD48cGF0aCBkPSJNMTcgN1Y4QzE3IDEwLjUgMTUgMTEgMTUgMTFMOSAxM0M5IDEzIDcgMTMuNSA3IDE2VjE3IiBzdHJva2U9IiMwMDAwMDAiIHN0cm9rZS13aWR0aD0iMi4yIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjwvcGF0aD48L3N2Zz4=")
114
+ }
115
+ </style>
116
+
117
+ <style scoped>
118
+ /* Component styling with minor optimizations */
119
+ .VPVersionSwitcher {
120
+ display: flex;
121
+ align-items: center;
122
+ }
123
+
124
+ .icon {
125
+ padding: 8px;
126
+ }
127
+
128
+ .title {
129
+ padding: 0 24px 0 12px;
130
+ line-height: 32px;
131
+ font-size: 14px;
132
+ font-weight: 700;
133
+ color: var(--vp-c-text-1);
134
+ }
135
+
136
+ /* Mobile version switcher styles */
137
+ .VPScreenVersionSwitcher {
138
+ border-bottom: 1px solid var(--vp-c-divider);
139
+ height: 48px;
140
+ overflow: hidden;
141
+ transition: border-color 0.5s;
142
+ }
143
+
144
+ .VPScreenVersionSwitcher .items {
145
+ visibility: hidden;
146
+ }
147
+
148
+ .VPScreenVersionSwitcher.open {
149
+ padding-bottom: 10px;
150
+ height: auto;
151
+ }
152
+
153
+ .VPScreenVersionSwitcher.open .items {
154
+ visibility: visible;
155
+ }
156
+
157
+ .VPScreenVersionSwitcher.open .button {
158
+ padding-bottom: 6px;
159
+ color: var(--vp-c-brand-1);
160
+ }
161
+
162
+ .VPScreenVersionSwitcher.open .button-icon {
163
+ /*rtl:ignore*/
164
+ transform: rotate(45deg);
165
+ }
166
+
167
+ .VPScreenVersionSwitcher button .icon {
168
+ margin-right: 8px;
169
+ }
170
+
171
+ .button {
172
+ display: flex;
173
+ justify-content: space-between;
174
+ align-items: center;
175
+ padding: 12px 4px 11px 0;
176
+ width: 100%;
177
+ line-height: 24px;
178
+ font-size: 14px;
179
+ font-weight: 500;
180
+ color: var(--vp-c-text-1);
181
+ transition: color 0.25s;
182
+ }
183
+
184
+ .button:hover {
185
+ color: var(--vp-c-brand-1);
186
+ }
187
+
188
+ .button-icon {
189
+ transition: transform 0.25s;
190
+ }
191
+
192
+ /* Group styling */
193
+ .group:first-child {
194
+ padding-top: 0;
195
+ }
196
+
197
+ .group + .group,
198
+ .group + .item {
199
+ padding-top: 4px;
200
+ }
201
+ </style>
@@ -0,0 +1,413 @@
1
+
2
+ /**
3
+ * This file was automatically generated by xBuild.
4
+ * DO NOT EDIT MANUALLY.
5
+ */
6
+ import type { UserConfig } from 'vitepress';
7
+ import type { DefaultTheme, UserConfig } from 'vitepress';
8
+ import type { DefaultTheme } from 'vitepress';
9
+
10
+ /**
11
+ * Import will remove at compile time
12
+ */
13
+ /**
14
+ * Exports
15
+ */
16
+ /**
17
+ * Defines a versioned configuration for a VitePress project.
18
+ *
19
+ * This function sets up the necessary folder structure for versioned documentation,
20
+ * merges default configuration values with the provided config, and initializes
21
+ * theme and routing for versioned documentation.
22
+ *
23
+ * @template T - Type extending {@link VersionThemeInterface}, used for theme configuration.
24
+ *
25
+ * @param config - The user-defined configuration object.
26
+ * @returns UserConfig - The finalized configuration object ready for VitePress.
27
+ *
28
+ * @remarks
29
+ * The function performs the following steps:
30
+ * 1. Resolves the absolute paths for the project root, documentation source folder, and versions folder.
31
+ * 2. Creates the `versions` folder if it doesn't exist and adds a `.gitkeep` file.
32
+ * 3. Reads all directories inside the `versions` folder to determine available versions.
33
+ * 4. Merges user-provided versioning configuration with the default values.
34
+ * 5. Initializes theme settings via {@link themeConfig}.
35
+ * 6. Initializes version-based routes via {@link versionRoutes}.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { defineVersionedConfig } from './config';
40
+ *
41
+ * export default defineVersionedConfig({
42
+ * root: '.',
43
+ * srcDir: 'docs',
44
+ * versioning: { enabled: true },
45
+ * theme: { colorMode: 'dark' }
46
+ * });
47
+ * ```
48
+ *
49
+ * @since 1.0.0
50
+ */
51
+ export declare function defineVersionedConfig<T extends VersionThemeInterface = VersionThemeInterface>(config: ConfigInterface<T>): UserConfig<T>;
52
+
53
+ /**
54
+ * Import will remove at compile time
55
+ */
56
+ export interface SidebarItemInterface extends DefaultTheme.SidebarItem {
57
+ skipVersioning?: boolean;
58
+ }
59
+ export interface SidebarInterface {
60
+ [path: string]: Array<SidebarItemInterface> | {
61
+ items: Array<SidebarItemInterface>;
62
+ base: string;
63
+ };
64
+ }
65
+ export interface RewritesOptionsInterface {
66
+ localePrefix?: string;
67
+ rewriteProcessor?: (inputFilePath: string, version: string) => string;
68
+ localeRewriteProcessor?: (inputFilePath: string, version: string, locale: string) => string;
69
+ }
70
+ export interface VersionThemeInterface extends DefaultTheme.Config {
71
+ sidebar?: SidebarInterface;
72
+ versionSwitcher: false | {
73
+ text?: string;
74
+ includeLatestVersion?: boolean;
75
+ };
76
+ }
77
+ export interface SidebarOptionsInterface {
78
+ processSidebarURLs?: boolean;
79
+ sidebarPathResolver?: (version: string) => string;
80
+ sidebarUrlProcessor?: (url: string, version: string) => string;
81
+ sidebarContentProcessor?: (sidebar: DefaultTheme.SidebarMulti) => DefaultTheme.SidebarMulti;
82
+ }
83
+ export interface ConfigInterface<T extends VersionThemeInterface = VersionThemeInterface> extends UserConfig<T> {
84
+ root: string;
85
+ versioning: {
86
+ rewrites?: RewritesOptionsInterface | false;
87
+ latestVersion: string | undefined;
88
+ sidebarOptions?: SidebarOptionsInterface | false;
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Import will remove at compile time
94
+ */
95
+ /**
96
+ * Configures the VitePress theme for versioned documentation.
97
+ *
98
+ * This function applies versioning to the theme, including the version switcher,
99
+ * navigation, and sidebar, for both the default locale and any additional locales.
100
+ *
101
+ * @template T - Type extending {@link VersionThemeInterface}, used for theme configuration.
102
+ *
103
+ * @param config - The configuration object containing theme and versioning settings.
104
+ * @param versions - An array of version strings detected from the `versions` folder.
105
+ * @param rootPath - The absolute path to the project root.
106
+ *
107
+ * @remarks
108
+ * For each theme configuration (default + locales):
109
+ * 1. Initializes the version switcher via {@link versionSwitcher} using `versions` and `config.versioning.latestVersion`.
110
+ * 2. Updates the navigation menu using {@link versioningNav}.
111
+ * 3. Validates the sidebar configuration:
112
+ * - If the sidebar is an array, logs an error recommending a `DefaultTheme.MultiSidebar` object instead.
113
+ * - Otherwise, merges versioned sidebar options via {@link versioningSidebar}.
114
+ *
115
+ * The `themeConfig` function ensures all theme-related versioning features are applied consistently
116
+ * across locales and prevents invalid sidebar structures.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * import { themeConfig } from './theme';
121
+ *
122
+ * themeConfig(config, ['1.0.0', '2.0.0'], '/path/to/project');
123
+ * ```
124
+ *
125
+ * @since 1.0.0
126
+ */
127
+ declare function themeConfig<T extends VersionThemeInterface>(config: ConfigInterface<T>, versions: Array<string>, rootPath: string): void;
128
+
129
+ /**
130
+ * Import will remove at compile time
131
+ */
132
+ /**
133
+ * Recursively adds versioning information to a navigation item.
134
+ *
135
+ * @param navItem - A navigation item to which versioning information will be added.
136
+ * @param versions - An array of available documentation versions.
137
+ * @param latestVersion - The latest version string to mark as the default/latest.
138
+ *
139
+ * @returns The updated navigation item with versioning plugin props applied.
140
+ *
141
+ * @remarks
142
+ * - If the `navItem` has nested `items`, the function recursively updates them.
143
+ * - If the `navItem` has a `component` property, a `versioningPlugin` prop is added
144
+ * containing `versions` and `latestVersion`.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * import { addVersioningToNavItem } from './nav';
149
+ *
150
+ * const navItemWithVersioning = addVersioningToNavItem(navItem, ['1.0.0', '2.0.0'], '2.0.0');
151
+ * ```
152
+ *
153
+ * @since 1.0.0
154
+ */
155
+ declare function addVersioningToNavItem(navItem: DefaultTheme.NavItem, versions: Array<string>, latestVersion: string): DefaultTheme.NavItem;
156
+ /**
157
+ * Applies versioning to all navigation items in a theme configuration.
158
+ *
159
+ * @param themeConfig - Theme configuration object containing the `nav` array.
160
+ * @param versions - An array of available documentation versions.
161
+ * @param latestVersion - The latest version string to mark as default/latest.
162
+ *
163
+ * @returns void
164
+ *
165
+ * @remarks
166
+ * - Iterates through all `nav` items and applies {@link addVersioningToNavItem}.
167
+ * - Skips processing if `themeConfig.nav` is not an array.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * import { versioningNav } from './nav';
172
+ *
173
+ * versioningNav(themeConfig, ['1.0.0', '2.0.0'], '2.0.0');
174
+ * ```
175
+ *
176
+ * @since 1.0.0
177
+ */
178
+ declare function versioningNav(themeConfig: VersionThemeInterface, versions: Array<string>, latestVersion?: string): void;
179
+
180
+ /**
181
+ * Import will remove at compile time
182
+ */
183
+ /**
184
+ * Adds a version-switching dropdown to the VitePress navigation.
185
+ *
186
+ * @remarks
187
+ * This utility augments the provided {@link VersionThemeInterface | themeConfig}
188
+ * with a `nav` entry that lists available documentation versions.
189
+ *
190
+ * - If `themeConfig.versionSwitcher` is `false`, the function exits without changes.
191
+ * - If `themeConfig.versionSwitcher` is an object, missing keys are filled using {@link assignMissingDeep}.
192
+ *
193
+ * @param themeConfig - The mutable VitePress theme configuration that will receive the version switcher.
194
+ * @param versions - Array of version strings (e.g., `['v1', 'v2']`) to display as selectable links.
195
+ * @param latestVersion - Optional label for the latest version entry. Defaults to `'Latest'`.
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * versionSwitcher(themeConfig, ['v1', 'v2']);
200
+ * // Adds a nav dropdown titled "Switch Version" with entries:
201
+ * // → Latest
202
+ * // → v1
203
+ * // → v2
204
+ * ```
205
+ *
206
+ * @since 1.0.0
207
+ */
208
+ declare function versionSwitcher(themeConfig: VersionThemeInterface, versions: Array<string>, latestVersion?: string): void;
209
+
210
+ /**
211
+ * Recursively assigns missing properties from a source object to a target object.
212
+ *
213
+ * @param target - The target object that will receive missing properties.
214
+ * @param source - The source object providing default properties.
215
+ *
216
+ * @returns The updated target object with missing properties filled from the source.
217
+ *
218
+ * @remarks
219
+ * - Only properties that are `undefined` in the target will be assigned from the source.
220
+ * - If both target and source values are objects, the function recursively merges missing properties.
221
+ * - Does not overwrite existing properties in the target.
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * const target = { a: 1, b: { x: 10 } };
226
+ * const source = { b: { x: 20, y: 30 }, c: 3 };
227
+ *
228
+ * assignMissingDeep(target, source);
229
+ * // Result: { a: 1, b: { x: 10, y: 30 }, c: 3 }
230
+ * ```
231
+ *
232
+ * @since 1.0.0
233
+ */
234
+ declare function assignMissingDeep(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown>;
235
+
236
+ /**
237
+ * Import will remove at compile time
238
+ */
239
+ /**
240
+ * Recursively replaces sidebar links for a given version using a custom URL processor.
241
+ *
242
+ * @param sidebarOptions - Sidebar options containing the `sidebarUrlProcessor` function.
243
+ * @param version - The current documentation version to apply in the links.
244
+ * @param sidebar - An array of sidebar items to process.
245
+ *
246
+ * @returns A new array of sidebar items with versioned links applied.
247
+ *
248
+ * @remarks
249
+ * - Skips items marked with `skipVersioning`.
250
+ * - Recursively processes nested items under `items`.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * const updatedSidebar = replaceLinksRecursive(sidebarOptions, '1.0.0', sidebar);
255
+ * ```
256
+ *
257
+ * @since 1.0.0
258
+ */
259
+ declare function replaceLinksRecursive(sidebarOptions: SidebarOptionsInterface, version: string, sidebar: Array<SidebarItemInterface>): Array<SidebarItemInterface>;
260
+ /**
261
+ * Loads a sidebar for a specific version and locale from the filesystem.
262
+ *
263
+ * @param sidebarOptions - Sidebar options including `sidebarPathResolver`.
264
+ * @param version - The current documentation version.
265
+ * @param locale - The locale key ('root' for default locale).
266
+ * @param rootPath - Absolute path to the project root.
267
+ *
268
+ * @returns A `DefaultTheme.Sidebar` object (array or multi-sidebar) with versioned links.
269
+ *
270
+ * @remarks
271
+ * - If the sidebar file does not exist, returns an empty array.
272
+ * - Recursively applies `replaceLinksRecursive` for versioned links.
273
+ * - Supports both single-array sidebars and multi-sidebar objects.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * const sidebar = loadSidebar(sidebarOptions, '1.0.0', 'en', '/path/to/project');
278
+ * ```
279
+ *
280
+ * @since 1.0.0
281
+ */
282
+ declare function loadSidebar(sidebarOptions: SidebarOptionsInterface, version: string, locale: string, rootPath: string): DefaultTheme.Sidebar;
283
+ /**
284
+ * Generates versioned sidebars for all versions and locales.
285
+ *
286
+ * @param config - The configuration object containing versioning and sidebar settings.
287
+ * @param versions - An array of available documentation versions.
288
+ * @param locales - An array of locale keys including `'root'`. If empty, `'root'` will be used.
289
+ * @param rootPath - Absolute path to the project root.
290
+ *
291
+ * @returns A `DefaultTheme.SidebarMulti` object mapping versioned paths to sidebars.
292
+ *
293
+ * @remarks
294
+ * - Iterates through all versions and locales to load and process sidebars.
295
+ * - Uses {@link loadSidebar} to read the sidebar JSON and convert links to versioned URLs.
296
+ * - Handles both single-array sidebars and multi-sidebar objects.
297
+ * - All sidebar links are converted to **absolute paths** relative to the version root to prevent duplicated folder segments in nested paths.
298
+ * - If `config.versioning.sidebarOptions` is `false`, returns an empty sidebar mapping.
299
+ * - Defaults to `'root'` locale if no locales are specified.
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * const sidebars = versioningSidebar(config, ['1.0.0', '2.0.0'], ['root', 'en'], '/path/to/project');
304
+ * // sidebars['/1.0.0/'] → sidebar for root locale, version 1.0.0
305
+ * // sidebars['/en/1.0.0/'] → sidebar for 'en' locale, version 1.0.0
306
+ * ```
307
+ *
308
+ * @since 1.0.0
309
+ */
310
+ declare function versioningSidebar(config: ConfigInterface, versions: Array<string>, locales: Array<string>, rootPath: string): DefaultTheme.SidebarMulti;
311
+
312
+ /**
313
+ * Import will remove at compile time
314
+ */
315
+ /**
316
+ * Default versioning configuration.
317
+ *
318
+ * @remarks
319
+ * This object provides the default settings for versioned documentation,
320
+ * including the latest version, URL rewrites, and sidebar options.
321
+ *
322
+ * - `latestVersion`: Initially `undefined`; can be set to mark the most recent version.
323
+ * - `rewrites`: Functions and prefix used to generate versioned URLs for documents.
324
+ * - `localePrefix`: Prefix for locale-specific URLs.
325
+ * - `rewriteProcessor`: Processes file paths for versioned URLs.
326
+ * - `localeRewriteProcessor`: Processes locale-specific versioned URLs.
327
+ * - `sidebarOptions`: Configuration for generating versioned sidebars.
328
+ * - `processSidebarURLs`: Whether sidebar URLs should be processed.
329
+ * - `sidebarPathResolver`: Resolves the path to the sidebar JSON file for a given version.
330
+ * - `sidebarUrlProcessor`: Processes sidebar item URLs to include the version prefix.
331
+ *
332
+ * @example
333
+ * ```ts
334
+ * import { defaultConfig } from './default.constant';
335
+ *
336
+ * console.log(defaultConfig.sidebarOptions.sidebarPathResolver('1.0.0'));
337
+ * // Output: ".vitepress/sidebars/versioned/1.0.0.json"
338
+ *
339
+ * console.log(defaultConfig.rewrites.rewriteProcessor('versions/guide.md'));
340
+ * // Output: "guide.md"
341
+ * ```
342
+ *
343
+ * @since 1.0.0
344
+ */
345
+ declare const defaultConfig: Required<ConfigInterface['versioning']>;
346
+
347
+ /**
348
+ * Import will remove at compile time
349
+ */
350
+ /**
351
+ * Recursively collects all file paths from a directory, skipping locale folders.
352
+ *
353
+ * @param dirPath - The directory path to scan.
354
+ * @param locales - An array of locale folder names to skip.
355
+ *
356
+ * @returns An array of file paths found recursively under `dirPath`.
357
+ *
358
+ * @remarks
359
+ * - Skips any directories that match names in the `locales` array.
360
+ * - Uses POSIX-style paths for consistency across platforms.
361
+ *
362
+ * @example
363
+ * ```ts
364
+ * const files = collectFilesRecursively('/docs/versions/1.0.0', ['en', 'fr']);
365
+ * ```
366
+ *
367
+ * @since 1.0.0
368
+ */
369
+ declare function collectFilesRecursively(dirPath: string, locales: Array<string>): Array<string>;
370
+ /**
371
+ * Generates versioned URL mappings for documentation files.
372
+ *
373
+ * @param rewrites - Rewrites options or `false` to disable URL generation.
374
+ * @param docPath - The root path to the documentation folder.
375
+ * @param versions - An array of documentation versions.
376
+ * @param locales - Optional array of locales to include in URL generation.
377
+ *
378
+ * @returns A record mapping original file paths to their versioned URLs.
379
+ *
380
+ * @remarks
381
+ * - Iterates through each version folder and collects all files.
382
+ * - Applies `rewriteProcessor` and optionally `localeRewriteProcessor` to generate versioned paths.
383
+ * - Locale files are prefixed with `rewrites.localePrefix` and cleaned up for the final path.
384
+ *
385
+ * @example
386
+ * ```ts
387
+ * const urls = generateVersionedUrls(rewrites, '/docs', ['1.0.0', '2.0.0'], ['en', 'fr']);
388
+ * ```
389
+ *
390
+ * @since 1.0.0
391
+ */
392
+ declare function generateVersionedUrls(rewrites: RewritesOptionsInterface | false, docPath: string, versions: Array<string>, locales?: Array<string>): Record<string, string>;
393
+ /**
394
+ * Updates the configuration object with versioned routes for documentation.
395
+ *
396
+ * @param config - The configuration object to update with versioned URLs.
397
+ * @param versions - An array of documentation versions.
398
+ * @param docPath - The root path to the documentation folder.
399
+ *
400
+ * @returns void
401
+ *
402
+ * @remarks
403
+ * - Calls {@link generateVersionedUrls} to generate mappings for all versions and locales.
404
+ * - Merges the generated URLs into `config.rewrites`.
405
+ *
406
+ * @example
407
+ * ```ts
408
+ * versionRoutes(config, ['1.0.0', '2.0.0'], '/docs');
409
+ * ```
410
+ *
411
+ * @since 1.0.0
412
+ */
413
+ declare function versionRoutes(config: ConfigInterface, versions: Array<string>, docPath: string): void;
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ var R=Object.defineProperty;var o=(e,i)=>R(e,"name",{value:i,configurable:!0});import{join as d}from"path";function v(e,i,t){if("items"in e&&e.items&&(e.items=e.items.map(r=>v(r,i,t))),"component"in e&&e.component){let r=e;r.props??={},r.props.versioningPlugin={versions:i,latestVersion:t}}return e}o(v,"addVersioningToNavItem");function b(e,i,t=""){Array.isArray(e.nav)&&(e.nav=e.nav.map(r=>v(r,i,t)))}o(b,"versioningNav");import{xterm as T}from"@remotex-labs/xansi/xterm.component";function u(e,i){for(let t in i){if(t==="__proto__"||t==="constructor"||t==="prototype")continue;let r=i[t],n=e[t];n===void 0?e[t]=r:r&&typeof r=="object"&&n&&typeof n=="object"&&u(n,r)}return e}o(u,"assignMissingDeep");function S(e,i,t="Latest"){if(e.versionSwitcher===!1)return;let r={text:"Switch Version",includeLatestVersion:!0};e.versionSwitcher?u(e.versionSwitcher,r):e.versionSwitcher={...r};let{text:n,includeLatestVersion:a}=e.versionSwitcher,s=[];a&&s.push({text:t==="Latest"?t:`${t} (latest)`,link:"/"});for(let f of i)s.push({text:f,link:`/${f}/`});e.nav??=[],e.nav.push({text:n,items:s})}o(S,"versionSwitcher");import{resolve as k}from"path";import{existsSync as V,readFileSync as $}from"fs";function g(e,i,t){return t.map(r=>(r.skipVersioning||(r.link&&(r.link=e.sidebarUrlProcessor(r.link,i)),r.items&&(r.items=g(e,i,r.items))),r))}o(g,"replaceLinksRecursive");function C(e,i,t,r){let n=k(r,e.sidebarPathResolver(i+(t==="root"?"":`-${t}`)));if(!V(n))return[];let a=JSON.parse($(n,"utf-8"));if(Array.isArray(a))return g(e,(t==="root"?"":`${t}/`)+i,a);let s=a;return Object.keys(s).forEach(f=>{Array.isArray(s[f])&&(s[f]=g(e,(t==="root"?"":`${t}/`)+i,s[f]))}),s}o(C,"loadSidebar");function I(e,i,t,r){let n={},a=e.versioning.sidebarOptions;if(a===!1)return n;for(let s of i)for(let f of t){let p=C(a,s,f,r);Array.isArray(p)?n[(f==="root"?"":`/${f}`)+`/${s}/`]=p:Object.keys(p).forEach(c=>{n[(f==="root"?"":`/${f}`)+`/${s}${c}`]=p[c]})}return n}o(I,"versioningSidebar");function x(e,i,t){let r=[e.themeConfig,...Object.values(e.locales??{}).map(n=>n.themeConfig)];for(let n of r)n&&(S(n,i,e.versioning.latestVersion),b(n,i,e.versioning.latestVersion),Array.isArray(n.sidebar)?console.error(`${T.redBright("[ viteplus ]")} - The sidebar cannot be an array.
2
+ `+T.dim("Please use a DefaultTheme.MultiSidebar object where the root ('/') is your array.")):n.sidebar={...n.sidebar,...I(e,i,Object.keys(e.locales??{}),t)})}o(x,"themeConfig");var A={latestVersion:void 0,rewrites:{localePrefix:"",rewriteProcessor:o(e=>e.replace("versions/",""),"rewriteProcessor"),localeRewriteProcessor(e,i,t){return`${t}/`+e.replace("versions/","").replace(`${t}/`,"")}},sidebarOptions:{processSidebarURLs:!0,sidebarPathResolver:o(e=>`.vitepress/sidebars/versioned/${e}.json`,"sidebarPathResolver"),sidebarUrlProcessor:o((e,i)=>`/${i}${e}`,"sidebarUrlProcessor")}};import{posix as l}from"path";import{existsSync as j,readdirSync as O}from"fs";function y(e,i){let t=[];for(let r of O(e,{withFileTypes:!0})){let n=l.join(e,r.name);if(r.isDirectory()){if(i.includes(r.name))continue;t.push(...y(n,i))}else t.push(n)}return t}o(y,"collectFilesRecursively");function N(e,i,t,r=[]){let n={};if(e===!1)return n;let a=l.join(i,"versions");for(let s of t){let f=l.join(a,s),p=y(f,r);for(let c of p){let m=c.replace(a,"versions");n[m]=e.rewriteProcessor(m,s)}for(let c of r){let m=l.join(a,s,e.localePrefix,c);if(!j(m))continue;let w=y(m,r);for(let P of w){let h=P.replace(a,"versions");n[h]=e.localeRewriteProcessor?.(h,s,c).replace(`/${e.localePrefix}`,"")??""}}}return n}o(N,"generateVersionedUrls");function D(e,i,t){e.rewrites={...e.rewrites,...N(e.versioning.rewrites,t,i,Object.keys(e.locales??{}))}}o(D,"versionRoutes");import{existsSync as L,mkdirSync as M,readdirSync as F,writeFileSync as U}from"fs";function ye(e){let i=d(process.cwd(),e.root),t=d(i,e.srcDir??""),r=d(t,"versions");L(r)||(M(r),U(d(r,".gitkeep"),""));let n=F(r,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>a.name);return e.versioning=u(e.versioning,A),x(e,n,i),D(e,n,t),e}o(ye,"defineVersionedConfig");export{ye as defineVersionedConfig};
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,8 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/components/nav.component.ts", "../src/providers/theme.provider.ts", "../src/components/object.component.ts", "../src/components/switcher.component.ts", "../src/components/sidebar.component.ts", "../src/constants/default.constant.ts", "../src/components/routes.component.ts"],
4
+ "sourceRoot": "https://github.com/viteplus/versions/tree/v1.0.0/",
5
+ "sourcesContent": ["/**\n * Import will remove at compile time\n */\n\nimport type { Dirent } from 'fs';\nimport type { UserConfig } from 'vitepress';\nimport type { ConfigInterface, VersionThemeInterface } from '@interfaces/config.interface';\n\n/**\n * Imports\n */\n\nimport { join } from 'path';\nimport { themeConfig } from '@providers/theme.provider';\nimport { defaultConfig } from './constants/default.constant';\nimport { versionRoutes } from '@components/routes.component';\nimport { assignMissingDeep } from '@components/object.component';\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'fs';\n\n/**\n * Exports\n */\n\nexport * from './interfaces/config.interface';\n\n/**\n * Defines a versioned configuration for a VitePress project.\n *\n * This function sets up the necessary folder structure for versioned documentation,\n * merges default configuration values with the provided config, and initializes\n * theme and routing for versioned documentation.\n *\n * @template T - Type extending {@link VersionThemeInterface}, used for theme configuration.\n *\n * @param config - The user-defined configuration object.\n * @returns UserConfig - The finalized configuration object ready for VitePress.\n *\n * @remarks\n * The function performs the following steps:\n * 1. Resolves the absolute paths for the project root, documentation source folder, and versions folder.\n * 2. Creates the `versions` folder if it doesn't exist and adds a `.gitkeep` file.\n * 3. Reads all directories inside the `versions` folder to determine available versions.\n * 4. Merges user-provided versioning configuration with the default values.\n * 5. Initializes theme settings via {@link themeConfig}.\n * 6. Initializes version-based routes via {@link versionRoutes}.\n *\n * @example\n * ```ts\n * import { defineVersionedConfig } from './config';\n *\n * export default defineVersionedConfig({\n * root: '.',\n * srcDir: 'docs',\n * versioning: { enabled: true },\n * theme: { colorMode: 'dark' }\n * });\n * ```\n *\n * @since 1.0.0\n */\n\nexport function defineVersionedConfig<T extends VersionThemeInterface = VersionThemeInterface>(config: ConfigInterface<T>): UserConfig<T> {\n const rootPath = join(process.cwd(), config.root);\n const docsPath = join(rootPath, config.srcDir ?? '');\n const versionsFolder = join(docsPath, 'versions');\n\n if (!existsSync(versionsFolder)) {\n mkdirSync(versionsFolder);\n writeFileSync(join(versionsFolder, '.gitkeep'), '');\n }\n\n const versions: string[] = readdirSync(versionsFolder, { withFileTypes: true })\n .filter((entry: Dirent) => entry.isDirectory())\n .map((entry: Dirent) => entry.name);\n\n config.versioning = <ConfigInterface['versioning']> assignMissingDeep(config.versioning, defaultConfig);\n themeConfig(config, versions, rootPath);\n versionRoutes(config, versions, docsPath);\n\n return config;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { DefaultTheme } from 'vitepress';\nimport type { VersionThemeInterface } from '@interfaces/config.interface';\n\n/**\n * Recursively adds versioning information to a navigation item.\n *\n * @param navItem - A navigation item to which versioning information will be added.\n * @param versions - An array of available documentation versions.\n * @param latestVersion - The latest version string to mark as the default/latest.\n *\n * @returns The updated navigation item with versioning plugin props applied.\n *\n * @remarks\n * - If the `navItem` has nested `items`, the function recursively updates them.\n * - If the `navItem` has a `component` property, a `versioningPlugin` prop is added\n * containing `versions` and `latestVersion`.\n *\n * @example\n * ```ts\n * import { addVersioningToNavItem } from './nav';\n *\n * const navItemWithVersioning = addVersioningToNavItem(navItem, ['1.0.0', '2.0.0'], '2.0.0');\n * ```\n *\n * @since 1.0.0\n */\n\nexport function addVersioningToNavItem(navItem: DefaultTheme.NavItem, versions: Array<string>, latestVersion: string): DefaultTheme.NavItem {\n if ('items' in navItem && navItem.items) {\n navItem.items = navItem.items.map((item) =>\n addVersioningToNavItem(item, versions, latestVersion)\n ) as Array<DefaultTheme.NavItemWithLink | DefaultTheme.NavItemChildren>;\n }\n\n if ('component' in navItem && navItem.component) {\n const componentItem = navItem as DefaultTheme.NavItem & {\n component: string;\n props?: Record<string, unknown>;\n };\n\n componentItem.props ??= {};\n componentItem.props.versioningPlugin = {\n versions,\n latestVersion\n };\n }\n\n return navItem;\n}\n\n/**\n * Applies versioning to all navigation items in a theme configuration.\n *\n * @param themeConfig - Theme configuration object containing the `nav` array.\n * @param versions - An array of available documentation versions.\n * @param latestVersion - The latest version string to mark as default/latest.\n *\n * @returns void\n *\n * @remarks\n * - Iterates through all `nav` items and applies {@link addVersioningToNavItem}.\n * - Skips processing if `themeConfig.nav` is not an array.\n *\n * @example\n * ```ts\n * import { versioningNav } from './nav';\n *\n * versioningNav(themeConfig, ['1.0.0', '2.0.0'], '2.0.0');\n * ```\n *\n * @since 1.0.0\n */\n\nexport function versioningNav(themeConfig: VersionThemeInterface, versions: Array<string>, latestVersion: string = ''): void {\n if (!Array.isArray(themeConfig.nav)) return;\n\n themeConfig.nav = themeConfig.nav.map((item) =>\n addVersioningToNavItem(item, versions, latestVersion)\n );\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConfigInterface, VersionThemeInterface } from '@interfaces/config.interface';\n\n/**\n * Imports\n */\n\nimport { versioningNav } from '@components/nav.component';\nimport { xterm } from '@remotex-labs/xansi/xterm.component';\nimport { versionSwitcher } from '@components/switcher.component';\nimport { versioningSidebar } from '@components/sidebar.component';\n\n/**\n * Configures the VitePress theme for versioned documentation.\n *\n * This function applies versioning to the theme, including the version switcher,\n * navigation, and sidebar, for both the default locale and any additional locales.\n *\n * @template T - Type extending {@link VersionThemeInterface}, used for theme configuration.\n *\n * @param config - The configuration object containing theme and versioning settings.\n * @param versions - An array of version strings detected from the `versions` folder.\n * @param rootPath - The absolute path to the project root.\n *\n * @remarks\n * For each theme configuration (default + locales):\n * 1. Initializes the version switcher via {@link versionSwitcher} using `versions` and `config.versioning.latestVersion`.\n * 2. Updates the navigation menu using {@link versioningNav}.\n * 3. Validates the sidebar configuration:\n * - If the sidebar is an array, logs an error recommending a `DefaultTheme.MultiSidebar` object instead.\n * - Otherwise, merges versioned sidebar options via {@link versioningSidebar}.\n *\n * The `themeConfig` function ensures all theme-related versioning features are applied consistently\n * across locales and prevents invalid sidebar structures.\n *\n * @example\n * ```ts\n * import { themeConfig } from './theme';\n *\n * themeConfig(config, ['1.0.0', '2.0.0'], '/path/to/project');\n * ```\n *\n * @since 1.0.0\n */\n\nexport function themeConfig<T extends VersionThemeInterface>(config: ConfigInterface<T>, versions: Array<string>, rootPath: string): void {\n const themeConfigArray = [\n config.themeConfig, ...Object.values(config.locales ?? {}).map(\n (locale) => locale.themeConfig\n )\n ];\n\n for (const themeConfig of themeConfigArray) {\n if (!themeConfig) continue;\n versionSwitcher(themeConfig, versions, config.versioning.latestVersion);\n versioningNav(themeConfig, versions, config.versioning.latestVersion);\n\n if(Array.isArray(themeConfig.sidebar)) {\n console.error(\n `${ xterm.redBright('[ viteplus ]') } - The sidebar cannot be an array.\\n` +\n xterm.dim('Please use a DefaultTheme.MultiSidebar object where the root (\\'/\\') is your array.')\n );\n } else {\n themeConfig.sidebar = {\n ...themeConfig.sidebar,\n ...versioningSidebar(config, versions, Object.keys(config.locales ?? {}), rootPath)\n };\n }\n }\n}\n", "/**\n * Recursively assigns missing properties from a source object to a target object.\n *\n * @param target - The target object that will receive missing properties.\n * @param source - The source object providing default properties.\n *\n * @returns The updated target object with missing properties filled from the source.\n *\n * @remarks\n * - Only properties that are `undefined` in the target will be assigned from the source.\n * - If both target and source values are objects, the function recursively merges missing properties.\n * - Does not overwrite existing properties in the target.\n *\n * @example\n * ```ts\n * const target = { a: 1, b: { x: 10 } };\n * const source = { b: { x: 20, y: 30 }, c: 3 };\n *\n * assignMissingDeep(target, source);\n * // Result: { a: 1, b: { x: 10, y: 30 }, c: 3 }\n * ```\n *\n * @since 1.0.0\n */\n\nexport function assignMissingDeep(\n target: Record<string, unknown>, source: Record<string, unknown>\n): Record<string, unknown> {\n for (const key in source) {\n // Prevent prototype pollution\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n continue;\n }\n\n const sourceValue = source[key];\n const targetValue = target[key];\n\n if (targetValue === undefined) {\n target[key] = sourceValue;\n } else if (\n sourceValue && typeof sourceValue === 'object' &&\n targetValue && typeof targetValue === 'object'\n ) {\n assignMissingDeep(\n targetValue as Record<string, unknown>,\n sourceValue as Record<string, unknown>\n );\n }\n }\n\n return target;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { DefaultTheme } from 'vitepress';\nimport type { VersionThemeInterface } from '@interfaces/config.interface';\n\n/**\n * Imports\n */\n\nimport { assignMissingDeep } from '@components/object.component';\n\n/**\n * Adds a version-switching dropdown to the VitePress navigation.\n *\n * @remarks\n * This utility augments the provided {@link VersionThemeInterface | themeConfig}\n * with a `nav` entry that lists available documentation versions.\n *\n * - If `themeConfig.versionSwitcher` is `false`, the function exits without changes.\n * - If `themeConfig.versionSwitcher` is an object, missing keys are filled using {@link assignMissingDeep}.\n *\n * @param themeConfig - The mutable VitePress theme configuration that will receive the version switcher.\n * @param versions - Array of version strings (e.g., `['v1', 'v2']`) to display as selectable links.\n * @param latestVersion - Optional label for the latest version entry. Defaults to `'Latest'`.\n *\n * @example\n * ```ts\n * versionSwitcher(themeConfig, ['v1', 'v2']);\n * // Adds a nav dropdown titled \"Switch Version\" with entries:\n * // \u2192 Latest\n * // \u2192 v1\n * // \u2192 v2\n * ```\n *\n * @since 1.0.0\n */\n\nexport function versionSwitcher(themeConfig: VersionThemeInterface, versions: Array<string>, latestVersion: string = 'Latest'): void {\n if (themeConfig.versionSwitcher === false) return;\n const defaults = { text: 'Switch Version', includeLatestVersion: true };\n\n if (!themeConfig.versionSwitcher) {\n themeConfig.versionSwitcher = { ...defaults };\n } else {\n assignMissingDeep(themeConfig.versionSwitcher, defaults);\n }\n\n const { text, includeLatestVersion } = themeConfig.versionSwitcher;\n const items: DefaultTheme.NavItemWithLink[] = [];\n if (includeLatestVersion) {\n items.push({\n text: latestVersion === 'Latest' ? latestVersion : `${ latestVersion } (latest)`,\n link: '/'\n });\n }\n\n for (const version of versions) {\n items.push({ text: version, link: `/${ version }/` });\n }\n\n themeConfig.nav ??= [];\n themeConfig.nav.push({ text, items });\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { DefaultTheme } from 'vitepress';\nimport type { ConfigInterface, SidebarItemInterface, SidebarOptionsInterface } from '@interfaces/config.interface';\n\n/**\n * Imports\n */\n\nimport { resolve } from 'path';\nimport { existsSync, readFileSync } from 'fs';\n\n/**\n * Recursively replaces sidebar links for a given version using a custom URL processor.\n *\n * @param sidebarOptions - Sidebar options containing the `sidebarUrlProcessor` function.\n * @param version - The current documentation version to apply in the links.\n * @param sidebar - An array of sidebar items to process.\n *\n * @returns A new array of sidebar items with versioned links applied.\n *\n * @remarks\n * - Skips items marked with `skipVersioning`.\n * - Recursively processes nested items under `items`.\n *\n * @example\n * ```ts\n * const updatedSidebar = replaceLinksRecursive(sidebarOptions, '1.0.0', sidebar);\n * ```\n *\n * @since 1.0.0\n */\n\nexport function replaceLinksRecursive(\n sidebarOptions: SidebarOptionsInterface, version: string, sidebar: Array<SidebarItemInterface>\n): Array<SidebarItemInterface> {\n return sidebar.map((item) => {\n if (item.skipVersioning) {\n return item;\n }\n\n if (item.link) {\n item.link = sidebarOptions.sidebarUrlProcessor!(item.link, version);\n }\n\n if (item.items) {\n item.items = replaceLinksRecursive(sidebarOptions, version, item.items);\n }\n\n return item;\n });\n}\n\n/**\n * Loads a sidebar for a specific version and locale from the filesystem.\n *\n * @param sidebarOptions - Sidebar options including `sidebarPathResolver`.\n * @param version - The current documentation version.\n * @param locale - The locale key ('root' for default locale).\n * @param rootPath - Absolute path to the project root.\n *\n * @returns A `DefaultTheme.Sidebar` object (array or multi-sidebar) with versioned links.\n *\n * @remarks\n * - If the sidebar file does not exist, returns an empty array.\n * - Recursively applies `replaceLinksRecursive` for versioned links.\n * - Supports both single-array sidebars and multi-sidebar objects.\n *\n * @example\n * ```ts\n * const sidebar = loadSidebar(sidebarOptions, '1.0.0', 'en', '/path/to/project');\n * ```\n *\n * @since 1.0.0\n */\n\nexport function loadSidebar(sidebarOptions: SidebarOptionsInterface, version: string, locale: string, rootPath: string): DefaultTheme.Sidebar {\n const sidebarPath = resolve(\n rootPath,\n sidebarOptions.sidebarPathResolver!(\n version + (locale === 'root' ? '' : `-${ locale }`)\n )\n );\n\n if (!existsSync(sidebarPath)) return [];\n const sidebar = JSON.parse(readFileSync(sidebarPath, 'utf-8'));\n if (Array.isArray(sidebar)) {\n return replaceLinksRecursive(\n sidebarOptions,\n (locale === 'root' ? '' : `${ locale }/`) + version,\n sidebar\n );\n }\n\n const multiSidebar = sidebar as DefaultTheme.SidebarMulti;\n Object.keys(multiSidebar).forEach((key) => {\n if (Array.isArray(multiSidebar[key])) {\n multiSidebar[key] = replaceLinksRecursive(\n sidebarOptions,\n (locale === 'root' ? '' : `${ locale }/`) + version,\n multiSidebar[key] as Array<SidebarItemInterface>\n );\n }\n });\n\n return multiSidebar;\n}\n\n/**\n * Generates versioned sidebars for all versions and locales.\n *\n * @param config - The configuration object containing versioning and sidebar settings.\n * @param versions - An array of available documentation versions.\n * @param locales - An array of locale keys including `'root'`. If empty, `'root'` will be used.\n * @param rootPath - Absolute path to the project root.\n *\n * @returns A `DefaultTheme.SidebarMulti` object mapping versioned paths to sidebars.\n *\n * @remarks\n * - Iterates through all versions and locales to load and process sidebars.\n * - Uses {@link loadSidebar} to read the sidebar JSON and convert links to versioned URLs.\n * - Handles both single-array sidebars and multi-sidebar objects.\n * - All sidebar links are converted to **absolute paths** relative to the version root to prevent duplicated folder segments in nested paths.\n * - If `config.versioning.sidebarOptions` is `false`, returns an empty sidebar mapping.\n * - Defaults to `'root'` locale if no locales are specified.\n *\n * @example\n * ```ts\n * const sidebars = versioningSidebar(config, ['1.0.0', '2.0.0'], ['root', 'en'], '/path/to/project');\n * // sidebars['/1.0.0/'] \u2192 sidebar for root locale, version 1.0.0\n * // sidebars['/en/1.0.0/'] \u2192 sidebar for 'en' locale, version 1.0.0\n * ```\n *\n * @since 1.0.0\n */\n\nexport function versioningSidebar(\n config: ConfigInterface, versions: Array<string>, locales: Array<string>, rootPath: string\n): DefaultTheme.SidebarMulti {\n const versionSidebars: DefaultTheme.SidebarMulti = {};\n const sidebarOptions = config.versioning.sidebarOptions!;\n if (sidebarOptions === false) return versionSidebars;\n\n for (const version of versions) {\n for (const locale of locales) {\n const sidebar = loadSidebar(sidebarOptions, version, locale, rootPath);\n\n if (Array.isArray(sidebar)) {\n versionSidebars[\n (locale === 'root' ? '' : `/${ locale }`) + `/${ version }/`\n ] = sidebar;\n } else {\n Object.keys(sidebar).forEach((key) => {\n versionSidebars[\n (locale === 'root' ? '' : `/${ locale }`) + `/${ version }${ key }`\n ] = (sidebar as DefaultTheme.SidebarMulti)[key];\n });\n }\n }\n }\n\n return versionSidebars;\n}\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConfigInterface } from '@interfaces/config.interface';\n\n/**\n * Default versioning configuration.\n *\n * @remarks\n * This object provides the default settings for versioned documentation,\n * including the latest version, URL rewrites, and sidebar options.\n *\n * - `latestVersion`: Initially `undefined`; can be set to mark the most recent version.\n * - `rewrites`: Functions and prefix used to generate versioned URLs for documents.\n * - `localePrefix`: Prefix for locale-specific URLs.\n * - `rewriteProcessor`: Processes file paths for versioned URLs.\n * - `localeRewriteProcessor`: Processes locale-specific versioned URLs.\n * - `sidebarOptions`: Configuration for generating versioned sidebars.\n * - `processSidebarURLs`: Whether sidebar URLs should be processed.\n * - `sidebarPathResolver`: Resolves the path to the sidebar JSON file for a given version.\n * - `sidebarUrlProcessor`: Processes sidebar item URLs to include the version prefix.\n *\n * @example\n * ```ts\n * import { defaultConfig } from './default.constant';\n *\n * console.log(defaultConfig.sidebarOptions.sidebarPathResolver('1.0.0'));\n * // Output: \".vitepress/sidebars/versioned/1.0.0.json\"\n *\n * console.log(defaultConfig.rewrites.rewriteProcessor('versions/guide.md'));\n * // Output: \"guide.md\"\n * ```\n *\n * @since 1.0.0\n */\n\nexport const defaultConfig: Required<ConfigInterface['versioning']> = {\n latestVersion: undefined,\n rewrites: {\n localePrefix: '',\n rewriteProcessor: (inputFilePath: string) => inputFilePath.replace('versions/', ''),\n localeRewriteProcessor(inputFilePath: string, _version: string, locale: string): string {\n return `${ locale }/` + inputFilePath.replace(\n 'versions/', '').replace(`${ locale }/`, ''\n );\n }\n },\n sidebarOptions: {\n processSidebarURLs: true,\n sidebarPathResolver: (version: string) => `.vitepress/sidebars/versioned/${ version }.json`,\n sidebarUrlProcessor: (url: string, version: string) => `/${ version }${ url }`\n }\n};\n", "/**\n * Import will remove at compile time\n */\n\nimport type { ConfigInterface, RewritesOptionsInterface } from '@interfaces/config.interface';\n\n/**\n * Imports\n */\n\nimport { posix } from 'path';\nimport { existsSync, readdirSync } from 'fs';\n\n/**\n * Recursively collects all file paths from a directory, skipping locale folders.\n *\n * @param dirPath - The directory path to scan.\n * @param locales - An array of locale folder names to skip.\n *\n * @returns An array of file paths found recursively under `dirPath`.\n *\n * @remarks\n * - Skips any directories that match names in the `locales` array.\n * - Uses POSIX-style paths for consistency across platforms.\n *\n * @example\n * ```ts\n * const files = collectFilesRecursively('/docs/versions/1.0.0', ['en', 'fr']);\n * ```\n *\n * @since 1.0.0\n */\n\nexport function collectFilesRecursively(dirPath: string, locales: Array<string>): Array<string> {\n const files: string[] = [];\n\n for (const entry of readdirSync(dirPath, { withFileTypes: true })) {\n const fullPath = posix.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n if (locales.includes(entry.name)) continue;\n files.push(...collectFilesRecursively(fullPath, locales));\n } else {\n files.push(fullPath);\n }\n }\n\n return files;\n}\n\n/**\n * Generates versioned URL mappings for documentation files.\n *\n * @param rewrites - Rewrites options or `false` to disable URL generation.\n * @param docPath - The root path to the documentation folder.\n * @param versions - An array of documentation versions.\n * @param locales - Optional array of locales to include in URL generation.\n *\n * @returns A record mapping original file paths to their versioned URLs.\n *\n * @remarks\n * - Iterates through each version folder and collects all files.\n * - Applies `rewriteProcessor` and optionally `localeRewriteProcessor` to generate versioned paths.\n * - Locale files are prefixed with `rewrites.localePrefix` and cleaned up for the final path.\n *\n * @example\n * ```ts\n * const urls = generateVersionedUrls(rewrites, '/docs', ['1.0.0', '2.0.0'], ['en', 'fr']);\n * ```\n *\n * @since 1.0.0\n */\n\nexport function generateVersionedUrls(\n rewrites: RewritesOptionsInterface | false, docPath: string, versions: Array<string>, locales: Array<string> = []\n): Record<string, string> {\n const versionedUrls: Record<string, string> = {};\n if (rewrites === false) return versionedUrls;\n\n const versionsDir = posix.join(docPath, 'versions');\n for (const version of versions) {\n const versionPath = posix.join(versionsDir, version);\n\n // Collect all files in this version folder\n const files = collectFilesRecursively(versionPath, locales);\n\n for (const filePath of files) {\n const sourcePath = filePath.replace(versionsDir, 'versions');\n versionedUrls[sourcePath] = rewrites.rewriteProcessor!(\n sourcePath,\n version\n );\n }\n\n for (const locale of locales) {\n const localeDir = posix.join(\n versionsDir,\n version,\n rewrites.localePrefix!,\n locale\n );\n\n if (!existsSync(localeDir)) continue;\n\n const localeFiles = collectFilesRecursively(localeDir, locales);\n\n for (const filePath of localeFiles) {\n const sourcePath = filePath.replace(versionsDir, 'versions');\n versionedUrls[sourcePath] = rewrites.localeRewriteProcessor?.(\n sourcePath,\n version,\n locale\n ).replace(`/${ rewrites.localePrefix! }`, '') ?? '';\n }\n }\n }\n\n return versionedUrls;\n}\n\n/**\n * Updates the configuration object with versioned routes for documentation.\n *\n * @param config - The configuration object to update with versioned URLs.\n * @param versions - An array of documentation versions.\n * @param docPath - The root path to the documentation folder.\n *\n * @returns void\n *\n * @remarks\n * - Calls {@link generateVersionedUrls} to generate mappings for all versions and locales.\n * - Merges the generated URLs into `config.rewrites`.\n *\n * @example\n * ```ts\n * versionRoutes(config, ['1.0.0', '2.0.0'], '/docs');\n * ```\n *\n * @since 1.0.0\n */\n\nexport function versionRoutes(config: ConfigInterface, versions: Array<string>, docPath: string): void {\n config.rewrites = {\n ...config.rewrites,\n ...generateVersionedUrls(\n config.versioning.rewrites!,\n docPath,\n versions,\n Object.keys(config.locales ?? {})\n )\n };\n}\n"],
6
+ "mappings": "+EAYA,OAAS,QAAAA,MAAY,OCmBd,SAASC,EAAuBC,EAA+BC,EAAyBC,EAA6C,CAOxI,GANI,UAAWF,GAAWA,EAAQ,QAC9BA,EAAQ,MAAQA,EAAQ,MAAM,IAAKG,GAC/BJ,EAAuBI,EAAMF,EAAUC,CAAa,CACxD,GAGA,cAAeF,GAAWA,EAAQ,UAAW,CAC7C,IAAMI,EAAgBJ,EAKtBI,EAAc,QAAU,CAAC,EACzBA,EAAc,MAAM,iBAAmB,CACnC,SAAAH,EACA,cAAAC,CACJ,CACJ,CAEA,OAAOF,CACX,CArBgBK,EAAAN,EAAA,0BA8CT,SAASO,EAAcC,EAAoCN,EAAyBC,EAAwB,GAAU,CACpH,MAAM,QAAQK,EAAY,GAAG,IAElCA,EAAY,IAAMA,EAAY,IAAI,IAAKJ,GACnCJ,EAAuBI,EAAMF,EAAUC,CAAa,CACxD,EACJ,CANgBG,EAAAC,EAAA,iBClEhB,OAAS,SAAAE,MAAa,sCCcf,SAASC,EACZC,EAAiCC,EACV,CACvB,QAAWC,KAAOD,EAAQ,CAEtB,GAAIC,IAAQ,aAAeA,IAAQ,eAAiBA,IAAQ,YACxD,SAGJ,IAAMC,EAAcF,EAAOC,CAAG,EACxBE,EAAcJ,EAAOE,CAAG,EAE1BE,IAAgB,OAChBJ,EAAOE,CAAG,EAAIC,EAEdA,GAAe,OAAOA,GAAgB,UACtCC,GAAe,OAAOA,GAAgB,UAEtCL,EACIK,EACAD,CACJ,CAER,CAEA,OAAOH,CACX,CA1BgBK,EAAAN,EAAA,qBCcT,SAASO,EAAgBC,EAAoCC,EAAyBC,EAAwB,SAAgB,CACjI,GAAIF,EAAY,kBAAoB,GAAO,OAC3C,IAAMG,EAAW,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I,EAAqBC,EAAYL,EAAgB,CAAE,cAAe,EAAK,CAAC,EACzE,OAAQM,GAAkBA,EAAM,YAAY,CAAC,EAC7C,IAAKA,GAAkBA,EAAM,IAAI,EAEtC,OAAAV,EAAO,WAA6CW,EAAkBX,EAAO,WAAYY,CAAa,EACtGC,EAAYb,EAAQQ,EAAUP,CAAQ,EACtCa,EAAcd,EAAQQ,EAAUL,CAAQ,EAEjCH,CACX,CAnBgBe,EAAAhB,GAAA",
7
+ "names": ["join", "addVersioningToNavItem", "navItem", "versions", "latestVersion", "item", "componentItem", "__name", "versioningNav", "themeConfig", "xterm", "assignMissingDeep", "target", "source", "key", "sourceValue", "targetValue", "__name", "versionSwitcher", "themeConfig", "versions", "latestVersion", "defaults", "assignMissingDeep", "text", "includeLatestVersion", "items", "version", "__name", "resolve", "existsSync", "readFileSync", "replaceLinksRecursive", "sidebarOptions", "version", "sidebar", "item", "__name", "loadSidebar", "locale", "rootPath", "sidebarPath", "resolve", "existsSync", "readFileSync", "multiSidebar", "key", "versioningSidebar", "config", "versions", "locales", "versionSidebars", "themeConfig", "config", "versions", "rootPath", "themeConfigArray", "locale", "versionSwitcher", "versioningNav", "xterm", "versioningSidebar", "__name", "defaultConfig", "__name", "inputFilePath", "_version", "locale", "version", "url", "posix", "existsSync", "readdirSync", "collectFilesRecursively", "dirPath", "locales", "files", "entry", "readdirSync", "fullPath", "posix", "__name", "generateVersionedUrls", "rewrites", "docPath", "versions", "versionedUrls", "versionsDir", "version", "versionPath", "filePath", "sourcePath", "locale", "localeDir", "existsSync", "localeFiles", "versionRoutes", "config", "existsSync", "mkdirSync", "readdirSync", "writeFileSync", "defineVersionedConfig", "config", "rootPath", "join", "docsPath", "versionsFolder", "existsSync", "mkdirSync", "writeFileSync", "versions", "readdirSync", "entry", "assignMissingDeep", "defaultConfig", "themeConfig", "versionRoutes", "__name"]
8
+ }
@@ -0,0 +1 @@
1
+ {"type": "module"}
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@viteplus/versions",
3
+ "main": "dist/index.js",
4
+ "type": "module",
5
+ "types": "./dist/index.d.ts",
6
+ "module": "./dist/index.js",
7
+ "author": "Garefild",
8
+ "version": "1.0.0",
9
+ "license": "Mozilla Public License Version 2.0",
10
+ "description": "A versioning plugin for VitePress",
11
+ "homepage": "https://viteplus.github.io/versions/",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/viteplus/versions.git"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/viteplus/versions/issues"
18
+ },
19
+ "keywords": [
20
+ "vite",
21
+ "plugin",
22
+ "versions",
23
+ "vitepress",
24
+ "versioning"
25
+ ],
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "LICENSE",
32
+ "README.md",
33
+ "components"
34
+ ],
35
+ "scripts": {
36
+ "dev": "xbuild -w",
37
+ "lint": "xbuild --tc && eslint . -c ./eslint.config.mjs",
38
+ "build": "xbuild",
39
+ "test": "xjet",
40
+ "test:coverage": "xjet --coverage",
41
+ "preci:test": "xbuild",
42
+ "ci:test": "xjet",
43
+ "ci:clean": "rm -rf ./dist",
44
+ "ci:build": "npm run build",
45
+ "docs:dev": "vitepress dev docs",
46
+ "docs:build": "vitepress build docs",
47
+ "docs:preview": "vitepress preview docs"
48
+ },
49
+ "devDependencies": {
50
+ "eslint": "^9.35.0",
51
+ "typescript-eslint": "^8.44.0",
52
+ "eslint-plugin-tsdoc": "^0.4.0",
53
+ "eslint-plugin-perfectionist": "^4.15.0",
54
+ "@types/node": "^24.5.0",
55
+ "@remotex-labs/xjet": "^1.0.1",
56
+ "@remotex-labs/xbuild": "1.6.0"
57
+ },
58
+ "peerDependencies": {
59
+ "vitepress": "^1.6.4",
60
+ "@remotex-labs/xansi": "^1.3.2"
61
+ }
62
+ }