kawapress 0.0.1 → 0.2.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 (73) hide show
  1. package/README.md +17 -5
  2. package/README.zh-CN.md +17 -5
  3. package/package.json +7 -3
  4. package/src/api/config.ts +12 -16
  5. package/src/api/plugin.ts +20 -3
  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 +11 -10
  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 +23 -16
  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 +223 -21
  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/extension-points.ts +64 -0
  37. package/src/core/head.ts +207 -0
  38. package/src/core/heading-title.ts +78 -0
  39. package/src/core/hydration-plan.ts +79 -0
  40. package/src/core/locale.ts +28 -18
  41. package/src/core/not-found.ts +22 -0
  42. package/src/core/outlet.ts +110 -0
  43. package/src/core/page-chunk.ts +50 -0
  44. package/src/core/page-manifest.ts +53 -0
  45. package/src/core/router.ts +46 -0
  46. package/src/core/site.ts +19 -19
  47. package/src/core/tokens.ts +59 -0
  48. package/src/generator/config.ts +93 -13
  49. package/src/generator/data/context.ts +1 -0
  50. package/src/generator/git.ts +79 -0
  51. package/src/generator/pages.ts +126 -0
  52. package/src/generator/runtime-dependencies.ts +280 -0
  53. package/src/generator/vite/app-chunk.ts +65 -0
  54. package/src/generator/vite/config.ts +98 -10
  55. package/src/generator/vite/page-inputs.ts +22 -0
  56. package/src/generator/vite/plugins/dev-dead-links.ts +72 -0
  57. package/src/generator/vite/plugins/pages.ts +162 -114
  58. package/src/generator.ts +13 -0
  59. package/src/index.ts +30 -2
  60. package/src/plugin/execution.ts +17 -13
  61. package/src/plugin/generator-runner.ts +8 -3
  62. package/src/plugin/outlet-collector.ts +69 -0
  63. package/src/plugin/runtime-runner.ts +7 -1
  64. package/src/server/build-node-env.ts +48 -0
  65. package/src/server/build.ts +50 -4
  66. package/src/server/check-dead-links.ts +88 -0
  67. package/src/server/page-assets.ts +138 -0
  68. package/src/server/prerender.ts +134 -27
  69. package/src/server/preview-routing.ts +64 -0
  70. package/src/server/preview.ts +78 -11
  71. package/src/server/request-handler.ts +36 -12
  72. package/src/server/template.ts +31 -0
  73. package/src/client/router.ts +0 -81
@@ -1,25 +1,32 @@
1
1
  import type { Component } from 'vue'
