kawapress 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +14 -3
  2. package/README.zh-CN.md +14 -3
  3. package/package.json +7 -3
  4. package/src/api/config.ts +5 -0
  5. package/src/api/plugin.ts +18 -2
  6. package/src/cli.ts +28 -2
  7. package/src/client/app.ts +36 -6
  8. package/src/client/components/KawaOutlet.vue +36 -0
  9. package/src/client/components/Root.vue +7 -0
  10. package/src/client/composables.ts +5 -5
  11. package/src/client/entries/entry-client.ts +8 -3
  12. package/src/client/entries/entry-server.ts +36 -6
  13. package/src/client/index.ts +8 -2
  14. package/src/client/outlet.ts +85 -0
  15. package/src/client/page-data.ts +22 -15
  16. package/src/client/page-table.ts +138 -0
  17. package/src/client/router/RouterLink.ts +34 -0
  18. package/src/client/router/RouterView.ts +25 -0
  19. package/src/client/router/app-router.ts +84 -0
  20. package/src/client/router/history.ts +53 -0
  21. package/src/client/router/injection.ts +29 -0
  22. package/src/client/router/link-interceptor.ts +67 -0
  23. package/src/client/router/reload.ts +34 -0
  24. package/src/client/router/route.ts +82 -0
  25. package/src/client/router/router.ts +160 -0
  26. package/src/client/testing/virtual-modules.ts +19 -0
  27. package/src/client/types/global-components.d.ts +1 -0
  28. package/src/client/types/virtual-modules.d.ts +3 -5
  29. package/src/compiler/frontmatter-compat.ts +12 -0
  30. package/src/compiler/link-registry.ts +29 -0
  31. package/src/compiler/markdown.ts +221 -20
  32. package/src/compiler/page-components.ts +144 -0
  33. package/src/compiler/page-loader.ts +15 -2
  34. package/src/compiler/page-summary.ts +96 -0
  35. package/src/core/dead-links.ts +234 -0
  36. package/src/core/head.ts +207 -0
  37. package/src/core/heading-title.ts +78 -0
  38. package/src/core/hydration-plan.ts +79 -0
  39. package/src/core/locale.ts +18 -8
  40. package/src/core/not-found.ts +22 -0
  41. package/src/core/outlet.ts +110 -0
  42. package/src/core/page-chunk.ts +50 -0
  43. package/src/core/page-manifest.ts +53 -0
  44. package/src/core/router.ts +46 -0
  45. package/src/core/site.ts +10 -0
  46. package/src/core/tokens.ts +59 -0
  47. package/src/generator/config.ts +93 -13
  48. package/src/generator/data/context.ts +1 -0
  49. package/src/generator/git.ts +79 -0
  50. package/src/generator/pages.ts +126 -0
  51. package/src/generator/runtime-dependencies.ts +280 -0
  52. package/src/generator/vite/app-chunk.ts +65 -0
  53. package/src/generator/vite/config.ts +84 -10
  54. package/src/generator/vite/page-inputs.ts +22 -0
  55. package/src/generator/vite/plugins/dev-dead-links.ts +72 -0
  56. package/src/generator/vite/plugins/pages.ts +162 -114
  57. package/src/generator.ts +13 -0
  58. package/src/index.ts +28 -0
  59. package/src/plugin/execution.ts +17 -13
  60. package/src/plugin/generator-runner.ts +6 -2
  61. package/src/plugin/outlet-collector.ts +69 -0
  62. package/src/plugin/runtime-runner.ts +7 -1
  63. package/src/server/build-node-env.ts +48 -0
  64. package/src/server/build.ts +50 -4
  65. package/src/server/check-dead-links.ts +88 -0
  66. package/src/server/page-assets.ts +138 -0
  67. package/src/server/prerender.ts +134 -27
  68. package/src/server/preview-routing.ts +64 -0
  69. package/src/server/preview.ts +78 -11
  70. package/src/server/request-handler.ts +36 -12
  71. package/src/server/template.ts +31 -0
  72. package/src/client/router.ts +0 -81
