File size: 11,712 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { describe, it, expect, vi, beforeEach } from "vitest";

// Mock fetch globally before any imports that use it
const mockFetch = vi.fn();
vi.stubGlobal("fetch", mockFetch);

import {
  stripHtml,
  extractTitle,
  extractContent,
  estimateDifficulty,
  createFromText,
  fetchAndExtract,
  MIN_CONTENT_CHARS,
  MAX_CONTENT_CHARS,
} from "../extract";

// ---------------------------------------------------------------------------
// Helpers for fetchAndExtract tests
// ---------------------------------------------------------------------------

function makeResponse(
  opts: {
    ok?: boolean;
    status?: number;
    statusText?: string;
    contentType?: string;
    body?: string;
  } = {},
) {
  const {
    ok = true,
    status = 200,
    statusText = "OK",
    contentType = "text/html; charset=utf-8",
    body = "",
  } = opts;
  return {
    ok,
    status,
    statusText,
    headers: { get: (key: string) => (key === "content-type" ? contentType : null) },
    text: vi.fn().mockResolvedValue(body),
  };
}

/** Build an HTML page with enough body text to pass MIN_CONTENT_CHARS */
function makeHtmlPage(opts: {
  title?: string;
  body?: string;
  wrap?: "article" | "main" | "body";
} = {}): string {
  const title = opts.title ?? "Test Article";
  const bodyText = opts.body ?? "This is a test sentence. ".repeat(20);
  const wrap = opts.wrap ?? "article";

  const inner =
    wrap === "article"
      ? `<article>${bodyText}</article>`
      : wrap === "main"
        ? `<main>${bodyText}</main>`
        : `<body>${bodyText}</body>`;

  return `<html><head><title>${title}</title></head><body>${inner}</body></html>`;
}

beforeEach(() => {
  mockFetch.mockReset();
});

describe("stripHtml", () => {
  it("removes basic tags", () => {
    expect(stripHtml("<p>Hello <b>world</b></p>")).toBe("Hello world");
  });

  it("removes script and style tags with content", () => {
    expect(
      stripHtml('<p>text</p><script>alert("x")</script><style>.a{}</style><p>more</p>'),
    ).toBe("text more");
  });

  it("removes nav, header, footer, aside", () => {
    expect(
      stripHtml("<nav>nav</nav><main>content</main><footer>foot</footer>"),
    ).toBe("content");
  });

  it("decodes common HTML entities", () => {
    expect(stripHtml("&amp; &lt; &gt; &quot; &#39; &mdash; &ndash; &hellip;")).toBe(
      '& < > " \' — – …',
    );
  });

  it("collapses whitespace", () => {
    expect(stripHtml("  hello   world  ")).toBe("hello world");
  });
});

describe("extractTitle", () => {
  it("extracts from <title> tag", () => {
    expect(extractTitle("<html><head><title>My Article</title></head></html>")).toBe(
      "My Article",
    );
  });

  it("falls back to og:title", () => {
    const html =
      '<html><head><meta property="og:title" content="OG Title"></head></html>';
    expect(extractTitle(html)).toBe("OG Title");
  });

  it("returns 'Untitled Article' when no title found", () => {
    expect(extractTitle("<html><head></head></html>")).toBe("Untitled Article");
  });

  it("strips HTML from title content", () => {
    expect(extractTitle("<title>My <b>Bold</b> Title</title>")).toBe("My Bold Title");
  });
});

describe("extractContent", () => {
  const longText = "A ".repeat(200); // > MIN_CONTENT_CHARS

  it("prefers <article> tag", () => {
    const html = `<body><div>sidebar</div><article><p>${longText}</p></article></body>`;
    const result = extractContent(html);
    expect(result).toContain("A");
    expect(result).not.toContain("sidebar");
  });

  it("falls back to <main> if no article", () => {
    const html = `<body><div>sidebar</div><main><p>${longText}</p></main></body>`;
    const result = extractContent(html);
    expect(result.length).toBeGreaterThan(MIN_CONTENT_CHARS);
  });

  it("falls back to body if no article or main", () => {
    const html = `<body><p>${longText}</p></body>`;
    const result = extractContent(html);
    expect(result.length).toBeGreaterThan(0);
  });

  it("skips short article tags", () => {
    const html = `<body><article>Short</article><main><p>${longText}</p></main></body>`;
    const result = extractContent(html);
    expect(result.length).toBeGreaterThan(MIN_CONTENT_CHARS);
  });
});

describe("estimateDifficulty", () => {
  it("returns beginner for simple text", () => {
    const simple = "The cat sat on the mat. It was a good day. The sun was out.";
    expect(estimateDifficulty(simple)).toBe("beginner");
  });

  it("returns advanced for complex text", () => {
    const complex =
      "The epistemological implications of Bayesian probabilistic reasoning fundamentally reconceptualize our understanding of inferential methodologies across interdisciplinary academic paradigms.";
    expect(estimateDifficulty(complex)).toBe("advanced");
  });

  it("returns intermediate for mixed text", () => {
    const medium =
      "Understanding economic principles requires careful analysis. Market dynamics and behavioral patterns interact in complex ways. The relationship between supply and demand forms the foundation of modern economic theory.";
    const result = estimateDifficulty(medium);
    expect(["intermediate", "advanced"]).toContain(result);
  });
});

