@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.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/chunks/bun-render-65mwzeq2.js +58 -0
- package/dist/chunks/bun-render-7jxnxg3v.js +714 -0
- package/dist/chunks/bun-render-mxhn5twt.js +130 -0
- package/dist/chunks/bun-render-w7fh3fg7.js +36 -0
- package/dist/src/adapters/html.js +134 -0
- package/dist/src/adapters/preact.js +126 -0
- package/dist/src/adapters/react.js +116 -0
- package/dist/src/adapters/solid.js +153 -0
- package/dist/src/adapters/svelte.js +90 -0
- package/dist/src/adapters/vue.js +166 -0
- package/dist/src/index.js +2732 -0
- package/dist/src/query.js +97 -0
- package/dist/src/render.js +12 -0
- package/dist/src/server/index.js +349 -0
- package/dist/types/src/adapters/html.d.ts +54 -0
- package/dist/types/src/adapters/page.d.ts +21 -0
- package/dist/types/src/adapters/preact.d.ts +53 -0
- package/dist/types/src/adapters/prose.d.ts +21 -0
- package/dist/types/src/adapters/react.d.ts +53 -0
- package/dist/types/src/adapters/search.d.ts +12 -0
- package/dist/types/src/adapters/solid.d.ts +54 -0
- package/dist/types/src/adapters/svelte-page.d.ts +9 -0
- package/dist/types/src/adapters/svelte-search.d.ts +9 -0
- package/dist/types/src/adapters/svelte.d.ts +24 -0
- package/dist/types/src/adapters/vue.d.ts +189 -0
- package/dist/types/src/build/api.d.ts +24 -0
- package/dist/types/src/build/dev-route.d.ts +4 -0
- package/dist/types/src/build/dev.d.ts +48 -0
- package/dist/types/src/build/graphql.d.ts +10 -0
- package/dist/types/src/build/image.d.ts +16 -0
- package/dist/types/src/build/index.d.ts +76 -0
- package/dist/types/src/build/live.d.ts +6 -0
- package/dist/types/src/build/prerender.d.ts +8 -0
- package/dist/types/src/build/query.d.ts +10 -0
- package/dist/types/src/build/raw.d.ts +23 -0
- package/dist/types/src/build/search.d.ts +9 -0
- package/dist/types/src/build/types.d.ts +16 -0
- package/dist/types/src/component.d.ts +10 -0
- package/dist/types/src/config.d.ts +6 -0
- package/dist/types/src/define.d.ts +14 -0
- package/dist/types/src/error.d.ts +4 -0
- package/dist/types/src/image.d.ts +15 -0
- package/dist/types/src/index.d.ts +64 -0
- package/dist/types/src/loaders/data.d.ts +12 -0
- package/dist/types/src/loaders/file.d.ts +3 -0
- package/dist/types/src/loaders/git.d.ts +27 -0
- package/dist/types/src/loaders/glob.d.ts +14 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/query.d.ts +17 -0
- package/dist/types/src/render.d.ts +9 -0
- package/dist/types/src/runtime/client.d.ts +25 -0
- package/dist/types/src/runtime/dev-client.d.ts +4 -0
- package/dist/types/src/runtime/dev-plugin.d.ts +12 -0
- package/dist/types/src/runtime/dev-store.d.ts +5 -0
- package/dist/types/src/runtime/live.d.ts +36 -0
- package/dist/types/src/runtime/navigation.d.ts +35 -0
- package/dist/types/src/runtime/page-plugin.d.ts +2 -0
- package/dist/types/src/runtime/page-source.d.ts +12 -0
- package/dist/types/src/runtime/query.d.ts +100 -0
- package/dist/types/src/runtime/raw-path.d.ts +2 -0
- package/dist/types/src/runtime/refresh-body.d.ts +4 -0
- package/dist/types/src/runtime/search-loaders.d.ts +7 -0
- package/dist/types/src/runtime/search-plugin.d.ts +2 -0
- package/dist/types/src/runtime/search-store.d.ts +19 -0
- package/dist/types/src/runtime/search.d.ts +28 -0
- package/dist/types/src/runtime/sections.d.ts +36 -0
- package/dist/types/src/runtime/server-store.d.ts +4 -0
- package/dist/types/src/runtime/store.d.ts +31 -0
- package/dist/types/src/server/door-dev-static.d.ts +3 -0
- package/dist/types/src/server/door-dev.d.ts +4 -0
- package/dist/types/src/server/door-static.d.ts +2 -0
- package/dist/types/src/server/door.d.ts +3 -0
- package/dist/types/src/server/endpoint.d.ts +1 -0
- package/dist/types/src/server/graphql.d.ts +24 -0
- package/dist/types/src/server/index.d.ts +10 -0
- package/dist/types/src/server/install.d.ts +1 -0
- package/dist/types/src/server/live.d.ts +10 -0
- package/dist/types/src/server/query.d.ts +15 -0
- package/dist/types/src/server/refresh.d.ts +2 -0
- package/dist/types/src/server/rest.d.ts +62 -0
- package/dist/types/src/server/search.d.ts +5 -0
- package/dist/types/src/server-config.d.ts +12 -0
- package/dist/types/src/source.d.ts +24 -0
- package/dist/types/src/types.d.ts +293 -0
- package/package.json +140 -4
- package/src/adapters/ContentRenderer.svelte +27 -0
- package/src/adapters/ProseA.svelte +11 -0
- package/src/adapters/ProseBlockquote.svelte +7 -0
- package/src/adapters/ProseCode.svelte +7 -0
- package/src/adapters/ProseEm.svelte +7 -0
- package/src/adapters/ProseH1.svelte +7 -0
- package/src/adapters/ProseH2.svelte +7 -0
- package/src/adapters/ProseH3.svelte +7 -0
- package/src/adapters/ProseH4.svelte +7 -0
- package/src/adapters/ProseH5.svelte +7 -0
- package/src/adapters/ProseH6.svelte +7 -0
- package/src/adapters/ProseHr.svelte +5 -0
- package/src/adapters/ProseImg.svelte +5 -0
- package/src/adapters/ProseLi.svelte +7 -0
- package/src/adapters/ProseOl.svelte +7 -0
- package/src/adapters/ProseP.svelte +7 -0
- package/src/adapters/ProsePre.svelte +21 -0
- package/src/adapters/ProseStrong.svelte +7 -0
- package/src/adapters/ProseTable.svelte +7 -0
- package/src/adapters/ProseUl.svelte +7 -0
- package/src/adapters/html.ts +152 -0
- package/src/adapters/page.ts +52 -0
- package/src/adapters/preact.ts +154 -0
- package/src/adapters/prose.ts +55 -0
- package/src/adapters/react.ts +142 -0
- package/src/adapters/search.ts +32 -0
- package/src/adapters/solid.ts +183 -0
- package/src/adapters/svelte-defaults.ts +41 -0
- package/src/adapters/svelte-page.ts +29 -0
- package/src/adapters/svelte-search.ts +36 -0
- package/src/adapters/svelte.ts +30 -0
- package/src/adapters/test/OwnA.svelte +7 -0
- package/src/adapters/test/OwnH1.svelte +7 -0
- package/src/adapters/test/OwnPre.svelte +7 -0
- package/src/adapters/test/support.ts +106 -0
- package/src/adapters/vue.ts +182 -0
- package/src/build/api.ts +201 -0
- package/src/build/dev-route.ts +5 -0
- package/src/build/dev.ts +299 -0
- package/src/build/graphql.ts +197 -0
- package/src/build/image.ts +60 -0
- package/src/build/index.ts +597 -0
- package/src/build/live.ts +34 -0
- package/src/build/prerender.ts +34 -0
- package/src/build/query.ts +70 -0
- package/src/build/raw.ts +157 -0
- package/src/build/search.ts +64 -0
- package/src/build/types.ts +108 -0
- package/src/component.ts +86 -0
- package/src/config.ts +156 -0
- package/src/define.ts +33 -0
- package/src/env.d.ts +34 -0
- package/src/error.ts +4 -0
- package/src/image.ts +41 -0
- package/src/index.ts +103 -0
- package/src/loaders/data.ts +186 -0
- package/src/loaders/file.ts +53 -0
- package/src/loaders/git.ts +266 -0
- package/src/loaders/glob.ts +179 -0
- package/src/module.ts +26 -0
- package/src/query.ts +82 -0
- package/src/render.ts +16 -0
- package/src/runtime/client.ts +75 -0
- package/src/runtime/dev-client.ts +6 -0
- package/src/runtime/dev-plugin.ts +64 -0
- package/src/runtime/dev-store.ts +19 -0
- package/src/runtime/live.ts +331 -0
- package/src/runtime/navigation.ts +225 -0
- package/src/runtime/page-plugin.ts +13 -0
- package/src/runtime/page-source.ts +22 -0
- package/src/runtime/query.ts +605 -0
- package/src/runtime/raw-path.ts +2 -0
- package/src/runtime/refresh-body.ts +22 -0
- package/src/runtime/search-loaders.ts +14 -0
- package/src/runtime/search-plugin.ts +6 -0
- package/src/runtime/search-store.ts +73 -0
- package/src/runtime/search.ts +126 -0
- package/src/runtime/sections.ts +155 -0
- package/src/runtime/server-store.ts +12 -0
- package/src/runtime/store.ts +59 -0
- package/src/server/door-dev-static.ts +6 -0
- package/src/server/door-dev.ts +7 -0
- package/src/server/door-static.ts +4 -0
- package/src/server/door.ts +6 -0
- package/src/server/endpoint.ts +17 -0
- package/src/server/graphql.ts +59 -0
- package/src/server/index.ts +17 -0
- package/src/server/install.ts +6 -0
- package/src/server/live.ts +51 -0
- package/src/server/query.ts +46 -0
- package/src/server/refresh.ts +19 -0
- package/src/server/rest.ts +157 -0
- package/src/server/search.ts +22 -0
- package/src/server-config.ts +24 -0
- package/src/source.ts +99 -0
- package/src/types.ts +282 -0
|
@@ -0,0 +1,2732 @@
|
|
|
1
|
+
// packages/content/src/module.ts
|
|
2
|
+
import { defineModule } from "hamur/kit";
|
|
3
|
+
|
|
4
|
+
// packages/content/src/build/dev.ts
|
|
5
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
addAppPlugin as addAppPlugin2,
|
|
8
|
+
addDevServerHandler,
|
|
9
|
+
createResolver as createResolver2,
|
|
10
|
+
DiagnosticError as DiagnosticError2,
|
|
11
|
+
useDevChannel,
|
|
12
|
+
useLogger
|
|
13
|
+
} from "hamur/kit";
|
|
14
|
+
|
|
15
|
+
// packages/content/src/runtime/refresh-body.ts
|
|
16
|
+
var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
17
|
+
function parseRefreshBody(text) {
|
|
18
|
+
if (text.trim() === "")
|
|
19
|
+
return {};
|
|
20
|
+
let body;
|
|
21
|
+
try {
|
|
22
|
+
body = JSON.parse(text);
|
|
23
|
+
} catch {
|
|
24
|
+
throw new TypeError("POST /_hamur/content/refresh: the body must be JSON { collections?: string[] }");
|
|
25
|
+
}
|
|
26
|
+
const collections = isObject(body) ? body.collections : undefined;
|
|
27
|
+
if (!isObject(body) || collections !== undefined && !(Array.isArray(collections) && collections.every((name) => typeof name === "string"))) {
|
|
28
|
+
throw new TypeError("POST /_hamur/content/refresh: the body must be JSON { collections?: string[] }");
|
|
29
|
+
}
|
|
30
|
+
return collections === undefined ? {} : { collections };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// packages/content/src/build/dev-route.ts
|
|
34
|
+
var DEV_ROUTE = "/_hamur/content/dev";
|
|
35
|
+
var REFRESH_ROUTE = "/_hamur/content/refresh";
|
|
36
|
+
|
|
37
|
+
// packages/content/src/build/search.ts
|
|
38
|
+
import { DiagnosticError, addAppPlugin, addTemplate, createResolver } from "hamur/kit";
|
|
39
|
+
|
|
40
|
+
// packages/content/src/runtime/search.ts
|
|
41
|
+
var SEPARATORS = /[^\p{L}\p{N}]+/u;
|
|
42
|
+
var fold = (text) => text.toLowerCase().normalize("NFD").replace(/\p{M}/gu, "");
|
|
43
|
+
var tokenize = (text) => fold(text).split(SEPARATORS).filter(Boolean);
|
|
44
|
+
var compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
45
|
+
var mean = (values) => values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0;
|
|
46
|
+
function buildSearchIndex(sections) {
|
|
47
|
+
const found = new Map;
|
|
48
|
+
const titleLengths = [];
|
|
49
|
+
const bodyLengths = [];
|
|
50
|
+
sections.forEach((section, number) => {
|
|
51
|
+
const counts = new Map;
|
|
52
|
+
const add = (token, field) => {
|
|
53
|
+
let pair = counts.get(token);
|
|
54
|
+
if (!pair)
|
|
55
|
+
counts.set(token, pair = [0, 0]);
|
|
56
|
+
pair[field]++;
|
|
57
|
+
};
|
|
58
|
+
const title = tokenize(section.title);
|
|
59
|
+
const body = tokenize(section.content);
|
|
60
|
+
for (const token of title)
|
|
61
|
+
add(token, 0);
|
|
62
|
+
for (const token of body)
|
|
63
|
+
add(token, 1);
|
|
64
|
+
titleLengths.push(title.length);
|
|
65
|
+
bodyLengths.push(body.length);
|
|
66
|
+
for (const [term, [inTitle, inBody]] of counts) {
|
|
67
|
+
let list = found.get(term);
|
|
68
|
+
if (!list)
|
|
69
|
+
found.set(term, list = []);
|
|
70
|
+
list.push(number, inTitle, inBody);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
const terms = [...found.keys()].sort(compare);
|
|
74
|
+
return {
|
|
75
|
+
version: 1,
|
|
76
|
+
sections: sections.map(({ id, title, titles, level }) => ({ id, title, titles, level })),
|
|
77
|
+
titleLengths,
|
|
78
|
+
bodyLengths,
|
|
79
|
+
avgTitleLength: mean(titleLengths),
|
|
80
|
+
avgBodyLength: mean(bodyLengths),
|
|
81
|
+
terms,
|
|
82
|
+
postings: terms.map((term) => found.get(term))
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// packages/content/src/runtime/query.ts
|
|
87
|
+
class QueryError extends Error {
|
|
88
|
+
}
|
|
89
|
+
var OPERATORS = new Set([
|
|
90
|
+
"=",
|
|
91
|
+
"<>",
|
|
92
|
+
">",
|
|
93
|
+
">=",
|
|
94
|
+
"<",
|
|
95
|
+
"<=",
|
|
96
|
+
"IN",
|
|
97
|
+
"NOT IN",
|
|
98
|
+
"BETWEEN",
|
|
99
|
+
"NOT BETWEEN",
|
|
100
|
+
"IS NULL",
|
|
101
|
+
"IS NOT NULL",
|
|
102
|
+
"LIKE",
|
|
103
|
+
"NOT LIKE"
|
|
104
|
+
]);
|
|
105
|
+
var QUERY_KEYS = new Set(["where", "select", "order", "limit", "skip", "count"]);
|
|
106
|
+
var DATA_FIELDS = ["collection", "id", "stem", "extension"];
|
|
107
|
+
var PAGE_FIELDS = [
|
|
108
|
+
...DATA_FIELDS,
|
|
109
|
+
"path",
|
|
110
|
+
"title",
|
|
111
|
+
"description",
|
|
112
|
+
"seo",
|
|
113
|
+
"navigation",
|
|
114
|
+
"draft",
|
|
115
|
+
"navigationDirs",
|
|
116
|
+
"body",
|
|
117
|
+
"excerpt",
|
|
118
|
+
"headings",
|
|
119
|
+
"toc",
|
|
120
|
+
"readingTime"
|
|
121
|
+
];
|
|
122
|
+
var QUERY_LIMITS = {
|
|
123
|
+
conditions: 100,
|
|
124
|
+
depth: 8,
|
|
125
|
+
values: 1000,
|
|
126
|
+
select: 100,
|
|
127
|
+
order: 10,
|
|
128
|
+
field: 200,
|
|
129
|
+
pattern: 200
|
|
130
|
+
};
|
|
131
|
+
function fail(message) {
|
|
132
|
+
throw new QueryError(message);
|
|
133
|
+
}
|
|
134
|
+
var shown = (value) => typeof value === "function" ? "a function" : JSON.stringify(value) ?? String(value);
|
|
135
|
+
var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
136
|
+
var FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
|
|
137
|
+
function checkFieldPath(field) {
|
|
138
|
+
if (typeof field !== "string" || field === "" || field.length > QUERY_LIMITS.field || field.split(".").includes(""))
|
|
139
|
+
fail(`a field is a name or a dotted path (got ${shown(field)})`);
|
|
140
|
+
const segment = field.split(".").find((part) => FORBIDDEN_SEGMENTS.has(part));
|
|
141
|
+
if (segment !== undefined)
|
|
142
|
+
fail(`a field may not name ${shown(segment)} (got ${shown(field)})`);
|
|
143
|
+
}
|
|
144
|
+
var isScalar = (value) => value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
145
|
+
function checkCondition(field, operator, value) {
|
|
146
|
+
if (typeof operator !== "string" || !OPERATORS.has(operator))
|
|
147
|
+
fail(`unknown operator ${shown(operator)}`);
|
|
148
|
+
checkFieldPath(field);
|
|
149
|
+
switch (operator) {
|
|
150
|
+
case "IS NULL":
|
|
151
|
+
case "IS NOT NULL":
|
|
152
|
+
if (value !== undefined)
|
|
153
|
+
fail(`${operator} takes no value (got ${shown(value)})`);
|
|
154
|
+
return;
|
|
155
|
+
case "IN":
|
|
156
|
+
case "NOT IN":
|
|
157
|
+
if (!Array.isArray(value))
|
|
158
|
+
fail(`IN takes an array (got ${shown(value)})`);
|
|
159
|
+
if (value.length > QUERY_LIMITS.values)
|
|
160
|
+
fail(`IN takes at most ${QUERY_LIMITS.values} values (got ${value.length})`);
|
|
161
|
+
if (!value.every(isScalar))
|
|
162
|
+
fail(`IN takes strings, numbers, booleans or null (got ${shown(value)})`);
|
|
163
|
+
return;
|
|
164
|
+
case "BETWEEN":
|
|
165
|
+
case "NOT BETWEEN":
|
|
166
|
+
if (!Array.isArray(value) || value.length !== 2 || !value.every(isScalar))
|
|
167
|
+
fail(`BETWEEN takes [low, high] (got ${shown(value)})`);
|
|
168
|
+
return;
|
|
169
|
+
case "LIKE":
|
|
170
|
+
case "NOT LIKE":
|
|
171
|
+
if (typeof value !== "string")
|
|
172
|
+
fail(`LIKE takes a string (got ${shown(value)})`);
|
|
173
|
+
if (value.length > QUERY_LIMITS.pattern)
|
|
174
|
+
fail(`LIKE takes a pattern of at most ${QUERY_LIMITS.pattern} characters`);
|
|
175
|
+
return;
|
|
176
|
+
default:
|
|
177
|
+
if (isScalar(value) || (operator === "=" || operator === "<>") && Array.isArray(value) && value.length <= QUERY_LIMITS.values && value.every(isScalar))
|
|
178
|
+
return;
|
|
179
|
+
fail(`${operator} takes a string, number, boolean or null${operator === "=" || operator === "<>" ? ", or an array of them" : ""} (got ${shown(value)})`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function fieldsOf(type, entries) {
|
|
183
|
+
const fields = new Set(type === "page" ? PAGE_FIELDS : DATA_FIELDS);
|
|
184
|
+
for (const entry of entries)
|
|
185
|
+
for (const key of Object.keys(entry))
|
|
186
|
+
fields.add(key);
|
|
187
|
+
return fields;
|
|
188
|
+
}
|
|
189
|
+
var fieldCache = new WeakMap;
|
|
190
|
+
function knownFields(type, entries) {
|
|
191
|
+
let fields = fieldCache.get(entries);
|
|
192
|
+
if (!fields)
|
|
193
|
+
fieldCache.set(entries, fields = fieldsOf(type, entries));
|
|
194
|
+
return fields;
|
|
195
|
+
}
|
|
196
|
+
var nonNegative = (value, name) => {
|
|
197
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
198
|
+
fail(`${name} must be a non-negative integer`);
|
|
199
|
+
};
|
|
200
|
+
function checkQuery(value, fields, collection) {
|
|
201
|
+
if (!isRecord(value))
|
|
202
|
+
fail(`query must be an object (got ${shown(value)})`);
|
|
203
|
+
const query = value;
|
|
204
|
+
for (const key of Object.keys(query))
|
|
205
|
+
if (!QUERY_KEYS.has(key))
|
|
206
|
+
fail(`unknown query key ${shown(key)}`);
|
|
207
|
+
const field = (name) => {
|
|
208
|
+
checkFieldPath(name);
|
|
209
|
+
if (!fields.has(name.split(".")[0]))
|
|
210
|
+
fail(`unknown field ${shown(name)} in collection ${shown(collection)}`);
|
|
211
|
+
};
|
|
212
|
+
let conditions = 0;
|
|
213
|
+
const clauses = (list, depth) => {
|
|
214
|
+
if (!Array.isArray(list))
|
|
215
|
+
fail(`where must be an array (got ${shown(list)})`);
|
|
216
|
+
if (depth > QUERY_LIMITS.depth)
|
|
217
|
+
fail(`groups nest at most ${QUERY_LIMITS.depth} deep`);
|
|
218
|
+
for (const clause of list) {
|
|
219
|
+
if (!isRecord(clause))
|
|
220
|
+
fail(`a where clause must be an object (got ${shown(clause)})`);
|
|
221
|
+
const { join, ...rest } = clause;
|
|
222
|
+
if (join !== "AND" && join !== "OR")
|
|
223
|
+
fail(`join must be "AND" or "OR" (got ${shown(join)})`);
|
|
224
|
+
if (++conditions > QUERY_LIMITS.conditions)
|
|
225
|
+
fail(`a query takes at most ${QUERY_LIMITS.conditions} conditions`);
|
|
226
|
+
if (Object.hasOwn(rest, "where")) {
|
|
227
|
+
for (const key of Object.keys(rest))
|
|
228
|
+
if (key !== "where")
|
|
229
|
+
fail(`unknown key ${shown(key)} in a where group`);
|
|
230
|
+
clauses(rest.where, depth + 1);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
for (const key of Object.keys(rest))
|
|
234
|
+
if (key !== "field" && key !== "operator" && key !== "value")
|
|
235
|
+
fail(`unknown key ${shown(key)} in a where condition`);
|
|
236
|
+
checkCondition(rest.field, rest.operator, rest.value);
|
|
237
|
+
field(rest.field);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
if (query.where !== undefined)
|
|
241
|
+
clauses(query.where, 1);
|
|
242
|
+
if (query.select !== undefined) {
|
|
243
|
+
if (!Array.isArray(query.select))
|
|
244
|
+
fail(`select must be an array of fields (got ${shown(query.select)})`);
|
|
245
|
+
if (query.select.length > QUERY_LIMITS.select)
|
|
246
|
+
fail(`select takes at most ${QUERY_LIMITS.select} fields`);
|
|
247
|
+
query.select.forEach(field);
|
|
248
|
+
}
|
|
249
|
+
if (query.order !== undefined) {
|
|
250
|
+
if (!Array.isArray(query.order))
|
|
251
|
+
fail(`order must be an array of [field, "ASC" | "DESC"] (got ${shown(query.order)})`);
|
|
252
|
+
if (query.order.length > QUERY_LIMITS.order)
|
|
253
|
+
fail(`order takes at most ${QUERY_LIMITS.order} fields`);
|
|
254
|
+
for (const item of query.order) {
|
|
255
|
+
if (!Array.isArray(item) || item.length !== 2)
|
|
256
|
+
fail(`order must be an array of [field, "ASC" | "DESC"] (got ${shown(item)})`);
|
|
257
|
+
const [name, direction] = item;
|
|
258
|
+
field(name);
|
|
259
|
+
if (direction !== "ASC" && direction !== "DESC")
|
|
260
|
+
fail(`order direction must be "ASC" or "DESC" (got ${shown(direction)})`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (query.limit !== undefined)
|
|
264
|
+
nonNegative(query.limit, "limit");
|
|
265
|
+
if (query.skip !== undefined)
|
|
266
|
+
nonNegative(query.skip, "skip");
|
|
267
|
+
if (query.count !== undefined && typeof query.count !== "boolean")
|
|
268
|
+
fail(`count must be a boolean (got ${shown(query.count)})`);
|
|
269
|
+
return query;
|
|
270
|
+
}
|
|
271
|
+
function valueAt(entry, field) {
|
|
272
|
+
let value = entry;
|
|
273
|
+
for (const key of field.split(".")) {
|
|
274
|
+
if (!isRecord(value) || !Object.hasOwn(value, key))
|
|
275
|
+
return null;
|
|
276
|
+
value = value[key];
|
|
277
|
+
}
|
|
278
|
+
return value ?? null;
|
|
279
|
+
}
|
|
280
|
+
var kind = (value) => typeof value === "boolean" ? 1 : typeof value === "number" ? 2 : typeof value === "string" ? 3 : Array.isArray(value) ? 4 : 5;
|
|
281
|
+
function compareText(a, b) {
|
|
282
|
+
if (a === b)
|
|
283
|
+
return 0;
|
|
284
|
+
const left = a[Symbol.iterator]();
|
|
285
|
+
const right = b[Symbol.iterator]();
|
|
286
|
+
for (;; ) {
|
|
287
|
+
const x = left.next();
|
|
288
|
+
const y = right.next();
|
|
289
|
+
if (x.done || y.done)
|
|
290
|
+
return x.done ? y.done ? 0 : -1 : 1;
|
|
291
|
+
const delta = x.value.codePointAt(0) - y.value.codePointAt(0);
|
|
292
|
+
if (delta)
|
|
293
|
+
return delta < 0 ? -1 : 1;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
function compare2(a, b) {
|
|
297
|
+
const ka = kind(a);
|
|
298
|
+
const kb = kind(b);
|
|
299
|
+
if (ka !== kb)
|
|
300
|
+
return ka - kb;
|
|
301
|
+
if (ka === 1)
|
|
302
|
+
return Number(a) - Number(b);
|
|
303
|
+
if (ka === 2)
|
|
304
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
305
|
+
if (ka === 3)
|
|
306
|
+
return compareText(a, b);
|
|
307
|
+
return compareText(JSON.stringify(a), JSON.stringify(b));
|
|
308
|
+
}
|
|
309
|
+
var equal = (a, b) => a !== null && b !== null && compare2(a, b) === 0;
|
|
310
|
+
var ordered = (a, b, test) => a === null || b === null ? null : test(compare2(a, b));
|
|
311
|
+
var textOf = (value) => typeof value === "string" ? value : typeof value === "boolean" ? value ? "1" : "0" : typeof value === "number" ? String(value) : JSON.stringify(value);
|
|
312
|
+
var foldAscii = (char) => char.length === 1 && char >= "A" && char <= "Z" ? String.fromCharCode(char.charCodeAt(0) + 32) : char;
|
|
313
|
+
function like(text, pattern) {
|
|
314
|
+
const s = Array.from(text, foldAscii);
|
|
315
|
+
const p = Array.from(pattern, foldAscii);
|
|
316
|
+
let i = 0;
|
|
317
|
+
let j = 0;
|
|
318
|
+
let star = -1;
|
|
319
|
+
let mark = 0;
|
|
320
|
+
while (i < s.length) {
|
|
321
|
+
if (j < p.length && p[j] !== "%" && (p[j] === "_" || p[j] === s[i])) {
|
|
322
|
+
i++;
|
|
323
|
+
j++;
|
|
324
|
+
} else if (j < p.length && p[j] === "%") {
|
|
325
|
+
star = j++;
|
|
326
|
+
mark = i;
|
|
327
|
+
} else if (star !== -1) {
|
|
328
|
+
j = star + 1;
|
|
329
|
+
i = ++mark;
|
|
330
|
+
} else
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
while (p[j] === "%")
|
|
334
|
+
j++;
|
|
335
|
+
return j === p.length;
|
|
336
|
+
}
|
|
337
|
+
function matches(entry, { field, operator, value }) {
|
|
338
|
+
const actual = valueAt(entry, field);
|
|
339
|
+
switch (operator) {
|
|
340
|
+
case "IS NULL":
|
|
341
|
+
return actual === null;
|
|
342
|
+
case "IS NOT NULL":
|
|
343
|
+
return actual !== null;
|
|
344
|
+
case "=":
|
|
345
|
+
return equal(actual, value ?? null);
|
|
346
|
+
case "<>":
|
|
347
|
+
return actual !== null && value !== null && !equal(actual, value);
|
|
348
|
+
case ">":
|
|
349
|
+
return ordered(actual, value ?? null, (order) => order > 0) === true;
|
|
350
|
+
case ">=":
|
|
351
|
+
return ordered(actual, value ?? null, (order) => order >= 0) === true;
|
|
352
|
+
case "<":
|
|
353
|
+
return ordered(actual, value ?? null, (order) => order < 0) === true;
|
|
354
|
+
case "<=":
|
|
355
|
+
return ordered(actual, value ?? null, (order) => order <= 0) === true;
|
|
356
|
+
case "IN":
|
|
357
|
+
case "NOT IN": {
|
|
358
|
+
const list = value;
|
|
359
|
+
if (list.length === 0)
|
|
360
|
+
return operator === "NOT IN";
|
|
361
|
+
if (actual === null)
|
|
362
|
+
return false;
|
|
363
|
+
const items = Array.isArray(actual) ? actual : [actual];
|
|
364
|
+
const found = items.some((item) => list.some((candidate) => equal(item, candidate)));
|
|
365
|
+
if (operator === "IN")
|
|
366
|
+
return found;
|
|
367
|
+
return !found && !list.includes(null);
|
|
368
|
+
}
|
|
369
|
+
case "BETWEEN":
|
|
370
|
+
case "NOT BETWEEN": {
|
|
371
|
+
const [low, high] = value;
|
|
372
|
+
const above = ordered(actual, low, (order) => order >= 0);
|
|
373
|
+
const below = ordered(actual, high, (order) => order <= 0);
|
|
374
|
+
const inside = above === false || below === false ? false : above === null || below === null ? null : true;
|
|
375
|
+
return inside === null ? false : operator === "BETWEEN" ? inside : !inside;
|
|
376
|
+
}
|
|
377
|
+
case "LIKE":
|
|
378
|
+
case "NOT LIKE":
|
|
379
|
+
return actual !== null && like(textOf(actual), value) === (operator === "LIKE");
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
function passes(entry, clauses) {
|
|
383
|
+
let result = true;
|
|
384
|
+
clauses.forEach((clause, index) => {
|
|
385
|
+
const term = "where" in clause ? passes(entry, clause.where) : matches(entry, clause);
|
|
386
|
+
result = index === 0 ? term : clause.join === "AND" ? result && term : result || term;
|
|
387
|
+
});
|
|
388
|
+
return result;
|
|
389
|
+
}
|
|
390
|
+
function sorter(order) {
|
|
391
|
+
return (a, b) => {
|
|
392
|
+
for (const [field, direction] of order) {
|
|
393
|
+
const x = valueAt(a, field);
|
|
394
|
+
const y = valueAt(b, field);
|
|
395
|
+
const result = x === null ? y === null ? 0 : -1 : y === null ? 1 : compare2(x, y);
|
|
396
|
+
if (result)
|
|
397
|
+
return direction === "DESC" ? -result : result;
|
|
398
|
+
}
|
|
399
|
+
return 0;
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
function pick(entry, select) {
|
|
403
|
+
const out = { id: entry.id };
|
|
404
|
+
const whole = ["id"];
|
|
405
|
+
for (const field of select.toSorted((a, b) => a.length - b.length)) {
|
|
406
|
+
if (whole.some((taken) => field === taken || field.startsWith(`${taken}.`)))
|
|
407
|
+
continue;
|
|
408
|
+
const value = valueAt(entry, field);
|
|
409
|
+
whole.push(field);
|
|
410
|
+
const keys = field.split(".");
|
|
411
|
+
let target = out;
|
|
412
|
+
for (const key of keys.slice(0, -1)) {
|
|
413
|
+
if (!Object.hasOwn(target, key) || !isRecord(target[key]))
|
|
414
|
+
Object.defineProperty(target, key, { value: {}, writable: true, enumerable: true, configurable: true });
|
|
415
|
+
target = target[key];
|
|
416
|
+
}
|
|
417
|
+
Object.defineProperty(target, keys.at(-1), {
|
|
418
|
+
value: structuredClone(value),
|
|
419
|
+
writable: true,
|
|
420
|
+
enumerable: true,
|
|
421
|
+
configurable: true
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
return out;
|
|
425
|
+
}
|
|
426
|
+
function runQuery(name, collection, entries, value) {
|
|
427
|
+
const query = checkQuery(value, knownFields(collection.type, entries), name);
|
|
428
|
+
const where = query.where ?? [];
|
|
429
|
+
const found = where.length ? entries.filter((entry) => passes(entry, where)) : [...entries];
|
|
430
|
+
if (query.count)
|
|
431
|
+
return found.length;
|
|
432
|
+
const order = query.order ?? (collection.order ? [collection.order] : []);
|
|
433
|
+
const sorted = order.length ? found.sort(sorter(order)) : found;
|
|
434
|
+
const skip = query.skip ?? 0;
|
|
435
|
+
const page = sorted.slice(skip, query.limit === undefined ? undefined : skip + query.limit);
|
|
436
|
+
return query.select ? page.map((entry) => pick(entry, query.select)) : page.map((entry) => structuredClone(entry));
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// packages/content/src/runtime/sections.ts
|
|
440
|
+
var BLOCKS = new Set([
|
|
441
|
+
"root",
|
|
442
|
+
"p",
|
|
443
|
+
"h1",
|
|
444
|
+
"h2",
|
|
445
|
+
"h3",
|
|
446
|
+
"h4",
|
|
447
|
+
"h5",
|
|
448
|
+
"h6",
|
|
449
|
+
"blockquote",
|
|
450
|
+
"ul",
|
|
451
|
+
"ol",
|
|
452
|
+
"li",
|
|
453
|
+
"pre",
|
|
454
|
+
"hr",
|
|
455
|
+
"br",
|
|
456
|
+
"html",
|
|
457
|
+
"table",
|
|
458
|
+
"thead",
|
|
459
|
+
"tbody",
|
|
460
|
+
"tr",
|
|
461
|
+
"th",
|
|
462
|
+
"td"
|
|
463
|
+
]);
|
|
464
|
+
var HEADING = /^h([1-6])$/;
|
|
465
|
+
function depthOf(value, name) {
|
|
466
|
+
const match = typeof value === "string" ? HEADING.exec(value) : null;
|
|
467
|
+
if (!match)
|
|
468
|
+
throw new QueryError(`${name} must be "h1" to "h6" (got ${JSON.stringify(value)})`);
|
|
469
|
+
return Number(match[1]);
|
|
470
|
+
}
|
|
471
|
+
function resolveSectionOptions(options = {}) {
|
|
472
|
+
const { ignoredTags = [], minHeading = "h1", maxHeading = "h6" } = options;
|
|
473
|
+
if (!Array.isArray(ignoredTags) || !ignoredTags.every((tag) => typeof tag === "string"))
|
|
474
|
+
throw new QueryError(`ignoredTags must be an array of tag names (got ${JSON.stringify(ignoredTags)})`);
|
|
475
|
+
const min = depthOf(minHeading, "minHeading");
|
|
476
|
+
const max = depthOf(maxHeading, "maxHeading");
|
|
477
|
+
if (min > max)
|
|
478
|
+
throw new QueryError(`minHeading ${minHeading} is deeper than maxHeading ${maxHeading}`);
|
|
479
|
+
return { ignored: new Set(ignoredTags), min, max };
|
|
480
|
+
}
|
|
481
|
+
function collect(node, ignored, out) {
|
|
482
|
+
if (typeof node === "string")
|
|
483
|
+
return void out.push(node);
|
|
484
|
+
const tag = node[0];
|
|
485
|
+
if (ignored.has(tag) || tag === "html")
|
|
486
|
+
return void out.push(" ");
|
|
487
|
+
const block = BLOCKS.has(tag);
|
|
488
|
+
if (block)
|
|
489
|
+
out.push(" ");
|
|
490
|
+
for (let i = 2;i < node.length; i++)
|
|
491
|
+
collect(node[i], ignored, out);
|
|
492
|
+
if (block)
|
|
493
|
+
out.push(" ");
|
|
494
|
+
}
|
|
495
|
+
var plain = (parts) => parts.join("").replace(/\s+/g, " ").trim();
|
|
496
|
+
function sectionsOf(page, { ignored, min, max }) {
|
|
497
|
+
const out = [];
|
|
498
|
+
const stack = [];
|
|
499
|
+
let current = {
|
|
500
|
+
id: page.path,
|
|
501
|
+
title: page.title ?? "",
|
|
502
|
+
titles: [],
|
|
503
|
+
level: 1,
|
|
504
|
+
parts: [],
|
|
505
|
+
lead: true
|
|
506
|
+
};
|
|
507
|
+
const close = () => {
|
|
508
|
+
const content = plain(current.parts);
|
|
509
|
+
if (!current.lead || content !== "" || current.title !== "" && min > 1)
|
|
510
|
+
out.push({ id: current.id, title: current.title, titles: current.titles, content, level: current.level });
|
|
511
|
+
};
|
|
512
|
+
for (let i = 2;i < page.body.length; i++) {
|
|
513
|
+
const node = page.body[i];
|
|
514
|
+
const depth = typeof node === "string" ? 0 : Number(HEADING.exec(node[0])?.[1] ?? 0);
|
|
515
|
+
if (depth >= min && depth <= max) {
|
|
516
|
+
const element = node;
|
|
517
|
+
const text = [];
|
|
518
|
+
for (let j = 2;j < element.length; j++)
|
|
519
|
+
collect(element[j], new Set, text);
|
|
520
|
+
const title = plain(text);
|
|
521
|
+
close();
|
|
522
|
+
while (stack.length && stack[stack.length - 1].depth >= depth)
|
|
523
|
+
stack.pop();
|
|
524
|
+
const id = element[1]?.id;
|
|
525
|
+
current = {
|
|
526
|
+
id: typeof id === "string" && id !== "" ? `${page.path}#${id}` : page.path,
|
|
527
|
+
title,
|
|
528
|
+
titles: stack.map((item) => item.text),
|
|
529
|
+
level: depth,
|
|
530
|
+
parts: [],
|
|
531
|
+
lead: false
|
|
532
|
+
};
|
|
533
|
+
stack.push({ depth, text: title });
|
|
534
|
+
} else {
|
|
535
|
+
collect(node, ignored, current.parts);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
close();
|
|
539
|
+
return out;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// packages/content/src/build/search.ts
|
|
543
|
+
var INDEXED = resolveSectionOptions({ ignoredTags: ["pre"] });
|
|
544
|
+
function resolveSearch(value, config) {
|
|
545
|
+
if (value === undefined || value === false)
|
|
546
|
+
return [];
|
|
547
|
+
const { collections } = value ?? {};
|
|
548
|
+
if (!Array.isArray(collections) || !collections.every((name) => typeof name === "string"))
|
|
549
|
+
throw new DiagnosticError("HAMUR_E5323", "content.search must be false or { collections: string[] }");
|
|
550
|
+
collections.forEach((name, index) => {
|
|
551
|
+
const at = `content.search.collections[${index}] ${JSON.stringify(name)}`;
|
|
552
|
+
const collection = Object.hasOwn(config.collections, name) ? config.collections[name] : undefined;
|
|
553
|
+
if (!collection)
|
|
554
|
+
throw new DiagnosticError("HAMUR_E5324", `${at} is not a collection of content.config.ts`);
|
|
555
|
+
if (collection.expose === false)
|
|
556
|
+
throw new DiagnosticError("HAMUR_E5325", `${at} is not exposed to the client (expose: false); the search index is served to the browser`);
|
|
557
|
+
if (collection.type !== "page")
|
|
558
|
+
throw new DiagnosticError("HAMUR_E5326", `${at} is not a page collection; only pages have sections`);
|
|
559
|
+
});
|
|
560
|
+
return [...new Set(collections)];
|
|
561
|
+
}
|
|
562
|
+
function searchIndexOf(entries) {
|
|
563
|
+
const sections = entries.flatMap((entry) => sectionsOf(entry, INDEXED));
|
|
564
|
+
return buildSearchIndex(sections);
|
|
565
|
+
}
|
|
566
|
+
function searchModule(names, devLoad) {
|
|
567
|
+
const loaders = names.map((name) => ` ${JSON.stringify(name)}: ${devLoad ? `devLoad(${JSON.stringify(`${DEV_ROUTE}/search/${name}.json`)})` : `() => import(${JSON.stringify(`#hamur/content/search-index/${name}.json`)})`},`);
|
|
568
|
+
const imports = devLoad && names.length ? [`import { devLoad } from ${JSON.stringify(devLoad)};`, ""] : [];
|
|
569
|
+
return [...imports, "export default {", ...loaders, "};", ""].join(`
|
|
570
|
+
`);
|
|
571
|
+
}
|
|
572
|
+
function setupSearch(options, config, entries, dev = false) {
|
|
573
|
+
const names = resolveSearch(options.search, config);
|
|
574
|
+
const resolver = createResolver(new URL("../../src/build/search.ts", import.meta.url).href);
|
|
575
|
+
const devLoad = dev ? resolver.resolve("../runtime/dev-client.ts") : undefined;
|
|
576
|
+
for (const name of names)
|
|
577
|
+
addTemplate({
|
|
578
|
+
filename: `content/search-index/${name}.json`,
|
|
579
|
+
getContents: async () => JSON.stringify(searchIndexOf((await entries())[name]))
|
|
580
|
+
});
|
|
581
|
+
addTemplate({ filename: "content/search", getContents: () => searchModule(names, devLoad) });
|
|
582
|
+
if (names.length)
|
|
583
|
+
addAppPlugin({ src: resolver.resolve("../runtime/search-plugin.ts"), mode: "client" });
|
|
584
|
+
return names;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// packages/content/src/build/dev.ts
|
|
588
|
+
var isInside = (file, dir) => {
|
|
589
|
+
const path = relative(dir, file);
|
|
590
|
+
return path !== "" && !path.startsWith("..") && !isAbsolute(path);
|
|
591
|
+
};
|
|
592
|
+
var sourcesOf = (source) => (Array.isArray(source) ? source : [source]).flatMap((item) => typeof item === "string" ? [{ include: item }] : item.repository === undefined ? [item] : []);
|
|
593
|
+
var shownOf = (rootDir, file) => relative(rootDir, file).split(sep).join("/");
|
|
594
|
+
function matchOf(source, rootDir, file) {
|
|
595
|
+
const cwd = resolve(rootDir, "content", source.cwd ?? "");
|
|
596
|
+
if (!isInside(file, cwd))
|
|
597
|
+
return;
|
|
598
|
+
const path = relative(cwd, file).split(sep).join("/");
|
|
599
|
+
if (!new Bun.Glob(source.include).match(path) || (source.exclude ?? []).some((pattern) => new Bun.Glob(pattern).match(path)))
|
|
600
|
+
return;
|
|
601
|
+
const dot = path.lastIndexOf(".");
|
|
602
|
+
const extension = dot > path.lastIndexOf("/") ? path.slice(dot + 1) : "";
|
|
603
|
+
return { stem: extension ? path.slice(0, dot) : path, extension };
|
|
604
|
+
}
|
|
605
|
+
function collectionsOf(config, rootDir, file) {
|
|
606
|
+
const content = resolve(rootDir, "content");
|
|
607
|
+
return Object.entries(config.collections).filter(([, collection]) => collection.source === undefined ? isInside(file, content) : sourcesOf(collection.source).some((source) => matchOf(source, rootDir, file))).map(([name]) => name);
|
|
608
|
+
}
|
|
609
|
+
function fileIds(collection, rootDir, file, entries) {
|
|
610
|
+
if (collection.source === undefined)
|
|
611
|
+
return [];
|
|
612
|
+
const ids = new Set;
|
|
613
|
+
for (const source of sourcesOf(collection.source)) {
|
|
614
|
+
const match = matchOf(source, rootDir, file);
|
|
615
|
+
if (match) {
|
|
616
|
+
for (const entry of entries)
|
|
617
|
+
if (entry.stem === match.stem && entry.extension === match.extension)
|
|
618
|
+
ids.add(entry.id);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
return [...ids];
|
|
622
|
+
}
|
|
623
|
+
function changedIds(before, after) {
|
|
624
|
+
const old = new Map(before.map((entry) => [entry.id, JSON.stringify(entry)]));
|
|
625
|
+
const ids = [];
|
|
626
|
+
for (const entry of after) {
|
|
627
|
+
if (old.get(entry.id) !== JSON.stringify(entry))
|
|
628
|
+
ids.push(entry.id);
|
|
629
|
+
old.delete(entry.id);
|
|
630
|
+
}
|
|
631
|
+
return [...ids, ...old.keys()];
|
|
632
|
+
}
|
|
633
|
+
function createContentUpdater({
|
|
634
|
+
config,
|
|
635
|
+
rootDir,
|
|
636
|
+
index,
|
|
637
|
+
update,
|
|
638
|
+
fail,
|
|
639
|
+
fixed
|
|
640
|
+
}) {
|
|
641
|
+
const pending = new Map;
|
|
642
|
+
const errors = new Map;
|
|
643
|
+
let running;
|
|
644
|
+
const keyOf = (collection, file) => `${collection}\x00${file}`;
|
|
645
|
+
function failingFile(name, message, files) {
|
|
646
|
+
const known = [
|
|
647
|
+
...files.map((file) => shownOf(rootDir, file)),
|
|
648
|
+
...[...errors.values()].filter((error) => error.collection === name).map((error) => error.file)
|
|
649
|
+
];
|
|
650
|
+
const last = files.at(-1);
|
|
651
|
+
return known.find((file) => message.startsWith(`${file}:`)) ?? (last === undefined ? "content.config.ts" : shownOf(rootDir, last));
|
|
652
|
+
}
|
|
653
|
+
async function run(name, files) {
|
|
654
|
+
const before = (await index.read())[name] ?? [];
|
|
655
|
+
let after;
|
|
656
|
+
try {
|
|
657
|
+
after = await index.rebuild(name);
|
|
658
|
+
} catch (error) {
|
|
659
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
660
|
+
const named = error instanceof DiagnosticError2 ? error.at ? `${error.at}: ${error.text}` : error.text : message;
|
|
661
|
+
const failure = { collection: name, file: failingFile(name, named, files), message };
|
|
662
|
+
errors.set(keyOf(name, failure.file), failure);
|
|
663
|
+
fail(failure);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
for (const [key, error] of errors) {
|
|
667
|
+
if (error.collection !== name)
|
|
668
|
+
continue;
|
|
669
|
+
errors.delete(key);
|
|
670
|
+
fixed({ collection: name, file: error.file });
|
|
671
|
+
}
|
|
672
|
+
const ids = new Set(changedIds(before, after));
|
|
673
|
+
for (const file of files)
|
|
674
|
+
for (const id of fileIds(config.collections[name], rootDir, file, after))
|
|
675
|
+
ids.add(id);
|
|
676
|
+
for (const id of ids)
|
|
677
|
+
update({ collection: name, id });
|
|
678
|
+
}
|
|
679
|
+
async function drain() {
|
|
680
|
+
try {
|
|
681
|
+
for (let next = pending.entries().next();!next.done; next = pending.entries().next()) {
|
|
682
|
+
const [name, files] = next.value;
|
|
683
|
+
pending.delete(name);
|
|
684
|
+
await run(name, [...files]);
|
|
685
|
+
}
|
|
686
|
+
} finally {
|
|
687
|
+
running = undefined;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
return {
|
|
691
|
+
errors: () => [...errors.values()],
|
|
692
|
+
changed(file) {
|
|
693
|
+
const names = collectionsOf(config, rootDir, file);
|
|
694
|
+
if (!names.length)
|
|
695
|
+
return;
|
|
696
|
+
for (const name of names)
|
|
697
|
+
pending.set(name, (pending.get(name) ?? new Set).add(file));
|
|
698
|
+
return running ??= drain();
|
|
699
|
+
},
|
|
700
|
+
refresh(names) {
|
|
701
|
+
if (!names.length)
|
|
702
|
+
return Promise.resolve();
|
|
703
|
+
for (const name of names)
|
|
704
|
+
if (!pending.has(name))
|
|
705
|
+
pending.set(name, new Set);
|
|
706
|
+
return running ??= drain();
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
function setupDev(hamur, config, index, search) {
|
|
711
|
+
if (!hamur.options.dev)
|
|
712
|
+
return;
|
|
713
|
+
const { rootDir } = hamur.options;
|
|
714
|
+
const logger = useLogger("content");
|
|
715
|
+
const channel = useDevChannel();
|
|
716
|
+
const updater = createContentUpdater({
|
|
717
|
+
config,
|
|
718
|
+
rootDir,
|
|
719
|
+
index,
|
|
720
|
+
update: (update) => channel.send("content:update", update),
|
|
721
|
+
fail: (failure) => {
|
|
722
|
+
logger.error(failure.message);
|
|
723
|
+
channel.send("content:error", failure);
|
|
724
|
+
},
|
|
725
|
+
fixed: (fixed) => channel.send("content:fixed", fixed)
|
|
726
|
+
});
|
|
727
|
+
addDevServerHandler({
|
|
728
|
+
route: DEV_ROUTE,
|
|
729
|
+
handler: async (request) => {
|
|
730
|
+
const pathname = new URL(request.url).pathname;
|
|
731
|
+
if (pathname.endsWith(`${DEV_ROUTE}/errors.json`))
|
|
732
|
+
return Response.json(updater.errors(), { headers: { "cache-control": "no-store" } });
|
|
733
|
+
const match = /\/(chunks|search)\/([^/]+)\.json$/.exec(pathname);
|
|
734
|
+
if (!match)
|
|
735
|
+
return;
|
|
736
|
+
const kind = match[1];
|
|
737
|
+
const name = match[2];
|
|
738
|
+
const collection = Object.hasOwn(config.collections, name) ? config.collections[name] : undefined;
|
|
739
|
+
if (!collection || collection.expose === false || kind === "search" && !search.includes(name))
|
|
740
|
+
return;
|
|
741
|
+
const entries = (await index.read())[name];
|
|
742
|
+
return Response.json(kind === "chunks" ? entries : searchIndexOf(entries), {
|
|
743
|
+
headers: { "cache-control": "no-store" }
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
});
|
|
747
|
+
addDevServerHandler({
|
|
748
|
+
route: REFRESH_ROUTE,
|
|
749
|
+
handler: async (request) => {
|
|
750
|
+
if (request.method !== "POST" || !new URL(request.url).pathname.endsWith(REFRESH_ROUTE))
|
|
751
|
+
return;
|
|
752
|
+
let requested;
|
|
753
|
+
try {
|
|
754
|
+
requested = parseRefreshBody(await request.text()).collections;
|
|
755
|
+
} catch {
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
if (requested?.some((name) => !Object.hasOwn(config.collections, name) && !Object.hasOwn(config.live, name)))
|
|
759
|
+
return;
|
|
760
|
+
await updater.refresh((requested ?? Object.keys(config.collections)).filter((name) => Object.hasOwn(config.collections, name)));
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
addAppPlugin2({ src: createResolver2(new URL("../../src/build/dev.ts", import.meta.url).href).resolve("../runtime/dev-plugin.ts"), mode: "client" });
|
|
765
|
+
hamur.hooks.hook("dev:change", async (change) => {
|
|
766
|
+
if (!collectionsOf(config, rootDir, change.file).length)
|
|
767
|
+
return;
|
|
768
|
+
if (await index.read().then(() => false, () => true)) {
|
|
769
|
+
index.reset();
|
|
770
|
+
try {
|
|
771
|
+
await index.read();
|
|
772
|
+
} catch (error) {
|
|
773
|
+
logger.error(error instanceof Error ? error.message : String(error));
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
change.rebuildServer = true;
|
|
777
|
+
change.reload = true;
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
updater.changed(change.file)?.catch((error) => logger.error(error instanceof Error ? error.message : String(error)));
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// packages/content/src/build/index.ts
|
|
785
|
+
import { rename as rename2 } from "node:fs/promises";
|
|
786
|
+
import { join as join5, relative as relative3, sep as sep4 } from "node:path";
|
|
787
|
+
import {
|
|
788
|
+
DiagnosticError as DiagnosticError5,
|
|
789
|
+
addTemplate as addTemplate2,
|
|
790
|
+
createResolver as createResolver3,
|
|
791
|
+
useLogger as useLogger2,
|
|
792
|
+
useMarkdownParser
|
|
793
|
+
} from "hamur/kit";
|
|
794
|
+
import { parseMarkdown } from "hamur/markdown";
|
|
795
|
+
|
|
796
|
+
// packages/content/src/error.ts
|
|
797
|
+
import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
|
|
798
|
+
|
|
799
|
+
class ContentError extends DiagnosticError3 {
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// packages/content/src/loaders/data.ts
|
|
803
|
+
import { DiagnosticError as DiagnosticError4 } from "hamur/kit";
|
|
804
|
+
var DEFAULT_CSV = { delimiter: ",", header: true };
|
|
805
|
+
var DATA_FORMATS = ["yml", "yaml", "json", "json5", "toml", "csv"];
|
|
806
|
+
function resolveCsv(value) {
|
|
807
|
+
if (value === undefined)
|
|
808
|
+
return DEFAULT_CSV;
|
|
809
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
810
|
+
throw new DiagnosticError4("HAMUR_E5342", "content.csv must be { delimiter?: string; header?: boolean }");
|
|
811
|
+
const { delimiter = DEFAULT_CSV.delimiter, header = DEFAULT_CSV.header } = value;
|
|
812
|
+
if (typeof delimiter !== "string" || [...delimiter].length !== 1 || delimiter === '"' || delimiter === `
|
|
813
|
+
` || delimiter === "\r") {
|
|
814
|
+
throw new DiagnosticError4("HAMUR_E5342", `content.csv.delimiter must be one character other than a quote or a line break (got ${JSON.stringify(delimiter)})`);
|
|
815
|
+
}
|
|
816
|
+
if (typeof header !== "boolean")
|
|
817
|
+
throw new DiagnosticError4("HAMUR_E5342", `content.csv.header must be a boolean (got ${JSON.stringify(header)})`);
|
|
818
|
+
return { delimiter, header };
|
|
819
|
+
}
|
|
820
|
+
function csvRows(text, delimiter, shown) {
|
|
821
|
+
const rows = [];
|
|
822
|
+
const fail = (message, line, column) => {
|
|
823
|
+
throw new ContentError("HAMUR_E5359", message, { at: `${shown}:${line}:${column}` });
|
|
824
|
+
};
|
|
825
|
+
let index = text.charCodeAt(0) === 65279 ? 1 : 0;
|
|
826
|
+
let line = 1;
|
|
827
|
+
let column = 1;
|
|
828
|
+
let rowLine = 1;
|
|
829
|
+
let fields = [];
|
|
830
|
+
let field = "";
|
|
831
|
+
let fresh = true;
|
|
832
|
+
let quoted = false;
|
|
833
|
+
const endRow = () => {
|
|
834
|
+
if (fields.length === 0 && field === "" && !quoted)
|
|
835
|
+
return;
|
|
836
|
+
fields.push(field);
|
|
837
|
+
rows.push({ line: rowLine, fields });
|
|
838
|
+
fields = [];
|
|
839
|
+
};
|
|
840
|
+
while (index < text.length) {
|
|
841
|
+
const char = text[index];
|
|
842
|
+
if (char === '"' && fresh) {
|
|
843
|
+
const startLine = line;
|
|
844
|
+
const startColumn = column;
|
|
845
|
+
index++;
|
|
846
|
+
column++;
|
|
847
|
+
for (;; ) {
|
|
848
|
+
if (index >= text.length)
|
|
849
|
+
fail("unterminated quoted field", startLine, startColumn);
|
|
850
|
+
const next = text[index];
|
|
851
|
+
if (next === '"') {
|
|
852
|
+
if (text[index + 1] === '"') {
|
|
853
|
+
field += '"';
|
|
854
|
+
index += 2;
|
|
855
|
+
column += 2;
|
|
856
|
+
continue;
|
|
857
|
+
}
|
|
858
|
+
index++;
|
|
859
|
+
column++;
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
field += next;
|
|
863
|
+
index++;
|
|
864
|
+
if (next === `
|
|
865
|
+
`) {
|
|
866
|
+
line++;
|
|
867
|
+
column = 1;
|
|
868
|
+
} else
|
|
869
|
+
column++;
|
|
870
|
+
}
|
|
871
|
+
const after = text[index];
|
|
872
|
+
if (after !== undefined && after !== delimiter && after !== "\r" && after !== `
|
|
873
|
+
`)
|
|
874
|
+
fail("unexpected character after a closing quote", line, column);
|
|
875
|
+
fresh = false;
|
|
876
|
+
quoted = true;
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
if (char === delimiter) {
|
|
880
|
+
fields.push(field);
|
|
881
|
+
field = "";
|
|
882
|
+
fresh = true;
|
|
883
|
+
quoted = false;
|
|
884
|
+
index++;
|
|
885
|
+
column++;
|
|
886
|
+
continue;
|
|
887
|
+
}
|
|
888
|
+
if (char === "\r" || char === `
|
|
889
|
+
`) {
|
|
890
|
+
endRow();
|
|
891
|
+
field = "";
|
|
892
|
+
fresh = true;
|
|
893
|
+
quoted = false;
|
|
894
|
+
index += char === "\r" && text[index + 1] === `
|
|
895
|
+
` ? 2 : 1;
|
|
896
|
+
line++;
|
|
897
|
+
column = 1;
|
|
898
|
+
rowLine = line;
|
|
899
|
+
continue;
|
|
900
|
+
}
|
|
901
|
+
if (char === '"')
|
|
902
|
+
fail("unexpected quote in an unquoted field", line, column);
|
|
903
|
+
field += char;
|
|
904
|
+
fresh = false;
|
|
905
|
+
index++;
|
|
906
|
+
column++;
|
|
907
|
+
}
|
|
908
|
+
endRow();
|
|
909
|
+
return rows;
|
|
910
|
+
}
|
|
911
|
+
function parseCsv(text, options, shown) {
|
|
912
|
+
const rows = csvRows(text, options.delimiter, shown);
|
|
913
|
+
let names;
|
|
914
|
+
if (options.header)
|
|
915
|
+
names = rows.shift()?.fields;
|
|
916
|
+
return rows.map(({ line, fields }) => {
|
|
917
|
+
if (names && fields.length !== names.length)
|
|
918
|
+
throw new ContentError("HAMUR_E5360", `row has ${fields.length} ${fields.length === 1 ? "field" : "fields"}, the header has ${names.length}`, { at: `${shown}:${line}:1` });
|
|
919
|
+
return Object.fromEntries(fields.map((value, index) => [names ? names[index] : String(index), value]));
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
function locate(parse, text, message) {
|
|
923
|
+
const lines = text.split(`
|
|
924
|
+
`);
|
|
925
|
+
const fails = (count) => {
|
|
926
|
+
try {
|
|
927
|
+
parse(lines.slice(0, count).join(`
|
|
928
|
+
`) + (count < lines.length ? `
|
|
929
|
+
` : ""));
|
|
930
|
+
return false;
|
|
931
|
+
} catch (error) {
|
|
932
|
+
return error.message === message;
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
let low = 1;
|
|
936
|
+
let high = lines.length;
|
|
937
|
+
while (low < high) {
|
|
938
|
+
const middle = low + high >> 1;
|
|
939
|
+
if (fails(middle))
|
|
940
|
+
high = middle;
|
|
941
|
+
else
|
|
942
|
+
low = middle + 1;
|
|
943
|
+
}
|
|
944
|
+
const found = lines[low - 1].search(/\S/);
|
|
945
|
+
return { line: low, column: found === -1 ? 1 : found + 1 };
|
|
946
|
+
}
|
|
947
|
+
var PARSERS = {
|
|
948
|
+
yml: (text) => Bun.YAML.parse(text),
|
|
949
|
+
yaml: (text) => Bun.YAML.parse(text),
|
|
950
|
+
json: (text) => JSON.parse(text),
|
|
951
|
+
json5: (text) => Bun.JSON5.parse(text),
|
|
952
|
+
toml: (text) => Bun.TOML.parse(text)
|
|
953
|
+
};
|
|
954
|
+
function parseDataText(text, extension, shown, csv = DEFAULT_CSV) {
|
|
955
|
+
if (extension === "csv")
|
|
956
|
+
return parseCsv(text, csv, shown);
|
|
957
|
+
const parse = PARSERS[extension];
|
|
958
|
+
try {
|
|
959
|
+
return parse(text);
|
|
960
|
+
} catch (error) {
|
|
961
|
+
const message = error.message;
|
|
962
|
+
const { line, column } = locate(parse, text, message);
|
|
963
|
+
throw new ContentError("HAMUR_E5359", message, { at: `${shown}:${line}:${column}` });
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// packages/content/src/loaders/glob.ts
|
|
968
|
+
import { join as join3, relative as relative2, sep as sep3 } from "node:path";
|
|
969
|
+
|
|
970
|
+
// packages/content/src/source.ts
|
|
971
|
+
import { existsSync } from "node:fs";
|
|
972
|
+
import { join as join2, resolve as resolve2, sep as sep2 } from "node:path";
|
|
973
|
+
|
|
974
|
+
// packages/content/src/loaders/git.ts
|
|
975
|
+
import { mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
|
|
976
|
+
import { join } from "node:path";
|
|
977
|
+
var MAX_ARCHIVE_BYTES = 100 * 1024 * 1024;
|
|
978
|
+
var MAX_UNPACKED_BYTES = 500 * 1024 * 1024;
|
|
979
|
+
var HOSTS = { "github.com": "github", "gitlab.com": "gitlab" };
|
|
980
|
+
function shownOf2(repository) {
|
|
981
|
+
try {
|
|
982
|
+
const url = new URL(repository);
|
|
983
|
+
if (!url.username && !url.password)
|
|
984
|
+
return repository;
|
|
985
|
+
url.username = "";
|
|
986
|
+
url.password = "";
|
|
987
|
+
return url.href;
|
|
988
|
+
} catch {
|
|
989
|
+
return repository;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
function parseRepository(repository) {
|
|
993
|
+
let url;
|
|
994
|
+
try {
|
|
995
|
+
url = new URL(repository);
|
|
996
|
+
} catch {}
|
|
997
|
+
const host = url ? HOSTS[url.hostname] : undefined;
|
|
998
|
+
const path = (url?.pathname ?? "").replace(/\/+$/, "").replace(/\.git$/, "").slice(1);
|
|
999
|
+
const segments = path.split("/");
|
|
1000
|
+
const plain = url !== undefined && url.protocol === "https:" && !url.username && !url.password && !url.port && !url.search && !url.hash;
|
|
1001
|
+
const shaped = segments.every((segment) => segment !== "" && segment !== "." && segment !== "..") && (host === "github" ? segments.length === 2 : segments.length >= 2);
|
|
1002
|
+
if (!plain || host === undefined || !shaped)
|
|
1003
|
+
throw new ContentError("HAMUR_E5361", `content: ${shownOf2(repository)} is not a GitHub or GitLab repository URL`);
|
|
1004
|
+
return { host, path };
|
|
1005
|
+
}
|
|
1006
|
+
var refPath = (ref) => ref.split("/").map(encodeURIComponent).join("/");
|
|
1007
|
+
function archiveRequest(repository, ref, token) {
|
|
1008
|
+
if (repository.host === "gitlab") {
|
|
1009
|
+
const sha = ref ? `?sha=${encodeURIComponent(ref.name)}` : "";
|
|
1010
|
+
return {
|
|
1011
|
+
url: `https://gitlab.com/api/v4/projects/${encodeURIComponent(repository.path)}/repository/archive.tar.gz${sha}`,
|
|
1012
|
+
headers: token ? { "private-token": token } : {}
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
if (token)
|
|
1016
|
+
return {
|
|
1017
|
+
url: `https://api.github.com/repos/${repository.path}/tarball${ref ? `/${refPath(ref.name)}` : ""}`,
|
|
1018
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" }
|
|
1019
|
+
};
|
|
1020
|
+
return {
|
|
1021
|
+
url: `https://codeload.github.com/${repository.path}/tar.gz/${ref ? `refs/${ref.kind === "branch" ? "heads" : "tags"}/${refPath(ref.name)}` : "HEAD"}`,
|
|
1022
|
+
headers: {}
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
var unsafe = (name) => name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name) || name.split(/[\\/]/).includes("..");
|
|
1026
|
+
async function readCapped(stream, max) {
|
|
1027
|
+
const chunks = [];
|
|
1028
|
+
let size = 0;
|
|
1029
|
+
if (stream) {
|
|
1030
|
+
const reader = stream.getReader();
|
|
1031
|
+
for (;; ) {
|
|
1032
|
+
const { done, value } = await reader.read();
|
|
1033
|
+
if (done)
|
|
1034
|
+
break;
|
|
1035
|
+
size += value.byteLength;
|
|
1036
|
+
if (size > max) {
|
|
1037
|
+
await reader.cancel();
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
chunks.push(value);
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
const bytes = new Uint8Array(size);
|
|
1044
|
+
let offset = 0;
|
|
1045
|
+
for (const chunk of chunks) {
|
|
1046
|
+
bytes.set(chunk, offset);
|
|
1047
|
+
offset += chunk.byteLength;
|
|
1048
|
+
}
|
|
1049
|
+
return bytes;
|
|
1050
|
+
}
|
|
1051
|
+
var random = () => crypto.randomUUID();
|
|
1052
|
+
async function unpack(bytes, base, shown, maxUnpacked) {
|
|
1053
|
+
let files;
|
|
1054
|
+
let version;
|
|
1055
|
+
try {
|
|
1056
|
+
const gzip = bytes[0] === 31 && bytes[1] === 139;
|
|
1057
|
+
const tar = gzip ? await readCapped(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")), maxUnpacked) : bytes.byteLength > maxUnpacked ? undefined : bytes;
|
|
1058
|
+
if (!tar)
|
|
1059
|
+
throw new ContentError("HAMUR_E5362", `content: cannot read the archive of ${shown} (larger than ${maxUnpacked} bytes unpacked)`);
|
|
1060
|
+
files = await new Bun.Archive(tar).files();
|
|
1061
|
+
version = new Bun.CryptoHasher("sha256").update(tar).digest("hex");
|
|
1062
|
+
} catch (error) {
|
|
1063
|
+
if (error instanceof ContentError)
|
|
1064
|
+
throw error;
|
|
1065
|
+
throw new ContentError("HAMUR_E5363", `content: cannot read the archive of ${shown} (${error instanceof Error ? error.message : String(error)})`);
|
|
1066
|
+
}
|
|
1067
|
+
let total = 0;
|
|
1068
|
+
for (const [name, file] of files) {
|
|
1069
|
+
if (unsafe(name))
|
|
1070
|
+
throw new ContentError("HAMUR_E5364", `content: ${shown}: archive entry "${name}" leaves the repository`);
|
|
1071
|
+
total += file.size;
|
|
1072
|
+
}
|
|
1073
|
+
if (total > maxUnpacked)
|
|
1074
|
+
throw new ContentError("HAMUR_E5362", `content: cannot read the archive of ${shown} (larger than ${maxUnpacked} bytes unpacked)`);
|
|
1075
|
+
const dir = join(base, version);
|
|
1076
|
+
if (!await isDirectory(dir)) {
|
|
1077
|
+
const temp = join(base, `${version}.${random()}.tmp`);
|
|
1078
|
+
try {
|
|
1079
|
+
await mkdir(temp, { recursive: true });
|
|
1080
|
+
for (const [name, file] of files) {
|
|
1081
|
+
const slash = name.indexOf("/");
|
|
1082
|
+
if (slash < 0 || slash === name.length - 1)
|
|
1083
|
+
continue;
|
|
1084
|
+
await Bun.write(join(temp, name.slice(slash + 1)), file);
|
|
1085
|
+
}
|
|
1086
|
+
await rename(temp, dir).catch((error) => {
|
|
1087
|
+
if (error.code !== "ENOTEMPTY" && error.code !== "EEXIST")
|
|
1088
|
+
throw error;
|
|
1089
|
+
});
|
|
1090
|
+
} finally {
|
|
1091
|
+
await rm(temp, { recursive: true, force: true });
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
const previous = await currentVersion(base);
|
|
1095
|
+
const pointer = join(base, `current.${random()}.tmp`);
|
|
1096
|
+
await Bun.write(pointer, version);
|
|
1097
|
+
await rename(pointer, join(base, "current"));
|
|
1098
|
+
for (const name of await readdir(base)) {
|
|
1099
|
+
if (/^[0-9a-f]{64}$/.test(name) && name !== version && name !== previous)
|
|
1100
|
+
await rm(join(base, name), { recursive: true, force: true });
|
|
1101
|
+
}
|
|
1102
|
+
return dir;
|
|
1103
|
+
}
|
|
1104
|
+
var isDirectory = (path) => stat(path).then((info) => info.isDirectory(), () => false);
|
|
1105
|
+
async function currentVersion(base) {
|
|
1106
|
+
try {
|
|
1107
|
+
const version = (await readFile(join(base, "current"), "utf8")).trim();
|
|
1108
|
+
return /^[0-9a-f]{64}$/.test(version) ? version : undefined;
|
|
1109
|
+
} catch {
|
|
1110
|
+
return;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
async function fetchRepository(source, { cacheDir, logger, maxBytes = MAX_ARCHIVE_BYTES, maxUnpackedBytes = MAX_UNPACKED_BYTES }) {
|
|
1114
|
+
const shown = shownOf2(source.repository);
|
|
1115
|
+
const repository = parseRepository(source.repository);
|
|
1116
|
+
if (source.branch !== undefined && source.tag !== undefined)
|
|
1117
|
+
throw new ContentError("HAMUR_E5365", `content: ${shown}: set branch or tag, not both`);
|
|
1118
|
+
const ref = source.branch !== undefined ? { kind: "branch", name: source.branch } : source.tag !== undefined ? { kind: "tag", name: source.tag } : undefined;
|
|
1119
|
+
const token = source.auth?.token || undefined;
|
|
1120
|
+
const key = new Bun.CryptoHasher("sha256").update(JSON.stringify([source.repository, ref?.kind ?? null, ref?.name ?? null])).digest("hex");
|
|
1121
|
+
const base = join(cacheDir, "content", key);
|
|
1122
|
+
const redact = (text) => token ? text.split(token).join("***") : text;
|
|
1123
|
+
const fallback = async (reason) => {
|
|
1124
|
+
const version = await currentVersion(base);
|
|
1125
|
+
if (version === undefined || !await isDirectory(join(base, version))) {
|
|
1126
|
+
throw new ContentError("HAMUR_E5366", `content: cannot fetch ${shown} and no cached copy exists (${redact(reason)})`);
|
|
1127
|
+
}
|
|
1128
|
+
logger?.warn(`using the cached copy of ${shown}`);
|
|
1129
|
+
return join(base, version);
|
|
1130
|
+
};
|
|
1131
|
+
const { url, headers } = archiveRequest(repository, ref, token);
|
|
1132
|
+
let bytes;
|
|
1133
|
+
try {
|
|
1134
|
+
const response = await globalThis.fetch(url, { headers });
|
|
1135
|
+
if (response.status >= 500 || response.status === 429)
|
|
1136
|
+
return await fallback(String(response.status));
|
|
1137
|
+
if (!response.ok)
|
|
1138
|
+
throw new ContentError("HAMUR_E5367", `content: cannot fetch ${shown} (${response.status})`);
|
|
1139
|
+
bytes = Number(response.headers.get("content-length") ?? 0) > maxBytes ? undefined : await readCapped(response.body, maxBytes);
|
|
1140
|
+
} catch (error) {
|
|
1141
|
+
if (error instanceof ContentError)
|
|
1142
|
+
throw error;
|
|
1143
|
+
return fallback(error instanceof Error ? error.message : String(error));
|
|
1144
|
+
}
|
|
1145
|
+
if (!bytes)
|
|
1146
|
+
throw new ContentError("HAMUR_E5362", `content: cannot fetch ${shown} (the archive is larger than ${maxBytes} bytes)`);
|
|
1147
|
+
return unpack(bytes, base, shown, maxUnpackedBytes);
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
// packages/content/src/source.ts
|
|
1151
|
+
var PREFIX = /^(\d+)\./;
|
|
1152
|
+
function pagePath(prefix, relative) {
|
|
1153
|
+
const segments = relative.split("/");
|
|
1154
|
+
segments[segments.length - 1] = segments.at(-1).replace(/\.[^.]*$/, "");
|
|
1155
|
+
const parts = segments.map((segment) => segment.replace(PREFIX, ""));
|
|
1156
|
+
if (parts.at(-1) === "index")
|
|
1157
|
+
parts.pop();
|
|
1158
|
+
const base = prefix.replace(/\/+$/, "");
|
|
1159
|
+
return parts.length ? `${base}/${parts.join("/")}` : base || "/";
|
|
1160
|
+
}
|
|
1161
|
+
function compareSegment(a, b) {
|
|
1162
|
+
const left = PREFIX.exec(a);
|
|
1163
|
+
const right = PREFIX.exec(b);
|
|
1164
|
+
if (left && !right)
|
|
1165
|
+
return -1;
|
|
1166
|
+
if (!left && right)
|
|
1167
|
+
return 1;
|
|
1168
|
+
if (left && right && Number(left[1]) !== Number(right[1]))
|
|
1169
|
+
return Number(left[1]) - Number(right[1]);
|
|
1170
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1171
|
+
}
|
|
1172
|
+
function compareSource(a, b) {
|
|
1173
|
+
const left = a.split("/");
|
|
1174
|
+
const right = b.split("/");
|
|
1175
|
+
for (let index = 0;index < Math.min(left.length, right.length); index++) {
|
|
1176
|
+
const order = compareSegment(left[index], right[index]);
|
|
1177
|
+
if (order !== 0)
|
|
1178
|
+
return order;
|
|
1179
|
+
}
|
|
1180
|
+
return left.length - right.length;
|
|
1181
|
+
}
|
|
1182
|
+
var options = (source) => typeof source === "string" ? { include: source } : source;
|
|
1183
|
+
async function setupSources(rootDir, source, remote = {}) {
|
|
1184
|
+
const files = [];
|
|
1185
|
+
const seen = new Set;
|
|
1186
|
+
for (const entry of (Array.isArray(source) ? source : [source]).map(options)) {
|
|
1187
|
+
const cwd = entry.repository !== undefined ? await fetchRepository(entry, {
|
|
1188
|
+
cacheDir: remote.cacheDir ?? join2(rootDir, "node_modules/.cache/hamur"),
|
|
1189
|
+
...remote.logger ? { logger: remote.logger } : {}
|
|
1190
|
+
}) : resolve2(rootDir, "content", entry.cwd ?? "");
|
|
1191
|
+
if (!existsSync(cwd)) {
|
|
1192
|
+
if (entry.repository !== undefined)
|
|
1193
|
+
throw new ContentError("HAMUR_E5368", `content: the cached copy of ${entry.repository} at ${cwd} is missing`);
|
|
1194
|
+
continue;
|
|
1195
|
+
}
|
|
1196
|
+
const exclude = (entry.exclude ?? []).map((pattern) => new Bun.Glob(pattern));
|
|
1197
|
+
const found = [];
|
|
1198
|
+
for await (const match of new Bun.Glob(entry.include).scan({ cwd, onlyFiles: true })) {
|
|
1199
|
+
const relative = match.split(sep2).join("/");
|
|
1200
|
+
if (!exclude.some((glob) => glob.match(relative)))
|
|
1201
|
+
found.push(relative);
|
|
1202
|
+
}
|
|
1203
|
+
for (const relative of found.sort(compareSource)) {
|
|
1204
|
+
const file = resolve2(cwd, relative);
|
|
1205
|
+
if (seen.has(file))
|
|
1206
|
+
continue;
|
|
1207
|
+
seen.add(file);
|
|
1208
|
+
const dot = relative.lastIndexOf(".");
|
|
1209
|
+
const extension = dot > relative.lastIndexOf("/") ? relative.slice(dot + 1) : "";
|
|
1210
|
+
const stem = extension ? relative.slice(0, dot) : relative;
|
|
1211
|
+
files.push({ cwd, file, relative, stem, extension, path: pagePath(entry.prefix ?? "/", relative) });
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
return files;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
// packages/content/src/loaders/glob.ts
|
|
1218
|
+
var FORMATS = new Set(["md", ...DATA_FORMATS]);
|
|
1219
|
+
var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1220
|
+
var DIRECTORY_FILES = [".navigation.yml", ".navigation.yaml"];
|
|
1221
|
+
async function directoryData(cwd, relativePath, cache, rootDir) {
|
|
1222
|
+
const segments = relativePath.split("/").slice(0, -1);
|
|
1223
|
+
const found = {};
|
|
1224
|
+
for (let depth = 1;depth <= segments.length; depth++) {
|
|
1225
|
+
const dir = segments.slice(0, depth).join("/");
|
|
1226
|
+
const key = join3(cwd, dir);
|
|
1227
|
+
let read = cache.get(key);
|
|
1228
|
+
if (!read) {
|
|
1229
|
+
read = (async () => {
|
|
1230
|
+
for (const name of DIRECTORY_FILES) {
|
|
1231
|
+
const file = Bun.file(join3(key, name));
|
|
1232
|
+
if (!await file.exists())
|
|
1233
|
+
continue;
|
|
1234
|
+
const shown = relative2(rootDir, join3(key, name)).split(sep3).join("/");
|
|
1235
|
+
const value = parseDataText(await file.text(), "yml", shown);
|
|
1236
|
+
if (!isObject2(value))
|
|
1237
|
+
throw new ContentError("HAMUR_E5357", `${shown}: a ${name} file holds an object`);
|
|
1238
|
+
return value;
|
|
1239
|
+
}
|
|
1240
|
+
return;
|
|
1241
|
+
})();
|
|
1242
|
+
cache.set(key, read);
|
|
1243
|
+
}
|
|
1244
|
+
const data = await read;
|
|
1245
|
+
if (data)
|
|
1246
|
+
found[dir] = data;
|
|
1247
|
+
}
|
|
1248
|
+
return Object.keys(found).length ? found : undefined;
|
|
1249
|
+
}
|
|
1250
|
+
async function parseWith(ctx, extension, id, shown, body) {
|
|
1251
|
+
const transformer = ctx.transformers.find((item) => item.parse !== undefined && item.extensions.includes(`.${extension}`));
|
|
1252
|
+
if (!transformer)
|
|
1253
|
+
return;
|
|
1254
|
+
let value;
|
|
1255
|
+
try {
|
|
1256
|
+
value = await transformer.parse({ id, path: shown, extension, body });
|
|
1257
|
+
} catch (error) {
|
|
1258
|
+
throw new ContentError("HAMUR_E5347", `${shown}: transformer "${transformer.name}" failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1259
|
+
}
|
|
1260
|
+
if (!isObject2(value))
|
|
1261
|
+
throw new ContentError("HAMUR_E5348", `${shown}: transformer "${transformer.name}" must return an object from parse`);
|
|
1262
|
+
return value;
|
|
1263
|
+
}
|
|
1264
|
+
function sourceLoader(source, cacheDir) {
|
|
1265
|
+
return {
|
|
1266
|
+
name: "glob",
|
|
1267
|
+
async load(ctx) {
|
|
1268
|
+
const directories = new Map;
|
|
1269
|
+
for (const file of await setupSources(ctx.rootDir, source, {
|
|
1270
|
+
...cacheDir === undefined ? {} : { cacheDir },
|
|
1271
|
+
logger: ctx.logger
|
|
1272
|
+
})) {
|
|
1273
|
+
const shown = relative2(ctx.rootDir, file.file).split(sep3).join("/");
|
|
1274
|
+
const transformed = !FORMATS.has(file.extension) && ctx.transformers.some((item) => item.parse !== undefined && item.extensions.includes(`.${file.extension}`));
|
|
1275
|
+
if (!FORMATS.has(file.extension) && !transformed)
|
|
1276
|
+
throw new ContentError("HAMUR_E5355", `${shown}: .${file.extension} is not a content format (md, yml, yaml, json, json5, toml, csv)`);
|
|
1277
|
+
const text = await ctx.beforeParse({
|
|
1278
|
+
id: file.stem,
|
|
1279
|
+
path: shown,
|
|
1280
|
+
extension: file.extension,
|
|
1281
|
+
body: await Bun.file(file.file).text()
|
|
1282
|
+
});
|
|
1283
|
+
const navigationDirs = ctx.type === "page" ? await directoryData(file.cwd, file.relative, directories, ctx.rootDir) : undefined;
|
|
1284
|
+
const entry = {
|
|
1285
|
+
stem: file.stem,
|
|
1286
|
+
path: file.path,
|
|
1287
|
+
file: file.file,
|
|
1288
|
+
...navigationDirs ? { navigationDirs } : {}
|
|
1289
|
+
};
|
|
1290
|
+
const dirs = navigationDirs ? `\x00${JSON.stringify(navigationDirs)}` : "";
|
|
1291
|
+
if (file.extension === "md") {
|
|
1292
|
+
ctx.store.set({
|
|
1293
|
+
...entry,
|
|
1294
|
+
id: file.stem,
|
|
1295
|
+
data: {},
|
|
1296
|
+
body: text,
|
|
1297
|
+
digest: ctx.digest(`${shown}\x00${text}${dirs}`)
|
|
1298
|
+
});
|
|
1299
|
+
continue;
|
|
1300
|
+
}
|
|
1301
|
+
const value = transformed ? await parseWith(ctx, file.extension, file.stem, shown, text) : parseDataText(text, file.extension, shown, ctx.csv);
|
|
1302
|
+
const options = file.extension === "csv" ? `\x00${ctx.csv.delimiter}${ctx.csv.header}` : "";
|
|
1303
|
+
if (ctx.type === "page") {
|
|
1304
|
+
if (Array.isArray(value))
|
|
1305
|
+
throw new ContentError("HAMUR_E5356", `${shown}: a page collection entry is one document; move the file to a data collection`);
|
|
1306
|
+
if (!isObject2(value))
|
|
1307
|
+
throw new ContentError("HAMUR_E5357", `${shown}: a page file holds an object`);
|
|
1308
|
+
const { body, ...data } = value;
|
|
1309
|
+
const markdown = transformed && typeof body === "string";
|
|
1310
|
+
ctx.store.set({
|
|
1311
|
+
...entry,
|
|
1312
|
+
id: file.stem,
|
|
1313
|
+
data: markdown ? data : value,
|
|
1314
|
+
...markdown ? { body } : {},
|
|
1315
|
+
digest: ctx.digest(`${shown}\x00${text}${dirs}${options}`)
|
|
1316
|
+
});
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
for (const [index, item] of (Array.isArray(value) ? value : [value]).entries()) {
|
|
1320
|
+
const label = Array.isArray(value) ? String(index) : undefined;
|
|
1321
|
+
if (!isObject2(item))
|
|
1322
|
+
throw new ContentError("HAMUR_E5350", `${shown}: ${label === undefined ? "" : `${label}: `}a data entry is an object`);
|
|
1323
|
+
ctx.store.set({
|
|
1324
|
+
...entry,
|
|
1325
|
+
id: label === undefined ? file.stem : `${file.stem}/${label}`,
|
|
1326
|
+
data: item,
|
|
1327
|
+
digest: ctx.digest(`${shown}\x00${label ?? ""}\x00${text}${options}`)
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
function glob({ pattern, base, exclude, prefix }) {
|
|
1335
|
+
return sourceLoader({
|
|
1336
|
+
include: pattern,
|
|
1337
|
+
...base === undefined ? {} : { cwd: base },
|
|
1338
|
+
...exclude === undefined ? {} : { exclude },
|
|
1339
|
+
...prefix === undefined ? {} : { prefix }
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// packages/content/src/build/image.ts
|
|
1344
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1345
|
+
import { mkdirSync, rmSync } from "node:fs";
|
|
1346
|
+
import { basename, dirname, extname, join as join4, resolve as resolve3 } from "node:path";
|
|
1347
|
+
import { addPublicAssets, readImageMeta } from "hamur/kit";
|
|
1348
|
+
|
|
1349
|
+
// packages/content/src/image.ts
|
|
1350
|
+
var IMAGE_SCOPE = Symbol.for("hamur.content.image");
|
|
1351
|
+
var URLISH = /^(?:[a-z][a-z0-9+.-]*:|\/)/i;
|
|
1352
|
+
function image() {
|
|
1353
|
+
return {
|
|
1354
|
+
"~standard": {
|
|
1355
|
+
version: 1,
|
|
1356
|
+
vendor: "hamur",
|
|
1357
|
+
async validate(value) {
|
|
1358
|
+
if (typeof value !== "string" || value === "")
|
|
1359
|
+
return { issues: [{ message: "expected an image path" }] };
|
|
1360
|
+
if (URLISH.test(value))
|
|
1361
|
+
return { issues: [{ message: `${value} is not a relative path; image() reads files next to the entry` }] };
|
|
1362
|
+
const scope = globalThis[IMAGE_SCOPE]?.getStore();
|
|
1363
|
+
if (!scope)
|
|
1364
|
+
return { issues: [{ message: "image() runs at build only" }] };
|
|
1365
|
+
const result = await scope.resolve(value);
|
|
1366
|
+
return typeof result === "string" ? { issues: [{ message: result }] } : { value: result };
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
// packages/content/src/build/image.ts
|
|
1373
|
+
var storage = new AsyncLocalStorage;
|
|
1374
|
+
globalThis[IMAGE_SCOPE] = storage;
|
|
1375
|
+
var withImages = (scope, run) => storage.run(scope, run);
|
|
1376
|
+
function setupImages(hamur) {
|
|
1377
|
+
const { buildDir, app } = hamur.options;
|
|
1378
|
+
const dir = join4(buildDir, "content", "images");
|
|
1379
|
+
rmSync(dir, { recursive: true, force: true });
|
|
1380
|
+
mkdirSync(dir, { recursive: true });
|
|
1381
|
+
const assets = app.buildAssetsDir.replace(/^\/*/, "").replace(/\/*$/, "");
|
|
1382
|
+
const path = `/${assets ? `${assets}/` : ""}content-images/`;
|
|
1383
|
+
addPublicAssets({ dir, baseURL: path, maxAge: 31536000 });
|
|
1384
|
+
return { dir, url: `${app.baseURL.replace(/\/+$/, "")}${path}` };
|
|
1385
|
+
}
|
|
1386
|
+
function entryImages(file, output) {
|
|
1387
|
+
const scope = {
|
|
1388
|
+
used: false,
|
|
1389
|
+
async resolve(path) {
|
|
1390
|
+
scope.used = true;
|
|
1391
|
+
if (!file)
|
|
1392
|
+
return "image() needs an entry that comes from a file";
|
|
1393
|
+
if (!output)
|
|
1394
|
+
return "image() needs the content module";
|
|
1395
|
+
const source = resolve3(dirname(file), path);
|
|
1396
|
+
const input = Bun.file(source);
|
|
1397
|
+
if (!await input.exists())
|
|
1398
|
+
return `${path} not found`;
|
|
1399
|
+
const bytes = await input.bytes();
|
|
1400
|
+
const extension = extname(source).slice(1).toLowerCase();
|
|
1401
|
+
let meta;
|
|
1402
|
+
try {
|
|
1403
|
+
meta = readImageMeta(bytes, extension, path);
|
|
1404
|
+
} catch (error) {
|
|
1405
|
+
return error instanceof Error ? error.message.replace(`${path}: `, "") : String(error);
|
|
1406
|
+
}
|
|
1407
|
+
const name = `${basename(source, extname(source))}-${new Bun.CryptoHasher("sha256").update(bytes).digest("hex").slice(0, 8)}.${extension}`;
|
|
1408
|
+
await Bun.write(join4(output.dir, name), bytes);
|
|
1409
|
+
return { src: `${output.url}${name}`, width: meta.width, height: meta.height, format: meta.format };
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
return scope;
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// packages/content/src/build/index.ts
|
|
1416
|
+
var RESERVED = ["collection", "id", "stem", "extension", "body", "excerpt", "headings", "toc"];
|
|
1417
|
+
var ENTRY_FIELDS = new Set(RESERVED);
|
|
1418
|
+
var PAGE_FIELDS2 = new Set([
|
|
1419
|
+
...RESERVED,
|
|
1420
|
+
"readingTime",
|
|
1421
|
+
"title",
|
|
1422
|
+
"description",
|
|
1423
|
+
"seo",
|
|
1424
|
+
"navigation",
|
|
1425
|
+
"draft",
|
|
1426
|
+
"path",
|
|
1427
|
+
"navigationDirs"
|
|
1428
|
+
]);
|
|
1429
|
+
var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1430
|
+
var pathOf = (path) => (path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
|
|
1431
|
+
var at = (shown, path) => path ? `${shown}: ${path}: ` : `${shown}: `;
|
|
1432
|
+
function toJson(value, shown, path = []) {
|
|
1433
|
+
if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number")
|
|
1434
|
+
return value;
|
|
1435
|
+
if (value instanceof Date)
|
|
1436
|
+
return value.toISOString();
|
|
1437
|
+
if (Array.isArray(value))
|
|
1438
|
+
return value.map((item, index) => item === undefined ? null : toJson(item, shown, [...path, String(index)]));
|
|
1439
|
+
if (typeof value === "object") {
|
|
1440
|
+
const proto = Object.getPrototypeOf(value);
|
|
1441
|
+
if (proto === Object.prototype || proto === null) {
|
|
1442
|
+
const out = {};
|
|
1443
|
+
for (const [key, item] of Object.entries(value))
|
|
1444
|
+
if (item !== undefined)
|
|
1445
|
+
out[key] = toJson(item, shown, [...path, key]);
|
|
1446
|
+
return out;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
const kind = typeof value === "object" ? value.constructor?.name ?? "object" : typeof value;
|
|
1450
|
+
throw new ContentError("HAMUR_E5343", `${at(shown, path.join("."))}a schema output must be JSON (got ${kind})`);
|
|
1451
|
+
}
|
|
1452
|
+
async function validate(schema, data, shown, item, images) {
|
|
1453
|
+
let output = data;
|
|
1454
|
+
if (schema) {
|
|
1455
|
+
const result = await withImages(images, async () => schema["~standard"].validate(data));
|
|
1456
|
+
if (result.issues) {
|
|
1457
|
+
throw new ContentError("HAMUR_E5344", result.issues.map((issue) => `${at(shown, [item, pathOf(issue.path)].filter(Boolean).join("."))}${issue.message}`).join(`
|
|
1458
|
+
`));
|
|
1459
|
+
}
|
|
1460
|
+
output = result.value;
|
|
1461
|
+
}
|
|
1462
|
+
if (!isObject3(output))
|
|
1463
|
+
throw new ContentError("HAMUR_E5345", `${at(shown, item ?? "")}a schema output must be an object`);
|
|
1464
|
+
return toJson(output, shown, item === undefined ? [] : [item]);
|
|
1465
|
+
}
|
|
1466
|
+
function checkReserved(data, shown, kind) {
|
|
1467
|
+
for (const field of RESERVED)
|
|
1468
|
+
if (Object.hasOwn(data, field))
|
|
1469
|
+
throw new ContentError("HAMUR_E5346", `${shown}: ${kind} field "${field}" is reserved`);
|
|
1470
|
+
}
|
|
1471
|
+
var without = (data, keys) => Object.fromEntries(Object.entries(data).filter(([key]) => !keys.has(key)));
|
|
1472
|
+
var extensionOf = (file) => {
|
|
1473
|
+
const dot = file.lastIndexOf(".");
|
|
1474
|
+
return dot > file.lastIndexOf("/") ? file.slice(dot + 1) : "";
|
|
1475
|
+
};
|
|
1476
|
+
var shownOf3 = (ctx, loader, id, file) => file ? relative3(ctx.rootDir, file).split(sep4).join("/") : `content: loader "${loader}", entry "${id}"`;
|
|
1477
|
+
var digestOf = (value) => Bun.hash(value).toString(36);
|
|
1478
|
+
var validated = new WeakSet;
|
|
1479
|
+
async function buildEntry(input, loader, collection, ctx, withImage) {
|
|
1480
|
+
const shown = shownOf3(ctx, loader, input.id, input.file);
|
|
1481
|
+
const extension = input.file ? extensionOf(input.file) : "";
|
|
1482
|
+
const stem = input.stem ?? input.id;
|
|
1483
|
+
const label = input.file && input.id.startsWith(`${stem}/`) ? input.id.slice(stem.length + 1) : undefined;
|
|
1484
|
+
const page = collection.type === "page";
|
|
1485
|
+
const done = validated.has(input.data);
|
|
1486
|
+
let parsed;
|
|
1487
|
+
let fields = input.data;
|
|
1488
|
+
if (page || input.body !== undefined) {
|
|
1489
|
+
const options = {
|
|
1490
|
+
...page ? { ...ctx.markdown, ...ctx.siteUrl === undefined ? {} : { siteUrl: ctx.siteUrl } } : {},
|
|
1491
|
+
...input.file ? { file: shown } : {}
|
|
1492
|
+
};
|
|
1493
|
+
parsed = await (ctx.parseMarkdown ?? parseMarkdown)(input.body ?? "", options);
|
|
1494
|
+
if (!done)
|
|
1495
|
+
fields = { ...parsed.frontmatter, ...input.data };
|
|
1496
|
+
}
|
|
1497
|
+
if (!done)
|
|
1498
|
+
checkReserved(fields, shown, extension === "md" ? "frontmatter" : "data");
|
|
1499
|
+
const images = entryImages(input.file, ctx.images);
|
|
1500
|
+
const data = done ? fields : await validate(collection.schema, fields, shown, label, images);
|
|
1501
|
+
if (images.used)
|
|
1502
|
+
withImage.add(input.id);
|
|
1503
|
+
if (!page || !parsed)
|
|
1504
|
+
return { collection: "", id: input.id, stem, extension, ...without(data, ENTRY_FIELDS) };
|
|
1505
|
+
const title = typeof data.title === "string" ? data.title : parsed.title;
|
|
1506
|
+
const description = typeof data.description === "string" ? data.description : parsed.description;
|
|
1507
|
+
const navigation = data.navigation === false ? false : isObject3(data.navigation) ? data.navigation : true;
|
|
1508
|
+
return {
|
|
1509
|
+
collection: "",
|
|
1510
|
+
id: input.id,
|
|
1511
|
+
stem,
|
|
1512
|
+
extension,
|
|
1513
|
+
path: typeof data.path === "string" && data.path.startsWith("/") ? data.path : input.path ?? `/${input.id}`,
|
|
1514
|
+
title,
|
|
1515
|
+
description,
|
|
1516
|
+
seo: {
|
|
1517
|
+
...title === undefined ? {} : { title },
|
|
1518
|
+
...description === undefined ? {} : { description },
|
|
1519
|
+
...isObject3(data.seo) ? data.seo : {}
|
|
1520
|
+
},
|
|
1521
|
+
navigation,
|
|
1522
|
+
draft: data.draft === true,
|
|
1523
|
+
...input.navigationDirs ? { navigationDirs: input.navigationDirs } : {},
|
|
1524
|
+
...without(data, PAGE_FIELDS2),
|
|
1525
|
+
body: parsed.ast,
|
|
1526
|
+
excerpt: parsed.excerpt,
|
|
1527
|
+
headings: parsed.headings,
|
|
1528
|
+
toc: parsed.toc,
|
|
1529
|
+
readingTime: parsed.readingTime
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
async function finishEntry(built, input, name, shown, ctx) {
|
|
1533
|
+
let entry = { ...built, collection: name };
|
|
1534
|
+
const transformers = (ctx.transformers ?? []).filter((item) => item.transform !== undefined);
|
|
1535
|
+
if (!transformers.length && !ctx.hooks)
|
|
1536
|
+
return entry;
|
|
1537
|
+
for (const transformer of transformers) {
|
|
1538
|
+
let result;
|
|
1539
|
+
try {
|
|
1540
|
+
result = await transformer.transform(entry);
|
|
1541
|
+
} catch (error) {
|
|
1542
|
+
throw new ContentError("HAMUR_E5347", `${shown}: transformer "${transformer.name}" failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1543
|
+
}
|
|
1544
|
+
if (!isObject3(result))
|
|
1545
|
+
throw new ContentError("HAMUR_E5348", `${shown}: transformer "${transformer.name}" must return an object from transform`);
|
|
1546
|
+
entry = result;
|
|
1547
|
+
}
|
|
1548
|
+
if (ctx.hooks) {
|
|
1549
|
+
try {
|
|
1550
|
+
await ctx.hooks.afterParse({ id: input.id, path: shown, extension: extensionOf(input.file ?? ""), body: input.body ?? "" }, entry, name);
|
|
1551
|
+
} catch (error) {
|
|
1552
|
+
throw new ContentError("HAMUR_E5349", `${shown}: content:file:afterParse failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
return toJson(entry, shown);
|
|
1556
|
+
}
|
|
1557
|
+
var fileKey = (collection, id) => `${collection}\x00${id}`;
|
|
1558
|
+
var indexPath = (ctx, name) => join5(ctx.buildDir, "content", `${name}.json`);
|
|
1559
|
+
async function readIndexFile(ctx, name) {
|
|
1560
|
+
try {
|
|
1561
|
+
const file = JSON.parse(await Bun.file(indexPath(ctx, name)).text());
|
|
1562
|
+
return file.version === 1 && file.digest === ctx.digest && Array.isArray(file.entries) && isObject3(file.meta) ? file : undefined;
|
|
1563
|
+
} catch {
|
|
1564
|
+
return;
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
async function collectionEntries(name, collection, ctx) {
|
|
1568
|
+
const { loader: custom, source } = collection;
|
|
1569
|
+
const loader = custom ?? sourceLoader(source, ctx.cacheDir);
|
|
1570
|
+
const last = await readIndexFile(ctx, name);
|
|
1571
|
+
const lastEntries = new Map((last?.entries ?? []).map((item) => [item.entry.id, item]));
|
|
1572
|
+
const inputs = new Map;
|
|
1573
|
+
const withImage = new Set;
|
|
1574
|
+
const meta = new Map(Object.entries(last?.meta ?? {}));
|
|
1575
|
+
const loaderContext = {
|
|
1576
|
+
collection: name,
|
|
1577
|
+
type: collection.type,
|
|
1578
|
+
rootDir: ctx.rootDir,
|
|
1579
|
+
store: {
|
|
1580
|
+
set: (entry) => void inputs.set(entry.id, entry),
|
|
1581
|
+
delete: (id) => void inputs.delete(id),
|
|
1582
|
+
keys: () => [...inputs.keys()],
|
|
1583
|
+
clear: () => inputs.clear()
|
|
1584
|
+
},
|
|
1585
|
+
meta: { get: (key) => meta.get(key), set: (key, value) => void meta.set(key, value) },
|
|
1586
|
+
async parseData({ id, data, file }) {
|
|
1587
|
+
const shown = shownOf3(ctx, loader.name, id, file);
|
|
1588
|
+
if (!isObject3(data))
|
|
1589
|
+
throw new ContentError("HAMUR_E5350", `${at(shown, "")}a data entry is an object`);
|
|
1590
|
+
checkReserved(data, shown, "data");
|
|
1591
|
+
const images = entryImages(file, ctx.images);
|
|
1592
|
+
const output = await validate(collection.schema, data, shown, undefined, images);
|
|
1593
|
+
if (images.used)
|
|
1594
|
+
withImage.add(id);
|
|
1595
|
+
validated.add(output);
|
|
1596
|
+
return output;
|
|
1597
|
+
},
|
|
1598
|
+
parseMarkdown: (text, options) => (ctx.parseMarkdown ?? parseMarkdown)(text, {
|
|
1599
|
+
...ctx.markdown,
|
|
1600
|
+
...ctx.siteUrl === undefined ? {} : { siteUrl: ctx.siteUrl },
|
|
1601
|
+
...options
|
|
1602
|
+
}),
|
|
1603
|
+
digest: digestOf,
|
|
1604
|
+
csv: ctx.csv ?? DEFAULT_CSV,
|
|
1605
|
+
logger: ctx.logger ?? useLogger2("content"),
|
|
1606
|
+
transformers: ctx.transformers ?? [],
|
|
1607
|
+
async beforeParse(file) {
|
|
1608
|
+
if (!ctx.hooks)
|
|
1609
|
+
return file.body;
|
|
1610
|
+
try {
|
|
1611
|
+
await ctx.hooks.beforeParse(file, name);
|
|
1612
|
+
} catch (error) {
|
|
1613
|
+
throw new ContentError("HAMUR_E5351", `${file.path}: content:file:beforeParse failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1614
|
+
}
|
|
1615
|
+
if (typeof file.body !== "string")
|
|
1616
|
+
throw new ContentError("HAMUR_E5352", `${file.path}: content:file:beforeParse must leave file.body a string`);
|
|
1617
|
+
return file.body;
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
try {
|
|
1621
|
+
await loader.load(loaderContext);
|
|
1622
|
+
} catch (error) {
|
|
1623
|
+
if (error instanceof ContentError)
|
|
1624
|
+
throw error;
|
|
1625
|
+
throw new ContentError("HAMUR_E5353", `content: loader "${loader.name}" failed: ${error.message}`);
|
|
1626
|
+
}
|
|
1627
|
+
const built = [];
|
|
1628
|
+
for (const input of inputs.values()) {
|
|
1629
|
+
const cached = input.digest === undefined ? undefined : lastEntries.get(input.id);
|
|
1630
|
+
const reuse = cached !== undefined && cached.images !== true && cached.digest === input.digest;
|
|
1631
|
+
const shown = shownOf3(ctx, loader.name, input.id, input.file);
|
|
1632
|
+
const entry = reuse ? { ...cached.entry, collection: name } : await finishEntry(await buildEntry(input, loader.name, collection, ctx, withImage), input, name, shown, ctx);
|
|
1633
|
+
built.push({ input, entry, shown });
|
|
1634
|
+
}
|
|
1635
|
+
if (ctx.files) {
|
|
1636
|
+
for (const { input } of built)
|
|
1637
|
+
if (input.file)
|
|
1638
|
+
ctx.files.set(fileKey(name, input.id), input.file);
|
|
1639
|
+
}
|
|
1640
|
+
if (ctx.bodies) {
|
|
1641
|
+
for (const { input } of built)
|
|
1642
|
+
if (input.body !== undefined)
|
|
1643
|
+
ctx.bodies.set(fileKey(name, input.id), input.body);
|
|
1644
|
+
}
|
|
1645
|
+
const file = {
|
|
1646
|
+
version: 1,
|
|
1647
|
+
digest: ctx.digest,
|
|
1648
|
+
meta: Object.fromEntries(meta),
|
|
1649
|
+
entries: built.map(({ input, entry }) => ({
|
|
1650
|
+
digest: input.digest ?? null,
|
|
1651
|
+
entry,
|
|
1652
|
+
...withImage.has(input.id) ? { images: true } : {}
|
|
1653
|
+
}))
|
|
1654
|
+
};
|
|
1655
|
+
await Bun.write(indexPath(ctx, name), JSON.stringify(file));
|
|
1656
|
+
if (collection.type === "data")
|
|
1657
|
+
return built.map(({ entry }) => entry);
|
|
1658
|
+
const kept = ctx.dev ? built : built.filter(({ entry }) => !entry.draft);
|
|
1659
|
+
const drafts = built.length - kept.length;
|
|
1660
|
+
if (drafts)
|
|
1661
|
+
ctx.log(`${name}: ${drafts} ${drafts === 1 ? "draft" : "drafts"} left out`);
|
|
1662
|
+
const paths = new Map;
|
|
1663
|
+
for (const { entry, shown } of kept) {
|
|
1664
|
+
const path = entry.path;
|
|
1665
|
+
const other = paths.get(path);
|
|
1666
|
+
if (other !== undefined)
|
|
1667
|
+
throw new ContentError("HAMUR_E5354", `content: ${other} and ${shown} both have path ${path}`);
|
|
1668
|
+
paths.set(path, shown);
|
|
1669
|
+
}
|
|
1670
|
+
return kept.map(({ entry }) => entry);
|
|
1671
|
+
}
|
|
1672
|
+
async function buildIndex(config, ctx) {
|
|
1673
|
+
const index = {};
|
|
1674
|
+
for (const [name, collection] of Object.entries(config.collections))
|
|
1675
|
+
index[name] = await collectionEntries(name, collection, ctx);
|
|
1676
|
+
return index;
|
|
1677
|
+
}
|
|
1678
|
+
var devChunkPath = (buildDir, name) => join5(buildDir, "content", "dev", `${name}.json`);
|
|
1679
|
+
async function writeDevChunk(buildDir, name, entries) {
|
|
1680
|
+
const path = devChunkPath(buildDir, name);
|
|
1681
|
+
await Bun.write(`${path}.tmp`, JSON.stringify(entries));
|
|
1682
|
+
await rename2(`${path}.tmp`, path);
|
|
1683
|
+
}
|
|
1684
|
+
function transformersKey(transformers) {
|
|
1685
|
+
return JSON.stringify(transformers.map(({ name, extensions, parse, transform }) => [
|
|
1686
|
+
name,
|
|
1687
|
+
extensions,
|
|
1688
|
+
parse?.toString() ?? null,
|
|
1689
|
+
transform?.toString() ?? null
|
|
1690
|
+
]));
|
|
1691
|
+
}
|
|
1692
|
+
var CONTENT_HOOKS = ["content:file:beforeParse", "content:file:afterParse"];
|
|
1693
|
+
function watchContentHooks(hamur) {
|
|
1694
|
+
const registered = new Set(Object.keys(hamur.options.hooks ?? {}).filter((name) => CONTENT_HOOKS.includes(name)));
|
|
1695
|
+
for (const method of ["hook", "hookOnce"]) {
|
|
1696
|
+
const original = hamur.hooks[method].bind(hamur.hooks);
|
|
1697
|
+
hamur.hooks[method] = (name, fn) => {
|
|
1698
|
+
if (CONTENT_HOOKS.includes(name))
|
|
1699
|
+
registered.add(name);
|
|
1700
|
+
return original(name, fn);
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
return registered;
|
|
1704
|
+
}
|
|
1705
|
+
var DEFAULT_CHUNK_SIZE = 1000;
|
|
1706
|
+
function resolveChunkSize(value) {
|
|
1707
|
+
if (value === undefined)
|
|
1708
|
+
return DEFAULT_CHUNK_SIZE;
|
|
1709
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1)
|
|
1710
|
+
throw new DiagnosticError5("HAMUR_E5338", `content.chunkSize must be a positive integer (got ${JSON.stringify(value)})`);
|
|
1711
|
+
return value;
|
|
1712
|
+
}
|
|
1713
|
+
function splitChunks(entries, size) {
|
|
1714
|
+
const chunks = [];
|
|
1715
|
+
for (let at = 0;at < entries.length; at += size)
|
|
1716
|
+
chunks.push(entries.slice(at, at + size));
|
|
1717
|
+
return chunks;
|
|
1718
|
+
}
|
|
1719
|
+
var chunkRangesOf = (chunks) => chunks.map((chunk) => ({ first: chunk[0].id, last: chunk.at(-1).id }));
|
|
1720
|
+
function setupIndex(hamur, config, options = {}) {
|
|
1721
|
+
const { rootDir, buildDir, cacheDir, markdown, site, dev } = hamur.options;
|
|
1722
|
+
const chunkSize = resolveChunkSize(options.chunkSize);
|
|
1723
|
+
const logger = useLogger2("content");
|
|
1724
|
+
const csv = resolveCsv(options.csv);
|
|
1725
|
+
const parse = useMarkdownParser();
|
|
1726
|
+
const transformers = config.transformers ?? [];
|
|
1727
|
+
const registered = watchContentHooks(hamur);
|
|
1728
|
+
const hooks = {
|
|
1729
|
+
beforeParse: (file, collection) => hamur.hooks.callHook("content:file:beforeParse", { file, collection }),
|
|
1730
|
+
afterParse: (file, entry, collection) => hamur.hooks.callHook("content:file:afterParse", { file, entry, collection })
|
|
1731
|
+
};
|
|
1732
|
+
const files = new Map;
|
|
1733
|
+
const bodies = new Map;
|
|
1734
|
+
const images = setupImages(hamur);
|
|
1735
|
+
let context;
|
|
1736
|
+
const contextOf = () => context ??= (async () => {
|
|
1737
|
+
const text = await Bun.file(join5(rootDir, "content.config.ts")).text();
|
|
1738
|
+
const digest = digestOf(`${text}\x00${JSON.stringify(markdown)}\x00${site?.url ?? ""}\x00${transformersKey(transformers)}\x00${[...registered].sort().join(",")}`);
|
|
1739
|
+
return {
|
|
1740
|
+
rootDir,
|
|
1741
|
+
buildDir,
|
|
1742
|
+
cacheDir,
|
|
1743
|
+
digest,
|
|
1744
|
+
csv,
|
|
1745
|
+
files,
|
|
1746
|
+
bodies,
|
|
1747
|
+
images,
|
|
1748
|
+
transformers,
|
|
1749
|
+
hooks,
|
|
1750
|
+
markdown,
|
|
1751
|
+
...site?.url === undefined ? {} : { siteUrl: site.url },
|
|
1752
|
+
dev,
|
|
1753
|
+
log: (message) => logger.info(message),
|
|
1754
|
+
logger,
|
|
1755
|
+
parseMarkdown: parse
|
|
1756
|
+
};
|
|
1757
|
+
})();
|
|
1758
|
+
let index;
|
|
1759
|
+
const read = () => index ??= (async () => {
|
|
1760
|
+
const entries = await buildIndex(config, await contextOf());
|
|
1761
|
+
if (dev)
|
|
1762
|
+
for (const [name, list] of Object.entries(entries))
|
|
1763
|
+
await writeDevChunk(buildDir, name, list);
|
|
1764
|
+
return entries;
|
|
1765
|
+
})();
|
|
1766
|
+
const rebuild = async (name) => {
|
|
1767
|
+
const current = await read();
|
|
1768
|
+
const entries = await collectionEntries(name, config.collections[name], await contextOf());
|
|
1769
|
+
current[name] = entries;
|
|
1770
|
+
if (dev)
|
|
1771
|
+
await writeDevChunk(buildDir, name, entries);
|
|
1772
|
+
return entries;
|
|
1773
|
+
};
|
|
1774
|
+
hamur.hooks.hook("build:before", async () => {
|
|
1775
|
+
await read();
|
|
1776
|
+
});
|
|
1777
|
+
if (dev)
|
|
1778
|
+
read().catch(() => {});
|
|
1779
|
+
for (const name of Object.keys(config.collections)) {
|
|
1780
|
+
addTemplate2({
|
|
1781
|
+
filename: `content/chunks/${name}.json`,
|
|
1782
|
+
getContents: async () => JSON.stringify((await read())[name])
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
const ranges = {};
|
|
1786
|
+
if (!dev) {
|
|
1787
|
+
hamur.hooks.hook("templates:extend", async () => {
|
|
1788
|
+
for (const [name, entries] of Object.entries(await read())) {
|
|
1789
|
+
const chunks = splitChunks(entries, chunkSize);
|
|
1790
|
+
ranges[name] = chunkRangesOf(chunks);
|
|
1791
|
+
chunks.forEach((chunk, at) => addTemplate2({ filename: `content/chunks/${name}.${at}.json`, getContents: () => JSON.stringify(chunk) }));
|
|
1792
|
+
}
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
const resolver = createResolver3(new URL("../../src/build/index.ts", import.meta.url).href);
|
|
1796
|
+
const store = resolver.resolve("../runtime/store.ts");
|
|
1797
|
+
const devStore = resolver.resolve("../runtime/dev-store.ts");
|
|
1798
|
+
addTemplate2({
|
|
1799
|
+
filename: "content/store",
|
|
1800
|
+
getContents: async () => {
|
|
1801
|
+
if (!dev)
|
|
1802
|
+
return storeModule(config, store, undefined, ranges);
|
|
1803
|
+
await read();
|
|
1804
|
+
return storeModule(config, store, { module: devStore, buildDir });
|
|
1805
|
+
}
|
|
1806
|
+
});
|
|
1807
|
+
return {
|
|
1808
|
+
read,
|
|
1809
|
+
rebuild,
|
|
1810
|
+
file: (collection, id) => files.get(fileKey(collection, id)),
|
|
1811
|
+
body: (collection, id) => bodies.get(fileKey(collection, id)),
|
|
1812
|
+
reset: () => void (index = undefined)
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
function storeModule(config, store, dev, chunks) {
|
|
1816
|
+
const collections = Object.entries(config.collections).map(([name, { type, expose = true, order }]) => {
|
|
1817
|
+
const meta = JSON.stringify({ type, expose, ...order ? { order } : {} }).slice(0, -1);
|
|
1818
|
+
const ranges = chunks?.[name];
|
|
1819
|
+
if (ranges) {
|
|
1820
|
+
const list = ranges.map(({ first, last }, at) => `{ first: ${JSON.stringify(first)}, last: ${JSON.stringify(last)}, load: () => import(${JSON.stringify(`#hamur/content/chunks/${name}.${at}.json`)}) }`);
|
|
1821
|
+
return ` ${JSON.stringify(name)}: ${meta}, chunks: [${list.join(", ")}] },`;
|
|
1822
|
+
}
|
|
1823
|
+
const load = dev ? `devChunk(${JSON.stringify(devChunkPath(dev.buildDir, name))})` : `() => import(${JSON.stringify(`#hamur/content/chunks/${name}.json`)})`;
|
|
1824
|
+
return ` ${JSON.stringify(name)}: ${meta}, load: ${load} },`;
|
|
1825
|
+
});
|
|
1826
|
+
return [
|
|
1827
|
+
`import { createStore } from ${JSON.stringify(store)};`,
|
|
1828
|
+
...dev ? [`import { devChunk } from ${JSON.stringify(dev.module)};`] : [],
|
|
1829
|
+
"",
|
|
1830
|
+
"export default createStore({",
|
|
1831
|
+
...collections,
|
|
1832
|
+
dev ? "}, { cache: false });" : "});",
|
|
1833
|
+
""
|
|
1834
|
+
].join(`
|
|
1835
|
+
`);
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
// packages/content/src/build/live.ts
|
|
1839
|
+
import { join as join6 } from "node:path";
|
|
1840
|
+
import { addBunPlugin, addTemplate as addTemplate3, createResolver as createResolver4 } from "hamur/kit";
|
|
1841
|
+
function liveModule(configFile, config) {
|
|
1842
|
+
const live = Object.keys(config.live);
|
|
1843
|
+
const names = JSON.stringify([...Object.keys(config.collections), ...live]);
|
|
1844
|
+
if (!live.length)
|
|
1845
|
+
return [`export const names = ${names};`, "export default {};", ""].join(`
|
|
1846
|
+
`);
|
|
1847
|
+
return [
|
|
1848
|
+
`import config from ${JSON.stringify(configFile)};`,
|
|
1849
|
+
"",
|
|
1850
|
+
`export const names = ${names};`,
|
|
1851
|
+
"export default {",
|
|
1852
|
+
...live.map((name) => ` ${JSON.stringify(name)}: config.collections[${JSON.stringify(name)}],`),
|
|
1853
|
+
"};",
|
|
1854
|
+
""
|
|
1855
|
+
].join(`
|
|
1856
|
+
`);
|
|
1857
|
+
}
|
|
1858
|
+
function setupLive(config, hamur) {
|
|
1859
|
+
addTemplate3({
|
|
1860
|
+
filename: "content/live",
|
|
1861
|
+
getContents: () => liveModule(join6(hamur.options.rootDir, "content.config.ts"), config)
|
|
1862
|
+
});
|
|
1863
|
+
if (!Object.keys(config.live).length)
|
|
1864
|
+
return;
|
|
1865
|
+
const definers = createResolver4(new URL("../../src/build/live.ts", import.meta.url).href).resolve("../server-config.ts");
|
|
1866
|
+
addBunPlugin({
|
|
1867
|
+
name: "hamur-content-config",
|
|
1868
|
+
setup: (build) => void build.onResolve({ filter: /^@hamur\/content$/ }, () => ({ path: definers }))
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
// packages/content/src/build/prerender.ts
|
|
1873
|
+
import { DiagnosticError as DiagnosticError6 } from "hamur/kit";
|
|
1874
|
+
function resolvePrerender(value, preset) {
|
|
1875
|
+
if (value === undefined)
|
|
1876
|
+
return preset === "static";
|
|
1877
|
+
if (typeof value !== "boolean")
|
|
1878
|
+
throw new DiagnosticError6("HAMUR_E5334", `content.prerender must be a boolean (got ${JSON.stringify(value)})`);
|
|
1879
|
+
return value;
|
|
1880
|
+
}
|
|
1881
|
+
function pagePaths(config, index) {
|
|
1882
|
+
const paths = [];
|
|
1883
|
+
for (const [name, collection] of Object.entries(config.collections)) {
|
|
1884
|
+
if (collection.type !== "page")
|
|
1885
|
+
continue;
|
|
1886
|
+
for (const entry of index[name] ?? [])
|
|
1887
|
+
if (!entry.draft)
|
|
1888
|
+
paths.push(entry.path);
|
|
1889
|
+
}
|
|
1890
|
+
return paths;
|
|
1891
|
+
}
|
|
1892
|
+
function setupPrerender(options, config, entries, hamur) {
|
|
1893
|
+
if (!resolvePrerender(options.prerender, hamur.options.preset))
|
|
1894
|
+
return;
|
|
1895
|
+
hamur.hooks.hook("prerender:routes", async (routes) => {
|
|
1896
|
+
for (const path of pagePaths(config, await entries()))
|
|
1897
|
+
routes.add(path);
|
|
1898
|
+
});
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
// packages/content/src/build/query.ts
|
|
1902
|
+
import { DiagnosticError as DiagnosticError10, addAppPlugin as addAppPlugin3, addServer as addServer2, addTemplate as addTemplate6, createResolver as createResolver7 } from "hamur/kit";
|
|
1903
|
+
|
|
1904
|
+
// packages/content/src/build/api.ts
|
|
1905
|
+
import { join as join7, relative as relative4, sep as sep5 } from "node:path";
|
|
1906
|
+
import { DiagnosticError as DiagnosticError7, addServer, addTemplate as addTemplate4, createResolver as createResolver5 } from "hamur/kit";
|
|
1907
|
+
var shown2 = (value) => JSON.stringify(value) ?? String(value);
|
|
1908
|
+
var isRecord2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1909
|
+
function resolveApi(value, preset, serverGraphQL) {
|
|
1910
|
+
if (value === undefined)
|
|
1911
|
+
return { rest: false, graphql: false };
|
|
1912
|
+
if (!isRecord2(value))
|
|
1913
|
+
throw new DiagnosticError7("HAMUR_E5335", `content.api must be { rest?: boolean, graphql?: boolean } (got ${shown2(value)})`);
|
|
1914
|
+
for (const key of Object.keys(value))
|
|
1915
|
+
if (key !== "rest" && key !== "graphql")
|
|
1916
|
+
throw new DiagnosticError7("HAMUR_E5335", `content.api has no key ${shown2(key)}; it takes rest and graphql`);
|
|
1917
|
+
for (const key of ["rest", "graphql"])
|
|
1918
|
+
if (value[key] !== undefined && typeof value[key] !== "boolean")
|
|
1919
|
+
throw new DiagnosticError7("HAMUR_E5335", `content.api.${key} must be a boolean (got ${shown2(value[key])})`);
|
|
1920
|
+
const rest = value.rest === true;
|
|
1921
|
+
const graphql = value.graphql === true;
|
|
1922
|
+
if (rest && preset === "static")
|
|
1923
|
+
throw new DiagnosticError7("HAMUR_E5336", "content.api.rest needs a server; the static preset serves no route");
|
|
1924
|
+
if (graphql && !serverGraphQL)
|
|
1925
|
+
throw new DiagnosticError7("HAMUR_E5337", "content.api.graphql needs server.graphql on");
|
|
1926
|
+
return { rest, graphql };
|
|
1927
|
+
}
|
|
1928
|
+
var STRING = { type: "string" };
|
|
1929
|
+
var DATA_FIELDS2 = { collection: STRING, id: STRING, stem: STRING, extension: STRING };
|
|
1930
|
+
var PAGE_FIELDS3 = {
|
|
1931
|
+
...DATA_FIELDS2,
|
|
1932
|
+
path: STRING,
|
|
1933
|
+
title: STRING,
|
|
1934
|
+
description: STRING,
|
|
1935
|
+
seo: { type: "object" },
|
|
1936
|
+
navigation: { type: ["boolean", "object"] },
|
|
1937
|
+
draft: { type: "boolean" },
|
|
1938
|
+
navigationDirs: { type: "object" },
|
|
1939
|
+
body: { type: "array" },
|
|
1940
|
+
excerpt: { type: "array" },
|
|
1941
|
+
headings: { type: "array" },
|
|
1942
|
+
toc: { type: "array" },
|
|
1943
|
+
readingTime: { type: "number" }
|
|
1944
|
+
};
|
|
1945
|
+
function outputSchema(collection) {
|
|
1946
|
+
const converter = collection.schema?.["~standard"]?.jsonSchema;
|
|
1947
|
+
if (typeof converter?.output !== "function")
|
|
1948
|
+
return;
|
|
1949
|
+
try {
|
|
1950
|
+
const schema = converter.output({ target: "draft-2020-12" });
|
|
1951
|
+
return isRecord2(schema) ? schema : undefined;
|
|
1952
|
+
} catch {
|
|
1953
|
+
return;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
var OPEN_KEYS = new Set(["additionalProperties", "unevaluatedProperties"]);
|
|
1957
|
+
function rerooted(value, entry) {
|
|
1958
|
+
if (Array.isArray(value))
|
|
1959
|
+
return value.map((item) => rerooted(item, entry));
|
|
1960
|
+
if (!isRecord2(value))
|
|
1961
|
+
return value;
|
|
1962
|
+
const result = {};
|
|
1963
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1964
|
+
const moved = key === "$ref" && typeof child === "string" && (child === "#" || child.startsWith("#/") && !child.startsWith("#/$defs/")) ? `#/$defs/${entry}${child.slice(1)}` : rerooted(child, entry);
|
|
1965
|
+
Object.defineProperty(result, key, { value: moved, enumerable: true, writable: true, configurable: true });
|
|
1966
|
+
}
|
|
1967
|
+
return result;
|
|
1968
|
+
}
|
|
1969
|
+
function restSchema(name, collection) {
|
|
1970
|
+
const page = collection.type === "page";
|
|
1971
|
+
const builtRequired = page ? ["collection", "id", "stem", "extension", "path"] : ["collection", "id", "stem", "extension"];
|
|
1972
|
+
const builtProperties = page ? PAGE_FIELDS3 : DATA_FIELDS2;
|
|
1973
|
+
const own = outputSchema(collection);
|
|
1974
|
+
const { $schema: _, $defs, ...rest } = own ?? {};
|
|
1975
|
+
const defs = isRecord2($defs) ? $defs : {};
|
|
1976
|
+
let entry = `Content${name[0].toUpperCase()}${name.slice(1)}`;
|
|
1977
|
+
while (Object.hasOwn(defs, entry))
|
|
1978
|
+
entry = `${entry}_`;
|
|
1979
|
+
const open = Object.fromEntries(Object.entries(rest).filter(([key]) => !OPEN_KEYS.has(key)));
|
|
1980
|
+
let schema;
|
|
1981
|
+
if (!own)
|
|
1982
|
+
schema = { type: "object", required: builtRequired, properties: builtProperties };
|
|
1983
|
+
else if (isRecord2(open.properties) || open.type === "object") {
|
|
1984
|
+
const required = [
|
|
1985
|
+
...Array.isArray(open.required) ? open.required.filter((key) => !builtRequired.includes(key)) : [],
|
|
1986
|
+
...builtRequired
|
|
1987
|
+
];
|
|
1988
|
+
schema = {
|
|
1989
|
+
...open,
|
|
1990
|
+
type: "object",
|
|
1991
|
+
properties: { ...isRecord2(open.properties) ? open.properties : {}, ...builtProperties },
|
|
1992
|
+
required
|
|
1993
|
+
};
|
|
1994
|
+
} else
|
|
1995
|
+
schema = { allOf: [{ type: "object", required: builtRequired, properties: builtProperties }, open] };
|
|
1996
|
+
return { type: "array", items: { $ref: `#/$defs/${entry}` }, $defs: rerooted({ ...defs, [entry]: schema }, entry) };
|
|
1997
|
+
}
|
|
1998
|
+
var exportOf = (name) => `contentRest${name[0].toUpperCase()}${name.slice(1)}`;
|
|
1999
|
+
var restCollections = (config) => Object.entries(config.collections).filter(([, { expose = true }]) => expose).map(([name]) => name);
|
|
2000
|
+
function restModule(config, runtime) {
|
|
2001
|
+
const q = JSON.stringify;
|
|
2002
|
+
const handlers = restCollections(config).map((name) => [
|
|
2003
|
+
`export const ${exportOf(name)} = defineHandler({`,
|
|
2004
|
+
` route: ${q(`/api/_content/${name}`)},`,
|
|
2005
|
+
` method: "GET",`,
|
|
2006
|
+
" input: restInput,",
|
|
2007
|
+
` output: restOutput(${q(restSchema(name, config.collections[name]))}),`,
|
|
2008
|
+
` meta: { summary: ${q(`Query the ${name} collection`)}, description: REST_DESCRIPTION, tags: ["content"], operationId: ${q(`getContent${exportOf(name).slice("contentRest".length)}`)}, responses: restResponses },`,
|
|
2009
|
+
` handler: (input) => answerRest(store, ${q(name)}, input),`,
|
|
2010
|
+
"});",
|
|
2011
|
+
""
|
|
2012
|
+
].join(`
|
|
2013
|
+
`));
|
|
2014
|
+
return [
|
|
2015
|
+
`import store from "#hamur/content/store";`,
|
|
2016
|
+
`import { defineHandler } from "hamur/server";`,
|
|
2017
|
+
`import { answerRest, missingCollection, REST_DESCRIPTION, restInput, restOutput, restResponses } from ${q(runtime)};`,
|
|
2018
|
+
"",
|
|
2019
|
+
...handlers,
|
|
2020
|
+
"export const contentRest = defineHandler({",
|
|
2021
|
+
` route: "/api/_content/:collection",`,
|
|
2022
|
+
` method: "GET",`,
|
|
2023
|
+
" meta: { hidden: true },",
|
|
2024
|
+
" handler: (input) => missingCollection(input),",
|
|
2025
|
+
"});",
|
|
2026
|
+
""
|
|
2027
|
+
].join(`
|
|
2028
|
+
`);
|
|
2029
|
+
}
|
|
2030
|
+
var posix = (path) => path.split(sep5).join("/");
|
|
2031
|
+
function restDoor(config, serverDir, doorDir, dev) {
|
|
2032
|
+
const from = (file) => {
|
|
2033
|
+
const path = posix(relative4(doorDir, join7(serverDir, file)));
|
|
2034
|
+
return JSON.stringify(path.startsWith(".") ? path : `./${path}`);
|
|
2035
|
+
};
|
|
2036
|
+
return [
|
|
2037
|
+
`import { defineServer } from "hamur/server";`,
|
|
2038
|
+
`import { installStore } from ${from("install.ts")};`,
|
|
2039
|
+
"",
|
|
2040
|
+
`export { contentQuery } from ${from("endpoint.ts")};`,
|
|
2041
|
+
...dev ? [`export { contentRefresh } from ${from("refresh.ts")};`] : [],
|
|
2042
|
+
`export { ${[...restCollections(config).map(exportOf), "contentRest"].join(", ")} } from "./rest.ts";`,
|
|
2043
|
+
"",
|
|
2044
|
+
"export default defineServer({ plugins: [installStore] });",
|
|
2045
|
+
""
|
|
2046
|
+
].join(`
|
|
2047
|
+
`);
|
|
2048
|
+
}
|
|
2049
|
+
var FOLDER = "content/server";
|
|
2050
|
+
function setupRest(config, hamur) {
|
|
2051
|
+
const resolver = createResolver5(new URL("../../src/build/api.ts", import.meta.url).href);
|
|
2052
|
+
const serverDir = resolver.resolve("../server");
|
|
2053
|
+
const doorDir = join7(hamur.options.buildDir, FOLDER);
|
|
2054
|
+
addTemplate4({
|
|
2055
|
+
filename: `${FOLDER}/rest.ts`,
|
|
2056
|
+
write: true,
|
|
2057
|
+
getContents: () => restModule(config, resolver.resolve("../server/rest.ts"))
|
|
2058
|
+
});
|
|
2059
|
+
addTemplate4({
|
|
2060
|
+
filename: `${FOLDER}/door.ts`,
|
|
2061
|
+
write: true,
|
|
2062
|
+
getContents: () => restDoor(config, serverDir, doorDir, hamur.options.dev)
|
|
2063
|
+
});
|
|
2064
|
+
addServer(join7(doorDir, "door.ts"));
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
// packages/content/src/build/graphql.ts
|
|
2068
|
+
import { join as join8 } from "node:path";
|
|
2069
|
+
import { DiagnosticError as DiagnosticError8, addServerGraphQL, addTemplate as addTemplate5, createResolver as createResolver6 } from "hamur/kit";
|
|
2070
|
+
var NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
|
|
2071
|
+
var SCALARS = { string: "String", integer: "Int", number: "Float", boolean: "Boolean" };
|
|
2072
|
+
var isRecord3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2073
|
+
var pascal = (name) => `${name[0].toUpperCase()}${name.slice(1)}`;
|
|
2074
|
+
var q = JSON.stringify;
|
|
2075
|
+
var JSON_TEXT = { type: "String", json: true };
|
|
2076
|
+
function typeOf(schema, name, objects) {
|
|
2077
|
+
if (!isRecord3(schema))
|
|
2078
|
+
return JSON_TEXT;
|
|
2079
|
+
let type = schema.type;
|
|
2080
|
+
if (Array.isArray(type)) {
|
|
2081
|
+
const rest = type.filter((entry) => entry !== "null");
|
|
2082
|
+
if (rest.length !== 1)
|
|
2083
|
+
return JSON_TEXT;
|
|
2084
|
+
type = rest[0];
|
|
2085
|
+
}
|
|
2086
|
+
if (typeof type !== "string")
|
|
2087
|
+
return JSON_TEXT;
|
|
2088
|
+
if (Object.hasOwn(SCALARS, type))
|
|
2089
|
+
return { type: SCALARS[type], json: false };
|
|
2090
|
+
if (type === "array") {
|
|
2091
|
+
const item = typeOf(schema.items, name, objects);
|
|
2092
|
+
return item.json ? JSON_TEXT : { type: `[${item.type}]`, json: false };
|
|
2093
|
+
}
|
|
2094
|
+
if (type === "object" && isRecord3(schema.properties) && Object.keys(schema.properties).some((key) => NAME.test(key) && !key.startsWith("__"))) {
|
|
2095
|
+
addObject(name, {}, schema.properties, objects);
|
|
2096
|
+
return { type: name, json: false };
|
|
2097
|
+
}
|
|
2098
|
+
return JSON_TEXT;
|
|
2099
|
+
}
|
|
2100
|
+
function addObject(name, built, properties, objects) {
|
|
2101
|
+
if (objects.has(name))
|
|
2102
|
+
throw new DiagnosticError8("HAMUR_E5339", `content.api.graphql: two generated types are named "${name}"; rename a collection or a field`);
|
|
2103
|
+
const object = { fields: [], json: [] };
|
|
2104
|
+
objects.set(name, object);
|
|
2105
|
+
for (const [field, type] of Object.entries(built)) {
|
|
2106
|
+
object.fields.push(` ${field}: ${type}`);
|
|
2107
|
+
if (type === "String" && JSON_BUILT.has(field))
|
|
2108
|
+
object.json.push(field);
|
|
2109
|
+
}
|
|
2110
|
+
for (const [field, schema] of Object.entries(properties)) {
|
|
2111
|
+
if (Object.hasOwn(built, field) || !NAME.test(field) || field.startsWith("__"))
|
|
2112
|
+
continue;
|
|
2113
|
+
const mapped = typeOf(schema, `${name}${pascal(field)}`, objects);
|
|
2114
|
+
object.fields.push(` ${field}: ${mapped.type}`);
|
|
2115
|
+
if (mapped.json)
|
|
2116
|
+
object.json.push(field);
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
var DATA_FIELDS3 = {
|
|
2120
|
+
collection: "String!",
|
|
2121
|
+
id: "String!",
|
|
2122
|
+
stem: "String!",
|
|
2123
|
+
extension: "String!"
|
|
2124
|
+
};
|
|
2125
|
+
var PAGE_FIELDS4 = {
|
|
2126
|
+
...DATA_FIELDS3,
|
|
2127
|
+
path: "String!",
|
|
2128
|
+
title: "String",
|
|
2129
|
+
description: "String",
|
|
2130
|
+
draft: "Boolean",
|
|
2131
|
+
readingTime: "Float",
|
|
2132
|
+
seo: "String",
|
|
2133
|
+
navigation: "String",
|
|
2134
|
+
navigationDirs: "String",
|
|
2135
|
+
body: "String",
|
|
2136
|
+
excerpt: "String",
|
|
2137
|
+
headings: "String",
|
|
2138
|
+
toc: "String"
|
|
2139
|
+
};
|
|
2140
|
+
var JSON_BUILT = new Set(["seo", "navigation", "navigationDirs", "body", "excerpt", "headings", "toc"]);
|
|
2141
|
+
function contentGraphQL(config, runtime) {
|
|
2142
|
+
const names = restCollections(config);
|
|
2143
|
+
if (names.length === 0)
|
|
2144
|
+
return;
|
|
2145
|
+
const objects = new Map;
|
|
2146
|
+
const roots = [];
|
|
2147
|
+
const query = [];
|
|
2148
|
+
const taken = new Map;
|
|
2149
|
+
for (const name of names) {
|
|
2150
|
+
const collection = config.collections[name];
|
|
2151
|
+
const type = pascal(name);
|
|
2152
|
+
const own = outputSchema(collection);
|
|
2153
|
+
addObject(type, collection.type === "page" ? PAGE_FIELDS4 : DATA_FIELDS3, isRecord3(own?.properties) ? own.properties : {}, objects);
|
|
2154
|
+
const key = collection.type === "page" ? "path" : "id";
|
|
2155
|
+
for (const field of [name, `${name}Item`]) {
|
|
2156
|
+
const other = taken.get(field);
|
|
2157
|
+
if (other !== undefined)
|
|
2158
|
+
throw new DiagnosticError8("HAMUR_E5340", `content.api.graphql: Query.${field} of collection "${name}" is also Query.${field} of collection "${other}"; rename one`);
|
|
2159
|
+
taken.set(field, name);
|
|
2160
|
+
}
|
|
2161
|
+
roots.push(` ${name}(where: [ContentWhere!], order: [ContentOrder!], limit: Int, skip: Int): [${type}!]!`, ` ${name}Item(${key}: String!): ${type}`);
|
|
2162
|
+
query.push(` ${name}: (_parent: unknown, args: ListArgs) => contentList(store, ${q(name)}, args),`, ` ${name}Item: (_parent: unknown, args: { ${key}: string }) => contentItem(store, ${q(name)}, ${q(key)}, args.${key}),`);
|
|
2163
|
+
}
|
|
2164
|
+
for (const shared of ["ContentWhere", "ContentOrder", "ContentDirection", "Query"]) {
|
|
2165
|
+
if (objects.has(shared))
|
|
2166
|
+
throw new DiagnosticError8("HAMUR_E5341", `content.api.graphql: the generated type "${shared}" has the name of a collection's type; rename the collection`);
|
|
2167
|
+
}
|
|
2168
|
+
const schema = [
|
|
2169
|
+
...[...objects].map(([name, { fields }]) => [`type ${name} {`, ...fields, "}", ""].join(`
|
|
2170
|
+
`)),
|
|
2171
|
+
"type Query {",
|
|
2172
|
+
...roots,
|
|
2173
|
+
"}",
|
|
2174
|
+
"",
|
|
2175
|
+
"input ContentWhere {",
|
|
2176
|
+
" field: String!",
|
|
2177
|
+
' operator: String! = "="',
|
|
2178
|
+
" value: String",
|
|
2179
|
+
"}",
|
|
2180
|
+
"",
|
|
2181
|
+
"input ContentOrder {",
|
|
2182
|
+
" field: String!",
|
|
2183
|
+
" direction: ContentDirection = ASC",
|
|
2184
|
+
"}",
|
|
2185
|
+
"",
|
|
2186
|
+
"enum ContentDirection {",
|
|
2187
|
+
" ASC",
|
|
2188
|
+
" DESC",
|
|
2189
|
+
"}",
|
|
2190
|
+
""
|
|
2191
|
+
].join(`
|
|
2192
|
+
`);
|
|
2193
|
+
const jsonTypes = [...objects].filter(([, { json }]) => json.length).map(([name, { json }]) => ` ${name}: { ${json.map((field) => `${field}: jsonField(${q(field)})`).join(", ")} },`);
|
|
2194
|
+
const resolvers = [
|
|
2195
|
+
`import store from "#hamur/content/store";`,
|
|
2196
|
+
`import { contentItem, contentList, jsonField, type ListArgs } from ${q(runtime)};`,
|
|
2197
|
+
"",
|
|
2198
|
+
"export default {",
|
|
2199
|
+
" Query: {",
|
|
2200
|
+
...query,
|
|
2201
|
+
" },",
|
|
2202
|
+
...jsonTypes,
|
|
2203
|
+
"};",
|
|
2204
|
+
""
|
|
2205
|
+
].join(`
|
|
2206
|
+
`);
|
|
2207
|
+
return { schema, resolvers };
|
|
2208
|
+
}
|
|
2209
|
+
function setupGraphQL(config, hamur) {
|
|
2210
|
+
const generated = contentGraphQL(config, createResolver6(new URL("../../src/build/graphql.ts", import.meta.url).href).resolve("../server/graphql.ts"));
|
|
2211
|
+
if (!generated)
|
|
2212
|
+
return;
|
|
2213
|
+
addTemplate5({ filename: "content/content.graphql", write: true, getContents: () => generated.schema });
|
|
2214
|
+
addTemplate5({ filename: "content/graphql/resolvers.ts", write: true, getContents: () => generated.resolvers });
|
|
2215
|
+
addServerGraphQL({
|
|
2216
|
+
schema: join8(hamur.options.buildDir, "content/content.graphql"),
|
|
2217
|
+
resolvers: join8(hamur.options.buildDir, "content/graphql/resolvers.ts")
|
|
2218
|
+
});
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
// packages/content/src/build/raw.ts
|
|
2222
|
+
import { DiagnosticError as DiagnosticError9, emitPublicAsset } from "hamur/kit";
|
|
2223
|
+
|
|
2224
|
+
// packages/content/src/runtime/raw-path.ts
|
|
2225
|
+
var rawPath = (path) => path === "/" ? "/index.md" : `${path.replace(/\/$/, "")}.md`;
|
|
2226
|
+
|
|
2227
|
+
// packages/content/src/build/raw.ts
|
|
2228
|
+
var isRecord4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2229
|
+
var shown3 = (value) => JSON.stringify(value) ?? String(value);
|
|
2230
|
+
function resolveRaw(value) {
|
|
2231
|
+
if (value === undefined)
|
|
2232
|
+
return false;
|
|
2233
|
+
if (typeof value !== "boolean" && value !== "body")
|
|
2234
|
+
throw new DiagnosticError9("HAMUR_E5327", `content.raw must be a boolean or "body" (got ${shown3(value)})`);
|
|
2235
|
+
return value;
|
|
2236
|
+
}
|
|
2237
|
+
function resolveLlms(value, config, siteUrl) {
|
|
2238
|
+
if (value === undefined || value === false)
|
|
2239
|
+
return;
|
|
2240
|
+
const shape = "content.llms must be { title: string, description?: string, sections: Array<{ title, collection, where? }> }";
|
|
2241
|
+
if (!isRecord4(value) || typeof value.title !== "string" || value.title === "")
|
|
2242
|
+
throw new DiagnosticError9("HAMUR_E5328", shape);
|
|
2243
|
+
if (value.description !== undefined && typeof value.description !== "string")
|
|
2244
|
+
throw new DiagnosticError9("HAMUR_E5328", shape);
|
|
2245
|
+
if (!Array.isArray(value.sections))
|
|
2246
|
+
throw new DiagnosticError9("HAMUR_E5328", shape);
|
|
2247
|
+
if (siteUrl === undefined)
|
|
2248
|
+
throw new DiagnosticError9("HAMUR_E5329", "content.llms needs site.url for absolute page URLs");
|
|
2249
|
+
value.sections.forEach((section, index) => {
|
|
2250
|
+
const at = `content.llms.sections[${index}]`;
|
|
2251
|
+
if (!isRecord4(section) || typeof section.title !== "string" || typeof section.collection !== "string")
|
|
2252
|
+
throw new DiagnosticError9("HAMUR_E5328", `${at} must be { title: string, collection: string, where? }`);
|
|
2253
|
+
const collection = Object.hasOwn(config.collections, section.collection) ? config.collections[section.collection] : undefined;
|
|
2254
|
+
if (!collection)
|
|
2255
|
+
throw new DiagnosticError9("HAMUR_E5330", `${at}.collection ${shown3(section.collection)} is not a collection of content.config.ts`);
|
|
2256
|
+
if (collection.type !== "page")
|
|
2257
|
+
throw new DiagnosticError9("HAMUR_E5331", `${at}.collection ${shown3(section.collection)} is not a page collection`);
|
|
2258
|
+
const where = section.where;
|
|
2259
|
+
if (where !== undefined && !(isRecord4(where) || Array.isArray(where) && where.every(isRecord4)))
|
|
2260
|
+
throw new DiagnosticError9("HAMUR_E5328", `${at}.where must be a condition { field, operator, value? } or an array of them`);
|
|
2261
|
+
});
|
|
2262
|
+
return value;
|
|
2263
|
+
}
|
|
2264
|
+
var clausesOf = (where) => where === undefined ? [] : (Array.isArray(where) ? where : [where]).map((condition) => ({ join: "AND", ...condition }));
|
|
2265
|
+
function llmsSections(llms, config, index) {
|
|
2266
|
+
return llms.sections.map((section) => {
|
|
2267
|
+
const where = clausesOf(section.where);
|
|
2268
|
+
const found = runQuery(section.collection, config.collections[section.collection], index[section.collection] ?? [], where.length ? { where } : {});
|
|
2269
|
+
return { title: section.title, entries: found };
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
var oneLine = (text) => text.replace(/\s+/g, " ").trim();
|
|
2273
|
+
var linkText = (text) => oneLine(text).replace(/[[\]]/g, "\\$&");
|
|
2274
|
+
var pageUrl = (origin, baseURL, path) => `${origin}${baseURL.replace(/\/$/, "")}${path}`;
|
|
2275
|
+
function llmsText(llms, sections, origin, baseURL) {
|
|
2276
|
+
const lines = [`# ${oneLine(llms.title)}`, ""];
|
|
2277
|
+
if (llms.description)
|
|
2278
|
+
lines.push(`> ${oneLine(llms.description)}`, "");
|
|
2279
|
+
for (const section of sections) {
|
|
2280
|
+
lines.push(`## ${oneLine(section.title)}`, "");
|
|
2281
|
+
for (const entry of section.entries) {
|
|
2282
|
+
const description = entry.description ? `: ${oneLine(entry.description)}` : "";
|
|
2283
|
+
lines.push(`- [${linkText(entry.title ?? entry.path)}](${pageUrl(origin, baseURL, entry.path)})${description}`);
|
|
2284
|
+
}
|
|
2285
|
+
lines.push("");
|
|
2286
|
+
}
|
|
2287
|
+
return `${lines.join(`
|
|
2288
|
+
`).trimEnd()}
|
|
2289
|
+
`;
|
|
2290
|
+
}
|
|
2291
|
+
var llmsFullText = (sources) => `${sources.join(`
|
|
2292
|
+
|
|
2293
|
+
---
|
|
2294
|
+
|
|
2295
|
+
`)}
|
|
2296
|
+
`;
|
|
2297
|
+
function setupRaw(options, config, index, hamur) {
|
|
2298
|
+
const raw = resolveRaw(options.raw);
|
|
2299
|
+
const llms = resolveLlms(options.llms, config, hamur.options.site.url);
|
|
2300
|
+
if (!raw && !llms)
|
|
2301
|
+
return;
|
|
2302
|
+
hamur.hooks.hook("build:before", async () => {
|
|
2303
|
+
const entries = await index.read();
|
|
2304
|
+
const text = async (entry) => {
|
|
2305
|
+
if (raw === "body")
|
|
2306
|
+
return index.body(entry.collection, entry.id);
|
|
2307
|
+
const file = index.file(entry.collection, entry.id);
|
|
2308
|
+
return file === undefined ? undefined : Bun.file(file).text();
|
|
2309
|
+
};
|
|
2310
|
+
if (raw) {
|
|
2311
|
+
for (const [name, collection] of Object.entries(config.collections)) {
|
|
2312
|
+
if (collection.type !== "page")
|
|
2313
|
+
continue;
|
|
2314
|
+
for (const entry of entries[name] ?? []) {
|
|
2315
|
+
const source = await text(entry);
|
|
2316
|
+
if (source !== undefined)
|
|
2317
|
+
emitPublicAsset(rawPath(entry.path), source);
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
if (llms) {
|
|
2322
|
+
const sections = llmsSections(llms, config, entries);
|
|
2323
|
+
emitPublicAsset("/llms.txt", llmsText(llms, sections, hamur.options.site.url, hamur.options.app.baseURL));
|
|
2324
|
+
const seen = new Set;
|
|
2325
|
+
const sources = [];
|
|
2326
|
+
for (const entry of sections.flatMap((section) => section.entries)) {
|
|
2327
|
+
const key = `${entry.collection}\x00${entry.id}`;
|
|
2328
|
+
if (seen.has(key))
|
|
2329
|
+
continue;
|
|
2330
|
+
seen.add(key);
|
|
2331
|
+
const source = await text(entry);
|
|
2332
|
+
if (source !== undefined)
|
|
2333
|
+
sources.push(source.trimEnd());
|
|
2334
|
+
}
|
|
2335
|
+
emitPublicAsset("/llms-full.txt", llmsFullText(sources));
|
|
2336
|
+
}
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
// packages/content/src/build/query.ts
|
|
2341
|
+
var SERVER = "@hamur/content/server";
|
|
2342
|
+
function resolveClientQuery(value, preset) {
|
|
2343
|
+
if (value === undefined)
|
|
2344
|
+
return preset === "static" ? "local" : "api";
|
|
2345
|
+
if (value !== "api" && value !== "local")
|
|
2346
|
+
throw new DiagnosticError10("HAMUR_E5332", `content.clientQuery must be "api" or "local" (got ${JSON.stringify(value)})`);
|
|
2347
|
+
if (value === "api" && preset === "static")
|
|
2348
|
+
throw new DiagnosticError10("HAMUR_E5333", 'content.clientQuery "api" needs a server; the static preset uses "local"');
|
|
2349
|
+
return value;
|
|
2350
|
+
}
|
|
2351
|
+
function clientModule(config, mode, devLoad, raw) {
|
|
2352
|
+
const collections = Object.entries(config.collections).map(([name, { type, expose = true, order }]) => {
|
|
2353
|
+
const meta = JSON.stringify({ type, expose, ...order ? { order } : {} });
|
|
2354
|
+
const loader = devLoad ? `devLoad(${JSON.stringify(`${DEV_ROUTE}/chunks/${name}.json`)})` : `() => import(${JSON.stringify(`#hamur/content/chunks/${name}.json`)})`;
|
|
2355
|
+
const load = mode === "local" && expose ? `, load: ${loader} }` : "";
|
|
2356
|
+
return ` ${JSON.stringify(name)}: ${load ? `${meta.slice(0, -1)}${load}` : meta},`;
|
|
2357
|
+
});
|
|
2358
|
+
const imports = devLoad && mode === "local" ? [`import { devLoad } from ${JSON.stringify(devLoad)};`, ""] : [];
|
|
2359
|
+
return [
|
|
2360
|
+
...imports,
|
|
2361
|
+
`export default {`,
|
|
2362
|
+
` mode: ${JSON.stringify(mode)},`,
|
|
2363
|
+
...raw === undefined ? [] : [` raw: ${JSON.stringify(raw)},`],
|
|
2364
|
+
" collections: {",
|
|
2365
|
+
...collections,
|
|
2366
|
+
" },",
|
|
2367
|
+
"};",
|
|
2368
|
+
""
|
|
2369
|
+
].join(`
|
|
2370
|
+
`);
|
|
2371
|
+
}
|
|
2372
|
+
function doorOf(preset, dev) {
|
|
2373
|
+
if (dev)
|
|
2374
|
+
return preset === "static" ? "../server/door-dev-static.ts" : "../server/door-dev.ts";
|
|
2375
|
+
return preset === "static" ? "../server/door-static.ts" : "../server/door.ts";
|
|
2376
|
+
}
|
|
2377
|
+
function setupQuery(options, config, hamur) {
|
|
2378
|
+
const { preset } = hamur.options;
|
|
2379
|
+
const mode = resolveClientQuery(options.clientQuery, preset);
|
|
2380
|
+
const client = hamur.options.build.importProtection.client ??= {};
|
|
2381
|
+
(client.deny ??= []).push(SERVER);
|
|
2382
|
+
const api = resolveApi(options.api, preset, hamur.options.server.graphql !== false);
|
|
2383
|
+
if (api.graphql)
|
|
2384
|
+
setupGraphQL(config, hamur);
|
|
2385
|
+
if (api.rest)
|
|
2386
|
+
setupRest(config, hamur);
|
|
2387
|
+
else
|
|
2388
|
+
addServer2(createResolver7(new URL("../../src/build/query.ts", import.meta.url).href).resolve(doorOf(preset, hamur.options.dev)));
|
|
2389
|
+
const devLoad = hamur.options.dev ? createResolver7(new URL("../../src/build/query.ts", import.meta.url).href).resolve("../runtime/dev-client.ts") : undefined;
|
|
2390
|
+
addAppPlugin3({ src: createResolver7(new URL("../../src/build/query.ts", import.meta.url).href).resolve("../runtime/page-plugin.ts"), mode: "all" });
|
|
2391
|
+
addTemplate6({
|
|
2392
|
+
filename: "content/client",
|
|
2393
|
+
getContents: () => clientModule(config, mode, devLoad, resolveRaw(options.raw) ? hamur.options.app.baseURL : undefined)
|
|
2394
|
+
});
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
// packages/content/src/build/types.ts
|
|
2398
|
+
import { posix as posix2, relative as relative5, sep as sep6 } from "node:path";
|
|
2399
|
+
import { addTemplate as addTemplate7, addTypeTemplate, diagnostic, useLogger as useLogger3 } from "hamur/kit";
|
|
2400
|
+
var SCHEMAS = "content/schemas";
|
|
2401
|
+
var posixOf = (path) => path.split(sep6).join("/");
|
|
2402
|
+
function contentTypes(config, configImport, live = []) {
|
|
2403
|
+
const entries = Object.keys(config.collections).map((name) => ` ${name}: CollectionItemOf<(typeof config)["collections"][${JSON.stringify(name)}]>;`);
|
|
2404
|
+
const liveEntries = live.length ? [
|
|
2405
|
+
" interface HamurLiveCollections {",
|
|
2406
|
+
...live.map((name) => ` ${name}: (typeof config)["collections"][${JSON.stringify(name)}];`),
|
|
2407
|
+
" }"
|
|
2408
|
+
] : [];
|
|
2409
|
+
return [
|
|
2410
|
+
`import type { CollectionItemOf } from "@hamur/content";`,
|
|
2411
|
+
`import type config from ${JSON.stringify(configImport)};`,
|
|
2412
|
+
"",
|
|
2413
|
+
`declare module "@hamur/content" {`,
|
|
2414
|
+
" interface HamurContentCollections {",
|
|
2415
|
+
...entries,
|
|
2416
|
+
" }",
|
|
2417
|
+
...liveEntries,
|
|
2418
|
+
"}",
|
|
2419
|
+
""
|
|
2420
|
+
].join(`
|
|
2421
|
+
`);
|
|
2422
|
+
}
|
|
2423
|
+
function sourceGlobs(source) {
|
|
2424
|
+
if (source === undefined)
|
|
2425
|
+
return [];
|
|
2426
|
+
return (Array.isArray(source) ? source : [source]).flatMap((entry) => {
|
|
2427
|
+
if (typeof entry !== "string" && entry.repository !== undefined)
|
|
2428
|
+
return [];
|
|
2429
|
+
const { include, cwd = "" } = typeof entry === "string" ? { include: entry } : entry;
|
|
2430
|
+
return [posix2.join("content", cwd, include)];
|
|
2431
|
+
});
|
|
2432
|
+
}
|
|
2433
|
+
function schemaFiles(config, buildFolder, warn) {
|
|
2434
|
+
const files = {};
|
|
2435
|
+
const map = {};
|
|
2436
|
+
for (const [name, collection] of Object.entries(config.collections)) {
|
|
2437
|
+
if (collection.schema === undefined)
|
|
2438
|
+
continue;
|
|
2439
|
+
const converter = collection.schema["~standard"]?.jsonSchema;
|
|
2440
|
+
if (typeof converter?.input !== "function") {
|
|
2441
|
+
warn(diagnostic("HAMUR_W5369", `${name}: schema has no JSON Schema; no editor schema written`));
|
|
2442
|
+
continue;
|
|
2443
|
+
}
|
|
2444
|
+
let schema;
|
|
2445
|
+
try {
|
|
2446
|
+
schema = converter.input({ target: "draft-2020-12" });
|
|
2447
|
+
} catch (error) {
|
|
2448
|
+
warn(diagnostic("HAMUR_W5369", `${name}: schema has no JSON Schema (${error instanceof Error ? error.message : String(error)}); no editor schema written`));
|
|
2449
|
+
continue;
|
|
2450
|
+
}
|
|
2451
|
+
files[name] = `${JSON.stringify(schema, null, 2)}
|
|
2452
|
+
`;
|
|
2453
|
+
const globs = sourceGlobs(collection.source);
|
|
2454
|
+
if (globs.length)
|
|
2455
|
+
map[posix2.join(buildFolder, SCHEMAS, `${name}.schema.json`)] = globs;
|
|
2456
|
+
}
|
|
2457
|
+
return { files, map };
|
|
2458
|
+
}
|
|
2459
|
+
function setupTypes(config, hamur) {
|
|
2460
|
+
const { rootDir, buildDir } = hamur.options;
|
|
2461
|
+
const configImport = posixOf(relative5(`${buildDir}${sep6}types`, `${rootDir}${sep6}content.config.ts`));
|
|
2462
|
+
addTypeTemplate({
|
|
2463
|
+
filename: "content.d.ts",
|
|
2464
|
+
getContents: () => contentTypes(config, configImport.startsWith(".") ? configImport : `./${configImport}`, Object.keys(config.live))
|
|
2465
|
+
});
|
|
2466
|
+
const logger = useLogger3("content");
|
|
2467
|
+
const { files, map } = schemaFiles(config, posixOf(relative5(rootDir, buildDir)), (message) => logger.warn(message));
|
|
2468
|
+
for (const [name, text] of Object.entries(files))
|
|
2469
|
+
addTemplate7({ filename: `${SCHEMAS}/${name}.schema.json`, write: true, getContents: () => text });
|
|
2470
|
+
if (Object.keys(files).length)
|
|
2471
|
+
addTemplate7({
|
|
2472
|
+
filename: "content/schemas.json",
|
|
2473
|
+
write: true,
|
|
2474
|
+
getContents: () => `${JSON.stringify(map, null, 2)}
|
|
2475
|
+
`
|
|
2476
|
+
});
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
// packages/content/src/config.ts
|
|
2480
|
+
import { existsSync as existsSync3, statSync as statSync2 } from "node:fs";
|
|
2481
|
+
import { join as join9 } from "node:path";
|
|
2482
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
2483
|
+
|
|
2484
|
+
// packages/content/src/component.ts
|
|
2485
|
+
import { existsSync as existsSync2, statSync } from "node:fs";
|
|
2486
|
+
import { isAbsolute as isAbsolute2, resolve as resolve4 } from "node:path";
|
|
2487
|
+
import { pathToFileURL } from "node:url";
|
|
2488
|
+
import { DiagnosticError as DiagnosticError11 } from "hamur/kit";
|
|
2489
|
+
var COMPONENT = Symbol.for("hamur.content.fromComponent");
|
|
2490
|
+
var SCRIPTS = [".ts", ".tsx", ".js", ".jsx", ".mjs"];
|
|
2491
|
+
var SFC = [".vue", ".svelte"];
|
|
2492
|
+
function fromComponent(path) {
|
|
2493
|
+
if (typeof path !== "string" || path === "")
|
|
2494
|
+
throw new DiagnosticError11("HAMUR_E5318", "fromComponent: the component path must be a non-empty string");
|
|
2495
|
+
return {
|
|
2496
|
+
[COMPONENT]: path,
|
|
2497
|
+
"~standard": {
|
|
2498
|
+
version: 1,
|
|
2499
|
+
vendor: "hamur",
|
|
2500
|
+
validate() {
|
|
2501
|
+
throw new DiagnosticError11("HAMUR_E5319", `fromComponent: ${path} is read only through content.config.ts`);
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
};
|
|
2505
|
+
}
|
|
2506
|
+
var componentPathOf = (schema) => schema !== null && typeof schema === "object" ? schema[COMPONENT] : undefined;
|
|
2507
|
+
function fileAt(candidate, rootDir) {
|
|
2508
|
+
if (candidate.startsWith("#")) {
|
|
2509
|
+
try {
|
|
2510
|
+
return Bun.resolveSync(candidate, rootDir);
|
|
2511
|
+
} catch {
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
return existsSync2(candidate) && statSync(candidate).isFile() ? candidate : undefined;
|
|
2516
|
+
}
|
|
2517
|
+
function fileOf(path, rootDir) {
|
|
2518
|
+
const base = path.startsWith("#") || isAbsolute2(path) ? path : resolve4(rootDir, path);
|
|
2519
|
+
const sfc = SFC.find((extension) => base.endsWith(extension));
|
|
2520
|
+
if (sfc) {
|
|
2521
|
+
const props = fileAt(`${base.slice(0, -sfc.length)}.props.ts`, rootDir);
|
|
2522
|
+
if (!props)
|
|
2523
|
+
throw new DiagnosticError11("HAMUR_E5320", `fromComponent: ${path} is not importable at build; export propsSchema from ${path.slice(0, -sfc.length)}.props.ts`);
|
|
2524
|
+
return props;
|
|
2525
|
+
}
|
|
2526
|
+
const candidates = [
|
|
2527
|
+
`${base}.props.ts`,
|
|
2528
|
+
`${base}.props.js`,
|
|
2529
|
+
base,
|
|
2530
|
+
...SCRIPTS.map((extension) => `${base}${extension}`)
|
|
2531
|
+
];
|
|
2532
|
+
for (const candidate of candidates) {
|
|
2533
|
+
const found = fileAt(candidate, rootDir);
|
|
2534
|
+
if (found)
|
|
2535
|
+
return found;
|
|
2536
|
+
}
|
|
2537
|
+
const sibling = SFC.find((extension) => fileAt(`${base}${extension}`, rootDir));
|
|
2538
|
+
if (sibling)
|
|
2539
|
+
throw new DiagnosticError11("HAMUR_E5320", `fromComponent: ${path}${sibling} is not importable at build; export propsSchema from ${path}.props.ts`);
|
|
2540
|
+
throw new DiagnosticError11("HAMUR_E5321", `fromComponent: ${path} not found`);
|
|
2541
|
+
}
|
|
2542
|
+
async function loadPropsSchema(path, rootDir) {
|
|
2543
|
+
const file = fileOf(path, rootDir);
|
|
2544
|
+
const loaded = await import(`${pathToFileURL(file).href}?t=${statSync(file).mtimeMs}`);
|
|
2545
|
+
const schema = loaded.propsSchema;
|
|
2546
|
+
if (typeof schema?.["~standard"]?.validate !== "function")
|
|
2547
|
+
throw new DiagnosticError11("HAMUR_E5322", `fromComponent: ${path} exports no propsSchema`);
|
|
2548
|
+
return schema;
|
|
2549
|
+
}
|
|
2550
|
+
|
|
2551
|
+
// packages/content/src/config.ts
|
|
2552
|
+
import { DiagnosticError as DiagnosticError12 } from "hamur/kit";
|
|
2553
|
+
|
|
2554
|
+
// packages/content/src/define.ts
|
|
2555
|
+
function defineContentConfig(config) {
|
|
2556
|
+
return config;
|
|
2557
|
+
}
|
|
2558
|
+
function defineTransformer(transformer) {
|
|
2559
|
+
return transformer;
|
|
2560
|
+
}
|
|
2561
|
+
function defineCollection(collection) {
|
|
2562
|
+
return collection;
|
|
2563
|
+
}
|
|
2564
|
+
function defineLiveCollection(collection) {
|
|
2565
|
+
return { ...collection, live: true };
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
// packages/content/src/config.ts
|
|
2569
|
+
var NAME2 = /^[a-z][A-Za-z0-9]*$/;
|
|
2570
|
+
async function setupConfig(rootDir) {
|
|
2571
|
+
const file = join9(rootDir, "content.config.ts");
|
|
2572
|
+
if (!existsSync3(file))
|
|
2573
|
+
throw new DiagnosticError12("HAMUR_E5301", `@hamur/content needs content.config.ts in ${rootDir}`);
|
|
2574
|
+
const loaded = await import(`${pathToFileURL2(file).href}?t=${statSync2(file).mtimeMs}`);
|
|
2575
|
+
const config = checkConfig(loaded.default);
|
|
2576
|
+
for (const collection of Object.values(config.collections)) {
|
|
2577
|
+
const component = componentPathOf(collection.schema);
|
|
2578
|
+
if (component !== undefined)
|
|
2579
|
+
collection.schema = await loadPropsSchema(component, rootDir);
|
|
2580
|
+
}
|
|
2581
|
+
return config;
|
|
2582
|
+
}
|
|
2583
|
+
function checkConfig(value) {
|
|
2584
|
+
const collections = value?.collections;
|
|
2585
|
+
if (collections === null || typeof collections !== "object" || Array.isArray(collections)) {
|
|
2586
|
+
throw new DiagnosticError12("HAMUR_E5302", "content.config.ts must default-export defineContentConfig({ collections: { … } })");
|
|
2587
|
+
}
|
|
2588
|
+
const built = {};
|
|
2589
|
+
const live = {};
|
|
2590
|
+
for (const [name, raw] of Object.entries(collections)) {
|
|
2591
|
+
if (!NAME2.test(name))
|
|
2592
|
+
throw new DiagnosticError12("HAMUR_E5303", `content.config.ts: collection name "${name}" must match [a-z][A-Za-z0-9]*`);
|
|
2593
|
+
if (raw?.live === true) {
|
|
2594
|
+
live[name] = checkLive(name, raw);
|
|
2595
|
+
continue;
|
|
2596
|
+
}
|
|
2597
|
+
const collection = raw ?? {};
|
|
2598
|
+
const source = collection.source !== undefined;
|
|
2599
|
+
const loader = collection.loader !== undefined;
|
|
2600
|
+
if (source && loader)
|
|
2601
|
+
throw new DiagnosticError12("HAMUR_E5304", `content.config.ts: collection "${name}" sets source and loader; set one`);
|
|
2602
|
+
if (!source && !loader)
|
|
2603
|
+
throw new DiagnosticError12("HAMUR_E5305", `content.config.ts: collection "${name}" sets neither source nor loader`);
|
|
2604
|
+
if (loader) {
|
|
2605
|
+
const { name: loaderName, load } = collection.loader;
|
|
2606
|
+
if (typeof loaderName !== "string" || loaderName === "" || typeof load !== "function") {
|
|
2607
|
+
throw new DiagnosticError12("HAMUR_E5306", `content.config.ts: collection "${name}": loader must be { name: string, load(ctx) }`);
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
if (collection.type !== "page" && collection.type !== "data") {
|
|
2611
|
+
throw new DiagnosticError12("HAMUR_E5307", `content.config.ts: collection "${name}": type must be "page" or "data" (got ${JSON.stringify(collection.type)})`);
|
|
2612
|
+
}
|
|
2613
|
+
built[name] = collection;
|
|
2614
|
+
}
|
|
2615
|
+
checkTransformers(value.transformers);
|
|
2616
|
+
return { ...value, collections: built, live };
|
|
2617
|
+
}
|
|
2618
|
+
function checkLive(name, collection) {
|
|
2619
|
+
const loader = collection.loader ?? {};
|
|
2620
|
+
if (typeof loader.loadCollection !== "function" || typeof loader.loadEntry !== "function" || loader.name !== undefined && typeof loader.name !== "string") {
|
|
2621
|
+
throw new DiagnosticError12("HAMUR_E5308", `content.config.ts: live collection "${name}": loader must be { name?: string, loadCollection(filter), loadEntry(filter) }`);
|
|
2622
|
+
}
|
|
2623
|
+
if (componentPathOf(collection.schema) !== undefined)
|
|
2624
|
+
throw new DiagnosticError12("HAMUR_E5309", `content.config.ts: live collection "${name}": fromComponent is build-time only; pass the component's propsSchema itself`);
|
|
2625
|
+
const schema = collection.schema;
|
|
2626
|
+
if (schema !== undefined && typeof schema?.["~standard"]?.validate !== "function")
|
|
2627
|
+
throw new DiagnosticError12("HAMUR_E5310", `content.config.ts: live collection "${name}": schema must be a Standard Schema`);
|
|
2628
|
+
return collection;
|
|
2629
|
+
}
|
|
2630
|
+
var BUILT_IN = new Set(["md", "yml", "yaml", "json", "json5", "toml", "csv"]);
|
|
2631
|
+
function checkTransformers(value) {
|
|
2632
|
+
if (value === undefined)
|
|
2633
|
+
return;
|
|
2634
|
+
if (!Array.isArray(value))
|
|
2635
|
+
throw new DiagnosticError12("HAMUR_E5311", "content.config.ts: transformers must be an array of defineTransformer({ … })");
|
|
2636
|
+
const names = new Set;
|
|
2637
|
+
const extensions = new Map;
|
|
2638
|
+
for (const [index, raw] of value.entries()) {
|
|
2639
|
+
const item = raw ?? {};
|
|
2640
|
+
const at = `content.config.ts: transformers[${index}]`;
|
|
2641
|
+
if (typeof item.name !== "string" || item.name === "")
|
|
2642
|
+
throw new DiagnosticError12("HAMUR_E5312", `${at}: name must be a non-empty string`);
|
|
2643
|
+
if (names.has(item.name))
|
|
2644
|
+
throw new DiagnosticError12("HAMUR_E5313", `${at}: name "${item.name}" is listed twice`);
|
|
2645
|
+
names.add(item.name);
|
|
2646
|
+
if (!Array.isArray(item.extensions) || item.extensions.some((extension) => typeof extension !== "string" || !/^\.[A-Za-z0-9]+$/.test(extension))) {
|
|
2647
|
+
throw new DiagnosticError12("HAMUR_E5314", `${at} "${item.name}": extensions must be an array of extensions with a dot, like [".adoc"]`);
|
|
2648
|
+
}
|
|
2649
|
+
for (const key of ["parse", "transform"]) {
|
|
2650
|
+
if (item[key] !== undefined && typeof item[key] !== "function")
|
|
2651
|
+
throw new DiagnosticError12("HAMUR_E5315", `${at} "${item.name}": ${key} must be a function`);
|
|
2652
|
+
}
|
|
2653
|
+
if (item.parse === undefined)
|
|
2654
|
+
continue;
|
|
2655
|
+
for (const extension of item.extensions) {
|
|
2656
|
+
const bare = extension.slice(1);
|
|
2657
|
+
if (BUILT_IN.has(bare))
|
|
2658
|
+
throw new DiagnosticError12("HAMUR_E5316", `${at} "${item.name}": ${extension} is a built-in content format`);
|
|
2659
|
+
const other = extensions.get(bare);
|
|
2660
|
+
if (other !== undefined)
|
|
2661
|
+
throw new DiagnosticError12("HAMUR_E5317", `${at} "${item.name}": ${extension} is already parsed by transformer "${other}"`);
|
|
2662
|
+
extensions.set(bare, item.name);
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
|
|
2667
|
+
// packages/content/src/module.ts
|
|
2668
|
+
var module_default = defineModule({
|
|
2669
|
+
meta: { name: "content", configKey: "content", hooks: ["content:file:beforeParse", "content:file:afterParse"] },
|
|
2670
|
+
async setup(options, hamur) {
|
|
2671
|
+
const config = await setupConfig(hamur.options.rootDir);
|
|
2672
|
+
const index = setupIndex(hamur, config, options);
|
|
2673
|
+
setupQuery(options, config, hamur);
|
|
2674
|
+
setupPrerender(options, config, index.read, hamur);
|
|
2675
|
+
setupRaw(options, config, index, hamur);
|
|
2676
|
+
const search = setupSearch(options, config, index.read, hamur.options.dev);
|
|
2677
|
+
setupDev(hamur, config, index, search);
|
|
2678
|
+
setupLive(config, hamur);
|
|
2679
|
+
setupTypes(config, hamur);
|
|
2680
|
+
}
|
|
2681
|
+
});
|
|
2682
|
+
// packages/content/src/loaders/file.ts
|
|
2683
|
+
import { relative as relative6, resolve as resolve5, sep as sep7 } from "node:path";
|
|
2684
|
+
var isObject4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2685
|
+
function file(path) {
|
|
2686
|
+
return {
|
|
2687
|
+
name: "file",
|
|
2688
|
+
async load(ctx) {
|
|
2689
|
+
const absolute = resolve5(ctx.rootDir, "content", path);
|
|
2690
|
+
const shown = relative6(ctx.rootDir, absolute).split(sep7).join("/");
|
|
2691
|
+
const dot = absolute.lastIndexOf(".");
|
|
2692
|
+
const extension = absolute.slice(dot + 1);
|
|
2693
|
+
if (!DATA_FORMATS.includes(extension))
|
|
2694
|
+
throw new ContentError("HAMUR_E5355", `${shown}: .${extension} is not a data file (${DATA_FORMATS.join(", ")})`);
|
|
2695
|
+
const source = Bun.file(absolute);
|
|
2696
|
+
if (!await source.exists())
|
|
2697
|
+
throw new ContentError("HAMUR_E5358", `${shown}: file not found`);
|
|
2698
|
+
const value = parseDataText(await ctx.beforeParse({
|
|
2699
|
+
id: path.slice(0, -extension.length - 1),
|
|
2700
|
+
path: shown,
|
|
2701
|
+
extension,
|
|
2702
|
+
body: await source.text()
|
|
2703
|
+
}), extension, shown, ctx.csv);
|
|
2704
|
+
if (value === null || typeof value !== "object")
|
|
2705
|
+
throw new ContentError("HAMUR_E5357", `${shown}: expected an array or an object of entries`);
|
|
2706
|
+
const items = Array.isArray(value) ? value.map((item, index) => [isObject4(item) && typeof item.id === "string" ? item.id : String(index), item]) : Object.entries(value);
|
|
2707
|
+
for (const [id, item] of items) {
|
|
2708
|
+
if (!isObject4(item))
|
|
2709
|
+
throw new ContentError("HAMUR_E5350", `${shown}: ${id}: a data entry is an object`);
|
|
2710
|
+
const data = Array.isArray(value) ? Object.fromEntries(Object.entries(item).filter(([key]) => key !== "id")) : item;
|
|
2711
|
+
ctx.store.set({
|
|
2712
|
+
id,
|
|
2713
|
+
stem: id,
|
|
2714
|
+
file: absolute,
|
|
2715
|
+
data,
|
|
2716
|
+
digest: ctx.digest(`${shown}\x00${id}\x00${JSON.stringify(item)}`)
|
|
2717
|
+
});
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
};
|
|
2721
|
+
}
|
|
2722
|
+
export {
|
|
2723
|
+
module_default as default,
|
|
2724
|
+
defineCollection,
|
|
2725
|
+
defineContentConfig,
|
|
2726
|
+
defineLiveCollection,
|
|
2727
|
+
defineTransformer,
|
|
2728
|
+
file,
|
|
2729
|
+
fromComponent,
|
|
2730
|
+
glob,
|
|
2731
|
+
image
|
|
2732
|
+
};
|