@arabold/docs-mcp-server 2.2.2 → 2.4.0

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.
@@ -9,7 +9,7 @@ import path from "node:path";
9
9
  import { URL as URL$1 } from "node:url";
10
10
  import envPaths from "env-paths";
11
11
  import { l as logger, n as normalizeEnvValue, g as getLogLevelFromEnv, a as setLogLevel, L as LogLevel } from "./logger-CLtABTNb.js";
12
- import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus, g as getProjectRoot, E as EmbeddingConfig, a as EventType, S as ServerEventName, s as shouldEnableTelemetry, r as resolveProtocol, p as parseAuthConfig, v as validateAuthConfig, w as warnHttpUsage, e as ensurePlaywrightBrowsersInstalled, b as getEventBus, h as handleEmbeddingModelChange, c as createAppServerConfig, d as parseHeaders, f as validatePort, i as validateHost, j as resolveStorePath, k as initTelemetry, l as EventBusService, m as TelemetryService } from "./utils-ntayxPjd.js";
12
+ import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus, f as getProjectRoot, E as EmbeddingConfig, b as EventType, S as ServerEventName, s as shouldEnableTelemetry, r as resolveProtocol, p as parseAuthConfig, v as validateAuthConfig, w as warnHttpUsage, e as ensurePlaywrightBrowsersInstalled, g as getEventBus, h as handleEmbeddingModelChange, d as createAppServerConfig, j as parseHeaders, m as validatePort, l as validateHost, k as resolveStorePath, i as initTelemetry, a as EventBusService, c as TelemetryService } from "./utils-CUTutkx-.js";
13
13
  import yargs from "yargs";
14
14
  import { hideBin } from "yargs/helpers";
15
15
  import yaml from "yaml";
@@ -28,9 +28,14 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
28
28
  import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
29
29
  import { z as z$1 } from "zod/v3";
30
30
  import { chromium } from "playwright";
31
+ import { lookup } from "node:dns/promises";
32
+ import fs$1 from "node:fs/promises";
33
+ import net from "node:net";
34
+ import os from "node:os";
35
+ import { minimatch } from "minimatch";
31
36
  import mime from "mime";
32
37
  import { HeaderGenerator } from "header-generator";
33
- import fs$1 from "node:fs/promises";
38
+ import https from "node:https";
34
39
  import axios from "axios";
35
40
  import { extractBytes } from "@kreuzberg/node";
36
41
  import { VirtualConsole, JSDOM } from "jsdom";
@@ -63,13 +68,11 @@ import DOMPurify from "dompurify";
63
68
  import { escapeHtml } from "@kitajs/html";
64
69
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
65
70
  import { v4 } from "uuid";
66
- import { minimatch } from "minimatch";
67
71
  import { exec } from "node:child_process";
68
72
  import { promisify } from "node:util";
69
73
  import { Readable } from "node:stream";
70
74
  import * as tar from "tar";
71
75
  import yauzl from "yauzl";
72
- import os from "node:os";
73
76
  class StoreError extends Error {
74
77
  constructor(message, cause) {
75
78
  super(cause ? `${message} caused by ${cause}` : message);
@@ -80,6 +83,7 @@ class StoreError extends Error {
80
83
  this.stack = causeError.stack;
81
84
  }
82
85
  }
86
+ cause;
83
87
  }
84
88
  class LibraryNotFoundInStoreError extends StoreError {
85
89
  constructor(library, similarLibraries = []) {
@@ -91,6 +95,8 @@ class LibraryNotFoundInStoreError extends StoreError {
91
95
  this.library = library;
92
96
  this.similarLibraries = similarLibraries;
93
97
  }
98
+ library;
99
+ similarLibraries;
94
100
  }
95
101
  class VersionNotFoundInStoreError extends StoreError {
96
102
  constructor(library, version, availableVersions) {
@@ -104,6 +110,9 @@ class VersionNotFoundInStoreError extends StoreError {
104
110
  this.version = version;
105
111
  this.availableVersions = availableVersions;
106
112
  }
113
+ library;
114
+ version;
115
+ availableVersions;
107
116
  }
108
117
  class DimensionError extends StoreError {
109
118
  constructor(modelName, modelDimension, dbDimension) {
@@ -114,6 +123,9 @@ class DimensionError extends StoreError {
114
123
  this.modelDimension = modelDimension;
115
124
  this.dbDimension = dbDimension;
116
125
  }
126
+ modelName;
127
+ modelDimension;
128
+ dbDimension;
117
129
  }
118
130
  class ConnectionError extends StoreError {
119
131
  }
@@ -133,6 +145,10 @@ and follow the prompts.`
133
145
  this.currentModel = currentModel;
134
146
  this.currentDimension = currentDimension;
135
147
  }
148
+ previousModel;
149
+ previousDimension;
150
+ currentModel;
151
+ currentDimension;
136
152
  }
137
153
  class MissingCredentialsError extends StoreError {
138
154
  constructor(provider, missingCredentials) {
@@ -141,6 +157,7 @@ class MissingCredentialsError extends StoreError {
141
157
  );
142
158
  this.provider = provider;
143
159
  }
160
+ provider;
144
161
  }
145
162
  class FixedDimensionEmbeddings extends Embeddings {
146
163
  constructor(embeddings, targetDimension, providerAndModel, allowTruncate = false) {
@@ -152,6 +169,9 @@ class FixedDimensionEmbeddings extends Embeddings {
152
169
  this.provider = modelName ? providerOrModel : "openai";
153
170
  this.model = modelName || providerOrModel;
154
171
  }
172
+ embeddings;
173
+ targetDimension;
174
+ allowTruncate;
155
175
  provider;
156
176
  model;
157
177
  /**
@@ -336,6 +356,16 @@ function createEmbeddingModel(providerAndModel, runtime) {
336
356
  throw new UnsupportedProviderError(provider);
337
357
  }
338
358
  }
359
+ const envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
360
+ if (Array.isArray(value)) {
361
+ return value;
362
+ }
363
+ const parsed = yaml.parse(value);
364
+ if (Array.isArray(parsed)) {
365
+ return parsed.map((item) => String(item));
366
+ }
367
+ return [value];
368
+ }).pipe(z.array(z.string()));
339
369
  const envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
340
370
  if (typeof val === "boolean") return val;
341
371
  const lower = val.toLowerCase().trim();
@@ -370,8 +400,10 @@ const DEFAULT_CONFIG = {
370
400
  maxConcurrency: 3,
371
401
  abortOnFailureRate: 0.5,
372
402
  preserveHashes: false,
403
+ skipKnownTrackers: true,
373
404
  pageTimeoutMs: 5e3,
374
405
  browserTimeoutMs: 3e4,
406
+ htmlExtractor: "cheerio",
375
407
  fetcher: {
376
408
  maxRetries: 3,
377
409
  baseDelayMs: 1e3,
@@ -381,6 +413,21 @@ const DEFAULT_CONFIG = {
381
413
  document: {
382
414
  maxSize: 10 * 1024 * 1024
383
415
  // 10MB max size for PDF/Office documents
416
+ },
417
+ security: {
418
+ network: {
419
+ mode: "open",
420
+ allowPrivateNetworks: false,
421
+ allowedHosts: [],
422
+ allowedCidrs: [],
423
+ allowInvalidTls: false
424
+ },
425
+ fileAccess: {
426
+ mode: "allowedRoots",
427
+ allowedRoots: ["$DOCUMENTS"],
428
+ followSymlinks: false,
429
+ includeHidden: false
430
+ }
384
431
  }
385
432
  },
386
433
  splitter: {
@@ -450,8 +497,10 @@ const AppConfigSchema = z.object({
450
497
  maxConcurrency: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxConcurrency),
451
498
  abortOnFailureRate: z.coerce.number().min(0).max(1).default(DEFAULT_CONFIG.scraper.abortOnFailureRate),
452
499
  preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),
500
+ skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
453
501
  pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
454
502
  browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
503
+ htmlExtractor: z.enum(["cheerio", "defuddle"]).default(DEFAULT_CONFIG.scraper.htmlExtractor),
455
504
  fetcher: z.object({
456
505
  maxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),
457
506
  baseDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),
@@ -460,7 +509,36 @@ const AppConfigSchema = z.object({
460
509
  }).default(DEFAULT_CONFIG.scraper.fetcher),
461
510
  document: z.object({
462
511
  maxSize: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.document.maxSize)
463
- }).default(DEFAULT_CONFIG.scraper.document)
512
+ }).default(DEFAULT_CONFIG.scraper.document),
513
+ security: z.object({
514
+ network: z.object({
515
+ mode: z.enum(["open", "allowlist"]).default(DEFAULT_CONFIG.scraper.security.network.mode),
516
+ allowPrivateNetworks: envBoolean.default(
517
+ DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks
518
+ ),
519
+ allowedHosts: envStringArray.default(
520
+ DEFAULT_CONFIG.scraper.security.network.allowedHosts
521
+ ),
522
+ allowedCidrs: envStringArray.default(
523
+ DEFAULT_CONFIG.scraper.security.network.allowedCidrs
524
+ ),
525
+ allowInvalidTls: envBoolean.default(
526
+ DEFAULT_CONFIG.scraper.security.network.allowInvalidTls
527
+ )
528
+ }).default(DEFAULT_CONFIG.scraper.security.network),
529
+ fileAccess: z.object({
530
+ mode: z.enum(["disabled", "allowedRoots", "unrestricted"]).default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),
531
+ allowedRoots: envStringArray.default(
532
+ DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots
533
+ ),
534
+ followSymlinks: envBoolean.default(
535
+ DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks
536
+ ),
537
+ includeHidden: envBoolean.default(
538
+ DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden
539
+ )
540
+ }).default(DEFAULT_CONFIG.scraper.security.fileAccess)
541
+ }).default(DEFAULT_CONFIG.scraper.security)
464
542
  }).default(DEFAULT_CONFIG.scraper),
465
543
  splitter: z.object({
466
544
  minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),
@@ -578,7 +656,43 @@ function loadConfig(cliArgs = {}, options = {}) {
578
656
  if (!getAtPath(mergedInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) {
579
657
  setAtPath(mergedInput, ["app", "embeddingModel"], "text-embedding-3-small");
580
658
  }
581
- return AppConfigSchema.parse(mergedInput);
659
+ const parseResult = AppConfigSchema.safeParse(mergedInput);
660
+ if (parseResult.success) {
661
+ return parseResult.data;
662
+ }
663
+ if (!isReadOnlyConfig && fs.existsSync(configPath)) {
664
+ const quarantinePath = `${configPath}.invalid-${Date.now()}`;
665
+ try {
666
+ fs.renameSync(configPath, quarantinePath);
667
+ logger.warn(
668
+ `Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`
669
+ );
670
+ } catch (renameError) {
671
+ logger.warn(
672
+ `Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`
673
+ );
674
+ }
675
+ } else {
676
+ logger.warn(
677
+ `Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`
678
+ );
679
+ }
680
+ const fallbackInput = deepMerge(
681
+ defaults,
682
+ deepMerge(envConfig, cliConfig)
683
+ );
684
+ if (!getAtPath(fallbackInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) {
685
+ setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
686
+ }
687
+ const fallback = AppConfigSchema.parse(fallbackInput);
688
+ if (!isReadOnlyConfig) {
689
+ try {
690
+ saveConfigFile(configPath, fallback);
691
+ } catch (error) {
692
+ logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
693
+ }
694
+ }
695
+ return fallback;
582
696
  }
583
697
  function loadConfigFile(filePath) {
584
698
  if (!fs.existsSync(filePath)) return null;
@@ -681,13 +795,14 @@ function getAtPath(obj, pathArr) {
681
795
  function deepMerge(target, source) {
682
796
  if (typeof target !== "object" || target === null) return source;
683
797
  if (typeof source !== "object" || source === null) return target;
798
+ if (Array.isArray(target) || Array.isArray(source)) return source;
684
799
  const t2 = target;
685
800
  const s = source;
686
801
  const output = { ...t2 };
687
802
  for (const key of Object.keys(s)) {
688
803
  const sValue = s[key];
689
804
  const tValue = t2[key];
690
- if (typeof sValue === "object" && sValue !== null && typeof tValue === "object" && tValue !== null && key in t2) {
805
+ if (typeof sValue === "object" && sValue !== null && !Array.isArray(sValue) && typeof tValue === "object" && tValue !== null && !Array.isArray(tValue) && key in t2) {
691
806
  output[key] = deepMerge(tValue, sValue);
692
807
  } else {
693
808
  output[key] = sValue;
@@ -965,6 +1080,7 @@ class ProxyAuthManager {
965
1080
  constructor(config) {
966
1081
  this.config = config;
967
1082
  }
1083
+ config;
968
1084
  proxyProvider = null;
969
1085
  discoveredEndpoints = null;
970
1086
  jwks = null;
@@ -1365,6 +1481,8 @@ class RemoteEventProxy {
1365
1481
  this.remoteWorkerUrl = remoteWorkerUrl;
1366
1482
  this.localEventBus = localEventBus;
1367
1483
  }
1484
+ remoteWorkerUrl;
1485
+ localEventBus;
1368
1486
  trpcClient = null;
1369
1487
  wsClient = null;
1370
1488
  subscription = null;
@@ -1461,6 +1579,7 @@ class ToolError extends Error {
1461
1579
  this.toolName = toolName;
1462
1580
  this.name = this.constructor.name;
1463
1581
  }
1582
+ toolName;
1464
1583
  }
1465
1584
  class ValidationError extends ToolError {
1466
1585
  }
@@ -2012,6 +2131,8 @@ class ScraperError extends Error {
2012
2131
  Caused by: ${cause.stack}`;
2013
2132
  }
2014
2133
  }
2134
+ isRetryable;
2135
+ cause;
2015
2136
  }
