third-audience-mdx 1.0.0 → 1.0.3
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/dashboard/routes/okf-graph-route.d.mts +6 -0
- package/dist/dashboard/routes/okf-graph-route.d.ts +6 -0
- package/dist/dashboard/routes/okf-graph-route.js +266 -0
- package/dist/dashboard/routes/okf-graph-route.js.map +1 -0
- package/dist/dashboard/routes/okf-graph-route.mjs +231 -0
- package/dist/dashboard/routes/okf-graph-route.mjs.map +1 -0
- package/dist/dashboard/routes/okf-route.js +1 -1
- package/dist/dashboard/routes/okf-route.js.map +1 -1
- package/dist/dashboard/routes/okf-route.mjs +1 -1
- package/dist/dashboard/routes/okf-route.mjs.map +1 -1
- package/dist/dashboard/ui/components/Sidebar.js +15 -0
- package/dist/dashboard/ui/components/Sidebar.js.map +1 -1
- package/dist/dashboard/ui/components/Sidebar.mjs +15 -0
- package/dist/dashboard/ui/components/Sidebar.mjs.map +1 -1
- package/dist/dashboard/ui/pages/OkfPage.d.mts +5 -0
- package/dist/dashboard/ui/pages/OkfPage.d.ts +5 -0
- package/dist/dashboard/ui/pages/OkfPage.js +438 -0
- package/dist/dashboard/ui/pages/OkfPage.js.map +1 -0
- package/dist/dashboard/ui/pages/OkfPage.mjs +414 -0
- package/dist/dashboard/ui/pages/OkfPage.mjs.map +1 -0
- package/dist/index.d.mts +4 -8
- package/dist/index.d.ts +4 -8
- package/dist/index.js +94 -231
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +94 -234
- package/dist/index.mjs.map +1 -1
- package/package.json +20 -2
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/dashboard/routes/okf-graph-route.ts
|
|
31
|
+
var okf_graph_route_exports = {};
|
|
32
|
+
__export(okf_graph_route_exports, {
|
|
33
|
+
GET: () => GET
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(okf_graph_route_exports);
|
|
36
|
+
var import_server2 = require("next/server");
|
|
37
|
+
var import_path3 = __toESM(require("path"));
|
|
38
|
+
|
|
39
|
+
// src/core/mdx-reader.ts
|
|
40
|
+
var import_fs = __toESM(require("fs"));
|
|
41
|
+
var import_path = __toESM(require("path"));
|
|
42
|
+
var import_gray_matter = __toESM(require("gray-matter"));
|
|
43
|
+
var MdxReader = class {
|
|
44
|
+
constructor(options) {
|
|
45
|
+
this.contentDir = options.contentDir;
|
|
46
|
+
}
|
|
47
|
+
/** Read a single MDX file by slug. Returns null if not found. */
|
|
48
|
+
read(slug) {
|
|
49
|
+
const candidates = [
|
|
50
|
+
import_path.default.join(this.contentDir, `${slug}.mdx`),
|
|
51
|
+
import_path.default.join(this.contentDir, `${slug}.md`),
|
|
52
|
+
import_path.default.join(this.contentDir, slug, "index.mdx"),
|
|
53
|
+
import_path.default.join(this.contentDir, slug, "index.md")
|
|
54
|
+
];
|
|
55
|
+
for (const filePath of candidates) {
|
|
56
|
+
if (import_fs.default.existsSync(filePath)) {
|
|
57
|
+
return this.parseFile(slug, filePath);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
/** Read all MDX files recursively. */
|
|
63
|
+
readAll() {
|
|
64
|
+
if (!import_fs.default.existsSync(this.contentDir)) return [];
|
|
65
|
+
return this.walkDir(this.contentDir, this.contentDir);
|
|
66
|
+
}
|
|
67
|
+
walkDir(dir, root) {
|
|
68
|
+
const results = [];
|
|
69
|
+
for (const entry of import_fs.default.readdirSync(dir, { withFileTypes: true })) {
|
|
70
|
+
const fullPath = import_path.default.join(dir, entry.name);
|
|
71
|
+
if (entry.isDirectory()) {
|
|
72
|
+
results.push(...this.walkDir(fullPath, root));
|
|
73
|
+
} else if (entry.name.endsWith(".mdx") || entry.name.endsWith(".md")) {
|
|
74
|
+
const relative = import_path.default.relative(root, fullPath);
|
|
75
|
+
const slug = relative.replace(/\.(mdx|md)$/, "").replace(/\/index$/, "");
|
|
76
|
+
results.push(this.parseFile(slug, fullPath));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return results;
|
|
80
|
+
}
|
|
81
|
+
parseFile(slug, filePath) {
|
|
82
|
+
const raw = import_fs.default.readFileSync(filePath, "utf-8");
|
|
83
|
+
const { data: frontmatter, content: rawContent } = (0, import_gray_matter.default)(raw);
|
|
84
|
+
return { slug, filePath, frontmatter, rawContent };
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// src/core/markdown-renderer.ts
|
|
89
|
+
var MarkdownRenderer = class {
|
|
90
|
+
render(file) {
|
|
91
|
+
const header = this.buildFrontmatterHeader(file.frontmatter);
|
|
92
|
+
const body = this.stripJsx(file.rawContent);
|
|
93
|
+
return header ? `${header}
|
|
94
|
+
|
|
95
|
+
${body}` : body;
|
|
96
|
+
}
|
|
97
|
+
buildFrontmatterHeader(fm) {
|
|
98
|
+
const keys = Object.keys(fm);
|
|
99
|
+
if (keys.length === 0) return "";
|
|
100
|
+
const lines = keys.filter((k) => fm[k] !== void 0 && fm[k] !== null).map((k) => `${k}: ${this.yamlValue(fm[k])}`);
|
|
101
|
+
return `---
|
|
102
|
+
${lines.join("\n")}
|
|
103
|
+
---`;
|
|
104
|
+
}
|
|
105
|
+
yamlValue(val) {
|
|
106
|
+
if (typeof val === "string") {
|
|
107
|
+
return /[:#\[\]{},&*?|<>=!%@`]/.test(val) ? `"${val.replace(/"/g, '\\"')}"` : val;
|
|
108
|
+
}
|
|
109
|
+
if (val instanceof Date) return val.toISOString();
|
|
110
|
+
if (Array.isArray(val)) return `[${val.map((v) => this.yamlValue(v)).join(", ")}]`;
|
|
111
|
+
return String(val);
|
|
112
|
+
}
|
|
113
|
+
stripJsx(content) {
|
|
114
|
+
let out = content;
|
|
115
|
+
out = out.replace(/^import\s+.*?['"].*?['"]\s*\n?/gm, "");
|
|
116
|
+
out = out.replace(/^export\s+(?:default\s+)?(?:const|let|var|function|class)\s+[\s\S]*?(?=\n(?=[^{]|\n)|\n{2,})/gm, "");
|
|
117
|
+
out = out.replace(/^export\s*\{[^}]*\}\s*(?:from\s+['"][^'"]*['"])?\s*\n?/gm, "");
|
|
118
|
+
out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*\/>/g, "");
|
|
119
|
+
out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*>[\s\S]*?<\/\1>/g, "");
|
|
120
|
+
out = out.replace(/^\s*\{[^}]+\}\s*\n/gm, "");
|
|
121
|
+
out = out.replace(/\n{3,}/g, "\n\n");
|
|
122
|
+
return out.trim();
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
// src/okf/okf-bundle.ts
|
|
127
|
+
var renderer = new MarkdownRenderer();
|
|
128
|
+
function buildOkfGraph(files, baseUrl) {
|
|
129
|
+
const base = baseUrl.replace(/\/$/, "");
|
|
130
|
+
const slugSet = new Set(files.map((f) => f.slug));
|
|
131
|
+
const mdMap = /* @__PURE__ */ new Map();
|
|
132
|
+
for (const file of files) {
|
|
133
|
+
mdMap.set(file.slug, renderer.render(file));
|
|
134
|
+
}
|
|
135
|
+
const degrees = new Map(files.map((f) => [f.slug, 0]));
|
|
136
|
+
const rawEdges = [];
|
|
137
|
+
for (const file of files) {
|
|
138
|
+
const md = mdMap.get(file.slug) ?? "";
|
|
139
|
+
const linkRe = /\[([^\]]+)\]\((\/[^)]+)\)/g;
|
|
140
|
+
let m;
|
|
141
|
+
while ((m = linkRe.exec(md)) !== null) {
|
|
142
|
+
const candidate = m[2].replace(/^\//, "").replace(/\.md$/, "");
|
|
143
|
+
if (slugSet.has(candidate) && candidate !== file.slug) {
|
|
144
|
+
rawEdges.push({ source: file.slug, target: candidate });
|
|
145
|
+
degrees.set(file.slug, (degrees.get(file.slug) ?? 0) + 1);
|
|
146
|
+
degrees.set(candidate, (degrees.get(candidate) ?? 0) + 1);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const top100 = files.slice().sort((a, b) => (degrees.get(b.slug) ?? 0) - (degrees.get(a.slug) ?? 0)).slice(0, 100);
|
|
151
|
+
const topSet = new Set(top100.map((f) => f.slug));
|
|
152
|
+
const nodes = top100.map((f) => ({
|
|
153
|
+
id: f.slug,
|
|
154
|
+
title: String(f.frontmatter.title ?? f.slug),
|
|
155
|
+
type: String(f.frontmatter.type ?? "WebPage"),
|
|
156
|
+
url: `${base}/${f.slug}`
|
|
157
|
+
}));
|
|
158
|
+
const edges = rawEdges.filter((e) => topSet.has(e.source) && topSet.has(e.target));
|
|
159
|
+
return { nodes, edges };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/dashboard/auth.ts
|
|
163
|
+
var import_server = require("next/server");
|
|
164
|
+
|
|
165
|
+
// src/dashboard/admin-store.ts
|
|
166
|
+
var import_fs2 = __toESM(require("fs"));
|
|
167
|
+
var import_path2 = __toESM(require("path"));
|
|
168
|
+
var import_crypto = __toESM(require("crypto"));
|
|
169
|
+
function adminFilePath() {
|
|
170
|
+
const dataDir = process.env.TA_DATA_DIR ?? "data";
|
|
171
|
+
return import_path2.default.join(process.cwd(), dataDir, "ta-admin.json");
|
|
172
|
+
}
|
|
173
|
+
function loadAdmin() {
|
|
174
|
+
const filePath = adminFilePath();
|
|
175
|
+
if (!import_fs2.default.existsSync(filePath)) return null;
|
|
176
|
+
try {
|
|
177
|
+
return JSON.parse(import_fs2.default.readFileSync(filePath, "utf-8"));
|
|
178
|
+
} catch {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
var CIPHER = "aes-256-gcm";
|
|
183
|
+
function getEncryptionKey() {
|
|
184
|
+
const secret = process.env.THIRD_AUDIENCE_SECRET ?? "ta-fallback-key-change-me";
|
|
185
|
+
return import_crypto.default.createHash("sha256").update(secret).digest();
|
|
186
|
+
}
|
|
187
|
+
function decryptApiKey(encoded) {
|
|
188
|
+
try {
|
|
189
|
+
const iv = Buffer.from(encoded.slice(0, 24), "hex");
|
|
190
|
+
const tag = Buffer.from(encoded.slice(24, 56), "hex");
|
|
191
|
+
const encrypted = Buffer.from(encoded.slice(56), "hex");
|
|
192
|
+
const key = getEncryptionKey();
|
|
193
|
+
const decipher = import_crypto.default.createDecipheriv(CIPHER, key, iv);
|
|
194
|
+
decipher.setAuthTag(tag);
|
|
195
|
+
return decipher.update(encrypted) + decipher.final("utf8");
|
|
196
|
+
} catch {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function getApiKey() {
|
|
201
|
+
const record = loadAdmin();
|
|
202
|
+
if (!record?.apiKey) return null;
|
|
203
|
+
return decryptApiKey(record.apiKey);
|
|
204
|
+
}
|
|
205
|
+
function verifyApiKey(key) {
|
|
206
|
+
const stored = getApiKey();
|
|
207
|
+
if (!stored) return false;
|
|
208
|
+
if (key.length !== stored.length) return false;
|
|
209
|
+
return import_crypto.default.timingSafeEqual(Buffer.from(key), Buffer.from(stored));
|
|
210
|
+
}
|
|
211
|
+
function verifySession(token) {
|
|
212
|
+
const lastDot = token.lastIndexOf(".");
|
|
213
|
+
if (lastDot === -1) return false;
|
|
214
|
+
const payload = token.slice(0, lastDot);
|
|
215
|
+
const sig = token.slice(lastDot + 1);
|
|
216
|
+
const expected = import_crypto.default.createHmac("sha256", process.env.THIRD_AUDIENCE_SECRET ?? "ta-salt").update(payload).digest("hex");
|
|
217
|
+
if (sig.length !== expected.length) return false;
|
|
218
|
+
return import_crypto.default.timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(expected, "hex"));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/dashboard/auth.ts
|
|
222
|
+
var SESSION_COOKIE = "ta_session";
|
|
223
|
+
function checkApiAuth(req) {
|
|
224
|
+
const apiKeyHeader = req.headers.get("x-ta-api-key");
|
|
225
|
+
if (apiKeyHeader) return verifyApiKey(apiKeyHeader);
|
|
226
|
+
const auth = req.headers.get("authorization") ?? "";
|
|
227
|
+
if (auth.startsWith("Bearer ")) {
|
|
228
|
+
const token = auth.slice(7);
|
|
229
|
+
return verifyApiKey(token);
|
|
230
|
+
}
|
|
231
|
+
const session = req.cookies.get(SESSION_COOKIE)?.value;
|
|
232
|
+
if (session) return verifySession(session);
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
function unauthorizedResponse() {
|
|
236
|
+
return import_server.NextResponse.json(
|
|
237
|
+
{ error: "Unauthorized. Provide X-TA-Api-Key header or a valid session cookie." },
|
|
238
|
+
{
|
|
239
|
+
status: 401,
|
|
240
|
+
headers: { "WWW-Authenticate": 'Bearer realm="Third Audience API"' }
|
|
241
|
+
}
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// src/dashboard/routes/okf-graph-route.ts
|
|
246
|
+
var reader = new MdxReader({ contentDir: import_path3.default.join(process.cwd(), process.env.TA_CONTENT_DIR ?? "content") });
|
|
247
|
+
async function GET(req) {
|
|
248
|
+
if (!checkApiAuth(req)) return unauthorizedResponse();
|
|
249
|
+
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL ?? `${req.nextUrl.protocol}//${req.nextUrl.host}`;
|
|
250
|
+
const files = reader.readAll();
|
|
251
|
+
const graph = buildOkfGraph(files, baseUrl);
|
|
252
|
+
return import_server2.NextResponse.json({
|
|
253
|
+
graph,
|
|
254
|
+
stats: {
|
|
255
|
+
pages: files.length,
|
|
256
|
+
nodes: graph.nodes.length,
|
|
257
|
+
edges: graph.edges.length
|
|
258
|
+
},
|
|
259
|
+
indexUrl: `${baseUrl}/okf`
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
263
|
+
0 && (module.exports = {
|
|
264
|
+
GET
|
|
265
|
+
});
|
|
266
|
+
//# sourceMappingURL=okf-graph-route.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/dashboard/routes/okf-graph-route.ts","../../../src/core/mdx-reader.ts","../../../src/core/markdown-renderer.ts","../../../src/okf/okf-bundle.ts","../../../src/dashboard/auth.ts","../../../src/dashboard/admin-store.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from 'next/server'\nimport path from 'path'\nimport { MdxReader } from '../../core/mdx-reader.js'\nimport { buildOkfGraph } from '../../okf/okf-bundle.js'\nimport { checkApiAuth, unauthorizedResponse } from '../auth.js'\n\nconst reader = new MdxReader({ contentDir: path.join(process.cwd(), process.env.TA_CONTENT_DIR ?? 'content') })\n\n/** GET /api/third-audience/okf-graph — returns graph JSON for the OKF dashboard viewer */\nexport async function GET(req: NextRequest): Promise<NextResponse> {\n if (!checkApiAuth(req)) return unauthorizedResponse()\n\n const baseUrl = process.env.NEXT_PUBLIC_SITE_URL\n ?? `${req.nextUrl.protocol}//${req.nextUrl.host}`\n\n const files = reader.readAll()\n const graph = buildOkfGraph(files, baseUrl)\n\n return NextResponse.json({\n graph,\n stats: {\n pages: files.length,\n nodes: graph.nodes.length,\n edges: graph.edges.length,\n },\n indexUrl: `${baseUrl}/okf`,\n })\n}\n","import fs from 'fs'\nimport path from 'path'\nimport matter from 'gray-matter'\n\nexport interface MdxFile {\n slug: string // relative path without extension, e.g. 'blog/my-post'\n filePath: string // absolute path to .mdx file\n frontmatter: Record<string, unknown>\n rawContent: string // body after frontmatter\n}\n\nexport interface MdxReaderOptions {\n contentDir: string // absolute path to content directory\n}\n\nexport class MdxReader {\n private contentDir: string\n\n constructor(options: MdxReaderOptions) {\n this.contentDir = options.contentDir\n }\n\n /** Read a single MDX file by slug. Returns null if not found. */\n read(slug: string): MdxFile | null {\n const candidates = [\n path.join(this.contentDir, `${slug}.mdx`),\n path.join(this.contentDir, `${slug}.md`),\n path.join(this.contentDir, slug, 'index.mdx'),\n path.join(this.contentDir, slug, 'index.md'),\n ]\n\n for (const filePath of candidates) {\n if (fs.existsSync(filePath)) {\n return this.parseFile(slug, filePath)\n }\n }\n\n return null\n }\n\n /** Read all MDX files recursively. */\n readAll(): MdxFile[] {\n if (!fs.existsSync(this.contentDir)) return []\n return this.walkDir(this.contentDir, this.contentDir)\n }\n\n private walkDir(dir: string, root: string): MdxFile[] {\n const results: MdxFile[] = []\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const fullPath = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n results.push(...this.walkDir(fullPath, root))\n } else if (entry.name.endsWith('.mdx') || entry.name.endsWith('.md')) {\n const relative = path.relative(root, fullPath)\n const slug = relative.replace(/\\.(mdx|md)$/, '').replace(/\\/index$/, '')\n results.push(this.parseFile(slug, fullPath))\n }\n }\n return results\n }\n\n private parseFile(slug: string, filePath: string): MdxFile {\n const raw = fs.readFileSync(filePath, 'utf-8')\n const { data: frontmatter, content: rawContent } = matter(raw)\n return { slug, filePath, frontmatter, rawContent }\n }\n}\n","import type { MdxFile } from './mdx-reader.js'\n\n/**\n * Strips JSX from MDX content and returns clean Markdown\n * suitable for AI crawlers.\n *\n * Removes:\n * - import/export statements\n * - JSX component tags (<ComponentName ... /> and <ComponentName>...</ComponentName>)\n * - Inline expressions {variable} that aren't standard Markdown\n *\n * Preserves:\n * - All standard Markdown (headings, lists, code blocks, links, images)\n * - Frontmatter (serialized as YAML header)\n */\nexport class MarkdownRenderer {\n render(file: MdxFile): string {\n const header = this.buildFrontmatterHeader(file.frontmatter)\n const body = this.stripJsx(file.rawContent)\n return header ? `${header}\\n\\n${body}` : body\n }\n\n private buildFrontmatterHeader(fm: Record<string, unknown>): string {\n const keys = Object.keys(fm)\n if (keys.length === 0) return ''\n const lines = keys\n .filter(k => fm[k] !== undefined && fm[k] !== null)\n .map(k => `${k}: ${this.yamlValue(fm[k])}`)\n return `---\\n${lines.join('\\n')}\\n---`\n }\n\n private yamlValue(val: unknown): string {\n if (typeof val === 'string') {\n // Quote strings containing special YAML chars\n return /[:#\\[\\]{},&*?|<>=!%@`]/.test(val) ? `\"${val.replace(/\"/g, '\\\\\"')}\"` : val\n }\n if (val instanceof Date) return val.toISOString()\n if (Array.isArray(val)) return `[${val.map(v => this.yamlValue(v)).join(', ')}]`\n return String(val)\n }\n\n private stripJsx(content: string): string {\n let out = content\n\n // Remove import statements: import Foo from '...' / import { Foo } from '...'\n out = out.replace(/^import\\s+.*?['\"].*?['\"]\\s*\\n?/gm, '')\n\n // Remove export statements at line start (export const, export default, export { })\n out = out.replace(/^export\\s+(?:default\\s+)?(?:const|let|var|function|class)\\s+[\\s\\S]*?(?=\\n(?=[^{]|\\n)|\\n{2,})/gm, '')\n out = out.replace(/^export\\s*\\{[^}]*\\}\\s*(?:from\\s+['\"][^'\"]*['\"])?\\s*\\n?/gm, '')\n\n // Remove self-closing JSX tags: <Component ... />\n // Must not match HTML img/br/hr which are valid Markdown\n out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*\\/>/g, '')\n\n // Remove JSX block tags: <Component ...>...</Component>\n // Greedy but bounded by matching closing tag\n out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*>[\\s\\S]*?<\\/\\1>/g, '')\n\n // Remove JSX expression blocks { expression } that span a whole line\n out = out.replace(/^\\s*\\{[^}]+\\}\\s*\\n/gm, '')\n\n // Collapse multiple blank lines to two\n out = out.replace(/\\n{3,}/g, '\\n\\n')\n\n return out.trim()\n }\n}\n","import type { MdxFile } from '../core/mdx-reader.js'\nimport { MarkdownRenderer } from '../core/markdown-renderer.js'\n\nconst renderer = new MarkdownRenderer()\n\nexport interface OkfGraphNode {\n id: string\n title: string\n type: string\n url: string\n}\n\nexport interface OkfGraphEdge {\n source: string\n target: string\n}\n\nexport interface OkfGraphData {\n nodes: OkfGraphNode[]\n edges: OkfGraphEdge[]\n}\n\n/**\n * Builds the knowledge graph data for the OKF viewer.\n * Nodes = content pages; edges = internal links between them.\n * Trims to top 100 most-connected nodes (matching WP plugin behaviour).\n */\nexport function buildOkfGraph(files: MdxFile[], baseUrl: string): OkfGraphData {\n const base = baseUrl.replace(/\\/$/, '')\n const slugSet = new Set(files.map(f => f.slug))\n\n // Build slug → markdown map for link extraction\n const mdMap = new Map<string, string>()\n for (const file of files) {\n mdMap.set(file.slug, renderer.render(file))\n }\n\n // Count degrees to pick top 100\n const degrees = new Map<string, number>(files.map(f => [f.slug, 0]))\n const rawEdges: OkfGraphEdge[] = []\n\n for (const file of files) {\n const md = mdMap.get(file.slug) ?? ''\n const linkRe = /\\[([^\\]]+)\\]\\((\\/[^)]+)\\)/g\n let m: RegExpExecArray | null\n while ((m = linkRe.exec(md)) !== null) {\n const candidate = m[2].replace(/^\\//, '').replace(/\\.md$/, '')\n if (slugSet.has(candidate) && candidate !== file.slug) {\n rawEdges.push({ source: file.slug, target: candidate })\n degrees.set(file.slug, (degrees.get(file.slug) ?? 0) + 1)\n degrees.set(candidate, (degrees.get(candidate) ?? 0) + 1)\n }\n }\n }\n\n // Top 100 nodes by degree\n const top100 = files\n .slice()\n .sort((a, b) => (degrees.get(b.slug) ?? 0) - (degrees.get(a.slug) ?? 0))\n .slice(0, 100)\n const topSet = new Set(top100.map(f => f.slug))\n\n const nodes: OkfGraphNode[] = top100.map(f => ({\n id: f.slug,\n title: String(f.frontmatter.title ?? f.slug),\n type: String(f.frontmatter.type ?? 'WebPage'),\n url: `${base}/${f.slug}`,\n }))\n\n const edges = rawEdges.filter(e => topSet.has(e.source) && topSet.has(e.target))\n\n return { nodes, edges }\n}\n\n/** Generates the /okf/index.md manifest listing all content. */\nexport function generateOkfIndex(files: MdxFile[], baseUrl: string): string {\n const base = baseUrl.replace(/\\/$/, '')\n const lines = [\n '# Open Knowledge Format (OKF) Bundle',\n '',\n 'This bundle contains all content as clean Markdown files for AI consumption.',\n '',\n '## Contents',\n '',\n ]\n\n for (const file of files) {\n const fm = file.frontmatter\n const title = String(fm.title ?? file.slug)\n const desc = fm.description ? ` — ${String(fm.description)}` : ''\n lines.push(`- [${title}](${base}/okf/${file.slug}.md)${desc}`)\n }\n\n return lines.join('\\n') + '\\n'\n}\n\n/** Renders a single MDX file for OKF, with internal links rewritten to .md siblings. */\nexport function generateOkfPage(file: MdxFile, allFiles: MdxFile[], baseUrl: string): string {\n const markdown = renderer.render(file)\n return rewriteInternalLinks(markdown, allFiles, baseUrl)\n}\n\n/**\n * Rewrites internal links to point at sibling .md files in the OKF bundle.\n * e.g. [link](/blog/post) → [link](/okf/blog/post.md)\n */\nfunction rewriteInternalLinks(markdown: string, allFiles: MdxFile[], baseUrl: string): string {\n const slugSet = new Set(allFiles.map(f => f.slug))\n const base = baseUrl.replace(/\\/$/, '')\n\n return markdown.replace(/\\[([^\\]]+)\\]\\((\\/[^)]+)\\)/g, (match, text, href) => {\n // Strip leading slash and any trailing .md to get candidate slug\n const candidate = href.replace(/^\\//, '').replace(/\\.md$/, '')\n if (slugSet.has(candidate)) {\n return `[${text}](${base}/okf/${candidate}.md)`\n }\n return match\n })\n}\n","import type { NextRequest } from 'next/server'\nimport { NextResponse } from 'next/server'\nimport { verifySession, verifyApiKey } from './admin-store.js'\n\nconst SESSION_COOKIE = 'ta_session'\n\n/**\n * Authenticate an API route request. Accepts (in order):\n * 1. X-TA-Api-Key header — for headless/external callers (mirrors WP's approach)\n * 2. Authorization: Bearer <api-key> — same key, different transport\n * 3. Valid ta_session cookie — browser dashboard session\n */\nexport function checkApiAuth(req: NextRequest): boolean {\n // 1. X-TA-Api-Key header (WP-style headless key)\n const apiKeyHeader = req.headers.get('x-ta-api-key')\n if (apiKeyHeader) return verifyApiKey(apiKeyHeader)\n\n // 2. Bearer token (treat as api key)\n const auth = req.headers.get('authorization') ?? ''\n if (auth.startsWith('Bearer ')) {\n const token = auth.slice(7)\n return verifyApiKey(token)\n }\n\n // 3. Browser session cookie\n const session = req.cookies.get(SESSION_COOKIE)?.value\n if (session) return verifySession(session)\n\n return false\n}\n\n/**\n * Returns a 401 JSON response with the correct WWW-Authenticate header.\n * Use as: if (!checkApiAuth(req)) return unauthorizedResponse()\n */\nexport function unauthorizedResponse(): NextResponse {\n return NextResponse.json(\n { error: 'Unauthorized. Provide X-TA-Api-Key header or a valid session cookie.' },\n {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer realm=\"Third Audience API\"' },\n }\n )\n}\n","import fs from 'fs'\nimport path from 'path'\nimport crypto from 'crypto'\n\nexport interface AdminRecord {\n passwordHash: string // sha256(secret + password)\n isDefaultPassword: boolean\n createdAt: string\n lastLoginAt: string | null\n apiKey?: string // AES-256-GCM encrypted, for headless/external API callers\n}\n\nfunction adminFilePath(): string {\n const dataDir = process.env.TA_DATA_DIR ?? 'data'\n return path.join(process.cwd(), dataDir, 'ta-admin.json')\n}\n\nexport function generateDefaultPassword(): string {\n return crypto.randomBytes(6).toString('hex') // 12-char hex, easy to type\n}\n\nexport function hashPassword(password: string): string {\n const secret = process.env.THIRD_AUDIENCE_SECRET ?? 'ta-salt'\n return crypto.createHash('sha256').update(secret + password).digest('hex')\n}\n\nexport function loadAdmin(): AdminRecord | null {\n const filePath = adminFilePath()\n if (!fs.existsSync(filePath)) return null\n try {\n return JSON.parse(fs.readFileSync(filePath, 'utf-8')) as AdminRecord\n } catch {\n return null\n }\n}\n\nexport function saveAdmin(record: AdminRecord): void {\n const filePath = adminFilePath()\n const dir = path.dirname(filePath)\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })\n fs.writeFileSync(filePath, JSON.stringify(record, null, 2), 'utf-8')\n}\n\nexport const DEFAULT_PASSWORD = 'Chang3M3Now!'\n\nexport function initAdmin(): { password: string; apiKey: string; isNew: boolean } {\n const existing = loadAdmin()\n if (existing) return { password: '', apiKey: '', isNew: false }\n\n const apiKey = generateApiKey()\n saveAdmin({\n passwordHash: hashPassword(DEFAULT_PASSWORD),\n isDefaultPassword: true,\n createdAt: new Date().toISOString(),\n lastLoginAt: null,\n apiKey: encryptApiKey(apiKey),\n })\n return { password: DEFAULT_PASSWORD, apiKey, isNew: true }\n}\n\nexport function verifyPassword(password: string): boolean {\n const record = loadAdmin()\n if (!record) return false\n return record.passwordHash === hashPassword(password)\n}\n\nexport function updatePassword(newPassword: string): void {\n const record = loadAdmin()\n if (!record) return\n saveAdmin({\n ...record,\n passwordHash: hashPassword(newPassword),\n isDefaultPassword: false,\n })\n}\n\nexport function recordLogin(): void {\n const record = loadAdmin()\n if (!record) return\n saveAdmin({ ...record, lastLoginAt: new Date().toISOString() })\n}\n\n// ---------------------------------------------------------------------------\n// API key — AES-256-GCM encrypted at rest, mirroring WP's SECURE_AUTH_KEY approach\n// ---------------------------------------------------------------------------\n\nconst CIPHER = 'aes-256-gcm'\n\nfunction getEncryptionKey(): Buffer {\n const secret = process.env.THIRD_AUDIENCE_SECRET ?? 'ta-fallback-key-change-me'\n // Derive a 32-byte key from the secret using SHA-256\n return crypto.createHash('sha256').update(secret).digest()\n}\n\nfunction encryptApiKey(plaintext: string): string {\n const iv = crypto.randomBytes(12)\n const key = getEncryptionKey()\n const cipher = crypto.createCipheriv(CIPHER, key, iv) as crypto.CipherGCM\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n // Format: iv(24 hex) + tag(32 hex) + encrypted(hex)\n return iv.toString('hex') + tag.toString('hex') + encrypted.toString('hex')\n}\n\nfunction decryptApiKey(encoded: string): string | null {\n try {\n const iv = Buffer.from(encoded.slice(0, 24), 'hex')\n const tag = Buffer.from(encoded.slice(24, 56), 'hex')\n const encrypted = Buffer.from(encoded.slice(56), 'hex')\n const key = getEncryptionKey()\n const decipher = crypto.createDecipheriv(CIPHER, key, iv) as crypto.DecipherGCM\n decipher.setAuthTag(tag)\n return decipher.update(encrypted) + decipher.final('utf8')\n } catch {\n return null\n }\n}\n\nexport function generateApiKey(): string {\n return 'ta_' + crypto.randomBytes(24).toString('hex') // 51-char key\n}\n\nexport function getApiKey(): string | null {\n const record = loadAdmin()\n if (!record?.apiKey) return null\n return decryptApiKey(record.apiKey)\n}\n\nexport function rotateApiKey(): string {\n const record = loadAdmin()\n if (!record) throw new Error('Admin store not initialised')\n const newKey = generateApiKey()\n saveAdmin({ ...record, apiKey: encryptApiKey(newKey) })\n return newKey\n}\n\nexport function verifyApiKey(key: string): boolean {\n const stored = getApiKey()\n if (!stored) return false\n if (key.length !== stored.length) return false\n return crypto.timingSafeEqual(Buffer.from(key), Buffer.from(stored))\n}\n\n// ---------------------------------------------------------------------------\n// Session cookie: HMAC-SHA256(secret, userId + timestamp) — stateless, no DB\n// ---------------------------------------------------------------------------\nexport function signSession(payload: string): string {\n const secret = process.env.THIRD_AUDIENCE_SECRET ?? 'ta-salt'\n const sig = crypto.createHmac('sha256', secret).update(payload).digest('hex')\n return `${payload}.${sig}`\n}\n\nexport function verifySession(token: string): boolean {\n const lastDot = token.lastIndexOf('.')\n if (lastDot === -1) return false\n const payload = token.slice(0, lastDot)\n const sig = token.slice(lastDot + 1)\n const expected = crypto.createHmac('sha256', process.env.THIRD_AUDIENCE_SECRET ?? 'ta-salt')\n .update(payload).digest('hex')\n // Constant-time comparison\n if (sig.length !== expected.length) return false\n return crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,iBAA+C;AAC/C,IAAAC,eAAiB;;;ACDjB,gBAAe;AACf,kBAAiB;AACjB,yBAAmB;AAaZ,IAAM,YAAN,MAAgB;AAAA,EAGrB,YAAY,SAA2B;AACrC,SAAK,aAAa,QAAQ;AAAA,EAC5B;AAAA;AAAA,EAGA,KAAK,MAA8B;AACjC,UAAM,aAAa;AAAA,MACjB,YAAAC,QAAK,KAAK,KAAK,YAAY,GAAG,IAAI,MAAM;AAAA,MACxC,YAAAA,QAAK,KAAK,KAAK,YAAY,GAAG,IAAI,KAAK;AAAA,MACvC,YAAAA,QAAK,KAAK,KAAK,YAAY,MAAM,WAAW;AAAA,MAC5C,YAAAA,QAAK,KAAK,KAAK,YAAY,MAAM,UAAU;AAAA,IAC7C;AAEA,eAAW,YAAY,YAAY;AACjC,UAAI,UAAAC,QAAG,WAAW,QAAQ,GAAG;AAC3B,eAAO,KAAK,UAAU,MAAM,QAAQ;AAAA,MACtC;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,UAAqB;AACnB,QAAI,CAAC,UAAAA,QAAG,WAAW,KAAK,UAAU,EAAG,QAAO,CAAC;AAC7C,WAAO,KAAK,QAAQ,KAAK,YAAY,KAAK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,qBAAqB;AAEpD,QAAM,UAAU,QAAQ,IAAI,wBACvB,GAAG,IAAI,QAAQ,QAAQ,KAAK,IAAI,QAAQ,IAAI;AAEjD,QAAM,QAAQ,OAAO,QAAQ;AAC7B,QAAM,QAAQ,cAAc,OAAO,OAAO;AAE1C,SAAO,4BAAa,KAAK;AAAA,IACvB;AAAA,IACA,OAAO;AAAA,MACL,OAAO,MAAM;AAAA,MACb,OAAO,MAAM,MAAM;AAAA,MACnB,OAAO,MAAM,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,GAAG,OAAO;AAAA,EACtB,CAAC;AACH;","names":["import_server","import_path","path","fs","matter","import_fs","import_path","path","fs","crypto","crypto","crypto","crypto","path"]}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// src/dashboard/routes/okf-graph-route.ts
|
|
2
|
+
import { NextResponse as NextResponse2 } from "next/server";
|
|
3
|
+
import path3 from "path";
|
|
4
|
+
|
|
5
|
+
// src/core/mdx-reader.ts
|
|
6
|
+
import fs from "fs";
|
|
7
|
+
import path from "path";
|
|
8
|
+
import matter from "gray-matter";
|
|
9
|
+
var MdxReader = class {
|
|
10
|
+
constructor(options) {
|
|
11
|
+
this.contentDir = options.contentDir;
|
|
12
|
+
}
|
|
13
|
+
/** Read a single MDX file by slug. Returns null if not found. */
|
|
14
|
+
read(slug) {
|
|
15
|
+
const candidates = [
|
|
16
|
+
path.join(this.contentDir, `${slug}.mdx`),
|
|
17
|
+
path.join(this.contentDir, `${slug}.md`),
|
|
18
|
+
path.join(this.contentDir, slug, "index.mdx"),
|
|
19
|
+
path.join(this.contentDir, slug, "index.md")
|
|
20
|
+
];
|
|
21
|
+
for (const filePath of candidates) {
|
|
22
|
+
if (fs.existsSync(filePath)) {
|
|
23
|
+
return this.parseFile(slug, filePath);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
/** Read all MDX files recursively. */
|
|
29
|
+
readAll() {
|
|
30
|
+
if (!fs.existsSync(this.contentDir)) return [];
|
|
31
|
+
return this.walkDir(this.contentDir, this.contentDir);
|
|
32
|
+
}
|
|
33
|
+
walkDir(dir, root) {
|
|
34
|
+
const results = [];
|
|
35
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
36
|
+
const fullPath = path.join(dir, entry.name);
|
|
37
|
+
if (entry.isDirectory()) {
|
|
38
|
+
results.push(...this.walkDir(fullPath, root));
|
|
39
|
+
} else if (entry.name.endsWith(".mdx") || entry.name.endsWith(".md")) {
|
|
40
|
+
const relative = path.relative(root, fullPath);
|
|
41
|
+
const slug = relative.replace(/\.(mdx|md)$/, "").replace(/\/index$/, "");
|
|
42
|
+
results.push(this.parseFile(slug, fullPath));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return results;
|
|
46
|
+
}
|
|
47
|
+
parseFile(slug, filePath) {
|
|
48
|
+
const raw = fs.readFileSync(filePath, "utf-8");
|
|
49
|
+
const { data: frontmatter, content: rawContent } = matter(raw);
|
|
50
|
+
return { slug, filePath, frontmatter, rawContent };
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// src/core/markdown-renderer.ts
|
|
55
|
+
var MarkdownRenderer = class {
|
|
56
|
+
render(file) {
|
|
57
|
+
const header = this.buildFrontmatterHeader(file.frontmatter);
|
|
58
|
+
const body = this.stripJsx(file.rawContent);
|
|
59
|
+
return header ? `${header}
|
|
60
|
+
|
|
61
|
+
${body}` : body;
|
|
62
|
+
}
|
|
63
|
+
buildFrontmatterHeader(fm) {
|
|
64
|
+
const keys = Object.keys(fm);
|
|
65
|
+
if (keys.length === 0) return "";
|
|
66
|
+
const lines = keys.filter((k) => fm[k] !== void 0 && fm[k] !== null).map((k) => `${k}: ${this.yamlValue(fm[k])}`);
|
|
67
|
+
return `---
|
|
68
|
+
${lines.join("\n")}
|
|
69
|
+
---`;
|
|
70
|
+
}
|
|
71
|
+
yamlValue(val) {
|
|
72
|
+
if (typeof val === "string") {
|
|
73
|
+
return /[:#\[\]{},&*?|<>=!%@`]/.test(val) ? `"${val.replace(/"/g, '\\"')}"` : val;
|
|
74
|
+
}
|
|
75
|
+
if (val instanceof Date) return val.toISOString();
|
|
76
|
+
if (Array.isArray(val)) return `[${val.map((v) => this.yamlValue(v)).join(", ")}]`;
|
|
77
|
+
return String(val);
|
|
78
|
+
}
|
|
79
|
+
stripJsx(content) {
|
|
80
|
+
let out = content;
|
|
81
|
+
out = out.replace(/^import\s+.*?['"].*?['"]\s*\n?/gm, "");
|
|
82
|
+
out = out.replace(/^export\s+(?:default\s+)?(?:const|let|var|function|class)\s+[\s\S]*?(?=\n(?=[^{]|\n)|\n{2,})/gm, "");
|
|
83
|
+
out = out.replace(/^export\s*\{[^}]*\}\s*(?:from\s+['"][^'"]*['"])?\s*\n?/gm, "");
|
|
84
|
+
out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*\/>/g, "");
|
|
85
|
+
out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*>[\s\S]*?<\/\1>/g, "");
|
|
86
|
+
out = out.replace(/^\s*\{[^}]+\}\s*\n/gm, "");
|
|
87
|
+
out = out.replace(/\n{3,}/g, "\n\n");
|
|
88
|
+
return out.trim();
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// src/okf/okf-bundle.ts
|
|
93
|
+
var renderer = new MarkdownRenderer();
|
|
94
|
+
function buildOkfGraph(files, baseUrl) {
|
|
95
|
+
const base = baseUrl.replace(/\/$/, "");
|
|
96
|
+
const slugSet = new Set(files.map((f) => f.slug));
|
|
97
|
+
const mdMap = /* @__PURE__ */ new Map();
|
|
98
|
+
for (const file of files) {
|
|
99
|
+
mdMap.set(file.slug, renderer.render(file));
|
|
100
|
+
}
|
|
101
|
+
const degrees = new Map(files.map((f) => [f.slug, 0]));
|
|
102
|
+
const rawEdges = [];
|
|
103
|
+
for (const file of files) {
|
|
104
|
+
const md = mdMap.get(file.slug) ?? "";
|
|
105
|
+
const linkRe = /\[([^\]]+)\]\((\/[^)]+)\)/g;
|
|
106
|
+
let m;
|
|
107
|
+
while ((m = linkRe.exec(md)) !== null) {
|
|
108
|
+
const candidate = m[2].replace(/^\//, "").replace(/\.md$/, "");
|
|
109
|
+
if (slugSet.has(candidate) && candidate !== file.slug) {
|
|
110
|
+
rawEdges.push({ source: file.slug, target: candidate });
|
|
111
|
+
degrees.set(file.slug, (degrees.get(file.slug) ?? 0) + 1);
|
|
112
|
+
degrees.set(candidate, (degrees.get(candidate) ?? 0) + 1);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const top100 = files.slice().sort((a, b) => (degrees.get(b.slug) ?? 0) - (degrees.get(a.slug) ?? 0)).slice(0, 100);
|
|
117
|
+
const topSet = new Set(top100.map((f) => f.slug));
|
|
118
|
+
const nodes = top100.map((f) => ({
|
|
119
|
+
id: f.slug,
|
|
120
|
+
title: String(f.frontmatter.title ?? f.slug),
|
|
121
|
+
type: String(f.frontmatter.type ?? "WebPage"),
|
|
122
|
+
url: `${base}/${f.slug}`
|
|
123
|
+
}));
|
|
124
|
+
const edges = rawEdges.filter((e) => topSet.has(e.source) && topSet.has(e.target));
|
|
125
|
+
return { nodes, edges };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/dashboard/auth.ts
|
|
129
|
+
import { NextResponse } from "next/server";
|
|
130
|
+
|
|
131
|
+
// src/dashboard/admin-store.ts
|
|
132
|
+
import fs2 from "fs";
|
|
133
|
+
import path2 from "path";
|
|
134
|
+
import crypto from "crypto";
|
|
135
|
+
function adminFilePath() {
|
|
136
|
+
const dataDir = process.env.TA_DATA_DIR ?? "data";
|
|
137
|
+
return path2.join(process.cwd(), dataDir, "ta-admin.json");
|
|
138
|
+
}
|
|
139
|
+
function loadAdmin() {
|
|
140
|
+
const filePath = adminFilePath();
|
|
141
|
+
if (!fs2.existsSync(filePath)) return null;
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(fs2.readFileSync(filePath, "utf-8"));
|
|
144
|
+
} catch {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
var CIPHER = "aes-256-gcm";
|
|
149
|
+
function getEncryptionKey() {
|
|
150
|
+
const secret = process.env.THIRD_AUDIENCE_SECRET ?? "ta-fallback-key-change-me";
|
|
151
|
+
return crypto.createHash("sha256").update(secret).digest();
|
|
152
|
+
}
|
|
153
|
+
function decryptApiKey(encoded) {
|
|
154
|
+
try {
|
|
155
|
+
const iv = Buffer.from(encoded.slice(0, 24), "hex");
|
|
156
|
+
const tag = Buffer.from(encoded.slice(24, 56), "hex");
|
|
157
|
+
const encrypted = Buffer.from(encoded.slice(56), "hex");
|
|
158
|
+
const key = getEncryptionKey();
|
|
159
|
+
const decipher = crypto.createDecipheriv(CIPHER, key, iv);
|
|
160
|
+
decipher.setAuthTag(tag);
|
|
161
|
+
return decipher.update(encrypted) + decipher.final("utf8");
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function getApiKey() {
|
|
167
|
+
const record = loadAdmin();
|
|
168
|
+
if (!record?.apiKey) return null;
|
|
169
|
+
return decryptApiKey(record.apiKey);
|
|
170
|
+
}
|
|
171
|
+
function verifyApiKey(key) {
|
|
172
|
+
const stored = getApiKey();
|
|
173
|
+
if (!stored) return false;
|
|
174
|
+
if (key.length !== stored.length) return false;
|
|
175
|
+
return crypto.timingSafeEqual(Buffer.from(key), Buffer.from(stored));
|
|
176
|
+
}
|
|
177
|
+
function verifySession(token) {
|
|
178
|
+
const lastDot = token.lastIndexOf(".");
|
|
179
|
+
if (lastDot === -1) return false;
|
|
180
|
+
const payload = token.slice(0, lastDot);
|
|
181
|
+
const sig = token.slice(lastDot + 1);
|
|
182
|
+
const expected = crypto.createHmac("sha256", process.env.THIRD_AUDIENCE_SECRET ?? "ta-salt").update(payload).digest("hex");
|
|
183
|
+
if (sig.length !== expected.length) return false;
|
|
184
|
+
return crypto.timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(expected, "hex"));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/dashboard/auth.ts
|
|
188
|
+
var SESSION_COOKIE = "ta_session";
|
|
189
|
+
function checkApiAuth(req) {
|
|
190
|
+
const apiKeyHeader = req.headers.get("x-ta-api-key");
|
|
191
|
+
if (apiKeyHeader) return verifyApiKey(apiKeyHeader);
|
|
192
|
+
const auth = req.headers.get("authorization") ?? "";
|
|
193
|
+
if (auth.startsWith("Bearer ")) {
|
|
194
|
+
const token = auth.slice(7);
|
|
195
|
+
return verifyApiKey(token);
|
|
196
|
+
}
|
|
197
|
+
const session = req.cookies.get(SESSION_COOKIE)?.value;
|
|
198
|
+
if (session) return verifySession(session);
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
function unauthorizedResponse() {
|
|
202
|
+
return NextResponse.json(
|
|
203
|
+
{ error: "Unauthorized. Provide X-TA-Api-Key header or a valid session cookie." },
|
|
204
|
+
{
|
|
205
|
+
status: 401,
|
|
206
|
+
headers: { "WWW-Authenticate": 'Bearer realm="Third Audience API"' }
|
|
207
|
+
}
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/dashboard/routes/okf-graph-route.ts
|
|
212
|
+
var reader = new MdxReader({ contentDir: path3.join(process.cwd(), process.env.TA_CONTENT_DIR ?? "content") });
|
|
213
|
+
async function GET(req) {
|
|
214
|
+
if (!checkApiAuth(req)) return unauthorizedResponse();
|
|
215
|
+
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL ?? `${req.nextUrl.protocol}//${req.nextUrl.host}`;
|
|
216
|
+
const files = reader.readAll();
|
|
217
|
+
const graph = buildOkfGraph(files, baseUrl);
|
|
218
|
+
return NextResponse2.json({
|
|
219
|
+
graph,
|
|
220
|
+
stats: {
|
|
221
|
+
pages: files.length,
|
|
222
|
+
nodes: graph.nodes.length,
|
|
223
|
+
edges: graph.edges.length
|
|
224
|
+
},
|
|
225
|
+
indexUrl: `${baseUrl}/okf`
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
export {
|
|
229
|
+
GET
|
|
230
|
+
};
|
|
231
|
+
//# sourceMappingURL=okf-graph-route.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/dashboard/routes/okf-graph-route.ts","../../../src/core/mdx-reader.ts","../../../src/core/markdown-renderer.ts","../../../src/okf/okf-bundle.ts","../../../src/dashboard/auth.ts","../../../src/dashboard/admin-store.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from 'next/server'\nimport path from 'path'\nimport { MdxReader } from '../../core/mdx-reader.js'\nimport { buildOkfGraph } from '../../okf/okf-bundle.js'\nimport { checkApiAuth, unauthorizedResponse } from '../auth.js'\n\nconst reader = new MdxReader({ contentDir: path.join(process.cwd(), process.env.TA_CONTENT_DIR ?? 'content') })\n\n/** GET /api/third-audience/okf-graph — returns graph JSON for the OKF dashboard viewer */\nexport async function GET(req: NextRequest): Promise<NextResponse> {\n if (!checkApiAuth(req)) return unauthorizedResponse()\n\n const baseUrl = process.env.NEXT_PUBLIC_SITE_URL\n ?? `${req.nextUrl.protocol}//${req.nextUrl.host}`\n\n const files = reader.readAll()\n const graph = buildOkfGraph(files, baseUrl)\n\n return NextResponse.json({\n graph,\n stats: {\n pages: files.length,\n nodes: graph.nodes.length,\n edges: graph.edges.length,\n },\n indexUrl: `${baseUrl}/okf`,\n })\n}\n","import fs from 'fs'\nimport path from 'path'\nimport matter from 'gray-matter'\n\nexport interface MdxFile {\n slug: string // relative path without extension, e.g. 'blog/my-post'\n filePath: string // absolute path to .mdx file\n frontmatter: Record<string, unknown>\n rawContent: string // body after frontmatter\n}\n\nexport interface MdxReaderOptions {\n contentDir: string // absolute path to content directory\n}\n\nexport class MdxReader {\n private contentDir: string\n\n constructor(options: MdxReaderOptions) {\n this.contentDir = options.contentDir\n }\n\n /** Read a single MDX file by slug. Returns null if not found. */\n read(slug: string): MdxFile | null {\n const candidates = [\n path.join(this.contentDir, `${slug}.mdx`),\n path.join(this.contentDir, `${slug}.md`),\n path.join(this.contentDir, slug, 'index.mdx'),\n path.join(this.contentDir, slug, 'index.md'),\n ]\n\n for (const filePath of candidates) {\n if (fs.existsSync(filePath)) {\n return this.parseFile(slug, filePath)\n }\n }\n\n return null\n }\n\n /** Read all MDX files recursively. */\n readAll(): MdxFile[] {\n if (!fs.existsSync(this.contentDir)) return []\n return this.walkDir(this.contentDir, this.contentDir)\n }\n\n private walkDir(dir: string, root: string): MdxFile[] {\n const results: MdxFile[] = []\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const fullPath = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n results.push(...this.walkDir(fullPath, root))\n } else if (entry.name.endsWith('.mdx') || entry.name.endsWith('.md')) {\n const relative = path.relative(root, fullPath)\n const slug = relative.replace(/\\.(mdx|md)$/, '').replace(/\\/index$/, '')\n results.push(this.parseFile(slug, fullPath))\n }\n }\n return results\n }\n\n private parseFile(slug: string, filePath: string): MdxFile {\n const raw = fs.readFileSync(filePath, 'utf-8')\n const { data: frontmatter, content: rawContent } = matter(raw)\n return { slug, filePath, frontmatter, rawContent }\n }\n}\n","import type { MdxFile } from './mdx-reader.js'\n\n/**\n * Strips JSX from MDX content and returns clean Markdown\n * suitable for AI crawlers.\n *\n * Removes:\n * - import/export statements\n * - JSX component tags (<ComponentName ... /> and <ComponentName>...</ComponentName>)\n * - Inline expressions {variable} that aren't standard Markdown\n *\n * Preserves:\n * - All standard Markdown (headings, lists, code blocks, links, images)\n * - Frontmatter (serialized as YAML header)\n */\nexport class MarkdownRenderer {\n render(file: MdxFile): string {\n const header = this.buildFrontmatterHeader(file.frontmatter)\n const body = this.stripJsx(file.rawContent)\n return header ? `${header}\\n\\n${body}` : body\n }\n\n private buildFrontmatterHeader(fm: Record<string, unknown>): string {\n const keys = Object.keys(fm)\n if (keys.length === 0) return ''\n const lines = keys\n .filter(k => fm[k] !== undefined && fm[k] !== null)\n .map(k => `${k}: ${this.yamlValue(fm[k])}`)\n return `---\\n${lines.join('\\n')}\\n---`\n }\n\n private yamlValue(val: unknown): string {\n if (typeof val === 'string') {\n // Quote strings containing special YAML chars\n return /[:#\\[\\]{},&*?|<>=!%@`]/.test(val) ? `\"${val.replace(/\"/g, '\\\\\"')}\"` : val\n }\n if (val instanceof Date) return val.toISOString()\n if (Array.isArray(val)) return `[${val.map(v => this.yamlValue(v)).join(', ')}]`\n return String(val)\n }\n\n private stripJsx(content: string): string {\n let out = content\n\n // Remove import statements: import Foo from '...' / import { Foo } from '...'\n out = out.replace(/^import\\s+.*?['\"].*?['\"]\\s*\\n?/gm, '')\n\n // Remove export statements at line start (export const, export default, export { })\n out = out.replace(/^export\\s+(?:default\\s+)?(?:const|let|var|function|class)\\s+[\\s\\S]*?(?=\\n(?=[^{]|\\n)|\\n{2,})/gm, '')\n out = out.replace(/^export\\s*\\{[^}]*\\}\\s*(?:from\\s+['\"][^'\"]*['\"])?\\s*\\n?/gm, '')\n\n // Remove self-closing JSX tags: <Component ... />\n // Must not match HTML img/br/hr which are valid Markdown\n out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*\\/>/g, '')\n\n // Remove JSX block tags: <Component ...>...</Component>\n // Greedy but bounded by matching closing tag\n out = out.replace(/<([A-Z][A-Za-z0-9.]*)[^>]*>[\\s\\S]*?<\\/\\1>/g, '')\n\n // Remove JSX expression blocks { expression } that span a whole line\n out = out.replace(/^\\s*\\{[^}]+\\}\\s*\\n/gm, '')\n\n // Collapse multiple blank lines to two\n out = out.replace(/\\n{3,}/g, '\\n\\n')\n\n return out.trim()\n }\n}\n","import type { MdxFile } from '../core/mdx-reader.js'\nimport { MarkdownRenderer } from '../core/markdown-renderer.js'\n\nconst renderer = new MarkdownRenderer()\n\nexport interface OkfGraphNode {\n id: string\n title: string\n type: string\n url: string\n}\n\nexport interface OkfGraphEdge {\n source: string\n target: string\n}\n\nexport interface OkfGraphData {\n nodes: OkfGraphNode[]\n edges: OkfGraphEdge[]\n}\n\n/**\n * Builds the knowledge graph data for the OKF viewer.\n * Nodes = content pages; edges = internal links between them.\n * Trims to top 100 most-connected nodes (matching WP plugin behaviour).\n */\nexport function buildOkfGraph(files: MdxFile[], baseUrl: string): OkfGraphData {\n const base = baseUrl.replace(/\\/$/, '')\n const slugSet = new Set(files.map(f => f.slug))\n\n // Build slug → markdown map for link extraction\n const mdMap = new Map<string, string>()\n for (const file of files) {\n mdMap.set(file.slug, renderer.render(file))\n }\n\n // Count degrees to pick top 100\n const degrees = new Map<string, number>(files.map(f => [f.slug, 0]))\n const rawEdges: OkfGraphEdge[] = []\n\n for (const file of files) {\n const md = mdMap.get(file.slug) ?? ''\n const linkRe = /\\[([^\\]]+)\\]\\((\\/[^)]+)\\)/g\n let m: RegExpExecArray | null\n while ((m = linkRe.exec(md)) !== null) {\n const candidate = m[2].replace(/^\\//, '').replace(/\\.md$/, '')\n if (slugSet.has(candidate) && candidate !== file.slug) {\n rawEdges.push({ source: file.slug, target: candidate })\n degrees.set(file.slug, (degrees.get(file.slug) ?? 0) + 1)\n degrees.set(candidate, (degrees.get(candidate) ?? 0) + 1)\n }\n }\n }\n\n // Top 100 nodes by degree\n const top100 = files\n .slice()\n .sort((a, b) => (degrees.get(b.slug) ?? 0) - (degrees.get(a.slug) ?? 0))\n .slice(0, 100)\n const topSet = new Set(top100.map(f => f.slug))\n\n const nodes: OkfGraphNode[] = top100.map(f => ({\n id: f.slug,\n title: String(f.frontmatter.title ?? f.slug),\n type: String(f.frontmatter.type ?? 'WebPage'),\n url: `${base}/${f.slug}`,\n }))\n\n const edges = rawEdges.filter(e => topSet.has(e.source) && topSet.has(e.target))\n\n return { nodes, edges }\n}\n\n/** Generates the /okf/index.md manifest listing all content. */\nexport function generateOkfIndex(files: MdxFile[], baseUrl: string): string {\n const base = baseUrl.replace(/\\/$/, '')\n const lines = [\n '# Open Knowledge Format (OKF) Bundle',\n '',\n 'This bundle contains all content as clean Markdown files for AI consumption.',\n '',\n '## Contents',\n '',\n ]\n\n for (const file of files) {\n const fm = file.frontmatter\n const title = String(fm.title ?? file.slug)\n const desc = fm.description ? ` — ${String(fm.description)}` : ''\n lines.push(`- [${title}](${base}/okf/${file.slug}.md)${desc}`)\n }\n\n return lines.join('\\n') + '\\n'\n}\n\n/** Renders a single MDX file for OKF, with internal links rewritten to .md siblings. */\nexport function generateOkfPage(file: MdxFile, allFiles: MdxFile[], baseUrl: string): string {\n const markdown = renderer.render(file)\n return rewriteInternalLinks(markdown, allFiles, baseUrl)\n}\n\n/**\n * Rewrites internal links to point at sibling .md files in the OKF bundle.\n * e.g. [link](/blog/post) → [link](/okf/blog/post.md)\n */\nfunction rewriteInternalLinks(markdown: string, allFiles: MdxFile[], baseUrl: string): string {\n const slugSet = new Set(allFiles.map(f => f.slug))\n const base = baseUrl.replace(/\\/$/, '')\n\n return markdown.replace(/\\[([^\\]]+)\\]\\((\\/[^)]+)\\)/g, (match, text, href) => {\n // Strip leading slash and any trailing .md to get candidate slug\n const candidate = href.replace(/^\\//, '').replace(/\\.md$/, '')\n if (slugSet.has(candidate)) {\n return `[${text}](${base}/okf/${candidate}.md)`\n }\n return match\n })\n}\n","import type { NextRequest } from 'next/server'\nimport { NextResponse } from 'next/server'\nimport { verifySession, verifyApiKey } from './admin-store.js'\n\nconst SESSION_COOKIE = 'ta_session'\n\n/**\n * Authenticate an API route request. Accepts (in order):\n * 1. X-TA-Api-Key header — for headless/external callers (mirrors WP's approach)\n * 2. Authorization: Bearer <api-key> — same key, different transport\n * 3. Valid ta_session cookie — browser dashboard session\n */\nexport function checkApiAuth(req: NextRequest): boolean {\n // 1. X-TA-Api-Key header (WP-style headless key)\n const apiKeyHeader = req.headers.get('x-ta-api-key')\n if (apiKeyHeader) return verifyApiKey(apiKeyHeader)\n\n // 2. Bearer token (treat as api key)\n const auth = req.headers.get('authorization') ?? ''\n if (auth.startsWith('Bearer ')) {\n const token = auth.slice(7)\n return verifyApiKey(token)\n }\n\n // 3. Browser session cookie\n const session = req.cookies.get(SESSION_COOKIE)?.value\n if (session) return verifySession(session)\n\n return false\n}\n\n/**\n * Returns a 401 JSON response with the correct WWW-Authenticate header.\n * Use as: if (!checkApiAuth(req)) return unauthorizedResponse()\n */\nexport function unauthorizedResponse(): NextResponse {\n return NextResponse.json(\n { error: 'Unauthorized. Provide X-TA-Api-Key header or a valid session cookie.' },\n {\n status: 401,\n headers: { 'WWW-Authenticate': 'Bearer realm=\"Third Audience API\"' },\n }\n )\n}\n","import fs from 'fs'\nimport path from 'path'\nimport crypto from 'crypto'\n\nexport interface AdminRecord {\n passwordHash: string // sha256(secret + password)\n isDefaultPassword: boolean\n createdAt: string\n lastLoginAt: string | null\n apiKey?: string // AES-256-GCM encrypted, for headless/external API callers\n}\n\nfunction adminFilePath(): string {\n const dataDir = process.env.TA_DATA_DIR ?? 'data'\n return path.join(process.cwd(), dataDir, 'ta-admin.json')\n}\n\nexport function generateDefaultPassword(): string {\n return crypto.randomBytes(6).toString('hex') // 12-char hex, easy to type\n}\n\nexport function hashPassword(password: string): string {\n const secret = process.env.THIRD_AUDIENCE_SECRET ?? 'ta-salt'\n return crypto.createHash('sha256').update(secret + password).digest('hex')\n}\n\nexport function loadAdmin(): AdminRecord | null {\n const filePath = adminFilePath()\n if (!fs.existsSync(filePath)) return null\n try {\n return JSON.parse(fs.readFileSync(filePath, 'utf-8')) as AdminRecord\n } catch {\n return null\n }\n}\n\nexport function saveAdmin(record: AdminRecord): void {\n const filePath = adminFilePath()\n const dir = path.dirname(filePath)\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })\n fs.writeFileSync(filePath, JSON.stringify(record, null, 2), 'utf-8')\n}\n\nexport const DEFAULT_PASSWORD = 'Chang3M3Now!'\n\nexport function initAdmin(): { password: string; apiKey: string; isNew: boolean } {\n const existing = loadAdmin()\n if (existing) return { password: '', apiKey: '', isNew: false }\n\n const apiKey = generateApiKey()\n saveAdmin({\n passwordHash: hashPassword(DEFAULT_PASSWORD),\n isDefaultPassword: true,\n createdAt: new Date().toISOString(),\n lastLoginAt: null,\n apiKey: encryptApiKey(apiKey),\n })\n return { password: DEFAULT_PASSWORD, apiKey, isNew: true }\n}\n\nexport function verifyPassword(password: string): boolean {\n const record = loadAdmin()\n if (!record) return false\n return record.passwordHash === hashPassword(password)\n}\n\nexport function updatePassword(newPassword: string): void {\n const record = loadAdmin()\n if (!record) return\n saveAdmin({\n ...record,\n passwordHash: hashPassword(newPassword),\n isDefaultPassword: false,\n })\n}\n\nexport function recordLogin(): void {\n const record = loadAdmin()\n if (!record) return\n saveAdmin({ ...record, lastLoginAt: new Date().toISOString() })\n}\n\n// ---------------------------------------------------------------------------\n// API key — AES-256-GCM encrypted at rest, mirroring WP's SECURE_AUTH_KEY approach\n// ---------------------------------------------------------------------------\n\nconst CIPHER = 'aes-256-gcm'\n\nfunction getEncryptionKey(): Buffer {\n const secret = process.env.THIRD_AUDIENCE_SECRET ?? 'ta-fallback-key-change-me'\n // Derive a 32-byte key from the secret using SHA-256\n return crypto.createHash('sha256').update(secret).digest()\n}\n\nfunction encryptApiKey(plaintext: string): string {\n const iv = crypto.randomBytes(12)\n const key = getEncryptionKey()\n const cipher = crypto.createCipheriv(CIPHER, key, iv) as crypto.CipherGCM\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n // Format: iv(24 hex) + tag(32 hex) + encrypted(hex)\n return iv.toString('hex') + tag.toString('hex') + encrypted.toString('hex')\n}\n\nfunction decryptApiKey(encoded: string): string | null {\n try {\n const iv = Buffer.from(encoded.slice(0, 24), 'hex')\n const tag = Buffer.from(encoded.slice(24, 56), 'hex')\n const encrypted = Buffer.from(encoded.slice(56), 'hex')\n const key = getEncryptionKey()\n const decipher = crypto.createDecipheriv(CIPHER, key, iv) as crypto.DecipherGCM\n decipher.setAuthTag(tag)\n return decipher.update(encrypted) + decipher.final('utf8')\n } catch {\n return null\n }\n}\n\nexport function generateApiKey(): string {\n return 'ta_' + crypto.randomBytes(24).toString('hex') // 51-char key\n}\n\nexport function getApiKey(): string | null {\n const record = loadAdmin()\n if (!record?.apiKey) return null\n return decryptApiKey(record.apiKey)\n}\n\nexport function rotateApiKey(): string {\n const record = loadAdmin()\n if (!record) throw new Error('Admin store not initialised')\n const newKey = generateApiKey()\n saveAdmin({ ...record, apiKey: encryptApiKey(newKey) })\n return newKey\n}\n\nexport function verifyApiKey(key: string): boolean {\n const stored = getApiKey()\n if (!stored) return false\n if (key.length !== stored.length) return false\n return crypto.timingSafeEqual(Buffer.from(key), Buffer.from(stored))\n}\n\n// ---------------------------------------------------------------------------\n// Session cookie: HMAC-SHA256(secret, userId + timestamp) — stateless, no DB\n// ---------------------------------------------------------------------------\nexport function signSession(payload: string): string {\n const secret = process.env.THIRD_AUDIENCE_SECRET ?? 'ta-salt'\n const sig = crypto.createHmac('sha256', secret).update(payload).digest('hex')\n return `${payload}.${sig}`\n}\n\nexport function verifySession(token: string): boolean {\n const lastDot = token.lastIndexOf('.')\n if (lastDot === -1) return false\n const payload = token.slice(0, lastDot)\n const sig = token.slice(lastDot + 1)\n const expected = crypto.createHmac('sha256', process.env.THIRD_AUDIENCE_SECRET ?? 'ta-salt')\n .update(payload).digest('hex')\n // Constant-time comparison\n if (sig.length !== expected.length) return false\n return crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'))\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAsC;AAC/C,OAAOC,WAAU;;;ACDjB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,YAAY;AAaZ,IAAM,YAAN,MAAgB;AAAA,EAGrB,YAAY,SAA2B;AACrC,SAAK,aAAa,QAAQ;AAAA,EAC5B;AAAA;AAAA,EAGA,KAAK,MAA8B;AACjC,UAAM,aAAa;AAAA,MACjB,KAAK,KAAK,KAAK,YAAY,GAAG,IAAI,MAAM;AAAA,MACxC,KAAK,KAAK,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O,aAAa;AAAA,IAClB,EAAE,OAAO,uEAAuE;AAAA,IAChF;AAAA,MACE,QAAQ;AAAA,MACR,SAAS,EAAE,oBAAoB,oCAAoC;AAAA,IACrE;AAAA,EACF;AACF;;;AJrCA,IAAM,SAAS,IAAI,UAAU,EAAE,YAAYC,MAAK,KAAK,QAAQ,IAAI,GAAG,QAAQ,IAAI,kBAAkB,SAAS,EAAE,CAAC;AAG9G,eAAsB,IAAI,KAAyC;AACjE,MAAI,CAAC,aAAa,GAAG,EAAG,QAAO,qBAAqB;AAEpD,QAAM,UAAU,QAAQ,IAAI,wBACvB,GAAG,IAAI,QAAQ,QAAQ,KAAK,IAAI,QAAQ,IAAI;AAEjD,QAAM,QAAQ,OAAO,QAAQ;AAC7B,QAAM,QAAQ,cAAc,OAAO,OAAO;AAE1C,SAAOC,cAAa,KAAK;AAAA,IACvB;AAAA,IACA,OAAO;AAAA,MACL,OAAO,MAAM;AAAA,MACb,OAAO,MAAM,MAAM;AAAA,MACnB,OAAO,MAAM,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,GAAG,OAAO;AAAA,EACtB,CAAC;AACH;","names":["NextResponse","path","fs","path","fs","path","NextResponse"]}
|
|
@@ -165,7 +165,7 @@ async function GET(req, { params }) {
|
|
|
165
165
|
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL ?? `${req.nextUrl.protocol}//${req.nextUrl.host}`;
|
|
166
166
|
const allFiles = reader.readAll();
|
|
167
167
|
const segments = params.path ?? [];
|
|
168
|
-
if (segments.length === 0 || segments.length === 1 && segments[0] === "index.md") {
|
|
168
|
+
if (segments.length === 0 || segments.length === 1 && (segments[0] === "index.md" || segments[0] === "index")) {
|
|
169
169
|
return new import_server.NextResponse(generateOkfIndex(allFiles, baseUrl), {
|
|
170
170
|
headers: { "Content-Type": "text/markdown; charset=utf-8" }
|
|
171
171
|
});
|