-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2611 lines (2234 loc) · 75.8 KB
/
server.js
File metadata and controls
2611 lines (2234 loc) · 75.8 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import axios from "axios";
import xml2js from "xml2js";
import multer from "multer";
import { createClient } from "@supabase/supabase-js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
// Service imports
import { fetchPaperByDOI, extractDOI, isDOI } from "./services/crossref.js";
import { fetchPaperByPMID, extractPMID, isPMID } from "./services/pubmed.js";
import { fetchPaper, searchPapers, getCitations, getReferences, getRelatedPapers, normalizePaperId, paperToSchema } from "./services/semanticscholar.js";
import { extractScholarQuery, isScholarUrl, findPapersFromScholarUrl } from "./services/scholar.js";
dotenv.config();
// Lazy imports to avoid blocking module load
let cachedDb;
let pool = null; // Exposed synchronously after first getDb() call
async function getDb() {
if (cachedDb) return cachedDb;
cachedDb = await import("./db.js");
pool = cachedDb.pool; // Cache for sync access
return cachedDb;
}
let cachedAuth;
async function getAuth() {
if (cachedAuth !== undefined) return cachedAuth;
const authModule = await import("./auth.js");
cachedAuth = await authModule.getAuth();
return cachedAuth;
}
const app = express();
const PORT = process.env.PORT || 3000;
const SKIP_AUTH = process.env.SKIP_AUTH === "true";
function asyncHandler(fn) {
return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}
let cachedGroq;
async function getGroqClient() {
if (cachedGroq) return cachedGroq;
const { default: Groq } = await import("groq-sdk");
cachedGroq = new Groq({
apiKey: process.env.GROQ_API_KEY,
});
return cachedGroq;
}
let cachedBetterAuthNode;
async function getBetterAuthNode() {
if (cachedBetterAuthNode) return cachedBetterAuthNode;
cachedBetterAuthNode = await import("better-auth/node");
return cachedBetterAuthNode;
}
let cachedAPIError;
async function getAPIErrorClass() {
if (cachedAPIError) return cachedAPIError;
const mod = await import("better-auth/api");
cachedAPIError = mod.APIError;
return cachedAPIError;
}
const SUPABASE_URL = (process.env.SUPABASE_URL || "").trim();
const SUPABASE_SERVICE_ROLE_KEY = (
process.env.SUPABASE_SERVICE_ROLE_KEY || ""
).trim();
const SUPABASE_STORAGE_BUCKET = (
process.env.SUPABASE_STORAGE_BUCKET || "paperplain-pdfs"
).trim();
const supabase =
SUPABASE_URL && SUPABASE_SERVICE_ROLE_KEY
? createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false },
})
: null;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Note: Vercel/serverless filesystems are ephemeral and the project directory
// may be read-only. Only use disk uploads in local/dev, and prefer /tmp.
const uploadsDir = process.env.VERCEL
? path.join("/tmp", "paperplain-uploads")
: path.join(__dirname, "public", "uploads");
if (!supabase) {
try {
fs.mkdirSync(uploadsDir, { recursive: true });
} catch (e) {
// If this fails in a restricted environment, we'll surface a clearer error
// when the PDF endpoint is used.
}
}
function safeUploadFilename(originalname) {
const base = (originalname || "upload.pdf")
.toString()
.replace(/[^a-zA-Z0-9._-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
const timestamp = Date.now();
const rand = Math.random().toString(16).slice(2, 10);
return `${timestamp}-${rand}-${base || "upload.pdf"}`;
}
const pdfUpload = multer({
storage: supabase
? multer.memoryStorage()
: multer.diskStorage({
destination: (_req, _file, cb) => cb(null, uploadsDir),
filename: (_req, file, cb) =>
cb(null, safeUploadFilename(file.originalname)),
}),
limits: { fileSize: 25 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
const isPdf =
file.mimetype === "application/pdf" ||
(file.originalname || "").toLowerCase().endsWith(".pdf");
if (!isPdf) return cb(new Error("Only PDF files are supported"));
cb(null, true);
},
});
async function uploadPdfToSupabaseStorage({
buffer,
contentType,
originalName,
}) {
if (!supabase) {
throw new Error(
"Supabase Storage is not configured (set SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY)"
);
}
const safeName = safeUploadFilename(originalName || "upload.pdf");
const objectPath = `pdf/${safeName}`;
const { error } = await supabase.storage
.from(SUPABASE_STORAGE_BUCKET)
.upload(objectPath, buffer, {
contentType: contentType || "application/pdf",
upsert: false,
});
if (error) {
throw new Error(error.message || "Failed to upload PDF to storage");
}
const { data } = supabase.storage
.from(SUPABASE_STORAGE_BUCKET)
.getPublicUrl(objectPath);
const url = data?.publicUrl;
if (!url) throw new Error("Failed to get public URL for uploaded PDF");
return url;
}
function normalizeKeyTermsHeading(text) {
return (text || "")
.replace(/^\s*(\*\*\s*)?Key\s*Terms\s*:\s*(\*\*)?\s*$/gim, "**Key Terms:**")
.replace(/^\s*(\*\*\s*)?Key\s*Terms\s*:\s*(\*\*)?/gim, "**Key Terms:**");
}
function clampText(value, maxLen) {
return (value || "").toString().trim().slice(0, maxLen);
}
function extractAbstractFromPdfText(text) {
const src = (text || "").toString().replace(/\r\n/g, "\n");
const idx = src.search(/\n\s*abstract\s*\n|\n\s*abstract\s*:/i);
if (idx === -1) return "";
const tail = src.slice(idx).replace(/^\s*\n\s*/g, "");
const after = tail.replace(/^abstract\s*(?:\n|:)/i, "").trim();
// Stop at common next-section headings.
const stopIdx = after.search(
/\n\s*(?:keywords?|index terms|introduction|1\s*\.\s*introduction|i\s*\.\s*introduction|contents)\b/i
);
const abstract = (stopIdx === -1 ? after : after.slice(0, stopIdx)).trim();
return abstract.replace(/\s+/g, " ");
}
function guessTitleAuthorsFromPdfText(text) {
const lines = (text || "")
.toString()
.replace(/\r\n/g, "\n")
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const titleCandidates = lines
.slice(0, 40)
.filter((l) => l.length >= 10 && l.length <= 180)
.filter((l) => /[a-zA-Z]/.test(l));
const title = titleCandidates.length ? titleCandidates[0] : "Uploaded PDF";
// Authors are often in the next couple lines after title.
const titleIndex = lines.findIndex((l) => l === title);
const authorWindow =
titleIndex >= 0 ? lines.slice(titleIndex + 1, titleIndex + 6) : [];
const authorsLine = authorWindow.find(
(l) =>
l.length <= 200 &&
/,| and |\b[A-Z][a-z]+\b/.test(l) &&
!/^abstract\b/i.test(l)
);
return {
title: clampText(title, 400) || "Uploaded PDF",
authors: clampText(authorsLine || "", 600),
};
}
function parseLabeledPdfExtraction(raw) {
const text = (raw || "").toString().replace(/\r\n/g, "\n");
const getBlock = (label) => {
const re = new RegExp(`(?:^|\\n)${label}:\\s*`, "i");
const m = text.match(re);
if (!m || m.index == null) return "";
const start = m.index + m[0].length;
const rest = text.slice(start);
const next = rest.search(/\n\s*(?:TITLE|AUTHORS|ABSTRACT|SUMMARY)\s*:\s*/i);
return (next === -1 ? rest : rest.slice(0, next)).trim();
};
return {
title: getBlock("TITLE"),
authors: getBlock("AUTHORS"),
abstract: getBlock("ABSTRACT"),
summary: getBlock("SUMMARY"),
};
}
// Middleware
app.use(
cors({
origin: true,
credentials: true,
})
);
// Better Auth handler (must be mounted before express.json)
app.all(
"/api/better-auth/*",
asyncHandler(async (req, res) => {
const auth = await getAuth();
if (!auth) {
return res.status(503).json({
message: "Auth is not configured. Set DATABASE_URL to enable it.",
});
}
const { toNodeHandler } = await getBetterAuthNode();
return toNodeHandler(auth)(req, res);
})
);
app.use(express.json());
app.use(express.static("public"));
async function ensurePapersTable() {
const { pool } = await getDb();
if (!pool) return;
await pgQuery(
`
CREATE TABLE IF NOT EXISTS papers (
id SERIAL PRIMARY KEY,
user_id TEXT NOT NULL,
arxiv_id TEXT,
title TEXT NOT NULL,
authors TEXT,
abstract TEXT,
pdf_url TEXT,
summary TEXT,
notes TEXT,
project TEXT,
tags TEXT[],
qa_history JSONB DEFAULT '[]'::jsonb,
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(user_id, arxiv_id)
);
`,
[],
"ensurePapersTable.create"
);
await pgQuery(
`ALTER TABLE papers ADD COLUMN IF NOT EXISTS project TEXT;`,
[],
"ensurePapersTable.alter.project"
);
await pgQuery(
`ALTER TABLE papers ADD COLUMN IF NOT EXISTS tags TEXT[];`,
[],
"ensurePapersTable.alter.tags"
);
await pgQuery(
`ALTER TABLE papers ADD COLUMN IF NOT EXISTS qa_history JSONB DEFAULT '[]'::jsonb;`,
[],
"ensurePapersTable.alter.qa_history"
);
}
function requireAuthSession() {
return async (req, res, next) => {
if (SKIP_AUTH) {
req.user = { id: "dev-user", email: "dev@example.com" };
return next();
}
const auth = await getAuth();
if (!auth) return res.status(401).json({ message: "Sign in required" });
try {
const { fromNodeHeaders } = await getBetterAuthNode();
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
if (!session?.user?.id) {
return res.status(401).json({ message: "Sign in required" });
}
req.user = session.user;
next();
} catch (error) {
return res.status(401).json({ message: "Sign in required" });
}
};
}
// Extract ArXiv ID from URL
function extractArxivId(url) {
const patterns = [
/arxiv\.org\/abs\/([0-9.]+)/,
/arxiv\.org\/pdf\/([0-9.]+)/,
/([0-9]{4}\.[0-9]{4,5})/,
];
for (const pattern of patterns) {
const match = url.match(pattern);
if (match) return match[1];
}
throw new Error("Invalid ArXiv URL format");
}
function decodeHtmlEntities(input) {
return (input || "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'");
}
app.get("/api/arxiv/:id/bibtex", async (req, res) => {
try {
const arxivId = (req.params.id || "").toString().trim();
if (!/^[0-9]{4}\.[0-9]{4,5}$/.test(arxivId)) {
return res.status(400).json({ message: "Invalid arXiv ID" });
}
const url = `https://arxiv.org/bibtex/${arxivId}`;
const response = await axios.get(url, {
responseType: "text",
headers: { "User-Agent": "PaperPlain/1.0" },
timeout: 15000,
});
let text = (response.data || "").toString();
const pre = text.match(/<pre[^>]*>([\s\S]*?)<\/pre>/i);
if (pre?.[1]) text = pre[1];
text = decodeHtmlEntities(text).replace(/\r\n/g, "\n").trim();
if (!text || !text.includes("@")) {
return res.status(502).json({ message: "Failed to fetch BibTeX" });
}
res.json({ success: true, bibtex: text });
} catch (error) {
res
.status(500)
.json({ message: error.message || "Failed to fetch BibTeX" });
}
});
app.get("/api/arxiv/:id/pdf", async (req, res) => {
try {
const arxivId = (req.params.id || "").toString().trim();
if (!/^[0-9]{4}\.[0-9]{4,5}$/.test(arxivId)) {
return res.status(400).json({ message: "Invalid arXiv ID" });
}
const url = `https://arxiv.org/pdf/${arxivId}.pdf`;
const response = await axios.get(url, {
responseType: "stream",
headers: { "User-Agent": "PaperPlain/1.0" },
timeout: 20000,
});
res.setHeader("content-type", "application/pdf");
res.setHeader(
"content-disposition",
`attachment; filename="${arxivId}.pdf"`
);
response.data.pipe(res);
} catch (error) {
const status = error?.response?.status || 502;
res.status(status).json({
message: error?.message || "Failed to download PDF",
});
}
});
// Fetch paper metadata from ArXiv API
async function fetchArxivPaper(arxivId) {
try {
const apiUrl = `http://export.arxiv.org/api/query?id_list=${arxivId}`;
const response = await axios.get(apiUrl);
const parser = new xml2js.Parser();
const result = await parser.parseStringPromise(response.data);
if (!result.feed.entry || result.feed.entry.length === 0) {
throw new Error("Paper not found");
}
const entry = result.feed.entry[0];
return {
title: entry.title[0].trim().replace(/\s+/g, " "),
authors: entry.author.map((a) => a.name[0]).join(", "),
abstract: entry.summary[0].trim().replace(/\s+/g, " "),
published: entry.published[0],
arxivId: arxivId,
pdfUrl: `https://arxiv.org/pdf/${arxivId}.pdf`,
};
} catch (error) {
throw new Error(`Failed to fetch paper: ${error.message}`);
}
}
function assertString(value, fieldName) {
if (typeof value !== "string" || value.trim().length === 0) {
const message = `${fieldName} is required`;
const error = new Error(message);
error.statusCode = 400;
throw error;
}
return value.trim();
}
function withTimeout(promise, ms, label) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => {
const err = new Error(
`${
label || "Operation"
} timed out after ${ms}ms. This usually means the database connection is blocked or misconfigured.`
);
err.statusCode = 504;
reject(err);
}, ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
async function pgQuery(queryText, params, label) {
const { pool } = await getDb();
if (!pool) {
const err = new Error("Database not configured");
err.statusCode = 503;
throw err;
}
return withTimeout(pool.query(queryText, params), 8000, label || "pg.query");
}
async function pipeWebResponseToExpress(res, response) {
res.status(response.status);
for (const [key, value] of response.headers.entries()) {
if (key.toLowerCase() === "set-cookie") continue;
res.setHeader(key, value);
}
const getSetCookie = response.headers.getSetCookie?.bind(response.headers);
if (typeof getSetCookie === "function") {
const cookies = getSetCookie();
if (cookies?.length) {
res.setHeader("set-cookie", cookies);
}
} else {
const cookie = response.headers.get("set-cookie");
if (cookie) {
res.setHeader("set-cookie", cookie);
}
}
const body = await response.text();
res.send(body);
}
// Simplify paper using Groq
const SUMMARY_STYLES = {
simple: {
description: "Plain English, minimal jargon",
maxTokens: 1000,
systemPrompt: "You are an expert at translating complex academic papers into clear, simple English that anyone can understand.",
promptTemplate: (title, abstract) => `You are an expert at explaining complex academic research in simple, plain English.
Paper Title: ${title}
Abstract: ${abstract}
Please provide a clear, concise summary that includes:
1. THE PROBLEM: What problem is this research trying to solve? (2-3 sentences)
2. THE METHOD: How did they approach it? What did they do? (2-3 sentences)
3. THE CONCLUSION: What did they find? Why does it matter? (2-3 sentences)
4. KEY TERMS: Define the 3 most important technical terms from this paper in simple language.
Format your response as follows:
**The Problem:**
[Your explanation]
**The Method:**
[Your explanation]
**The Conclusion:**
[Your explanation]
**Key Terms:**
• **Term 1**: Definition
• **Term 2**: Definition
• **Term 3**: Definition
Use simple language, avoid jargon, and make it accessible to someone without expertise in this field.`
},
detailed: {
description: "Comprehensive with methodology depth",
maxTokens: 1500,
systemPrompt: "You are a research analyst providing comprehensive paper analysis.",
promptTemplate: (title, abstract) => `Provide a detailed analysis of this academic paper.
Paper Title: ${title}
Abstract: ${abstract}
Please provide a comprehensive summary that includes:
1. RESEARCH PROBLEM: What specific problem or gap in the field does this research address? (3-4 sentences)
2. METHODOLOGY: What methods, data sources, or approaches were used? Include technical details. (4-5 sentences)
3. KEY FINDINGS: What were the main results and contributions? (3-4 sentences)
4. IMPLICATIONS: What are the practical and theoretical implications of this work? (2-3 sentences)
5. LIMITATIONS: What are the acknowledged limitations of the study? (2 sentences)
6. KEY TERMS & CONCEPTS: Define 5 important technical terms or concepts from this paper.
Format your response as follows:
**Research Problem:**
[Your explanation]
**Methodology:**
[Your explanation]
**Key Findings:**
[Your explanation]
**Implications:**
[Your explanation]
**Limitations:**
[Your explanation]
**Key Terms & Concepts:**
• **Term 1**: Definition
• **Term 2**: Definition
• **Term 3**: Definition
• **Term 4**: Definition
• **Term 5**: Definition`
},
technical: {
description: "Preserve technical terminology",
maxTokens: 1200,
systemPrompt: "You are a domain expert providing technically accurate paper summaries.",
promptTemplate: (title, abstract) => `Provide a technically accurate summary of this academic paper, maintaining all specialized terminology.
Paper Title: ${title}
Abstract: ${abstract}
Provide a summary that preserves technical accuracy:
1. PROBLEM STATEMENT: Technical formulation of the research problem
2. TECHNICAL APPROACH: Methodology with technical details preserved
3. RESULTS: Key findings with technical specifications
4. CONTRIBUTIONS: Original contributions to the field
5. TECHNICAL GLOSSARY: Define 5 technical terms with precise definitions
Format:
**Problem Statement:**
[Technical description]
**Technical Approach:**
[Methodology with terminology]
**Results:**
[Findings]
**Contributions:**
[List]
**Technical Glossary:**
• **Term 1**: Precise definition
• **Term 2**: Precise definition
• **Term 3**: Precise definition`
},
tldr: {
description: "One-paragraph summary",
maxTokens: 200,
systemPrompt: "You specialize in ultra-concise summaries.",
promptTemplate: (title, abstract) => `Provide a single-paragraph TL;DR summary of this paper.
Paper: ${title}
Abstract: ${abstract}
TL;DR: [One paragraph, 3-4 sentences maximum, covering the main point in simple terms]`
}
};
async function simplifyPaper(paperData, style = 'simple') {
const styleConfig = SUMMARY_STYLES[style] || SUMMARY_STYLES.simple;
const prompt = styleConfig.promptTemplate(paperData.title, paperData.abstract);
try {
const groq = await getGroqClient();
const completion = await groq.chat.completions.create({
model: "llama-3.3-70b-versatile",
messages: [
{ role: "system", content: styleConfig.systemPrompt },
{ role: "user", content: prompt },
],
temperature: 0.7,
max_tokens: styleConfig.maxTokens,
});
let text = (completion.choices?.[0]?.message?.content || "").trim();
// Normalize Key Terms heading for the frontend parser.
text = text.replace(
/^(\*\*\s*)?Key\s*Terms\s*:\s*(\*\*)?/gim,
"**Key Terms:**"
);
// If the model omitted key terms and this isn't TL;DR style, add them via a small follow-up.
if (style !== 'tldr' && !/\bKey\s*Terms\b/i.test(text)) {
const keyTermsPrompt = `Return ONLY the Key Terms section in the exact format below. No extra text.
**Key Terms:**
• **Term 1**: Definition
• **Term 2**: Definition
• **Term 3**: Definition
Paper Title: ${paperData.title}
Abstract: ${paperData.abstract}
Existing Summary: ${text}`;
const keyTermsCompletion = await groq.chat.completions.create({
model: "llama-3.3-70b-versatile",
messages: [
{
role: "system",
content: "You extract key terms and define them simply. Output must match the requested format exactly.",
},
{ role: "user", content: keyTermsPrompt },
],
temperature: 0.2,
max_tokens: 250,
});
const keyTermsText = (
keyTermsCompletion.choices?.[0]?.message?.content || ""
)
.trim()
.replace(/^(\*\*\s*)?Key\s*Terms\s*:\s*(\*\*)?/gim, "**Key Terms:**");
if (keyTermsText) {
text = `${text}\n\n${keyTermsText}`.trim();
}
}
return text;
} catch (error) {
throw new Error(`Failed to generate summary: ${error.message}`);
}
}
async function answerQuestion({ question, paper }) {
const context = `Title: ${paper.title || ""}
Authors: ${paper.authors || ""}
Abstract: ${paper.abstract || ""}
Summary: ${paper.summary || ""}`;
const qaPrompt = `You are answering questions about a paper using its abstract/summary. Keep answers concise (4-6 sentences max). If the question cannot be answered from the provided text, say so briefly.
${context}
Question: ${question}
Answer:`;
const groq = await getGroqClient();
const completion = await groq.chat.completions.create({
model: "llama-3.3-70b-versatile",
messages: [
{
role: "system",
content:
"Answer based only on the provided paper text. Be concise and avoid speculation.",
},
{ role: "user", content: qaPrompt },
],
temperature: 0.2,
max_tokens: 400,
});
const answer = completion.choices[0].message.content;
const sources = buildQaSources({ question, paper });
return { answer, sources };
}
function tokenizeForQa(text) {
return (text || "")
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, " ")
.split(/\s+/)
.filter((t) => t.length >= 3);
}
function buildQaSources({ question, paper }) {
const questionTokens = new Set(tokenizeForQa(question));
if (!questionTokens.size) return [];
const candidates = [];
const abstract =
typeof paper?.abstract === "string" ? paper.abstract.trim() : "";
if (abstract) {
candidates.push({ label: "Abstract", text: abstract });
}
const summary =
typeof paper?.summary === "string" ? paper.summary.trim() : "";
if (summary) {
// Split into reasonably sized snippets.
const parts = summary
.split(/\n+/)
.map((s) => s.trim())
.filter(Boolean)
.flatMap((line) => line.split(/(?<=[.!?])\s+/g).map((s) => s.trim()));
for (const part of parts) {
if (part.length < 40) continue;
candidates.push({ label: "Summary", text: part });
}
}
const scored = candidates
.map((c) => {
const tokens = tokenizeForQa(c.text);
let score = 0;
for (const t of tokens) {
if (questionTokens.has(t)) score += 1;
}
// Prefer shorter, denser snippets.
score = score / Math.max(8, Math.sqrt(tokens.length));
return { ...c, score };
})
.filter((c) => c.score > 0)
.sort((a, b) => b.score - a.score);
const out = [];
const seen = new Set();
for (const item of scored) {
const normalized = item.text.toLowerCase().replace(/\s+/g, " ");
if (seen.has(normalized)) continue;
seen.add(normalized);
out.push({
label: item.label,
text:
item.text.length > 220
? item.text.slice(0, 217).trimEnd() + "…"
: item.text,
});
if (out.length >= 3) break;
}
return out;
}
// Auth wrapper routes (vanilla JS frontend; Better Auth remains mounted separately)
app.post(
"/api/auth/signup",
asyncHandler(async (req, res) => {
const auth = await getAuth();
if (!auth) {
return res.status(503).json({
message: "Auth is not configured. Set DATABASE_URL to enable it.",
});
}
const reqId = `${Date.now()}-${Math.random().toString(16).slice(2, 10)}`;
const startedAt = Date.now();
try {
const name = assertString(req.body?.name, "name");
const email = assertString(req.body?.email, "email");
const password = assertString(req.body?.password, "password");
console.log("[auth] signup:start", { reqId });
const { fromNodeHeaders } = await getBetterAuthNode();
const response = await withTimeout(
auth.api.signUpEmail({
headers: fromNodeHeaders(req.headers),
body: {
name,
email,
password,
},
asResponse: true,
}),
12000,
"auth.signUpEmail"
);
await pipeWebResponseToExpress(res, response);
} catch (error) {
console.error("[auth] signup:error", {
reqId,
durationMs: Date.now() - startedAt,
message: error?.message,
});
const APIError = await getAPIErrorClass();
if (error instanceof APIError) {
return res.status(error.status).json({
message: error.message,
});
}
const statusCode = error?.statusCode ?? 500;
res.status(statusCode).json({
message: error?.message ?? "Failed to sign up",
reqId,
});
} finally {
console.log("[auth] signup:end", {
reqId,
durationMs: Date.now() - startedAt,
});
}
})
);
app.post(
"/api/auth/signin",
asyncHandler(async (req, res) => {
const auth = await getAuth();
if (!auth) {
return res.status(503).json({
message: "Auth is not configured. Set DATABASE_URL to enable it.",
});
}
const reqId = `${Date.now()}-${Math.random().toString(16).slice(2, 10)}`;
const startedAt = Date.now();
try {
const email = assertString(req.body?.email, "email");
const password = assertString(req.body?.password, "password");
console.log("[auth] signin:start", { reqId });
const { fromNodeHeaders } = await getBetterAuthNode();
const response = await withTimeout(
auth.api.signInEmail({
headers: fromNodeHeaders(req.headers),
body: {
email,
password,
rememberMe: true,
},
asResponse: true,
}),
12000,
"auth.signInEmail"
);
await pipeWebResponseToExpress(res, response);
} catch (error) {
console.error("[auth] signin:error", {
reqId,
durationMs: Date.now() - startedAt,
message: error?.message,
});
const APIError = await getAPIErrorClass();
if (error instanceof APIError) {
return res.status(error.status).json({
message: error.message,
});
}
const statusCode = error?.statusCode ?? 500;
res.status(statusCode).json({
message: error?.message ?? "Failed to sign in",
reqId,
});
} finally {
console.log("[auth] signin:end", {
reqId,
durationMs: Date.now() - startedAt,
});
}
})
);
app.post(
"/api/auth/signout",
asyncHandler(async (req, res) => {
const auth = await getAuth();
if (!auth) {
return res.status(503).json({
message: "Auth is not configured. Set DATABASE_URL to enable it.",
});
}
try {
const { fromNodeHeaders } = await getBetterAuthNode();
const response = await auth.api.signOut({
headers: fromNodeHeaders(req.headers),
asResponse: true,
});
await pipeWebResponseToExpress(res, response);
} catch (error) {
const APIError = await getAPIErrorClass();
if (error instanceof APIError) {
return res.status(error.status).json({
message: error.message,
});
}
res.status(500).json({
message: error?.message ?? "Failed to sign out",
});
}
})
);
app.get(
"/api/auth/me",
asyncHandler(async (req, res) => {
if (SKIP_AUTH) {
return res.json({ user: { id: "dev-user", email: "dev@example.com" } });
}
const auth = await getAuth();
if (!auth) {
return res.json(null);
}
try {
const { fromNodeHeaders } = await getBetterAuthNode();
const session = await withTimeout(
auth.api.getSession({
headers: fromNodeHeaders(req.headers),
}),
8000,
"auth.getSession"
);
res.json(session);
} catch (error) {
res.status(500).json({
message: error?.message ?? "Failed to get session",