2016
2137
  class InvalidUrlError extends ScraperError {
2017
2138
  constructor(url, cause) {
@@ -2028,6 +2149,9 @@ class RedirectError extends ScraperError {
2028
2149
  this.redirectUrl = redirectUrl;
2029
2150
  this.statusCode = statusCode;
2030
2151
  }
2152
+ originalUrl;
2153
+ redirectUrl;
2154
+ statusCode;
2031
2155
  }
2032
2156
  class ChallengeError extends ScraperError {
2033
2157
  constructor(url, statusCode, challengeType) {
@@ -2039,6 +2163,9 @@ class ChallengeError extends ScraperError {
2039
2163
  this.statusCode = statusCode;
2040
2164
  this.challengeType = challengeType;
2041
2165
  }
2166
+ url;
2167
+ statusCode;
2168
+ challengeType;
2042
2169
  }
2043
2170
  class TlsCertificateError extends ScraperError {
2044
2171
  constructor(url, code, cause) {
@@ -2050,6 +2177,499 @@ class TlsCertificateError extends ScraperError {
2050
2177
  this.url = url;
2051
2178
  this.code = code;
2052
2179
  }
2180
+ url;
2181
+ code;
2182
+ }
2183
+ class AccessPolicyError extends ScraperError {
2184
+ constructor(message) {
2185
+ super(message, false);
2186
+ }
2187
+ }
2188
+ const DEFAULT_FILE_EXCLUSIONS = [
2189
+ // CHANGELOG files (case variations)
2190
+ "**/CHANGELOG.md",
2191
+ "**/changelog.md",
2192
+ "**/CHANGELOG.mdx",
2193
+ "**/changelog.mdx",
2194
+ // LICENSE files (case variations)
2195
+ "**/LICENSE",
2196
+ "**/LICENSE.md",
2197
+ "**/license.md",
2198
+ // CODE_OF_CONDUCT files (case variations)
2199
+ "**/CODE_OF_CONDUCT.md",
2200
+ "**/code_of_conduct.md",
2201
+ // Test files
2202
+ "**/*.test.*",
2203
+ "**/*.spec.*",
2204
+ "**/*_test.py",
2205
+ "**/*_test.go",
2206
+ // Package manager lock files
2207
+ "**/*.lock",
2208
+ "**/package-lock.json",
2209
+ "**/yarn.lock",
2210
+ "**/pnpm-lock.yaml",
2211
+ "**/go.sum",
2212
+ // Build artifacts
2213
+ "**/*.min.js",
2214
+ "**/*.min.css",
2215
+ "**/*.map",
2216
+ "**/*.d.ts",
2217
+ // IDE/System files
2218
+ "**/.DS_Store",
2219
+ "**/Thumbs.db",
2220
+ "**/*.swp",
2221
+ "**/*.swo",
2222
+ // Internal config files (using regex pattern)
2223
+ "/.*\\.(ini|cfg|conf|log|pid)$/"
2224
+ ];
2225
+ const DEFAULT_FOLDER_EXCLUSIONS = [
2226
+ // Archive and deprecated content (matches anywhere in path)
2227
+ "**/archive/**",
2228
+ "**/archived/**",
2229
+ "**/deprecated/**",
2230
+ "**/legacy/**",
2231
+ "**/old/**",
2232
+ "**/outdated/**",
2233
+ "**/previous/**",
2234
+ "**/superseded/**",
2235
+ // Specific paths that don't follow the general pattern
2236
+ "docs/old/**",
2237
+ // Test directories
2238
+ "**/test/**",
2239
+ "**/tests/**",
2240
+ "**/__tests__/**",
2241
+ "**/spec/**",
2242
+ // Build output directories
2243
+ "**/dist/**",
2244
+ "**/build/**",
2245
+ "**/out/**",
2246
+ "**/target/**",
2247
+ "**/.next/**",
2248
+ "**/.nuxt/**",
2249
+ // IDE directories
2250
+ "**/.vscode/**",
2251
+ "**/.idea/**",
2252
+ // Internationalization folders - non-English locales
2253
+ "**/i18n/ar*/**",
2254
+ "**/i18n/de*/**",
2255
+ "**/i18n/es*/**",
2256
+ "**/i18n/fr*/**",
2257
+ "**/i18n/hi*/**",
2258
+ "**/i18n/it*/**",
2259
+ "**/i18n/ja*/**",
2260
+ "**/i18n/ko*/**",
2261
+ "**/i18n/nl*/**",
2262
+ "**/i18n/pl*/**",
2263
+ "**/i18n/pt*/**",
2264
+ "**/i18n/ru*/**",
2265
+ "**/i18n/sv*/**",
2266
+ "**/i18n/th*/**",
2267
+ "**/i18n/tr*/**",
2268
+ "**/i18n/vi*/**",
2269
+ "**/i18n/zh*/**",
2270
+ // Common locale folder patterns
2271
+ "**/zh-cn/**",
2272
+ "**/zh-hk/**",
2273
+ "**/zh-mo/**",
2274
+ "**/zh-sg/**",
2275
+ "**/zh-tw/**"
2276
+ ];
2277
+ const DEFAULT_EXCLUSION_PATTERNS = [
2278
+ ...DEFAULT_FILE_EXCLUSIONS,
2279
+ ...DEFAULT_FOLDER_EXCLUSIONS
2280
+ ];
2281
+ function getEffectiveExclusionPatterns(userPatterns) {
2282
+ if (userPatterns !== void 0) {
2283
+ return userPatterns;
2284
+ }
2285
+ return DEFAULT_EXCLUSION_PATTERNS;
2286
+ }
2287
+ function isRegexPattern(pattern) {
2288
+ return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
2289
+ }
2290
+ function patternToRegExp(pattern) {
2291
+ if (isRegexPattern(pattern)) {
2292
+ return new RegExp(pattern.slice(1, -1));
2293
+ }
2294
+ const re = minimatch.makeRe(pattern, { dot: true });
2295
+ if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
2296
+ return re;
2297
+ }
2298
+ const URL_WITH_PROTOCOL_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
2299
+ function matchesAnyPattern(path2, patterns) {
2300
+ if (!patterns || patterns.length === 0) return false;
2301
+ const isFullUrl = URL_WITH_PROTOCOL_RE.test(path2);
2302
+ const normalizedPath = isFullUrl || path2.startsWith("/") ? path2 : `/${path2}`;
2303
+ return patterns.some((pattern) => {
2304
+ if (isRegexPattern(pattern)) {
2305
+ return patternToRegExp(pattern).test(normalizedPath);
2306
+ }
2307
+ const pathForMatch = normalizedPath.replace(/^\//, "");
2308
+ const patternForMatch = pattern.startsWith("/") ? pattern.slice(1) : pattern;
2309
+ return minimatch(pathForMatch, patternForMatch, { dot: true });
2310
+ });
2311
+ }
2312
+ function matchesAnyHostPattern(value, patterns) {
2313
+ if (!patterns || patterns.length === 0) return false;
2314
+ const normalized = value.toLowerCase();
2315
+ return patterns.some((pattern) => {
2316
+ if (isRegexPattern(pattern)) {
2317
+ return patternToRegExp(pattern).test(value);
2318
+ }
2319
+ return minimatch(normalized, pattern.toLowerCase(), { dot: true });
2320
+ });
2321
+ }
2322
+ function extractPathAndQuery(url) {
2323
+ try {
2324
+ const u = new URL(url);
2325
+ return u.pathname + (u.search || "");
2326
+ } catch {
2327
+ return url;
2328
+ }
2329
+ }
2330
+ function shouldIncludeUrl(url, includePatterns, excludePatterns) {
2331
+ const path2 = extractPathAndQuery(url);
2332
+ const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
2333
+ let basename;
2334
+ if (url.startsWith("file://")) {
2335
+ try {
2336
+ const u = new URL(url);
2337
+ basename = u.pathname ? u.pathname.split("/").pop() : void 0;
2338
+ } catch {
2339
+ }
2340
+ }
2341
+ const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
2342
+ const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
2343
+ if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns)))
2344
+ return false;
2345
+ if (!includePatterns || includePatterns.length === 0) return true;
2346
+ return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
2347
+ }
2348
+ const SPECIAL_USE_IPV4_CIDRS = [
2349
+ "0.0.0.0/8",
2350
+ "10.0.0.0/8",
2351
+ "100.64.0.0/10",
2352
+ "127.0.0.0/8",
2353
+ "169.254.0.0/16",
2354
+ "172.16.0.0/12",
2355
+ "192.0.0.0/24",
2356
+ "192.0.2.0/24",
2357
+ "192.168.0.0/16",
2358
+ "198.18.0.0/15",
2359
+ "198.51.100.0/24",
2360
+ "203.0.113.0/24",
2361
+ "224.0.0.0/4",
2362
+ "240.0.0.0/4"
2363
+ ];
2364
+ const SPECIAL_USE_IPV6_CIDRS = ["::/128", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8"];
2365
+ const ARCHIVE_EXTENSIONS = /* @__PURE__ */ new Set([".zip", ".tar", ".gz", ".tgz"]);
2366
+ class ScraperAccessPolicy {
2367
+ constructor(security) {
2368
+ this.security = security;
2369
+ this.allowedHosts = security.network.allowedHosts;
2370
+ for (const cidr of security.network.allowedCidrs) {
2371
+ this.addCidr(this.allowedCidrs, cidr);
2372
+ }
2373
+ for (const cidr of SPECIAL_USE_IPV4_CIDRS) {
2374
+ this.addCidr(this.specialUseCidrs, cidr);
2375
+ }
2376
+ for (const cidr of SPECIAL_USE_IPV6_CIDRS) {
2377
+ this.addCidr(this.specialUseCidrs, cidr);
2378
+ }
2379
+ }
2380
+ security;
2381
+ allowedCidrs = new net.BlockList();
2382
+ specialUseCidrs = new net.BlockList();
2383
+ allowedHosts;
2384
+ /**
2385
+ * Checks whether a network URL is allowed before connecting.
2386
+ */
2387
+ async assertNetworkUrlAllowed(url) {
2388
+ const parsed = new URL(url);
2389
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2390
+ return;
2391
+ }
2392
+ const hostname = normalizeHostname(parsed.hostname);
2393
+ const ipFamily = net.isIP(hostname);
2394
+ if (this.security.network.mode === "allowlist") {
2395
+ if (ipFamily !== 0) {
2396
+ const family = ipFamily === 6 ? "ipv6" : "ipv4";
2397
+ if (this.allowedCidrs.check(hostname, family)) return;
2398
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2399
+ }
2400
+ if (matchesAnyHostPattern(hostname, this.allowedHosts)) {
2401
+ return;
2402
+ }
2403
+ const addresses2 = await resolveAddresses(hostname);
2404
+ const allAllowedByCidr = addresses2.length > 0 && addresses2.every((address) => {
2405
+ const family = net.isIP(address.address);
2406
+ if (family === 0) return false;
2407
+ return this.allowedCidrs.check(address.address, family === 6 ? "ipv6" : "ipv4");
2408
+ });
2409
+ if (allAllowedByCidr) return;
2410
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2411
+ }
2412
+ if (this.security.network.allowPrivateNetworks) {
2413
+ return;
2414
+ }
2415
+ if (ipFamily !== 0) {
2416
+ this.assertSpecialUseAddressAllowed(hostname, url);
2417
+ return;
2418
+ }
2419
+ if (looksLikeIpLiteral(hostname)) {
2420
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2421
+ }
2422
+ if (matchesAnyHostPattern(hostname, this.allowedHosts)) {
2423
+ return;
2424
+ }
2425
+ const addresses = await resolveAddresses(hostname);
2426
+ for (const address of addresses) {
2427
+ this.assertSpecialUseAddressAllowed(address.address, url);
2428
+ }
2429
+ }
2430
+ /**
2431
+ * Checks whether TLS certificate validation may be bypassed for a URL.
2432
+ */
2433
+ shouldAllowInvalidTls(url) {
2434
+ try {
2435
+ const parsed = new URL(url);
2436
+ return parsed.protocol === "https:" && this.security.network.allowInvalidTls;
2437
+ } catch {
2438
+ return false;
2439
+ }
2440
+ }
2441
+ /**
2442
+ * Resolves and validates a file URL against the configured file access policy.
2443
+ */
2444
+ async resolveFileAccess(url, additionalAllowedRoots = []) {
2445
+ const filePath = fileUrlToPathLoose(url);
2446
+ const resolved = await resolveArchiveAwarePath(filePath);
2447
+ const accessPath = resolved.archivePath ?? filePath;
2448
+ const bypassRoots = await this.expandRoots(additionalAllowedRoots);
2449
+ const matchedBypassRoot = await this.findContainingRoot(
2450
+ accessPath,
2451
+ bypassRoots,
2452
+ false
2453
+ );
2454
+ let matchedRoot = matchedBypassRoot;
2455
+ if (this.security.fileAccess.mode === "disabled" && !matchedBypassRoot) {
2456
+ throw new AccessPolicyError(`Security policy blocked local file access for ${url}`);
2457
+ }
2458
+ if (this.security.fileAccess.mode === "allowedRoots" && !matchedBypassRoot) {
2459
+ const configuredRoots = await this.expandRoots(
2460
+ this.security.fileAccess.allowedRoots
2461
+ );
2462
+ if (configuredRoots.length === 0) {
2463
+ throw new AccessPolicyError(
2464
+ `Security policy blocked local file access for ${url}`
2465
+ );
2466
+ }
2467
+ matchedRoot = await this.findContainingRoot(
2468
+ accessPath,
2469
+ configuredRoots,
2470
+ this.security.fileAccess.followSymlinks
2471
+ );
2472
+ if (!matchedRoot) {
2473
+ throw new AccessPolicyError(
2474
+ `Security policy blocked local file access for ${url}`
2475
+ );
2476
+ }
2477
+ }
2478
+ if (!this.security.fileAccess.followSymlinks && !matchedBypassRoot) {
2479
+ const symlinkPath = await findSymlinkInPath(accessPath);
2480
+ if (symlinkPath) {
2481
+ throw new AccessPolicyError(`Security policy blocked symlink access for ${url}`);
2482
+ }
2483
+ }
2484
+ if (!this.security.fileAccess.includeHidden) {
2485
+ if (hasHiddenSegmentBelowRoot(filePath, matchedRoot)) {
2486
+ throw new AccessPolicyError(
2487
+ `Security policy blocked hidden file access for ${url}`
2488
+ );
2489
+ }
2490
+ if (resolved.virtualArchivePath && hasHiddenArchiveSegment(resolved.virtualArchivePath)) {
2491
+ throw new AccessPolicyError(
2492
+ `Security policy blocked hidden archive entry access for ${url}`
2493
+ );
2494
+ }
2495
+ }
2496
+ return {
2497
+ filePath,
2498
+ accessPath,
2499
+ virtualArchivePath: resolved.virtualArchivePath
2500
+ };
2501
+ }
2502
+ /**
2503
+ * Throws if `address` falls inside a blocked special-use range and is not
2504
+ * explicitly permitted by `allowedCidrs`. Used both for direct-IP targets
2505
+ * and for revalidating DNS-resolved addresses (open mode) and allowlisted
2506
+ * hostnames (allowlist mode, to close DNS-rebinding gaps).
2507
+ */
2508
+ assertSpecialUseAddressAllowed(address, url) {
2509
+ const family = net.isIP(address);
2510
+ if (family === 0) {
2511
+ return;
2512
+ }
2513
+ const type = family === 6 ? "ipv6" : "ipv4";
2514
+ if (!this.specialUseCidrs.check(address, type)) {
2515
+ return;
2516
+ }
2517
+ if (this.allowedCidrs.check(address, type)) {
2518
+ return;
2519
+ }
2520
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2521
+ }
2522
+ addCidr(blockList, cidr) {
2523
+ const [network, prefix] = cidr.split("/");
2524
+ const family = net.isIP(network);
2525
+ if (family === 0 || prefix === void 0) {
2526
+ return;
2527
+ }
2528
+ blockList.addSubnet(
2529
+ network,
2530
+ Number.parseInt(prefix, 10),
2531
+ family === 6 ? "ipv6" : "ipv4"
2532
+ );
2533
+ }
2534
+ async expandRoots(roots) {
2535
+ const expanded = [];
2536
+ for (const root of roots) {
2537
+ const value = await expandConfiguredRoot(root);
2538
+ if (value) {
2539
+ expanded.push(value);
2540
+ }
2541
+ }
2542
+ return expanded;
2543
+ }
2544
+ async findContainingRoot(accessPath, roots, followSymlinks) {
2545
+ const resolvedAccessPath = await resolveContainmentPath(accessPath, followSymlinks);
2546
+ for (const root of roots) {
2547
+ const resolvedRoot = await resolveContainmentPath(root, followSymlinks);
2548
+ if (pathContains(resolvedRoot, resolvedAccessPath)) {
2549
+ return resolvedRoot;
2550
+ }
2551
+ }
2552
+ return null;
2553
+ }
2554
+ }
2555
+ async function resolveAddresses(hostname) {
2556
+ try {
2557
+ const result = await lookup(hostname, { all: true, verbatim: true });
2558
+ return Array.isArray(result) ? result : [];
2559
+ } catch {
2560
+ return [];
2561
+ }
2562
+ }
2563
+ function normalizeHostname(hostname) {
2564
+ return hostname.toLowerCase().replace(/^\[(.*)]$/, "$1");
2565
+ }
2566
+ function looksLikeIpLiteral(hostname) {
2567
+ return hostname.includes(":") || /^\d+(?:\.\d+){0,3}$/.test(hostname);
2568
+ }
2569
+ async function findSymlinkInPath(targetPath) {
2570
+ const resolved = path.resolve(targetPath);
2571
+ const root = path.parse(resolved).root;
2572
+ const relative = path.relative(root, resolved);
2573
+ const segments = relative.split(path.sep).filter(Boolean);
2574
+ let current = root;
2575
+ for (const segment of segments) {
2576
+ current = path.join(current, segment);
2577
+ const stats = await fs$1.lstat(current).catch(() => null);
2578
+ if (stats?.isSymbolicLink()) {
2579
+ return current;
2580
+ }
2581
+ }
2582
+ return null;
2583
+ }
2584
+ function fileUrlToPathLoose(url) {
2585
+ let filePath = url.replace(/^file:\/\/\/?/, "");
2586
+ filePath = decodeURIComponent(filePath);
2587
+ if (!filePath.startsWith("/") && process.platform !== "win32") {
2588
+ filePath = `/${filePath}`;
2589
+ }
2590
+ return filePath;
2591
+ }
2592
+ const USER_DIR_TOKENS = {
2593
+ $DOCUMENTS: "Documents",
2594
+ $DOWNLOADS: "Downloads",
2595
+ $DESKTOP: "Desktop"
2596
+ };
2597
+ async function expandConfiguredRoot(root) {
2598
+ if (root === "$HOME") {
2599
+ const homeDir = os.homedir();
2600
+ return homeDir ? path.resolve(homeDir) : null;
2601
+ }
2602
+ if (root === "$CWD") {
2603
+ return path.resolve(process.cwd());
2604
+ }
2605
+ const subdir = USER_DIR_TOKENS[root];
2606
+ if (subdir !== void 0) {
2607
+ const homeDir = os.homedir();
2608
+ if (!homeDir) {
2609
+ return null;
2610
+ }
2611
+ const candidate = path.join(homeDir, subdir);
2612
+ const stats = await fs$1.stat(candidate).catch(() => null);
2613
+ if (!stats?.isDirectory()) {
2614
+ return null;
2615
+ }
2616
+ return path.resolve(candidate);
2617
+ }
2618
+ return path.resolve(root);
2619
+ }
2620
+ async function resolveArchiveAwarePath(filePath) {
2621
+ let currentPath = filePath;
2622
+ while (currentPath !== "/" && currentPath !== "." && path.dirname(currentPath) !== currentPath) {
2623
+ const stats = await fs$1.lstat(currentPath).catch(() => null);
2624
+ if (stats?.isFile() && looksLikeArchivePath(currentPath)) {
2625
+ const virtualArchivePath = filePath.substring(currentPath.length).replace(/^\/+/, "").replace(/^\\+/, "");
2626
+ return {
2627
+ archivePath: currentPath,
2628
+ virtualArchivePath: virtualArchivePath || null
2629
+ };
2630
+ }
2631
+ if (stats) {
2632
+ return { archivePath: null, virtualArchivePath: null };
2633
+ }
2634
+ currentPath = path.dirname(currentPath);
2635
+ }
2636
+ return { archivePath: null, virtualArchivePath: null };
2637
+ }
2638
+ async function resolveContainmentPath(targetPath, followSymlinks) {
2639
+ if (!followSymlinks) {
2640
+ return path.resolve(targetPath);
2641
+ }
2642
+ return fs$1.realpath(targetPath).catch(() => path.resolve(targetPath));
2643
+ }
2644
+ function looksLikeArchivePath(filePath) {
2645
+ return ARCHIVE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
2646
+ }
2647
+ function pathContains(root, candidate) {
2648
+ if (root === candidate) {
2649
+ return true;
2650
+ }
2651
+ const relative = path.relative(root, candidate);
2652
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
2653
+ }
2654
+ function hasHiddenSegmentBelowRoot(targetPath, matchedRoot) {
2655
+ const resolved = path.resolve(targetPath);
2656
+ let segments;
2657
+ if (matchedRoot) {
2658
+ const resolvedRoot = path.resolve(matchedRoot);
2659
+ if (resolved === resolvedRoot) return false;
2660
+ const relative = path.relative(resolvedRoot, resolved);
2661
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
2662
+ segments = resolved.split(path.sep).filter(Boolean);
2663
+ } else {
2664
+ segments = relative.split(path.sep).filter(Boolean);
2665
+ }
2666
+ } else {
2667
+ segments = resolved.split(path.sep).filter(Boolean);
2668
+ }
2669
+ return segments.some((segment) => segment.startsWith("."));
2670
+ }
2671
+ function hasHiddenArchiveSegment(archivePath) {
2672
+ return archivePath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
2053
2673
  }