describe("createFromText", () => {
  const validText = "A ".repeat(150); // 300 chars, > MIN_CONTENT_CHARS

  it("creates article from valid text", () => {
    const result = createFromText(validText, "Test Title");
    expect(result.title).toBe("Test Title");
    expect(result.body).toBe(validText.trim());
    expect(result.domain).toBe("Custom");
    expect(result.sourceUrl).toBe("");
    expect(result.wordCount).toBeGreaterThan(0);
    expect(result.estimatedMinutes).toBeGreaterThanOrEqual(1);
  });

  it("uses default title when none provided", () => {
    const result = createFromText(validText);
    expect(result.title).toBe("Custom Reading");
  });

  it("throws on text shorter than minimum", () => {
    expect(() => createFromText("Too short")).toThrow(/too short/i);
  });

  it("truncates text exceeding maximum", () => {
    const longText = "Word. ".repeat(5000); // way over MAX_CONTENT_CHARS
    const result = createFromText(longText);
    expect(result.body.length).toBeLessThanOrEqual(MAX_CONTENT_CHARS + 1);
  });

  it("trims whitespace", () => {
    const result = createFromText("  " + validText + "  ");
    expect(result.body).not.toMatch(/^\s/);
    expect(result.body).not.toMatch(/\s$/);
  });
});

// ---------------------------------------------------------------------------
// fetchAndExtract — fetch-layer tests
// ---------------------------------------------------------------------------

describe("fetchAndExtract", () => {
  it("returns extracted article for a valid HTML response", async () => {
    const html = makeHtmlPage({ title: "Great Article", wrap: "article" });
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    const result = await fetchAndExtract("https://example.com/article");
    expect(result.title).toBe("Great Article");
    expect(result.domain).toBe("example.com");
    expect(result.sourceUrl).toBe("https://example.com/article");
    expect(result.wordCount).toBeGreaterThan(0);
    expect(result.estimatedMinutes).toBeGreaterThanOrEqual(1);
    expect(result.body.length).toBeGreaterThan(0);
  });

  it("strips www. from domain", async () => {
    const html = makeHtmlPage();
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    const result = await fetchAndExtract("https://www.example.com/page");
    expect(result.domain).toBe("example.com");
  });

  it("throws on non-ok HTTP response", async () => {
    mockFetch.mockResolvedValue(
      makeResponse({ ok: false, status: 404, statusText: "Not Found" }),
    );

    await expect(fetchAndExtract("https://example.com/missing")).rejects.toThrow(
      /404.*Not Found/i,
    );
  });

  it("throws on unsupported content type (PDF)", async () => {
    mockFetch.mockResolvedValue(
      makeResponse({ contentType: "application/pdf" }),
    );

    await expect(fetchAndExtract("https://example.com/file.pdf")).rejects.toThrow(
      /unsupported content type/i,
    );
  });

  it("accepts text/plain content type", async () => {
    const plainText = "This is a plain text article. ".repeat(15);
    mockFetch.mockResolvedValue(
      makeResponse({ contentType: "text/plain", body: plainText }),
    );

    // text/plain has no article/main tags — falls back to body strip
    const result = await fetchAndExtract("https://example.com/plain.txt");
    expect(result.body.length).toBeGreaterThan(0);
  });

  it("accepts application/xhtml content type", async () => {
    const html = makeHtmlPage({ title: "XHTML Page", wrap: "article" });
    mockFetch.mockResolvedValue(
      makeResponse({ contentType: "application/xhtml+xml", body: html }),
    );

    const result = await fetchAndExtract("https://example.com/page.xhtml");
    expect(result.title).toBe("XHTML Page");
  });

  it("throws when extracted content is too short", async () => {
    const html = "<html><head><title>Short</title></head><body><p>Hi</p></body></html>";
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    await expect(fetchAndExtract("https://example.com/short")).rejects.toThrow(
      /could not extract enough/i,
    );
  });

  it("truncates content exceeding MAX_CONTENT_CHARS", async () => {
    // Build a very long article body
    const longContent = "This is a complete sentence. ".repeat(1500); // ~45K chars
    const html = makeHtmlPage({ body: longContent, wrap: "article" });
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    const result = await fetchAndExtract("https://example.com/long");
    // Body is formatted text; underlying raw content was capped at MAX_CONTENT_CHARS
    // so word count won't be absurdly large
    expect(result.wordCount).toBeLessThan(15_000);
  });

  it("sends correct User-Agent header", async () => {
    const html = makeHtmlPage();
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    await fetchAndExtract("https://example.com/article");
    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers["User-Agent"]).toMatch(/RotNot/);
  });

  it("propagates network errors", async () => {
    mockFetch.mockRejectedValue(new TypeError("Network error"));

    await expect(fetchAndExtract("https://example.com/article")).rejects.toThrow(
      "Network error",
    );
  });

  it("falls back to main tag when article is absent", async () => {
    const html = makeHtmlPage({ wrap: "main" });
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    const result = await fetchAndExtract("https://example.com/article");
    expect(result.body.length).toBeGreaterThan(0);
  });

  it("computes estimatedMinutes from word count", async () => {
    // ~400 words → 2 minutes at 200 wpm
    const body = "word ".repeat(400);
    const html = makeHtmlPage({ body, wrap: "article" });
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    const result = await fetchAndExtract("https://example.com/article");
    expect(result.estimatedMinutes).toBeGreaterThanOrEqual(1);
  });

  it("uses og:title when <title> is absent", async () => {
    const bodyText = "This is a test sentence. ".repeat(20);
    const html = `<html><head><meta property="og:title" content="OG Article Title"></head><body><article>${bodyText}</article></body></html>`;
    mockFetch.mockResolvedValue(makeResponse({ body: html }));

    const result = await fetchAndExtract("https://example.com/article");
    expect(result.title).toBe("OG Article Title");
  });
});