dommief 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2695 -0
- package/dist/index.d.ts +326 -0
- package/dist/index.js +1383 -0
- package/dist/theme-api.d.ts +108 -0
- package/dist/theme-api.js +268 -0
- package/dist/types-zwMRCGy9.d.ts +81 -0
- package/package.json +70 -4
- package/src/client/Api.tsx +73 -0
- package/src/client/AppRoutes.tsx +51 -0
- package/src/client/ClientOnly.tsx +22 -0
- package/src/client/Demo.tsx +70 -0
- package/src/client/DemoRegistry.ts +11 -0
- package/src/client/NotFound.tsx +13 -0
- package/src/client/Tabs.tsx +70 -0
- package/src/client/entry-client.tsx +84 -0
- package/src/client/entry-server.tsx +52 -0
- package/src/client/index.tsx +4 -0
- package/src/client/search-client.ts +91 -0
- package/src/client/search-core.ts +151 -0
- package/src/client/search-worker.ts +45 -0
- package/src/client/virtual.d.ts +16 -0
- package/src/routesModule.ts +61 -0
- package/src/search-config.ts +45 -0
- package/src/theme-api.tsx +242 -0
- package/src/types.ts +71 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1383 @@
|
|
|
1
|
+
// src/config.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import path from "path";
|
|
5
|
+
import { loadConfigFromFile } from "vite";
|
|
6
|
+
|
|
7
|
+
// src/markdown/errors.ts
|
|
8
|
+
var DommiefError = class extends Error {
|
|
9
|
+
file;
|
|
10
|
+
line;
|
|
11
|
+
col;
|
|
12
|
+
code;
|
|
13
|
+
layout;
|
|
14
|
+
constructor(message, opts = {}) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "DommiefError";
|
|
17
|
+
this.file = opts.file ?? "";
|
|
18
|
+
this.line = opts.line;
|
|
19
|
+
this.col = opts.col;
|
|
20
|
+
this.code = opts.code;
|
|
21
|
+
this.layout = opts.layout;
|
|
22
|
+
}
|
|
23
|
+
format() {
|
|
24
|
+
const loc = this.line != null ? `:${this.line}${this.col != null ? ":" + this.col : ""}` : "";
|
|
25
|
+
const head = this.file ? `${this.file}${loc}` : loc.slice(1) || "";
|
|
26
|
+
return head ? `${head}: ${this.message}` : this.message;
|
|
27
|
+
}
|
|
28
|
+
toString() {
|
|
29
|
+
return this.format();
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
function formatError(err) {
|
|
33
|
+
if (err instanceof DommiefError) return err.format();
|
|
34
|
+
if (err instanceof Error) return err.message;
|
|
35
|
+
return String(err);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/plugins.ts
|
|
39
|
+
var Hook = class {
|
|
40
|
+
name;
|
|
41
|
+
constructor(name = "") {
|
|
42
|
+
this.name = name;
|
|
43
|
+
}
|
|
44
|
+
taps = [];
|
|
45
|
+
tap(name, fn) {
|
|
46
|
+
this.taps.push({ name, fn });
|
|
47
|
+
}
|
|
48
|
+
call(arg) {
|
|
49
|
+
let value = arg;
|
|
50
|
+
for (const t of this.taps) {
|
|
51
|
+
const r = t.fn(value);
|
|
52
|
+
if (r !== void 0) value = r;
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
async callAsync(arg) {
|
|
57
|
+
let value = arg;
|
|
58
|
+
for (const t of this.taps) {
|
|
59
|
+
const r = await t.fn(value);
|
|
60
|
+
if (r !== void 0) value = r;
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
var PluginHookHost = class {
|
|
66
|
+
modifyConfig = new Hook("modifyConfig");
|
|
67
|
+
modifyRoutes = new Hook("modifyRoutes");
|
|
68
|
+
addRemarkPlugins = new Hook("addRemarkPlugins");
|
|
69
|
+
addRehypePlugins = new Hook("addRehypePlugins");
|
|
70
|
+
addHtmlHeadTags = new Hook("addHtmlHeadTags");
|
|
71
|
+
onBuildEnd = new Hook("onBuildEnd");
|
|
72
|
+
applyModifyConfig(config) {
|
|
73
|
+
return this.modifyConfig.call(config);
|
|
74
|
+
}
|
|
75
|
+
applyModifyRoutes(routes) {
|
|
76
|
+
const r = this.modifyRoutes.call(routes);
|
|
77
|
+
return r ?? routes;
|
|
78
|
+
}
|
|
79
|
+
collectRemarkPlugins() {
|
|
80
|
+
const out = [];
|
|
81
|
+
for (const t of this.addRemarkPlugins.taps) {
|
|
82
|
+
const r = t.fn();
|
|
83
|
+
if (Array.isArray(r)) out.push(...r);
|
|
84
|
+
else if (r !== void 0 && r !== null) out.push(r);
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
collectRehypePlugins() {
|
|
89
|
+
const out = [];
|
|
90
|
+
for (const t of this.addRehypePlugins.taps) {
|
|
91
|
+
const r = t.fn();
|
|
92
|
+
if (Array.isArray(r)) out.push(...r);
|
|
93
|
+
else if (r !== void 0 && r !== null) out.push(r);
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
collectHtmlHeadTags() {
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const t of this.addHtmlHeadTags.taps) {
|
|
100
|
+
const r = t.fn();
|
|
101
|
+
if (Array.isArray(r)) out.push(...r.map(String));
|
|
102
|
+
else if (r !== void 0 && r !== null) out.push(String(r));
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
async runBuildEnd(ctx) {
|
|
107
|
+
for (const t of this.onBuildEnd.taps) {
|
|
108
|
+
await t.fn(ctx);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
function assertSync(result, name) {
|
|
113
|
+
if (result && typeof result.then === "function") {
|
|
114
|
+
throw new DommiefError(`plugin "${name}": setup ph\u1EA3i \u0111\u1ED3ng b\u1ED9 \u2014 hook tap sau \`await\` s\u1EBD kh\xF4ng bao gi\u1EDD ch\u1EA1y`, { code: "plugin_setup_async" });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function registerPlugin(host, plugin) {
|
|
118
|
+
if (!plugin) return;
|
|
119
|
+
if (typeof plugin === "function") {
|
|
120
|
+
assertSync(plugin(host), plugin.name || "plugin");
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const p = plugin;
|
|
124
|
+
const name = p.name ?? "plugin";
|
|
125
|
+
if (typeof p.setup === "function") assertSync(p.setup(host), name);
|
|
126
|
+
if (typeof p.modifyConfig === "function") host.modifyConfig.tap(name, p.modifyConfig);
|
|
127
|
+
if (typeof p.modifyRoutes === "function") host.modifyRoutes.tap(name, p.modifyRoutes);
|
|
128
|
+
if (typeof p.addRemarkPlugins === "function") host.addRemarkPlugins.tap(name, p.addRemarkPlugins);
|
|
129
|
+
if (typeof p.addRehypePlugins === "function") host.addRehypePlugins.tap(name, p.addRehypePlugins);
|
|
130
|
+
if (typeof p.addHtmlHeadTags === "function") host.addHtmlHeadTags.tap(name, p.addHtmlHeadTags);
|
|
131
|
+
if (typeof p.onBuildEnd === "function") host.onBuildEnd.tap(name, p.onBuildEnd);
|
|
132
|
+
}
|
|
133
|
+
function createPluginHost(plugins = []) {
|
|
134
|
+
const host = new PluginHookHost();
|
|
135
|
+
for (const p of plugins ?? []) registerPlugin(host, p);
|
|
136
|
+
return host;
|
|
137
|
+
}
|
|
138
|
+
function definePlugin(plugin) {
|
|
139
|
+
return plugin;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/config.ts
|
|
143
|
+
var LocaleInputSchema = z.object({
|
|
144
|
+
id: z.string().min(1).refine(
|
|
145
|
+
(s) => {
|
|
146
|
+
try {
|
|
147
|
+
Intl.getCanonicalLocales(s);
|
|
148
|
+
return true;
|
|
149
|
+
} catch {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
'ph\u1EA3i l\xE0 m\xE3 locale BCP 47 (vd "en-US", "vi-VN"; kh\xF4ng d\xF9ng "_")'
|
|
154
|
+
),
|
|
155
|
+
name: z.string().optional(),
|
|
156
|
+
base: z.string().startsWith("/", 'ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "/"').optional(),
|
|
157
|
+
suffix: z.string().optional()
|
|
158
|
+
});
|
|
159
|
+
var ConfigSchema = z.object({
|
|
160
|
+
title: z.string().default("Dommief"),
|
|
161
|
+
description: z.string().optional(),
|
|
162
|
+
base: z.string().startsWith("/", 'ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "/" (URL tuy\u1EC7t \u0111\u1ED1i kh\xF4ng \u0111\u01B0\u1EE3c h\u1ED7 tr\u1EE3)').default("/"),
|
|
163
|
+
outDir: z.string().default("dist"),
|
|
164
|
+
srcDir: z.string().default("docs"),
|
|
165
|
+
/** Khi `library`, tự động quét `src/` để hỗ trợ atom routing cho component library. */
|
|
166
|
+
preset: z.enum(["docs", "library"]).default("docs"),
|
|
167
|
+
docDirs: z.array(z.union([z.string(), z.object({ dir: z.string() })])).optional(),
|
|
168
|
+
forceKebabCase: z.boolean().default(true),
|
|
169
|
+
locales: z.array(LocaleInputSchema).default([{ id: "en-US", name: "English" }]),
|
|
170
|
+
themeConfig: z.record(z.string(), z.unknown()).default({}),
|
|
171
|
+
theme: z.string().default("dommief-theme-default"),
|
|
172
|
+
ssg: z.object({
|
|
173
|
+
concurrency: z.number().int().positive().default(4),
|
|
174
|
+
/** Route không prerender nhưng VẪN phát shell (REVIEW §1 #17). Pattern: path chính xác hoặc `/prefix/*`. */
|
|
175
|
+
exclude: z.array(z.string()).default([]),
|
|
176
|
+
/** Route không phát file nào. */
|
|
177
|
+
noEmit: z.array(z.string()).default([])
|
|
178
|
+
}).default({ concurrency: 4, exclude: [], noEmit: [] }),
|
|
179
|
+
/** Cache transform md theo content-hash (DM-406). `--no-cache` tắt. */
|
|
180
|
+
cache: z.boolean().default(true),
|
|
181
|
+
/** Kiểm link nội bộ chết lúc build (DM-410). `--no-link-check` tắt. */
|
|
182
|
+
linkCheck: z.boolean().default(true),
|
|
183
|
+
dev: z.object({ port: z.number().int().positive().default(5173) }).default({ port: 5173 }),
|
|
184
|
+
/** sitemap.xml + robots.txt (DM-708, CONFIG §1.5). `false` (mặc định) = không phát; khai
|
|
185
|
+
* object thì `hostname` BẮT BUỘC (không đoán domain). */
|
|
186
|
+
sitemap: z.union([z.literal(false), z.object({ hostname: z.string().url(), exclude: z.array(z.string()).default([]) })]).default(false),
|
|
187
|
+
/** Ghi `robots.txt` trỏ tới sitemap. Mặc định: true nếu có sitemap, ngược lại false. */
|
|
188
|
+
robots: z.boolean().optional(),
|
|
189
|
+
/** Shiki lúc build + số dòng (CONFIG §1, DM-706). `shiki: false` = code thô. */
|
|
190
|
+
markdown: z.object({
|
|
191
|
+
shiki: z.union([z.literal(false), z.object({ themes: z.object({ light: z.string(), dark: z.string() }) })]).default({ themes: { light: "github-light", dark: "github-dark" } }),
|
|
192
|
+
lineNumbers: z.boolean().default(false)
|
|
193
|
+
}).default({ shiki: { themes: { light: "github-light", dark: "github-dark" } }, lineNumbers: false }),
|
|
194
|
+
/** Search index (DM-801). */
|
|
195
|
+
search: z.object({ enabled: z.boolean().default(true) }).default({ enabled: true }),
|
|
196
|
+
plugins: z.array(z.any()).default([])
|
|
197
|
+
}).strict();
|
|
198
|
+
function defineConfig(config) {
|
|
199
|
+
return config;
|
|
200
|
+
}
|
|
201
|
+
var CONFIG_FILES = ["dommief.config.ts", "dommief.config.mts", "dommief.config.js", "dommief.config.mjs"];
|
|
202
|
+
async function loadConfigFile(opts) {
|
|
203
|
+
let file;
|
|
204
|
+
if (opts.configPath) {
|
|
205
|
+
file = path.resolve(opts.cwd, opts.configPath);
|
|
206
|
+
if (!fs.existsSync(file)) throw new DommiefError(`kh\xF4ng t\xECm th\u1EA5y file config: ${file}`, { code: "config_not_found", file });
|
|
207
|
+
} else {
|
|
208
|
+
file = CONFIG_FILES.map((f) => path.join(opts.cwd, f)).find((p) => fs.existsSync(p));
|
|
209
|
+
if (!file) return null;
|
|
210
|
+
}
|
|
211
|
+
const loaded = await loadConfigFromFile({ command: "serve", mode: "development" }, file, opts.cwd, "silent");
|
|
212
|
+
if (!loaded) return null;
|
|
213
|
+
return { path: loaded.path, config: loaded.config };
|
|
214
|
+
}
|
|
215
|
+
function normalizeBase(base) {
|
|
216
|
+
return base.endsWith("/") ? base : base + "/";
|
|
217
|
+
}
|
|
218
|
+
function resolveConfig(userConfig, opts) {
|
|
219
|
+
const fileLabel = opts.configFile ? path.basename(opts.configFile) : "dommief.config";
|
|
220
|
+
const sources = {};
|
|
221
|
+
for (const k of Object.keys(userConfig ?? {})) sources[k] = fileLabel;
|
|
222
|
+
let merged = { ...userConfig };
|
|
223
|
+
const layer = (key, value, source) => {
|
|
224
|
+
if (value === void 0 || value === "") return;
|
|
225
|
+
merged[key] = value;
|
|
226
|
+
sources[key] = source;
|
|
227
|
+
};
|
|
228
|
+
if (opts.cli?.cache === false) {
|
|
229
|
+
merged.cache = false;
|
|
230
|
+
sources.cache = "--no-cache";
|
|
231
|
+
}
|
|
232
|
+
if (opts.cli?.linkCheck === false) {
|
|
233
|
+
merged.linkCheck = false;
|
|
234
|
+
sources.linkCheck = "--no-link-check";
|
|
235
|
+
}
|
|
236
|
+
layer("base", opts.cli?.base, "--base");
|
|
237
|
+
layer("outDir", opts.cli?.outDir, "--out-dir");
|
|
238
|
+
layer("base", opts.env?.DOMMIEF_BASE, "DOMMIEF_BASE");
|
|
239
|
+
layer("outDir", opts.env?.DOMMIEF_OUT_DIR, "DOMMIEF_OUT_DIR");
|
|
240
|
+
const fail = (keyPath, message) => {
|
|
241
|
+
const top = String(keyPath[0] ?? "");
|
|
242
|
+
const value = keyPath.reduce((v, k) => v?.[k], merged);
|
|
243
|
+
const shown = value === void 0 ? "(thi\u1EBFu)" : JSON.stringify(value);
|
|
244
|
+
throw new DommiefError(
|
|
245
|
+
`c\u1EA5u h\xECnh kh\xF4ng h\u1EE3p l\u1EC7
|
|
246
|
+
${formatKeyPath(keyPath)} ${shown}
|
|
247
|
+
${message}
|
|
248
|
+
(ngu\u1ED3n: ${sources[top] ?? "default"})`,
|
|
249
|
+
{ code: "config_invalid" }
|
|
250
|
+
);
|
|
251
|
+
};
|
|
252
|
+
const pluginHost = createPluginHost(Array.isArray(merged.plugins) ? merged.plugins : []);
|
|
253
|
+
const modified = pluginHost.applyModifyConfig(merged);
|
|
254
|
+
if (modified && typeof modified === "object") merged = { ...merged, ...modified };
|
|
255
|
+
const parsed = ConfigSchema.safeParse(merged);
|
|
256
|
+
if (!parsed.success) {
|
|
257
|
+
const issue = parsed.error.issues[0];
|
|
258
|
+
if (issue.code === "unrecognized_keys") {
|
|
259
|
+
const key = issue.keys[0];
|
|
260
|
+
const hint = suggestKey(key);
|
|
261
|
+
fail([key], `key kh\xF4ng \u0111\u01B0\u1EE3c h\u1ED7 tr\u1EE3${hint ? `; b\u1EA1n mu\u1ED1n n\xF3i "${hint}"?` : ""}`);
|
|
262
|
+
}
|
|
263
|
+
fail(issue.path, issue.message);
|
|
264
|
+
}
|
|
265
|
+
const c = parsed.data;
|
|
266
|
+
const locales = resolveLocales(c.locales, fail);
|
|
267
|
+
const config = {
|
|
268
|
+
root: opts.cwd,
|
|
269
|
+
title: c.title,
|
|
270
|
+
base: normalizeBase(c.base),
|
|
271
|
+
outDir: c.outDir,
|
|
272
|
+
srcDir: c.srcDir,
|
|
273
|
+
docDirs: (c.docDirs ?? [c.srcDir]).map((d) => typeof d === "string" ? { dir: d } : { dir: d.dir }),
|
|
274
|
+
forceKebabCase: c.forceKebabCase,
|
|
275
|
+
locales,
|
|
276
|
+
themeConfig: c.themeConfig,
|
|
277
|
+
theme: c.theme,
|
|
278
|
+
ssg: c.ssg,
|
|
279
|
+
cache: c.cache,
|
|
280
|
+
linkCheck: c.linkCheck,
|
|
281
|
+
dev: c.dev,
|
|
282
|
+
sitemap: c.sitemap,
|
|
283
|
+
robots: c.robots ?? c.sitemap !== false,
|
|
284
|
+
search: c.search,
|
|
285
|
+
markdown: c.markdown,
|
|
286
|
+
plugins: c.plugins ?? []
|
|
287
|
+
};
|
|
288
|
+
if (c.description !== void 0) config.description = c.description;
|
|
289
|
+
return config;
|
|
290
|
+
}
|
|
291
|
+
async function loadConfig(root, cli) {
|
|
292
|
+
const file = await loadConfigFile({ cwd: root });
|
|
293
|
+
return resolveConfig(file?.config ?? {}, { cwd: root, env: process.env, configFile: file?.path, ...cli ? { cli } : {} });
|
|
294
|
+
}
|
|
295
|
+
function resolveLocales(input, fail) {
|
|
296
|
+
const suffixMode = input[0]?.suffix !== void 0;
|
|
297
|
+
const seen = /* @__PURE__ */ new Set();
|
|
298
|
+
return input.map((l, i) => {
|
|
299
|
+
if (seen.has(l.id)) fail(["locales", i, "id"], `id "${l.id}" b\u1ECB tr\xF9ng`);
|
|
300
|
+
seen.add(l.id);
|
|
301
|
+
const name = l.name ?? l.id;
|
|
302
|
+
if (suffixMode) {
|
|
303
|
+
if (l.base !== void 0 || l.suffix === void 0) {
|
|
304
|
+
fail(["locales", i], 'kh\xF4ng tr\u1ED9n "base" v\xE0 "suffix": locales[0] d\xF9ng ch\u1EBF \u0111\u1ED9 suffix n\xEAn m\u1ECDi locale ph\u1EA3i khai "suffix" v\xE0 kh\xF4ng khai "base"');
|
|
305
|
+
}
|
|
306
|
+
return { id: l.id, name, base: "/", suffix: l.suffix };
|
|
307
|
+
}
|
|
308
|
+
if (l.suffix !== void 0) {
|
|
309
|
+
fail(["locales", i], 'kh\xF4ng tr\u1ED9n "base" v\xE0 "suffix": locales[0] d\xF9ng ch\u1EBF \u0111\u1ED9 base n\xEAn kh\xF4ng locale n\xE0o \u0111\u01B0\u1EE3c khai "suffix"');
|
|
310
|
+
}
|
|
311
|
+
const base = normalizeBase(l.base ?? (i === 0 ? "/" : `/${l.id}/`));
|
|
312
|
+
if (i > 0 && base === "/") {
|
|
313
|
+
fail(["locales", i, "base"], `ch\u1EC9 locale \u0111\u1EA7u ti\xEAn \u0111\u01B0\u1EE3c d\xF9ng base "/". \u0110\u01B0a "${l.id}" l\xEAn \u0111\u1EA7u m\u1EA3ng ho\u1EB7c \u0111\u1ED5i base.`);
|
|
314
|
+
}
|
|
315
|
+
return { id: l.id, name, base, suffix: "" };
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
function formatKeyPath(keyPath) {
|
|
319
|
+
return keyPath.map((k, i) => typeof k === "number" ? `[${k}]` : i === 0 ? k : `.${k}`).join("");
|
|
320
|
+
}
|
|
321
|
+
function suggestKey(key) {
|
|
322
|
+
let best;
|
|
323
|
+
let bestDist = 3;
|
|
324
|
+
for (const known of Object.keys(ConfigSchema.shape)) {
|
|
325
|
+
const d = editDistance(key, known);
|
|
326
|
+
if (d < bestDist) [best, bestDist] = [known, d];
|
|
327
|
+
}
|
|
328
|
+
return best;
|
|
329
|
+
}
|
|
330
|
+
function editDistance(a, b) {
|
|
331
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
332
|
+
for (let i = 1; i <= a.length; i++) {
|
|
333
|
+
const cur = [i];
|
|
334
|
+
for (let j = 1; j <= b.length; j++) {
|
|
335
|
+
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
336
|
+
}
|
|
337
|
+
prev = cur;
|
|
338
|
+
}
|
|
339
|
+
return prev[b.length];
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// src/routes.ts
|
|
343
|
+
import fs2 from "fs";
|
|
344
|
+
import path2 from "path";
|
|
345
|
+
import { createHash } from "crypto";
|
|
346
|
+
|
|
347
|
+
// src/utils/path.ts
|
|
348
|
+
function winPath(p) {
|
|
349
|
+
if (/^\\\\\?\\/.test(p)) return p;
|
|
350
|
+
return p.replace(/\\/g, "/");
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// src/routes.ts
|
|
354
|
+
var INDEX_NAMES = /* @__PURE__ */ new Set(["index", "README"]);
|
|
355
|
+
var SEGMENT_OK = /^[\p{L}\p{N}_-]+$/u;
|
|
356
|
+
function listMarkdownFiles(dir) {
|
|
357
|
+
const out = [];
|
|
358
|
+
const walk = (d) => {
|
|
359
|
+
for (const e of fs2.readdirSync(d, { withFileTypes: true })) {
|
|
360
|
+
if (e.name.startsWith(".") || e.name.startsWith("_") || e.name === "node_modules") continue;
|
|
361
|
+
const p = path2.join(d, e.name);
|
|
362
|
+
if (e.isDirectory()) walk(p);
|
|
363
|
+
else if (e.isFile() && e.name.endsWith(".md")) out.push(winPath(p));
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
walk(dir);
|
|
367
|
+
return out.sort();
|
|
368
|
+
}
|
|
369
|
+
function scanRoutes({ cwd, config }) {
|
|
370
|
+
const routes = [];
|
|
371
|
+
const warnings = [];
|
|
372
|
+
const seen = /* @__PURE__ */ new Set();
|
|
373
|
+
const docDirs = config.preset === "library" && !(config.docDirs || []).some((d) => d.dir === "src") ? [...config.docDirs || [], { dir: "src" }] : config.docDirs || [];
|
|
374
|
+
for (const { dir } of docDirs) {
|
|
375
|
+
const absDir = path2.resolve(cwd, dir);
|
|
376
|
+
if (!fs2.existsSync(absDir)) {
|
|
377
|
+
warnings.push(`doc_dir_missing: docDirs "${dir}" kh\xF4ng t\u1ED3n t\u1EA1i (${winPath(absDir)})`);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
for (const file of listMarkdownFiles(absDir)) {
|
|
381
|
+
if (seen.has(file)) {
|
|
382
|
+
warnings.push(`route_duplicate_file: ${file} n\u1EB1m trong nhi\u1EC1u docDirs, gi\u1EEF docDir khai tr\u01B0\u1EDBc`);
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
seen.add(file);
|
|
386
|
+
const id = path2.posix.relative(winPath(absDir), file).slice(0, -".md".length);
|
|
387
|
+
routes.push({ id, path: `/${id}`, file });
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return { routes, warnings };
|
|
391
|
+
}
|
|
392
|
+
function kebab(segment, localeId2) {
|
|
393
|
+
return segment.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLocaleLowerCase(localeId2);
|
|
394
|
+
}
|
|
395
|
+
function normalizeRoutes(raw, { cwd, config }) {
|
|
396
|
+
const warnings = [];
|
|
397
|
+
const errors = [];
|
|
398
|
+
const show = (file) => path2.posix.relative(winPath(cwd), file) || file;
|
|
399
|
+
const defaultLocale = config.locales[0];
|
|
400
|
+
const items = [];
|
|
401
|
+
for (const r of raw) {
|
|
402
|
+
const segs = r.id.split("/");
|
|
403
|
+
let name = segs.pop();
|
|
404
|
+
const dir = segs.join("/");
|
|
405
|
+
let locale = defaultLocale;
|
|
406
|
+
let suffixStripped = false;
|
|
407
|
+
const hit = config.locales.find((l) => name.endsWith("." + l.id));
|
|
408
|
+
if (hit) {
|
|
409
|
+
locale = hit;
|
|
410
|
+
suffixStripped = true;
|
|
411
|
+
name = name.slice(0, -(hit.id.length + 1));
|
|
412
|
+
} else {
|
|
413
|
+
const last = name.slice(name.lastIndexOf(".") + 1);
|
|
414
|
+
const typo = name.includes(".") && config.locales.find((l) => l.id.toLowerCase() === last.toLowerCase());
|
|
415
|
+
if (typo) warnings.push(`locale_unknown_suffix: ${show(r.file)} c\xF3 h\u1EADu t\u1ED1 ".${last}" g\u1EA7n gi\u1ED1ng locale "${typo.id}" nh\u01B0ng kh\xF4ng kh\u1EDBp; x\u1EED l\xFD nh\u01B0 file th\u01B0\u1EDDng`);
|
|
416
|
+
}
|
|
417
|
+
const indexName = INDEX_NAMES.has(name) ? name : void 0;
|
|
418
|
+
const parts = indexName ? segs : [...segs, name];
|
|
419
|
+
const split = parts.flatMap((s) => s.split("."));
|
|
420
|
+
const dotted = split.length !== parts.length;
|
|
421
|
+
const routePath = split.filter(Boolean).map((s) => config.forceKebabCase ? kebab(s, locale.id) : s).join("/").normalize("NFC");
|
|
422
|
+
const bad = routePath.split("/").find((s) => s && !SEGMENT_OK.test(s));
|
|
423
|
+
if (bad) {
|
|
424
|
+
const ch = [...bad].find((c) => !SEGMENT_OK.test(c));
|
|
425
|
+
errors.push({
|
|
426
|
+
code: "route_invalid_path",
|
|
427
|
+
message: `dommief: routes: k\xFD t\u1EF1 kh\xF4ng h\u1EE3p l\u1EC7 "${ch}" trong \u0111\u01B0\u1EDDng d\u1EABn c\u1EE7a file
|
|
428
|
+
${show(r.file)}
|
|
429
|
+
segment ch\u1EC9 \u0111\u01B0\u1EE3c ch\u1EE9a ch\u1EEF, s\u1ED1, "-" v\xE0 "_". \u0110\u1ED5i t\xEAn file.`
|
|
430
|
+
});
|
|
431
|
+
} else if (/[^\x00-\x7F]/.test(routePath)) {
|
|
432
|
+
warnings.push(`route_non_ascii: ${show(r.file)} \u2192 "/${routePath}" c\xF3 k\xFD t\u1EF1 ngo\xE0i ASCII; NFC/NFD v\xE0 hosting t\u0129nh c\xF3 th\u1EC3 l\u1EC7ch, n\xEAn \u0111\u1EB7t t\xEAn file ASCII`);
|
|
433
|
+
}
|
|
434
|
+
const joined = locale.suffix ? `/${routePath}${locale.suffix}` : `${locale.base}${routePath}`;
|
|
435
|
+
const p = joined.replace(/\/{2,}/g, "/").replace(/(.)\/$/, "$1");
|
|
436
|
+
items.push({
|
|
437
|
+
// locale mặc định ⇒ không có key (JSON round-trip giữ nguyên object)
|
|
438
|
+
route: { id: r.id, path: p, file: r.file, ...locale === defaultLocale ? {} : { locale: locale.id } },
|
|
439
|
+
routePath,
|
|
440
|
+
locale,
|
|
441
|
+
suffixStripped,
|
|
442
|
+
...indexName === void 0 ? {} : { indexName },
|
|
443
|
+
dir,
|
|
444
|
+
dotted
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
const byId = /* @__PURE__ */ new Map();
|
|
448
|
+
for (const it of items) byId.set(it.route.id, [...byId.get(it.route.id) ?? [], it]);
|
|
449
|
+
for (const [id, group] of byId) {
|
|
450
|
+
if (group.length < 2) continue;
|
|
451
|
+
errors.push({
|
|
452
|
+
code: "route_duplicate",
|
|
453
|
+
message: `dommief: routes: tr\xF9ng route id "${id}" (${group.length} file)
|
|
454
|
+
${group.map((g) => ` ${show(g.route.file)}`).join("\n")}
|
|
455
|
+
id l\xE0 \u0111\u01B0\u1EDDng d\u1EABn t\u01B0\u01A1ng \u0111\u1ED1i trong docDir. \u0110\u1ED5i t\xEAn file ho\u1EB7c t\xE1ch docDir th\xE0nh 2 site.`
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
459
|
+
for (const it of items) {
|
|
460
|
+
if ((byId.get(it.route.id)?.length ?? 0) > 1) continue;
|
|
461
|
+
const key = it.route.path.toLowerCase();
|
|
462
|
+
byPath.set(key, [...byPath.get(key) ?? [], it]);
|
|
463
|
+
}
|
|
464
|
+
for (const group of byPath.values()) {
|
|
465
|
+
if (group.length < 2) continue;
|
|
466
|
+
errors.push({
|
|
467
|
+
code: "route_duplicate",
|
|
468
|
+
message: `dommief: routes: tr\xF9ng \u0111\u01B0\u1EDDng d\u1EABn "${group[0].route.path}" (${group.length} file)
|
|
469
|
+
${group.map((g) => ` ${show(g.route.file)}`).join("\n")}
|
|
470
|
+
nguy\xEAn nh\xE2n: ${duplicateCause(group[0], group[1])}`
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
if (errors.length) {
|
|
474
|
+
throw new DommiefError(errors.map((e) => e.message).join("\n\n"), { code: errors[0].code });
|
|
475
|
+
}
|
|
476
|
+
return { routes: items.map((it) => it.route), warnings };
|
|
477
|
+
}
|
|
478
|
+
function duplicateCause(a, b) {
|
|
479
|
+
const base = (n) => path2.posix.basename(n.route.file);
|
|
480
|
+
const stripped = a.suffixStripped ? a : b.suffixStripped ? b : void 0;
|
|
481
|
+
if (stripped && a.locale === b.locale) {
|
|
482
|
+
const other = stripped === a ? b : a;
|
|
483
|
+
const owner = stripped.route.locale ? `locale "${stripped.locale.id}"` : "locale m\u1EB7c \u0111\u1ECBnh";
|
|
484
|
+
return `"${base(stripped)}" thu\u1ED9c ${owner} n\xEAn tr\xF9ng "${base(other)}"`;
|
|
485
|
+
}
|
|
486
|
+
const dirName = (n) => n.dir || "/";
|
|
487
|
+
if (a.indexName && b.indexName) return `c\u1EA3 "${a.indexName}.md" v\xE0 "${b.indexName}.md" \u0111\u1EC1u g\u1ED9p v\xE0o "${dirName(a)}"`;
|
|
488
|
+
const idx = a.indexName ? a : b.indexName ? b : void 0;
|
|
489
|
+
if (idx) return `"${idx.indexName}.md" g\u1ED9p v\xE0o th\u01B0 m\u1EE5c "${dirName(idx)}"`;
|
|
490
|
+
if (a.route.id.toLowerCase() === b.route.id.toLowerCase()) return "tr\xF9ng sau khi kebab (macOS/Windows kh\xF4ng ph\xE2n bi\u1EC7t hoa th\u01B0\u1EDDng)";
|
|
491
|
+
if (a.dotted || b.dotted) return '"." trong t\xEAn file \u0111\u01B0\u1EE3c \u0111\u1ED5i th\xE0nh "/"';
|
|
492
|
+
return "kebab-case l\xE0m hai file tr\xF9ng nhau";
|
|
493
|
+
}
|
|
494
|
+
function routeConfigHash(config) {
|
|
495
|
+
const { srcDir, docDirs, locales, forceKebabCase, preset } = config;
|
|
496
|
+
const json = JSON.stringify({
|
|
497
|
+
srcDir,
|
|
498
|
+
docDirs: docDirs.map((d) => d.dir),
|
|
499
|
+
locales: locales.map(({ id, name, base, suffix }) => ({ id, name, base, suffix })),
|
|
500
|
+
forceKebabCase,
|
|
501
|
+
preset: preset ?? "docs"
|
|
502
|
+
});
|
|
503
|
+
return createHash("sha256").update(json).digest("hex").slice(0, 8);
|
|
504
|
+
}
|
|
505
|
+
function buildRouteTable({ cwd, config, hooks, plugins }) {
|
|
506
|
+
const host = hooks ?? (plugins ? createPluginHost(plugins) : config?.plugins ? createPluginHost(config.plugins) : void 0);
|
|
507
|
+
const scan = scanRoutes({ cwd, config });
|
|
508
|
+
const norm = normalizeRoutes(scan.routes, { cwd, config });
|
|
509
|
+
const cmp = (x, y) => x < y ? -1 : x > y ? 1 : 0;
|
|
510
|
+
let routes = norm.routes;
|
|
511
|
+
if (host) routes = host.applyModifyRoutes(routes);
|
|
512
|
+
routes = routes.sort((a, b) => cmp(a.path, b.path) || cmp(a.id, b.id));
|
|
513
|
+
const table = {
|
|
514
|
+
warnings: [...scan.warnings, ...norm.warnings],
|
|
515
|
+
routes,
|
|
516
|
+
byId: {},
|
|
517
|
+
byPath: {},
|
|
518
|
+
byFile: {},
|
|
519
|
+
configHash: routeConfigHash(config)
|
|
520
|
+
};
|
|
521
|
+
for (const r of routes) {
|
|
522
|
+
table.byId[r.id] = r;
|
|
523
|
+
table.byPath[r.path] = r;
|
|
524
|
+
table.byFile[r.file] = r;
|
|
525
|
+
}
|
|
526
|
+
return table;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// src/markdown/remark-meta.ts
|
|
530
|
+
import yaml from "yaml";
|
|
531
|
+
import { unified } from "unified";
|
|
532
|
+
import remarkParse from "remark-parse";
|
|
533
|
+
import remarkFrontmatter from "remark-frontmatter";
|
|
534
|
+
import Slugger from "github-slugger";
|
|
535
|
+
import { visit } from "unist-util-visit";
|
|
536
|
+
function textOf(node) {
|
|
537
|
+
let out = "";
|
|
538
|
+
if (node.type === "text") out += node.value || "";
|
|
539
|
+
if (node.children) for (const c of node.children) out += textOf(c);
|
|
540
|
+
return out;
|
|
541
|
+
}
|
|
542
|
+
function parseFrontmatterYaml(raw, opts = {}) {
|
|
543
|
+
const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
544
|
+
if (!m || m[1] === void 0) return {};
|
|
545
|
+
try {
|
|
546
|
+
return yaml.parse(m[1]) ?? {};
|
|
547
|
+
} catch (e) {
|
|
548
|
+
opts.onWarn?.(`frontmatter_invalid_yaml: ${opts.file ?? ""}: ${e.message}`);
|
|
549
|
+
return {};
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
function remarkMeta(options = {}) {
|
|
553
|
+
return (tree, file) => {
|
|
554
|
+
const filename = options.filename ?? file?.path ?? file?.history?.[0] ?? "";
|
|
555
|
+
file.data = file.data || {};
|
|
556
|
+
let frontmatter = {};
|
|
557
|
+
if (tree.children?.[0]?.type === "yaml") {
|
|
558
|
+
frontmatter = parseFrontmatterYaml("---\n" + tree.children[0].value + "\n---", { file: filename });
|
|
559
|
+
tree.children.shift();
|
|
560
|
+
}
|
|
561
|
+
if (frontmatter.title == null) {
|
|
562
|
+
let firstH1 = null;
|
|
563
|
+
visit(tree, "heading", (node) => {
|
|
564
|
+
if (node.depth === 1 && firstH1 === null) firstH1 = textOf(node).trim();
|
|
565
|
+
});
|
|
566
|
+
if (firstH1) frontmatter.title = firstH1;
|
|
567
|
+
}
|
|
568
|
+
file.data.frontmatter = frontmatter;
|
|
569
|
+
file.data.filename = filename;
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// src/siteFeatures.ts
|
|
574
|
+
function fmFor(map, route) {
|
|
575
|
+
if (!map) return {};
|
|
576
|
+
return map[route.id] ?? map[route.file] ?? {};
|
|
577
|
+
}
|
|
578
|
+
function localeId(route, locales) {
|
|
579
|
+
if (route.locale) return route.locale;
|
|
580
|
+
return locales[0]?.id ?? "default";
|
|
581
|
+
}
|
|
582
|
+
function titleOf(route, fm) {
|
|
583
|
+
const t = fm.title ?? fm.navTitle ?? fm.sidebarTitle;
|
|
584
|
+
if (typeof t === "string" && t.trim()) return t;
|
|
585
|
+
return route.id.split("/").pop() ?? route.id;
|
|
586
|
+
}
|
|
587
|
+
function orderOf(fm) {
|
|
588
|
+
const v = fm.order ?? fm.navOrder ?? fm.sidebarOrder;
|
|
589
|
+
return typeof v === "number" ? v : Number(v ?? 0) || 0;
|
|
590
|
+
}
|
|
591
|
+
function buildNav(routes, frontmatter, locales = []) {
|
|
592
|
+
const out = {};
|
|
593
|
+
const groups = /* @__PURE__ */ new Map();
|
|
594
|
+
for (const route of routes) {
|
|
595
|
+
const lid = localeId(route, locales);
|
|
596
|
+
const fm = fmFor(frontmatter, route);
|
|
597
|
+
const navFlag = fm.nav;
|
|
598
|
+
if (navFlag === false) continue;
|
|
599
|
+
const item = {
|
|
600
|
+
title: titleOf(route, fm),
|
|
601
|
+
link: route.path,
|
|
602
|
+
order: orderOf(fm),
|
|
603
|
+
activePath: route.path
|
|
604
|
+
};
|
|
605
|
+
const arr = groups.get(lid) ?? [];
|
|
606
|
+
arr.push(item);
|
|
607
|
+
groups.set(lid, arr);
|
|
608
|
+
}
|
|
609
|
+
for (const [lid, items] of groups) {
|
|
610
|
+
out[lid] = items.sort((a, b) => a.order - b.order || String(a.link).localeCompare(String(b.link)));
|
|
611
|
+
}
|
|
612
|
+
for (const l of locales) {
|
|
613
|
+
if (!out[l.id]) out[l.id] = [];
|
|
614
|
+
}
|
|
615
|
+
return out;
|
|
616
|
+
}
|
|
617
|
+
function buildSidebar(routes, frontmatter, locales = []) {
|
|
618
|
+
const out = {};
|
|
619
|
+
const byLocale = /* @__PURE__ */ new Map();
|
|
620
|
+
for (const route of routes) {
|
|
621
|
+
const lid = localeId(route, locales);
|
|
622
|
+
const fm = fmFor(frontmatter, route);
|
|
623
|
+
const groupTitle = typeof fm.group === "string" && fm.group.trim() ? fm.group : route.id.split("/")[0] ?? "General";
|
|
624
|
+
const item = {
|
|
625
|
+
title: titleOf(route, fm),
|
|
626
|
+
link: route.path,
|
|
627
|
+
order: orderOf(fm),
|
|
628
|
+
...Object.keys(fm).length ? { frontmatter: fm } : {}
|
|
629
|
+
};
|
|
630
|
+
let groups = byLocale.get(lid);
|
|
631
|
+
if (!groups) {
|
|
632
|
+
groups = /* @__PURE__ */ new Map();
|
|
633
|
+
byLocale.set(lid, groups);
|
|
634
|
+
}
|
|
635
|
+
let g = groups.get(groupTitle);
|
|
636
|
+
if (!g) {
|
|
637
|
+
g = { title: groupTitle, order: orderOf(fm), children: [] };
|
|
638
|
+
groups.set(groupTitle, g);
|
|
639
|
+
}
|
|
640
|
+
g.children.push(item);
|
|
641
|
+
g.order = Math.min(g.order, orderOf(fm));
|
|
642
|
+
}
|
|
643
|
+
for (const [lid, groups] of byLocale) {
|
|
644
|
+
const arr = [...groups.values()].map((g) => ({
|
|
645
|
+
...g,
|
|
646
|
+
children: g.children.sort((a, b) => a.order - b.order || a.link.localeCompare(b.link))
|
|
647
|
+
}));
|
|
648
|
+
out[lid] = arr.sort((a, b) => a.order - b.order || String(a.title).localeCompare(String(b.title)));
|
|
649
|
+
}
|
|
650
|
+
for (const l of locales) {
|
|
651
|
+
if (!out[l.id]) out[l.id] = [];
|
|
652
|
+
}
|
|
653
|
+
return out;
|
|
654
|
+
}
|
|
655
|
+
function paginate(routes, currentPath) {
|
|
656
|
+
const current = routes.find((r) => r.path === currentPath);
|
|
657
|
+
if (!current) return {};
|
|
658
|
+
const cmp = (x, y) => x < y ? -1 : x > y ? 1 : 0;
|
|
659
|
+
const sorted = routes.filter((r) => r.locale === current.locale).sort((a, b) => cmp(a.path, b.path));
|
|
660
|
+
const idx = sorted.findIndex((r) => r.path === currentPath);
|
|
661
|
+
return {
|
|
662
|
+
...idx > 0 ? { prev: sorted[idx - 1] } : {},
|
|
663
|
+
...idx < sorted.length - 1 ? { next: sorted[idx + 1] } : {}
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
function parseFrontmatter(fileContent) {
|
|
667
|
+
return parseFrontmatterYaml(fileContent);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// src/markdown/index.ts
|
|
671
|
+
import { unified as unified2 } from "unified";
|
|
672
|
+
import remarkParse2 from "remark-parse";
|
|
673
|
+
import remarkFrontmatter2 from "remark-frontmatter";
|
|
674
|
+
import remarkGfm from "remark-gfm";
|
|
675
|
+
import remarkDirective from "remark-directive";
|
|
676
|
+
import remarkRehype from "remark-rehype";
|
|
677
|
+
import rehypeRaw from "rehype-raw";
|
|
678
|
+
import "unist-util-visit";
|
|
679
|
+
|
|
680
|
+
// src/markdown/rehype-slug.ts
|
|
681
|
+
import { visit as visit2 } from "unist-util-visit";
|
|
682
|
+
import Slugger2 from "github-slugger";
|
|
683
|
+
function textOf2(node) {
|
|
684
|
+
if (node.type === "text") return node.value || "";
|
|
685
|
+
if (node.children) return node.children.map(textOf2).join("");
|
|
686
|
+
return "";
|
|
687
|
+
}
|
|
688
|
+
function rehypeSlug() {
|
|
689
|
+
return (tree, file) => {
|
|
690
|
+
file.data = file.data || {};
|
|
691
|
+
const toc = [];
|
|
692
|
+
const slugger = new Slugger2();
|
|
693
|
+
visit2(tree, "element", (node) => {
|
|
694
|
+
if (/^h[1-6]$/.test(node.tagName)) {
|
|
695
|
+
const text = textOf2(node).trim();
|
|
696
|
+
const depth = Number(node.tagName.slice(1));
|
|
697
|
+
let id = node.properties?.id;
|
|
698
|
+
if (!id) id = slugger.slug(text);
|
|
699
|
+
if (!node.properties) node.properties = {};
|
|
700
|
+
node.properties.id = id;
|
|
701
|
+
toc.push({ id, depth, title: text });
|
|
702
|
+
}
|
|
703
|
+
});
|
|
704
|
+
file.data.toc = toc;
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
function rehypeAutolinkHeadings() {
|
|
708
|
+
return (tree) => {
|
|
709
|
+
visit2(tree, "element", (node) => {
|
|
710
|
+
if (/^h[1-6]$/.test(node.tagName) && node.properties?.id) {
|
|
711
|
+
const anchor = { type: "element", tagName: "a", properties: { href: "#" + node.properties.id, className: ["dommief-heading-anchor"], tabIndex: -1 }, children: [] };
|
|
712
|
+
node.children = [anchor, ...node.children];
|
|
713
|
+
}
|
|
714
|
+
});
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// src/markdown/rehype-link.ts
|
|
719
|
+
import path3 from "path";
|
|
720
|
+
import { visit as visit3 } from "unist-util-visit";
|
|
721
|
+
var EXTERNAL = /^([a-z][a-z0-9+.-]*:|\/\/|#|\/)/i;
|
|
722
|
+
function rehypeLink(options = {}) {
|
|
723
|
+
return (tree, file) => {
|
|
724
|
+
const from = winPath(String(file?.path ?? ""));
|
|
725
|
+
const prefix = (options.base ?? "/").replace(/\/$/, "");
|
|
726
|
+
const warnings = Array.isArray(file?.data?.warnings) ? file.data.warnings : [];
|
|
727
|
+
visit3(tree, "element", (node) => {
|
|
728
|
+
if (node.tagName !== "a" || !node.properties?.href) return;
|
|
729
|
+
const href = String(node.properties.href);
|
|
730
|
+
if (EXTERNAL.test(href)) return;
|
|
731
|
+
const m = href.match(/^([^#?]*\.md)([?#].*)?$/);
|
|
732
|
+
if (!m || m[1] === void 0) return;
|
|
733
|
+
const tail = m[2] ?? "";
|
|
734
|
+
if (!options.byFile) {
|
|
735
|
+
node.properties.href = m[1].replace(/\.md$/, "") + tail;
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const abs = path3.posix.resolve(path3.posix.dirname(from), m[1]);
|
|
739
|
+
const route = options.byFile[abs];
|
|
740
|
+
if (route) node.properties.href = (route.path === "/" ? prefix + "/" : prefix + route.path) + tail;
|
|
741
|
+
else warnings.push(`link_unresolved: "${href}" trong ${from} kh\xF4ng tr\u1ECF t\u1EDBi file md n\xE0o thu\u1ED9c docDirs`);
|
|
742
|
+
});
|
|
743
|
+
visit3(tree, "element", (node) => {
|
|
744
|
+
if (node.tagName !== "a" || !node.properties?.href || node.properties["data-src-line"]) return;
|
|
745
|
+
const href = String(node.properties.href);
|
|
746
|
+
if (EXTERNAL.test(href) && !href.startsWith("/")) return;
|
|
747
|
+
const line = node.position?.start?.line;
|
|
748
|
+
if (line) node.properties["data-src-line"] = String(line);
|
|
749
|
+
});
|
|
750
|
+
if (file?.data) file.data.warnings = warnings;
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// src/markdown/rehype-img.ts
|
|
755
|
+
import path4 from "path";
|
|
756
|
+
import { visit as visit4 } from "unist-util-visit";
|
|
757
|
+
var PLACEHOLDER = "__DOMMIEF_IMG_";
|
|
758
|
+
var SKIP = /^([a-z][a-z0-9+.-]*:|\/\/|#|\/)/i;
|
|
759
|
+
function rehypeImg() {
|
|
760
|
+
return (tree, file) => {
|
|
761
|
+
const images = [];
|
|
762
|
+
visit4(tree, "element", (node) => {
|
|
763
|
+
if (node.tagName !== "img" || !node.properties?.src) return;
|
|
764
|
+
const src = String(node.properties.src);
|
|
765
|
+
if (SKIP.test(src)) return;
|
|
766
|
+
const clean = src.replace(/[?#].*$/, "");
|
|
767
|
+
const specifier = clean.startsWith(".") ? clean : "./" + path4.posix.normalize(clean);
|
|
768
|
+
const name = `${PLACEHOLDER}${images.length}__`;
|
|
769
|
+
images.push({ name, specifier });
|
|
770
|
+
node.properties.src = name;
|
|
771
|
+
});
|
|
772
|
+
visit4(tree, "element", (node) => {
|
|
773
|
+
if (node.tagName !== "img" || !node.properties?.src || node.properties["data-src-line"]) return;
|
|
774
|
+
const line = node.position?.start?.line;
|
|
775
|
+
if (line) node.properties["data-src-line"] = String(line);
|
|
776
|
+
});
|
|
777
|
+
file.data = file.data || {};
|
|
778
|
+
file.data.images = images;
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// src/markdown/rehype-desc.ts
|
|
783
|
+
import { visit as visit5 } from "unist-util-visit";
|
|
784
|
+
function rehypeDesc() {
|
|
785
|
+
return (tree, file) => {
|
|
786
|
+
file.data = file.data || {};
|
|
787
|
+
let desc;
|
|
788
|
+
visit5(tree, "element", (node) => {
|
|
789
|
+
if (!desc && node.tagName === "p") {
|
|
790
|
+
const text = (node.children || []).map((c) => c.value || "").join("").trim();
|
|
791
|
+
if (text) desc = text.slice(0, 160);
|
|
792
|
+
}
|
|
793
|
+
});
|
|
794
|
+
if (desc) {
|
|
795
|
+
if (!file.data.frontmatter) file.data.frontmatter = {};
|
|
796
|
+
if (file.data.frontmatter.description == null) file.data.frontmatter.description = desc;
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
function rehypeStrip() {
|
|
801
|
+
return (tree) => {
|
|
802
|
+
visit5(tree, "element", (node, index, parent) => {
|
|
803
|
+
if (node.tagName === "script" && parent && index !== void 0) {
|
|
804
|
+
parent.children.splice(index, 1);
|
|
805
|
+
return index;
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// src/markdown/rehype-text.ts
|
|
812
|
+
function rehypeText() {
|
|
813
|
+
return (tree, file) => {
|
|
814
|
+
file.data = file.data || {};
|
|
815
|
+
const toc = file.data.toc || [];
|
|
816
|
+
const texts = [];
|
|
817
|
+
const paraIdOf = /* @__PURE__ */ new WeakMap();
|
|
818
|
+
let nextParaId = 0;
|
|
819
|
+
let tocCursor = -1;
|
|
820
|
+
let currentTocIndex;
|
|
821
|
+
const isContainer = (node) => {
|
|
822
|
+
if (!node || node.type !== "element") return false;
|
|
823
|
+
const tag = node.tagName;
|
|
824
|
+
if (tag === "p" || tag === "ul" || tag === "ol" || tag === "root") return true;
|
|
825
|
+
return typeof tag === "string" && /^[A-Z]/.test(tag);
|
|
826
|
+
};
|
|
827
|
+
const containerOf = (ancestors) => {
|
|
828
|
+
for (let i = ancestors.length - 1; i >= 0; i--) {
|
|
829
|
+
if (isContainer(ancestors[i])) return ancestors[i];
|
|
830
|
+
}
|
|
831
|
+
return tree;
|
|
832
|
+
};
|
|
833
|
+
const walk = (node, ancestors) => {
|
|
834
|
+
if (node && node.type === "element" && /^h[1-6]$/.test(node.tagName)) {
|
|
835
|
+
tocCursor += 1;
|
|
836
|
+
if (tocCursor < toc.length) currentTocIndex = tocCursor;
|
|
837
|
+
for (const c of node.children || []) walk(c, [...ancestors, node]);
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
if (node && node.type === "text") {
|
|
841
|
+
const parent = ancestors[ancestors.length - 1];
|
|
842
|
+
if (parent && /^h[1-6]$/.test(parent.tagName)) return;
|
|
843
|
+
const v = node.value || "";
|
|
844
|
+
if (!v.trim()) return;
|
|
845
|
+
const container = containerOf(ancestors);
|
|
846
|
+
if (!paraIdOf.has(container)) paraIdOf.set(container, nextParaId++);
|
|
847
|
+
const paraId = paraIdOf.get(container);
|
|
848
|
+
const frag = { type: "content", value: v, paraId };
|
|
849
|
+
if (currentTocIndex !== void 0) frag.tocIndex = currentTocIndex;
|
|
850
|
+
texts.push(frag);
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
if (node && Array.isArray(node.children)) {
|
|
854
|
+
for (const c of node.children) walk(c, [...ancestors, node]);
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
walk(tree, []);
|
|
858
|
+
file.data.texts = texts;
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// src/markdown/rehype-demo.ts
|
|
863
|
+
import { visit as visit6 } from "unist-util-visit";
|
|
864
|
+
import { createHash as createHash2 } from "crypto";
|
|
865
|
+
function remarkDemoMeta() {
|
|
866
|
+
return (tree) => {
|
|
867
|
+
visit6(tree, "code", (node) => {
|
|
868
|
+
if (/\bdemo\b/.test(String(node.meta ?? ""))) {
|
|
869
|
+
node.data = { ...node.data, hProperties: { ...node.data?.hProperties, "data-demo": "true" } };
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
function demoId(source, file) {
|
|
875
|
+
return createHash2("sha256").update(file + "\n" + source).digest("hex").slice(0, 8);
|
|
876
|
+
}
|
|
877
|
+
function codeText(node) {
|
|
878
|
+
let out = "";
|
|
879
|
+
visit6(node, "text", (t) => {
|
|
880
|
+
out += t.value;
|
|
881
|
+
});
|
|
882
|
+
return out;
|
|
883
|
+
}
|
|
884
|
+
function rehypeDemo() {
|
|
885
|
+
return (tree, file) => {
|
|
886
|
+
const demos = Array.isArray(file.data?.demos) ? file.data.demos : [];
|
|
887
|
+
const filePath = String(file.path ?? "");
|
|
888
|
+
visit6(tree, "element", (node, index, parent) => {
|
|
889
|
+
if (!parent || typeof index !== "number") return;
|
|
890
|
+
if (node.tagName === "code" && node.properties?.src) {
|
|
891
|
+
const src = String(node.properties.src);
|
|
892
|
+
const source2 = codeText(node).trim();
|
|
893
|
+
const id2 = demoId(source2 || src, filePath);
|
|
894
|
+
demos.push({ id: id2, source: source2, src });
|
|
895
|
+
parent.children[index] = {
|
|
896
|
+
type: "element",
|
|
897
|
+
tagName: "DomDemo",
|
|
898
|
+
properties: { id: id2, src, source: source2 },
|
|
899
|
+
children: []
|
|
900
|
+
};
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
if (node.tagName !== "pre") return;
|
|
904
|
+
const codeNode = Array.isArray(node.children) ? node.children.find((c) => c?.tagName === "code") : null;
|
|
905
|
+
if (!codeNode) return;
|
|
906
|
+
if (!codeNode.properties?.dataDemo) return;
|
|
907
|
+
const source = codeText(codeNode).replace(/\n$/, "");
|
|
908
|
+
const id = demoId(source, filePath);
|
|
909
|
+
demos.push({ id, source });
|
|
910
|
+
parent.children[index] = {
|
|
911
|
+
type: "element",
|
|
912
|
+
tagName: "DomDemo",
|
|
913
|
+
properties: { id, source },
|
|
914
|
+
children: []
|
|
915
|
+
};
|
|
916
|
+
});
|
|
917
|
+
file.data.demos = demos;
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
// src/markdown/rehype-api.ts
|
|
922
|
+
import { visit as visit7 } from "unist-util-visit";
|
|
923
|
+
import { createHash as createHash3 } from "crypto";
|
|
924
|
+
import fs3 from "fs";
|
|
925
|
+
import path5 from "path";
|
|
926
|
+
import { createRequire } from "module";
|
|
927
|
+
var docgen;
|
|
928
|
+
function loadDocgen() {
|
|
929
|
+
if (docgen) return docgen;
|
|
930
|
+
try {
|
|
931
|
+
docgen = createRequire(import.meta.url)("react-docgen-typescript");
|
|
932
|
+
return docgen;
|
|
933
|
+
} catch (e) {
|
|
934
|
+
throw new DommiefError(`<API> c\u1EA7n react-docgen-typescript + typescript 5.x: ${e.message}`, { code: "api_docgen_unavailable" });
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
var apiCache = /* @__PURE__ */ new Map();
|
|
938
|
+
function clearApiCache() {
|
|
939
|
+
apiCache.clear();
|
|
940
|
+
}
|
|
941
|
+
function hashFileContent(content) {
|
|
942
|
+
return createHash3("sha256").update(content).digest("hex");
|
|
943
|
+
}
|
|
944
|
+
function resolveApiSrc(src, filePath) {
|
|
945
|
+
const base = filePath ? path5.dirname(filePath) : process.cwd();
|
|
946
|
+
return path5.isAbsolute(src) ? src : path5.resolve(base, src);
|
|
947
|
+
}
|
|
948
|
+
function buildApiTable(src, filePath = "") {
|
|
949
|
+
const abs = resolveApiSrc(src, filePath);
|
|
950
|
+
let content;
|
|
951
|
+
try {
|
|
952
|
+
content = fs3.readFileSync(abs, "utf8");
|
|
953
|
+
} catch {
|
|
954
|
+
return null;
|
|
955
|
+
}
|
|
956
|
+
const hash = hashFileContent(content);
|
|
957
|
+
const cached = apiCache.get(abs);
|
|
958
|
+
if (cached && cached.hash === hash) return cached.entries;
|
|
959
|
+
const parser = loadDocgen().withDefaultConfig({});
|
|
960
|
+
let docs;
|
|
961
|
+
try {
|
|
962
|
+
docs = parser.parse(abs) ?? [];
|
|
963
|
+
} catch {
|
|
964
|
+
docs = [];
|
|
965
|
+
}
|
|
966
|
+
const entries = (docs || []).map((d) => ({
|
|
967
|
+
displayName: d.displayName,
|
|
968
|
+
description: d.description || "",
|
|
969
|
+
src: abs,
|
|
970
|
+
hash,
|
|
971
|
+
props: Object.values(d.props || {}).map((p) => ({
|
|
972
|
+
name: p.name,
|
|
973
|
+
type: p.type?.name ?? p.type?.raw ?? "",
|
|
974
|
+
required: !!p.required,
|
|
975
|
+
description: p.description || "",
|
|
976
|
+
defaultValue: p.defaultValue?.value
|
|
977
|
+
}))
|
|
978
|
+
}));
|
|
979
|
+
apiCache.set(abs, { hash, entries });
|
|
980
|
+
return entries;
|
|
981
|
+
}
|
|
982
|
+
function rehypeApi() {
|
|
983
|
+
return (tree, file) => {
|
|
984
|
+
const apis = Array.isArray(file?.data?.apis) ? file.data.apis : [];
|
|
985
|
+
const watched = Array.isArray(file?.data?.apiSrcFiles) ? file.data.apiSrcFiles : [];
|
|
986
|
+
const filePath = String(file?.path ?? "");
|
|
987
|
+
visit7(tree, "element", (node, index, parent) => {
|
|
988
|
+
if (!parent || typeof index !== "number") return;
|
|
989
|
+
if (String(node.tagName).toLowerCase() !== "api") return;
|
|
990
|
+
const src = String(node.properties?.src ?? "");
|
|
991
|
+
if (!src) return;
|
|
992
|
+
const abs = resolveApiSrc(src, filePath);
|
|
993
|
+
const data = buildApiTable(src, filePath);
|
|
994
|
+
watched.push(abs);
|
|
995
|
+
apis.push({ id: hashFileContent(src + filePath).slice(0, 8), src: abs, data });
|
|
996
|
+
parent.children[index] = {
|
|
997
|
+
type: "element",
|
|
998
|
+
tagName: "DomApi",
|
|
999
|
+
properties: {
|
|
1000
|
+
src: abs,
|
|
1001
|
+
data: data ? JSON.stringify(data) : void 0
|
|
1002
|
+
},
|
|
1003
|
+
children: []
|
|
1004
|
+
};
|
|
1005
|
+
});
|
|
1006
|
+
if (file?.data) {
|
|
1007
|
+
file.data.apis = apis;
|
|
1008
|
+
file.data.apiSrcFiles = watched;
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
// src/markdown/remark-container.ts
|
|
1014
|
+
import { visit as visit8 } from "unist-util-visit";
|
|
1015
|
+
var CONTAINER_TYPES = ["info", "warning", "success", "error"];
|
|
1016
|
+
function restrictToContainerSyntax(extensions) {
|
|
1017
|
+
const isDirective = (e) => {
|
|
1018
|
+
const f = e?.flow?.[58];
|
|
1019
|
+
return !!e?.text?.[58] && (Array.isArray(f) ? f : [f]).some((c) => /Directive/.test(c?.tokenize?.name ?? ""));
|
|
1020
|
+
};
|
|
1021
|
+
const hit = extensions.filter(isDirective);
|
|
1022
|
+
if (hit.length !== 1) throw new Error("remark-directive \u0111\u1ED5i c\u1EA5u tr\xFAc n\u1ED9i b\u1ED9 (kh\xF4ng th\u1EA5y \u0111\xFAng 1 extension directive {text, flow}); c\u1EADp nh\u1EADt remarkContainer");
|
|
1023
|
+
const ext = hit[0];
|
|
1024
|
+
const flow = ext.flow[58];
|
|
1025
|
+
const constructs = Array.isArray(flow) ? flow : [flow];
|
|
1026
|
+
const containers = constructs.filter((c) => /Container/.test(c?.tokenize?.name ?? ""));
|
|
1027
|
+
if (containers.length !== 1) throw new Error("remark-directive \u0111\u1ED5i c\u1EA5u tr\xFAc n\u1ED9i b\u1ED9 (kh\xF4ng th\u1EA5y \u0111\xFAng 1 container construct); c\u1EADp nh\u1EADt remarkContainer");
|
|
1028
|
+
delete ext.text;
|
|
1029
|
+
ext.flow = { 58: containers };
|
|
1030
|
+
}
|
|
1031
|
+
function remarkContainer() {
|
|
1032
|
+
const data = this.data();
|
|
1033
|
+
restrictToContainerSyntax(data.micromarkExtensions ?? []);
|
|
1034
|
+
return (tree, file) => {
|
|
1035
|
+
visit8(tree, "containerDirective", (node, index, parent) => {
|
|
1036
|
+
if (!parent || typeof index !== "number") return;
|
|
1037
|
+
const name = String(node.name);
|
|
1038
|
+
if (!CONTAINER_TYPES.includes(name)) {
|
|
1039
|
+
const warnings = (file.data ??= {}).warnings ??= [];
|
|
1040
|
+
const pos = node.position?.start;
|
|
1041
|
+
warnings.push(`${file.path ?? ""}${pos ? `:${pos.line}:${pos.column}` : ""} container ":::${name}" kh\xF4ng \u0111\u01B0\u1EE3c h\u1ED7 tr\u1EE3 (ch\u1EC9 ${CONTAINER_TYPES.join("/")}); render th\xE0nh <div> th\u01B0\u1EDDng`);
|
|
1042
|
+
node.data = { hName: "div", hProperties: {} };
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
const type = name;
|
|
1046
|
+
const labelIdx = node.children.findIndex((c) => c.data?.directiveLabel);
|
|
1047
|
+
const labelNode = labelIdx >= 0 ? node.children.splice(labelIdx, 1)[0] : null;
|
|
1048
|
+
const title = node.attributes?.title ?? (labelNode ? textOf3(labelNode) : void 0);
|
|
1049
|
+
const children = [...node.children];
|
|
1050
|
+
if (title) {
|
|
1051
|
+
children.unshift({ type: "paragraph", data: { hName: "p", hProperties: { className: ["dommief-container__title"] } }, children: [{ type: "text", value: title }] });
|
|
1052
|
+
}
|
|
1053
|
+
node.children = children;
|
|
1054
|
+
node.data = {
|
|
1055
|
+
hName: "div",
|
|
1056
|
+
hProperties: {
|
|
1057
|
+
className: ["dommief-container", `dommief-container--${type}`],
|
|
1058
|
+
// warning/error là thông tin cần chú ý ngay → role="alert" không đúng (nó ngắt screen reader);
|
|
1059
|
+
// dùng role="note" cho mọi loại, kiểu nằm ở class.
|
|
1060
|
+
role: "note",
|
|
1061
|
+
...title ? {} : { "aria-label": type }
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
});
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
function textOf3(node) {
|
|
1068
|
+
let out = "";
|
|
1069
|
+
visit8(node, "text", (t) => {
|
|
1070
|
+
out += t.value;
|
|
1071
|
+
});
|
|
1072
|
+
return out.trim();
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// src/markdown/rehype-code.ts
|
|
1076
|
+
import { visit as visit9 } from "unist-util-visit";
|
|
1077
|
+
import { bundledLanguages, createHighlighter } from "shiki";
|
|
1078
|
+
var DEFAULT_SHIKI = { themes: { light: "github-light", dark: "github-dark" } };
|
|
1079
|
+
var HIGHLIGHT_RE = /\{((?:\d+(?:-\d+)?,?)+)\}/;
|
|
1080
|
+
function parseHighlightLines(meta) {
|
|
1081
|
+
const m = meta.match(HIGHLIGHT_RE);
|
|
1082
|
+
if (!m) return { lines: [], rest: meta.trim() };
|
|
1083
|
+
const set = /* @__PURE__ */ new Set();
|
|
1084
|
+
for (const part of m[1].split(",").filter(Boolean)) {
|
|
1085
|
+
const [a, b] = part.split("-").map(Number);
|
|
1086
|
+
const end = b ?? a;
|
|
1087
|
+
for (let n = Math.min(a, end); n <= Math.max(a, end); n++) if (n >= 1) set.add(n);
|
|
1088
|
+
}
|
|
1089
|
+
return { lines: [...set].sort((x, y) => x - y), rest: meta.replace(HIGHLIGHT_RE, "").trim() };
|
|
1090
|
+
}
|
|
1091
|
+
function remarkCodeMeta() {
|
|
1092
|
+
return (tree) => {
|
|
1093
|
+
visit9(tree, "code", (node) => {
|
|
1094
|
+
const meta = String(node.meta ?? "");
|
|
1095
|
+
if (!meta) return;
|
|
1096
|
+
const { lines, rest } = parseHighlightLines(meta);
|
|
1097
|
+
const title = rest.match(/\[([^\]]+)\]/)?.[1];
|
|
1098
|
+
const props = {};
|
|
1099
|
+
if (lines.length) props["data-highlight-lines"] = lines.join(",");
|
|
1100
|
+
if (title) props["data-title"] = title;
|
|
1101
|
+
if (Object.keys(props).length) node.data = { ...node.data, hProperties: { ...node.data?.hProperties, ...props } };
|
|
1102
|
+
node.meta = rest || null;
|
|
1103
|
+
});
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
var highlighters = /* @__PURE__ */ new Map();
|
|
1107
|
+
function getHighlighter(opts) {
|
|
1108
|
+
const key = `${opts.themes.light}|${opts.themes.dark}`;
|
|
1109
|
+
let h = highlighters.get(key);
|
|
1110
|
+
if (!h) {
|
|
1111
|
+
h = createHighlighter({ themes: [opts.themes.light, opts.themes.dark], langs: [] });
|
|
1112
|
+
highlighters.set(key, h);
|
|
1113
|
+
}
|
|
1114
|
+
return h;
|
|
1115
|
+
}
|
|
1116
|
+
function textOf4(node) {
|
|
1117
|
+
let out = "";
|
|
1118
|
+
visit9(node, "text", (t) => {
|
|
1119
|
+
out += t.value;
|
|
1120
|
+
});
|
|
1121
|
+
return out;
|
|
1122
|
+
}
|
|
1123
|
+
function langOf(code) {
|
|
1124
|
+
const cls = code.properties?.className;
|
|
1125
|
+
const list = Array.isArray(cls) ? cls.map(String) : typeof cls === "string" ? cls.split(/\s+/) : [];
|
|
1126
|
+
return list.map((c) => /^language-(.+)$/.exec(c)?.[1]).find(Boolean);
|
|
1127
|
+
}
|
|
1128
|
+
function markLines(pre, highlight, lineNumbers) {
|
|
1129
|
+
const code = pre.children?.find((c) => c.tagName === "code");
|
|
1130
|
+
let n = 0;
|
|
1131
|
+
for (const child of code?.children ?? []) {
|
|
1132
|
+
if (child.type !== "element" || child.tagName !== "span") continue;
|
|
1133
|
+
const cls = String(child.properties?.class ?? child.properties?.className ?? "");
|
|
1134
|
+
if (!/\bline\b/.test(cls)) continue;
|
|
1135
|
+
n++;
|
|
1136
|
+
const classes = cls.split(/\s+/).filter(Boolean);
|
|
1137
|
+
if (highlight.has(n)) classes.push("highlighted");
|
|
1138
|
+
child.properties = { ...child.properties, class: classes.join(" ") };
|
|
1139
|
+
if (lineNumbers) child.properties["data-line"] = String(n);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
function rehypeCode(options = {}) {
|
|
1143
|
+
const shiki = options.shiki === void 0 ? DEFAULT_SHIKI : options.shiki;
|
|
1144
|
+
const lineNumbers = !!options.lineNumbers;
|
|
1145
|
+
return async (tree, file) => {
|
|
1146
|
+
const jobs = [];
|
|
1147
|
+
visit9(tree, "element", (node, index, parent) => {
|
|
1148
|
+
if (node.tagName !== "pre" || !parent || typeof index !== "number") return;
|
|
1149
|
+
const kids = (node.children ?? []).filter((c) => !(c.type === "text" && !c.value.trim()));
|
|
1150
|
+
if (kids.length !== 1 || kids[0].tagName !== "code") return;
|
|
1151
|
+
jobs.push({ parent, index, pre: node, code: kids[0] });
|
|
1152
|
+
});
|
|
1153
|
+
if (!jobs.length) return;
|
|
1154
|
+
const highlighter = shiki ? await getHighlighter(shiki) : null;
|
|
1155
|
+
for (const { parent, index, pre, code } of jobs) {
|
|
1156
|
+
const lang = langOf(code);
|
|
1157
|
+
const title = code.properties?.dataTitle;
|
|
1158
|
+
const hl = new Set(String(code.properties?.dataHighlightLines ?? "").split(",").filter(Boolean).map(Number));
|
|
1159
|
+
let inner = pre;
|
|
1160
|
+
if (highlighter && shiki && lang) {
|
|
1161
|
+
if (lang in bundledLanguages) {
|
|
1162
|
+
if (!highlighter.getLoadedLanguages().includes(lang)) await highlighter.loadLanguage(lang);
|
|
1163
|
+
const source = textOf4(code).replace(/\n$/, "");
|
|
1164
|
+
const root = highlighter.codeToHast(source, { lang, themes: { light: shiki.themes.light, dark: shiki.themes.dark }, defaultColor: false });
|
|
1165
|
+
inner = root.children[0];
|
|
1166
|
+
markLines(inner, hl, lineNumbers);
|
|
1167
|
+
} else {
|
|
1168
|
+
const warnings = (file.data ??= {}).warnings ??= [];
|
|
1169
|
+
const pos = pre.position?.start;
|
|
1170
|
+
warnings.push(`${file.path ?? ""}${pos ? `:${pos.line}` : ""} Shiki kh\xF4ng c\xF3 grammar cho "${lang}"; hi\u1EC3n th\u1ECB code th\xF4`);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
if (inner === pre && hl.size) pre.properties = { ...pre.properties, "data-highlight-lines": [...hl].join(",") };
|
|
1174
|
+
delete code.properties?.dataHighlightLines;
|
|
1175
|
+
delete code.properties?.dataTitle;
|
|
1176
|
+
const children = [];
|
|
1177
|
+
if (title) children.push({ type: "element", tagName: "div", properties: { className: ["dommief-code__title"] }, children: [{ type: "text", value: title }] });
|
|
1178
|
+
children.push(inner);
|
|
1179
|
+
parent.children[index] = {
|
|
1180
|
+
type: "element",
|
|
1181
|
+
tagName: "div",
|
|
1182
|
+
properties: { className: ["dommief-code"], ...lang ? { "data-lang": lang } : {} },
|
|
1183
|
+
children
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// src/markdown/to-module.ts
|
|
1190
|
+
import { toEstree } from "hast-util-to-estree";
|
|
1191
|
+
import { toJs, jsx } from "estree-util-to-js";
|
|
1192
|
+
var CLIENT_MODULE = "dommief/client";
|
|
1193
|
+
function toModule(hast, meta, images = [], demos = []) {
|
|
1194
|
+
const { texts: _texts, ...clientMeta } = meta;
|
|
1195
|
+
const estree = toEstree(hast, { elementAttributeNameCase: "react" });
|
|
1196
|
+
const { value: code } = toJs(estree, { handlers: jsx });
|
|
1197
|
+
let body = code.replace(/;\s*$/, "").trim();
|
|
1198
|
+
const imageImports = images.map((im, i) => {
|
|
1199
|
+
body = body.split(`src="${im.name}"`).join(`src={__dmImg${i}}`);
|
|
1200
|
+
return `import __dmImg${i} from ${JSON.stringify(im.specifier)};
|
|
1201
|
+
`;
|
|
1202
|
+
}).join("");
|
|
1203
|
+
const used = ["DomDemo", "DumiDemo", "DomApi", "DumiApi"].filter((n) => new RegExp(`<${n}[\\s/>]`).test(body));
|
|
1204
|
+
const clientNames = [...used];
|
|
1205
|
+
if (demos.length) clientNames.push("registerDemo");
|
|
1206
|
+
const clientImport = clientNames.length ? `import { ${Array.from(new Set(clientNames)).join(", ")} } from '${CLIENT_MODULE}';
|
|
1207
|
+
` : "";
|
|
1208
|
+
const demoImports = demos.map((d) => {
|
|
1209
|
+
const specifier = d.src ? d.src : `virtual:dommief-demo/${d.id}`;
|
|
1210
|
+
return `import Demo_${d.id} from ${JSON.stringify(specifier)};
|
|
1211
|
+
`;
|
|
1212
|
+
}).join("");
|
|
1213
|
+
const demoRegs = demos.map((d) => `registerDemo(${JSON.stringify(d.id)}, Demo_${d.id});
|
|
1214
|
+
`).join("");
|
|
1215
|
+
return `import React from 'react';
|
|
1216
|
+
${imageImports}${clientImport}${demoImports}${demoRegs}export default function Content(){ return (
|
|
1217
|
+
${body}
|
|
1218
|
+
); }
|
|
1219
|
+
export const meta = ${JSON.stringify(clientMeta)};
|
|
1220
|
+
`;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
// src/markdown/index.ts
|
|
1224
|
+
async function transformMarkdown(source, file, opts = {}) {
|
|
1225
|
+
const host = opts.hooks ?? (opts.plugins ? createPluginHost(opts.plugins) : void 0);
|
|
1226
|
+
const remarkPlugins = [...opts.remarkPlugins ?? [], ...host ? host.collectRemarkPlugins() : []];
|
|
1227
|
+
const rehypePlugins = [...opts.rehypePlugins ?? [], ...host ? host.collectRehypePlugins() : []];
|
|
1228
|
+
let processor;
|
|
1229
|
+
try {
|
|
1230
|
+
processor = unified2().use(remarkParse2).use(remarkFrontmatter2, ["yaml"]).use(remarkGfm).use(remarkDirective).use(remarkContainer).use(remarkMeta, { filename: file }).use(remarkCodeMeta).use(remarkDemoMeta);
|
|
1231
|
+
for (const p of remarkPlugins) processor = processor.use(p);
|
|
1232
|
+
processor = processor.use(remarkRehype, { allowDangerousHtml: true }).use(rehypeRaw);
|
|
1233
|
+
for (const p of rehypePlugins) processor = processor.use(p);
|
|
1234
|
+
processor = processor.use(rehypeSlug).use(rehypeAutolinkHeadings).use(rehypeLink, opts.byFile ? { byFile: opts.byFile, base: opts.base ?? "/" } : {}).use(rehypeImg).use(rehypeDesc).use(rehypeStrip).use(rehypeText).use(rehypeDemo).use(rehypeCode, opts.code ?? {}).use(rehypeApi);
|
|
1235
|
+
} catch (e) {
|
|
1236
|
+
throw new DommiefError("failed to build pipeline", { file });
|
|
1237
|
+
}
|
|
1238
|
+
const vfile = { data: {}, path: file };
|
|
1239
|
+
let hast;
|
|
1240
|
+
try {
|
|
1241
|
+
const tree = processor.parse(source);
|
|
1242
|
+
hast = await processor.run(tree, vfile);
|
|
1243
|
+
} catch (e) {
|
|
1244
|
+
throw new DommiefError("markdown transform failed: " + e.message, { file });
|
|
1245
|
+
}
|
|
1246
|
+
const apiSrcFiles = vfile.data?.apiSrcFiles ?? [];
|
|
1247
|
+
const meta = {
|
|
1248
|
+
frontmatter: vfile.data?.frontmatter ?? {},
|
|
1249
|
+
toc: vfile.data?.toc ?? [],
|
|
1250
|
+
texts: vfile.data?.texts ?? []
|
|
1251
|
+
};
|
|
1252
|
+
const demos = vfile.data?.demos ?? [];
|
|
1253
|
+
const code = toModule(hast, meta, vfile.data?.images ?? [], demos);
|
|
1254
|
+
return { code, meta, warnings: vfile.data?.warnings ?? [], apiSrcFiles, demos };
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// src/log.ts
|
|
1258
|
+
function createLogger(verbose = false) {
|
|
1259
|
+
return {
|
|
1260
|
+
verbose,
|
|
1261
|
+
info: (m) => console.log(m),
|
|
1262
|
+
debug: (m) => {
|
|
1263
|
+
if (verbose) console.log("[debug]", m);
|
|
1264
|
+
},
|
|
1265
|
+
warn: (m) => console.warn("[warn]", m),
|
|
1266
|
+
error: (m) => console.error("[error]", m)
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
// src/search.ts
|
|
1271
|
+
import MiniSearch from "minisearch";
|
|
1272
|
+
|
|
1273
|
+
// src/search-config.ts
|
|
1274
|
+
var CJK_RANGE = /[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/;
|
|
1275
|
+
function createMiniSearchConfig() {
|
|
1276
|
+
const stripDiacritics = (s) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
1277
|
+
const processTerm = (term) => {
|
|
1278
|
+
const t = stripDiacritics(term).toLowerCase().replace(/đ/g, "d").normalize("NFC").trim();
|
|
1279
|
+
return t.length ? t : null;
|
|
1280
|
+
};
|
|
1281
|
+
const tokenize = (text) => {
|
|
1282
|
+
const out = [];
|
|
1283
|
+
for (const raw of text.split(/[\s\p{P}]+/u)) {
|
|
1284
|
+
if (!raw) continue;
|
|
1285
|
+
let buf = "";
|
|
1286
|
+
for (const ch of raw) {
|
|
1287
|
+
if (CJK_RANGE.test(ch)) {
|
|
1288
|
+
if (buf) {
|
|
1289
|
+
out.push(buf);
|
|
1290
|
+
buf = "";
|
|
1291
|
+
}
|
|
1292
|
+
out.push(ch);
|
|
1293
|
+
} else {
|
|
1294
|
+
buf += ch;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
if (buf) out.push(buf);
|
|
1298
|
+
}
|
|
1299
|
+
return out;
|
|
1300
|
+
};
|
|
1301
|
+
return { tokenize, processTerm };
|
|
1302
|
+
}
|
|
1303
|
+
var SEARCH_FIELDS = ["value", "pageTitle", "sectionTitle"];
|
|
1304
|
+
var SEARCH_STORE_FIELDS = ["routeId", "path", "pageTitle", "sectionTitle", "paraId", "value", "pageKey", "sectionKey"];
|
|
1305
|
+
|
|
1306
|
+
// src/search.ts
|
|
1307
|
+
var INDEX_BUDGET_BYTES_PER_PAGE = 5 * 1024;
|
|
1308
|
+
async function buildSearchIndex(opts) {
|
|
1309
|
+
const { routes, loadPageMeta, config } = opts;
|
|
1310
|
+
const cfg = createMiniSearchConfig();
|
|
1311
|
+
const defaultLocale = config.locales[0]?.id;
|
|
1312
|
+
const localesOut = {};
|
|
1313
|
+
const stats = {};
|
|
1314
|
+
const manifestLocales = {};
|
|
1315
|
+
for (const loc of config.locales) {
|
|
1316
|
+
const locRoutes = routes.filter((r) => (r.locale ?? defaultLocale) === loc.id);
|
|
1317
|
+
if (locRoutes.length === 0) continue;
|
|
1318
|
+
const ms = new MiniSearch({
|
|
1319
|
+
fields: [...SEARCH_FIELDS],
|
|
1320
|
+
storeFields: [...SEARCH_STORE_FIELDS],
|
|
1321
|
+
...cfg
|
|
1322
|
+
});
|
|
1323
|
+
const docs = [];
|
|
1324
|
+
for (const route of locRoutes) {
|
|
1325
|
+
const meta = await loadPageMeta(route);
|
|
1326
|
+
const title = meta.frontmatter?.title || route.id;
|
|
1327
|
+
const toc = meta.toc || [];
|
|
1328
|
+
const fragments = meta.texts || [];
|
|
1329
|
+
for (let i = 0; i < fragments.length; i++) {
|
|
1330
|
+
const f = fragments[i];
|
|
1331
|
+
const tocIndex = f.tocIndex;
|
|
1332
|
+
const sectionTitle = tocIndex !== void 0 && toc[tocIndex] ? toc[tocIndex].title : title;
|
|
1333
|
+
const pageKey = route.id;
|
|
1334
|
+
const sectionKey = `${route.id}::${tocIndex ?? "orphan"}`;
|
|
1335
|
+
docs.push({
|
|
1336
|
+
id: `${route.id}#${f.paraId ?? i}#${i}`,
|
|
1337
|
+
routeId: route.id,
|
|
1338
|
+
path: route.path,
|
|
1339
|
+
pageTitle: title,
|
|
1340
|
+
sectionTitle,
|
|
1341
|
+
paraId: f.paraId ?? 0,
|
|
1342
|
+
value: f.value,
|
|
1343
|
+
pageKey,
|
|
1344
|
+
sectionKey
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
ms.addAll(docs);
|
|
1349
|
+
const json = ms.toJSON();
|
|
1350
|
+
localesOut[loc.id] = json;
|
|
1351
|
+
const bytes = Buffer.byteLength(JSON.stringify(json));
|
|
1352
|
+
stats[loc.id] = { docs: docs.length, bytes, pages: locRoutes.length };
|
|
1353
|
+
manifestLocales[loc.id] = `/search-index/${loc.id}.json`;
|
|
1354
|
+
}
|
|
1355
|
+
return { locales: localesOut, stats, manifest: { locales: manifestLocales } };
|
|
1356
|
+
}
|
|
1357
|
+
export {
|
|
1358
|
+
DommiefError,
|
|
1359
|
+
Hook,
|
|
1360
|
+
INDEX_BUDGET_BYTES_PER_PAGE,
|
|
1361
|
+
PluginHookHost,
|
|
1362
|
+
buildApiTable,
|
|
1363
|
+
buildNav,
|
|
1364
|
+
buildRouteTable,
|
|
1365
|
+
buildSearchIndex,
|
|
1366
|
+
buildSidebar,
|
|
1367
|
+
clearApiCache,
|
|
1368
|
+
createLogger,
|
|
1369
|
+
createMiniSearchConfig,
|
|
1370
|
+
createPluginHost,
|
|
1371
|
+
defineConfig,
|
|
1372
|
+
definePlugin,
|
|
1373
|
+
formatError,
|
|
1374
|
+
hashFileContent,
|
|
1375
|
+
loadConfig,
|
|
1376
|
+
loadConfigFile,
|
|
1377
|
+
paginate,
|
|
1378
|
+
parseFrontmatter,
|
|
1379
|
+
registerPlugin,
|
|
1380
|
+
rehypeApi,
|
|
1381
|
+
resolveConfig,
|
|
1382
|
+
transformMarkdown
|
|
1383
|
+
};
|