-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
235 lines (202 loc) · 8.16 KB
/
index.ts
File metadata and controls
235 lines (202 loc) · 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/**
* kong-pdf-api
* Generic HTML/URL → PDF microservice via Playwright + Bun
*
* POST /generate
* {
* url: string // Required. https://... or file://...
* filename?: string // Output filename (default: page-title.pdf)
* format?: "A4" | "Letter" // Default: A4
* landscape?: boolean // Default: false
* printBackground?: boolean // Default: true
* waitUntil?: "load" | "networkidle" | "domcontentloaded" // Default: networkidle
* extraWaitMs?: number // Extra ms to wait after load (default: 500)
* margin?: { top, right, bottom, left } // Default: see below
* pageNumberFooter?: boolean // Default: true — adds "X / N" footer
* footerHtml?: string // Custom footer HTML (overrides pageNumberFooter)
* injectCss?: string // Extra CSS to inject before capture
* }
*
* GET /health → { ok: true, version: "1.0.0" }
*/
import { chromium } from "playwright";
import { tmpdir } from "os";
import { join } from "path";
import { existsSync, unlinkSync } from "fs";
const PORT = parseInt(process.env.PORT ?? "3200");
const API_TOKEN = process.env.KONG_PDF_TOKEN ?? "";
const ALLOWED_ORIGINS = (process.env.ALLOWED_ORIGINS ?? "*").split(",");
const VERSION = "1.0.0";
// ─── Auth middleware ──────────────────────────────────────────────────────────
function isAuthorized(req: Request): boolean {
if (!API_TOKEN) return true; // no token configured = open
const auth = req.headers.get("Authorization") ?? "";
return auth === `Bearer ${API_TOKEN}`;
}
// ─── CORS headers ─────────────────────────────────────────────────────────────
function corsHeaders(origin: string): Record<string, string> {
const allowed =
ALLOWED_ORIGINS.includes("*") || ALLOWED_ORIGINS.includes(origin)
? origin
: "";
return {
"Access-Control-Allow-Origin": allowed || ALLOWED_ORIGINS[0],
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
}
// ─── PDF generation ───────────────────────────────────────────────────────────
async function generatePdf(options: {
url: string;
format?: string;
landscape?: boolean;
printBackground?: boolean;
waitUntil?: "load" | "networkidle" | "domcontentloaded";
extraWaitMs?: number;
margin?: { top?: string; right?: string; bottom?: string; left?: string };
pageNumberFooter?: boolean;
footerHtml?: string;
injectCss?: string;
}): Promise<Buffer> {
const {
url,
format = "A4",
landscape = false,
printBackground = true,
waitUntil = "networkidle",
extraWaitMs = 500,
margin,
pageNumberFooter = true,
footerHtml,
injectCss,
} = options;
const hasFooter = !!(pageNumberFooter || footerHtml);
const defaultMargin = {
top: "0mm",
right: "0mm",
bottom: hasFooter ? "14mm" : "0mm",
left: "0mm",
};
const finalMargin = { ...defaultMargin, ...(margin ?? {}) };
const defaultFooter = pageNumberFooter
? `<div style="width:100%;padding:0 8mm;display:flex;justify-content:space-between;
align-items:center;font-family:Helvetica,Arial,sans-serif;font-size:8pt;color:#9CA3AF;">
<span></span>
<span><span class="pageNumber"></span> / <span class="totalPages"></span></span>
</div>`
: "<span></span>";
const browser = await chromium.launch({
headless: true,
args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage"],
});
try {
const page = await browser.newPage();
await page.setViewportSize({ width: 1240, height: 1754 });
await page.goto(url, { waitUntil, timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
// Fix: orphaned headings detection
await page.evaluate(() => {
const MM_TO_PX = 3.7795;
const pageHeightPx = 297 * MM_TO_PX;
const dangerZone = 0.85;
const headings = Array.from(
document.querySelectorAll("h2, h3")
) as HTMLElement[];
for (const h of headings) {
const top = h.getBoundingClientRect().top + window.scrollY;
if ((top % pageHeightPx) / pageHeightPx >= dangerZone) {
h.style.breakBefore = "page";
h.style.pageBreakBefore = "always";
}
}
});
// Inject @page margins + extra CSS
const pageCss = `
@page { margin-top: 10mm; margin-right: 0; margin-left: 0; }
@page :first { margin-top: 0; }
${injectCss ?? ""}
`;
await page.addStyleTag({ content: pageCss });
if (extraWaitMs > 0) await page.waitForTimeout(extraWaitMs);
// Generate to temp file
const tmpPath = join(tmpdir(), `kong-pdf-${Date.now()}.pdf`);
await page.pdf({
path: tmpPath,
format: format as "A4" | "Letter",
landscape,
printBackground,
preferCSSPageSize: false,
margin: finalMargin,
displayHeaderFooter: hasFooter,
headerTemplate: "<span></span>",
footerTemplate: footerHtml ?? defaultFooter,
});
const file = Bun.file(tmpPath);
const buffer = Buffer.from(await file.arrayBuffer());
if (existsSync(tmpPath)) unlinkSync(tmpPath);
return buffer;
} finally {
await browser.close();
}
}
// ─── Server ───────────────────────────────────────────────────────────────────
const server = Bun.serve({
port: PORT,
async fetch(req) {
const url = new URL(req.url);
const origin = req.headers.get("origin") ?? "*";
const cors = corsHeaders(origin);
// CORS preflight
if (req.method === "OPTIONS") {
return new Response(null, { status: 204, headers: cors });
}
// Health check
if (req.method === "GET" && url.pathname === "/health") {
return Response.json({ ok: true, version: VERSION }, { headers: cors });
}
// PDF generation
if (req.method === "POST" && url.pathname === "/generate") {
if (!isAuthorized(req)) {
return Response.json({ error: "Unauthorized" }, { status: 401, headers: cors });
}
let body: Record<string, any>;
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body" }, { status: 400, headers: cors });
}
if (!body.url) {
return Response.json({ error: "Missing required field: url" }, { status: 400, headers: cors });
}
const start = Date.now();
console.log(`[kong-pdf] ${new Date().toISOString()} → ${body.url}`);
try {
const pdf = await generatePdf(body);
const elapsed = ((Date.now() - start) / 1000).toFixed(1);
// Filename: from body or slug from URL
const rawName = body.filename ?? new URL(body.url).hostname;
const filename = rawName.replace(/[^a-z0-9._-]/gi, "-").replace(/-+/g, "-") + ".pdf";
console.log(`[kong-pdf] ✓ ${filename} — ${(pdf.length / 1024).toFixed(1)} KB — ${elapsed}s`);
return new Response(pdf, {
status: 200,
headers: {
...cors,
"Content-Type": "application/pdf",
"Content-Disposition": `attachment; filename="${filename}"`,
"Content-Length": String(pdf.length),
"X-Generation-Time": `${elapsed}s`,
},
});
} catch (err: any) {
console.error(`[kong-pdf] ✗ ${err.message}`);
return Response.json({ error: err.message }, { status: 500, headers: cors });
}
}
return Response.json({ error: "Not found" }, { status: 404, headers: cors });
},
});
console.log(`\n 👑 kong-pdf-api v${VERSION}`);
console.log(` ├─ Port: ${PORT}`);
console.log(` ├─ Auth: ${API_TOKEN ? "Bearer token actiu" : "⚠️ sense token (obert)"}`);
console.log(` ├─ CORS: ${ALLOWED_ORIGINS.join(", ")}`);
console.log(` └─ Health: http://localhost:${PORT}/health\n`);