package/README.md CHANGED
@@ -16,7 +16,7 @@
16
16
  </p>
17
17
 
18
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>
19
+ <a href="https://www.npmjs.com/package/kawapress"><img src="https://img.shields.io/npm/v/kawapress?label=npm&color=42b883" alt="npm version"></a>
20
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
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
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">
@@ -28,8 +28,7 @@
28
28
  <a href="https://github.com/ShenQingchuan/kawapress/blob/main/README.zh-CN.md">简体中文</a>
29
29
  </p>
30
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.
31
+ If you run into any problems while using KawaPress, please [open an issue](https://github.com/ShenQingchuan/kawapress/issues). Your feedback helps shape the project during its early development.
33
32
 
34
33
  ## Why KawaPress?
35
34
 
@@ -47,6 +46,18 @@ KawaPress is an independent project. It is not a VitePress fork or a drop-in rep
47
46
 
48
47
  You need [Node.js](https://nodejs.org/) 22.12 or newer.
49
48
 
49
+ Create a new site with the scaffolder:
50
+
51
+ ```sh
52
+ npm create kawapress@latest my-kawapress-site
53
+ cd my-kawapress-site
54
+ npm run dev
55
+ ```
56
+
57
+ `pnpm create kawapress my-kawapress-site` and `yarn create kawapress my-kawapress-site` do the same thing. The scaffolder asks for a site title and a default language, and can install dependencies for you.
58
+
59
+ If you would rather see every file from the start, set the site up by hand:
60
+
50
61
  ```sh
51
62
  mkdir my-kawapress-site
52
63
  cd my-kawapress-site
package/README.zh-CN.md CHANGED
@@ -16,7 +16,7 @@
16
16
  </p>
17
17
 
18
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>
19
+ <a href="https://www.npmjs.com/package/kawapress"><img src="https://img.shields.io/npm/v/kawapress?label=npm&color=42b883" alt="npm 版本"></a>
20
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
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
22
  <img src="https://img.shields.io/badge/Node.js-%E2%89%A522.12-339933?logo=nodedotjs&logoColor=white" alt="Node.js 22.12 或更高版本">
@@ -28,8 +28,7 @@
28
28
  <a href="https://github.com/ShenQingchuan/kawapress/blob/main/README.md">English</a>
29
29
  </p>
30
30
 
31
- > [!IMPORTANT]
32
- > KawaPress 目前处于 beta 阶段,适合试用和早期项目。0.1.0 之前,公开 API 仍可能调整;现阶段使用时请固定具体版本。
31
+ 使用 KawaPress 时遇到任何问题,欢迎到 [提交 Issue](https://github.com/ShenQingchuan/kawapress/issues) 反馈,一起参与本项目的早期建设。
33
32
 
34
33
  ## 为什么选择 KawaPress?
35
34
 
@@ -47,6 +46,18 @@ KawaPress 是一个独立项目,不是 VitePress 的分支或配置兼容层
47
46
 
48
47
  请先准备 [Node.js](https://nodejs.org/) 22.12 或更高版本。
49
48
 
49
+ 用脚手架创建新站点:
50
+
51
+ ```sh
52
+ npm create kawapress@latest my-kawapress-site
53
+ cd my-kawapress-site
54
+ npm run dev
55
+ ```
56
+
57
+ `pnpm create kawapress my-kawapress-site` 和 `yarn create kawapress my-kawapress-site` 的作用完全一样。脚手架会询问站点标题和默认语言,也可以顺便帮你安装依赖。
58
+
59
+ 如果你更想从零看清每个文件,可以手动创建:
60
+
50
61
  ```sh
51
62
  mkdir my-kawapress-site
52
63
  cd my-kawapress-site
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kawapress",
3
3
  "type": "module",
4
- "version": "0.0.1",
4
+ "version": "0.1.0",
5
5
  "description": "A Vue-centric static site generator",
6
6
  "license": "MIT",
7
7
  "homepage": "https://shenqingchuan.github.io/kawapress/",
@@ -36,6 +36,11 @@
36
36
  "import": "./src/client/index.ts",
37
37
  "default": "./src/client/index.ts"
38
38
  },
39
+ "./generator": {
40
+ "types": "./src/generator.ts",
41
+ "import": "./src/generator.ts",
42
+ "default": "./src/generator.ts"
43
+ },
39
44
  "./nagi": {
40
45
  "types": "./src/nagi.ts",
41
46
  "import": "./src/nagi.ts",
@@ -76,7 +81,6 @@
76
81
  "tinyglobby": "^0.2.17",
77
82
  "vite": "^8.2.2",
78
83
  "vue": "^3.5.41",
79
- "vue-router": "^5.2.0",
80
- "@kawapress/preset-nagi": "0.0.1"
84
+ "@kawapress/preset-nagi": "0.1.0"
81
85
  }
82
86
  }
