@rol1n/pi-kit 0.1.1 → 0.1.2

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/web-reach/page.ts DELETED
@@ -1,214 +0,0 @@
1
- import { DEFAULT_USER_AGENT, envNum, truncate, withTimeout } from "./transport.ts";
2
- import { extractRSCContent } from "./rsc.ts";
3
- import { extractTitleFromHtml, htmlToMarkdown, isLikelyJSRendered } from "./html.ts";
4
-
5
- const JINA_READER_BASE = "https://r.jina.ai/";
6
-
7
- export async function fetchViaJinaReader(
8
- url: string,
9
- signal?: AbortSignal,
10
- ): Promise<{ text: string; title: string } | null> {
11
- const { ac, done } = withTimeout(30_000, "Jina Reader timed out", signal);
12
- try {
13
- const res = await fetch(`${JINA_READER_BASE}${url}`, {
14
- headers: {
15
- Accept: "text/markdown",
16
- "X-No-Cache": "true",
17
- "User-Agent": DEFAULT_USER_AGENT,
18
- },
19
- signal: ac.signal,
20
- });
21
- if (!res.ok) return null;
22
-
23
- const raw = await res.text();
24
- const contentIndex = raw.indexOf("Markdown Content:");
25
- const markdown = contentIndex >= 0 ? raw.slice(contentIndex + 17).trim() : raw.trim();
26
-
27
- if (
28
- markdown.length < 80 ||
29
- markdown.startsWith("Loading...") ||
30
- markdown.startsWith("Please enable JavaScript")
31
- ) {
32
- return null;
33
- }
34
-
35
- const titleMatch = markdown.match(/^#+\s+(.+)$/m);
36
- const title = titleMatch?.[1]?.trim() || "";
37
-
38
- return { text: markdown, title };
39
- } catch {
40
- return null;
41
- } finally {
42
- done();
43
- }
44
- }
45
-
46
- export function isPdfUrl(url: string, contentType?: string): boolean {
47
- if (contentType?.includes("application/pdf")) return true;
48
- try {
49
- return new URL(url).pathname.toLowerCase().endsWith(".pdf");
50
- } catch {
51
- return false;
52
- }
53
- }
54
-
55
- export async function extractPdfBuffer(
56
- buffer: ArrayBuffer,
57
- url: string,
58
- ): Promise<{ text: string; title: string }> {
59
- try {
60
- const { getDocumentProxy } = await import("unpdf");
61
- const pdf = await getDocumentProxy(new Uint8Array(buffer));
62
- const maxPages = Math.min(pdf.numPages, 80);
63
- const pages: string[] = [];
64
-
65
- for (let i = 1; i <= maxPages; i++) {
66
- const page = await pdf.getPage(i);
67
- const textContent = await page.getTextContent();
68
- const pageText = textContent.items
69
- .map((item: unknown) => (item as { str?: string }).str || "")
70
- .join(" ")
71
- .replace(/\s+/g, " ")
72
- .trim();
73
- if (pageText) pages.push(`--- Page ${i} ---\n${pageText}`);
74
- }
75
-
76
- const title = new URL(url).pathname.split("/").pop() || "PDF Document";
77
- const text = `# ${title}\n\nPages: ${pdf.numPages}\n\n${pages.join("\n\n")}`;
78
- return { text, title };
79
- } catch {
80
- // Fallback plain text extraction
81
- const text = Buffer.from(buffer).toString("latin1").replace(/[^\x20-\x7E\n\r\t]/g, " ");
82
- return {
83
- text: `# PDF Document\n\n${text.slice(0, 8000)}`,
84
- title: "PDF Document",
85
- };
86
- }
87
- }
88
-
89
- const MIN_USEFUL_CONTENT_LENGTH = 300;
90
-
91
- export async function fetchUrl(
92
- url: string,
93
- opts: { mode?: "readable" | "raw" } = {},
94
- signal?: AbortSignal,
95
- ): Promise<{ text: string; title: string; contentType: string; status: number; engine: string }> {
96
- const mode = opts.mode ?? "readable";
97
- const { ac, done } = withTimeout(
98
- envNum("SRP_WEB_FETCH_TIMEOUT_MS", 20_000),
99
- "Web fetch timed out",
100
- signal,
101
- );
102
-
103
- try {
104
- const res = await fetch(url, {
105
- redirect: "follow",
106
- headers: {
107
- "User-Agent": DEFAULT_USER_AGENT,
108
- Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,application/pdf,text/plain,*/*;q=0.8",
109
- },
110
- signal: ac.signal,
111
- });
112
-
113
- if (!res.ok) {
114
- throw new Error(`HTTP ${res.status} ${res.statusText}`);
115
- }
116
-
117
- const contentType = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
118
- const maxBytes = envNum("SRP_WEB_FETCH_MAX_BYTES", 4 * 1024 * 1024);
119
- const arrayBuf = await res.arrayBuffer();
120
-
121
- if (arrayBuf.byteLength > maxBytes) {
122
- throw new Error(`Content exceeds ${Math.round((maxBytes / 1024 / 1024) * 10) / 10} MiB limit.`);
123
- }
124
-
125
- // 1. PDF extraction
126
- if (isPdfUrl(url, contentType)) {
127
- const { text, title } = await extractPdfBuffer(arrayBuf, url);
128
- return { text: truncate(text), title, contentType, status: res.status, engine: "unpdf" };
129
- }
130
-
131
- const body = Buffer.from(arrayBuf).toString("utf8");
132
-
133
- // 2. Raw mode
134
- if (mode === "raw") {
135
- return {
136
- text: truncate(body),
137
- title: extractTitleFromHtml(body) || url,
138
- contentType,
139
- status: res.status,
140
- engine: "raw",
141
- };
142
- }
143
-
144
- // 3. JSON formatting
145
- if (contentType.includes("json")) {
146
- try {
147
- const text = JSON.stringify(JSON.parse(body), null, 2);
148
- return { text: truncate(text), title: "JSON Response", contentType, status: res.status, engine: "json" };
149
- } catch {
150
- return { text: truncate(body), title: "JSON", contentType, status: res.status, engine: "text" };
151
- }
152
- }
153
-
154
- // 4. HTML processing
155
- if (contentType.includes("html") || contentType.includes("xhtml")) {
156
- // 4.1 Attempt Next.js RSC extraction
157
- const rsc = extractRSCContent(body);
158
- if (rsc && rsc.content.length >= MIN_USEFUL_CONTENT_LENGTH) {
159
- return {
160
- text: truncate(rsc.content),
161
- title: rsc.title || extractTitleFromHtml(body),
162
- contentType,
163
- status: res.status,
164
- engine: "nextjs-rsc",
165
- };
166
- }
167
-
168
- // 4.2 Semantic HTML to Markdown
169
- const title = extractTitleFromHtml(body);
170
- const markdown = htmlToMarkdown(body);
171
-
172
- if (markdown.length >= MIN_USEFUL_CONTENT_LENGTH && !isLikelyJSRendered(body)) {
173
- return {
174
- text: truncate(markdown),
175
- title,
176
- contentType,
177
- status: res.status,
178
- engine: "html-markdown",
179
- };
180
- }
181
-
182
- // 4.3 Dynamic JS page or short content: attempt Jina Reader fallback
183
- const jina = await fetchViaJinaReader(url, signal);
184
- if (jina && jina.text.length >= 100) {
185
- return {
186
- text: truncate(jina.text),
187
- title: jina.title || title,
188
- contentType: "text/markdown",
189
- status: res.status,
190
- engine: "jina-reader",
191
- };
192
- }
193
-
194
- return {
195
- text: truncate(markdown || body.slice(0, 4000)),
196
- title,
197
- contentType,
198
- status: res.status,
199
- engine: "html-fallback",
200
- };
201
- }
202
-
203
- // 5. Plain text and other types
204
- return {
205
- text: truncate(body),
206
- title: url.split("/").pop() || "Plain Text",
207
- contentType,
208
- status: res.status,
209
- engine: "text",
210
- };
211
- } finally {
212
- done();
213
- }
214
- }
package/web-reach/rsc.ts DELETED
@@ -1,161 +0,0 @@
1
- export function extractRSCContent(html: string): { title: string; content: string } | null {
2
- if (!html.includes("self.__next_f.push")) return null;
3
-
4
- const chunkMap = new Map<string, string>();
5
- const scriptRegex = /<script>self\.__next_f\.push\(\[1,"([\s\S]*?)"\]\)<\/script>/g;
6
-
7
- for (const match of html.matchAll(scriptRegex)) {
8
- let content: string;
9
- try {
10
- content = JSON.parse('"' + match[1] + '"');
11
- } catch {
12
- continue;
13
- }
14
- for (const line of content.split("\n")) {
15
- if (!line.trim()) continue;
16
- const colonIdx = line.indexOf(":");
17
- if (colonIdx <= 0 || colonIdx > 4) continue;
18
- const id = line.slice(0, colonIdx);
19
- if (!/^[0-9a-f]+$/i.test(id)) continue;
20
- const payload = line.slice(colonIdx + 1);
21
- if (!payload) continue;
22
- const existing = chunkMap.get(id);
23
- if (!existing || payload.length > existing.length) {
24
- chunkMap.set(id, payload);
25
- }
26
- }
27
- }
28
-
29
- if (chunkMap.size === 0) return null;
30
-
31
- const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
32
- const title = titleMatch?.[1]?.split("|")[0]?.trim() || "";
33
-
34
- const parsedCache = new Map<string, unknown>();
35
- function getParsedChunk(id: string): unknown | null {
36
- if (parsedCache.has(id)) return parsedCache.get(id);
37
- const chunk = chunkMap.get(id);
38
- if (!chunk || !chunk.startsWith("[")) {
39
- parsedCache.set(id, null);
40
- return null;
41
- }
42
- try {
43
- const parsed = JSON.parse(chunk);
44
- parsedCache.set(id, parsed);
45
- return parsed;
46
- } catch {
47
- parsedCache.set(id, null);
48
- return null;
49
- }
50
- }
51
-
52
- const visitedRefs = new Set<string>();
53
-
54
- function extractNode(node: unknown, ctx = { inCode: false }): string {
55
- if (node === null || node === undefined) return "";
56
- if (typeof node === "string") {
57
- const refMatch = node.match(/^\$L([0-9a-f]+)$/i);
58
- if (refMatch) {
59
- const refId = refMatch[1];
60
- if (visitedRefs.has(refId)) return "";
61
- visitedRefs.add(refId);
62
- const refNode = getParsedChunk(refId);
63
- const result = refNode ? extractNode(refNode, ctx) : "";
64
- visitedRefs.delete(refId);
65
- return result;
66
- }
67
- if (!ctx.inCode && (node === "$undefined" || node === "$" || /^\$[A-Z]/.test(node))) {
68
- return "";
69
- }
70
- return node.trim() ? node : "";
71
- }
72
- if (typeof node === "number") return String(node);
73
- if (typeof node === "boolean") return "";
74
- if (!Array.isArray(node)) return "";
75
-
76
- if (node[0] === "$" && typeof node[1] === "string") {
77
- const tag = node[1] as string;
78
- const props = (node[3] || {}) as Record<string, unknown>;
79
- const skipTags = [
80
- "script", "style", "svg", "path", "circle", "link", "meta",
81
- "template", "button", "input", "nav", "footer", "aside",
82
- ];
83
- if (skipTags.includes(tag)) return "";
84
-
85
- if (tag.startsWith("$L")) {
86
- const refId = tag.slice(2);
87
- if (visitedRefs.has(refId)) return "";
88
- if (props.baseId && props.children) {
89
- return `## ${String(props.children)}\n\n`;
90
- }
91
- visitedRefs.add(refId);
92
- const refNode = getParsedChunk(refId);
93
- let result = "";
94
- if (refNode) result = extractNode(refNode, ctx);
95
- else if (props.children) result = extractNode(props.children, ctx);
96
- visitedRefs.delete(refId);
97
- return result;
98
- }
99
-
100
- const children = props.children;
101
- const content = children ? extractNode(children, ctx) : "";
102
-
103
- switch (tag) {
104
- case "h1": return `# ${content.trim()}\n\n`;
105
- case "h2": return `## ${content.trim()}\n\n`;
106
- case "h3": return `### ${content.trim()}\n\n`;
107
- case "h4": return `#### ${content.trim()}\n\n`;
108
- case "h5": return `##### ${content.trim()}\n\n`;
109
- case "h6": return `###### ${content.trim()}\n\n`;
110
- case "p": return `${content.trim()}\n\n`;
111
- case "code": {
112
- const cc = children ? extractNode(children, { inCode: true }) : "";
113
- return ctx.inCode ? cc : `\`${cc}\``;
114
- }
115
- case "pre": {
116
- const pc = children ? extractNode(children, { inCode: true }) : "";
117
- return "```\n" + pc + "\n```\n\n";
118
- }
119
- case "strong": case "b": return `**${content}**`;
120
- case "em": case "i": return `*${content}*`;
121
- case "li": return `- ${content.trim()}\n`;
122
- case "ul": case "ol": return content + "\n";
123
- case "blockquote": return `> ${content.trim()}\n\n`;
124
- case "a": {
125
- const href = props.href as string | undefined;
126
- return href && !href.startsWith("#") ? `[${content}](${href})` : content;
127
- }
128
- default: return content;
129
- }
130
- }
131
-
132
- return (node as unknown[]).map((n) => extractNode(n, ctx)).join("");
133
- }
134
-
135
- const contentParts: { order: number; text: string }[] = [];
136
- for (const [id] of chunkMap) {
137
- const parsed = getParsedChunk(id);
138
- if (!parsed) continue;
139
- visitedRefs.clear();
140
- const text = extractNode(parsed);
141
- if (text.trim().length > 50 && !text.includes("404") && !text.includes("not found")) {
142
- contentParts.push({ order: parseInt(id, 16) || 0, text: text.trim() });
143
- }
144
- }
145
-
146
- if (contentParts.length === 0) return null;
147
- contentParts.sort((a, b) => a.order - b.order);
148
-
149
- const seen = new Set<string>();
150
- const uniqueParts: string[] = [];
151
- for (const part of contentParts) {
152
- const key = part.text.slice(0, 150);
153
- if (!seen.has(key)) {
154
- seen.add(key);
155
- uniqueParts.push(part.text);
156
- }
157
- }
158
-
159
- const content = uniqueParts.join("\n\n").replace(/\n{3,}/g, "\n\n").trim();
160
- return content.length > 100 ? { title, content } : null;
161
- }
@@ -1,85 +0,0 @@
1
- import { envNum, truncate, withTimeout } from "./transport.ts";
2
-
3
- const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
4
- const EXA_SEARCH_TOOL = "web_search_exa";
5
-
6
- interface ExaMcpResponse {
7
- result?: {
8
- content?: Array<{ type?: string; text?: string }>;
9
- isError?: boolean;
10
- };
11
- error?: { code?: number; message?: string };
12
- }
13
-
14
- function parseExaResponse(body: string): ExaMcpResponse | undefined {
15
- for (const line of body.split("\n")) {
16
- if (!line.startsWith("data:")) continue;
17
- const payload = line.slice(5).trim();
18
- if (!payload) continue;
19
- try {
20
- const parsed = JSON.parse(payload) as ExaMcpResponse;
21
- if (parsed.result || parsed.error) return parsed;
22
- } catch {
23
- /* continue to next SSE event */
24
- }
25
- }
26
- try {
27
- const parsed = JSON.parse(body) as ExaMcpResponse;
28
- return parsed.result || parsed.error ? parsed : undefined;
29
- } catch {
30
- return undefined;
31
- }
32
- }
33
-
34
- export async function searchWeb(
35
- query: string,
36
- signal?: AbortSignal,
37
- ): Promise<{ text: string; provider: string }> {
38
- query = query.trim();
39
- if (!query) throw new Error("Search query cannot be empty.");
40
- const { ac, done } = withTimeout(
41
- envNum("SRP_WEB_SEARCH_TIMEOUT_MS", 60_000),
42
- "Search request timed out",
43
- signal,
44
- );
45
- try {
46
- const res = await fetch(`${EXA_MCP_URL}?tools=${EXA_SEARCH_TOOL}`, {
47
- method: "POST",
48
- headers: {
49
- "Content-Type": "application/json",
50
- Accept: "application/json, text/event-stream",
51
- "x-exa-source": "web-reach",
52
- },
53
- body: JSON.stringify({
54
- jsonrpc: "2.0",
55
- id: 1,
56
- method: "tools/call",
57
- params: { name: EXA_SEARCH_TOOL, arguments: { query, numResults: 6 } },
58
- }),
59
- signal: ac.signal,
60
- });
61
- const body = await res.text();
62
- if (!res.ok) {
63
- const hint = res.status === 429 ? " (Exa free tier rate limit reached; please try again later)" : "";
64
- throw new Error(`Exa MCP HTTP ${res.status}${hint}: ${body.slice(0, 300)}`);
65
- }
66
-
67
- const payload = parseExaResponse(body);
68
- if (!payload) throw new Error("Exa MCP returned an unparseable response.");
69
- if (payload.error) {
70
- throw new Error(
71
- `Exa MCP error${payload.error.code ? ` ${payload.error.code}` : ""}: ${payload.error.message ?? "Unknown error"}`,
72
- );
73
- }
74
-
75
- const text = payload.result?.content
76
- ?.find((item) => item.type === "text" && item.text?.trim())
77
- ?.text?.trim();
78
- if (payload.result?.isError || !text) {
79
- throw new Error(text || "Exa MCP returned empty content.");
80
- }
81
- return { text: truncate(text), provider: "exa-mcp" };
82
- } finally {
83
- done();
84
- }
85
- }
@@ -1,35 +0,0 @@
1
- export const DEFAULT_USER_AGENT =
2
- "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 web-reach/2.0";
3
-
4
- const MAX_RETURN_CHARS = 35_000;
5
-
6
- export function envNum(name: string, fallback: number): number {
7
- const n = Number(process.env[name]);
8
- return Number.isFinite(n) && n > 0 ? n : fallback;
9
- }
10
-
11
- // ============================ Timeout & Helpers ============================
12
-
13
- export function withTimeout(
14
- ms: number,
15
- label: string,
16
- signal?: AbortSignal,
17
- ): { ac: AbortController; done: () => void } {
18
- const ac = new AbortController();
19
- const timer = setTimeout(() => ac.abort(new Error(`${label} timed out (${ms / 1000}s)`)), ms);
20
- const onAbort = () => ac.abort(signal?.reason);
21
- signal?.addEventListener("abort", onAbort, { once: true });
22
- if (signal?.aborted) onAbort();
23
- return {
24
- ac,
25
- done: () => {
26
- clearTimeout(timer);
27
- signal?.removeEventListener("abort", onAbort);
28
- },
29
- };
30
- }
31
-
32
- export function truncate(text: string, limit = MAX_RETURN_CHARS): string {
33
- if (text.length <= limit) return text;
34
- return text.slice(0, limit) + `\n\n...(content truncated to ${limit} characters)`;
35
- }