chore: 이력서 레포 git 초기화
직무 트랙별 이력서(md), PDF 변환 스크립트, 생성된 dist 산출물 추가. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,352 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, extname, resolve } from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
|
||||
const inputArg = process.argv[2];
|
||||
|
||||
if (!inputArg) {
|
||||
console.error("Usage: npm run pdf -- <resume.md> [output.pdf]");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const inputPath = resolve(inputArg);
|
||||
const outputPath = resolve(process.argv[3] ?? `dist/${basename(inputPath, extname(inputPath))}.pdf`);
|
||||
const htmlPath = outputPath.replace(/\.pdf$/i, ".html");
|
||||
const cssPath = resolve("resume.css");
|
||||
const markdown = readFileSync(inputPath, "utf8");
|
||||
const css = readFileSync(cssPath, "utf8");
|
||||
|
||||
mkdirSync(dirname(outputPath), { recursive: true });
|
||||
|
||||
const html = `<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${escapeHtml(basename(inputPath, extname(inputPath)))}</title>
|
||||
<style>${css}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
${renderMarkdown(markdown)}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
async function printPdfWithChrome(sourceHtmlPath, targetPdfPath) {
|
||||
const chrome = findChrome();
|
||||
const userDataDir = mkdtempSync(resolve(tmpdir(), "resume-chrome-"));
|
||||
const chromeProcess = spawn(chrome, [
|
||||
"--headless",
|
||||
"--disable-gpu",
|
||||
"--no-sandbox",
|
||||
"--remote-debugging-port=0",
|
||||
`--user-data-dir=${userDataDir}`,
|
||||
"about:blank",
|
||||
], {
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
|
||||
let stderr = "";
|
||||
chromeProcess.stderr.on("data", (chunk) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
|
||||
try {
|
||||
const browserWsUrl = await readBrowserWsUrl(userDataDir, chromeProcess);
|
||||
const tab = await createTab(browserWsUrl, `file://${sourceHtmlPath}`);
|
||||
const pdfBase64 = await printTabToPdf(tab.webSocketDebuggerUrl);
|
||||
writeFileSync(targetPdfPath, Buffer.from(pdfBase64, "base64"));
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
if (stderr.trim()) {
|
||||
console.error(stderr.trim());
|
||||
}
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
chromeProcess.kill("SIGTERM");
|
||||
rmSync(userDataDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
if (process.exitCode) {
|
||||
process.exit(process.exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
async function readBrowserWsUrl(userDataDir, chromeProcess) {
|
||||
const activePortPath = resolve(userDataDir, "DevToolsActivePort");
|
||||
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
if (chromeProcess.exitCode !== null) {
|
||||
throw new Error(`Chrome exited before DevTools became available. Exit code: ${chromeProcess.exitCode}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const [port, path] = readFileSync(activePortPath, "utf8").trim().split("\n");
|
||||
return `ws://127.0.0.1:${port}${path}`;
|
||||
} catch {
|
||||
await delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Timed out while waiting for Chrome DevTools.");
|
||||
}
|
||||
|
||||
async function createTab(browserWsUrl, url) {
|
||||
const browser = new CdpClient(browserWsUrl);
|
||||
await browser.open();
|
||||
const { targetId } = await browser.send("Target.createTarget", { url });
|
||||
await browser.close();
|
||||
|
||||
const targetsUrl = `http://${new URL(browserWsUrl).host}/json/list`;
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
const targets = await fetch(targetsUrl).then((response) => response.json());
|
||||
const tab = targets.find((target) => target.id === targetId);
|
||||
if (tab?.webSocketDebuggerUrl) {
|
||||
return tab;
|
||||
}
|
||||
await delay(50);
|
||||
}
|
||||
|
||||
throw new Error("Timed out while opening the HTML tab.");
|
||||
}
|
||||
|
||||
async function printTabToPdf(tabWsUrl) {
|
||||
const tab = new CdpClient(tabWsUrl);
|
||||
await tab.open();
|
||||
await tab.send("Page.enable");
|
||||
await delay(300);
|
||||
await tab.send("Page.getLayoutMetrics");
|
||||
const result = await tab.send("Page.printToPDF", {
|
||||
displayHeaderFooter: false,
|
||||
printBackground: true,
|
||||
preferCSSPageSize: true,
|
||||
});
|
||||
await tab.close();
|
||||
return result.data;
|
||||
}
|
||||
|
||||
class CdpClient {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.nextId = 1;
|
||||
this.pending = new Map();
|
||||
}
|
||||
|
||||
open() {
|
||||
return new Promise((resolveOpen, rejectOpen) => {
|
||||
this.ws = new WebSocket(this.url);
|
||||
this.ws.onopen = () => resolveOpen();
|
||||
this.ws.onerror = () => rejectOpen(new Error(`Failed to connect to ${this.url}`));
|
||||
this.ws.onmessage = (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
if (message.error) {
|
||||
pending.reject(new Error(message.error.message));
|
||||
} else {
|
||||
pending.resolve(message.result);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
send(method, params = {}) {
|
||||
const id = this.nextId;
|
||||
this.nextId += 1;
|
||||
const payload = JSON.stringify({ id, method, params });
|
||||
|
||||
return new Promise((resolveSend, rejectSend) => {
|
||||
this.pending.set(id, { resolve: resolveSend, reject: rejectSend });
|
||||
this.ws.send(payload);
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
this.ws.close();
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms) {
|
||||
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
|
||||
}
|
||||
|
||||
function findChrome() {
|
||||
const candidates = [
|
||||
process.env.CHROME_BIN,
|
||||
"google-chrome",
|
||||
"google-chrome-stable",
|
||||
"chromium",
|
||||
"chromium-browser",
|
||||
].filter(Boolean);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const found = spawnSync("which", [candidate], { encoding: "utf8" });
|
||||
if (found.status === 0) {
|
||||
return found.stdout.trim();
|
||||
}
|
||||
}
|
||||
|
||||
console.error("Chrome executable not found. Install Google Chrome or Chromium first.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function renderMarkdown(source) {
|
||||
const lines = source.replace(/\r\n/g, "\n").split("\n");
|
||||
const blocks = [];
|
||||
|
||||
for (let index = 0; index < lines.length;) {
|
||||
const line = lines[index];
|
||||
|
||||
if (!line.trim()) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const heading = /^(#{1,3})\s+(.+)$/.exec(line);
|
||||
if (heading) {
|
||||
const level = heading[1].length;
|
||||
blocks.push(`<h${level}>${inline(heading[2])}</h${level}>`);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^---+$/.test(line.trim())) {
|
||||
blocks.push("<hr>");
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTableStart(lines, index)) {
|
||||
const rows = [];
|
||||
rows.push(parseTableRow(lines[index]));
|
||||
index += 2;
|
||||
while (index < lines.length && /^\|.*\|$/.test(lines[index].trim())) {
|
||||
rows.push(parseTableRow(lines[index]));
|
||||
index += 1;
|
||||
}
|
||||
blocks.push(renderTable(rows));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.startsWith(">")) {
|
||||
const quoteLines = [];
|
||||
while (index < lines.length && lines[index].startsWith(">")) {
|
||||
quoteLines.push(lines[index].replace(/^>\s?/, ""));
|
||||
index += 1;
|
||||
}
|
||||
blocks.push(`<blockquote>${renderParagraphs(quoteLines)}</blockquote>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^-\s+/.test(line)) {
|
||||
const items = [];
|
||||
while (index < lines.length && /^-\s+/.test(lines[index])) {
|
||||
items.push(lines[index].replace(/^-\s+/, ""));
|
||||
index += 1;
|
||||
}
|
||||
blocks.push(`<ul>${items.map((item) => `<li>${inline(item)}</li>`).join("")}</ul>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const paragraph = [];
|
||||
while (
|
||||
index < lines.length &&
|
||||
lines[index].trim() &&
|
||||
!/^(#{1,3})\s+/.test(lines[index]) &&
|
||||
!/^---+$/.test(lines[index].trim()) &&
|
||||
!lines[index].startsWith(">") &&
|
||||
!/^- /.test(lines[index]) &&
|
||||
!isTableStart(lines, index)
|
||||
) {
|
||||
paragraph.push(lines[index].trim());
|
||||
index += 1;
|
||||
}
|
||||
blocks.push(`<p>${inline(paragraph.join(" "))}</p>`);
|
||||
}
|
||||
|
||||
return groupProjectSections(blocks).map((block) => ` ${block}`).join("\n");
|
||||
}
|
||||
|
||||
function groupProjectSections(blocks) {
|
||||
const grouped = [];
|
||||
|
||||
for (let index = 0; index < blocks.length;) {
|
||||
if (!blocks[index].startsWith("<h3>")) {
|
||||
grouped.push(blocks[index]);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const section = [];
|
||||
while (
|
||||
index < blocks.length &&
|
||||
!blocks[index].startsWith("<h2>") &&
|
||||
(section.length === 0 || !blocks[index].startsWith("<h3>"))
|
||||
) {
|
||||
section.push(blocks[index]);
|
||||
index += 1;
|
||||
}
|
||||
grouped.push(`<section class="project">${section.join("")}</section>`);
|
||||
}
|
||||
|
||||
return grouped;
|
||||
}
|
||||
|
||||
function renderParagraphs(lines) {
|
||||
return lines
|
||||
.join("\n")
|
||||
.split(/\n\s*\n/)
|
||||
.map((paragraph) => `<p>${inline(paragraph.replace(/\n/g, " ").trim())}</p>`)
|
||||
.join("");
|
||||
}
|
||||
|
||||
function isTableStart(lines, index) {
|
||||
return (
|
||||
index + 1 < lines.length &&
|
||||
/^\|.*\|$/.test(lines[index].trim()) &&
|
||||
/^\|\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/.test(lines[index + 1].trim())
|
||||
);
|
||||
}
|
||||
|
||||
function parseTableRow(line) {
|
||||
return line
|
||||
.trim()
|
||||
.replace(/^\|/, "")
|
||||
.replace(/\|$/, "")
|
||||
.split("|")
|
||||
.map((cell) => cell.trim());
|
||||
}
|
||||
|
||||
function renderTable(rows) {
|
||||
return `<table><tbody>${rows
|
||||
.map((row) => `<tr>${row.map((cell) => `<td>${inline(cell)}</td>`).join("")}</tr>`)
|
||||
.join("")}</tbody></table>`;
|
||||
}
|
||||
|
||||
function inline(value) {
|
||||
return escapeHtml(value)
|
||||
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
||||
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
||||
.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '<a href="$2">$1</a>');
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
writeFileSync(htmlPath, html);
|
||||
|
||||
await printPdfWithChrome(htmlPath, outputPath);
|
||||
|
||||
console.log(`HTML: ${htmlPath}`);
|
||||
console.log(`PDF: ${outputPath}`);
|
||||
Reference in New Issue
Block a user