@kawapress/plugin-sitemap 0.0.0-stage → 0.0.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) KawaPress contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,145 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo-dark.png">
4
+ <img src="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo.png" alt="KawaPress" width="180">
5
+ </picture>
6
+ </p>
2
7
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
8
+ <h1 align="center">KawaPress</h1>
9
+
10
+ <p align="center">
11
+ <strong>A Vue-first static site generator for documentation and content-focused websites.</strong>
12
+ </p>
13
+
14
+ <p align="center">
15
+ Write in Markdown. Develop with real SSR. Extend everything through public APIs.
16
+ </p>
17
+
18
+ <p align="center">
19
+ <a href="https://www.npmjs.com/package/kawapress"><img src="https://img.shields.io/npm/v/kawapress/beta?label=npm%20beta&color=42b883" alt="npm beta version"></a>
20
+ <a href="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml"><img src="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml/badge.svg" alt="documentation build"></a>
21
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE"><img src="https://img.shields.io/github/license/ShenQingchuan/kawapress" alt="MIT license"></a>
22
+ <img src="https://img.shields.io/badge/Node.js-%E2%89%A522.12-339933?logo=nodedotjs&logoColor=white" alt="Node.js 22.12 or newer">
23
+ </p>
24
+
25
+ <p align="center">
26
+ <a href="https://shenqingchuan.github.io/kawapress/en/">Documentation</a>
27
+ ·
28
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/README.zh-CN.md">简体中文</a>
29
+ </p>
30
+
31
+ > [!IMPORTANT]
32
+ > KawaPress is in beta. It is ready for testing and early projects, but APIs may change before 0.1.0. Please pin the version when adopting it today.
33
+
34
+ ## Why KawaPress?
35
+
36
+ KawaPress turns Markdown into pre-rendered Vue websites. It keeps the familiar simplicity of a documentation generator while giving themes and plugins the same public extension points used by the official experience.
37
+
38
+ - **Real SSR during development** — every initial request is server-rendered, so SSR-only problems appear before build or deployment.
39
+ - **A complete default experience** — the built-in nagi (凪) preset includes responsive documentation layouts, dark mode, local search, syntax highlighting, Twoslash, code groups, multilingual navigation, and more.
40
+ - **Vue from end to end** — Markdown becomes Vue components, Vue Router handles navigation, and regular Vue SFCs fit naturally into content.
41
+ - **AI-ready output** — nagi generates page-level Markdown, locale-aware `llms.txt` and `llms-full.txt`, plus built-in copy actions.
42
+ - **One extension model** — Generator Plugins, Runtime Plugins, and Presets cover build-time behavior, the Vue runtime, themes, and reusable product setups without private theme hooks.
43
+
44
+ KawaPress is an independent project. It is not a VitePress fork or a drop-in replacement, and it intentionally does not use VitePress configuration.
45
+
46
+ ## Quick Start
47
+
48
+ You need [Node.js](https://nodejs.org/) 22.12 or newer.
49
+
50
+ ```sh
51
+ mkdir my-kawapress-site
52
+ cd my-kawapress-site
53
+ pnpm init
54
+ pnpm add --save-dev kawapress
55
+ ```
56
+
57
+ Create `kawapress.config.ts`:
58
+
59
+ ```ts
60
+ import { nagi } from 'kawapress/nagi'
61
+
62
+ export default nagi({
63
+ title: 'My Docs',
64
+ })
65
+ ```
66
+
67
+ Create `index.md`:
68
+
69
+ ```md
70
+ ---
71
+ layout: home
72
+ title: My Docs
73
+ ---
74
+
75
+ # My Docs
76
+
77
+ Welcome to my KawaPress site.
78
+ ```
79
+
80
+ Start the development server:
81
+
82
+ ```sh
83
+ pnpm exec kawapress dev
84
+ ```
85
+
86
+ Build static files into `dist`:
87
+
88
+ ```sh
89
+ pnpm exec kawapress build
90
+ ```
91
+
92
+ The deployed output is static and does not require a Node.js server. npm and Yarn commands are available in the [Getting Started guide](https://shenqingchuan.github.io/kawapress/en/guide/getting-started).
93
+
94
+ > If your site directly imports Vue APIs or Vue components, also install `vue` as a development dependency.
95
+
96
+ ## What You Get
97
+
98
+ | Area | Included capability |
99
+ | --- | --- |
100
+ | Authoring | Markdown, frontmatter, Vue in Markdown, file-based routing, data loaders |
101
+ | Rendering | Shared development/build SSR semantics, hydration, Vue Router navigation |
102
+ | Documentation UI | nagi layouts, responsive sidebar, page outline, dark mode, i18n |
103
+ | Content | Shiki, Twoslash, code groups, code copy, containers, GitHub alerts |
104
+ | Discovery | Lazy local search and locale-aware navigation |
105
+ | AI consumption | Page `.md`, `llms.txt`, `llms-full.txt`, copy actions |
106
+ | Styling | UnoCSS integration with sensible nagi defaults |
107
+
108
+ The `kawapress` package includes nagi and its official plugins. A basic site only needs this one package; advanced users can compose the individual `@kawapress/*` packages directly.
109
+
110
+ ## Extension Model
111
+
112
+ KawaPress keeps extension boundaries explicit:
113
+
114
+ - a **Generator Plugin** extends configuration, Markdown, page data, Vite, and build artifacts;
115
+ - a **Runtime Plugin** extends the real Vue App and Vue Router in both SSR and the browser;
116
+ - a **Preset** combines configuration and plugins into a ready-to-use experience such as nagi.
117
+
118
+ A logical plugin is installed once and can provide both generator and runtime behavior. Learn more in the [Plugin System guide](https://shenqingchuan.github.io/kawapress/en/guide/plugin-system).
119
+
120
+ ## Documentation
121
+
122
+ - [Getting Started](https://shenqingchuan.github.io/kawapress/en/guide/getting-started)
123
+ - [What is KawaPress?](https://shenqingchuan.github.io/kawapress/en/guide/what-is-kawapress)
124
+ - [Markdown Extensions](https://shenqingchuan.github.io/kawapress/en/guide/markdown-extensions)
125
+ - [Internationalization](https://shenqingchuan.github.io/kawapress/en/guide/internationalization)
126
+ - [Plugin System](https://shenqingchuan.github.io/kawapress/en/guide/plugin-system)
127
+ - [Theme Customization](https://shenqingchuan.github.io/kawapress/en/guide/theme-customization)
128
+
129
+ ## Contributing
130
+
131
+ Issues and pull requests are welcome. For a large feature, please open an issue first so the direction can be agreed on before implementation.
132
+
133
+ ```sh
134
+ pnpm install
135
+ pnpm lint
136
+ pnpm typecheck
137
+ pnpm test
138
+ pnpm build
139
+ ```
140
+
141
+ KawaPress uses Node.js 22.12 or newer and pnpm 11.22.0 for repository development.
142
+
143
+ ## License
144
+
145
+ [MIT](https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE) © KawaPress contributors
@@ -0,0 +1,145 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo-dark.png">
4
+ <img src="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo.png" alt="KawaPress" width="180">
5
+ </picture>
6
+ </p>
7
+
8
+ <h1 align="center">KawaPress</h1>
9
+
10
+ <p align="center">
11
+ <strong>以 Vue 为核心,面向文档与内容型网站的静态站点生成器。</strong>
12
+ </p>
13
+
14
+ <p align="center">
15
+ 用 Markdown 安心写作,在真实 SSR 中开发,通过公开能力自由扩展。
16
+ </p>
17
+
18
+ <p align="center">
19
+ <a href="https://www.npmjs.com/package/kawapress"><img src="https://img.shields.io/npm/v/kawapress/beta?label=npm%20beta&color=42b883" alt="npm beta 版本"></a>
20
+ <a href="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml"><img src="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml/badge.svg" alt="文档构建状态"></a>
21
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE"><img src="https://img.shields.io/github/license/ShenQingchuan/kawapress" alt="MIT 许可"></a>
22
+ <img src="https://img.shields.io/badge/Node.js-%E2%89%A522.12-339933?logo=nodedotjs&logoColor=white" alt="Node.js 22.12 或更高版本">
23
+ </p>
24
+
25
+ <p align="center">
26
+ <a href="https://shenqingchuan.github.io/kawapress/">中文文档</a>
27
+ ·
28
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/README.md">English</a>
29
+ </p>
30
+
31
+ > [!IMPORTANT]
32
+ > KawaPress 目前处于 beta 阶段,适合试用和早期项目。0.1.0 之前,公开 API 仍可能调整;现阶段使用时请固定具体版本。
33
+
34
+ ## 为什么选择 KawaPress?
35
+
36
+ KawaPress 会把 Markdown 编译成预渲染的 Vue 网站。它保留了文档生成器简单、轻快的写作方式,同时让官方主题和第三方扩展使用完全相同的公开能力。
37
+
38
+ - **开发时也执行真实 SSR**:每次首次请求都会在服务端渲染。只在 SSR 中出现的问题,不必等到构建或上线后才发现。
39
+ - **默认体验完整**:内置 nagi(凪)预设,包含响应式文档布局、深浅色模式、本地搜索、代码高亮、Twoslash、代码组和多语言导航等常用能力。
40
+ - **从头到尾使用 Vue**:Markdown 会变成 Vue 组件,页面跳转交给 Vue Router;需要交互时,也可以自然地使用普通 Vue SFC。
41
+ - **面向 AI 的文档产物**:nagi 默认生成每页 `.md`、各语言的 `llms.txt` 与 `llms-full.txt`,并提供复制正文和链接的操作。
42
+ - **统一的扩展模型**:Generator Plugin、Runtime Plugin 与 Preset 分别覆盖生成阶段、Vue 运行时和能力组合,不依赖主题私有入口。
43
+
44
+ KawaPress 是一个独立项目,不是 VitePress 的分支或配置兼容层,也不能直接使用 VitePress 配置。
45
+
46
+ ## 快速开始
47
+
48
+ 请先准备 [Node.js](https://nodejs.org/) 22.12 或更高版本。
49
+
50
+ ```sh
51
+ mkdir my-kawapress-site
52
+ cd my-kawapress-site
53
+ pnpm init
54
+ pnpm add --save-dev kawapress
55
+ ```
56
+
57
+ 创建 `kawapress.config.ts`:
58
+
59
+ ```ts
60
+ import { nagi } from 'kawapress/nagi'
61
+
62
+ export default nagi({
63
+ title: 'My Docs',
64
+ })
65
+ ```
66
+
67
+ 创建 `index.md`:
68
+
69
+ ```md
70
+ ---
71
+ layout: home
72
+ title: My Docs
73
+ ---
74
+
75
+ # My Docs
76
+
77
+ 欢迎来到我的 KawaPress 站点。
78
+ ```
79
+
80
+ 启动开发服务器:
81
+
82
+ ```sh
83
+ pnpm exec kawapress dev
84
+ ```
85
+
86
+ 构建静态文件到 `dist`:
87
+
88
+ ```sh
89
+ pnpm exec kawapress build
90
+ ```
91
+
92
+ 部署产物是普通静态文件,不需要在服务器上继续运行 Node.js。npm 和 Yarn 的完整命令可以查看[快速开始](https://shenqingchuan.github.io/kawapress/guide/getting-started)。
93
+
94
+ > 如果站点会直接导入 Vue API 或 Vue 组件,还需要把 `vue` 安装为开发依赖。
95
+
96
+ ## 默认包含什么?
97
+
98
+ | 范围 | 内置能力 |
99
+ | --- | --- |
100
+ | 内容编写 | Markdown、Frontmatter、在 Markdown 中使用 Vue、文件路由、Data Loader |
101
+ | 渲染 | 开发与构建共享 SSR 语义、Hydration、Vue Router 站内导航 |
102
+ | 文档界面 | nagi 布局、响应式 Sidebar、本页目录、深浅色模式、多语言 |
103
+ | 内容增强 | Shiki、Twoslash、代码组、代码复制、提示容器、GitHub Alerts |
104
+ | 内容发现 | 按需加载的本地搜索与多语言导航 |
105
+ | AI 读取 | 页面 `.md`、`llms.txt`、`llms-full.txt`、页面复制操作 |
106
+ | 样式 | UnoCSS 集成与 nagi 默认配置 |
107
+
108
+ `kawapress` 已经包含 nagi 和它使用的官方插件。普通文档站只需要安装这一个包;需要自行组合能力时,也可以直接使用独立的 `@kawapress/*` 包。
109
+
110
+ ## 扩展模型
111
+
112
+ KawaPress 把扩展边界分得很清楚:
113
+
114
+ - **Generator Plugin** 负责配置、Markdown、页面数据、Vite 与构建产物;
115
+ - **Runtime Plugin** 在 SSR 和浏览器中扩展真实的 Vue App 与 Vue Router;
116
+ - **Preset** 把配置和一组插件组合成可以直接使用的产品体验,例如 nagi。
117
+
118
+ 一个逻辑插件只需要安装一次,同时可以提供生成侧和运行侧能力。更多内容请查看[插件体系](https://shenqingchuan.github.io/kawapress/guide/plugin-system)。
119
+
120
+ ## 文档
121
+
122
+ - [快速开始](https://shenqingchuan.github.io/kawapress/guide/getting-started)
123
+ - [KawaPress 是什么?](https://shenqingchuan.github.io/kawapress/guide/what-is-kawapress)
124
+ - [Markdown 语法扩展](https://shenqingchuan.github.io/kawapress/guide/markdown-extensions)
125
+ - [国际化](https://shenqingchuan.github.io/kawapress/guide/internationalization)
126
+ - [插件体系](https://shenqingchuan.github.io/kawapress/guide/plugin-system)
127
+ - [主题定制](https://shenqingchuan.github.io/kawapress/guide/theme-customization)
128
+
129
+ ## 参与贡献
130
+
131
+ 欢迎提交 Issue 和 Pull Request。如果准备增加较大的功能,请先创建 Issue,把目标和方案聊清楚后再开始实现。
132
+
133
+ ```sh
134
+ pnpm install
135
+ pnpm lint
136
+ pnpm typecheck
137
+ pnpm test
138
+ pnpm build
139
+ ```
140
+
141
+ KawaPress 仓库使用 Node.js 22.12 或更高版本,以及 pnpm 11.22.0 进行开发。
142
+
143
+ ## 开源许可
144
+
145
+ [MIT](https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE) © KawaPress 贡献者
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@kawapress/plugin-sitemap",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "description": "sitemap.xml output for KawaPress",
6
+ "license": "MIT",
7
+ "homepage": "https://shenqingchuan.github.io/kawapress/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ShenQingchuan/kawapress.git",
11
+ "directory": "packages/plugin-sitemap"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/ShenQingchuan/kawapress/issues"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/index.ts",
19
+ "import": "./src/index.ts",
20
+ "default": "./src/index.ts"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "src/**/!(*.test.*)"
26
+ ],
27
+ "engines": {
28
+ "node": ">=22.12.0"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "registry": "https://registry.npmjs.org/"
33
+ },
34
+ "peerDependencies": {
35
+ "kawapress": "0.0.1"
36
+ },
37
+ "dependencies": {
38
+ "consola": "^3.4.2",
39
+ "sitemap": "^9.0.1"
40
+ },
41
+ "devDependencies": {
42
+ "typescript": "^6.0.3",
43
+ "vite": "^8.2.2",
44
+ "kawapress": "0.0.1"
45
+ }
6
46
  }
package/src/git.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { resolve } from 'node:path'
3
+ import { promisify } from 'node:util'
4
+ import { consola } from 'consola'
5
+
6
+ const execFileAsync = promisify(execFile)
7
+ const RECORD_SEPARATOR = '\x1E'
8
+ const MAX_BUFFER = 256 * 1024 * 1024
9
+
10
+ async function runGit(cwd: string, args: string[]): Promise<string> {
11
+ const { stdout } = await execFileAsync('git', args, { cwd, maxBuffer: MAX_BUFFER })
12
+ return stdout
13
+ }
14
+
15
+ /**
16
+ * 批量读取站点目录下每个文件最后一次提交的时间(毫秒)。
17
+ * 仓库不可用或为浅克隆时返回 `undefined`,并给出 warning,不输出错误日期。
18
+ */
19
+ export async function readGitLastUpdated(
20
+ siteRoot: string,
21
+ ): Promise<Map<string, number> | undefined> {
22
+ try {
23
+ await runGit(siteRoot, ['rev-parse', '--is-inside-work-tree'])
24
+ }
25
+ catch {
26
+ consola.warn('KawaPress Sitemap: 当前目录不在 git 仓库中,已跳过 lastmod。')
27
+ return undefined
28
+ }
29
+
30
+ const shallow = (await runGit(siteRoot, ['rev-parse', '--is-shallow-repository'])).trim()
31
+ if (shallow === 'true') {
32
+ consola.warn('KawaPress Sitemap: 当前仓库是浅克隆,已跳过 lastmod。请在 CI 中设置 fetch-depth: 0。')
33
+ return undefined
34
+ }
35
+
36
+ const output = await runGit(siteRoot, [
37
+ 'log',
38
+ '--format=%x1e%at',
39
+ '--name-only',
40
+ '-z',
41
+ '--relative',
42
+ '--',
43
+ '.',
44
+ ])
45
+ return parseGitLog(output, siteRoot)
46
+ }
47
+
48
+ export function parseGitLog(output: string, siteRoot: string): Map<string, number> {
49
+ const timestamps = new Map<string, number>()
50
+ for (const record of output.split(RECORD_SEPARATOR)) {
51
+ const [head = '', ...files] = record.split('\0')
52
+ const seconds = Number.parseInt(head.trim(), 10)
53
+ if (!(seconds > 0)) {
54
+ continue
55
+ }
56
+ for (const file of files) {
57
+ const name = file.replace(/^\n+/, '')
58
+ if (!name) {
59
+ continue
60
+ }
61
+ // git 输出按时间从新到旧排列,第一次出现即为最后一次提交
62
+ const absolute = resolve(siteRoot, name)
63
+ if (!timestamps.has(absolute)) {
64
+ timestamps.set(absolute, seconds * 1000)
65
+ }
66
+ }
67
+ }
68
+ return timestamps
69
+ }
@@ -0,0 +1,28 @@
1
+ const TRAILING_SLASH_RE = /\/+$/
2
+
3
+ export function normalizeSitemapBase(base: string | undefined): string {
4
+ if (!base || base === '/') {
5
+ return '/'
6
+ }
7
+ return `/${base.replace(/^\/+|\/+$/g, '')}/`
8
+ }
9
+
10
+ /**
11
+ * 把 `hostname` 与站点 `base` 合并为 sitemap 的基地址。
12
+ * 如果 `hostname` 已经包含 `base`,则不会重复追加。
13
+ */
14
+ export function resolveSitemapHostname(hostname: string, base: string): string {
15
+ const url = new URL(hostname)
16
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
17
+ throw new Error(`KawaPress Sitemap: hostname must use http or https, received ${JSON.stringify(hostname)}.`)
18
+ }
19
+
20
+ const sitePath = normalizeSitemapBase(base)
21
+ const hostPath = `${url.pathname.replace(TRAILING_SLASH_RE, '')}/`
22
+ url.pathname = hostPath === sitePath || sitePath === '/'
23
+ ? hostPath
24
+ : `${hostPath.replace(TRAILING_SLASH_RE, '')}${sitePath}`
25
+ url.search = ''
26
+ url.hash = ''
27
+ return url.href
28
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { default, sitemapPlugin } from './plugin'
2
+ export type { SitemapPluginItem, SitemapPluginOptions } from './types'
package/src/items.ts ADDED
@@ -0,0 +1,91 @@
1
+ import type { LocaleConfig, PageBuildArtifact } from 'kawapress'
2
+ import type { SitemapPluginItem } from './types'
3
+
4
+ export interface CreateSitemapItemsOptions {
5
+ pages: readonly PageBuildArtifact[]
6
+ locales?: Record<string, LocaleConfig>
7
+ lastUpdated: boolean
8
+ /** 文件绝对路径到最后提交时间(毫秒)的映射,仅 `lastUpdated` 开启时使用 */
9
+ gitLastUpdated?: ReadonlyMap<string, number>
10
+ }
11
+
12
+ interface PageVariant {
13
+ lang: string
14
+ url: string
15
+ lastmod?: number
16
+ }
17
+
18
+ const DEFAULT_LANG = 'en'
19
+
20
+ export function createSitemapItems(options: CreateSitemapItemsOptions): SitemapPluginItem[] {
21
+ const locales = options.locales ?? {}
22
+ const rootLang = locales.root?.lang ?? DEFAULT_LANG
23
+ const localeKeys = Object.keys(locales)
24
+ .filter(key => key !== 'root')
25
+ .sort((left, right) => right.length - left.length)
26
+
27
+ const groups = new Map<string, PageVariant[]>()
28
+ for (const page of options.pages) {
29
+ if (page.pageData.frontmatter.sitemap === false) {
30
+ continue
31
+ }
32
+
33
+ const localeIndex = localeKeys.find(key => (
34
+ page.routePath === `/${key}` || page.routePath.startsWith(`/${key}/`)
35
+ )) ?? 'root'
36
+ const groupKey = localeIndex === 'root'
37
+ ? page.routePath
38
+ : page.routePath.slice(`/${localeIndex}`.length) || '/'
39
+
40
+ const variant: PageVariant = {
41
+ lang: localeIndex === 'root'
42
+ ? rootLang
43
+ : (locales[localeIndex]?.lang ?? localeIndex),
44
+ url: toSitemapUrl(page.routePath),
45
+ lastmod: resolveLastmod(page, options),
46
+ }
47
+ const variants = groups.get(groupKey) ?? []
48
+ variants.push(variant)
49
+ groups.set(groupKey, variants)
50
+ }
51
+
52
+ return [...groups.values()].flatMap(variants => (
53
+ variants.length < 2
54
+ ? [{ url: variants[0].url, lastmod: variants[0].lastmod }]
55
+ : variants.map(({ url, lastmod }) => ({
56
+ url,
57
+ lastmod,
58
+ links: variants.map(link => ({ lang: link.lang, url: link.url })),
59
+ }))
60
+ ))
61
+ }
62
+
63
+ function resolveLastmod(
64
+ page: PageBuildArtifact,
65
+ options: CreateSitemapItemsOptions,
66
+ ): number | undefined {
67
+ if (!options.lastUpdated) {
68
+ return undefined
69
+ }
70
+ const frontmatterValue = page.pageData.frontmatter.lastUpdated
71
+ if (frontmatterValue === false) {
72
+ return undefined
73
+ }
74
+ if (typeof frontmatterValue === 'string') {
75
+ const time = Date.parse(frontmatterValue)
76
+ if (Number.isNaN(time)) {
77
+ throw new TypeError(`KawaPress Sitemap: ${page.routePath} 的 frontmatter lastUpdated 不是有效日期:${JSON.stringify(frontmatterValue)}`)
78
+ }
79
+ return time
80
+ }
81
+ return options.gitLastUpdated?.get(page.file)
82
+ }
83
+
84
+ /**
85
+ * sitemap 库会用 `new URL(url, hostname)` 解析条目。
86
+ * 这里输出不带前导斜杠的相对路径,使 hostname 中的 base 得以保留。
87
+ */
88
+ function toSitemapUrl(routePath: string): string {
89
+ const path = routePath.replace(/^\/+/, '')
90
+ return path.split('/').map(segment => encodeURIComponent(segment)).join('/')
91
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,66 @@
1
+ import type { LocaleConfig } from 'kawapress'
2
+ import type { SitemapPluginOptions } from './types'
3
+ import { resolve } from 'node:path'
4
+ import process from 'node:process'
5
+ import { consola } from 'consola'
6
+ import { definePlugin } from 'kawapress'
7
+ import { SitemapStream, streamToPromise } from 'sitemap'
8
+ import { readGitLastUpdated } from './git'
9
+ import { resolveSitemapHostname } from './hostname'
10
+ import { createSitemapItems } from './items'
11
+
12
+ const MAX_SITEMAP_URLS = 50000
13
+
14
+ export function sitemapPlugin(options: SitemapPluginOptions = {}) {
15
+ let root = process.cwd()
16
+ let base = '/'
17
+ let locales: Record<string, LocaleConfig> | undefined
18
+
19
+ return definePlugin({
20
+ name: '@kawapress/plugin-sitemap',
21
+ setup(api) {
22
+ api.config((config) => {
23
+ base = config.base ?? '/'
24
+ locales = config.locales
25
+ })
26
+ api.vite((config) => {
27
+ root = config.root ? resolve(config.root) : process.cwd()
28
+ })
29
+ api.buildArtifacts(async ({ pages, emitFile }) => {
30
+ // 未设置 hostname 时保持关闭:不输出日志,也不生成文件
31
+ if (!options.hostname) {
32
+ return
33
+ }
34
+
35
+ consola.start('sitemap 正在生成中…')
36
+ const hostname = resolveSitemapHostname(options.hostname, base)
37
+ const gitLastUpdated = options.lastUpdated
38
+ ? await readGitLastUpdated(root)
39
+ : undefined
40
+ let items = createSitemapItems({
41
+ pages,
42
+ locales,
43
+ lastUpdated: options.lastUpdated ?? false,
44
+ gitLastUpdated,
45
+ })
46
+ items = (await options.transformItems?.(items)) || items
47
+ if (items.length > MAX_SITEMAP_URLS) {
48
+ throw new RangeError(`sitemap 条目数 ${items.length} 超过单文件上限 ${MAX_SITEMAP_URLS},暂不支持 sitemap index`)
49
+ }
50
+
51
+ const { lastUpdated: _lastUpdated, transformItems: _transformItems, ...streamOptions } = options
52
+ const stream = new SitemapStream({ ...streamOptions, hostname })
53
+ for (const item of items) {
54
+ stream.write(item)
55
+ }
56
+ stream.end()
57
+ const xml = (await streamToPromise(stream)).toString()
58
+
59
+ await emitFile('sitemap.xml', xml)
60
+ consola.success(`sitemap 已生成:共计 ${items.length} 个条目`)
61
+ })
62
+ },
63
+ })
64
+ }
65
+
66
+ export default sitemapPlugin
package/src/types.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { MaybePromise } from 'kawapress'
2
+ import type { LinkItem, SitemapItemLoose, SitemapStreamOptions } from 'sitemap'
3
+
4
+ export type SitemapPluginItem = Omit<SitemapItemLoose, 'url' | 'lastmod' | 'links'> & {
5
+ url: string
6
+ lastmod?: string | number | Date
7
+ links?: LinkItem[]
8
+ }
9
+
10
+ export interface SitemapPluginOptions extends SitemapStreamOptions {
11
+ /**
12
+ * 站点的绝对地址,例如 `https://kawapress.dev`。未设置时插件不生成 sitemap.xml。
13
+ * 站点配置的 `base` 会自动追加,无需重复写入。
14
+ */
15
+ hostname?: string
16
+ /**
17
+ * 是否为每个页面输出 `<lastmod>`。时间来自该 Markdown 文件最后一次 git 提交。
18
+ * 页面 frontmatter 的 `lastUpdated: false` 可关闭单页,`lastUpdated: <Date>` 可手动指定。
19
+ * @default false
20
+ */
21
+ lastUpdated?: boolean
22
+ /**
23
+ * 写入前对条目做增删改,返回 `undefined` 时保留原条目。
24
+ */
25
+ transformItems?: (
26
+ items: SitemapPluginItem[],
27
+ ) => MaybePromise<SitemapPluginItem[] | undefined>
28
+ }