@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,597 @@
1
+ import { rename } from "node:fs/promises"
2
+ import { join, relative, sep } from "node:path"
3
+ import {
4
+ DiagnosticError,
5
+ addTemplate,
6
+ createResolver,
7
+ useLogger,
8
+ useMarkdownParser,
9
+ type HamurContext,
10
+ } from "hamur/kit"
11
+ import { parseMarkdown, type MarkdownDocument, type MarkdownOptions, type ParseMarkdownOptions } from "hamur/markdown"
12
+ import type { Logger, StandardSchemaV1 } from "hamur/server"
13
+ import { ContentError } from "../error.ts"
14
+ import { DEFAULT_CSV, resolveCsv, type CsvOptions } from "../loaders/data.ts"
15
+ import { sourceLoader } from "../loaders/glob.ts"
16
+ import { entryImages, setupImages, withImages, type ImageOutput } from "./image.ts"
17
+ import type {
18
+ CollectionDefinition,
19
+ ContentConfig,
20
+ ContentEntry,
21
+ ContentFile,
22
+ ContentOptions,
23
+ DataEntry,
24
+ LoaderContext,
25
+ LoaderEntry,
26
+ PageEntry,
27
+ Transformer,
28
+ } from "../types.ts"
29
+
30
+ const RESERVED = ["collection", "id", "stem", "extension", "body", "excerpt", "headings", "toc"]
31
+ const ENTRY_FIELDS = new Set(RESERVED)
32
+ const PAGE_FIELDS = new Set([
33
+ ...RESERVED,
34
+ "readingTime",
35
+ "title",
36
+ "description",
37
+ "seo",
38
+ "navigation",
39
+ "draft",
40
+ "path",
41
+ "navigationDirs",
42
+ ])
43
+
44
+ export interface IndexContext {
45
+ rootDir: string
46
+ markdown: MarkdownOptions
47
+ siteUrl?: string
48
+ buildDir: string
49
+ /** `<cacheDir>`, where remote sources are cached; default `<rootDir>/node_modules/.cache/hamur`. */
50
+ cacheDir?: string
51
+ /** Hash of everything but an entry that changes how every entry parses; a different one drops the last build's index. */
52
+ digest: string
53
+ /** Where `image()` writes the files it resolves; without it `image()` fails. */
54
+ images?: ImageOutput
55
+ /** `hamur dev` keeps drafts; every build leaves them out. */
56
+ dev: boolean
57
+ /** `content.csv` with its defaults. */
58
+ csv?: CsvOptions
59
+ log(message: string): void
60
+ logger?: Logger
61
+ /** Replaces `hamur/markdown`'s `parseMarkdown`. */
62
+ parseMarkdown?: typeof parseMarkdown
63
+ /** `content.config.ts`'s `transformers`. */
64
+ transformers?: readonly Transformer[]
65
+ /** Filled with each entry's file, by `<collection>\0<id>`, for `content.raw` and `content.llms`. */
66
+ files?: Map<string, string>
67
+ /** Filled with each entry's loader body, by `<collection>\0<id>`, for `content.raw: "body"`. */
68
+ bodies?: Map<string, string>
69
+ /** The `content:file:*` hooks. */
70
+ hooks?: {
71
+ beforeParse(file: ContentFile, collection: string): Promise<void>
72
+ afterParse(file: ContentFile, entry: ContentEntry, collection: string): Promise<void>
73
+ }
74
+ }
75
+
76
+ type Fields = Record<string, unknown>
77
+
78
+ const isObject = (value: unknown): value is Fields =>
79
+ value !== null && typeof value === "object" && !Array.isArray(value)
80
+
81
+ const pathOf = (path: StandardSchemaV1.Issue["path"]): string =>
82
+ (path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".")
83
+
84
+ const at = (shown: string, path: string): string => (path ? `${shown}: ${path}: ` : `${shown}: `)
85
+
86
+ /** A value of the index is JSON; a `Date` becomes its ISO string. */
87
+ export function toJson(value: unknown, shown: string, path: string[] = []): unknown {
88
+ if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number")
89
+ return value
90
+ if (value instanceof Date) return value.toISOString()
91
+ if (Array.isArray(value))
92
+ return value.map((item, index) => (item === undefined ? null : toJson(item, shown, [...path, String(index)])))
93
+ if (typeof value === "object") {
94
+ const proto = Object.getPrototypeOf(value)
95
+ if (proto === Object.prototype || proto === null) {
96
+ const out: Fields = {}
97
+ for (const [key, item] of Object.entries(value))
98
+ if (item !== undefined) out[key] = toJson(item, shown, [...path, key])
99
+ return out
100
+ }
101
+ }
102
+ const kind = typeof value === "object" ? ((value as object).constructor?.name ?? "object") : typeof value
103
+ throw new ContentError("HAMUR_E5343", `${at(shown, path.join("."))}a schema output must be JSON (got ${kind})`)
104
+ }
105
+
106
+ async function validate(
107
+ schema: StandardSchemaV1 | undefined,
108
+ data: Fields,
109
+ shown: string,
110
+ item: string | undefined,
111
+ images: ReturnType<typeof entryImages>,
112
+ ): Promise<Fields> {
113
+ let output: unknown = data
114
+ if (schema) {
115
+ const result = await withImages(images, async () => schema["~standard"].validate(data))
116
+ if (result.issues) {
117
+ throw new ContentError(
118
+ "HAMUR_E5344",
119
+ result.issues
120
+ .map((issue) => `${at(shown, [item, pathOf(issue.path)].filter(Boolean).join("."))}${issue.message}`)
121
+ .join("\n"),
122
+ )
123
+ }
124
+ output = result.value
125
+ }
126
+ if (!isObject(output))
127
+ throw new ContentError("HAMUR_E5345", `${at(shown, item ?? "")}a schema output must be an object`)
128
+ return toJson(output, shown, item === undefined ? [] : [item]) as Fields
129
+ }
130
+
131
+ function checkReserved(data: Fields, shown: string, kind: string): void {
132
+ for (const field of RESERVED)
133
+ if (Object.hasOwn(data, field))
134
+ throw new ContentError("HAMUR_E5346", `${shown}: ${kind} field "${field}" is reserved`)
135
+ }
136
+
137
+ const without = (data: Fields, keys: Set<string>): Fields =>
138
+ Object.fromEntries(Object.entries(data).filter(([key]) => !keys.has(key)))
139
+
140
+ const extensionOf = (file: string): string => {
141
+ const dot = file.lastIndexOf(".")
142
+ return dot > file.lastIndexOf("/") ? file.slice(dot + 1) : ""
143
+ }
144
+
145
+ const shownOf = (ctx: IndexContext, loader: string, id: string, file: string | undefined): string =>
146
+ file ? relative(ctx.rootDir, file).split(sep).join("/") : `content: loader "${loader}", entry "${id}"`
147
+
148
+ const digestOf = (value: string | Uint8Array): string => Bun.hash(value).toString(36)
149
+
150
+ /** Outputs of `parseData`, which `store.set` does not validate again. */
151
+ const validated = new WeakSet<object>()
152
+
153
+ async function buildEntry(
154
+ input: LoaderEntry,
155
+ loader: string,
156
+ collection: CollectionDefinition,
157
+ ctx: IndexContext,
158
+ withImage: Set<string>,
159
+ ): Promise<ContentEntry> {
160
+ const shown = shownOf(ctx, loader, input.id, input.file)
161
+ const extension = input.file ? extensionOf(input.file) : ""
162
+ const stem = input.stem ?? input.id
163
+ const label = input.file && input.id.startsWith(`${stem}/`) ? input.id.slice(stem.length + 1) : undefined
164
+ const page = collection.type === "page"
165
+ const done = validated.has(input.data)
166
+ let parsed: MarkdownDocument | undefined
167
+ let fields = input.data
168
+ if (page || input.body !== undefined) {
169
+ const options: ParseMarkdownOptions = {
170
+ ...(page ? { ...ctx.markdown, ...(ctx.siteUrl === undefined ? {} : { siteUrl: ctx.siteUrl }) } : {}),
171
+ ...(input.file ? { file: shown } : {}),
172
+ }
173
+ parsed = await (ctx.parseMarkdown ?? parseMarkdown)(input.body ?? "", options)
174
+ if (!done) fields = { ...parsed.frontmatter, ...input.data }
175
+ }
176
+ if (!done) checkReserved(fields, shown, extension === "md" ? "frontmatter" : "data")
177
+ const images = entryImages(input.file, ctx.images)
178
+ const data = done ? fields : await validate(collection.schema, fields, shown, label, images)
179
+ if (images.used) withImage.add(input.id)
180
+ if (!page || !parsed)
181
+ return { collection: "", id: input.id, stem, extension, ...without(data, ENTRY_FIELDS) } as DataEntry
182
+ const title = typeof data.title === "string" ? data.title : parsed.title
183
+ const description = typeof data.description === "string" ? data.description : parsed.description
184
+ const navigation =
185
+ data.navigation === false ? false : isObject(data.navigation) ? (data.navigation as PageEntry["navigation"]) : true
186
+ return {
187
+ collection: "",
188
+ id: input.id,
189
+ stem,
190
+ extension,
191
+ path: typeof data.path === "string" && data.path.startsWith("/") ? data.path : (input.path ?? `/${input.id}`),
192
+ title,
193
+ description,
194
+ seo: {
195
+ ...(title === undefined ? {} : { title }),
196
+ ...(description === undefined ? {} : { description }),
197
+ ...(isObject(data.seo) ? data.seo : {}),
198
+ } as PageEntry["seo"],
199
+ navigation,
200
+ draft: data.draft === true,
201
+ ...(input.navigationDirs ? { navigationDirs: input.navigationDirs } : {}),
202
+ ...without(data, PAGE_FIELDS),
203
+ body: parsed.ast,
204
+ excerpt: parsed.excerpt,
205
+ headings: parsed.headings,
206
+ toc: parsed.toc,
207
+ readingTime: parsed.readingTime,
208
+ }
209
+ }
210
+
211
+ /** The transformers' `transform` in list order, then the `content:file:afterParse` hooks; the result is JSON again. */
212
+ async function finishEntry(
213
+ built: ContentEntry,
214
+ input: LoaderEntry,
215
+ name: string,
216
+ shown: string,
217
+ ctx: IndexContext,
218
+ ): Promise<ContentEntry> {
219
+ let entry = { ...built, collection: name } as ContentEntry
220
+ const transformers = (ctx.transformers ?? []).filter((item) => item.transform !== undefined)
221
+ if (!transformers.length && !ctx.hooks) return entry
222
+ for (const transformer of transformers) {
223
+ let result: unknown
224
+ try {
225
+ result = await transformer.transform!(entry)
226
+ } catch (error) {
227
+ throw new ContentError(
228
+ "HAMUR_E5347",
229
+ `${shown}: transformer "${transformer.name}" failed: ${error instanceof Error ? error.message : String(error)}`,
230
+ )
231
+ }
232
+ if (!isObject(result))
233
+ throw new ContentError(
234
+ "HAMUR_E5348",
235
+ `${shown}: transformer "${transformer.name}" must return an object from transform`,
236
+ )
237
+ entry = result as ContentEntry
238
+ }
239
+ if (ctx.hooks) {
240
+ try {
241
+ await ctx.hooks.afterParse(
242
+ { id: input.id, path: shown, extension: extensionOf(input.file ?? ""), body: input.body ?? "" },
243
+ entry,
244
+ name,
245
+ )
246
+ } catch (error) {
247
+ throw new ContentError(
248
+ "HAMUR_E5349",
249
+ `${shown}: content:file:afterParse failed: ${error instanceof Error ? error.message : String(error)}`,
250
+ )
251
+ }
252
+ }
253
+ return toJson(entry, shown) as ContentEntry
254
+ }
255
+
256
+ interface IndexFile {
257
+ version: 1
258
+ digest: string
259
+ meta: Record<string, string>
260
+ entries: Array<{ digest: string | null; entry: ContentEntry; images?: true }>
261
+ }
262
+
263
+ export const fileKey = (collection: string, id: string): string => `${collection}\0${id}`
264
+
265
+ const indexPath = (ctx: IndexContext, name: string): string => join(ctx.buildDir, "content", `${name}.json`)
266
+
267
+ async function readIndexFile(ctx: IndexContext, name: string): Promise<IndexFile | undefined> {
268
+ try {
269
+ const file = JSON.parse(await Bun.file(indexPath(ctx, name)).text()) as Partial<IndexFile>
270
+ return file.version === 1 && file.digest === ctx.digest && Array.isArray(file.entries) && isObject(file.meta)
271
+ ? (file as IndexFile)
272
+ : undefined
273
+ } catch {
274
+ return undefined
275
+ }
276
+ }
277
+
278
+ /** One collection's entries in loader order, drafts left out of a build; an entry whose digest equals the last build's is not parsed again. */
279
+ export async function collectionEntries(
280
+ name: string,
281
+ collection: CollectionDefinition,
282
+ ctx: IndexContext,
283
+ ): Promise<ContentEntry[]> {
284
+ const { loader: custom, source } = collection
285
+ const loader = custom ?? sourceLoader(source!, ctx.cacheDir)
286
+ const last = await readIndexFile(ctx, name)
287
+ const lastEntries = new Map((last?.entries ?? []).map((item) => [item.entry.id, item]))
288
+ const inputs = new Map<string, LoaderEntry>()
289
+ const withImage = new Set<string>()
290
+ const meta = new Map(Object.entries(last?.meta ?? {}))
291
+ const loaderContext: LoaderContext = {
292
+ collection: name,
293
+ type: collection.type,
294
+ rootDir: ctx.rootDir,
295
+ store: {
296
+ set: (entry) => void inputs.set(entry.id, entry),
297
+ delete: (id) => void inputs.delete(id),
298
+ keys: () => [...inputs.keys()],
299
+ clear: () => inputs.clear(),
300
+ },
301
+ meta: { get: (key) => meta.get(key), set: (key, value) => void meta.set(key, value) },
302
+ async parseData({ id, data, file }) {
303
+ const shown = shownOf(ctx, loader.name, id, file)
304
+ if (!isObject(data)) throw new ContentError("HAMUR_E5350", `${at(shown, "")}a data entry is an object`)
305
+ checkReserved(data, shown, "data")
306
+ const images = entryImages(file, ctx.images)
307
+ const output = await validate(collection.schema, data, shown, undefined, images)
308
+ if (images.used) withImage.add(id)
309
+ validated.add(output)
310
+ return output
311
+ },
312
+ parseMarkdown: (text, options) =>
313
+ (ctx.parseMarkdown ?? parseMarkdown)(text, {
314
+ ...ctx.markdown,
315
+ ...(ctx.siteUrl === undefined ? {} : { siteUrl: ctx.siteUrl }),
316
+ ...options,
317
+ }),
318
+ digest: digestOf,
319
+ csv: ctx.csv ?? DEFAULT_CSV,
320
+ logger: ctx.logger ?? useLogger("content"),
321
+ transformers: ctx.transformers ?? [],
322
+ async beforeParse(file) {
323
+ if (!ctx.hooks) return file.body
324
+ try {
325
+ await ctx.hooks.beforeParse(file, name)
326
+ } catch (error) {
327
+ throw new ContentError(
328
+ "HAMUR_E5351",
329
+ `${file.path}: content:file:beforeParse failed: ${error instanceof Error ? error.message : String(error)}`,
330
+ )
331
+ }
332
+ if (typeof file.body !== "string")
333
+ throw new ContentError("HAMUR_E5352", `${file.path}: content:file:beforeParse must leave file.body a string`)
334
+ return file.body
335
+ },
336
+ }
337
+ try {
338
+ await loader.load(loaderContext)
339
+ } catch (error) {
340
+ if (error instanceof ContentError) throw error
341
+ throw new ContentError("HAMUR_E5353", `content: loader "${loader.name}" failed: ${(error as Error).message}`)
342
+ }
343
+ const built: Array<{ input: LoaderEntry; entry: ContentEntry; shown: string }> = []
344
+ for (const input of inputs.values()) {
345
+ const cached = input.digest === undefined ? undefined : lastEntries.get(input.id)
346
+ const reuse = cached !== undefined && cached.images !== true && cached.digest === input.digest
347
+ const shown = shownOf(ctx, loader.name, input.id, input.file)
348
+ const entry = reuse
349
+ ? ({ ...cached.entry, collection: name } as ContentEntry)
350
+ : await finishEntry(await buildEntry(input, loader.name, collection, ctx, withImage), input, name, shown, ctx)
351
+ built.push({ input, entry, shown })
352
+ }
353
+ if (ctx.files) for (const { input } of built) if (input.file) ctx.files.set(fileKey(name, input.id), input.file)
354
+ if (ctx.bodies)
355
+ for (const { input } of built) if (input.body !== undefined) ctx.bodies.set(fileKey(name, input.id), input.body)
356
+ const file: IndexFile = {
357
+ version: 1,
358
+ digest: ctx.digest,
359
+ meta: Object.fromEntries(meta),
360
+ entries: built.map(({ input, entry }) => ({
361
+ digest: input.digest ?? null,
362
+ entry,
363
+ ...(withImage.has(input.id) ? { images: true as const } : {}),
364
+ })),
365
+ }
366
+ await Bun.write(indexPath(ctx, name), JSON.stringify(file))
367
+ if (collection.type === "data") return built.map(({ entry }) => entry)
368
+ const kept = ctx.dev ? built : built.filter(({ entry }) => !(entry as PageEntry).draft)
369
+ const drafts = built.length - kept.length
370
+ if (drafts) ctx.log(`${name}: ${drafts} ${drafts === 1 ? "draft" : "drafts"} left out`)
371
+ const paths = new Map<string, string>()
372
+ for (const { entry, shown } of kept) {
373
+ const path = (entry as PageEntry).path
374
+ const other = paths.get(path)
375
+ if (other !== undefined)
376
+ throw new ContentError("HAMUR_E5354", `content: ${other} and ${shown} both have path ${path}`)
377
+ paths.set(path, shown)
378
+ }
379
+ return kept.map(({ entry }) => entry)
380
+ }
381
+
382
+ /** Every collection's entries, built once per build context. */
383
+ export async function buildIndex(config: ContentConfig, ctx: IndexContext): Promise<Record<string, ContentEntry[]>> {
384
+ const index: Record<string, ContentEntry[]> = {}
385
+ for (const [name, collection] of Object.entries(config.collections))
386
+ index[name] = await collectionEntries(name, collection, ctx)
387
+ return index
388
+ }
389
+
390
+ export interface ContentIndex {
391
+ /** Every collection's entries, read once per build and kept for the process in `hamur dev`. */
392
+ read(): Promise<Record<string, ContentEntry[]>>
393
+ /** The file an entry was read from, when its loader gave one. */
394
+ file(collection: string, id: string): string | undefined
395
+ /** The Markdown the entry's loader gave as `body`, frontmatter included. */
396
+ body(collection: string, id: string): string | undefined
397
+ /** `hamur dev`: runs the collection's loader again, parses the entries whose digest changed and keeps the result. */
398
+ rebuild(name: string): Promise<ContentEntry[]>
399
+ /** `hamur dev`: forgets a failed `read`, so the next one starts again. */
400
+ reset(): void
401
+ }
402
+
403
+ /** `hamur dev`: the file `#hamur/content/store` reads a collection from, written whole and renamed into place. */
404
+ export const devChunkPath = (buildDir: string, name: string): string => join(buildDir, "content", "dev", `${name}.json`)
405
+
406
+ async function writeDevChunk(buildDir: string, name: string, entries: ContentEntry[]): Promise<void> {
407
+ const path = devChunkPath(buildDir, name)
408
+ await Bun.write(`${path}.tmp`, JSON.stringify(entries))
409
+ await rename(`${path}.tmp`, path)
410
+ }
411
+
412
+ /** Everything of the transformers the index can key on: names, extensions and the source of `parse` and `transform`; what they import is not hashed. */
413
+ export function transformersKey(transformers: readonly Transformer[]): string {
414
+ return JSON.stringify(
415
+ transformers.map(({ name, extensions, parse, transform }) => [
416
+ name,
417
+ extensions,
418
+ parse?.toString() ?? null,
419
+ transform?.toString() ?? null,
420
+ ]),
421
+ )
422
+ }
423
+
424
+ const CONTENT_HOOKS = ["content:file:beforeParse", "content:file:afterParse"]
425
+
426
+ /** The `content:file:*` hooks registered so far, from the config's `hooks` and, as modules install after this one, by watching `hamur.hooks`; hook code itself cannot be hashed. */
427
+ function watchContentHooks(hamur: HamurContext): Set<string> {
428
+ const registered = new Set(Object.keys(hamur.options.hooks ?? {}).filter((name) => CONTENT_HOOKS.includes(name)))
429
+ for (const method of ["hook", "hookOnce"] as const) {
430
+ const original = hamur.hooks[method].bind(hamur.hooks)
431
+ hamur.hooks[method] = ((name: string, fn: never) => {
432
+ if (CONTENT_HOOKS.includes(name)) registered.add(name)
433
+ return original(name as never, fn)
434
+ }) as typeof original
435
+ }
436
+ return registered
437
+ }
438
+
439
+ const DEFAULT_CHUNK_SIZE = 1000
440
+
441
+ /** `content.chunkSize`, a positive integer, 1000 by default. */
442
+ export function resolveChunkSize(value: unknown): number {
443
+ if (value === undefined) return DEFAULT_CHUNK_SIZE
444
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1)
445
+ throw new DiagnosticError(
446
+ "HAMUR_E5338",
447
+ `content.chunkSize must be a positive integer (got ${JSON.stringify(value)})`,
448
+ )
449
+ return value
450
+ }
451
+
452
+ export interface ChunkRange {
453
+ first: string
454
+ last: string
455
+ }
456
+
457
+ /** Splits entries into chunks of `size` in source order; an empty collection has no chunk. */
458
+ export function splitChunks(entries: ContentEntry[], size: number): ContentEntry[][] {
459
+ const chunks: ContentEntry[][] = []
460
+ for (let at = 0; at < entries.length; at += size) chunks.push(entries.slice(at, at + size))
461
+ return chunks
462
+ }
463
+
464
+ export const chunkRangesOf = (chunks: ContentEntry[][]): ChunkRange[] =>
465
+ chunks.map((chunk) => ({ first: chunk[0]!.id, last: chunk.at(-1)!.id }))
466
+
467
+ /** `#hamur/content/chunks/<name>.json` is the whole collection (the client's chunk); the server imports `<name>.<n>.json`, chunks of `content.chunkSize` entries, on the collection's first read. */
468
+ export function setupIndex(hamur: HamurContext, config: ContentConfig, options: ContentOptions = {}): ContentIndex {
469
+ const { rootDir, buildDir, cacheDir, markdown, site, dev } = hamur.options
470
+ const chunkSize = resolveChunkSize(options.chunkSize)
471
+ const logger = useLogger("content")
472
+ const csv = resolveCsv(options.csv)
473
+ const parse = useMarkdownParser()
474
+ const transformers = config.transformers ?? []
475
+ const registered = watchContentHooks(hamur)
476
+ const hooks: NonNullable<IndexContext["hooks"]> = {
477
+ beforeParse: (file, collection) => hamur.hooks.callHook("content:file:beforeParse", { file, collection }),
478
+ afterParse: (file, entry, collection) =>
479
+ hamur.hooks.callHook("content:file:afterParse", { file, entry, collection }),
480
+ }
481
+ const files = new Map<string, string>()
482
+ const bodies = new Map<string, string>()
483
+ const images = setupImages(hamur)
484
+ let context: Promise<IndexContext> | undefined
485
+ const contextOf = () =>
486
+ (context ??= (async () => {
487
+ const text = await Bun.file(join(rootDir, "content.config.ts")).text()
488
+ const digest = digestOf(
489
+ `${text}\0${JSON.stringify(markdown)}\0${site?.url ?? ""}\0${transformersKey(transformers)}\0${[...registered].sort().join(",")}`,
490
+ )
491
+ return {
492
+ rootDir,
493
+ buildDir,
494
+ cacheDir,
495
+ digest,
496
+ csv,
497
+ files,
498
+ bodies,
499
+ images,
500
+ transformers,
501
+ hooks,
502
+ markdown,
503
+ ...(site?.url === undefined ? {} : { siteUrl: site.url }),
504
+ dev,
505
+ log: (message: string) => logger.info(message),
506
+ logger,
507
+ parseMarkdown: parse,
508
+ }
509
+ })())
510
+ let index: Promise<Record<string, ContentEntry[]>> | undefined
511
+ const read = () =>
512
+ (index ??= (async () => {
513
+ const entries = await buildIndex(config, await contextOf())
514
+ if (dev) for (const [name, list] of Object.entries(entries)) await writeDevChunk(buildDir, name, list)
515
+ return entries
516
+ })())
517
+ const rebuild = async (name: string): Promise<ContentEntry[]> => {
518
+ const current = await read()
519
+ const entries = await collectionEntries(name, config.collections[name]!, await contextOf())
520
+ current[name] = entries
521
+ if (dev) await writeDevChunk(buildDir, name, entries)
522
+ return entries
523
+ }
524
+ hamur.hooks.hook("build:before", async () => {
525
+ await read()
526
+ })
527
+ if (dev) read().catch(() => {})
528
+ for (const name of Object.keys(config.collections)) {
529
+ addTemplate({
530
+ filename: `content/chunks/${name}.json`,
531
+ getContents: async () => JSON.stringify((await read())[name]),
532
+ })
533
+ }
534
+ const ranges: Record<string, ChunkRange[]> = {}
535
+ if (!dev) {
536
+ hamur.hooks.hook("templates:extend", async () => {
537
+ for (const [name, entries] of Object.entries(await read())) {
538
+ const chunks = splitChunks(entries, chunkSize)
539
+ ranges[name] = chunkRangesOf(chunks)
540
+ chunks.forEach((chunk, at) =>
541
+ addTemplate({ filename: `content/chunks/${name}.${at}.json`, getContents: () => JSON.stringify(chunk) }),
542
+ )
543
+ }
544
+ })
545
+ }
546
+ const resolver = createResolver(import.meta.url)
547
+ const store = resolver.resolve("../runtime/store.ts")
548
+ const devStore = resolver.resolve("../runtime/dev-store.ts")
549
+ addTemplate({
550
+ filename: "content/store",
551
+ getContents: async () => {
552
+ if (!dev) return storeModule(config, store, undefined, ranges)
553
+ await read()
554
+ return storeModule(config, store, { module: devStore, buildDir })
555
+ },
556
+ })
557
+ return {
558
+ read,
559
+ rebuild,
560
+ file: (collection, id) => files.get(fileKey(collection, id)),
561
+ body: (collection, id) => bodies.get(fileKey(collection, id)),
562
+ reset: () => void (index = undefined),
563
+ }
564
+ }
565
+
566
+ /** `#hamur/content/store`; in `hamur dev` each collection is read from its dev file on every query. */
567
+ export function storeModule(
568
+ config: ContentConfig,
569
+ store: string,
570
+ dev?: { module: string; buildDir: string },
571
+ chunks?: Record<string, ChunkRange[]>,
572
+ ): string {
573
+ const collections = Object.entries(config.collections).map(([name, { type, expose = true, order }]) => {
574
+ const meta = JSON.stringify({ type, expose, ...(order ? { order } : {}) }).slice(0, -1)
575
+ const ranges = chunks?.[name]
576
+ if (ranges) {
577
+ const list = ranges.map(
578
+ ({ first, last }, at) =>
579
+ `{ first: ${JSON.stringify(first)}, last: ${JSON.stringify(last)}, load: () => import(${JSON.stringify(`#hamur/content/chunks/${name}.${at}.json`)}) }`,
580
+ )
581
+ return ` ${JSON.stringify(name)}: ${meta}, chunks: [${list.join(", ")}] },`
582
+ }
583
+ const load = dev
584
+ ? `devChunk(${JSON.stringify(devChunkPath(dev.buildDir, name))})`
585
+ : `() => import(${JSON.stringify(`#hamur/content/chunks/${name}.json`)})`
586
+ return ` ${JSON.stringify(name)}: ${meta}, load: ${load} },`
587
+ })
588
+ return [
589
+ `import { createStore } from ${JSON.stringify(store)};`,
590
+ ...(dev ? [`import { devChunk } from ${JSON.stringify(dev.module)};`] : []),
591
+ "",
592
+ "export default createStore({",
593
+ ...collections,
594
+ dev ? "}, { cache: false });" : "});",
595
+ "",
596
+ ].join("\n")
597
+ }
@@ -0,0 +1,34 @@
1
+ import { join } from "node:path"
2
+ import { addBunPlugin, addTemplate, createResolver, type HamurContext } from "hamur/kit"
3
+ import type { LoadedContentConfig } from "../types.ts"
4
+
5
+ /** `#hamur/content/live`: every collection name, and the live collections read from `content.config.ts` itself. */
6
+ export function liveModule(configFile: string, config: LoadedContentConfig): string {
7
+ const live = Object.keys(config.live)
8
+ const names = JSON.stringify([...Object.keys(config.collections), ...live])
9
+ if (!live.length) return [`export const names = ${names};`, "export default {};", ""].join("\n")
10
+ return [
11
+ `import config from ${JSON.stringify(configFile)};`,
12
+ "",
13
+ `export const names = ${names};`,
14
+ "export default {",
15
+ ...live.map((name) => ` ${JSON.stringify(name)}: config.collections[${JSON.stringify(name)}],`),
16
+ "};",
17
+ "",
18
+ ].join("\n")
19
+ }
20
+
21
+ /** The live loaders reach the server bundle through `#hamur/content/live`, which imports `content.config.ts`. */
22
+ export function setupLive(config: LoadedContentConfig, hamur: HamurContext): void {
23
+ addTemplate({
24
+ filename: "content/live",
25
+ getContents: () => liveModule(join(hamur.options.rootDir, "content.config.ts"), config),
26
+ })
27
+ if (!Object.keys(config.live).length) return
28
+ const definers = createResolver(import.meta.url).resolve("../server-config.ts")
29
+ // The root export is the module and imports the build; a bundle that holds content.config.ts gets its definers only.
30
+ addBunPlugin({
31
+ name: "hamur-content-config",
32
+ setup: (build) => void build.onResolve({ filter: /^@hamur\/content$/ }, () => ({ path: definers })),
33
+ })
34
+ }
@@ -0,0 +1,34 @@
1
+ import type { HamurContext } from "hamur/kit"
2
+ import type { ContentConfig, ContentEntry, ContentOptions, PageEntry } from "../types.ts"
3
+ import { DiagnosticError } from "hamur/kit"
4
+
5
+ /** `content.prerender`, `true` by default on the `static` preset. */
6
+ export function resolvePrerender(value: unknown, preset: string): boolean {
7
+ if (value === undefined) return preset === "static"
8
+ if (typeof value !== "boolean")
9
+ throw new DiagnosticError("HAMUR_E5334", `content.prerender must be a boolean (got ${JSON.stringify(value)})`)
10
+ return value
11
+ }
12
+
13
+ /** The `path` of every entry of every page collection, drafts left out. */
14
+ export function pagePaths(config: ContentConfig, index: Record<string, ContentEntry[]>): string[] {
15
+ const paths: string[] = []
16
+ for (const [name, collection] of Object.entries(config.collections)) {
17
+ if (collection.type !== "page") continue
18
+ for (const entry of (index[name] ?? []) as PageEntry[]) if (!entry.draft) paths.push(entry.path)
19
+ }
20
+ return paths
21
+ }
22
+
23
+ /** Adds the page paths to the prerender routes, which `hamur generate` then writes. */
24
+ export function setupPrerender(
25
+ options: ContentOptions,
26
+ config: ContentConfig,
27
+ entries: () => Promise<Record<string, ContentEntry[]>>,
28
+ hamur: HamurContext,
29
+ ): void {
30
+ if (!resolvePrerender(options.prerender, hamur.options.preset)) return
31
+ hamur.hooks.hook("prerender:routes", async (routes) => {
32
+ for (const path of pagePaths(config, await entries())) routes.add(path)
33
+ })
34
+ }