@hamur/content 0.0.0-stage → 0.0.2

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 (183) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/chunks/bun-render-65mwzeq2.js +58 -0
  4. package/dist/chunks/bun-render-7jxnxg3v.js +714 -0
  5. package/dist/chunks/bun-render-mxhn5twt.js +130 -0
  6. package/dist/chunks/bun-render-w7fh3fg7.js +36 -0
  7. package/dist/src/adapters/html.js +134 -0
  8. package/dist/src/adapters/preact.js +126 -0
  9. package/dist/src/adapters/react.js +116 -0
  10. package/dist/src/adapters/solid.js +153 -0
  11. package/dist/src/adapters/svelte.js +90 -0
  12. package/dist/src/adapters/vue.js +166 -0
  13. package/dist/src/index.js +2732 -0
  14. package/dist/src/query.js +97 -0
  15. package/dist/src/render.js +12 -0
  16. package/dist/src/server/index.js +349 -0
  17. package/dist/types/src/adapters/html.d.ts +54 -0
  18. package/dist/types/src/adapters/page.d.ts +21 -0
  19. package/dist/types/src/adapters/preact.d.ts +53 -0
  20. package/dist/types/src/adapters/prose.d.ts +21 -0
  21. package/dist/types/src/adapters/react.d.ts +53 -0
  22. package/dist/types/src/adapters/search.d.ts +12 -0
  23. package/dist/types/src/adapters/solid.d.ts +54 -0
  24. package/dist/types/src/adapters/svelte-page.d.ts +9 -0
  25. package/dist/types/src/adapters/svelte-search.d.ts +9 -0
  26. package/dist/types/src/adapters/svelte.d.ts +24 -0
  27. package/dist/types/src/adapters/vue.d.ts +189 -0
  28. package/dist/types/src/build/api.d.ts +24 -0
  29. package/dist/types/src/build/dev-route.d.ts +4 -0
  30. package/dist/types/src/build/dev.d.ts +48 -0
  31. package/dist/types/src/build/graphql.d.ts +10 -0
  32. package/dist/types/src/build/image.d.ts +16 -0
  33. package/dist/types/src/build/index.d.ts +76 -0
  34. package/dist/types/src/build/live.d.ts +6 -0
  35. package/dist/types/src/build/prerender.d.ts +8 -0
  36. package/dist/types/src/build/query.d.ts +10 -0
  37. package/dist/types/src/build/raw.d.ts +23 -0
  38. package/dist/types/src/build/search.d.ts +9 -0
  39. package/dist/types/src/build/types.d.ts +16 -0
  40. package/dist/types/src/component.d.ts +10 -0
  41. package/dist/types/src/config.d.ts +6 -0
  42. package/dist/types/src/define.d.ts +14 -0
  43. package/dist/types/src/error.d.ts +4 -0
  44. package/dist/types/src/image.d.ts +15 -0
  45. package/dist/types/src/index.d.ts +64 -0
  46. package/dist/types/src/loaders/data.d.ts +12 -0
  47. package/dist/types/src/loaders/file.d.ts +3 -0
  48. package/dist/types/src/loaders/git.d.ts +27 -0
  49. package/dist/types/src/loaders/glob.d.ts +14 -0
  50. package/dist/types/src/module.d.ts +3 -0
  51. package/dist/types/src/query.d.ts +17 -0
  52. package/dist/types/src/render.d.ts +9 -0
  53. package/dist/types/src/runtime/client.d.ts +25 -0
  54. package/dist/types/src/runtime/dev-client.d.ts +4 -0
  55. package/dist/types/src/runtime/dev-plugin.d.ts +12 -0
  56. package/dist/types/src/runtime/dev-store.d.ts +5 -0
  57. package/dist/types/src/runtime/live.d.ts +36 -0
  58. package/dist/types/src/runtime/navigation.d.ts +35 -0
  59. package/dist/types/src/runtime/page-plugin.d.ts +2 -0
  60. package/dist/types/src/runtime/page-source.d.ts +12 -0
  61. package/dist/types/src/runtime/query.d.ts +100 -0
  62. package/dist/types/src/runtime/raw-path.d.ts +2 -0
  63. package/dist/types/src/runtime/refresh-body.d.ts +4 -0
  64. package/dist/types/src/runtime/search-loaders.d.ts +7 -0
  65. package/dist/types/src/runtime/search-plugin.d.ts +2 -0
  66. package/dist/types/src/runtime/search-store.d.ts +19 -0
  67. package/dist/types/src/runtime/search.d.ts +28 -0
  68. package/dist/types/src/runtime/sections.d.ts +36 -0
  69. package/dist/types/src/runtime/server-store.d.ts +4 -0
  70. package/dist/types/src/runtime/store.d.ts +31 -0
  71. package/dist/types/src/server/door-dev-static.d.ts +3 -0
  72. package/dist/types/src/server/door-dev.d.ts +4 -0
  73. package/dist/types/src/server/door-static.d.ts +2 -0
  74. package/dist/types/src/server/door.d.ts +3 -0
  75. package/dist/types/src/server/endpoint.d.ts +1 -0
  76. package/dist/types/src/server/graphql.d.ts +24 -0
  77. package/dist/types/src/server/index.d.ts +10 -0
  78. package/dist/types/src/server/install.d.ts +1 -0
  79. package/dist/types/src/server/live.d.ts +10 -0
  80. package/dist/types/src/server/query.d.ts +15 -0
  81. package/dist/types/src/server/refresh.d.ts +2 -0
  82. package/dist/types/src/server/rest.d.ts +62 -0
  83. package/dist/types/src/server/search.d.ts +5 -0
  84. package/dist/types/src/server-config.d.ts +12 -0
  85. package/dist/types/src/source.d.ts +24 -0
  86. package/dist/types/src/types.d.ts +293 -0
  87. package/package.json +140 -4
  88. package/src/adapters/ContentRenderer.svelte +27 -0
  89. package/src/adapters/ProseA.svelte +11 -0
  90. package/src/adapters/ProseBlockquote.svelte +7 -0
  91. package/src/adapters/ProseCode.svelte +7 -0
  92. package/src/adapters/ProseEm.svelte +7 -0
  93. package/src/adapters/ProseH1.svelte +7 -0
  94. package/src/adapters/ProseH2.svelte +7 -0
  95. package/src/adapters/ProseH3.svelte +7 -0
  96. package/src/adapters/ProseH4.svelte +7 -0
  97. package/src/adapters/ProseH5.svelte +7 -0
  98. package/src/adapters/ProseH6.svelte +7 -0
  99. package/src/adapters/ProseHr.svelte +5 -0
  100. package/src/adapters/ProseImg.svelte +5 -0
  101. package/src/adapters/ProseLi.svelte +7 -0
  102. package/src/adapters/ProseOl.svelte +7 -0
  103. package/src/adapters/ProseP.svelte +7 -0
  104. package/src/adapters/ProsePre.svelte +21 -0
  105. package/src/adapters/ProseStrong.svelte +7 -0
  106. package/src/adapters/ProseTable.svelte +7 -0
  107. package/src/adapters/ProseUl.svelte +7 -0
  108. package/src/adapters/html.ts +152 -0
  109. package/src/adapters/page.ts +52 -0
  110. package/src/adapters/preact.ts +154 -0
  111. package/src/adapters/prose.ts +55 -0
  112. package/src/adapters/react.ts +142 -0
  113. package/src/adapters/search.ts +32 -0
  114. package/src/adapters/solid.ts +183 -0
  115. package/src/adapters/svelte-defaults.ts +41 -0
  116. package/src/adapters/svelte-page.ts +29 -0
  117. package/src/adapters/svelte-search.ts +36 -0
  118. package/src/adapters/svelte.ts +30 -0
  119. package/src/adapters/test/OwnA.svelte +7 -0
  120. package/src/adapters/test/OwnH1.svelte +7 -0
  121. package/src/adapters/test/OwnPre.svelte +7 -0
  122. package/src/adapters/test/support.ts +106 -0
  123. package/src/adapters/vue.ts +182 -0
  124. package/src/build/api.ts +201 -0
  125. package/src/build/dev-route.ts +5 -0
  126. package/src/build/dev.ts +299 -0
  127. package/src/build/graphql.ts +197 -0
  128. package/src/build/image.ts +60 -0
  129. package/src/build/index.ts +597 -0
  130. package/src/build/live.ts +34 -0
  131. package/src/build/prerender.ts +34 -0
  132. package/src/build/query.ts +70 -0
  133. package/src/build/raw.ts +157 -0
  134. package/src/build/search.ts +64 -0
  135. package/src/build/types.ts +108 -0
  136. package/src/component.ts +86 -0
  137. package/src/config.ts +156 -0
  138. package/src/define.ts +33 -0
  139. package/src/env.d.ts +34 -0
  140. package/src/error.ts +4 -0
  141. package/src/image.ts +41 -0
  142. package/src/index.ts +103 -0
  143. package/src/loaders/data.ts +186 -0
  144. package/src/loaders/file.ts +53 -0
  145. package/src/loaders/git.ts +266 -0
  146. package/src/loaders/glob.ts +179 -0
  147. package/src/module.ts +26 -0
  148. package/src/query.ts +82 -0
  149. package/src/render.ts +16 -0
  150. package/src/runtime/client.ts +75 -0
  151. package/src/runtime/dev-client.ts +6 -0
  152. package/src/runtime/dev-plugin.ts +64 -0
  153. package/src/runtime/dev-store.ts +19 -0
  154. package/src/runtime/live.ts +331 -0
  155. package/src/runtime/navigation.ts +225 -0
  156. package/src/runtime/page-plugin.ts +13 -0
  157. package/src/runtime/page-source.ts +22 -0
  158. package/src/runtime/query.ts +605 -0
  159. package/src/runtime/raw-path.ts +2 -0
  160. package/src/runtime/refresh-body.ts +22 -0
  161. package/src/runtime/search-loaders.ts +14 -0
  162. package/src/runtime/search-plugin.ts +6 -0
  163. package/src/runtime/search-store.ts +73 -0
  164. package/src/runtime/search.ts +126 -0
  165. package/src/runtime/sections.ts +155 -0
  166. package/src/runtime/server-store.ts +12 -0
  167. package/src/runtime/store.ts +59 -0
  168. package/src/server/door-dev-static.ts +6 -0
  169. package/src/server/door-dev.ts +7 -0
  170. package/src/server/door-static.ts +4 -0
  171. package/src/server/door.ts +6 -0
  172. package/src/server/endpoint.ts +17 -0
  173. package/src/server/graphql.ts +59 -0
  174. package/src/server/index.ts +17 -0
  175. package/src/server/install.ts +6 -0
  176. package/src/server/live.ts +51 -0
  177. package/src/server/query.ts +46 -0
  178. package/src/server/refresh.ts +19 -0
  179. package/src/server/rest.ts +157 -0
  180. package/src/server/search.ts +22 -0
  181. package/src/server-config.ts +24 -0
  182. package/src/source.ts +99 -0
  183. package/src/types.ts +282 -0