package/src/api/config.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { DeadLinkConfig } from '../core/dead-links'
2
+ import type { HeadConfig } from '../core/head'
1
3
  import type { LocaleConfig } from '../core/site'
2
4
  import type { KawaPressPlugin } from './plugin'
3
5
 
@@ -6,9 +8,12 @@ export interface KawapressConfig<ThemeConfig extends object = object> {
6
8
  base?: string
7
9
  srcDir?: string
8
10
  publicDir?: string
11
+ head?: HeadConfig[]
9
12
  themeConfig?: ThemeConfig
10
13
  locales?: Record<string, LocaleConfig<ThemeConfig>>
11
14
  plugins?: KawaPressPlugin[]
15
+ /** Internal link checking. Defaults to `{ level: 'error' }`; `false` disables it. */
16
+ deadLinks?: false | DeadLinkConfig
12
17
  }
13
18
 
14
19
  export function defineConfig<ThemeConfig extends object = object>(
package/src/api/plugin.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import type { MarkdownExit } from 'markdown-exit'
2
2
  import type { UserConfig } from 'vite'
3
3
  import type { App } from 'vue'
4
- import type { Router } from 'vue-router'
4
+ import type { OutletItemInput, OutletName } from '../core/outlet'
5
+ import type { Router } from '../core/router'
5
6
  import type { PageData, SiteConfig } from '../core/site'
6
7
 
7
8
  export type MaybePromise<T> = T | Promise<T>
@@ -25,10 +26,23 @@ export interface BuildArtifactsContext {
25
26
  importModule: <T = unknown>(path: string) => Promise<T>
26
27
  }
27
28
 
29
+ /** Where the page being processed comes from. Generator-only; never sent to the browser. */
30
+ export interface PageDataContext {
31
+ /** Absolute path of the Markdown source file. */
32
+ file: string
33
+ /** Source path relative to srcDir, for example `/guide/intro.md`. */
34
+ sourcePath: string
35
+ }
36
+
37
+ export type PageDataHandler = (
38
+ pageData: PageData,
39
+ context: Readonly<PageDataContext>,
40
+ ) => MaybePromise<void>
41
+
28
42
  export interface GeneratorPluginAPI {
29
43
  config: (handler: GeneratorPluginHandler<SiteConfig>) => void
30
44
  markdown: (handler: GeneratorPluginHandler<MarkdownExit>) => void
31
- pageData: (handler: GeneratorPluginHandler<PageData>) => void
45
+ pageData: (handler: PageDataHandler) => void
32
46
  pageArtifact: (
33
47
  handler: GeneratorPluginHandler<Readonly<PageBuildArtifact>>,
34
48
  ) => void
@@ -53,6 +67,8 @@ export function definePlugin(plugin: KawaPressPlugin): KawaPressPlugin {
53
67
  export type RuntimePluginHandler<T> = (value: T) => MaybePromise<void>
54
68
 
55
69
  export interface RuntimePluginAPI {
70
+ /** Places a component in a theme outlet. */
71
+ addToOutlet: (outlet: OutletName, item: OutletItemInput) => void
56
72
  vueApp: (handler: RuntimePluginHandler<App>) => void
57
73
  router: (handler: RuntimePluginHandler<Router>) => void
58
74
  }
package/src/cli.ts CHANGED
@@ -2,6 +2,10 @@ import { performance } from 'node:perf_hooks'
2
2
  import process from 'node:process'
3
3
  import { defineCommand, runMain } from 'citty'
4
4
  import { version } from '../package.json'
5
+ import {
6
+ ensureProductionNodeEnv,
7
+ warnAboutReplacedNodeEnv,
8
+ } from './server/build-node-env'
5
9
 
6
10
  const dev = defineCommand({
7
11
  meta: { name: 'dev', description: 'Start the dev server' },
@@ -22,6 +26,11 @@ const dev = defineCommand({
22
26
  const build = defineCommand({
23
27
  meta: { name: 'build', description: 'Build the static site' },
24
28
  async run() {
29
+ // Pinned before `./server/build` is imported: that import chain reaches
30
+ // `@vue/compiler-core` through Vite's Vue plugin, and Vue picks its
31
+ // development or production compiler the moment the module is required.
32
+ // A later fix-up could no longer strip template comments from the output.
33
+ warnAboutReplacedNodeEnv(ensureProductionNodeEnv(process.env))
25
34
  const { buildSite } = await import('./server/build')
26
35
  await buildSite(process.cwd())
27
36
  },
@@ -29,9 +38,16 @@ const build = defineCommand({
29
38
 
30
39
  const preview = defineCommand({
31
40
  meta: { name: 'preview', description: 'Preview the built site' },
32
- async run() {
41
+ args: {
42
+ port: {
43
+ type: 'string',
44
+ description: 'Port to listen on',
45
+ default: '4173',
46
+ },
47
+ },
48
+ async run({ args }) {
33
49
  const { previewSite } = await import('./server/preview')
34
- await previewSite(process.cwd())
50
+ await previewSite(process.cwd(), { port: parsePort(args.port) })
35
51
  },
36
52
  })
37
53
 
@@ -48,4 +64,14 @@ export const main = defineCommand({
48
64
  },
49
65
  })
50
66
 
67
+ function parsePort(port: string): number {
68
+ const parsed = Number(port)
69
+ if (!Number.isInteger(parsed)) {
70
+ throw new TypeError(
71
+ `KawaPress: --port must be an integer, got ${JSON.stringify(port)}.`,
72
+ )
73
+ }
74
+ return parsed
75
+ }
76
+
51
77
  runMain(main)
package/src/client/app.ts CHANGED
@@ -1,27 +1,57 @@
1
- import type { Plugin } from 'vue'
1
+ import type { App, Plugin } from 'vue'
2
+ import type { OutletRegistry } from '../core/outlet'
3
+ import type { PageTable } from '../core/page-manifest'
4
+ import type { Router } from '../core/router'
2
5
  import { runtimePlugins } from 'virtual:kawapress-runtime-plugins'
3
6
  import { createSSRApp } from 'vue'
4
7
  import { createRuntimePluginRunner } from '../plugin/runtime-runner'
8
+ import KawaOutlet from './components/KawaOutlet.vue'
5
9
  import Root from './components/Root.vue'
6
- import { createAppRouter } from './router'
10
+ import { createOutletRenderStore, outletRegistryKey, outletRenderStoreKey } from './outlet'
11
+ import { createAppRouter } from './router/app-router'
12
+ import { routerKey } from './router/injection'
7
13
 
8
14
  export interface CreateKawapressAppOptions {
9
15
  head: Plugin
16
+ /**
17
+ * Pages of the site. A dev server and the SSR build hand over module loaders;
18
+ * the browser of a build hands over the chunk files its page table names.
19
+ */
20
+ pages: PageTable
21
+ }
22
+
23
+ export interface KawapressApp {
24
+ app: App
25
+ router: Router
26
+ outlets: OutletRegistry
27
+ /** See {@link import('./router/app-router').AppRouter.start}. */
28
+ start: () => Promise<void>
29
+ /** See {@link import('./router/app-router').AppRouter.adoptRequestedUrl}. */
30
+ adoptRequestedUrl: () => Promise<void>
10
31
  }
11
32
 
12
33
  export async function createKawapressApp(
13
- { head }: CreateKawapressAppOptions,
14
- ) {
15
- const router = createAppRouter()
34
+ { head, pages }: CreateKawapressAppOptions,
35
+ ): Promise<KawapressApp> {
36
+ const { router, start, adoptRequestedUrl } = createAppRouter(pages)
16
37
  const app = createSSRApp(Root)
17
- app.use(router)
38
+ app.provide(routerKey, router)
18
39
  app.use(head)
40
+ // Plugin setup runs before the app is touched, so the collected outlets are
41
+ // provided before any `vueApp()` handler runs. Runtime plugins can then read
42
+ // the registry through the app context, exactly like a theme component does.
19
43
  const pluginRunner = await createRuntimePluginRunner(runtimePlugins)
44
+ app.provide(outletRegistryKey, pluginRunner.outlets)
45
+ app.provide(outletRenderStoreKey, createOutletRenderStore())
46
+ app.component('KawaOutlet', KawaOutlet)
20
47
  await pluginRunner.runVueApp(app)
21
48
  await pluginRunner.runRouter(router)
22
49
 
23
50
  return {
24
51
  app,
25
52
  router,
53
+ outlets: pluginRunner.outlets,
54
+ start,
55
+ adoptRequestedUrl,
26
56
  }
27
57
  }
@@ -0,0 +1,36 @@
1
+ <script setup lang="ts">
2
+ import type { OutletItem, OutletName } from '../../core/outlet'
3
+ import { computed, onUnmounted } from 'vue'
4
+ import { assertOutletName, getOutletItems } from '../../core/outlet'
5
+ import { recordRenderedOutlet, useOutletRegistry, useOutletRenderStore } from '../outlet'
6
+
7
+ const props = defineProps<{
8
+ name: OutletName
9
+ }>()
10
+
11
+ defineSlots<{
12
+ /** Full control over the outlet: filter, wrap, or replace the items. */
13
+ default?: (props: { items: readonly OutletItem[] }) => unknown
14
+ }>()
15
+
16
+ assertOutletName(props.name, '<KawaOutlet>')
17
+
18
+ const registry = useOutletRegistry('<KawaOutlet>')
19
+ const items = computed(() => getOutletItems(registry, props.name))
20
+
21
+ const renderStore = useOutletRenderStore()
22
+ renderStore?.mount(props.name)
23
+ onUnmounted(() => renderStore?.unmount(props.name))
24
+
25
+ recordRenderedOutlet(props.name)
26
+ </script>
27
+
28
+ <template>
29
+ <slot :items="items">
30
+ <component
31
+ :is="item.component"
32
+ v-for="item in items"
33
+ :key="item.id"
34
+ />
35
+ </slot>
36
+ </template>
@@ -1,11 +1,13 @@
1
1
  <script setup lang="ts">
2
2
  import { useHead } from '@unhead/vue'
3
+ import { headConfigToUnheadInput } from '../../core/head'
3
4
  import { resolveDocumentTitle } from '../../core/page-metadata'
4
5
  import { usePageData, useSite } from '../composables'
5
6
 
6
7
  const site = useSite()
7
8
  const page = usePageData()
8
9
 
10
+ // Registered first so that user head tags can replace the generated description.
9
11
  useHead(() => ({
10
12
  htmlAttrs: {
11
13
  lang: site.value.lang,
@@ -23,6 +25,11 @@ useHead(() => ({
23
25
  }]
24
26
  : [],
25
27
  }))
28
+
29
+ // Later entries win on duplicate tags, so the order is site, locale, then page.
30
+ useHead(() => headConfigToUnheadInput(site.value.head))
31
+ useHead(() => headConfigToUnheadInput(site.value.localeHead))
32
+ useHead(() => headConfigToUnheadInput(page.value?.head ?? []))
26
33
  </script>
27
34
 
28
35
  <template>
@@ -2,9 +2,9 @@ import type { ComputedRef } from 'vue'
2
2
  import type { LocaleLink, PageData, ResolvedSiteData, SiteData } from '../core/site'
3
3
  import { site } from 'virtual:kawapress-site'
4
4
  import { computed } from 'vue'
5
- import { useRoute } from 'vue-router'
6
5
  import { getLocaleIndex, resolveLocaleLinks, resolveSiteDataByPath } from '../core/locale'
7
6
  import { getPageData } from './page-data'
7
+ import { useRoute } from './router/injection'
8
8
 
9
9
  export interface LocaleContext {
10
10
  localeIndex: ComputedRef<string>
@@ -17,7 +17,7 @@ export function useSite<ThemeConfig extends object = object>(): ComputedRef<Reso
17
17
  const route = useRoute()
18
18
  return computed(() => resolveSiteDataByPath(
19
19
  site as SiteData<ThemeConfig>,
20
- route.path,
20
+ route.value.path,
21
21
  ))
22
22
  }
23
23
 
@@ -28,8 +28,8 @@ export function useThemeConfig<ThemeConfig extends object = object>(): ComputedR
28
28
 
29
29
  export function useLocale(): LocaleContext {
30
30
  const route = useRoute()
31
- const localeIndex = computed(() => getLocaleIndex(site, route.path))
32
- const locales = computed(() => resolveLocaleLinks(site, route.fullPath))
31
+ const localeIndex = computed(() => getLocaleIndex(site, route.value.path))
32
+ const locales = computed(() => resolveLocaleLinks(site, route.value.fullPath))
33
33
  const locale = computed(() => locales.value.find(
34
34
  item => item.localeIndex === localeIndex.value,
35
35
  ))
@@ -47,5 +47,5 @@ export function useLocale(): LocaleContext {
47
47
 
48
48
  export function usePageData(): ComputedRef<PageData | undefined> {
49
49
  const route = useRoute()
50
- return computed(() => getPageData(route.path))
50
+ return computed(() => getPageData(route.value.path))
51
51
  }
@@ -1,11 +1,16 @@
1
1
  import { createHead } from '@unhead/vue/client'
2
+ import { pages } from 'virtual:kawapress-pages'
2
3
  import { createKawapressApp } from '../app'
3
4
 
4
- async function bootstrap() {
5
+ async function bootstrap(): Promise<void> {
5
6
  const head = createHead()
6
- const { app, router } = await createKawapressApp({ head })
7
- await router.isReady()
7
+ const { app, start, adoptRequestedUrl } = await createKawapressApp({ head, pages })
8
+ // The first render has to match the served HTML, which only describes a path.
9
+ await start()
8
10
  app.mount('#app')
11
+ // The query, the hash, the not-found document and encoded paths are adopted
12
+ // afterwards: no page load, no history entry.
13
+ await adoptRequestedUrl()
9
14
  }
10
15
 
11
16
  bootstrap()
@@ -1,9 +1,12 @@
1
+ import type { OutletRegistry } from '../../core/outlet'
1
2
  import { createHead } from '@unhead/vue/server'
2
3
  import { renderToString } from '@vue/server-renderer'
3
4
  import consola from 'consola'
5
+ import { pageModules, pages } from 'virtual:kawapress-pages'
4
6
  import { createKawapressApp } from '../app'
7
+ import { getRenderedOutlets } from '../outlet'
5
8
 
6
- export { pages } from 'virtual:kawapress-pages'
9
+ export { pageModules, pages }
7
10
  export { site } from 'virtual:kawapress-site'
8
11
 
9
12
  export interface RenderResult {
@@ -11,20 +14,47 @@ export interface RenderResult {
11
14
  found: boolean
12
15
  head: string
13
16
  htmlAttrs: string
17
+ /** Outlets the rendered page actually mounted. */
18
+ outlets: string[]
19
+ /** Module id of the rendered page, the id the client manifest knows it by. */
20
+ pageModuleId: string | undefined
21
+ }
22
+
23
+ // The registry only depends on runtime plugin setup, so any render returns the
24
+ // same one. Prerendering renders pages one after another and reads it afterwards.
25
+ let latestOutletRegistry: OutletRegistry | undefined
26
+
27
+ export function getOutletRegistry(): OutletRegistry {
28
+ if (!latestOutletRegistry) {
29
+ throw new Error(
30
+ 'KawaPress: the outlet registry is not ready. Render at least one page with render() first.',
31
+ )
32
+ }
33
+ return latestOutletRegistry
14
34
  }
15
35
 
16
36
  export async function render(url: string): Promise<RenderResult> {
17
37
  const head = createHead()
18
- const { app, router } = await createKawapressApp({ head })
38
+ const { app, router, outlets } = await createKawapressApp({ head, pages })
39
+ latestOutletRegistry = outlets
19
40
 
20
41
  app.config.errorHandler = (error) => {
21
42
  consola.error('KawaPress SSR error:', error)
22
43
  }
23
44
 
45
+ // One render, one navigation: the router looks the path up in the page table
46
+ // and loads that page, instead of rebuilding a matcher for every request.
24
47
  await router.push(url)
25
- await router.isReady()
26
- const found = router.currentRoute.value.name !== 'not-found'
27
- const html = await renderToString(app)
48
+ const current = router.currentRoute.value
49
+ const ssrContext: Record<string, unknown> = {}
50
+ const html = await renderToString(app, ssrContext)
28
51
  const { headTags, htmlAttrs } = await head.render()
29
- return { html, found, head: headTags, htmlAttrs }
52
+ return {
53
+ html,
54
+ found: current.found,
55
+ head: headTags,
56
+ htmlAttrs,
57
+ outlets: getRenderedOutlets(ssrContext),
58
+ pageModuleId: pageModules[current.path],
59
+ }
30
60
  }
@@ -1,5 +1,11 @@
1
1
  export { withBase } from '../core/base'
2
+ export { resolveLocaleIndex } from '../core/locale'
3
+ export { OUTLET_NAMES } from '../core/outlet'
4
+ export type { OutletItem, OutletName, OutletRegistry } from '../core/outlet'
5
+ export type { Route, RouteGuard, RouteHook, Router } from '../core/router'
6
+ export { default as KawaOutlet } from './components/KawaOutlet.vue'
2
7
  export { useLocale, usePageData, useSite, useThemeConfig } from './composables'
3
8
  export type { LocaleContext } from './composables'
4
- export { RouterLink, RouterView, useRouter } from 'vue-router'
5
- export type { Router } from 'vue-router'
9
+ export { useRoute, useRouter } from './router/injection'
10
+ export { default as RouterLink } from './router/RouterLink'
11
+ export { default as RouterView } from './router/RouterView'
@@ -0,0 +1,85 @@
1
+ import type { InjectionKey } from 'vue'
2
+ import type { OutletName, OutletRegistry } from '../core/outlet'
3
+ import { inject, useSSRContext } from 'vue'
4
+
5
+ /** Registry handed to the app by core once every runtime plugin has run. */
6
+ export const outletRegistryKey: InjectionKey<OutletRegistry> = Symbol('kawapress:outlet-registry')
7
+
8
+ /** Per-app mount bookkeeping. Never module-level: SSR builds one app per request. */
9
+ export const outletRenderStoreKey: InjectionKey<OutletRenderStore> = Symbol('kawapress:outlet-render-store')
10
+
11
+ /** Key on the SSR context that collects the outlets a page rendered. */
12
+ export const SSR_OUTLETS_CONTEXT_KEY = 'kawapressOutlets'
13
+
14
+ export interface OutletRenderStore {
15
+ mount: (outlet: OutletName) => void
16
+ unmount: (outlet: OutletName) => void
17
+ }
18
+
19
+ /**
20
+ * Counts mounted outlets per app so a duplicated outlet warns once instead of
21
+ * on every navigation, and stays silent on the server where every request
22
+ * would repeat the same warning.
23
+ */
24
+ export function createOutletRenderStore(): OutletRenderStore {
25
+ const mountedCounts = new Map<OutletName, number>()
26
+ const warned = new Set<OutletName>()
27
+
28
+ return {
29
+ mount(outlet) {
30
+ const count = (mountedCounts.get(outlet) ?? 0) + 1
31
+ mountedCounts.set(outlet, count)
32
+ if (count < 2 || warned.has(outlet) || !import.meta.env.DEV || import.meta.env.SSR) {
33
+ return
34
+ }
35
+ warned.add(outlet)
36
+ console.warn(
37
+ `[KawaPress] Outlet ${JSON.stringify(outlet)} is mounted more than once in this app. `
38
+ + `Render each outlet once per page, otherwise every item appears twice `
39
+ + `(duplicate DOM ids, duplicate keyboard shortcuts).`,
40
+ )
41
+ },
42
+ unmount(outlet) {
43
+ const count = (mountedCounts.get(outlet) ?? 1) - 1
44
+ if (count > 0) {
45
+ mountedCounts.set(outlet, count)
46
+ }
47
+ else {
48
+ mountedCounts.delete(outlet)
49
+ }
50
+ },
51
+ }
52
+ }
53
+
54
+ export function useOutletRegistry(context: string): OutletRegistry {
55
+ const registry = inject(outletRegistryKey, undefined)
56
+ if (!registry) {
57
+ throw new Error(
58
+ `KawaPress: ${context} was rendered outside a KawaPress app. `
59
+ + `Render it from a theme layout, or create the app with createKawapressApp().`,
60
+ )
61
+ }
62
+ return registry
63
+ }
64
+
65
+ export function useOutletRenderStore(): OutletRenderStore | undefined {
66
+ return inject(outletRenderStoreKey, undefined)
67
+ }
68
+
69
+ /** Records the outlet in the SSR context so prerendering can report unused items. */
70
+ export function recordRenderedOutlet(outlet: OutletName): void {
71
+ if (!import.meta.env.SSR) {
72
+ return
73
+ }
74
+ const context = useSSRContext()
75
+ if (!context) {
76
+ return
77
+ }
78
+ const rendered = (context[SSR_OUTLETS_CONTEXT_KEY] ??= new Set<string>())
79
+ rendered.add(outlet)
80
+ }
81
+
82
+ export function getRenderedOutlets(context: Record<string, unknown> | undefined): string[] {
83
+ const rendered = context?.[SSR_OUTLETS_CONTEXT_KEY]
84
+ return rendered instanceof Set ? [...rendered] : []
85
+ }
@@ -1,25 +1,32 @@
1
1
  import type { Component } from 'vue'
2
+ import type { PageTable } from '../core/page-manifest'
2
3
  import type { PageData } from '../core/site'
3
4
 
4
- interface PageModule {
5
- default: Component
6
- __pageData?: PageData
7
- }
8
-
9
5
  // path-level cache: same content for every request, safe under SSR concurrency
10
6
  const cache = new Map<string, PageData>()
11
7
 
12
- export function wrapPageLoader(path: string, loader: () => Promise<PageModule>) {
13
- return async (): Promise<Component> => {
14
- const mod = await loader()
15
- if (mod.__pageData) {
16
- cache.set(path, {
17
- ...mod.__pageData,
18
- path,
19
- })
20
- }
21
- return mod.default
8
+ /**
9
+ * Load the page component of `path` and remember the page data it carries.
10
+ * Returns `null` for a path the page table does not know, which is what the
11
+ * router renders as the not-found page.
12
+ */
13
+ export async function loadPage(
14
+ path: string,
15
+ pages: PageTable,
16
+ ): Promise<Component | null> {
17
+ const load = pages[path]
18
+ if (!load) {
19
+ return null
20
+ }
21
+
22
+ const module = await load()
23
+ if (module.__pageData) {
24
+ cache.set(path, {
25
+ ...module.__pageData,
26
+ path,
27
+ })
22
28
  }
29
+ return module.default
23
30
  }
24
31
 
25
32
  export function getPageData(path: string): PageData | undefined {