2
- import type { PageData } from '../core/site'
3
-
4
- interface PageModule {
5
- default: Component
6
- __pageData?: PageData
7
- }
2
+ import type { PageData } from '../core/extension-points'
3
+ import type { PageTable } from '../core/page-manifest'
8
4
 
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 {
@@ -0,0 +1,138 @@
1
+ import type { BuiltPageEntry, BuiltPageTable, PageLoader, PageModule, PageTable } from '../core/page-manifest'
2
+ import { withBase } from '../core/base'
3
+ import { pageChunkFileName } from '../core/page-chunk'
4
+ import { PAGE_TABLE_META } from '../core/page-manifest'
5
+
6
+ /** Stylesheet requests already started, so a page never loads its CSS twice. */
7
+ const styleLoads = new Map<string, Promise<void>>()
8
+ /** Module preloads already inserted by the router. */
9
+ const preloadedModules = new Set<string>()
10
+
11
+ /** URL of the page table, taken from the `<meta>` the prerendered HTML carries. */
12
+ export function readPageTableUrl(doc: Document = document): string {
13
+ const url = doc
14
+ .querySelector(`meta[name="${PAGE_TABLE_META}"]`)
15
+ ?.getAttribute('content')
16
+
17
+ if (!url) {
18
+ throw new Error(
19
+ `KawaPress: the served HTML has no <meta name="${PAGE_TABLE_META}"> tag, `
20
+ + `so the browser cannot find the page table. `
21
+ + `The document was probably not written by kawapress build; `
22
+ + `in dev, the page table comes from the dev server instead.`,
23
+ )
24
+ }
25
+ return url
26
+ }
27
+
28
+ /** Load the built page table and turn it into page loaders. */
29
+ export async function loadPageTable(
30
+ url: string,
31
+ base: string,
32
+ doc: Document = document,
33
+ ): Promise<PageTable> {
34
+ const table = (await import(/* @vite-ignore */ url) as { default: BuiltPageTable }).default
35
+ return createPageTable(table, base, doc)
36
+ }
37
+
38
+ /** Turn the serialised table into the loaders the router runs. */
39
+ export function createPageTable(
40
+ table: BuiltPageTable,
41
+ base: string,
42
+ doc: Document = document,
43
+ ): PageTable {
44
+ return Object.fromEntries(Object.entries(table).map(
45
+ ([path, entry]) => [path, createPageLoader(path, entry, base, doc)],
46
+ ))
47
+ }
48
+
49
+ /**
50
+ * Loader of one built page: the table holds the content hash of the page chunk,
51
+ * the route supplies the rest of its file name. Warming the browser for the
52
+ * chunk and its extra files, then waiting for the page CSS, happens before the
53
+ * import, so the chunk travels in parallel with its stylesheet instead of after
54
+ * it.
55
+ */
56
+ export function createPageLoader(
57
+ path: string,
58
+ entry: BuiltPageEntry,
59
+ base: string,
60
+ doc: Document = document,
61
+ ): PageLoader {
62
+ const [hash, js = [], css = []] = typeof entry === 'string' ? [entry] : entry
63
+
64
+ return async () => {
65
+ const url = withBase(pageChunkFileName(path, hash), base)
66
+ for (const href of js) {
67
+ preloadModule(withBase(href, base), doc)
68
+ }
69
+ await Promise.all(css.map(href => loadStyle(withBase(href, base), doc)))
70
+ return await import(/* @vite-ignore */ url) as PageModule
71
+ }
72
+ }
73
+
74
+ /** Insert a module preload once; the later `import()` reuses it. */
75
+ export function preloadModule(href: string, doc: Document = document): void {
76
+ if (preloadedModules.has(href)) {
77
+ return
78
+ }
79
+ preloadedModules.add(href)
80
+ if (findLink(doc, 'modulepreload', href)) {
81
+ return
82
+ }
83
+ doc.head.append(createLink(doc, 'modulepreload', href))
84
+ }
85
+
86
+ /**
87
+ * Make sure the stylesheet for `href` is applied. The page CSS of the first
88
+ * document is already in the HTML head, so a page opened directly resolves at
89
+ * once; a client navigation inserts the link and waits for it.
90
+ */
91
+ export function loadStyle(href: string, doc: Document = document): Promise<void> {
92
+ const started = styleLoads.get(href)
93
+ if (started) {
94
+ return started
95
+ }
96
+
97
+ const link = findLink(doc, 'stylesheet', href) ?? insertStyleLink(href, doc)
98
+ const loading = link.sheet ? Promise.resolve() : waitForStyle(link)
99
+ styleLoads.set(href, loading)
100
+ return loading
101
+ }
102
+
103
+ function insertStyleLink(href: string, doc: Document): HTMLLinkElement {
104
+ const link = createLink(doc, 'stylesheet', href)
105
+ doc.head.append(link)
106
+ return link
107
+ }
108
+
109
+ function createLink(
110
+ doc: Document,
111
+ rel: string,
112
+ href: string,
113
+ ): HTMLLinkElement {
114
+ const link = doc.createElement('link')
115
+ link.rel = rel
116
+ link.href = href
117
+ return link
118
+ }
119
+
120
+ function findLink(
121
+ doc: Document,
122
+ rel: string,
123
+ href: string,
124
+ ): HTMLLinkElement | undefined {
125
+ return Array.from(doc.head.querySelectorAll<HTMLLinkElement>(`link[rel="${rel}"]`))
126
+ .find(link => link.getAttribute('href') === href)
127
+ }
128
+
129
+ /**
130
+ * Resolves on `load` and on `error`: a stylesheet that fails to arrive must not
131
+ * keep the next page from showing.
132
+ */
133
+ function waitForStyle(link: HTMLLinkElement): Promise<void> {
134
+ return new Promise<void>((resolve) => {
135
+ link.addEventListener('load', () => resolve(), { once: true })
136
+ link.addEventListener('error', () => resolve(), { once: true })
137
+ })
138
+ }
@@ -0,0 +1,34 @@
1
+ import { site } from 'virtual:kawapress-site'
2
+ import { computed, defineComponent, h, useAttrs } from 'vue'
3
+ import { withBase } from '../../core/base'
4
+ import { useAppRouter } from './injection'
5
+ import { isSamePagePath, routePathOf } from './route'
6
+
7
+ /**
8
+ * A link to another page of the site, rendered as a plain `<a>` with the site
9
+ * base applied. Clicks are handled by the global link interceptor, so a page
10
+ * with a thousand sidebar links does no per-link work: the only thing this
11
+ * component computes is whether it is the current page.
12
+ */
13
+ export default defineComponent({
14
+ name: 'KawaRouterLink',
15
+ inheritAttrs: false,
16
+ props: {
17
+ /** Route path without the site base, for example `/guide/intro`. */
18
+ to: { type: String, required: true },
19
+ },
20
+ setup(props, { slots }) {
21
+ const router = useAppRouter()
22
+ const attrs = useAttrs()
23
+ const isCurrent = computed(() => isSamePagePath(
24
+ router.currentRoute.value.path,
25
+ routePathOf(props.to),
26
+ ))
27
+
28
+ return () => h('a', {
29
+ ...attrs,
30
+ 'href': withBase(props.to, site.base),
31
+ 'aria-current': isCurrent.value ? 'page' : undefined,
32
+ }, slots.default?.())
33
+ },
34
+ })
@@ -0,0 +1,25 @@
1
+ import type { Component } from 'vue'
2
+ import { defineComponent, h } from 'vue'
3
+ import NotFoundRoute from '../components/NotFoundRoute.vue'
4
+ import { useAppRouter } from './injection'
5
+
6
+ /**
7
+ * Renders the current page, or the not-found page for a route the page table
8
+ * does not know. Nothing is rendered while the first page is still loading; the
9
+ * app mounts only after that, so a reader never sees an empty frame.
10
+ */
11
+ export default defineComponent({
12
+ name: 'KawaRouterView',
13
+ setup() {
14
+ const router = useAppRouter()
15
+
16
+ return (): ReturnType<typeof h> | null => {
17
+ const route = router.currentRoute.value
18
+ if (!route.found) {
19
+ return h(NotFoundRoute)
20
+ }
21
+ const page: Component | null = router.page.value
22
+ return page === null ? null : h(page)
23
+ }
24
+ },
25
+ })
@@ -0,0 +1,84 @@
1
+ import type { PageTable } from '../../core/page-manifest'
2
+ import type { AppRouterInstance } from './router'
3
+ import { site } from 'virtual:kawapress-site'
4
+ import { resolveHydrationPlan } from '../../core/hydration-plan'
5
+ import { NOT_FOUND_DOCUMENT_META } from '../../core/not-found'
6
+ import { createBrowserHistory, createMemoryHistory } from './history'
7
+ import { installLinkInterceptor } from './link-interceptor'
8
+ import { reloadDocument } from './reload'
9
+ import { createRouter } from './router'
10
+
11
+ export interface AppRouter {
12
+ router: AppRouterInstance
13
+ /**
14
+ * Loads the page of the route the served HTML was rendered with, so the first
15
+ * render matches the markup exactly. Resolves before the app mounts.
16
+ */
17
+ start: () => Promise<void>
18
+ /**
19
+ * Points the router at the URL in the address bar once the app is hydrated,
20
+ * without a navigation and without a history entry. A no-op on the server.
21
+ */
22
+ adoptRequestedUrl: () => Promise<void>
23
+ }
24
+
25
+ export function createAppRouter(pages: PageTable): AppRouter {
26
+ if (import.meta.env.SSR) {
27
+ // Every render gets its own router: one table lookup and one page load, no
28
+ // matching structure and no state shared between requests.
29
+ const router = createRouter({ pages, history: createMemoryHistory() })
30
+ return {
31
+ router,
32
+ start: () => Promise.resolve(),
33
+ adoptRequestedUrl: () => Promise.resolve(),
34
+ }
35
+ }
36
+
37
+ const history = createBrowserHistory(site.base)
38
+ const router = createRouter({
39
+ pages,
40
+ history,
41
+ // A page chunk that cannot be loaded means the page table no longer matches
42
+ // the deployment. Reload the target URL so the server answers with fresh
43
+ // HTML instead of showing the not-found page for a page that exists.
44
+ onPageLoadError: (error, to) => {
45
+ if (!reloadDocument(to.fullPath, site.base)) {
46
+ reportPageLoadError(error, to.path)
47
+ }
48
+ },
49
+ })
50
+ // The served HTML only describes a path: static hosts ignore the query, the
51
+ // browser never sends the hash and the not-found document is served for every
52
+ // unknown URL. See resolveHydrationPlan().
53
+ const plan = resolveHydrationPlan({
54
+ isNotFoundDocument: document
55
+ .querySelector(`meta[name="${NOT_FOUND_DOCUMENT_META}"]`) !== null,
56
+ requestedLocation: history.location(),
57
+ hasPage: path => Object.hasOwn(pages, path),
58
+ })
59
+ installLinkInterceptor(router, pages, site.base)
60
+
61
+ return {
62
+ router,
63
+ start: () => router.enter(plan.startPath),
64
+ async adoptRequestedUrl() {
65
+ // An encoded page path is replaced by the decoded one it resolved to.
66
+ if (plan.replacePath !== undefined) {
67
+ history.replace(plan.replacePath)
68
+ }
69
+ if (plan.adoptPath !== undefined) {
70
+ await router.enter(plan.adoptPath)
71
+ }
72
+ },
73
+ }
74
+ }
75
+
76
+ /** A page chunk that even a fresh document load would ask for again, for example when offline. */
77
+ function reportPageLoadError(error: unknown, path: string): void {
78
+ console.error(
79
+ `[KawaPress] Could not load the page ${JSON.stringify(path)}, and a full reload would request `
80
+ + `the very same files again. Reload the page once the site is reachable, or after the `
81
+ + `deployment that replaced them finished.`,
82
+ error,
83
+ )
84
+ }
@@ -0,0 +1,53 @@
1
+ import { withBase, withoutBase } from '../../core/base'
2
+
3
+ /**
4
+ * Where the router reads and writes the current location. The browser
5
+ * implementation talks to `window.history`; the server keeps a plain string,
6
+ * which is all an SSR render needs.
7
+ */
8
+ export interface RouteHistory {
9
+ /** Current location, site base already removed; the path stays percent-encoded. */
10
+ location: () => string
11
+ push: (location: string) => void
12
+ replace: (location: string) => void
13
+ /** Calls `listener` whenever the browser moves through its own history. */
14
+ listen: (listener: (location: string) => void) => () => void
15
+ }
16
+
17
+ /** History of the browser: `pushState`/`replaceState` plus back and forward. */
18
+ export function createBrowserHistory(base: string): RouteHistory {
19
+ const readLocation = (): string => {
20
+ const path = withoutBase(window.location.pathname, base) ?? '/'
21
+ return `${path}${window.location.search}${window.location.hash}`
22
+ }
23
+
24
+ return {
25
+ location: readLocation,
26
+ push(location) {
27
+ window.history.pushState(null, '', withBase(location, base))
28
+ },
29
+ replace(location) {
30
+ window.history.replaceState(null, '', withBase(location, base))
31
+ },
32
+ listen(listener) {
33
+ const onPopState = () => listener(readLocation())
34
+ window.addEventListener('popstate', onPopState)
35
+ return () => window.removeEventListener('popstate', onPopState)
36
+ },
37
+ }
38
+ }
39
+
40
+ /** History of a server render: one location, no entries and no events. */
41
+ export function createMemoryHistory(location = '/'): RouteHistory {
42
+ let current = location
43
+ return {
44
+ location: () => current,
45
+ push(next) {
46
+ current = next
47
+ },
48
+ replace(next) {
49
+ current = next
50
+ },
51
+ listen: () => () => {},
52
+ }
53
+ }
@@ -0,0 +1,29 @@
1
+ import type { InjectionKey, ShallowRef } from 'vue'
2
+ import type { Route, Router } from '../../core/router'
3
+ import type { AppRouterInstance } from './router'
4
+ import { inject } from 'vue'
5
+
6
+ /** Injection key of the router a KawaPress app provides. */
7
+ export const routerKey: InjectionKey<AppRouterInstance> = Symbol('kawapress:router')
8
+
9
+ /** Router of the current app: navigation, guards and the current route. */
10
+ export function useRouter(): Router {
11
+ return useAppRouter()
12
+ }
13
+
14
+ /** Current route of the app, updated by every navigation. */
15
+ export function useRoute(): Readonly<ShallowRef<Route>> {
16
+ return useAppRouter().currentRoute
17
+ }
18
+
19
+ /** Internal access shared by `RouterView` and `RouterLink`. */
20
+ export function useAppRouter(): AppRouterInstance {
21
+ const router = inject(routerKey, undefined)
22
+ if (!router) {
23
+ throw new Error(
24
+ 'KawaPress: useRoute() and useRouter() need a KawaPress app. '
25
+ + 'Render the component from a theme layout, or create the app with createKawapressApp().',
26
+ )
27
+ }
28
+ return router
29
+ }
@@ -0,0 +1,67 @@
1
+ import type { PageTable } from '../../core/page-manifest'
2
+ import type { Router } from '../../core/router'
3
+ import { decodeUrlPathname, withoutBase } from '../../core/base'
4
+
5
+ /**
6
+ * Sends clicks on internal links through the router instead of the browser.
7
+ *
8
+ * The rules are the ones a reader expects from a documentation site: modified
9
+ * clicks, other buttons, new windows, downloads, external URLs and anything
10
+ * outside the site base keep their default behaviour, and so does a link to a
11
+ * path the page table does not know, because only the server can answer that
12
+ * with the not-found document.
13
+ */
14
+ export function installLinkInterceptor(
15
+ router: Router,
16
+ pages: PageTable,
17
+ base: string,
18
+ ): void {
19
+ if (import.meta.env.SSR) {
20
+ return
21
+ }
22
+
23
+ window.addEventListener('click', (event) => {
24
+ if (!isInterceptable(event)) {
25
+ return
26
+ }
27
+
28
+ const anchor = (event.target as Element | null)?.closest('a')
29
+ if (!anchor || anchor.target || anchor.hasAttribute('download')) {
30
+ return
31
+ }
32
+
33
+ const href = anchor.getAttribute('href')
34
+ // A bare fragment is handled by the browser: it moves the scroll container
35
+ // of the current page without touching the router.
36
+ if (!href || href.startsWith('#')) {
37
+ return
38
+ }
39
+
40
+ // Anything that does not resolve to this origin keeps its default
41
+ // behaviour: another site, but also `mailto:`, `tel:` or `javascript:`,
42
+ // whose URLs have no origin.
43
+ const url = new URL(anchor.href)
44
+ if (url.origin !== window.location.origin) {
45
+ return
46
+ }
47
+
48
+ const routePath = withoutBase(decodeUrlPathname(url.pathname), base)
49
+ if (routePath === undefined || !Object.hasOwn(pages, routePath)) {
50
+ return
51
+ }
52
+
53
+ event.preventDefault()
54
+ void router.push(`${routePath}${url.search}${url.hash}`).catch((error: unknown) => {
55
+ console.error('[KawaPress] Navigation failed:', error)
56
+ })
57
+ })
58
+ }
59
+
60
+ function isInterceptable(event: MouseEvent): boolean {
61
+ return !event.defaultPrevented
62
+ && event.button === 0
63
+ && !event.metaKey
64
+ && !event.ctrlKey
65
+ && !event.shiftKey
66
+ && !event.altKey
67
+ }
@@ -0,0 +1,34 @@
1
+ import { withBase } from '../../core/base'
2
+
3
+ /** The parts of `window.location` a document reload needs, so tests can pass a stub. */
4
+ export interface ReloadTarget {
5
+ pathname: string
6
+ search: string
7
+ hash: string
8
+ assign: (url: string) => void
9
+ }
10
+
11
+ /**
12
+ * Loads `location` as a whole new document.
13
+ *
14
+ * A page chunk that cannot be loaded is usually a stale page table after a
15
+ * redeploy: the chunk it names does not exist any more, so the current document
16
+ * cannot show the page by itself. Asking the server for fresh HTML is the only
17
+ * way out, and it also revalidates everything else the old document holds.
18
+ *
19
+ * @returns `false` when the target is already the open document, which would
20
+ * repeat the very same failure; the caller reports the error instead.
21
+ */
22
+ export function reloadDocument(
23
+ location: string,
24
+ base: string,
25
+ target: ReloadTarget = window.location,
26
+ ): boolean {
27
+ const url = withBase(location, base)
28
+ const current = `${target.pathname}${target.search}${target.hash}`
29
+ if (url === current) {
30
+ return false
31
+ }
32
+ target.assign(url)
33
+ return true
34
+ }
@@ -0,0 +1,82 @@
1
+ import type { PageTable } from '../../core/page-manifest'
2
+ import type { Route } from '../../core/router'
3
+ import { decodeUrlPathname } from '../../core/base'
4
+
5
+ /** Path, query and hash of a location; the delimiters stay with query and hash. */
6
+ export interface LocationParts {
7
+ path: string
8
+ /** Query including `?`, empty when the URL has none. */
9
+ search: string
10
+ /** Hash including `#`, empty when the URL has none. */
11
+ hash: string
12
+ }
13
+
14
+ /**
15
+ * Split a location into its parts. A percent-encoded path is decoded, because
16
+ * the page table is keyed by the paths the site author wrote.
17
+ */
18
+ export function parseLocation(location: string): LocationParts {
19
+ const hashIndex = location.indexOf('#')
20
+ const beforeHash = hashIndex === -1 ? location : location.slice(0, hashIndex)
21
+ const hash = hashIndex === -1 ? '' : location.slice(hashIndex)
22
+ const searchIndex = beforeHash.indexOf('?')
23
+ const search = searchIndex === -1 ? '' : beforeHash.slice(searchIndex)
24
+ const path = searchIndex === -1 ? beforeHash : beforeHash.slice(0, searchIndex)
25
+
26
+ return {
27
+ path: normalizePath(decodeUrlPathname(path)),
28
+ search,
29
+ hash,
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Query object of a location, parsed like `URLSearchParams`: every value is a
35
+ * string, and a key that appears more than once keeps all values in order.
36
+ */
37
+ export function parseQuery(search: string): Record<string, string | string[]> {
38
+ const query: Record<string, string | string[]> = {}
39
+ for (const [key, value] of new URLSearchParams(search)) {
40
+ const existing = query[key]
41
+ if (existing === undefined) {
42
+ query[key] = value
43
+ }
44
+ else if (Array.isArray(existing)) {
45
+ existing.push(value)
46
+ }
47
+ else {
48
+ query[key] = [existing, value]
49
+ }
50
+ }
51
+ return query
52
+ }
53
+
54
+ /** Resolve a location against the page table, without loading anything. */
55
+ export function resolveRoute(location: string, pages: PageTable): Route {
56
+ const { path, search, hash } = parseLocation(location)
57
+ return {
58
+ path,
59
+ fullPath: `${path}${search}${hash}`,
60
+ query: parseQuery(search),
61
+ hash,
62
+ found: Object.hasOwn(pages, path),
63
+ }
64
+ }
65
+
66
+ /** Path part of a location, without query and hash. */
67
+ export function routePathOf(location: string): string {
68
+ return parseLocation(location).path
69
+ }
70
+
71
+ /** Whether two route paths address the same page, ignoring a trailing slash. */
72
+ export function isSamePagePath(a: string, b: string): boolean {
73
+ return normalizeTrailingSlash(a) === normalizeTrailingSlash(b)
74
+ }
75
+
76
+ function normalizePath(path: string): string {
77
+ return path.startsWith('/') ? path : `/${path}`
78
+ }
79
+
80
+ function normalizeTrailingSlash(path: string): string {
81
+ return path.length > 1 ? path.replace(/\/$/, '') : path
82
+ }