@unana_dev/doxen 0.0.0-stage → 0.2.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.
@@ -0,0 +1,74 @@
1
+ import { readFile, writeFile, mkdir, rename, rm, lstat, chmod } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+
6
+ export const credentialsDirectory = path.join(homedir(), ".config", "doxen", "accounts");
7
+ export const statePath = (root) => path.join(root, ".doxen-deploy.json");
8
+
9
+ async function readJson(file) {
10
+ try { return JSON.parse(await readFile(file, "utf8")); }
11
+ catch (error) {
12
+ if (error.code === "ENOENT") return null;
13
+ throw new Error(`${file} 파일을 읽을 수 없습니다. 내용을 확인하세요.`);
14
+ }
15
+ }
16
+
17
+ export async function readDeploymentState(root, file) {
18
+ const state = await readJson(statePath(root));
19
+ if (!state) return null;
20
+ if (state.version !== 1 || state.configFile !== path.basename(file) ||
21
+ !/^[a-f0-9]{32}$/i.test(state.accountId) || typeof state.ready !== "boolean" ||
22
+ typeof state.project !== "string" || !/^[a-z0-9][a-z0-9-]{0,57}[a-z0-9]$/.test(state.project) ||
23
+ !Array.isArray(state.emails) || !state.emails.length ||
24
+ state.emails.some((email) => typeof email !== "string" || !/^[^\s@*]+@[^\s@*]+\.[^\s@*]+$/.test(email)) ||
25
+ !state.apps || typeof state.apps !== "object" || Array.isArray(state.apps))
26
+ throw new Error(".doxen-deploy.json이 현재 문서 설정과 맞지 않습니다. 배포 상태 파일을 확인하세요.");
27
+ return state;
28
+ }
29
+
30
+ async function atomicJson(file, value) {
31
+ const temporary = `${file}.${randomUUID()}.tmp`;
32
+ try {
33
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx", mode: 0o600 });
34
+ await rename(temporary, file);
35
+ } finally { await rm(temporary, { force: true }); }
36
+ }
37
+
38
+ export async function saveDeploymentState(root, state) {
39
+ await atomicJson(statePath(root), state);
40
+ }
41
+
42
+ function credentialPath(account, directory) {
43
+ if (!/^[a-f0-9]{32}$/i.test(account)) throw new Error("Cloudflare 계정 ID가 올바르지 않습니다.");
44
+ return path.join(directory, `${account}.json`);
45
+ }
46
+
47
+ export async function readToken(account, directory = credentialsDirectory) {
48
+ const file = credentialPath(account, directory);
49
+ const info = await lstat(file).catch((error) => {
50
+ if (error.code !== "ENOENT") throw error;
51
+ });
52
+ if (!info) return null;
53
+ if (!info.isFile() || info.isSymbolicLink() || (process.platform !== "win32" && (info.mode & 0o077)))
54
+ throw new Error("저장된 배포 토큰 파일의 접근 권한이 안전하지 않습니다. 소유자만 읽을 수 있도록 변경하세요.");
55
+ const saved = await readJson(file);
56
+ return typeof saved?.token === "string" ? saved.token : null;
57
+ }
58
+
59
+ export async function saveToken(account, token, directory = credentialsDirectory) {
60
+ const file = credentialPath(account, directory);
61
+ await mkdir(directory, { recursive: true, mode: 0o700 });
62
+ const info = await lstat(directory);
63
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("토큰 저장 경로는 일반 디렉터리여야 합니다.");
64
+ await chmod(directory, 0o700);
65
+ await atomicJson(file, { token });
66
+ }
67
+
68
+ export function deploymentFromState(state) {
69
+ if (!state?.ready) return undefined;
70
+ return {
71
+ project: state.project,
72
+ access: { teamDomain: state.teamDomain, audiences: Object.values(state.apps).map((app) => app.aud), emails: state.emails },
73
+ };
74
+ }
package/src/deploy.js ADDED
@@ -0,0 +1,111 @@
1
+ import { createRequire } from "node:module";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdtemp, writeFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { build as bundle } from "esbuild";
8
+ import { build } from "./build.js";
9
+
10
+ export function validateDeployment(deploy) {
11
+ if (!deploy || typeof deploy !== "object")
12
+ throw new Error("deploy 설정이 필요합니다. README의 비공개 배포 설정을 확인하세요.");
13
+ if (typeof deploy.project !== "string" || !/^[a-z0-9][a-z0-9-]{0,57}[a-z0-9]$/.test(deploy.project))
14
+ throw new Error("deploy.project에 Cloudflare Pages 프로젝트 이름을 설정하세요.");
15
+ const access = deploy.access;
16
+ if (!access || typeof access.teamDomain !== "string" ||
17
+ !/^https:\/\/[a-z0-9][a-z0-9-]*\.cloudflareaccess\.com$/.test(access.teamDomain))
18
+ throw new Error("deploy.access.teamDomain은 https://팀이름.cloudflareaccess.com 형식이어야 합니다.");
19
+ if (!Array.isArray(access.audiences) || !access.audiences.length ||
20
+ access.audiences.some((value) => typeof value !== "string" || !/^[a-f0-9]{64}$/i.test(value)))
21
+ throw new Error("deploy.access.audiences에 Access 애플리케이션의 AUD를 설정하세요.");
22
+ if (!Array.isArray(access.emails) || !access.emails.length ||
23
+ access.emails.some((value) => typeof value !== "string" || !/^[^\s@*]+@[^\s@*]+\.[^\s@*]+$/.test(value)))
24
+ throw new Error("deploy.access.emails에 허용할 이메일 주소를 하나 이상 설정하세요.");
25
+ return {
26
+ project: deploy.project,
27
+ access: { teamDomain: access.teamDomain, audiences: access.audiences, emails: access.emails },
28
+ };
29
+ }
30
+
31
+ export async function protectedFiles(deploy) {
32
+ const { access } = validateDeployment(deploy);
33
+ const result = await bundle({
34
+ stdin: {
35
+ contents: `import { accessWorker } from './access-worker.js';\nexport default accessWorker(${JSON.stringify(access)});`,
36
+ resolveDir: fileURLToPath(new URL(".", import.meta.url)),
37
+ },
38
+ bundle: true,
39
+ write: false,
40
+ format: "esm",
41
+ platform: "browser",
42
+ target: "es2022",
43
+ });
44
+ return new Map([
45
+ ["/_worker.js", Buffer.from(result.outputFiles[0].contents)],
46
+ ["/_routes.json", Buffer.from(JSON.stringify({ version: 1, include: ["/*"], exclude: [] }))],
47
+ ]);
48
+ }
49
+
50
+ export async function checkProject(deploy, env = process.env, fetcher = fetch) {
51
+ const account = env.CLOUDFLARE_ACCOUNT_ID;
52
+ const token = env.CLOUDFLARE_API_TOKEN;
53
+ if (!account || !/^[a-f0-9]{32}$/i.test(account) || !token)
54
+ throw new Error("CLOUDFLARE_ACCOUNT_ID와 CLOUDFLARE_API_TOKEN 환경 변수를 설정하세요. 토큰에는 해당 계정의 Cloudflare Pages Edit 권한이 필요합니다.");
55
+ const response = await fetcher(
56
+ `https://api.cloudflare.com/client/v4/accounts/${account}/pages/projects/${deploy.project}`,
57
+ { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15000) },
58
+ );
59
+ if (!response.ok) throw new Error(`Pages 프로젝트 확인 실패 (HTTP ${response.status}). 계정, 토큰, 기존 프로젝트 이름을 확인하세요.`);
60
+ const data = await response.json();
61
+ if (!data.success || !data.result?.production_branch)
62
+ throw new Error("Pages 프로젝트 정보를 확인할 수 없습니다.");
63
+ for (const name of ["production", "preview"]) {
64
+ if (data.result.deployment_configs?.[name]?.fail_open !== false)
65
+ throw new Error(`Pages ${name}의 Functions 설정을 Fail closed로 변경한 후 다시 배포하세요. 인증 없이 정적 파일을 제공하는 Fail open 설정에서는 배포하지 않습니다.`);
66
+ }
67
+ return data.result;
68
+ }
69
+
70
+ export function resolveWrangler(root) {
71
+ let packageFile;
72
+ try {
73
+ packageFile = createRequire(path.join(root, "package.json")).resolve("wrangler/package.json");
74
+ } catch {
75
+ packageFile = createRequire(import.meta.url).resolve("wrangler/package.json");
76
+ }
77
+ return path.join(path.dirname(packageFile), "bin", "wrangler.js");
78
+ }
79
+
80
+ export async function deploy(config, options) {
81
+ if (Number(process.versions.node.split(".")[0]) < 22)
82
+ throw new Error("자동 배포에는 Node.js 22 이상이 필요합니다. Node.js를 업데이트한 뒤 다시 실행하세요.");
83
+ const { prepareDeployment } = await import("./deploy-setup.js");
84
+ const prepared = await prepareDeployment(config, options);
85
+ config = prepared.config;
86
+ const settings = validateDeployment(config.deploy);
87
+ const wrangler = resolveWrangler(config.root);
88
+ const project = await checkProject(settings, prepared.env);
89
+ const out = await build(config);
90
+ // Isolate Wrangler from unrelated project config, functions and redirects.
91
+ const temporary = await mkdtemp(path.join(tmpdir(), "doxen-deploy-"));
92
+ try {
93
+ await writeFile(path.join(temporary, "wrangler.json"), JSON.stringify({
94
+ name: settings.project,
95
+ pages_build_output_dir: out,
96
+ compatibility_date: "2026-10-08",
97
+ }));
98
+ await new Promise((resolve, reject) => {
99
+ const child = spawn(process.execPath, [wrangler, "pages", "deploy", out,
100
+ "--project-name", settings.project, "--branch", project.production_branch], {
101
+ cwd: temporary, stdio: "inherit", shell: false, env: prepared.env,
102
+ });
103
+ child.once("error", reject);
104
+ child.once("exit", (code, signal) => code === 0 ? resolve() :
105
+ reject(new Error(`배포 실패: ${signal || `종료 코드 ${code}`}`)));
106
+ });
107
+ } finally {
108
+ await rm(temporary, { recursive: true, force: true });
109
+ }
110
+ console.log(`배포 완료: https://${project.subdomain || `${settings.project}.pages.dev`} (허용 계정으로 접근을 확인하세요.)`);
111
+ }
package/src/dev.js ADDED
@@ -0,0 +1,112 @@
1
+ import http from "node:http";
2
+ import path from "node:path";
3
+ import { watch } from "chokidar";
4
+ import { loadConfig } from "./config.js";
5
+ import { siteFiles } from "./build.js";
6
+
7
+ const types = {
8
+ ".html": "text/html; charset=utf-8",
9
+ ".js": "text/javascript; charset=utf-8",
10
+ ".css": "text/css; charset=utf-8",
11
+ ".json": "application/json; charset=utf-8",
12
+ ".png": "image/png",
13
+ ".jpg": "image/jpeg",
14
+ ".jpeg": "image/jpeg",
15
+ ".gif": "image/gif",
16
+ ".webp": "image/webp",
17
+ ".avif": "image/avif",
18
+ ".ico": "image/x-icon",
19
+ ".svg": "image/svg+xml",
20
+ ".pdf": "application/pdf",
21
+ };
22
+
23
+ export async function dev(cwd, configPath, port = 4173) {
24
+ let config = await loadConfig(cwd, configPath);
25
+ let files = await siteFiles(config, true);
26
+ let currentError = "";
27
+ const clients = new Set();
28
+ const server = http.createServer((req, res) => {
29
+ const pathname = new URL(req.url, "http://localhost").pathname;
30
+ if (pathname === "/__events") {
31
+ res.writeHead(200, {
32
+ "Content-Type": "text/event-stream",
33
+ "Cache-Control": "no-cache",
34
+ Connection: "keep-alive",
35
+ });
36
+ res.write(": connected\n\n");
37
+ clients.add(res);
38
+ req.on("close", () => clients.delete(res));
39
+ return;
40
+ }
41
+ if (currentError && (pathname === "/" || pathname === "/index.html")) {
42
+ res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
43
+ return res.end(
44
+ `문서 빌드 오류. 파일을 수정한 뒤 새로고침하세요.\n\n${currentError}`,
45
+ );
46
+ }
47
+ const key = pathname === "/" ? "/index.html" : pathname;
48
+ const body = files.get(key);
49
+ res.writeHead(body ? 200 : 404, {
50
+ "Content-Type": types[path.extname(key)] || "text/plain; charset=utf-8",
51
+ "Cache-Control": "no-store",
52
+ "X-Content-Type-Options": "nosniff",
53
+ });
54
+ res.end(body || "Not found");
55
+ });
56
+ const watcher = watch(config.root, {
57
+ ignoreInitial: true,
58
+ ignored: (file) =>
59
+ path
60
+ .relative(config.root, file)
61
+ .split(path.sep)
62
+ .some((part) => part === "node_modules" || part.startsWith(".")),
63
+ awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 },
64
+ });
65
+ let timer;
66
+ let queue = Promise.resolve();
67
+ watcher.on("all", () => {
68
+ clearTimeout(timer);
69
+ timer = setTimeout(() => {
70
+ queue = queue.then(async () => {
71
+ try {
72
+ config = await loadConfig(cwd, configPath);
73
+ files = await siteFiles(config, true);
74
+ currentError = "";
75
+ console.log("문서를 갱신했습니다.");
76
+ } catch (error) {
77
+ currentError = error.message;
78
+ console.error(currentError);
79
+ }
80
+ for (const client of clients)
81
+ client.write("event: reload\ndata: changed\n\n");
82
+ });
83
+ }, 100);
84
+ });
85
+ watcher.on("error", (error) =>
86
+ console.error(`파일 감시 오류: ${error.message}`),
87
+ );
88
+ try {
89
+ await new Promise((resolve, reject) => {
90
+ server.once("error", reject);
91
+ server.listen(port, "127.0.0.1", resolve);
92
+ });
93
+ } catch (error) {
94
+ await watcher.close();
95
+ throw error;
96
+ }
97
+ const heartbeat = setInterval(() => {
98
+ for (const client of clients) client.write(": heartbeat\n\n");
99
+ }, 20000);
100
+ console.log(`Doxen → http://127.0.0.1:${server.address().port}`);
101
+ return {
102
+ server,
103
+ async close() {
104
+ clearTimeout(timer);
105
+ clearInterval(heartbeat);
106
+ await watcher.close();
107
+ await queue;
108
+ for (const client of clients) client.end();
109
+ await new Promise((resolve) => server.close(resolve));
110
+ },
111
+ };
112
+ }
@@ -0,0 +1,30 @@
1
+ # 문서 제목
2
+
3
+ > **문서 정보 범위:** 문서의 목적, 적용 대상과 확인한 근거를 설명합니다.
4
+
5
+ ---
6
+
7
+ ## 1. 첫 번째 단계
8
+
9
+ :::search 첫 번째 단계 검색
10
+ | 상황 | 현재 동작 | 다음 행동 |
11
+ | --- | --- | --- |
12
+ | 확인된 조건 | 실제 동작 | 사용자가 할 일 |
13
+ :::
14
+
15
+ ## 2. 두 번째 단계
16
+
17
+ :::search 두 번째 단계 검색
18
+ | 상황 | 현재 동작 | 다음 행동 |
19
+ | --- | --- | --- |
20
+ | 확인된 조건 | 실제 동작 | 사용자가 할 일 |
21
+ :::
22
+
23
+ ## 3. 예외 및 확인 사항
24
+
25
+ 검색이 필요 없는 짧은 섹션에는 검색 영역을 붙이지 않습니다.
26
+ 미확인 정책이나 수치는 추측하지 않고 확인 필요로 표시합니다.
27
+
28
+ ## 4. 관련 문서
29
+
30
+ 기존 문서와 근거를 상대 Markdown 링크로 연결합니다.
package/src/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ export interface DocsConfig {
2
+ title: string;
3
+ description?: string;
4
+ icon?: string | { background?: string; color?: string; border?: string };
5
+ deploy?: {
6
+ project: string;
7
+ access: {
8
+ teamDomain: string;
9
+ audiences: string[];
10
+ emails: string[];
11
+ };
12
+ };
13
+ tabs: Array<{ title: string; dir: string; slug: string }>;
14
+ }
15
+ export declare function defineConfig(config: DocsConfig): DocsConfig;
package/src/index.js ADDED
@@ -0,0 +1 @@
1
+ export const defineConfig = (config) => config;
package/src/init.js ADDED
@@ -0,0 +1,54 @@
1
+ import { access, readFile, writeFile, mkdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ const exists = (file) =>
5
+ access(file).then(
6
+ () => true,
7
+ () => false,
8
+ );
9
+
10
+ export async function init(cwd) {
11
+ const packageFile = path.join(cwd, "package.json");
12
+ const pkg = (await exists(packageFile))
13
+ ? JSON.parse(await readFile(packageFile, "utf8"))
14
+ : { private: true };
15
+ let hasConfig = false;
16
+ for (const name of ["docs.config.ts", "docs.config.mjs", "docs.config.js"])
17
+ if (await exists(path.join(cwd, name))) hasConfig = true;
18
+ if (!hasConfig) {
19
+ await mkdir(path.join(cwd, "docs"), { recursive: true });
20
+ await writeFile(
21
+ path.join(cwd, "docs.config.ts"),
22
+ `export default {\n title: '팀 문서',\n icon: { background: '#edf8ff', color: '#467792', border: '#bcdff8' },\n tabs: [\n { title: '가이드', dir: './docs', slug: 'guide' },\n ],\n};\n`,
23
+ { flag: "wx" },
24
+ );
25
+ if (!(await exists(path.join(cwd, "docs", "README.md"))))
26
+ await writeFile(
27
+ path.join(cwd, "docs", "README.md"),
28
+ "# 시작하기\n\n팀의 문서를 여기에 작성하세요.\n\n## 문서 연결\n\n설정 파일의 tabs에 문서 폴더를 추가하세요.\n\n:::search 용어 검색\n## 용어 사전\n\n| 용어 | 설명 |\n| --- | --- |\n| Doxen | 저장소 기반 문서 사이트 도구 |\n:::\n",
29
+ { flag: "wx" },
30
+ );
31
+ }
32
+ pkg.scripts ||= {};
33
+ for (const [name, command] of Object.entries({
34
+ "docs:dev": "doxen dev",
35
+ "docs:build": "doxen build",
36
+ "docs:deploy": "doxen deploy",
37
+ })) {
38
+ if (pkg.scripts[name] && pkg.scripts[name] !== command)
39
+ console.log(`기존 ${name} 스크립트를 유지합니다: ${pkg.scripts[name]}`);
40
+ else pkg.scripts[name] = command;
41
+ }
42
+ await writeFile(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);
43
+ const ignorePath = path.join(cwd, ".gitignore");
44
+ let ignore = (await exists(ignorePath))
45
+ ? await readFile(ignorePath, "utf8")
46
+ : "";
47
+ for (const entry of [".docs-dist/", ".docs-build-*/", "node_modules/"])
48
+ if (!ignore.split(/\r?\n/).includes(entry))
49
+ ignore += `${ignore && !ignore.endsWith("\n") ? "\n" : ""}${entry}\n`;
50
+ await writeFile(ignorePath, ignore);
51
+ console.log(
52
+ "설정과 실행 스크립트를 준비했습니다. docs.config.ts를 편집한 후 npm run docs:dev 또는 yarn docs:dev를 실행하세요.",
53
+ );
54
+ }