@@ -0,0 +1,73 @@
1
+ import { searchIndex, type SearchHit, type SearchIndex } from "./search.ts"
2
+
3
+ export type SearchStatus = "idle" | "loading" | "ready" | "error"
4
+
5
+ export interface SearchOptions {
6
+ /** The most hits returned; default `20`. */
7
+ limit?: number
8
+ }
9
+
10
+ /** One collection's search index in the browser: loaded once, shared by every caller. */
11
+ export interface SearchCollection {
12
+ readonly status: SearchStatus
13
+ subscribe(listener: () => void): () => void
14
+ /** Loads the index; a load in flight is shared, a loaded index answers at once, a failed load is tried again. */
15
+ init(): Promise<void>
16
+ search(query: string, options?: SearchOptions): Promise<SearchHit[]>
17
+ /** `hamur dev`: an index loaded or loading is loaded again; an idle one stays idle. */
18
+ reset(): void
19
+ }
20
+
21
+ const DEFAULT_LIMIT = 20
22
+
23
+ export function createSearchCollection(load: () => Promise<{ default: SearchIndex }>): SearchCollection {
24
+ const listeners = new Set<() => void>()
25
+ let status: SearchStatus = "idle"
26
+ let loading: Promise<SearchIndex> | undefined
27
+ const set = (next: SearchStatus): void => {
28
+ status = next
29
+ for (const listener of [...listeners]) listener()
30
+ }
31
+ const ensure = (): Promise<SearchIndex> => {
32
+ if (!loading) {
33
+ set("loading")
34
+ const current: Promise<SearchIndex> = new Promise<{ default: SearchIndex }>((resolve) => resolve(load())).then(
35
+ (chunk) => {
36
+ if (loading === current) set("ready")
37
+ return chunk.default
38
+ },
39
+ (error: unknown) => {
40
+ if (loading === current) {
41
+ loading = undefined
42
+ set("error")
43
+ }
44
+ throw error
45
+ },
46
+ )
47
+ loading = current
48
+ }
49
+ return loading
50
+ }
51
+ return {
52
+ get status() {
53
+ return status
54
+ },
55
+ subscribe(listener) {
56
+ listeners.add(listener)
57
+ return () => void listeners.delete(listener)
58
+ },
59
+ async init() {
60
+ await ensure()
61
+ },
62
+ reset() {
63
+ if (!loading) return
64
+ loading = undefined
65
+ ensure().catch(() => {})
66
+ },
67
+ async search(query, { limit = DEFAULT_LIMIT } = {}) {
68
+ if (typeof query !== "string") throw new TypeError(`search: the query is a string (got ${JSON.stringify(query)})`)
69
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new TypeError("search: limit must be a non-negative integer")
70
+ return searchIndex(await ensure(), query, limit)
71
+ },
72
+ }
73
+ }
@@ -0,0 +1,126 @@
1
+ import type { SearchSection } from "./sections.ts"
2
+
3
+ /** An inverted index as JSON; `postings[i]` is `[section, title count, body count, …]` for `terms[i]`. */
4
+ export interface SearchIndex {
5
+ version: 1
6
+ sections: Array<Pick<SearchSection, "id" | "title" | "titles" | "level">>
7
+ /** Token count of each section's title and of its content. */
8
+ titleLengths: number[]
9
+ bodyLengths: number[]
10
+ avgTitleLength: number
11
+ avgBodyLength: number
12
+ /** Folded terms in code-unit order. */
13
+ terms: string[]
14
+ postings: number[][]
15
+ }
16
+
17
+ export interface SearchHit {
18
+ id: string
19
+ title: string
20
+ titles: string[]
21
+ level: number
22
+ score: number
23
+ }
24
+
25
+ const K1 = 1.2
26
+ const B = 0.75
27
+ const TITLE_BOOST = 5
28
+ const PREFIX_WEIGHT = 0.5
29
+ const SEPARATORS = /[^\p{L}\p{N}]+/u
30
+
31
+ /** Lower case, then `normalize("NFD")` with the combining marks removed. */
32
+ export const fold = (text: string): string => text.toLowerCase().normalize("NFD").replace(/\p{M}/gu, "")
33
+
34
+ export const tokenize = (text: string): string[] => fold(text).split(SEPARATORS).filter(Boolean)
35
+
36
+ const compare = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)
37
+
38
+ const mean = (values: readonly number[]): number =>
39
+ values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0
40
+
41
+ /** The index of `sections`, each term counted apart in its title and its content. */
42
+ export function buildSearchIndex(sections: readonly SearchSection[]): SearchIndex {
43
+ const found = new Map<string, number[]>()
44
+ const titleLengths: number[] = []
45
+ const bodyLengths: number[] = []
46
+ sections.forEach((section, number) => {
47
+ const counts = new Map<string, [number, number]>()
48
+ const add = (token: string, field: 0 | 1): void => {
49
+ let pair = counts.get(token)
50
+ if (!pair) counts.set(token, (pair = [0, 0]))
51
+ pair[field]++
52
+ }
53
+ const title = tokenize(section.title)
54
+ const body = tokenize(section.content)
55
+ for (const token of title) add(token, 0)
56
+ for (const token of body) add(token, 1)
57
+ titleLengths.push(title.length)
58
+ bodyLengths.push(body.length)
59
+ for (const [term, [inTitle, inBody]] of counts) {
60
+ let list = found.get(term)
61
+ if (!list) found.set(term, (list = []))
62
+ list.push(number, inTitle, inBody)
63
+ }
64
+ })
65
+ const terms = [...found.keys()].sort(compare)
66
+ return {
67
+ version: 1,
68
+ sections: sections.map(({ id, title, titles, level }) => ({ id, title, titles, level })),
69
+ titleLengths,
70
+ bodyLengths,
71
+ avgTitleLength: mean(titleLengths),
72
+ avgBodyLength: mean(bodyLengths),
73
+ terms,
74
+ postings: terms.map((term) => found.get(term)!),
75
+ }
76
+ }
77
+
78
+ function firstAtLeast(terms: readonly string[], token: string): number {
79
+ let low = 0
80
+ let high = terms.length
81
+ while (low < high) {
82
+ const middle = (low + high) >>> 1
83
+ if (terms[middle]! < token) low = middle + 1
84
+ else high = middle
85
+ }
86
+ return low
87
+ }
88
+
89
+ /** BM25 over the terms of `query`; the last term also matches by prefix, all its matches counting as one term. Hits are new objects, best first, ties in section order. */
90
+ export function searchIndex(index: SearchIndex, query: string, limit: number): SearchHit[] {
91
+ const tokens = [...new Set(tokenize(query))]
92
+ const total = index.sections.length
93
+ const scores = new Map<number, number>()
94
+ tokens.forEach((token, position) => {
95
+ const matches: number[] = []
96
+ const start = firstAtLeast(index.terms, token)
97
+ if (position === tokens.length - 1) {
98
+ for (let at = start; at < index.terms.length && index.terms[at]!.startsWith(token); at++) matches.push(at)
99
+ } else if (index.terms[start] === token) {
100
+ matches.push(start)
101
+ }
102
+ const counts = new Map<number, [number, number]>()
103
+ for (const at of matches) {
104
+ const postings = index.postings[at]!
105
+ const weight = index.terms[at] === token ? 1 : PREFIX_WEIGHT
106
+ for (let i = 0; i < postings.length; i += 3) {
107
+ const pair = counts.get(postings[i]!) ?? [0, 0]
108
+ counts.set(postings[i]!, [pair[0] + weight * postings[i + 1]!, pair[1] + weight * postings[i + 2]!])
109
+ }
110
+ }
111
+ const idf = Math.log(1 + (total - counts.size + 0.5) / (counts.size + 0.5))
112
+ for (const [section, [inTitle, inBody]] of counts) {
113
+ const titleNorm = 1 - B + (B * index.titleLengths[section]!) / (index.avgTitleLength || 1)
114
+ const bodyNorm = 1 - B + (B * index.bodyLengths[section]!) / (index.avgBodyLength || 1)
115
+ const count = (TITLE_BOOST * inTitle) / titleNorm + inBody / bodyNorm
116
+ scores.set(section, (scores.get(section) ?? 0) + (idf * count * (K1 + 1)) / (count + K1))
117
+ }
118
+ })
119
+ return [...scores]
120
+ .sort((a, b) => b[1] - a[1] || a[0] - b[0])
121
+ .slice(0, limit)
122
+ .map(([section, score]) => {
123
+ const { id, title, titles, level } = index.sections[section]!
124
+ return { id, title, titles: [...titles], level, score }
125
+ })
126
+ }
@@ -0,0 +1,155 @@
1
+ import type { MdNode } from "hamur/markdown"
2
+ import { QueryError, type CollectionQueryBuilder } from "./query.ts"
3
+
4
+ export type HeadingTag = "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
5
+
6
+ /** The split of `queryCollectionSearchSections`. */
7
+ export interface SearchSectionsOptions {
8
+ /** Tags whose text is left out of `content`, `pre` and `code` for example; default none. */
9
+ ignoredTags?: string[]
10
+ /** The shallowest heading that starts a section; default `"h1"`. */
11
+ minHeading?: HeadingTag
12
+ /** The deepest heading that starts a section; default `"h6"`. */
13
+ maxHeading?: HeadingTag
14
+ }
15
+
16
+ export interface SearchSection {
17
+ /** `<path>#<heading id>`, or the page's `path` for the text before its first section heading. */
18
+ id: string
19
+ title: string
20
+ /** The titles of the headings above this section, outermost first. */
21
+ titles: string[]
22
+ content: string
23
+ /** The heading's depth, 1 for the text before the first heading. */
24
+ level: number
25
+ }
26
+
27
+ export interface ResolvedSectionOptions {
28
+ ignored: ReadonlySet<string>
29
+ min: number
30
+ max: number
31
+ }
32
+
33
+ const BLOCKS = new Set([
34
+ "root",
35
+ "p",
36
+ "h1",
37
+ "h2",
38
+ "h3",
39
+ "h4",
40
+ "h5",
41
+ "h6",
42
+ "blockquote",
43
+ "ul",
44
+ "ol",
45
+ "li",
46
+ "pre",
47
+ "hr",
48
+ "br",
49
+ "html",
50
+ "table",
51
+ "thead",
52
+ "tbody",
53
+ "tr",
54
+ "th",
55
+ "td",
56
+ ])
57
+ const HEADING = /^h([1-6])$/
58
+
59
+ function depthOf(value: unknown, name: string): number {
60
+ const match = typeof value === "string" ? HEADING.exec(value) : null
61
+ if (!match) throw new QueryError(`${name} must be "h1" to "h6" (got ${JSON.stringify(value)})`)
62
+ return Number(match[1])
63
+ }
64
+
65
+ export function resolveSectionOptions(options: SearchSectionsOptions = {}): ResolvedSectionOptions {
66
+ const { ignoredTags = [], minHeading = "h1", maxHeading = "h6" } = options
67
+ if (!Array.isArray(ignoredTags) || !ignoredTags.every((tag) => typeof tag === "string"))
68
+ throw new QueryError(`ignoredTags must be an array of tag names (got ${JSON.stringify(ignoredTags)})`)
69
+ const min = depthOf(minHeading, "minHeading")
70
+ const max = depthOf(maxHeading, "maxHeading")
71
+ if (min > max) throw new QueryError(`minHeading ${minHeading} is deeper than maxHeading ${maxHeading}`)
72
+ return { ignored: new Set(ignoredTags), min, max }
73
+ }
74
+
75
+ function collect(node: MdNode, ignored: ReadonlySet<string>, out: string[]): void {
76
+ if (typeof node === "string") return void out.push(node)
77
+ const tag = node[0]
78
+ if (ignored.has(tag) || tag === "html") return void out.push(" ")
79
+ const block = BLOCKS.has(tag)
80
+ if (block) out.push(" ")
81
+ for (let i = 2; i < node.length; i++) collect(node[i] as MdNode, ignored, out)
82
+ if (block) out.push(" ")
83
+ }
84
+
85
+ const plain = (parts: string[]): string => parts.join("").replace(/\s+/g, " ").trim()
86
+
87
+ export interface SectionedPage {
88
+ path: string
89
+ title?: string | undefined
90
+ body: readonly unknown[]
91
+ }
92
+
93
+ /** Splits one page at the headings in `[min, max]`; the text before the first one is a section with the page's own title. */
94
+ export function sectionsOf(page: SectionedPage, { ignored, min, max }: ResolvedSectionOptions): SearchSection[] {
95
+ const out: SearchSection[] = []
96
+ const stack: Array<{ depth: number; text: string }> = []
97
+ let current = {
98
+ id: page.path,
99
+ title: page.title ?? "",
100
+ titles: [] as string[],
101
+ level: 1,
102
+ parts: [] as string[],
103
+ lead: true,
104
+ }
105
+ const close = (): void => {
106
+ const content = plain(current.parts)
107
+ if (!current.lead || content !== "" || (current.title !== "" && min > 1))
108
+ out.push({ id: current.id, title: current.title, titles: current.titles, content, level: current.level })
109
+ }
110
+ for (let i = 2; i < page.body.length; i++) {
111
+ const node = page.body[i] as MdNode
112
+ const depth = typeof node === "string" ? 0 : Number(HEADING.exec(node[0])?.[1] ?? 0)
113
+ if (depth >= min && depth <= max) {
114
+ const element = node as Exclude<MdNode, string>
115
+ const text: string[] = []
116
+ for (let j = 2; j < element.length; j++) collect(element[j] as MdNode, new Set(), text)
117
+ const title = plain(text)
118
+ close()
119
+ while (stack.length && stack[stack.length - 1]!.depth >= depth) stack.pop()
120
+ const id = element[1]?.id
121
+ current = {
122
+ id: typeof id === "string" && id !== "" ? `${page.path}#${id}` : page.path,
123
+ title,
124
+ titles: stack.map((item) => item.text),
125
+ level: depth,
126
+ parts: [],
127
+ lead: false,
128
+ }
129
+ stack.push({ depth, text: title })
130
+ } else {
131
+ collect(node, ignored, current.parts)
132
+ }
133
+ }
134
+ close()
135
+ return out
136
+ }
137
+
138
+ /** The sections of every page of a collection, over any `queryCollection` builder. */
139
+ export async function searchSectionsOf(
140
+ query: () => CollectionQueryBuilder<Record<string, unknown>>,
141
+ options?: SearchSectionsOptions,
142
+ ): Promise<SearchSection[]> {
143
+ let resolved: ResolvedSectionOptions
144
+ try {
145
+ resolved = resolveSectionOptions(options)
146
+ } catch (error) {
147
+ throw error instanceof QueryError ? new QueryError(`queryCollectionSearchSections: ${error.message}`) : error
148
+ }
149
+ const rows = (await query().select("path", "title", "body").all()) as unknown as Array<{
150
+ path: string
151
+ title?: string
152
+ body: MdNode[]
153
+ }>
154
+ return rows.flatMap((row) => sectionsOf(row, resolved))
155
+ }
@@ -0,0 +1,12 @@
1
+ import type { ContentStore } from "./store.ts"
2
+
3
+ let current: ContentStore | undefined
4
+
5
+ /** The door's plugin hands over `#hamur/content/store` at start, so `queryCollection` reaches it without the client graph importing it. */
6
+ export function setServerStore(store: ContentStore): void {
7
+ current = store
8
+ }
9
+
10
+ export function serverStore(): ContentStore | undefined {
11
+ return current
12
+ }
@@ -0,0 +1,59 @@
1
+ import type { CollectionDefinition, ContentEntry } from "../types.ts"
2
+
3
+ /** One chunk of a collection, with the `id` of its first and last entry. */
4
+ export interface StoredChunk {
5
+ first: string
6
+ last: string
7
+ load(): Promise<{ default: ContentEntry[] }>
8
+ }
9
+
10
+ export interface StoredCollection {
11
+ type: CollectionDefinition["type"]
12
+ expose: boolean
13
+ order?: CollectionDefinition["order"]
14
+ /** Imports the whole collection as one JSON chunk (`hamur dev`). */
15
+ load?(): Promise<{ default: ContentEntry[] }>
16
+ /** The collection's chunks in source order, each imported on the collection's first read. */
17
+ chunks?: StoredChunk[]
18
+ }
19
+
20
+ export interface ContentStore {
21
+ readonly collections: Readonly<Record<string, Omit<StoredCollection, "load">>>
22
+ /** The collection's entries in source order; its chunks are imported together on the first call in a process. */
23
+ entries(name: string): Promise<ContentEntry[]>
24
+ }
25
+
26
+ export interface StoreOptions {
27
+ /** `false` calls `load` on every read: `hamur dev`'s loader reads the entries as they are now. Default `true`. */
28
+ cache?: boolean
29
+ }
30
+
31
+ /** The store the server reads, over the chunks `#hamur/content/store` lists. */
32
+ export function createStore(
33
+ collections: Record<string, StoredCollection>,
34
+ { cache = true }: StoreOptions = {},
35
+ ): ContentStore {
36
+ const loaded = new Map<string, Promise<ContentEntry[]>>()
37
+ const read = async ({ load, chunks = [] }: StoredCollection): Promise<ContentEntry[]> =>
38
+ load
39
+ ? (await load()).default
40
+ : (await Promise.all(chunks.map((chunk) => chunk.load()))).flatMap((chunk) => chunk.default)
41
+ return {
42
+ collections: Object.fromEntries(
43
+ Object.entries(collections).map(([name, { load: _, chunks: __, ...meta }]) => [name, meta]),
44
+ ),
45
+ entries(name) {
46
+ const collection = Object.hasOwn(collections, name) ? collections[name] : undefined
47
+ if (!collection)
48
+ return Promise.reject(new TypeError(`content: "${name}" is not a collection of content.config.ts`))
49
+ if (!cache) return read(collection)
50
+ let entries = loaded.get(name)
51
+ if (!entries) {
52
+ entries = read(collection)
53
+ loaded.set(name, entries)
54
+ entries.catch(() => loaded.delete(name))
55
+ }
56
+ return entries
57
+ },
58
+ }
59
+ }
@@ -0,0 +1,6 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { installStore } from "./install.ts"
3
+
4
+ export { contentRefresh } from "./refresh.ts"
5
+
6
+ export default defineServer({ plugins: [installStore] })
@@ -0,0 +1,7 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { installStore } from "./install.ts"
3
+
4
+ export { contentQuery } from "./endpoint.ts"
5
+ export { contentRefresh } from "./refresh.ts"
6
+
7
+ export default defineServer({ plugins: [installStore] })
@@ -0,0 +1,4 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { installStore } from "./install.ts"
3
+
4
+ export default defineServer({ plugins: [installStore] })
@@ -0,0 +1,6 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { installStore } from "./install.ts"
3
+
4
+ export { contentQuery } from "./endpoint.ts"
5
+
6
+ export default defineServer({ plugins: [installStore] })
@@ -0,0 +1,17 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import store from "#hamur/content/store"
3
+ import { createError, defineHandler } from "hamur/server"
4
+ import { answerQuery, QueryError } from "../runtime/query.ts"
5
+
6
+ export const contentQuery = defineHandler({
7
+ route: "/_hamur/content/query",
8
+ method: "POST",
9
+ async handler(input: unknown) {
10
+ try {
11
+ return await answerQuery(store, input)
12
+ } catch (error) {
13
+ if (error instanceof QueryError) throw createError({ status: 400, message: error.message })
14
+ throw error
15
+ }
16
+ },
17
+ })
@@ -0,0 +1,59 @@
1
+ import type { CollectionQuery, QueryClause } from "../runtime/query.ts"
2
+ import type { ContentStore } from "../runtime/store.ts"
3
+ import { answerExposed, condition, REST_LIMIT } from "./rest.ts"
4
+
5
+ /** The arguments of `Query.<collection>` in `content.graphql`. */
6
+ export interface ListArgs {
7
+ where?: Array<{ field: string; operator?: string | null; value?: string | null }> | null
8
+ order?: Array<{ field: string; direction?: "ASC" | "DESC" | null }> | null
9
+ limit?: number | null
10
+ skip?: number | null
11
+ }
12
+
13
+ const NO_VALUE = new Set(["IS NULL", "IS NOT NULL"])
14
+
15
+ /** The arguments as the engine's query: a `value` is read as a REST query value is, and `limit` is capped as REST caps it. */
16
+ export function graphqlQuery({ where, order, limit, skip }: ListArgs): CollectionQuery {
17
+ const query: CollectionQuery = { limit: limit == null ? REST_LIMIT : Math.min(limit, REST_LIMIT) }
18
+ if (skip != null) query.skip = skip
19
+ if (order?.length)
20
+ query.order = order.map(({ field, direction }): [string, "ASC" | "DESC"] => [field, direction ?? "ASC"])
21
+ if (where?.length) {
22
+ query.where = where.map(({ field, operator, value }): QueryClause => {
23
+ const written = operator ?? "="
24
+ if (value == null)
25
+ return {
26
+ join: "AND",
27
+ field,
28
+ operator: written.toUpperCase() as never,
29
+ ...(NO_VALUE.has(written.toUpperCase()) ? {} : { value: null }),
30
+ }
31
+ return { join: "AND", ...condition(field, written, value) }
32
+ })
33
+ }
34
+ return query
35
+ }
36
+
37
+ /** `Query.<collection>`: the entries the arguments select. */
38
+ export const contentList = (store: ContentStore, name: string, args: ListArgs): Promise<unknown> =>
39
+ answerExposed(store, name, () => graphqlQuery(args))
40
+
41
+ /** `Query.<collection>Item`: the entry whose `key` (`path` for a page, `id` for data) is `value`, or null. */
42
+ export async function contentItem(
43
+ store: ContentStore,
44
+ name: string,
45
+ key: "path" | "id",
46
+ value: string,
47
+ ): Promise<unknown> {
48
+ const found = (await answerExposed(store, name, () => ({
49
+ where: [{ join: "AND", field: key, operator: "=", value }],
50
+ limit: 1,
51
+ }))) as unknown[]
52
+ return found[0] ?? null
53
+ }
54
+
55
+ /** A field with no GraphQL type of its own: its value as JSON text, null when it is missing. */
56
+ export const jsonField =
57
+ (field: string) =>
58
+ (parent: Record<string, unknown>): string | null =>
59
+ parent[field] === undefined || parent[field] === null ? null : JSON.stringify(parent[field])
@@ -0,0 +1,17 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import "hamur/server-only"
3
+
4
+ export {
5
+ queryCollection,
6
+ queryCollectionItemSurroundings,
7
+ queryCollectionNavigation,
8
+ queryCollectionSearchSections,
9
+ } from "./query.ts"
10
+ export { searchCollection } from "./search.ts"
11
+ export { getLiveCollection, getLiveEntry, refreshContent } from "./live.ts"
12
+ export type { LiveCollectionResult, LiveEntry, LiveEntryResult } from "../types.ts"
13
+ export { findPageBreadcrumb, findPageChildren, findPageHeadline, findPageSiblings } from "../runtime/navigation.ts"
14
+ export type { NavigationItem, SurroundingsOptions } from "../runtime/navigation.ts"
15
+ export type { SearchHit } from "../runtime/search.ts"
16
+ export type { SearchOptions } from "../runtime/search-store.ts"
17
+ export type { HeadingTag, SearchSection, SearchSectionsOptions } from "../runtime/sections.ts"
@@ -0,0 +1,6 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import store from "#hamur/content/store"
3
+ import { definePlugin } from "hamur/server"
4
+ import { setServerStore } from "../runtime/server-store.ts"
5
+
6
+ export const installStore = definePlugin(() => setServerStore(store))
@@ -0,0 +1,51 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import collections, { names } from "#hamur/content/live"
3
+ import type { MdRoot } from "hamur/markdown"
4
+ import { useLogger, useStorage } from "hamur/server"
5
+ import type { LiveCollectionFilter, LiveCollectionItem, LiveCollectionName, LiveEntryFilter } from "../index.ts"
6
+ import { createLiveContent } from "../runtime/live.ts"
7
+ import type { LiveCollectionResult, LiveEntryResult } from "../types.ts"
8
+
9
+ const hasMarkdown = typeof (globalThis as { Bun?: { markdown?: unknown } }).Bun?.markdown !== "undefined"
10
+
11
+ const live = createLiveContent({
12
+ collections,
13
+ names,
14
+ storage: () => {
15
+ const cache = useStorage("cache")
16
+ return {
17
+ getItem: (key) => cache.getItem(key),
18
+ setItem: (key, value, options) => cache.setItem(key, value, options),
19
+ removeItem: (key) => cache.removeItem(key),
20
+ clear: (prefix) => cache.clear(prefix),
21
+ }
22
+ },
23
+ warn: (message) => useLogger().child({ name: "content" }).warn(message),
24
+ ...(hasMarkdown
25
+ ? {
26
+ parseMarkdown: async (source: string): Promise<MdRoot> =>
27
+ (await (await import("hamur/markdown")).parseMarkdown(source)).ast,
28
+ }
29
+ : {}),
30
+ })
31
+
32
+ /** Runs the collection's `loadCollection(filter)` now, or reuses a result cached for its `cacheHint.maxAge`. */
33
+ export function getLiveCollection<N extends LiveCollectionName>(
34
+ name: N,
35
+ filter?: LiveCollectionFilter<N>,
36
+ ): Promise<LiveCollectionResult<LiveCollectionItem<N>>> {
37
+ return live.getLiveCollection(name, filter) as Promise<LiveCollectionResult<LiveCollectionItem<N>>>
38
+ }
39
+
40
+ /** Runs the collection's `loadEntry(filter)` now, or reuses a result cached for its `cacheHint.maxAge`. */
41
+ export function getLiveEntry<N extends LiveCollectionName>(
42
+ name: N,
43
+ filter: LiveEntryFilter<N>,
44
+ ): Promise<LiveEntryResult<LiveCollectionItem<N>>> {
45
+ return live.getLiveEntry(name, filter) as Promise<LiveEntryResult<LiveCollectionItem<N>>>
46
+ }
47
+
48
+ /** Drops the cached live results of `collections` (default every live collection); a load running now stores nothing. */
49
+ export function refreshContent(options?: { collections?: string[] }): Promise<void> {
50
+ return live.refreshContent(options)
51
+ }
@@ -0,0 +1,46 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import store from "#hamur/content/store"
3
+ import type { HamurEvent } from "hamur/server"
4
+ import { navigationOf, surroundingsOf, type NavigationItem, type SurroundingsOptions } from "../runtime/navigation.ts"
5
+ import { createQuery, queryStore, type CollectionQueryBuilder } from "../runtime/query.ts"
6
+ import { searchSectionsOf, type SearchSection, type SearchSectionsOptions } from "../runtime/sections.ts"
7
+ import type { CollectionField, CollectionItem, CollectionName } from "../index.ts"
8
+ import type { ContentEntry } from "../types.ts"
9
+
10
+ /** A query from a handler, over every collection, `expose: false` ones included. */
11
+ export function queryCollection<N extends CollectionName>(
12
+ event: HamurEvent,
13
+ name: N,
14
+ ): CollectionQueryBuilder<CollectionItem<N>, never, CollectionField<N>>
15
+ export function queryCollection<T = ContentEntry>(event: HamurEvent, name: CollectionName): CollectionQueryBuilder<T>
16
+ export function queryCollection(_event: HamurEvent, name: string): CollectionQueryBuilder<any, never, any> {
17
+ return createQuery((query) => queryStore(store, name, query))
18
+ }
19
+
20
+ /** The navigation tree from a handler, over any collection. */
21
+ export function queryCollectionNavigation(
22
+ event: HamurEvent,
23
+ name: CollectionName,
24
+ extraFields?: string[],
25
+ ): Promise<NavigationItem[]> {
26
+ return navigationOf(() => queryCollection<ContentEntry>(event, name), extraFields)
27
+ }
28
+
29
+ /** The entries around `path` from a handler. */
30
+ export function queryCollectionItemSurroundings<N extends CollectionName, F extends string = never>(
31
+ event: HamurEvent,
32
+ name: N,
33
+ path: string,
34
+ options?: SurroundingsOptions<F>,
35
+ ) {
36
+ return surroundingsOf<CollectionItem<N>, F>(() => queryCollection<CollectionItem<N>>(event, name), path, options)
37
+ }
38
+
39
+ /** The sections of a collection's pages from a handler, over any collection. */
40
+ export function queryCollectionSearchSections(
41
+ event: HamurEvent,
42
+ name: CollectionName,
43
+ options?: SearchSectionsOptions,
44
+ ): Promise<SearchSection[]> {
45
+ return searchSectionsOf(() => queryCollection<Record<string, unknown>>(event, name), options)
46
+ }