2054
2674
  class MimeTypeUtils {
2055
2675
  /**
@@ -2552,6 +3172,22 @@ class FingerprintGenerator {
2552
3172
  return this.headerGenerator.getHeaders();
2553
3173
  }
2554
3174
  }
3175
+ const MARKDOWN_PREFERRED_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8";
3176
+ function withMarkdownPreferredAccept(headers, callerHeaders = {}) {
3177
+ const hasCallerAccept = Object.keys(callerHeaders).some(
3178
+ (header) => header.toLowerCase() === "accept"
3179
+ );
3180
+ if (hasCallerAccept) {
3181
+ return headers;
3182
+ }
3183
+ const withoutGeneratedAccept = Object.fromEntries(
3184
+ Object.entries(headers).filter(([header]) => header.toLowerCase() !== "accept")
3185
+ );
3186
+ return {
3187
+ ...withoutGeneratedAccept,
3188
+ Accept: MARKDOWN_PREFERRED_ACCEPT
3189
+ };
3190
+ }
2555
3191
  var FetchStatus = /* @__PURE__ */ ((FetchStatus2) => {
2556
3192
  FetchStatus2["SUCCESS"] = "success";
2557
3193
  FetchStatus2["NOT_MODIFIED"] = "not_modified";
@@ -2560,28 +3196,58 @@ var FetchStatus = /* @__PURE__ */ ((FetchStatus2) => {
2560
3196
  })(FetchStatus || {});
2561
3197
  class BrowserFetcher {
2562
3198
  browser = null;
2563
- page = null;
2564
3199
  fingerprintGenerator;
2565
3200
  defaultTimeoutMs;
3201
+ accessPolicy;
2566
3202
  constructor(scraperConfig) {
2567
3203
  this.defaultTimeoutMs = scraperConfig.browserTimeoutMs;
2568
3204
  this.fingerprintGenerator = new FingerprintGenerator();
3205
+ this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
2569
3206
  }
2570
3207
  canFetch(source) {
2571
3208
  return source.startsWith("http://") || source.startsWith("https://");
2572
3209
  }
3210
+ async isRequestAllowed(url) {
3211
+ try {
3212
+ await this.accessPolicy.assertNetworkUrlAllowed(url);
3213
+ return true;
3214
+ } catch {
3215
+ return false;
3216
+ }
3217
+ }
2573
3218
  async fetch(source, options) {
3219
+ let page = null;
3220
+ let browserContext = null;
2574
3221
  try {
2575
- await this.ensureBrowserReady();
2576
- if (!this.page) {
2577
- throw new ScraperError("Failed to create browser page", false);
2578
- }
2579
- if (options?.headers) {
2580
- await this.page.setExtraHTTPHeaders(options.headers);
2581
- }
3222
+ await this.accessPolicy.assertNetworkUrlAllowed(source);
3223
+ const browser = await this.ensureBrowserReady();
3224
+ const fingerprintHeaders = this.fingerprintGenerator.generateHeaders();
3225
+ browserContext = await browser.newContext({
3226
+ ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
3227
+ "https://browser-context.local"
3228
+ )
3229
+ });
3230
+ page = await browserContext.newPage();
3231
+ await page.setViewportSize({ width: 1920, height: 1080 });
3232
+ await page.route("**/*", async (route) => {
3233
+ const requestUrl = route.request().url();
3234
+ if (!await this.isRequestAllowed(requestUrl)) {
3235
+ return await route.abort("blockedbyclient");
3236
+ }
3237
+ return await route.continue();
3238
+ });
3239
+ await page.setExtraHTTPHeaders(
3240
+ withMarkdownPreferredAccept(
3241
+ {
3242
+ ...fingerprintHeaders,
3243
+ ...options?.headers
3244
+ },
3245
+ options?.headers
3246
+ )
3247
+ );
2582
3248
  const timeout = options?.timeout || this.defaultTimeoutMs;
2583
3249
  logger.debug(`Navigating to ${source} with browser...`);
2584
- const response = await this.page.goto(source, {
3250
+ const response = await page.goto(source, {
2585
3251
  waitUntil: "networkidle",
2586
3252
  timeout
2587
3253
  });
@@ -2594,11 +3260,12 @@ class BrowserFetcher {
2594
3260
  throw new ScraperError(`Redirect blocked: ${source} -> ${location}`, false);
2595
3261
  }
2596
3262
  }
2597
- const finalUrl = this.page.url();
2598
- const content = await this.page.content();
2599
- const contentBuffer = Buffer.from(content, "utf-8");
3263
+ const finalUrl = page.url();
3264
+ await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
2600
3265
  const contentType = response.headers()["content-type"] || "text/html";
2601
3266
  const { mimeType, charset } = MimeTypeUtils.parseContentType(contentType);
3267
+ const content = MimeTypeUtils.isHtml(mimeType) ? await page.content() : await response.body();
3268
+ const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content, "utf-8");
2602
3269
  const etag = response.headers().etag;
2603
3270
  return {
2604
3271
  content: contentBuffer,
@@ -2620,6 +3287,10 @@ class BrowserFetcher {
2620
3287
  false,
2621
3288
  error instanceof Error ? error : void 0
2622
3289
  );
3290
+ } finally {
3291
+ await page?.unroute("**/*").catch(() => void 0);
3292
+ await page?.close().catch(() => void 0);
3293
+ await browserContext?.close().catch(() => void 0);
2623
3294
  }
2624
3295
  }
2625
3296
  static async launchBrowser() {
@@ -2634,27 +3305,13 @@ class BrowserFetcher {
2634
3305
  logger.debug("Launching browser...");
2635
3306
  this.browser = await BrowserFetcher.launchBrowser();
2636
3307
  }
2637
- if (!this.page) {
2638
- this.page = await this.browser.newPage();
2639
- const dynamicHeaders = this.fingerprintGenerator.generateHeaders();
2640
- await this.page.setExtraHTTPHeaders(dynamicHeaders);
2641
- await this.page.setViewportSize({ width: 1920, height: 1080 });
2642
- }
3308
+ return this.browser;
2643
3309
  }
2644
3310
  /**
2645
3311
  * Close the browser and clean up resources.
2646
3312
  * Always attempts cleanup even if browser is disconnected to reap zombie processes.
2647
3313
  */
2648
3314
  async close() {
2649
- if (this.page) {
2650
- try {
2651
- await this.page.close();
2652
- } catch (error) {
2653
- logger.warn(`⚠️ Error closing browser page: ${error}`);
2654
- } finally {
2655
- this.page = null;
2656
- }
2657
- }
2658
3315
  if (this.browser) {
2659
3316
  try {
2660
3317
  await this.browser.close();
@@ -2668,6 +3325,10 @@ class BrowserFetcher {
2668
3325
  }
2669
3326
  }
2670
3327
  class FileFetcher {
3328
+ accessPolicy;
3329
+ constructor(scraperConfig) {
3330
+ this.accessPolicy = scraperConfig ? new ScraperAccessPolicy(scraperConfig.security) : null;
3331
+ }
2671
3332
  canFetch(source) {
2672
3333
  return source.startsWith("file://");
2673
3334
  }
@@ -2677,11 +3338,10 @@ class FileFetcher {
2677
3338
  * Supports conditional fetching via ETag comparison for efficient refresh operations.
2678
3339
  */
2679
3340
  async fetch(source, options) {
2680
- let filePath = source.replace(/^file:\/\/\/?/, "");
2681
- filePath = decodeURIComponent(filePath);
2682
- if (!filePath.startsWith("/") && process.platform !== "win32") {
2683
- filePath = `/${filePath}`;
2684
- }
3341
+ const filePath = this.accessPolicy ? (await this.accessPolicy.resolveFileAccess(
3342
+ source,
3343
+ options?.internalAllowedFileRoots
3344
+ )).filePath : fileUrlToPathLoose(source);
2685
3345
  try {
2686
3346
  const stats = await fs$1.stat(filePath);
2687
3347
  const currentEtag = crypto.createHash("md5").update(stats.mtime.toISOString()).digest("hex");
@@ -2734,6 +3394,7 @@ class PipelineError extends Error {
2734
3394
  Caused by: ${cause.stack}`;
2735
3395
  }
2736
3396
  }
3397
+ cause;
2737
3398
  }
2738
3399
  class PipelineStateError extends PipelineError {
2739
3400
  }
@@ -2742,6 +3403,7 @@ class CancellationError extends PipelineError {
2742
3403
  super(message);
2743
3404
  }
2744
3405
  }
3406
+ const MAX_REDIRECTS = 5;
2745
3407
  class HttpFetcher {
2746
3408
  maxRetriesDefault;
2747
3409
  baseDelayDefaultMs;
@@ -2789,10 +3451,12 @@ class HttpFetcher {
2789
3451
  "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
2790
3452
  ];
2791
3453
  fingerprintGenerator;
3454
+ accessPolicy;
2792
3455
  constructor(scraperConfig) {
2793
3456
  this.maxRetriesDefault = scraperConfig.fetcher.maxRetries;
2794
3457
  this.baseDelayDefaultMs = scraperConfig.fetcher.baseDelayMs;
2795
3458
  this.fingerprintGenerator = new FingerprintGenerator();
3459
+ this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
2796
3460
  }
2797
3461
  canFetch(source) {
2798
3462
  return source.startsWith("http://") || source.startsWith("https://");
@@ -2817,85 +3481,129 @@ class HttpFetcher {
2817
3481
  return result;
2818
3482
  }
2819
3483
  async performFetch(source, options, maxRetries = this.maxRetriesDefault, baseDelay = this.baseDelayDefaultMs, followRedirects = true) {
3484
+ await this.accessPolicy.assertNetworkUrlAllowed(source);
2820
3485
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
2821
3486
  try {
2822
- const fingerprint = this.fingerprintGenerator.generateHeaders();
2823
- const headers = {
2824
- ...fingerprint,
2825
- ...options?.headers
2826
- // User-provided headers override generated ones
2827
- };
2828
- if (options?.etag) {
2829
- headers["If-None-Match"] = options.etag;
2830
- logger.debug(
2831
- `Conditional request for ${source} with If-None-Match: ${options.etag}`
3487
+ let currentUrl = source;
3488
+ let redirectCount = 0;
3489
+ while (true) {
3490
+ const fingerprint = this.fingerprintGenerator.generateHeaders();
3491
+ const headers = withMarkdownPreferredAccept(
3492
+ {
3493
+ ...fingerprint,
3494
+ ...options?.headers
3495
+ // User-provided headers override generated ones
3496
+ },
3497
+ options?.headers
2832
3498
  );
2833
- }
2834
- const config = {
2835
- responseType: "arraybuffer",
2836
- headers: {
2837
- ...headers,
2838
- // Override Accept-Encoding to exclude zstd which Axios doesn't handle automatically
2839
- // This prevents servers from sending zstd-compressed content that would appear as binary garbage
2840
- "Accept-Encoding": "gzip, deflate, br"
2841
- },
2842
- timeout: options?.timeout,
2843
- signal: options?.signal,
2844
- // Pass signal to axios
2845
- // Axios follows redirects by default, we need to explicitly disable it if needed
2846
- maxRedirects: followRedirects ? 5 : 0,
2847
- decompress: true,
2848
- // Allow 304 responses to be handled as successful responses
2849
- validateStatus: (status) => {
2850
- return status >= 200 && status < 300 || status === 304;
3499
+ if (options?.etag) {
3500
+ headers["If-None-Match"] = options.etag;
3501
+ logger.debug(
3502
+ `Conditional request for ${source} with If-None-Match: ${options.etag}`
3503
+ );
2851
3504
  }
2852
- };
2853
- const response = await axios.get(source, config);
2854
- if (response.status === 304) {
2855
- logger.debug(`HTTP 304 Not Modified for ${source}`);
3505
+ const config = {
3506
+ responseType: "arraybuffer",
3507
+ headers: {
3508
+ ...headers,
3509
+ // Override Accept-Encoding to exclude zstd which Axios doesn't handle automatically
3510
+ // This prevents servers from sending zstd-compressed content that would appear as binary garbage
3511
+ "Accept-Encoding": "gzip, deflate, br"
3512
+ },
3513
+ timeout: options?.timeout,
3514
+ signal: options?.signal,
3515
+ // Pass signal to axios
3516
+ // Redirects are handled manually so every target can be revalidated before connect.
3517
+ maxRedirects: 0,
3518
+ decompress: true,
3519
+ // Allow 304 responses to be handled as successful responses
3520
+ validateStatus: (status) => {
3521
+ return status >= 200 && status < 400 || status === 304;
3522
+ }
3523
+ };
3524
+ if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) {
3525
+ config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
3526
+ }
3527
+ const response = await axios.get(currentUrl, config);
3528
+ if (response.status === 304) {
3529
+ logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
3530
+ return {
3531
+ content: Buffer.from(""),
3532
+ mimeType: "text/plain",
3533
+ source: currentUrl,
3534
+ status: FetchStatus.NOT_MODIFIED
3535
+ };
3536
+ }
3537
+ if (response.status >= 300 && response.status < 400) {
3538
+ const location = response.headers.location;
3539
+ if (!location) {
3540
+ throw new ScraperError(
3541
+ `Redirect response for ${currentUrl} did not include a location header`,
3542
+ false
3543
+ );
3544
+ }
3545
+ if (!followRedirects) {
3546
+ throw new RedirectError(currentUrl, location, response.status);
3547
+ }
3548
+ if (redirectCount >= MAX_REDIRECTS) {
3549
+ throw new ScraperError(
3550
+ `Too many redirects while fetching ${source}`,
3551
+ false
3552
+ );
3553
+ }
3554
+ const redirectUrl = new URL(location, currentUrl).href;
3555
+ await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
3556
+ currentUrl = redirectUrl;
3557
+ redirectCount += 1;
3558
+ continue;
3559
+ }
3560
+ const contentTypeHeader = response.headers["content-type"];
3561
+ const { mimeType, charset } = MimeTypeUtils.parseContentType(
3562
+ typeof contentTypeHeader === "string" ? contentTypeHeader : void 0
3563
+ );
3564
+ const rawContentEncoding = response.headers["content-encoding"];
3565
+ const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
3566
+ let content;
3567
+ if (response.data instanceof ArrayBuffer) {
3568
+ content = Buffer.from(response.data);
3569
+ } else if (Buffer.isBuffer(response.data)) {
3570
+ content = response.data;
3571
+ } else if (typeof response.data === "string") {
3572
+ content = Buffer.from(response.data, "utf-8");
3573
+ } else {
3574
+ content = Buffer.from(response.data);
3575
+ }
3576
+ const finalUrl = (
3577
+ // Node follow-redirects style
3578
+ response.request?.res?.responseUrl || // Some adapters may expose directly
3579
+ response.request?.responseUrl || // Fallback to axios recorded config URL
3580
+ response.config?.url || currentUrl
3581
+ );
3582
+ await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
3583
+ const etag = response.headers.etag || response.headers.ETag;
3584
+ if (etag) {
3585
+ logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
3586
+ }
3587
+ const lastModified = response.headers["last-modified"];
3588
+ const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
2856
3589
  return {
2857
- content: Buffer.from(""),
2858
- mimeType: "text/plain",
2859
- source,
2860
- status: FetchStatus.NOT_MODIFIED
3590
+ content,
3591
+ mimeType,
3592
+ charset,
3593
+ encoding: contentEncoding,
3594
+ source: finalUrl,
3595
+ etag,
3596
+ lastModified: lastModifiedISO,
3597
+ status: FetchStatus.SUCCESS
2861
3598
  };
2862
3599
  }
2863
- const contentTypeHeader = response.headers["content-type"];
2864
- const { mimeType, charset } = MimeTypeUtils.parseContentType(contentTypeHeader);
2865
- const contentEncoding = response.headers["content-encoding"];
2866
- let content;
2867
- if (response.data instanceof ArrayBuffer) {
2868
- content = Buffer.from(response.data);
2869
- } else if (Buffer.isBuffer(response.data)) {
2870
- content = response.data;
2871
- } else if (typeof response.data === "string") {
2872
- content = Buffer.from(response.data, "utf-8");
2873
- } else {
2874
- content = Buffer.from(response.data);
3600
+ } catch (error) {
3601
+ if (error instanceof RedirectError || error instanceof ChallengeError) {
3602
+ throw error;
2875
3603
  }
2876
- const finalUrl = (
2877
- // Node follow-redirects style
2878
- response.request?.res?.responseUrl || // Some adapters may expose directly
2879
- response.request?.responseUrl || // Fallback to axios recorded config URL
2880
- response.config?.url || source
2881
- );
2882
- const etag = response.headers.etag || response.headers.ETag;
2883
- if (etag) {
2884
- logger.debug(`Received ETag for ${source}: ${etag}`);
3604
+ if (error instanceof ScraperError && !error.isRetryable) {
3605
+ throw error;
2885
3606
  }
2886
- const lastModified = response.headers["last-modified"];
2887
- const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
2888
- return {
2889
- content,
2890
- mimeType,
2891
- charset,
2892
- encoding: contentEncoding,
2893
- source: finalUrl,
2894
- etag,
2895
- lastModified: lastModifiedISO,
2896
- status: FetchStatus.SUCCESS
2897
- };
2898
- } catch (error) {
2899
3607
  const axiosError = error;
2900
3608
  const status = axiosError.response?.status;
2901
3609
  const code = axiosError.code;
@@ -2966,10 +3674,11 @@ class HttpFetcher {
2966
3674
  class AutoDetectFetcher {
2967
3675
  httpFetcher;
2968
3676
  browserFetcher;
2969
- fileFetcher = new FileFetcher();
3677
+ fileFetcher;
2970
3678
  constructor(scraperConfig) {
2971
3679
  this.httpFetcher = new HttpFetcher(scraperConfig);
2972
3680
  this.browserFetcher = new BrowserFetcher(scraperConfig);
3681
+ this.fileFetcher = new FileFetcher(scraperConfig);
2973
3682
  }
2974
3683
  /**
2975
3684
  * Check if this fetcher can handle the given source.
@@ -3353,41 +4062,114 @@ class CodeContentSplitter {
3353
4062
  constructor(options) {
3354
4063
  this.options = options;
3355
4064
  }
4065
+ options;
3356
4066
  async split(content) {
3357
- const language = content.match(/^```(\w+)\n/)?.[1];
3358
- const strippedContent = content.replace(/^```(\w*)\n/, "").replace(/```\s*$/, "");
4067
+ const infoMatch = content.match(/^```([^\n]*)\n/);
4068
+ const infoString = (infoMatch?.[1] ?? "").trimEnd();
4069
+ const strippedContent = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "");
3359
4070
  const lines = strippedContent.split("\n");
3360
4071
  const chunks = [];
3361
4072
  let currentChunkLines = [];
3362
4073
  for (const line of lines) {
3363
- const singleLineSize = this.wrap(line, language).length;
4074
+ const singleLineSize = this.wrap(line, infoString).length;
3364
4075
  if (singleLineSize > this.options.chunkSize) {
3365
4076
  throw new MinimumChunkSizeError(singleLineSize, this.options.chunkSize);
3366
4077
  }
3367
4078
  currentChunkLines.push(line);
3368
- const newChunkContent = this.wrap(currentChunkLines.join("\n"), language);
4079
+ const newChunkContent = this.wrap(currentChunkLines.join("\n"), infoString);
3369
4080
  const newChunkSize = newChunkContent.length;
3370
4081
  if (newChunkSize > this.options.chunkSize && currentChunkLines.length > 1) {
3371
4082
  const lastLine = currentChunkLines.pop();
3372
- chunks.push(this.wrap(currentChunkLines.join("\n"), language));
4083
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
3373
4084
  currentChunkLines = [lastLine];
3374
4085
  }
3375
4086
  }
3376
4087
  if (currentChunkLines.length > 0) {
3377
- chunks.push(this.wrap(currentChunkLines.join("\n"), language));
4088
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
3378
4089
  }
3379
4090
  return chunks;
3380
4091
  }
3381
- wrap(content, language) {
3382
- return `\`\`\`${language || ""}
4092
+ wrap(content, infoString) {
4093
+ return `\`\`\`${infoString || ""}
3383
4094
  ${content.replace(/\n+$/, "")}
3384
4095
  \`\`\``;
3385
4096
  }
3386
4097
  }
4098
+ const FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
4099
+ const FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
4100
+ function splitLinesWithOffsets(text) {
4101
+ const lines = [];
4102
+ let offset = 0;
4103
+ while (offset <= text.length) {
4104
+ const nlIndex = text.indexOf("\n", offset);
4105
+ if (nlIndex === -1) {
4106
+ if (offset < text.length) {
4107
+ lines.push({ content: text.slice(offset), offset, newlineLength: 0 });
4108
+ }
4109
+ return lines;
4110
+ }
4111
+ lines.push({
4112
+ content: text.slice(offset, nlIndex),
4113
+ offset,
4114
+ newlineLength: 1
4115
+ });
4116
+ offset = nlIndex + 1;
4117
+ }
4118
+ return lines;
4119
+ }
4120
+ function isClosingFence(line, delimiter, openerCount) {
4121
+ const closerRegex = new RegExp(
4122
+ `^${FENCE_PREFIX}\\${delimiter}{${openerCount},}[ \\t]*$`
4123
+ );
4124
+ return closerRegex.test(line);
4125
+ }
4126
+ function findFenceRegions(text) {
4127
+ const regions = [];
4128
+ const lines = splitLinesWithOffsets(text);
4129
+ let i = 0;
4130
+ while (i < lines.length) {
4131
+ const opener = FENCE_OPENER.exec(lines[i].content);
4132
+ if (!opener) {
4133
+ i += 1;
4134
+ continue;
4135
+ }
4136
+ const delimiter = opener[1][0];
4137
+ const count = opener[1].length;
4138
+ const startOffset = lines[i].offset;
4139
+ let closerLineIndex = -1;
4140
+ for (let j = i + 1; j < lines.length; j++) {
4141
+ if (isClosingFence(lines[j].content, delimiter, count)) {
4142
+ closerLineIndex = j;
4143
+ break;
4144
+ }
4145
+ }
4146
+ if (closerLineIndex === -1) {
4147
+ regions.push({ startOffset, endOffset: text.length });
4148
+ break;
4149
+ }
4150
+ const closerLine = lines[closerLineIndex];
4151
+ const endOffset = closerLine.offset + closerLine.content.length + closerLine.newlineLength;
4152
+ regions.push({ startOffset, endOffset });
4153
+ i = closerLineIndex + 1;
4154
+ }
4155
+ return regions;
4156
+ }
4157
+ function hasOpenFenceAtEnd(chunk) {
4158
+ const regions = findFenceRegions(chunk);
4159
+ if (regions.length === 0) return false;
4160
+ const last = regions[regions.length - 1];
4161
+ if (last.endOffset !== chunk.length) return false;
4162
+ const lines = splitLinesWithOffsets(chunk.slice(last.startOffset));
4163
+ if (lines.length < 2) return true;
4164
+ const opener = FENCE_OPENER.exec(lines[0].content);
4165
+ if (!opener) return false;
4166
+ return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
4167
+ }
3387
4168
  class TextContentSplitter {
3388
4169
  constructor(options) {
3389
4170
  this.options = options;
3390
4171
  }
4172
+ options;
3391
4173
  /**
3392
4174
  * Splits text content into chunks while trying to preserve semantic boundaries.
3393
4175
  * Prefers paragraph breaks, then line breaks, finally falling back to word boundaries.
@@ -3404,16 +4186,50 @@ class TextContentSplitter {
3404
4186
  if (longestWord.length > this.options.chunkSize) {
3405
4187
  throw new MinimumChunkSizeError(longestWord.length, this.options.chunkSize);
3406
4188
  }
3407
- const paragraphChunks = this.splitByParagraphs(content);
4189
+ const paragraphChunks = this.mergeForFenceBalance(
4190
+ this.splitByParagraphs(content),
4191
+ ""
4192
+ );
3408
4193
  if (this.areChunksValid(paragraphChunks)) {
3409
4194
  return paragraphChunks;
3410
4195
  }
3411
- const lineChunks = this.splitByLines(content);
4196
+ const lineChunks = this.mergeForFenceBalance(this.splitByLines(content), "");
3412
4197
  if (this.areChunksValid(lineChunks)) {
3413
4198
  return this.mergeChunks(lineChunks, "");
3414
4199
  }
3415
- const wordChunks = await this.splitByWords(content);
3416
- return this.mergeChunks(wordChunks, " ");
4200
+ const wordChunks = this.mergeForFenceBalance(await this.splitByWords(content), " ");
4201
+ const merged = this.mergeChunks(wordChunks, " ");
4202
+ this.warnOversize(merged);
4203
+ return merged;
4204
+ }
4205
+ /**
4206
+ * Walks `chunks` left to right and merges adjacent chunks whenever the running
4207
+ * buffer ends inside an open fenced code block. Guarantees that every emitted
4208
+ * chunk has balanced fences (i.e. `hasOpenFenceAtEnd` returns false).
4209
+ */
4210
+ mergeForFenceBalance(chunks, separator) {
4211
+ const result = [];
4212
+ let buffer = "";
4213
+ for (const chunk of chunks) {
4214
+ buffer = buffer ? `${buffer}${separator}${chunk}` : chunk;
4215
+ if (!hasOpenFenceAtEnd(buffer)) {
4216
+ result.push(buffer);
4217
+ buffer = "";
4218
+ }
4219
+ }
4220
+ if (buffer) {
4221
+ result.push(buffer);
4222
+ }
4223
+ return result;
4224
+ }
4225
+ warnOversize(chunks) {
4226
+ for (const chunk of chunks) {
4227
+ if (chunk.length > this.options.chunkSize) {
4228
+ logger.warn(
4229
+ `⚠ TextContentSplitter emitted oversize chunk to preserve fence balance: ${chunk.length} > ${this.options.chunkSize}`
4230
+ );
4231
+ }
4232
+ }
3417
4233
  }
3418
4234
  /**
3419
4235
  * Checks if all chunks are within the maximum size limit
@@ -3515,6 +4331,7 @@ class ListContentSplitter {
3515
4331
  this.options = options;
3516
4332
  this.textSplitter = new TextContentSplitter(options);
3517
4333
  }
4334
+ options;
3518
4335
  textSplitter;
3519
4336
  async split(content) {
3520
4337
  if (content.length <= this.options.chunkSize) {
@@ -3584,6 +4401,7 @@ class TableContentSplitter {
3584
4401
  constructor(options) {
3585
4402
  this.options = options;
3586
4403
  }
4404
+ options;
3587
4405
  /**
3588
4406
  * Splits table content into chunks while preserving table structure
3589
4407
  */
@@ -3698,6 +4516,8 @@ class SemanticMarkdownSplitter {
3698
4516
  // Lists prefer to stay together, so use preferred size
3699
4517
  });
3700
4518
  }
4519
+ preferredChunkSize;
4520
+ maxChunkSize;
3701
4521
  turndownService;
3702
4522
  textSplitter;
3703
4523
  codeSplitter;
@@ -4581,22 +5401,129 @@ class SimpleMemoryCache {
4581
5401
  this.cache.clear();
4582
5402
  }
4583
5403
  }
5404
+ const BLOCKLIST_NOT_BLOCKED = Object.freeze({ blocked: false });
5405
+ const SUBRESOURCE_BLOCKLIST = Object.freeze([
5406
+ // Analytics — page-view and event tracking SDKs; no content.
5407
+ { host: "google-analytics.com", category: "Analytics" },
5408
+ { host: "googletagmanager.com", category: "Analytics" },
5409
+ { host: "segment.io", category: "Analytics" },
5410
+ { host: "segment.com", category: "Analytics" },
5411
+ { host: "mixpanel.com", category: "Analytics" },
5412
+ { host: "amplitude.com", category: "Analytics" },
5413
+ { host: "plausible.io", category: "Analytics" },
5414
+ { host: "matomo.cloud", category: "Analytics" },
5415
+ { host: "stats.wp.com", category: "Analytics" },
5416
+ // Session Replay — record user interactions; never content.
5417
+ { host: "hotjar.com", category: "Session Replay" },
5418
+ { host: "fullstory.com", category: "Session Replay" },
5419
+ { host: "logrocket.com", category: "Session Replay" },
5420
+ { host: "lr-ingest.io", category: "Session Replay" },
5421
+ { host: "smartlook.com", category: "Session Replay" },
5422
+ // Chat Widgets — UI overlays the sanitizer strips post-fetch anyway.
5423
+ { host: "intercom.io", category: "Chat Widget" },
5424
+ { host: "intercomcdn.com", category: "Chat Widget" },
5425
+ { host: "widget.kapa.ai", category: "Chat Widget" },
5426
+ { host: "drift.com", category: "Chat Widget" },
5427
+ { host: "driftt.com", category: "Chat Widget" },
5428
+ { host: "crisp.chat", category: "Chat Widget" },
5429
+ { host: "tawk.to", category: "Chat Widget" },
5430
+ { host: "zdassets.com", category: "Chat Widget" },
5431
+ // Captcha — challenge runtimes; documentation pages don't need them.
5432
+ { host: "hcaptcha.com", category: "Captcha" },
5433
+ { host: "recaptcha.net", category: "Captcha" },
5434
+ // Social Embed runtimes — the embed-document iframe is allowed (document type
5435
+ // is exempt at the route handler); only the runtime JS is blocked.
5436
+ {
5437
+ host: "youtube-nocookie.com",
5438
+ pathPrefix: "/s/_/ytembeds/",
5439
+ category: "Social Embed"
5440
+ },
5441
+ { host: "platform.twitter.com", category: "Social Embed" },
5442
+ { host: "connect.facebook.net", category: "Social Embed" },
5443
+ { host: "platform.linkedin.com", category: "Social Embed" }
5444
+ ]);
5445
+ for (const entry of SUBRESOURCE_BLOCKLIST) {
5446
+ if (!entry.host || entry.host.includes("/") || entry.host.includes(":")) {
5447
+ throw new Error(
5448
+ `Invalid blocklist entry: host must be a bare hostname (got "${entry.host}")`
5449
+ );
5450
+ }
5451
+ if ("pathPrefix" in entry && !entry.pathPrefix.startsWith("/")) {
5452
+ throw new Error(
5453
+ `Invalid blocklist entry for "${entry.host}": pathPrefix must start with "/" (got "${entry.pathPrefix}")`
5454
+ );
5455
+ }
5456
+ }
5457
+ function hostMatches(requestHost, entryHost) {
5458
+ if (requestHost === entryHost) return true;
5459
+ return requestHost.endsWith(`.${entryHost}`);
5460
+ }
5461
+ function isBlockedSubresource(url) {
5462
+ let parsed;
5463
+ try {
5464
+ parsed = new URL(url);
5465
+ } catch {
5466
+ return BLOCKLIST_NOT_BLOCKED;
5467
+ }
5468
+ const host = parsed.hostname;
5469
+ for (const entry of SUBRESOURCE_BLOCKLIST) {
5470
+ if (!hostMatches(host, entry.host)) continue;
5471
+ if ("pathPrefix" in entry && !parsed.pathname.startsWith(entry.pathPrefix)) {
5472
+ continue;
5473
+ }
5474
+ return { blocked: true, category: entry.category };
5475
+ }
5476
+ return BLOCKLIST_NOT_BLOCKED;
5477
+ }
4584
5478
  class HtmlPlaywrightMiddleware {
4585
5479
  browser = null;
4586
5480
  config;
5481
+ accessPolicy;
4587
5482
  // Static LRU cache for all fetched resources, shared across instances
4588
5483
  static resourceCache = new SimpleMemoryCache(
4589
5484
  defaults.scraper.fetcher.maxCacheItems
4590
5485
  );
4591
5486
  constructor(config) {
4592
5487
  this.config = config;
5488
+ this.accessPolicy = new ScraperAccessPolicy(config.security);
5489
+ }
5490
+ async isRequestAllowed(url) {
5491
+ try {
5492
+ await this.accessPolicy.assertNetworkUrlAllowed(url);
5493
+ return true;
5494
+ } catch {
5495
+ return false;
5496
+ }
5497
+ }
5498
+ /**
5499
+ * Returns true if the request was handled (aborted) by the built-in tracker
5500
+ * blocklist; the caller should bail out of further processing in that case.
5501
+ * Returns false when the blocklist is disabled, when the request is a
5502
+ * top-level/iframe document navigation, or when no entry matches.
5503
+ */
5504
+ async tryBlocklistAbort(route, reqUrl) {
5505
+ if (!this.config.skipKnownTrackers) return false;
5506
+ if (route.request().resourceType() === "document") return false;
5507
+ const match = isBlockedSubresource(reqUrl);
5508
+ if (!match.blocked) return false;
5509
+ logger.debug(`Blocked sub-resource (${match.category}): ${reqUrl}`);
5510
+ try {
5511
+ await route.abort("blockedbyclient");
5512
+ } catch (error) {
5513
+ if (this.isRouteAlreadyHandledError(error)) {
5514
+ logger.debug(`Route already handled (blocklist abort): ${reqUrl}`);
5515
+ return true;
5516
+ }
5517
+ throw error;
5518
+ }
5519
+ return true;
4593
5520
  }
4594
5521
  /**
4595
5522
  * Initializes the Playwright browser instance.
4596
5523
  * Consider making this more robust (e.g., lazy initialization, singleton).
4597
5524
  */
4598
5525
  async ensureBrowser() {
4599
- if (!this.browser || !this.browser.isConnected()) {
5526
+ if (!this.browser?.isConnected()) {
4600
5527
  logger.debug("Launching new Playwright browser instance (Chromium)");
4601
5528
  this.browser = await BrowserFetcher.launchBrowser();
4602
5529
  this.browser.on("disconnected", () => {
@@ -4974,121 +5901,160 @@ class HtmlPlaywrightMiddleware {
4974
5901
  }
4975
5902
  return false;
4976
5903
  }
4977
- async setupCachingRouteInterception(page, customHeaders = {}, credentials, origin) {
4978
- await page.route("**/*", async (route) => {
4979
- const reqUrl = route.request().url();
4980
- const reqOrigin = (() => {
4981
- try {
4982
- return new URL(reqUrl).origin;
4983
- } catch {
4984
- return null;
4985
- }
4986
- })();
4987
- const resourceType = route.request().resourceType();
4988
- if (["image", "font", "media"].includes(resourceType)) {
4989
- try {
4990
- return await route.abort();
4991
- } catch (error) {
4992
- if (this.isRouteAlreadyHandledError(error)) {
4993
- logger.debug(`Route already handled (abort): ${reqUrl}`);
4994
- return;
4995
- }
4996
- throw error;
4997
- }
5904
+ isTargetClosedError(error) {
5905
+ if (!(error instanceof Error)) {
5906
+ return false;
5907
+ }
5908
+ return error.message.includes("Target page, context or browser has been closed");
5909
+ }
5910
+ formatRouteError(error) {
5911
+ const message = error instanceof Error ? error.message : String(error);
5912
+ return message.split("\n")[0] || message;
5913
+ }
5914
+ isSpeculativePrefetch(route) {
5915
+ const headers = route.request().headers();
5916
+ return headers["next-router-prefetch"] === "1" || headers.purpose?.toLowerCase() === "prefetch" || headers["sec-purpose"]?.toLowerCase().includes("prefetch") === true;
5917
+ }
5918
+ isCacheableResponseContent(contentType) {
5919
+ const { mimeType } = MimeTypeUtils.parseContentType(contentType);
5920
+ return MimeTypeUtils.isHtml(mimeType) || MimeTypeUtils.isMarkdown(mimeType) || MimeTypeUtils.isSafeForTextProcessing(mimeType);
5921
+ }
5922
+ getRequestOrigin(url) {
5923
+ try {
5924
+ return new URL(url).origin;
5925
+ } catch {
5926
+ return null;
5927
+ }
5928
+ }
5929
+ ignoreRouteLifecycleError(error, action, reqUrl) {
5930
+ if (this.isRouteAlreadyHandledError(error)) {
5931
+ logger.debug(`Route already handled (${action}): ${reqUrl}`);
5932
+ return true;
5933
+ }
5934
+ if (this.isTargetClosedError(error)) {
5935
+ logger.debug(`Route target closed (${action}): ${reqUrl}`);
5936
+ return true;
5937
+ }
5938
+ return false;
5939
+ }
5940
+ async abortRoute(route, reqUrl, action, reason) {
5941
+ try {
5942
+ await route.abort(reason);
5943
+ } catch (error) {
5944
+ if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {
5945
+ return;
4998
5946
  }
4999
- if (route.request().method() === "GET") {
5000
- const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);
5001
- if (cached !== void 0) {
5002
- logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);
5003
- try {
5004
- return await route.fulfill({
5005
- status: 200,
5006
- contentType: cached.contentType,
5007
- body: cached.body
5008
- });
5009
- } catch (error) {
5010
- if (this.isRouteAlreadyHandledError(error)) {
5011
- logger.debug(`Route already handled (fulfill cached): ${reqUrl}`);
5012
- return;
5013
- }
5014
- throw error;
5015
- }
5016
- }
5017
- const headers2 = mergePlaywrightHeaders(
5018
- route.request().headers(),
5019
- customHeaders,
5020
- credentials,
5021
- origin,
5022
- reqOrigin ?? void 0
5023
- );
5024
- try {
5025
- const response = await route.fetch({ headers: headers2 });
5026
- const body = await response.text();
5027
- if (response.status() >= 200 && response.status() < 300 && body.length > 0) {
5028
- const contentSizeBytes = Buffer.byteLength(body, "utf8");
5029
- if (contentSizeBytes <= this.config.fetcher.maxCacheItemSizeBytes) {
5030
- const contentType = response.headers()["content-type"] || "application/octet-stream";
5031
- HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType });
5032
- logger.debug(
5033
- `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`
5034
- );
5035
- } else {
5036
- logger.debug(
5037
- `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${this.config.fetcher.maxCacheItemSizeBytes} bytes limit)`
5038
- );
5039
- }
5040
- }
5041
- try {
5042
- return await route.fulfill({ response });
5043
- } catch (error) {
5044
- if (this.isRouteAlreadyHandledError(error)) {
5045
- logger.debug(`Route already handled (fulfill): ${reqUrl}`);
5046
- return;
5047
- }
5048
- throw error;
5049
- }
5050
- } catch (error) {
5051
- const errorMessage = error instanceof Error ? error.message : String(error);
5052
- logger.debug(
5053
- `Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`
5054
- );
5055
- try {
5056
- return await route.abort("failed");
5057
- } catch (abortError) {
5058
- if (this.isRouteAlreadyHandledError(abortError)) {
5059
- logger.debug(`Route already handled (abort after error): ${reqUrl}`);
5060
- return;
5061
- }
5062
- throw abortError;
5063
- }
5064
- }
5947
+ throw error;
5948
+ }
5949
+ }
5950
+ async fulfillRoute(route, reqUrl, options, action) {
5951
+ try {
5952
+ await route.fulfill(options);
5953
+ } catch (error) {
5954
+ if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {
5955
+ return;
5065
5956
  }
5066
- const headers = mergePlaywrightHeaders(
5067
- route.request().headers(),
5068
- customHeaders,
5069
- credentials,
5070
- origin,
5071
- reqOrigin ?? void 0
5957
+ throw error;
5958
+ }
5959
+ }
5960
+ async continueRoute(route, reqUrl, resourceType, options) {
5961
+ try {
5962
+ await route.continue(options);
5963
+ } catch (error) {
5964
+ if (this.ignoreRouteLifecycleError(error, "continue", reqUrl)) {
5965
+ return;
5966
+ }
5967
+ const errorMessage = this.formatRouteError(error);
5968
+ logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
5969
+ await this.abortRoute(route, reqUrl, "abort after continue error", "failed");
5970
+ }
5971
+ }
5972
+ async cacheResponseIfEligible(reqUrl, resourceType, response) {
5973
+ const contentType = response.headers()["content-type"] || "application/octet-stream";
5974
+ if (response.status() < 200 || response.status() >= 300) {
5975
+ return;
5976
+ }
5977
+ if (!this.isCacheableResponseContent(contentType)) {
5978
+ logger.debug(
5979
+ `Skipping cache for unsupported content type "${contentType}" (${resourceType}): ${reqUrl}`
5072
5980
  );
5073
- try {
5074
- return await route.continue({ headers });
5075
- } catch (error) {
5076
- if (this.isRouteAlreadyHandledError(error)) {
5077
- logger.debug(`Route already handled (continue): ${reqUrl}`);
5078
- return;
5079
- }
5080
- const errorMessage = error instanceof Error ? error.message : String(error);
5081
- logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
5082
- try {
5083
- return await route.abort("failed");
5084
- } catch (abortError) {
5085
- if (this.isRouteAlreadyHandledError(abortError)) {
5086
- logger.debug(`Route already handled (abort after continue error): ${reqUrl}`);
5087
- return;
5088
- }
5089
- throw abortError;
5090
- }
5981
+ return;
5982
+ }
5983
+ const body = await response.text();
5984
+ if (body.length === 0) {
5985
+ return;
5986
+ }
5987
+ const contentSizeBytes = Buffer.byteLength(body, "utf8");
5988
+ const maxCacheItemSizeBytes = this.config?.fetcher?.maxCacheItemSizeBytes ?? defaults.scraper.fetcher.maxCacheItemSizeBytes;
5989
+ if (contentSizeBytes > maxCacheItemSizeBytes) {
5990
+ logger.debug(
5991
+ `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${maxCacheItemSizeBytes} bytes limit)`
5992
+ );
5993
+ return;
5994
+ }
5995
+ HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType });
5996
+ logger.debug(
5997
+ `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`
5998
+ );
5999
+ }
6000
+ async handleSubresourceRoute(route, customHeaders, credentials, origin) {
6001
+ const reqUrl = route.request().url();
6002
+ const reqOrigin = this.getRequestOrigin(reqUrl);
6003
+ const resourceType = route.request().resourceType();
6004
+ if (!await this.isRequestAllowed(reqUrl)) {
6005
+ await this.abortRoute(route, reqUrl, "policy abort", "blockedbyclient");
6006
+ return;
6007
+ }
6008
+ if (await this.tryBlocklistAbort(route, reqUrl)) {
6009
+ return;
6010
+ }
6011
+ if (this.isSpeculativePrefetch(route)) {
6012
+ logger.debug(`Aborting speculative prefetch ${resourceType}: ${reqUrl}`);
6013
+ await this.abortRoute(route, reqUrl, "prefetch abort", "aborted");
6014
+ return;
6015
+ }
6016
+ if (["image", "font", "media"].includes(resourceType)) {
6017
+ await this.abortRoute(route, reqUrl, "abort");
6018
+ return;
6019
+ }
6020
+ const headers = mergePlaywrightHeaders(
6021
+ route.request().headers(),
6022
+ customHeaders,
6023
+ credentials,
6024
+ origin,
6025
+ reqOrigin ?? void 0
6026
+ );
6027
+ if (route.request().method() !== "GET") {
6028
+ await this.continueRoute(route, reqUrl, resourceType, { headers });
6029
+ return;
6030
+ }
6031
+ const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);
6032
+ if (cached !== void 0) {
6033
+ logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);
6034
+ await this.fulfillRoute(
6035
+ route,
6036
+ reqUrl,
6037
+ { status: 200, contentType: cached.contentType, body: cached.body },
6038
+ "fulfill cached"
6039
+ );
6040
+ return;
6041
+ }
6042
+ try {
6043
+ const response = await route.fetch({ headers });
6044
+ await this.cacheResponseIfEligible(reqUrl, resourceType, response);
6045
+ await this.fulfillRoute(route, reqUrl, { response }, "fulfill");
6046
+ } catch (error) {
6047
+ if (this.ignoreRouteLifecycleError(error, `fetch ${resourceType}`, reqUrl)) {
6048
+ return;
5091
6049
  }
6050
+ const errorMessage = this.formatRouteError(error);
6051
+ logger.debug(`Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`);
6052
+ await this.abortRoute(route, reqUrl, "abort after error", "failed");
6053
+ }
6054
+ }
6055
+ async setupCachingRouteInterception(page, customHeaders = {}, credentials, origin) {
6056
+ await page.route("**/*", async (route) => {
6057
+ await this.handleSubresourceRoute(route, customHeaders, credentials, origin);
5092
6058
  });
5093
6059
  }
5094
6060
  /**
@@ -5109,6 +6075,9 @@ class HtmlPlaywrightMiddleware {
5109
6075
  logger.debug(`Cache miss for frame: ${resolvedUrl}`);
5110
6076
  let framePage = null;
5111
6077
  try {
6078
+ if (!await this.isRequestAllowed(resolvedUrl)) {
6079
+ return "";
6080
+ }
5112
6081
  framePage = await parentPage.context().newPage();
5113
6082
  await this.setupCachingRouteInterception(framePage);
5114
6083
  logger.debug(`Fetching frame content from: ${resolvedUrl}`);
@@ -5230,9 +6199,18 @@ ${frame.content}
5230
6199
  try {
5231
6200
  const browser = await this.ensureBrowser();
5232
6201
  if (credentials) {
5233
- browserContext = await browser.newContext({ httpCredentials: credentials });
6202
+ browserContext = await browser.newContext({
6203
+ httpCredentials: credentials,
6204
+ ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
6205
+ "https://browser-context.local"
6206
+ )
6207
+ });
5234
6208
  } else {
5235
- browserContext = await browser.newContext();
6209
+ browserContext = await browser.newContext({
6210
+ ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
6211
+ "https://browser-context.local"
6212
+ )
6213
+ });
5236
6214
  }
5237
6215
  page = await browserContext.newPage();
5238
6216
  logger.debug(`Playwright: Processing ${context.source}`);
@@ -5263,121 +6241,12 @@ ${frame.content}
5263
6241
  throw error;
5264
6242
  }
5265
6243
  }
5266
- const reqOrigin = (() => {
5267
- try {
5268
- return new URL(reqUrl).origin;
5269
- } catch {
5270
- return null;
5271
- }
5272
- })();
5273
- const resourceType = route.request().resourceType();
5274
- if (["image", "font", "media"].includes(resourceType)) {
5275
- try {
5276
- return await route.abort();
5277
- } catch (error) {
5278
- if (this.isRouteAlreadyHandledError(error)) {
5279
- logger.debug(`Route already handled (abort): ${reqUrl}`);
5280
- return;
5281
- }
5282
- throw error;
5283
- }
5284
- }
5285
- if (route.request().method() === "GET") {
5286
- const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);
5287
- if (cached !== void 0) {
5288
- logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);
5289
- try {
5290
- return await route.fulfill({
5291
- status: 200,
5292
- contentType: cached.contentType,
5293
- body: cached.body
5294
- });
5295
- } catch (error) {
5296
- if (this.isRouteAlreadyHandledError(error)) {
5297
- logger.debug(`Route already handled (fulfill cached): ${reqUrl}`);
5298
- return;
5299
- }
5300
- throw error;
5301
- }
5302
- }
5303
- const headers2 = mergePlaywrightHeaders(
5304
- route.request().headers(),
5305
- customHeaders,
5306
- credentials ?? void 0,
5307
- origin ?? void 0,
5308
- reqOrigin ?? void 0
5309
- );
5310
- try {
5311
- const response = await route.fetch({ headers: headers2 });
5312
- const body = await response.text();
5313
- if (response.status() >= 200 && response.status() < 300 && body.length > 0) {
5314
- const contentSizeBytes = Buffer.byteLength(body, "utf8");
5315
- const maxCacheItemSizeBytes = this.config?.fetcher?.maxCacheItemSizeBytes ?? defaults.scraper.fetcher.maxCacheItemSizeBytes;
5316
- if (contentSizeBytes <= maxCacheItemSizeBytes) {
5317
- const contentType2 = response.headers()["content-type"] || "application/octet-stream";
5318
- HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType: contentType2 });
5319
- logger.debug(
5320
- `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`
5321
- );
5322
- } else {
5323
- logger.debug(
5324
- `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${maxCacheItemSizeBytes} bytes limit)`
5325
- );
5326
- }
5327
- }
5328
- try {
5329
- return await route.fulfill({ response });
5330
- } catch (error) {
5331
- if (this.isRouteAlreadyHandledError(error)) {
5332
- logger.debug(`Route already handled (fulfill): ${reqUrl}`);
5333
- return;
5334
- }
5335
- throw error;
5336
- }
5337
- } catch (error) {
5338
- const errorMessage = error instanceof Error ? error.message : String(error);
5339
- logger.debug(
5340
- `Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`
5341
- );
5342
- try {
5343
- return await route.abort("failed");
5344
- } catch (abortError) {
5345
- if (this.isRouteAlreadyHandledError(abortError)) {
5346
- logger.debug(`Route already handled (abort after error): ${reqUrl}`);
5347
- return;
5348
- }
5349
- throw abortError;
5350
- }
5351
- }
5352
- }
5353
- const headers = mergePlaywrightHeaders(
5354
- route.request().headers(),
6244
+ await this.handleSubresourceRoute(
6245
+ route,
5355
6246
  customHeaders,
5356
6247
  credentials ?? void 0,
5357
- origin ?? void 0,
5358
- reqOrigin ?? void 0
6248
+ origin ?? void 0
5359
6249
  );
5360
- try {
5361
- return await route.continue({ headers });
5362
- } catch (error) {
5363
- if (this.isRouteAlreadyHandledError(error)) {
5364
- logger.debug(`Route already handled (continue): ${reqUrl}`);
5365
- return;
5366
- }
5367
- const errorMessage = error instanceof Error ? error.message : String(error);
5368
- logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
5369
- try {
5370
- return await route.abort("failed");
5371
- } catch (abortError) {
5372
- if (this.isRouteAlreadyHandledError(abortError)) {
5373
- logger.debug(
5374
- `Route already handled (abort after continue error): ${reqUrl}`
5375
- );
5376
- return;
5377
- }
5378
- throw abortError;
5379
- }
5380
- }
5381
6250
  });
5382
6251
  await page.goto(context.source, { waitUntil: "load" });
5383
6252
  const pageTimeoutMs = this.config.pageTimeoutMs ?? defaults.scraper.pageTimeoutMs;
@@ -5482,7 +6351,7 @@ function mergePlaywrightHeaders(requestHeaders, customHeaders, credentials, orig
5482
6351
  Authorization: `Basic ${basic}`
5483
6352
  };
5484
6353
  }
5485
- return headers;
6354
+ return withMarkdownPreferredAccept(headers, customHeaders);
5486
6355
  }
5487
6356
  class HtmlSanitizerMiddleware {
5488
6357
  // Default selectors to remove
@@ -5556,7 +6425,84 @@ class HtmlSanitizerMiddleware {
5556
6425
  '[role="search"]',
5557
6426
  '[role="region"][aria-label*="skip" i]',
5558
6427
  '[aria-modal="true"]',
5559
- ".noprint"
6428
+ ".noprint",
6429
+ // Skip-links and screen-reader-only anchors (e.g. "Skip to main content").
6430
+ // Scoped to <a> so icon-button labels (`<span class="sr-only">`) are left alone.
6431
+ "a.sr-only",
6432
+ "a.skip-link",
6433
+ "a.skip-nav",
6434
+ "a.screen-reader-only",
6435
+ "a.visually-hidden",
6436
+ // Breadcrumb variants beyond the .breadcrumb class above (ARIA + schema.org).
6437
+ '[aria-label="Breadcrumb" i]',
6438
+ '[itemtype*="BreadcrumbList"]',
6439
+ // Ad networks — removed at sanitization time (after render) rather than at
6440
+ // network level, to avoid triggering anti-adblock detection on monetized
6441
+ // sites. See subresourceBlocklist.ts for the rationale on why ads are not
6442
+ // network-blocked.
6443
+ // Carbon Ads (Vite, Astro, Tailwind, MDN, …)
6444
+ "#carbonads",
6445
+ ".carbonads",
6446
+ ".carbon-wrap",
6447
+ ".carbon-text",
6448
+ ".carbon-img",
6449
+ ".carbon-poweredby",
6450
+ // Scoped to the click-redirect host (srv.carbonads.net) rather than the
6451
+ // apex domain so that legitimate prose links to carbonads.net survive.
6452
+ 'a[href*="srv.carbonads.net"]',
6453
+ // BuySellAds
6454
+ ".bsa-promotion",
6455
+ ".bsa-cpc",
6456
+ '[id^="bsap_"]',
6457
+ '[id^="bsa-zone_"]',
6458
+ 'img[src*="buysellads.com"]',
6459
+ 'img[src*="buysellads.net"]',
6460
+ // EthicalAds (ReadTheDocs, Python/Django docs)
6461
+ ".ethical-rtd",
6462
+ ".ethical-fixedfooter",
6463
+ ".ethical-bottom-right",
6464
+ "[data-ea-publisher]",
6465
+ ".keep-us-sustainable",
6466
+ 'img[src*="ethicalads.io"]',
6467
+ // Google AdSense
6468
+ ".adsbygoogle",
6469
+ "ins.adsbygoogle",
6470
+ '[id^="google_ads_iframe"]',
6471
+ 'img[src*="googlesyndication.com"]',
6472
+ 'img[src*="doubleclick.net"]',
6473
+ // Outbrain / Taboola — content-recommendation widgets, indistinguishable
6474
+ // from ads on doc pages.
6475
+ ".OUTBRAIN",
6476
+ '[data-widget-id^="OB_"]',
6477
+ ".taboola",
6478
+ '[id^="taboola-"]',
6479
+ // Tracker pixels that escape via async injection
6480
+ 'img[src*="bidr.io"]',
6481
+ 'img[src*="adnxs.com"]',
6482
+ 'img[src*="adsrvr.org"]',
6483
+ 'img[src*="analytics.yahoo.com"]',
6484
+ // Third-party search widgets injected outside of nav/header.
6485
+ // Algolia DocSearch (dominant in technical docs)
6486
+ ".DocSearch",
6487
+ ".DocSearch-Button",
6488
+ ".DocSearch-Container",
6489
+ ".DocSearch-Modal",
6490
+ "#docsearch",
6491
+ '[id^="docsearch-"]',
6492
+ ".algolia-autocomplete",
6493
+ ".algolia-docsearch-suggestion",
6494
+ // MkDocs Material result containers (the search box is in nav; results can
6495
+ // render standalone)
6496
+ ".md-search-result",
6497
+ ".md-search__output",
6498
+ // Sphinx / ReadTheDocs search
6499
+ "#searchbox",
6500
+ "#search-results",
6501
+ ".wy-side-search",
6502
+ // Swiftype / Elastic Site Search
6503
+ "#st-search-input",
6504
+ "#st-results-container",
6505
+ ".st-default-search-input"
5560
6506
  ];
5561
6507
  async process(context, next) {
5562
6508
  const $ = context.dom;
@@ -5654,11 +6600,15 @@ class HtmlToMarkdownMiddleware {
5654
6600
  if (match) language = match[1];
5655
6601
  }
5656
6602
  }
5657
- const brElements = Array.from(element.querySelectorAll("br"));
5658
- for (const br of brElements) {
6603
+ const clone = element.cloneNode(true);
6604
+ for (const br of Array.from(clone.querySelectorAll("br"))) {
5659
6605
  br.replaceWith("\n");
5660
6606
  }
5661
- const text = element.textContent || "";
6607
+ const lineNodes = clone.querySelectorAll("span.line, div.line, [data-line]");
6608
+ for (let i = 0; i < lineNodes.length - 1; i++) {
6609
+ lineNodes[i].appendChild(clone.ownerDocument.createTextNode("\n"));
6610
+ }
6611
+ const text = clone.textContent || "";
5662
6612
  return `
5663
6613
  \`\`\`${language}
5664
6614
  ${text.replace(/^\n+|\n+$/g, "")}
@@ -5802,11 +6752,13 @@ class HtmlPipeline extends BasePipeline {
5802
6752
  const maxChunkSize = config.splitter.maxChunkSize;
5803
6753
  const minChunkSize = config.splitter.minChunkSize;
5804
6754
  this.playwrightMiddleware = new HtmlPlaywrightMiddleware(config.scraper);
6755
+ const extractor = config.scraper.htmlExtractor === "defuddle" ? createLazyDefuddleMiddleware() : new HtmlSanitizerMiddleware();
6756
+ logger.debug(`HtmlPipeline using extractor: ${config.scraper.htmlExtractor}`);
5805
6757
  this.standardMiddleware = [
5806
6758
  new HtmlCheerioParserMiddleware(),
5807
6759
  new HtmlMetadataExtractorMiddleware(),
5808
6760
  new HtmlLinkExtractorMiddleware(),
5809
- new HtmlSanitizerMiddleware(),
6761
+ extractor,
5810
6762
  new HtmlNormalizationMiddleware(),
5811
6763
  new HtmlToMarkdownMiddleware()
5812
6764
  ];
@@ -5871,6 +6823,18 @@ class HtmlPipeline extends BasePipeline {
5871
6823
  }
5872
6824
  }
5873
6825
  }
6826
+ function createLazyDefuddleMiddleware() {
6827
+ let real = null;
6828
+ return {
6829
+ async process(context, next) {
6830
+ if (!real) {
6831
+ const mod = await import("./HtmlDefuddleMiddleware-DjhdN_D2.js");
6832
+ real = new mod.HtmlDefuddleMiddleware();
6833
+ }
6834
+ await real.process(context, next);
6835
+ }
6836
+ };
6837
+ }
5874
6838
  class TextDocumentSplitter {
5875
6839
  config;
5876
6840
  textSplitter;
@@ -6231,9 +7195,12 @@ class JsonPipeline extends BasePipeline {
6231
7195
  return currentDepth;
6232
7196
  }
6233
7197
  }
7198
+ const inlineLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\(([^)\s]+)(?:\s+"[^"]*"|\s+'[^']*'|\s+\([^)]*\))?\)/g;
7199
+ const referenceLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\[([^\]\n]+)\]/g;
7200
+ const referenceDefinitionPattern = /^\s{0,3}\[([^\]\n]+)\]:\s*(\S+)(?:\s+.*)?$/gm;
6234
7201
  class MarkdownLinkExtractorMiddleware {
6235
7202
  /**
6236
- * Processes the context. Currently a no-op regarding link extraction.
7203
+ * Processes the context and appends Markdown link targets to context.links.
6237
7204
  * @param context The current processing context.
6238
7205
  * @param next Function to call the next middleware.
6239
7206
  */
@@ -6241,9 +7208,50 @@ class MarkdownLinkExtractorMiddleware {
6241
7208
  if (!Array.isArray(context.links)) {
6242
7209
  context.links = [];
6243
7210
  }
7211
+ for (const link of extractMarkdownLinks(context.content)) {
7212
+ if (!context.links.includes(link)) {
7213
+ context.links.push(link);
7214
+ }
7215
+ }
6244
7216
  await next();
6245
7217
  }
6246
7218
  }
7219
+ function extractMarkdownLinks(content) {
7220
+ const links = [];
7221
+ const referenceDefinitions = /* @__PURE__ */ new Map();
7222
+ for (const match of content.matchAll(referenceDefinitionPattern)) {
7223
+ const label = normalizeReferenceLabel(match[1]);
7224
+ const target = cleanReferenceTarget(match[2]);
7225
+ if (label && target && !referenceDefinitions.has(label)) {
7226
+ referenceDefinitions.set(label, target);
7227
+ }
7228
+ }
7229
+ for (const match of content.matchAll(inlineLinkPattern)) {
7230
+ addUniqueLink(links, match[2]);
7231
+ }
7232
+ for (const match of content.matchAll(referenceLinkPattern)) {
7233
+ const target = referenceDefinitions.get(normalizeReferenceLabel(match[2]));
7234
+ if (target) {
7235
+ addUniqueLink(links, target);
7236
+ }
7237
+ }
7238
+ return links;
7239
+ }
7240
+ function addUniqueLink(links, target) {
7241
+ if (!target || links.includes(target)) {
7242
+ return;
7243
+ }
7244
+ links.push(target);
7245
+ }
7246
+ function normalizeReferenceLabel(label) {
7247
+ return label?.trim().replace(/\s+/g, " ").toLowerCase() ?? "";
7248
+ }
7249
+ function cleanReferenceTarget(target) {
7250
+ if (!target) {
7251
+ return "";
7252
+ }
7253
+ return target.trim().replace(/^<(.+)>$/, "$1");
7254
+ }
6247
7255
  class MarkdownMetadataExtractorMiddleware {
6248
7256
  /**
6249
7257
  * Processes the context to extract the title from Markdown.
@@ -6468,6 +7476,7 @@ class PythonParser {
6468
7476
  constructor(treeSitterSizeLimit = defaults.splitter.treeSitterSizeLimit) {
6469
7477
  this.treeSitterSizeLimit = treeSitterSizeLimit;
6470
7478
  }
7479
+ treeSitterSizeLimit;
6471
7480
  name = "python";
6472
7481
  fileExtensions = [".py", ".pyi", ".pyw"];
6473
7482
  mimeTypes = [
@@ -6881,6 +7890,7 @@ class TypeScriptParser {
6881
7890
  constructor(treeSitterSizeLimit = defaults.splitter.treeSitterSizeLimit) {
6882
7891
  this.treeSitterSizeLimit = treeSitterSizeLimit;
6883
7892
  }
7893
+ treeSitterSizeLimit;
6884
7894
  // Unified extensions: TS + JS
6885
7895
  fileExtensions = [
6886
7896
  ".ts",
@@ -7987,6 +8997,8 @@ class RemoveTool {
7987
8997
  this.documentManagementService = documentManagementService;
7988
8998
  this.pipeline = pipeline;
7989
8999
  }
9000
+ documentManagementService;
9001
+ pipeline;
7990
9002
  /**
7991
9003
  * Executes the tool to remove the specified library version completely.
7992
9004
  * Aborts any QUEUED/RUNNING job for the same library+version before deleting.
@@ -8205,6 +9217,7 @@ class HierarchicalAssemblyStrategy {
8205
9217
  constructor(config) {
8206
9218
  this.config = config;
8207
9219
  }
9220
+ config;
8208
9221
  /**
8209
9222
  * Determines if this strategy can handle the given content type.
8210
9223
  * Handles structured content like source code, JSON, configuration files.
@@ -8623,6 +9636,7 @@ class MarkdownAssemblyStrategy {
8623
9636
  constructor(config) {
8624
9637
  this.config = config;
8625
9638
  }
9639
+ config;
8626
9640
  /**
8627
9641
  * Determines if this strategy can handle the given content type.
8628
9642
  * Handles markdown, HTML, plain text, and serves as fallback for unknown types.
@@ -9948,9 +10962,10 @@ class DocumentStore {
9948
10962
  *
9949
10963
  * @param texts Array of texts to embed
9950
10964
  * @param isRetry Internal flag to prevent duplicate warning logs
10965
+ * @param hasTruncatedSingleText Whether a single text has already been truncated once
9951
10966
  * @returns Array of embedding vectors
9952
10967
  */
9953
- async embedDocumentsWithRetry(texts, isRetry = false) {
10968
+ async embedDocumentsWithRetry(texts, isRetry = false, hasTruncatedSingleText = false) {
9954
10969
  if (texts.length === 0) {
9955
10970
  return [];
9956
10971
  }
@@ -9968,11 +10983,14 @@ class DocumentStore {
9968
10983
  );
9969
10984
  }
9970
10985
  const [firstEmbeddings, secondEmbeddings] = await Promise.all([
9971
- this.embedDocumentsWithRetry(firstHalf, true),
9972
- this.embedDocumentsWithRetry(secondHalf, true)
10986
+ this.embedDocumentsWithRetry(firstHalf, true, false),
10987
+ this.embedDocumentsWithRetry(secondHalf, true, false)
9973
10988
  ]);
9974
10989
  return [...firstEmbeddings, ...secondEmbeddings];
9975
10990
  } else {
10991
+ if (hasTruncatedSingleText) {
10992
+ throw error;
10993
+ }
9976
10994
  const text = texts[0];
9977
10995
  const midpoint = Math.floor(text.length / 2);
9978
10996
  const firstHalf = text.substring(0, midpoint);
@@ -9982,7 +11000,7 @@ class DocumentStore {
9982
11000
  );
9983
11001
  }
9984
11002
  try {
9985
- const embedding = await this.embedDocumentsWithRetry([firstHalf], true);
11003
+ const embedding = await this.embedDocumentsWithRetry([firstHalf], true, true);
9986
11004
  return embedding;
9987
11005
  } catch (retryError) {
9988
11006
  logger.error(
@@ -10271,7 +11289,7 @@ class DocumentStore {
10271
11289
  if (!versionRow) {
10272
11290
  return [];
10273
11291
  }
10274
- const { id: versionId, library_id: libraryId } = versionRow;
11292
+ const { id: versionId } = versionRow;
10275
11293
  if (this.isVectorSearchEnabled) {
10276
11294
  const rawEmbedding = await this.embeddings.embedQuery(query);
10277
11295
  const embedding = this.padVector(rawEmbedding);
@@ -10283,8 +11301,12 @@ class DocumentStore {
10283
11301
  dv.rowid as id,
10284
11302
  dv.distance as vec_distance
10285
11303
  FROM documents_vec dv
10286
- WHERE dv.library_id = ?
10287
- AND dv.version_id = ?
11304
+ JOIN documents d ON dv.rowid = d.id
11305
+ JOIN pages p ON d.page_id = p.id
11306
+ JOIN versions v ON p.version_id = v.id
11307
+ JOIN libraries l ON v.library_id = l.id
11308
+ WHERE l.name = ?
11309
+ AND COALESCE(v.name, '') = COALESCE(?, '')
10288
11310
  AND dv.embedding MATCH ?
10289
11311
  AND dv.k = ?
10290
11312
  ORDER BY dv.distance
@@ -10322,8 +11344,8 @@ class DocumentStore {
10322
11344
  )
10323
11345
  `);
10324
11346
  const rawResults = stmt.all(
10325
- libraryId,
10326
- versionId,
11347
+ library.toLowerCase(),
11348
+ normalizedVersion,
10327
11349
  JSON.stringify(embedding),
10328
11350
  vectorSearchK,
10329
11351
  versionId,
@@ -11790,7 +12812,7 @@ const Layout = ({
11790
12812
  children,
11791
12813
  eventClientConfig
11792
12814
  }) => {
11793
- const versionString = version || "2.2.2";
12815
+ const versionString = version || "2.4.0";
11794
12816
  const versionInitializer = `versionUpdate({ currentVersion: ${`'${versionString}'`} })`;
11795
12817
  return /* @__PURE__ */ jsxs("html", { lang: "en", children: [
11796
12818
  /* @__PURE__ */ jsxs("head", { children: [
@@ -13070,174 +14092,75 @@ const ScrapeFormContent = ({
13070
14092
  }
13071
14093
  )
13072
14094
  ] })
13073
- ] }),
13074
- /* @__PURE__ */ jsxs("div", { class: "flex items-center", children: [
13075
- /* @__PURE__ */ jsx(
13076
- "input",
13077
- {
13078
- id: "followRedirects",
13079
- name: "followRedirects",
13080
- type: "checkbox",
13081
- checked: followRedirectsValue,
13082
- class: "h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
13083
- }
13084
- ),
13085
- /* @__PURE__ */ jsx(
13086
- "label",
13087
- {
13088
- for: "followRedirects",
13089
- class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
13090
- children: "Follow Redirects"
13091
- }
13092
- )
13093
- ] }),
13094
- /* @__PURE__ */ jsxs("div", { class: "flex items-center", children: [
13095
- /* @__PURE__ */ jsx(
13096
- "input",
13097
- {
13098
- id: "ignoreErrors",
13099
- name: "ignoreErrors",
13100
- type: "checkbox",
13101
- checked: ignoreErrorsValue,
13102
- class: "h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
13103
- }
13104
- ),
13105
- /* @__PURE__ */ jsx(
13106
- "label",
13107
- {
13108
- for: "ignoreErrors",
13109
- class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
13110
- children: "Ignore Errors During Scraping"
13111
- }
13112
- )
13113
- ] })
13114
- ] })
13115
- ]
13116
- }
13117
- ),
13118
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
13119
- "button",
13120
- {
13121
- type: "submit",
13122
- class: "w-full flex justify-center py-1.5 px-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500",
13123
- children: "Start Indexing"
13124
- }
13125
- ) })
13126
- ]
13127
- }
13128
- ),
13129
- /* @__PURE__ */ jsx("div", { id: "job-response", class: "mt-2 text-sm" })
13130
- ] });
13131
- };
13132
- const ScrapeForm = ({
13133
- defaultExcludePatterns,
13134
- scraperConfig
13135
- }) => /* @__PURE__ */ jsx("div", { id: "scrape-form-container", class: "animate-[fadeSlideIn_0.2s_ease-out]", children: /* @__PURE__ */ jsx(
13136
- ScrapeFormContent,
13137
- {
13138
- defaultExcludePatterns,
13139
- scraperConfig
13140
- }
13141
- ) });
13142
- const DEFAULT_FILE_EXCLUSIONS = [
13143
- // CHANGELOG files (case variations)
13144
- "**/CHANGELOG.md",
13145
- "**/changelog.md",
13146
- "**/CHANGELOG.mdx",
13147
- "**/changelog.mdx",
13148
- // LICENSE files (case variations)
13149
- "**/LICENSE",
13150
- "**/LICENSE.md",
13151
- "**/license.md",
13152
- // CODE_OF_CONDUCT files (case variations)
13153
- "**/CODE_OF_CONDUCT.md",
13154
- "**/code_of_conduct.md",
13155
- // Test files
13156
- "**/*.test.*",
13157
- "**/*.spec.*",
13158
- "**/*_test.py",
13159
- "**/*_test.go",
13160
- // Package manager lock files
13161
- "**/*.lock",
13162
- "**/package-lock.json",
13163
- "**/yarn.lock",
13164
- "**/pnpm-lock.yaml",
13165
- "**/go.sum",
13166
- // Build artifacts
13167
- "**/*.min.js",
13168
- "**/*.min.css",
13169
- "**/*.map",
13170
- "**/*.d.ts",
13171
- // IDE/System files
13172
- "**/.DS_Store",
13173
- "**/Thumbs.db",
13174
- "**/*.swp",
13175
- "**/*.swo",
13176
- // Internal config files (using regex pattern)
13177
- "/.*\\.(ini|cfg|conf|log|pid)$/"
13178
- ];
13179
- const DEFAULT_FOLDER_EXCLUSIONS = [
13180
- // Archive and deprecated content (matches anywhere in path)
13181
- "**/archive/**",
13182
- "**/archived/**",
13183
- "**/deprecated/**",
13184
- "**/legacy/**",
13185
- "**/old/**",
13186
- "**/outdated/**",
13187
- "**/previous/**",
13188
- "**/superseded/**",
13189
- // Specific paths that don't follow the general pattern
13190
- "docs/old/**",
13191
- // Test directories
13192
- "**/test/**",
13193
- "**/tests/**",
13194
- "**/__tests__/**",
13195
- "**/spec/**",
13196
- // Build output directories
13197
- "**/dist/**",
13198
- "**/build/**",
13199
- "**/out/**",
13200
- "**/target/**",
13201
- "**/.next/**",
13202
- "**/.nuxt/**",
13203
- // IDE directories
13204
- "**/.vscode/**",
13205
- "**/.idea/**",
13206
- // Internationalization folders - non-English locales
13207
- "**/i18n/ar*/**",
13208
- "**/i18n/de*/**",
13209
- "**/i18n/es*/**",
13210
- "**/i18n/fr*/**",
13211
- "**/i18n/hi*/**",
13212
- "**/i18n/it*/**",
13213
- "**/i18n/ja*/**",
13214
- "**/i18n/ko*/**",
13215
- "**/i18n/nl*/**",
13216
- "**/i18n/pl*/**",
13217
- "**/i18n/pt*/**",
13218
- "**/i18n/ru*/**",
13219
- "**/i18n/sv*/**",
13220
- "**/i18n/th*/**",
13221
- "**/i18n/tr*/**",
13222
- "**/i18n/vi*/**",
13223
- "**/i18n/zh*/**",
13224
- // Common locale folder patterns
13225
- "**/zh-cn/**",
13226
- "**/zh-hk/**",
13227
- "**/zh-mo/**",
13228
- "**/zh-sg/**",
13229
- "**/zh-tw/**"
13230
- ];
13231
- const DEFAULT_EXCLUSION_PATTERNS = [
13232
- ...DEFAULT_FILE_EXCLUSIONS,
13233
- ...DEFAULT_FOLDER_EXCLUSIONS
13234
- ];
13235
- function getEffectiveExclusionPatterns(userPatterns) {
13236
- if (userPatterns !== void 0) {
13237
- return userPatterns;
14095
+ ] }),
14096
+ /* @__PURE__ */ jsxs("div", { class: "flex items-center", children: [
14097
+ /* @__PURE__ */ jsx(
14098
+ "input",
14099
+ {
14100
+ id: "followRedirects",
14101
+ name: "followRedirects",
14102
+ type: "checkbox",
14103
+ checked: followRedirectsValue,
14104
+ class: "h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
14105
+ }
14106
+ ),
14107
+ /* @__PURE__ */ jsx(
14108
+ "label",
14109
+ {
14110
+ for: "followRedirects",
14111
+ class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
14112
+ children: "Follow Redirects"
14113
+ }
14114
+ )
14115
+ ] }),
14116
+ /* @__PURE__ */ jsxs("div", { class: "flex items-center", children: [
14117
+ /* @__PURE__ */ jsx(
14118
+ "input",
14119
+ {
14120
+ id: "ignoreErrors",
14121
+ name: "ignoreErrors",
14122
+ type: "checkbox",
14123
+ checked: ignoreErrorsValue,
14124
+ class: "h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
14125
+ }
14126
+ ),
14127
+ /* @__PURE__ */ jsx(
14128
+ "label",
14129
+ {
14130
+ for: "ignoreErrors",
14131
+ class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
14132
+ children: "Ignore Errors During Scraping"
14133
+ }
14134
+ )
14135
+ ] })
14136
+ ] })
14137
+ ]
14138
+ }
14139
+ ),
14140
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
14141
+ "button",
14142
+ {
14143
+ type: "submit",
14144
+ class: "w-full flex justify-center py-1.5 px-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500",
14145
+ children: "Start Indexing"
14146
+ }
14147
+ ) })
14148
+ ]
14149
+ }
14150
+ ),
14151
+ /* @__PURE__ */ jsx("div", { id: "job-response", class: "mt-2 text-sm" })
14152
+ ] });
14153
+ };
14154
+ const ScrapeForm = ({
14155
+ defaultExcludePatterns,
14156
+ scraperConfig
14157
+ }) => /* @__PURE__ */ jsx("div", { id: "scrape-form-container", class: "animate-[fadeSlideIn_0.2s_ease-out]", children: /* @__PURE__ */ jsx(
14158
+ ScrapeFormContent,
14159
+ {
14160
+ defaultExcludePatterns,
14161
+ scraperConfig
13238
14162
  }
13239
- return DEFAULT_EXCLUSION_PATTERNS;
13240
- }
14163
+ ) });
13241
14164
  function registerNewJobRoutes(server, scrapeTool, scraperConfig) {
13242
14165
  server.get("/web/jobs/new", async () => {
13243
14166
  return /* @__PURE__ */ jsx(
@@ -14136,6 +15059,9 @@ class AppServer {
14136
15059
  // Use our own logger
14137
15060
  });
14138
15061
  }
15062
+ docService;
15063
+ pipeline;
15064
+ eventBus;
14139
15065
  server;
14140
15066
  mcpServer = null;
14141
15067
  authManager = null;
@@ -14172,7 +15098,7 @@ class AppServer {
14172
15098
  try {
14173
15099
  if (telemetry.isEnabled()) {
14174
15100
  telemetry.setGlobalContext({
14175
- appVersion: "2.2.2",
15101
+ appVersion: "2.4.0",
14176
15102
  appPlatform: process.platform,
14177
15103
  appNodeVersion: process.version,
14178
15104
  appServicesEnabled: this.getActiveServicesList(),
@@ -14695,82 +15621,137 @@ class PipelineClient {
14695
15621
  logger.debug("PipelineClient.setCallbacks called - no-op for external worker");
14696
15622
  }
14697
15623
  }
14698
- function isRegexPattern(pattern) {
14699
- return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
14700
- }
14701
- function patternToRegExp(pattern) {
14702
- if (isRegexPattern(pattern)) {
14703
- return new RegExp(pattern.slice(1, -1));
14704
- }
14705
- const re = minimatch.makeRe(pattern, { dot: true });
14706
- if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
14707
- return re;
14708
- }
14709
- function matchesAnyPattern(path2, patterns) {
14710
- if (!patterns || patterns.length === 0) return false;
14711
- const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
14712
- return patterns.some((pattern) => {
14713
- if (isRegexPattern(pattern)) {
14714
- return patternToRegExp(pattern).test(normalizedPath);
14715
- }
14716
- const pathForMatch = normalizedPath.replace(/^\//, "");
14717
- const patternForMatch = pattern.startsWith("/") ? pattern.slice(1) : pattern;
14718
- return minimatch(pathForMatch, patternForMatch, { dot: true });
14719
- });
14720
- }
14721
- function extractPathAndQuery(url) {
15624
+ const emptyLlmsTxtResult = () => ({
15625
+ sections: [],
15626
+ links: []
15627
+ });
15628
+ const markdownLinkPattern = /^\s*[-*+]\s+\[([^\]\n]+)]\(([^)\s]+)\)\s*(?::\s*(.+?)\s*)?$/;
15629
+ function isLlmsTxtUrl(url) {
14722
15630
  try {
14723
- const u = new URL(url);
14724
- return u.pathname + (u.search || "");
15631
+ const basename = new URL(url).pathname.split("/").filter(Boolean).at(-1);
15632
+ return basename?.toLowerCase() === "llms.txt";
14725
15633
  } catch {
14726
- return url;
15634
+ return false;
14727
15635
  }
14728
15636
  }
14729
- function shouldIncludeUrl(url, includePatterns, excludePatterns) {
14730
- const path2 = extractPathAndQuery(url);
14731
- const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
14732
- let basename;
14733
- if (url.startsWith("file://")) {
14734
- try {
14735
- const u = new URL(url);
14736
- basename = u.pathname ? u.pathname.split("/").pop() : void 0;
14737
- } catch {
15637
+ function parseLlmsTxt(content) {
15638
+ if (!content.trim() || content.includes("\0")) {
15639
+ return emptyLlmsTxtResult();
15640
+ }
15641
+ if (/^\s*<(?:!doctype\s+html|html|body|head)(?:\s|>)/i.test(content)) {
15642
+ return emptyLlmsTxtResult();
15643
+ }
15644
+ const lines = content.split(/\r?\n/);
15645
+ const firstH1Index = lines.findIndex((line) => /^#\s+\S/.test(line));
15646
+ if (firstH1Index === -1) {
15647
+ return emptyLlmsTxtResult();
15648
+ }
15649
+ const projectName = lines[firstH1Index].replace(/^#\s+/, "").trim();
15650
+ if (!projectName) {
15651
+ return emptyLlmsTxtResult();
15652
+ }
15653
+ const result = {
15654
+ projectName,
15655
+ sections: [],
15656
+ links: []
15657
+ };
15658
+ let currentSection;
15659
+ const summaryLines = [];
15660
+ let collectingSummary = true;
15661
+ for (const line of lines.slice(firstH1Index + 1)) {
15662
+ if (/^#\s+\S/.test(line)) {
15663
+ collectingSummary = false;
15664
+ continue;
15665
+ }
15666
+ const h2Match = /^##\s+(.+?)\s*$/.exec(line);
15667
+ if (h2Match) {
15668
+ collectingSummary = false;
15669
+ const title = h2Match[1].trim();
15670
+ currentSection = {
15671
+ title,
15672
+ optional: title.toLowerCase() === "optional",
15673
+ links: []
15674
+ };
15675
+ result.sections.push(currentSection);
15676
+ continue;
15677
+ }
15678
+ if (collectingSummary) {
15679
+ if (/^>\s?/.test(line)) {
15680
+ summaryLines.push(line.replace(/^>\s?/, "").trim());
15681
+ continue;
15682
+ }
15683
+ if (summaryLines.length > 0 && line.trim() === "") {
15684
+ continue;
15685
+ }
15686
+ if (line.trim() !== "") {
15687
+ collectingSummary = false;
15688
+ }
15689
+ }
15690
+ const linkMatch = markdownLinkPattern.exec(line);
15691
+ if (!linkMatch) {
15692
+ continue;
14738
15693
  }
15694
+ const link = {
15695
+ title: linkMatch[1].trim(),
15696
+ url: linkMatch[2].trim(),
15697
+ optional: currentSection?.optional ?? false,
15698
+ ...currentSection ? { section: currentSection.title } : {},
15699
+ ...linkMatch[3]?.trim() ? { description: linkMatch[3].trim() } : {}
15700
+ };
15701
+ currentSection?.links.push(link);
15702
+ result.links.push(link);
14739
15703
  }
14740
- const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
14741
- const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
14742
- if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns)))
14743
- return false;
14744
- if (!includePatterns || includePatterns.length === 0) return true;
14745
- return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
15704
+ if (summaryLines.length > 0) {
15705
+ result.summary = summaryLines.join("\n");
15706
+ }
15707
+ if (result.links.length === 0) {
15708
+ return emptyLlmsTxtResult();
15709
+ }
15710
+ return result;
14746
15711
  }
15712
+ const INDEX_FILE_PATTERN = /^index(\.[a-z0-9]+)?$/i;
14747
15713
  function computeBaseDirectory(pathname) {
14748
- if (pathname === "") return "/";
15714
+ if (pathname === "" || pathname === "/") return "/";
14749
15715
  if (pathname.endsWith("/")) return pathname;
14750
15716
  const lastSegment = pathname.split("/").at(-1) || "";
14751
- const looksLikeFile = lastSegment.includes(".");
14752
- if (looksLikeFile) {
15717
+ if (INDEX_FILE_PATTERN.test(lastSegment)) {
14753
15718
  return pathname.replace(/\/[^/]*$/, "/");
14754
15719
  }
14755
15720
  return `${pathname}/`;
14756
15721
  }
15722
+ function isPathDescendant(parentPath, childPath) {
15723
+ const normalizedParent = parentPath.endsWith("/") ? parentPath : `${parentPath}/`;
15724
+ if (childPath === normalizedParent) return true;
15725
+ if (`${childPath}/` === normalizedParent) return true;
15726
+ return childPath.startsWith(normalizedParent);
15727
+ }
15728
+ function stripTrailingDot(hostname) {
15729
+ return hostname.endsWith(".") ? hostname.slice(0, -1) : hostname;
15730
+ }
14757
15731
  function isInScope(baseUrl, targetUrl, scope) {
14758
15732
  if (baseUrl.protocol !== targetUrl.protocol) return false;
15733
+ const baseHostNoDot = normalizeHost(baseUrl.host, baseUrl.hostname);
15734
+ const targetHostNoDot = normalizeHost(targetUrl.host, targetUrl.hostname);
14759
15735
  switch (scope) {
14760
15736
  case "subpages": {
14761
- if (baseUrl.hostname !== targetUrl.hostname) return false;
15737
+ if (baseHostNoDot !== targetHostNoDot) return false;
14762
15738
  const baseDir = computeBaseDirectory(baseUrl.pathname);
14763
15739
  return targetUrl.pathname.startsWith(baseDir);
14764
15740
  }
14765
15741
  case "hostname":
14766
- return baseUrl.hostname === targetUrl.hostname;
15742
+ return baseHostNoDot === targetHostNoDot;
14767
15743
  case "domain": {
14768
- return extractPrimaryDomain(baseUrl.hostname) === extractPrimaryDomain(targetUrl.hostname);
15744
+ return extractPrimaryDomain(stripTrailingDot(baseUrl.hostname)) === extractPrimaryDomain(stripTrailingDot(targetUrl.hostname));
14769
15745
  }
14770
15746
  default:
14771
15747
  return false;
14772
15748
  }
14773
15749
  }
15750
+ function normalizeHost(host, hostname) {
15751
+ const stripped = stripTrailingDot(hostname);
15752
+ if (stripped === hostname) return host;
15753
+ return host.replace(hostname, stripped);
15754
+ }
14774
15755
  class FailureThresholdExceededError extends ScraperError {
14775
15756
  }
14776
15757
  class BaseScraperStrategy {
@@ -14816,13 +15797,29 @@ class BaseScraperStrategy {
14816
15797
  /**
14817
15798
  * Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.
14818
15799
  * Scope is checked first, then patterns.
14819
- */
14820
- shouldProcessUrl(url, options) {
14821
- if (options.scope) {
15800
+ *
15801
+ * `internalAllowedFileRoots` opts a queue item out of the protocol-strict
15802
+ * scope check: when a web URL has been accepted as an archive root and the
15803
+ * archive expands into `file://` members, those members are continuations of
15804
+ * the same accepted scrape and should not be rejected because they crossed
15805
+ * from `https:` to `file:`. The bypass is intentionally narrow — the
15806
+ * `file://` target must resolve inside one of the internal roots — so
15807
+ * arbitrary links injected into archive content cannot escape the archive
15808
+ * sandbox via this path. Downstream `resolveFileAccess` enforces the same
15809
+ * rule, but rejecting early here keeps unrelated `file://` URLs out of the
15810
+ * crawl queue entirely.
15811
+ */
15812
+ shouldProcessUrl(url, options, context = {}) {
15813
+ if (isLlmsTxtUrl(url)) {
15814
+ return false;
15815
+ }
15816
+ const isInternalArchiveMember = url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots);
15817
+ if (!isInternalArchiveMember) {
15818
+ const scope = options.scope ?? "subpages";
14822
15819
  try {
14823
15820
  const base = this.canonicalBaseUrl ?? new URL$1(options.url);
14824
15821
  const target = new URL$1(url);
14825
- if (!isInScope(base, target, options.scope)) return false;
15822
+ if (!isInScope(base, target, scope)) return false;
14826
15823
  } catch {
14827
15824
  return false;
14828
15825
  }
@@ -14917,11 +15914,17 @@ class BaseScraperStrategy {
14917
15914
  this.recordChildPageCompletion(item, result);
14918
15915
  ensureFailureRateWithinThreshold();
14919
15916
  throwIfBatchAborted();
14920
- return [];
15917
+ return result.queueItems ?? [];
14921
15918
  }
14922
15919
  if (result.status === FetchStatus.NOT_FOUND) {
14923
15920
  const isRefreshDeletion = this.isRefreshDeletion(item, result);
14924
- if (item.depth === 0 && !isRefreshDeletion) {
15921
+ const fallbackQueueItems = result.queueItems ?? [];
15922
+ const hasNewFallbackQueueItem = fallbackQueueItems.some(
15923
+ (queueItem) => !this.visited.has(
15924
+ normalizeUrl(queueItem.url, this.getUrlNormalizerOptions(options))
15925
+ )
15926
+ );
15927
+ if (item.depth === 0 && !isRefreshDeletion && !hasNewFallbackQueueItem) {
14925
15928
  throw new ScraperError(`Root page not found: ${item.url}`, false);
14926
15929
  }
14927
15930
  if (!isRefreshDeletion) {
@@ -14946,7 +15949,7 @@ class BaseScraperStrategy {
14946
15949
  }
14947
15950
  await progressCallback(progress);
14948
15951
  }
14949
- return [];
15952
+ return fallbackQueueItems;
14950
15953
  }
14951
15954
  if (result.status !== FetchStatus.SUCCESS) {
14952
15955
  logger.error(`❌ Unknown fetch status: ${result.status}`);
@@ -14979,24 +15982,29 @@ class BaseScraperStrategy {
14979
15982
  }
14980
15983
  const nextItems = result.links || [];
14981
15984
  const linkBaseUrl = finalUrl ? new URL$1(finalUrl) : baseUrl;
15985
+ const internalAllowedFileRoots = result.internalAllowedFileRoots ?? item.internalAllowedFileRoots;
14982
15986
  this.recordChildPageCompletion(item, result);
14983
15987
  ensureFailureRateWithinThreshold();
14984
15988
  throwIfBatchAborted();
14985
- return nextItems.map((value) => {
15989
+ const linkQueueItems = nextItems.map((value) => {
14986
15990
  try {
14987
15991
  const targetUrl = new URL$1(value, linkBaseUrl);
14988
- if (!this.shouldProcessUrl(targetUrl.href, options)) {
15992
+ if (!this.shouldProcessUrl(targetUrl.href, options, {
15993
+ internalAllowedFileRoots
15994
+ })) {
14989
15995
  return null;
14990
15996
  }
14991
15997
  return {
14992
15998
  url: targetUrl.href,
14993
- depth: item.depth + 1
15999
+ depth: item.depth + 1,
16000
+ ...internalAllowedFileRoots ? { internalAllowedFileRoots } : {}
14994
16001
  };
14995
16002
  } catch (_error) {
14996
16003
  logger.warn(`❌ Invalid URL: ${value}`);
14997
16004
  }
14998
16005
  return null;
14999
16006
  }).filter((item2) => item2 !== null);
16007
+ return [...result.queueItems ?? [], ...linkQueueItems];
15000
16008
  } catch (error) {
15001
16009
  if (error instanceof FailureThresholdExceededError || error instanceof CancellationError) {
15002
16010
  throw error;
@@ -15100,6 +16108,21 @@ class BaseScraperStrategy {
15100
16108
  async cleanup() {
15101
16109
  }
15102
16110
  }
16111
+ function isFileUrlInsideRoots(url, roots) {
16112
+ if (!roots || roots.length === 0) return false;
16113
+ let target;
16114
+ try {
16115
+ target = path.resolve(fileUrlToPathLoose(url));
16116
+ } catch {
16117
+ return false;
16118
+ }
16119
+ return roots.some((root) => {
16120
+ const resolvedRoot = path.resolve(root);
16121
+ if (resolvedRoot === target) return true;
16122
+ const relative = path.relative(resolvedRoot, target);
16123
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
16124
+ });
16125
+ }
15103
16126
  class GitHubRepoProcessor {
15104
16127
  httpFetcher;
15105
16128
  pipelines;
@@ -16070,21 +17093,24 @@ async function getArchiveAdapter(filePath) {
16070
17093
  return null;
16071
17094
  }
16072
17095
  class LocalFileStrategy extends BaseScraperStrategy {
16073
- fileFetcher = new FileFetcher();
17096
+ fileFetcher;
16074
17097
  pipelines;
17098
+ accessPolicy;
16075
17099
  constructor(config) {
16076
17100
  super(config);
17101
+ this.fileFetcher = new FileFetcher(config.scraper);
16077
17102
  this.pipelines = PipelineFactory$1.createStandardPipelines(config);
17103
+ this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);
16078
17104
  }
16079
17105
  canHandle(url) {
16080
17106
  return url.startsWith("file://");
16081
17107
  }
16082
17108
  async processItem(item, options, _signal) {
16083
- let filePath = item.url.replace(/^file:\/\/\/?/, "");
16084
- filePath = decodeURIComponent(filePath);
16085
- if (!filePath.startsWith("/") && process.platform !== "win32") {
16086
- filePath = `/${filePath}`;
16087
- }
17109
+ const resolvedAccess = await this.accessPolicy.resolveFileAccess(
17110
+ item.url,
17111
+ options.internalAllowedFileRoots
17112
+ );
17113
+ const filePath = resolvedAccess.filePath;
16088
17114
  let stats = null;
16089
17115
  let archivePath = null;
16090
17116
  let innerPath = null;
@@ -16114,16 +17140,25 @@ class LocalFileStrategy extends BaseScraperStrategy {
16114
17140
  }
16115
17141
  if (stats?.isDirectory()) {
16116
17142
  const contents = await fs$1.readdir(filePath);
16117
- const links = contents.map((name) => {
16118
- const url = new URL(
16119
- `file://${path.join(filePath, name).replace(/\\/g, "/")}`
16120
- );
16121
- if (url.hostname !== "") {
16122
- url.pathname = `/${url.hostname}${url.pathname}`;
16123
- url.hostname = "";
16124
- }
16125
- return url.href;
16126
- }).filter((url) => {
17143
+ const visibleContents = this.config.scraper.security.fileAccess.includeHidden ? contents : contents.filter((name) => !name.startsWith("."));
17144
+ const linkEntries = await Promise.all(
17145
+ visibleContents.map(async (name) => {
17146
+ const entryPath = path.join(filePath, name);
17147
+ if (!this.config.scraper.security.fileAccess.followSymlinks) {
17148
+ const entryStats = await fs$1.lstat(entryPath).catch(() => null);
17149
+ if (entryStats?.isSymbolicLink()) {
17150
+ return null;
17151
+ }
17152
+ }
17153
+ const url = new URL(`file://${entryPath.replace(/\\/g, "/")}`);
17154
+ if (url.hostname !== "") {
17155
+ url.pathname = `/${url.hostname}${url.pathname}`;
17156
+ url.hostname = "";
17157
+ }
17158
+ return url.href;
17159
+ })
17160
+ );
17161
+ const links = linkEntries.filter((url) => Boolean(url)).filter((url) => {
16127
17162
  const allowed = this.shouldProcessUrl(url, options);
16128
17163
  if (!allowed) {
16129
17164
  logger.debug(`Skipping out-of-scope link: ${url}`);
@@ -16131,7 +17166,7 @@ class LocalFileStrategy extends BaseScraperStrategy {
16131
17166
  return allowed;
16132
17167
  });
16133
17168
  logger.debug(
16134
- `Found ${links.length} files in ${filePath} (from ${contents.length} entries)`
17169
+ `Found ${links.length} files in ${filePath} (from ${visibleContents.length} entries)`
16135
17170
  );
16136
17171
  return { url: item.url, links, status: FetchStatus.SUCCESS };
16137
17172
  }
@@ -16153,7 +17188,7 @@ class LocalFileStrategy extends BaseScraperStrategy {
16153
17188
  virtualUrl.pathname = `/${virtualUrl.hostname}${virtualUrl.pathname}`;
16154
17189
  virtualUrl.hostname = "";
16155
17190
  }
16156
- if (this.shouldProcessUrl(virtualUrl.href, options)) {
17191
+ if (this.shouldProcessUrl(virtualUrl.href, options) && this.isVisibleArchiveEntry(entry.path)) {
16157
17192
  links.push(virtualUrl.href);
16158
17193
  }
16159
17194
  }
@@ -16221,6 +17256,12 @@ class LocalFileStrategy extends BaseScraperStrategy {
16221
17256
  }
16222
17257
  return { archive: null, inner: null, adapter: null };
16223
17258
  }
17259
+ isVisibleArchiveEntry(entryPath) {
17260
+ if (this.config.scraper.security.fileAccess.includeHidden) {
17261
+ return true;
17262
+ }
17263
+ return !entryPath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
17264
+ }
16224
17265
  async processArchiveEntry(item, archivePath, innerPath, adapter, options) {
16225
17266
  logger.debug(`Reading archive entry: ${innerPath} inside ${archivePath}`);
16226
17267
  try {
@@ -16301,6 +17342,8 @@ class WebScraperStrategy extends BaseScraperStrategy {
16301
17342
  pipelines;
16302
17343
  localFileStrategy;
16303
17344
  tempFiles = [];
17345
+ siblingwiseRedirectWarned = false;
17346
+ pendingLlmsTxtProbe = null;
16304
17347
  constructor(config, options = {}) {
16305
17348
  super(config, { urlNormalizerOptions: options.urlNormalizerOptions });
16306
17349
  this.shouldFollowLinkFn = options.shouldFollowLink;
@@ -16334,6 +17377,152 @@ class WebScraperStrategy extends BaseScraperStrategy {
16334
17377
  return actualUrl;
16335
17378
  }
16336
17379
  // Removed custom isInScope logic; using shared scope utility for consistent behavior
17380
+ createFetchOptions(item, options, signal) {
17381
+ return {
17382
+ signal,
17383
+ followRedirects: options.followRedirects,
17384
+ headers: options.headers,
17385
+ etag: item.etag,
17386
+ ...item.internalAllowedFileRoots ? { internalAllowedFileRoots: item.internalAllowedFileRoots } : {}
17387
+ };
17388
+ }
17389
+ buildMarkdownVariantUrl(url) {
17390
+ const variant = new URL(url);
17391
+ if (variant.pathname.endsWith("/")) {
17392
+ variant.pathname = `${variant.pathname}index.html.md`;
17393
+ return variant.toString();
17394
+ }
17395
+ const lastSegment = variant.pathname.split("/").at(-1) ?? "";
17396
+ if (lastSegment.includes(".")) {
17397
+ variant.pathname = `${variant.pathname}.md`;
17398
+ return variant.toString();
17399
+ }
17400
+ variant.pathname = `${variant.pathname}/index.html.md`;
17401
+ return variant.toString();
17402
+ }
17403
+ isAcceptableMarkdownVariant(rawContent) {
17404
+ const mimeType = rawContent.mimeType.toLowerCase();
17405
+ return MimeTypeUtils.isMarkdown(mimeType) || mimeType === "text/plain";
17406
+ }
17407
+ isMarkdownUrl(url) {
17408
+ const mimeType = MimeTypeUtils.detectMimeTypeFromPath(url);
17409
+ return mimeType ? MimeTypeUtils.isMarkdown(mimeType) : false;
17410
+ }
17411
+ async fetchItemContent(item, options, signal) {
17412
+ const fetchOptions = this.createFetchOptions(item, options, signal);
17413
+ if (!item.fromLlmsTxt || this.isMarkdownUrl(item.url)) {
17414
+ return this.fetcher.fetch(item.url, fetchOptions);
17415
+ }
17416
+ const markdownVariantUrl = this.buildMarkdownVariantUrl(item.url);
17417
+ try {
17418
+ const markdownContent = await this.fetcher.fetch(markdownVariantUrl, fetchOptions);
17419
+ if (markdownContent.status === FetchStatus.SUCCESS && this.isAcceptableMarkdownVariant(markdownContent)) {
17420
+ logger.debug(
17421
+ `llms.txt Markdown URL preference succeeded: ${item.url} -> ${markdownVariantUrl}`
17422
+ );
17423
+ return MimeTypeUtils.isMarkdown(markdownContent.mimeType) ? markdownContent : { ...markdownContent, mimeType: "text/markdown" };
17424
+ }
17425
+ logger.debug(
17426
+ `llms.txt Markdown URL preference fell back for ${item.url}: ${markdownVariantUrl} returned status=${markdownContent.status}, contentType=${markdownContent.mimeType}`
17427
+ );
17428
+ } catch (error) {
17429
+ logger.debug(
17430
+ `llms.txt Markdown URL preference fell back for ${item.url}: ${error}`
17431
+ );
17432
+ }
17433
+ return this.fetcher.fetch(item.url, fetchOptions);
17434
+ }
17435
+ getLlmsTxtCandidates(baseUrl, inputUrl) {
17436
+ const input = new URL(inputUrl);
17437
+ const parentPath = input.pathname.endsWith("/") ? input.pathname : input.pathname.slice(0, input.pathname.lastIndexOf("/") + 1);
17438
+ input.pathname = `${parentPath}llms.txt`.replace(/\/+/g, "/");
17439
+ input.search = "";
17440
+ input.hash = "";
17441
+ const root = new URL(baseUrl);
17442
+ root.pathname = "/llms.txt";
17443
+ root.search = "";
17444
+ root.hash = "";
17445
+ return [.../* @__PURE__ */ new Set([input.toString(), root.toString()])];
17446
+ }
17447
+ /**
17448
+ * Probes for an llms.txt file using the existing fetcher and access policy.
17449
+ * @param baseUrl The site base URL used for the root fallback probe.
17450
+ * @param inputUrl The original input URL used for the subpath probe.
17451
+ * @param options Scraper options to apply to probe requests.
17452
+ * @param signal Optional abort signal.
17453
+ * @returns The first valid llms.txt result, or null when none is available.
17454
+ */
17455
+ async probeLlmsTxt(baseUrl, inputUrl, options, signal) {
17456
+ for (const candidate of this.getLlmsTxtCandidates(baseUrl, inputUrl)) {
17457
+ try {
17458
+ const rawContent = await this.fetcher.fetch(
17459
+ candidate,
17460
+ this.createFetchOptions({ url: candidate, depth: 0 }, options, signal)
17461
+ );
17462
+ if (rawContent.status !== FetchStatus.SUCCESS) {
17463
+ logger.debug(`llms.txt probe failed for ${candidate}: ${rawContent.status}`);
17464
+ continue;
17465
+ }
17466
+ const result = parseLlmsTxt(
17467
+ convertToString(rawContent.content, rawContent.charset)
17468
+ );
17469
+ if (result.links.length === 0) {
17470
+ logger.debug(`llms.txt probe failed for ${candidate}: invalid content`);
17471
+ continue;
17472
+ }
17473
+ logger.info(
17474
+ `📄 Detected llms.txt at ${rawContent.source} (${result.links.length} URLs)`
17475
+ );
17476
+ return { url: rawContent.source, result };
17477
+ } catch (error) {
17478
+ logger.debug(`llms.txt probe failed for ${candidate}: ${error}`);
17479
+ }
17480
+ }
17481
+ return null;
17482
+ }
17483
+ createLlmsTxtQueueItems(options, probe) {
17484
+ const items = [];
17485
+ for (const link of probe.result.links) {
17486
+ try {
17487
+ const targetUrl = new URL(link.url, probe.url);
17488
+ if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") {
17489
+ continue;
17490
+ }
17491
+ if (!this.shouldProcessUrl(targetUrl.href, options)) {
17492
+ continue;
17493
+ }
17494
+ if (this.shouldFollowLinkFn) {
17495
+ const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
17496
+ if (!this.shouldFollowLinkFn(baseUrl, targetUrl)) {
17497
+ continue;
17498
+ }
17499
+ }
17500
+ items.push({ url: targetUrl.href, depth: 0, fromLlmsTxt: true });
17501
+ } catch {
17502
+ }
17503
+ }
17504
+ return items;
17505
+ }
17506
+ consumePendingLlmsTxtQueueItems(item, options) {
17507
+ if (item.depth !== 0) {
17508
+ return [];
17509
+ }
17510
+ const probe = this.pendingLlmsTxtProbe;
17511
+ this.pendingLlmsTxtProbe = null;
17512
+ return probe ? this.createLlmsTxtQueueItems(options, probe) : [];
17513
+ }
17514
+ updateCanonicalBaseUrl(effectiveSource, options) {
17515
+ const final = new URL(effectiveSource);
17516
+ const userPath = new URL(options.url).pathname;
17517
+ if (!isPathDescendant(userPath, final.pathname) && !this.siblingwiseRedirectWarned) {
17518
+ logger.warn(
17519
+ `⚠️ Depth-0 redirect changed path siblingwise. Scope anchor remains the user-provided path; discovered links under the redirected path will not be in scope. Requested: ${options.url} → Final: ${effectiveSource} → Scope anchor: ${userPath}. If the redirected path is intended, resubmit with that URL.`
17520
+ );
17521
+ this.siblingwiseRedirectWarned = true;
17522
+ }
17523
+ final.pathname = userPath;
17524
+ this.canonicalBaseUrl = final;
17525
+ }
16337
17526
  /**
16338
17527
  * Processes a single queue item by fetching its content and processing it through pipelines.
16339
17528
  * @param item - The queue item to process.
@@ -16345,6 +17534,10 @@ class WebScraperStrategy extends BaseScraperStrategy {
16345
17534
  async processItem(item, options, signal) {
16346
17535
  const { url } = item;
16347
17536
  try {
17537
+ if (isLlmsTxtUrl(url)) {
17538
+ logger.debug(`Skipping llms.txt meta-file: ${url}`);
17539
+ return { url, links: [], status: FetchStatus.SUCCESS };
17540
+ }
16348
17541
  if (item.etag) {
16349
17542
  logger.debug(`Processing ${url} with stored ETag: ${item.etag}`);
16350
17543
  }
@@ -16354,22 +17547,28 @@ class WebScraperStrategy extends BaseScraperStrategy {
16354
17547
  return this.processRootArchive(item, options, signal);
16355
17548
  }
16356
17549
  }
16357
- const fetchOptions = {
16358
- signal,
16359
- followRedirects: options.followRedirects,
16360
- headers: options.headers,
16361
- // Forward custom headers
16362
- etag: item.etag
16363
- // Pass ETag for conditional requests
16364
- };
16365
- const rawContent = await this.fetcher.fetch(url, fetchOptions);
17550
+ const rawContent = await this.fetchItemContent(item, options, signal);
16366
17551
  const effectiveSource = options.preserveHashes ? this.restorePreservedHash(url, rawContent.source) : rawContent.source;
17552
+ if (item.depth === 0) {
17553
+ this.updateCanonicalBaseUrl(effectiveSource, options);
17554
+ }
17555
+ const llmsTxtQueueItems = this.consumePendingLlmsTxtQueueItems(item, options);
16367
17556
  logger.debug(
16368
17557
  `Fetch result for ${url}: status=${rawContent.status}, etag=${rawContent.etag || "none"}`
16369
17558
  );
16370
17559
  if (rawContent.status !== FetchStatus.SUCCESS) {
16371
17560
  logger.debug(`Skipping pipeline for ${url} due to status: ${rawContent.status}`);
16372
- return { url: effectiveSource, links: [], status: rawContent.status };
17561
+ return {
17562
+ url: effectiveSource,
17563
+ links: [],
17564
+ queueItems: llmsTxtQueueItems,
17565
+ status: rawContent.status
17566
+ };
17567
+ }
17568
+ if (MimeTypeUtils.isMarkdown(rawContent.mimeType)) {
17569
+ logger.debug(
17570
+ `Server provided Markdown content for ${url} via content negotiation or Markdown URL (${rawContent.mimeType})`
17571
+ );
16373
17572
  }
16374
17573
  let processed;
16375
17574
  for (const pipeline of this.pipelines) {
@@ -16390,40 +17589,43 @@ class WebScraperStrategy extends BaseScraperStrategy {
16390
17589
  logger.warn(
16391
17590
  `⚠️ Unsupported content type "${rawContent.mimeType}" for URL ${url}. Skipping processing.`
16392
17591
  );
16393
- return { url: effectiveSource, links: [], status: FetchStatus.SUCCESS };
17592
+ return {
17593
+ url: effectiveSource,
17594
+ links: [],
17595
+ queueItems: llmsTxtQueueItems,
17596
+ status: FetchStatus.SUCCESS
17597
+ };
16394
17598
  }
16395
17599
  for (const err of processed.errors ?? []) {
16396
17600
  logger.warn(`⚠️ Processing error for ${url}: ${err.message}`);
16397
17601
  }
16398
- if (!processed.textContent || !processed.textContent.trim()) {
17602
+ if (!processed.textContent?.trim()) {
16399
17603
  logger.warn(
16400
17604
  `⚠️ No processable content found for ${url} after pipeline execution.`
16401
17605
  );
16402
17606
  return {
16403
17607
  url: effectiveSource,
16404
17608
  links: processed.links,
17609
+ queueItems: llmsTxtQueueItems,
16405
17610
  status: FetchStatus.SUCCESS
16406
17611
  };
16407
17612
  }
16408
- if (item.depth === 0) {
16409
- this.canonicalBaseUrl = new URL(effectiveSource);
16410
- }
16411
- const filteredLinks = processed.links?.filter((link) => {
17613
+ const filteredLinks = processed.links?.flatMap((link) => {
16412
17614
  try {
16413
- const targetUrl = new URL(link);
17615
+ const targetUrl = new URL(link, effectiveSource);
16414
17616
  if (/\.(zip|tar|gz|tgz)$/i.test(targetUrl.pathname)) {
16415
- return false;
17617
+ return [];
16416
17618
  }
16417
17619
  if (!this.shouldProcessUrl(targetUrl.href, options)) {
16418
- return false;
17620
+ return [];
16419
17621
  }
16420
17622
  if (this.shouldFollowLinkFn) {
16421
17623
  const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
16422
- return this.shouldFollowLinkFn(baseUrl, targetUrl);
17624
+ return this.shouldFollowLinkFn(baseUrl, targetUrl) ? [targetUrl.href] : [];
16423
17625
  }
16424
- return true;
17626
+ return [targetUrl.href];
16425
17627
  } catch {
16426
- return false;
17628
+ return [];
16427
17629
  }
16428
17630
  }) ?? [];
16429
17631
  return {
@@ -16434,6 +17636,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
16434
17636
  contentType: processed.contentType || rawContent.mimeType,
16435
17637
  content: processed,
16436
17638
  links: filteredLinks,
17639
+ queueItems: llmsTxtQueueItems,
16437
17640
  status: FetchStatus.SUCCESS
16438
17641
  };
16439
17642
  } catch (error) {
@@ -16441,6 +17644,16 @@ class WebScraperStrategy extends BaseScraperStrategy {
16441
17644
  throw error;
16442
17645
  }
16443
17646
  }
17647
+ async scrape(options, progressCallback, signal) {
17648
+ this.pendingLlmsTxtProbe = null;
17649
+ this.pendingLlmsTxtProbe = await this.probeLlmsTxt(
17650
+ options.url,
17651
+ options.url,
17652
+ options,
17653
+ signal
17654
+ );
17655
+ await super.scrape(options, progressCallback, signal);
17656
+ }
16444
17657
  async processRootArchive(item, options, signal) {
16445
17658
  logger.info(`📦 Downloading root archive: ${item.url}`);
16446
17659
  const rawContent = await this.fetcher.fetch(item.url, {
@@ -16460,11 +17673,21 @@ class WebScraperStrategy extends BaseScraperStrategy {
16460
17673
  await fs$1.writeFile(tempFile, buffer);
16461
17674
  const localUrl = `file://${tempFile}`;
16462
17675
  const localItem = { ...item, url: localUrl };
16463
- const result = await this.localFileStrategy.processItem(localItem, options, signal);
17676
+ const localOptions = {
17677
+ ...options,
17678
+ internalAllowedFileRoots: [...options.internalAllowedFileRoots ?? [], tempFile]
17679
+ };
17680
+ const result = await this.localFileStrategy.processItem(
17681
+ localItem,
17682
+ localOptions,
17683
+ signal
17684
+ );
16464
17685
  return {
16465
17686
  ...result,
16466
- url: item.url
17687
+ url: item.url,
16467
17688
  // Keep original URL as the source of this item
17689
+ links: result.links,
17690
+ internalAllowedFileRoots: [tempFile]
16468
17691
  // links are file://...
16469
17692
  };
16470
17693
  }
@@ -18500,7 +19723,7 @@ function createCli(argv) {
18500
19723
  let globalEventBus = null;
18501
19724
  let globalTelemetryService = null;
18502
19725
  const commandStartTimes = /* @__PURE__ */ new Map();
18503
- const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.2.2").option("verbose", {
19726
+ const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.4.0").option("verbose", {
18504
19727
  type: "boolean",
18505
19728
  description: "Enable verbose (debug) logging",
18506
19729
  default: false
@@ -18561,7 +19784,7 @@ function createCli(argv) {
18561
19784
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
18562
19785
  const commandName = argv2._[0]?.toString() || "default";
18563
19786
  telemetry.setGlobalContext({
18564
- appVersion: "2.2.2",
19787
+ appVersion: "2.4.0",
18565
19788
  appPlatform: process.platform,
18566
19789
  appNodeVersion: process.version,
18567
19790
  appInterface: "cli",
@@ -18707,4 +19930,4 @@ export {
18707
19930
  cleanupCliCommand,
18708
19931
  runCli
18709
19932
  };
18710
- //# sourceMappingURL=main-DPijzQ1K.js.map
19933
+ //# sourceMappingURL=main-BoUugvTO.js.map