@arabold/docs-mcp-server 2.2.1 → 2.3.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();
@@ -368,10 +398,13 @@ const DEFAULT_CONFIG = {
368
398
  maxPages: 1e3,
369
399
  maxDepth: 3,
370
400
  maxConcurrency: 3,
401
+ abortOnFailureRate: 0.5,
402
+ preserveHashes: false,
403
+ skipKnownTrackers: true,
371
404
  pageTimeoutMs: 5e3,
372
405
  browserTimeoutMs: 3e4,
373
406
  fetcher: {
374
- maxRetries: 6,
407
+ maxRetries: 3,
375
408
  baseDelayMs: 1e3,
376
409
  maxCacheItems: 200,
377
410
  maxCacheItemSizeBytes: 500 * 1024
@@ -379,6 +412,21 @@ const DEFAULT_CONFIG = {
379
412
  document: {
380
413
  maxSize: 10 * 1024 * 1024
381
414
  // 10MB max size for PDF/Office documents
415
+ },
416
+ security: {
417
+ network: {
418
+ mode: "open",
419
+ allowPrivateNetworks: false,
420
+ allowedHosts: [],
421
+ allowedCidrs: [],
422
+ allowInvalidTls: false
423
+ },
424
+ fileAccess: {
425
+ mode: "allowedRoots",
426
+ allowedRoots: ["$DOCUMENTS"],
427
+ followSymlinks: false,
428
+ includeHidden: false
429
+ }
382
430
  }
383
431
  },
384
432
  splitter: {
@@ -446,6 +494,9 @@ const AppConfigSchema = z.object({
446
494
  maxPages: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxPages),
447
495
  maxDepth: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxDepth),
448
496
  maxConcurrency: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxConcurrency),
497
+ abortOnFailureRate: z.coerce.number().min(0).max(1).default(DEFAULT_CONFIG.scraper.abortOnFailureRate),
498
+ preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),
499
+ skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
449
500
  pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
450
501
  browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
451
502
  fetcher: z.object({
@@ -456,7 +507,36 @@ const AppConfigSchema = z.object({
456
507
  }).default(DEFAULT_CONFIG.scraper.fetcher),
457
508
  document: z.object({
458
509
  maxSize: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.document.maxSize)
459
- }).default(DEFAULT_CONFIG.scraper.document)
510
+ }).default(DEFAULT_CONFIG.scraper.document),
511
+ security: z.object({
512
+ network: z.object({
513
+ mode: z.enum(["open", "allowlist"]).default(DEFAULT_CONFIG.scraper.security.network.mode),
514
+ allowPrivateNetworks: envBoolean.default(
515
+ DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks
516
+ ),
517
+ allowedHosts: envStringArray.default(
518
+ DEFAULT_CONFIG.scraper.security.network.allowedHosts
519
+ ),
520
+ allowedCidrs: envStringArray.default(
521
+ DEFAULT_CONFIG.scraper.security.network.allowedCidrs
522
+ ),
523
+ allowInvalidTls: envBoolean.default(
524
+ DEFAULT_CONFIG.scraper.security.network.allowInvalidTls
525
+ )
526
+ }).default(DEFAULT_CONFIG.scraper.security.network),
527
+ fileAccess: z.object({
528
+ mode: z.enum(["disabled", "allowedRoots", "unrestricted"]).default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),
529
+ allowedRoots: envStringArray.default(
530
+ DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots
531
+ ),
532
+ followSymlinks: envBoolean.default(
533
+ DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks
534
+ ),
535
+ includeHidden: envBoolean.default(
536
+ DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden
537
+ )
538
+ }).default(DEFAULT_CONFIG.scraper.security.fileAccess)
539
+ }).default(DEFAULT_CONFIG.scraper.security)
460
540
  }).default(DEFAULT_CONFIG.scraper),
461
541
  splitter: z.object({
462
542
  minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),
@@ -574,7 +654,43 @@ function loadConfig(cliArgs = {}, options = {}) {
574
654
  if (!getAtPath(mergedInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) {
575
655
  setAtPath(mergedInput, ["app", "embeddingModel"], "text-embedding-3-small");
576
656
  }
577
- return AppConfigSchema.parse(mergedInput);
657
+ const parseResult = AppConfigSchema.safeParse(mergedInput);
658
+ if (parseResult.success) {
659
+ return parseResult.data;
660
+ }
661
+ if (!isReadOnlyConfig && fs.existsSync(configPath)) {
662
+ const quarantinePath = `${configPath}.invalid-${Date.now()}`;
663
+ try {
664
+ fs.renameSync(configPath, quarantinePath);
665
+ logger.warn(
666
+ `Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`
667
+ );
668
+ } catch (renameError) {
669
+ logger.warn(
670
+ `Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`
671
+ );
672
+ }
673
+ } else {
674
+ logger.warn(
675
+ `Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`
676
+ );
677
+ }
678
+ const fallbackInput = deepMerge(
679
+ defaults,
680
+ deepMerge(envConfig, cliConfig)
681
+ );
682
+ if (!getAtPath(fallbackInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) {
683
+ setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
684
+ }
685
+ const fallback = AppConfigSchema.parse(fallbackInput);
686
+ if (!isReadOnlyConfig) {
687
+ try {
688
+ saveConfigFile(configPath, fallback);
689
+ } catch (error) {
690
+ logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
691
+ }
692
+ }
693
+ return fallback;
578
694
  }
579
695
  function loadConfigFile(filePath) {
580
696
  if (!fs.existsSync(filePath)) return null;
@@ -677,13 +793,14 @@ function getAtPath(obj, pathArr) {
677
793
  function deepMerge(target, source) {
678
794
  if (typeof target !== "object" || target === null) return source;
679
795
  if (typeof source !== "object" || source === null) return target;
796
+ if (Array.isArray(target) || Array.isArray(source)) return source;
680
797
  const t2 = target;
681
798
  const s = source;
682
799
  const output = { ...t2 };
683
800
  for (const key of Object.keys(s)) {
684
801
  const sValue = s[key];
685
802
  const tValue = t2[key];
686
- if (typeof sValue === "object" && sValue !== null && typeof tValue === "object" && tValue !== null && key in t2) {
803
+ if (typeof sValue === "object" && sValue !== null && !Array.isArray(sValue) && typeof tValue === "object" && tValue !== null && !Array.isArray(tValue) && key in t2) {
687
804
  output[key] = deepMerge(tValue, sValue);
688
805
  } else {
689
806
  output[key] = sValue;
@@ -935,10 +1052,33 @@ function createAuthMiddleware(authManager) {
935
1052
  }
936
1053
  };
937
1054
  }
1055
+ const ALLOWED_GRANT_TYPES = /* @__PURE__ */ new Set(["authorization_code", "refresh_token"]);
1056
+ const ALLOWED_RESPONSE_TYPES = /* @__PURE__ */ new Set(["code"]);
1057
+ async function sendUpstreamJsonResponse(reply, response, upstream) {
1058
+ const text = await response.text();
1059
+ if (text.length > 0) {
1060
+ try {
1061
+ const data = JSON.parse(text);
1062
+ if (data !== null && typeof data === "object") {
1063
+ reply.status(response.status).type("application/json").send(data);
1064
+ return;
1065
+ }
1066
+ } catch {
1067
+ }
1068
+ }
1069
+ logger.warn(
1070
+ `Upstream ${upstream} endpoint returned a non-JSON-object body (status=${response.status}, bytes=${text.length})`
1071
+ );
1072
+ reply.status(502).type("application/json").send({
1073
+ error: "server_error",
1074
+ error_description: `Upstream ${upstream} endpoint returned an invalid response.`
1075
+ });
1076
+ }
938
1077
  class ProxyAuthManager {
939
1078
  constructor(config) {
940
1079
  this.config = config;
941
1080
  }
1081
+ config;
942
1082
  proxyProvider = null;
943
1083
  discoveredEndpoints = null;
944
1084
  jwks = null;
@@ -1009,8 +1149,8 @@ class ProxyAuthManager {
1009
1149
  revocation_endpoint: `${baseUrl.origin}/oauth/revoke`,
1010
1150
  registration_endpoint: `${baseUrl.origin}/oauth/register`,
1011
1151
  scopes_supported: ["profile", "email"],
1012
- response_types_supported: ["code"],
1013
- grant_types_supported: ["authorization_code", "refresh_token"],
1152
+ response_types_supported: [...ALLOWED_RESPONSE_TYPES],
1153
+ grant_types_supported: [...ALLOWED_GRANT_TYPES],
1014
1154
  token_endpoint_auth_methods_supported: [
1015
1155
  "client_secret_basic",
1016
1156
  "client_secret_post",
@@ -1020,52 +1160,77 @@ class ProxyAuthManager {
1020
1160
  };
1021
1161
  reply.type("application/json").send(metadata);
1022
1162
  });
1023
- server.get("/.well-known/oauth-protected-resource", async (request, reply) => {
1024
- const baseUrl2 = `${request.protocol}://${request.headers.host}`;
1163
+ server.get("/.well-known/oauth-protected-resource", async (_request, reply) => {
1164
+ const origin = baseUrl.origin;
1025
1165
  const metadata = {
1026
- resource: `${baseUrl2}/sse`,
1166
+ resource: `${origin}/sse`,
1027
1167
  authorization_servers: [this.config.issuerUrl],
1028
1168
  scopes_supported: ["profile", "email"],
1029
1169
  bearer_methods_supported: ["header"],
1030
1170
  resource_name: "Documentation MCP Server",
1031
1171
  resource_documentation: "https://github.com/arabold/docs-mcp-server#readme",
1032
1172
  // Enhanced metadata for better discoverability
1033
- resource_server_metadata_url: `${baseUrl2}/.well-known/oauth-protected-resource`,
1173
+ resource_server_metadata_url: `${origin}/.well-known/oauth-protected-resource`,
1034
1174
  authorization_server_metadata_url: `${this.config.issuerUrl}/.well-known/openid-configuration`,
1035
1175
  jwks_uri: `${this.config.issuerUrl}/.well-known/jwks.json`,
1036
1176
  // Supported MCP transports
1037
1177
  mcp_transports: [
1038
1178
  {
1039
1179
  transport: "sse",
1040
- endpoint: `${baseUrl2}/sse`,
1180
+ endpoint: `${origin}/sse`,
1041
1181
  description: "Server-Sent Events transport"
1042
1182
  },
1043
1183
  {
1044
1184
  transport: "http",
1045
- endpoint: `${baseUrl2}/mcp`,
1185
+ endpoint: `${origin}/mcp`,
1046
1186
  description: "Streaming HTTP transport"
1047
1187
  }
1048
1188
  ]
1049
1189
  };
1050
1190
  reply.type("application/json").send(metadata);
1051
1191
  });
1192
+ const pinnedResourceUrl = `${baseUrl.origin}/sse`;
1052
1193
  server.get("/oauth/authorize", async (request, reply) => {
1053
- const endpoints = await this.discoverEndpoints();
1054
1194
  const params = new URLSearchParams(request.query);
1055
- if (!params.has("resource")) {
1056
- const resourceUrl = `${request.protocol}://${request.headers.host}/sse`;
1057
- params.set("resource", resourceUrl);
1195
+ const responseType = params.get("response_type");
1196
+ if (!responseType) {
1197
+ reply.status(400).type("application/json").send({
1198
+ error: "invalid_request",
1199
+ error_description: "Missing required parameter 'response_type'."
1200
+ });
1201
+ return;
1058
1202
  }
1203
+ if (!ALLOWED_RESPONSE_TYPES.has(responseType)) {
1204
+ reply.status(400).type("application/json").send({
1205
+ error: "unsupported_response_type",
1206
+ error_description: "Only the 'code' response_type is supported by this proxy."
1207
+ });
1208
+ return;
1209
+ }
1210
+ params.set("resource", pinnedResourceUrl);
1211
+ const endpoints = await this.discoverEndpoints();
1059
1212
  const redirectUrl = `${endpoints.authorizationUrl}?${params.toString()}`;
1060
1213
  reply.redirect(redirectUrl);
1061
1214
  });
1062
1215
  server.post("/oauth/token", async (request, reply) => {
1063
- const endpoints = await this.discoverEndpoints();
1064
1216
  const tokenBody = new URLSearchParams(request.body);
1065
- if (!tokenBody.has("resource")) {
1066
- const resourceUrl = `${request.protocol}://${request.headers.host}/sse`;
1067
- tokenBody.set("resource", resourceUrl);
1217
+ const grantType = tokenBody.get("grant_type");
1218
+ if (!grantType) {
1219
+ reply.status(400).type("application/json").send({
1220
+ error: "invalid_request",
1221
+ error_description: "Missing required parameter 'grant_type'."
1222
+ });
1223
+ return;
1068
1224
  }
1225
+ if (!ALLOWED_GRANT_TYPES.has(grantType)) {
1226
+ reply.status(400).type("application/json").send({
1227
+ error: "unsupported_grant_type",
1228
+ error_description: `Grant type '${grantType}' is not supported by this proxy.`
1229
+ });
1230
+ return;
1231
+ }
1232
+ tokenBody.set("resource", pinnedResourceUrl);
1233
+ const endpoints = await this.discoverEndpoints();
1069
1234
  const response = await fetch(endpoints.tokenUrl, {
1070
1235
  method: "POST",
1071
1236
  headers: {
@@ -1073,8 +1238,7 @@ class ProxyAuthManager {
1073
1238
  },
1074
1239
  body: tokenBody.toString()
1075
1240
  });
1076
- const data = await response.json();
1077
- reply.status(response.status).type("application/json").send(data);
1241
+ await sendUpstreamJsonResponse(reply, response, "token");
1078
1242
  });
1079
1243
  server.post("/oauth/revoke", async (request, reply) => {
1080
1244
  const endpoints = await this.discoverEndpoints();
@@ -1101,8 +1265,7 @@ class ProxyAuthManager {
1101
1265
  },
1102
1266
  body: JSON.stringify(request.body)
1103
1267
  });
1104
- const data = await response.json();
1105
- reply.status(response.status).type("application/json").send(data);
1268
+ await sendUpstreamJsonResponse(reply, response, "register");
1106
1269
  } else {
1107
1270
  reply.status(404).send({ error: "Dynamic client registration not supported" });
1108
1271
  }
@@ -1316,6 +1479,8 @@ class RemoteEventProxy {
1316
1479
  this.remoteWorkerUrl = remoteWorkerUrl;
1317
1480
  this.localEventBus = localEventBus;
1318
1481
  }
1482
+ remoteWorkerUrl;
1483
+ localEventBus;
1319
1484
  trpcClient = null;
1320
1485
  wsClient = null;
1321
1486
  subscription = null;
@@ -1412,6 +1577,7 @@ class ToolError extends Error {
1412
1577
  this.toolName = toolName;
1413
1578
  this.name = this.constructor.name;
1414
1579
  }
1580
+ toolName;
1415
1581
  }
1416
1582
  class ValidationError extends ToolError {
1417
1583
  }
@@ -1465,7 +1631,8 @@ function createMcpServerInstance(tools, config) {
1465
1631
  ),
1466
1632
  maxDepth: z$1.number().optional().default(config.scraper.maxDepth).describe(`Maximum navigation depth (default: ${config.scraper.maxDepth}).`),
1467
1633
  scope: z$1.enum(["subpages", "hostname", "domain"]).optional().default("subpages").describe("Crawling boundary: 'subpages', 'hostname', or 'domain'."),
1468
- followRedirects: z$1.boolean().optional().default(true).describe("Follow HTTP redirects (3xx responses).")
1634
+ followRedirects: z$1.boolean().optional().default(true).describe("Follow HTTP redirects (3xx responses)."),
1635
+ preserveHashes: z$1.boolean().optional().describe("Preserve hash fragments for hash-routed SPA documentation sites.")
1469
1636
  },
1470
1637
  {
1471
1638
  title: "Scrape New Library Documentation",
@@ -1474,7 +1641,16 @@ function createMcpServerInstance(tools, config) {
1474
1641
  openWorldHint: true
1475
1642
  // requires internet access
1476
1643
  },
1477
- async ({ url, library, version, maxPages, maxDepth, scope, followRedirects }) => {
1644
+ async ({
1645
+ url,
1646
+ library,
1647
+ version,
1648
+ maxPages,
1649
+ maxDepth,
1650
+ scope,
1651
+ followRedirects,
1652
+ preserveHashes
1653
+ }) => {
1478
1654
  telemetry.track(TelemetryEvent.TOOL_USED, {
1479
1655
  tool: "scrape_docs",
1480
1656
  context: "mcp_server",
@@ -1498,7 +1674,8 @@ function createMcpServerInstance(tools, config) {
1498
1674
  maxPages,
1499
1675
  maxDepth,
1500
1676
  scope,
1501
- followRedirects
1677
+ followRedirects,
1678
+ preserveHashes
1502
1679
  }
1503
1680
  });
1504
1681
  if ("jobId" in result) {
@@ -1939,57 +2116,558 @@ ${formattedJob}`);
1939
2116
  }
1940
2117
  );
1941
2118
  }
1942
- return server;
2119
+ return server;
2120
+ }
2121
+ class ScraperError extends Error {
2122
+ constructor(message, isRetryable = false, cause) {
2123
+ super(message);
2124
+ this.isRetryable = isRetryable;
2125
+ this.cause = cause;
2126
+ this.name = this.constructor.name;
2127
+ if (cause?.stack) {
2128
+ this.stack = `${this.stack}
2129
+ Caused by: ${cause.stack}`;
2130
+ }
2131
+ }
2132
+ isRetryable;
2133
+ cause;
2134
+ }
2135
+ class InvalidUrlError extends ScraperError {
2136
+ constructor(url, cause) {
2137
+ super(`Invalid URL: ${url}`, false, cause);
2138
+ }
2139
+ }
2140
+ class RedirectError extends ScraperError {
2141
+ constructor(originalUrl, redirectUrl, statusCode) {
2142
+ super(
2143
+ `Redirect detected from ${originalUrl} to ${redirectUrl} (status: ${statusCode})`,
2144
+ false
2145
+ );
2146
+ this.originalUrl = originalUrl;
2147
+ this.redirectUrl = redirectUrl;
2148
+ this.statusCode = statusCode;
2149
+ }
2150
+ originalUrl;
2151
+ redirectUrl;
2152
+ statusCode;
2153
+ }
2154
+ class ChallengeError extends ScraperError {
2155
+ constructor(url, statusCode, challengeType) {
2156
+ super(
2157
+ `Challenge detected for ${url} (status: ${statusCode}, type: ${challengeType})`,
2158
+ false
2159
+ );
2160
+ this.url = url;
2161
+ this.statusCode = statusCode;
2162
+ this.challengeType = challengeType;
2163
+ }
2164
+ url;
2165
+ statusCode;
2166
+ challengeType;
2167
+ }
2168
+ class TlsCertificateError extends ScraperError {
2169
+ constructor(url, code, cause) {
2170
+ super(
2171
+ `TLS certificate validation failed for ${url}${code ? ` (${code})` : ""}. The remote site may have an incomplete or untrusted certificate chain.`,
2172
+ false,
2173
+ cause
2174
+ );
2175
+ this.url = url;
2176
+ this.code = code;
2177
+ }
2178
+ url;
2179
+ code;
2180
+ }
2181
+ class AccessPolicyError extends ScraperError {
2182
+ constructor(message) {
2183
+ super(message, false);
2184
+ }
2185
+ }
2186
+ const DEFAULT_FILE_EXCLUSIONS = [
2187
+ // CHANGELOG files (case variations)
2188
+ "**/CHANGELOG.md",
2189
+ "**/changelog.md",
2190
+ "**/CHANGELOG.mdx",
2191
+ "**/changelog.mdx",
2192
+ // LICENSE files (case variations)
2193
+ "**/LICENSE",
2194
+ "**/LICENSE.md",
2195
+ "**/license.md",
2196
+ // CODE_OF_CONDUCT files (case variations)
2197
+ "**/CODE_OF_CONDUCT.md",
2198
+ "**/code_of_conduct.md",
2199
+ // Test files
2200
+ "**/*.test.*",
2201
+ "**/*.spec.*",
2202
+ "**/*_test.py",
2203
+ "**/*_test.go",
2204
+ // Package manager lock files
2205
+ "**/*.lock",
2206
+ "**/package-lock.json",
2207
+ "**/yarn.lock",
2208
+ "**/pnpm-lock.yaml",
2209
+ "**/go.sum",
2210
+ // Build artifacts
2211
+ "**/*.min.js",
2212
+ "**/*.min.css",
2213
+ "**/*.map",
2214
+ "**/*.d.ts",
2215
+ // IDE/System files
2216
+ "**/.DS_Store",
2217
+ "**/Thumbs.db",
2218
+ "**/*.swp",
2219
+ "**/*.swo",
2220
+ // Internal config files (using regex pattern)
2221
+ "/.*\\.(ini|cfg|conf|log|pid)$/"
2222
+ ];
2223
+ const DEFAULT_FOLDER_EXCLUSIONS = [
2224
+ // Archive and deprecated content (matches anywhere in path)
2225
+ "**/archive/**",
2226
+ "**/archived/**",
2227
+ "**/deprecated/**",
2228
+ "**/legacy/**",
2229
+ "**/old/**",
2230
+ "**/outdated/**",
2231
+ "**/previous/**",
2232
+ "**/superseded/**",
2233
+ // Specific paths that don't follow the general pattern
2234
+ "docs/old/**",
2235
+ // Test directories
2236
+ "**/test/**",
2237
+ "**/tests/**",
2238
+ "**/__tests__/**",
2239
+ "**/spec/**",
2240
+ // Build output directories
2241
+ "**/dist/**",
2242
+ "**/build/**",
2243
+ "**/out/**",
2244
+ "**/target/**",
2245
+ "**/.next/**",
2246
+ "**/.nuxt/**",
2247
+ // IDE directories
2248
+ "**/.vscode/**",
2249
+ "**/.idea/**",
2250
+ // Internationalization folders - non-English locales
2251
+ "**/i18n/ar*/**",
2252
+ "**/i18n/de*/**",
2253
+ "**/i18n/es*/**",
2254
+ "**/i18n/fr*/**",
2255
+ "**/i18n/hi*/**",
2256
+ "**/i18n/it*/**",
2257
+ "**/i18n/ja*/**",
2258
+ "**/i18n/ko*/**",
2259
+ "**/i18n/nl*/**",
2260
+ "**/i18n/pl*/**",
2261
+ "**/i18n/pt*/**",
2262
+ "**/i18n/ru*/**",
2263
+ "**/i18n/sv*/**",
2264
+ "**/i18n/th*/**",
2265
+ "**/i18n/tr*/**",
2266
+ "**/i18n/vi*/**",
2267
+ "**/i18n/zh*/**",
2268
+ // Common locale folder patterns
2269
+ "**/zh-cn/**",
2270
+ "**/zh-hk/**",
2271
+ "**/zh-mo/**",
2272
+ "**/zh-sg/**",
2273
+ "**/zh-tw/**"
2274
+ ];
2275
+ const DEFAULT_EXCLUSION_PATTERNS = [
2276
+ ...DEFAULT_FILE_EXCLUSIONS,
2277
+ ...DEFAULT_FOLDER_EXCLUSIONS
2278
+ ];
2279
+ function getEffectiveExclusionPatterns(userPatterns) {
2280
+ if (userPatterns !== void 0) {
2281
+ return userPatterns;
2282
+ }
2283
+ return DEFAULT_EXCLUSION_PATTERNS;
2284
+ }
2285
+ function isRegexPattern(pattern) {
2286
+ return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
2287
+ }
2288
+ function patternToRegExp(pattern) {
2289
+ if (isRegexPattern(pattern)) {
2290
+ return new RegExp(pattern.slice(1, -1));
2291
+ }
2292
+ const re = minimatch.makeRe(pattern, { dot: true });
2293
+ if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
2294
+ return re;
2295
+ }
2296
+ const URL_WITH_PROTOCOL_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
2297
+ function matchesAnyPattern(path2, patterns) {
2298
+ if (!patterns || patterns.length === 0) return false;
2299
+ const isFullUrl = URL_WITH_PROTOCOL_RE.test(path2);
2300
+ const normalizedPath = isFullUrl || path2.startsWith("/") ? path2 : `/${path2}`;
2301
+ return patterns.some((pattern) => {
2302
+ if (isRegexPattern(pattern)) {
2303
+ return patternToRegExp(pattern).test(normalizedPath);
2304
+ }
2305
+ const pathForMatch = normalizedPath.replace(/^\//, "");
2306
+ const patternForMatch = pattern.startsWith("/") ? pattern.slice(1) : pattern;
2307
+ return minimatch(pathForMatch, patternForMatch, { dot: true });
2308
+ });
2309
+ }
2310
+ function matchesAnyHostPattern(value, patterns) {
2311
+ if (!patterns || patterns.length === 0) return false;
2312
+ const normalized = value.toLowerCase();
2313
+ return patterns.some((pattern) => {
2314
+ if (isRegexPattern(pattern)) {
2315
+ return patternToRegExp(pattern).test(value);
2316
+ }
2317
+ return minimatch(normalized, pattern.toLowerCase(), { dot: true });
2318
+ });
2319
+ }
2320
+ function extractPathAndQuery(url) {
2321
+ try {
2322
+ const u = new URL(url);
2323
+ return u.pathname + (u.search || "");
2324
+ } catch {
2325
+ return url;
2326
+ }
2327
+ }
2328
+ function shouldIncludeUrl(url, includePatterns, excludePatterns) {
2329
+ const path2 = extractPathAndQuery(url);
2330
+ const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
2331
+ let basename;
2332
+ if (url.startsWith("file://")) {
2333
+ try {
2334
+ const u = new URL(url);
2335
+ basename = u.pathname ? u.pathname.split("/").pop() : void 0;
2336
+ } catch {
2337
+ }
2338
+ }
2339
+ const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
2340
+ const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
2341
+ if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns)))
2342
+ return false;
2343
+ if (!includePatterns || includePatterns.length === 0) return true;
2344
+ return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
2345
+ }
2346
+ const SPECIAL_USE_IPV4_CIDRS = [
2347
+ "0.0.0.0/8",
2348
+ "10.0.0.0/8",
2349
+ "100.64.0.0/10",
2350
+ "127.0.0.0/8",
2351
+ "169.254.0.0/16",
2352
+ "172.16.0.0/12",
2353
+ "192.0.0.0/24",
2354
+ "192.0.2.0/24",
2355
+ "192.168.0.0/16",
2356
+ "198.18.0.0/15",
2357
+ "198.51.100.0/24",
2358
+ "203.0.113.0/24",
2359
+ "224.0.0.0/4",
2360
+ "240.0.0.0/4"
2361
+ ];
2362
+ const SPECIAL_USE_IPV6_CIDRS = ["::/128", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8"];
2363
+ const ARCHIVE_EXTENSIONS = /* @__PURE__ */ new Set([".zip", ".tar", ".gz", ".tgz"]);
2364
+ class ScraperAccessPolicy {
2365
+ constructor(security) {
2366
+ this.security = security;
2367
+ this.allowedHosts = security.network.allowedHosts;
2368
+ for (const cidr of security.network.allowedCidrs) {
2369
+ this.addCidr(this.allowedCidrs, cidr);
2370
+ }
2371
+ for (const cidr of SPECIAL_USE_IPV4_CIDRS) {
2372
+ this.addCidr(this.specialUseCidrs, cidr);
2373
+ }
2374
+ for (const cidr of SPECIAL_USE_IPV6_CIDRS) {
2375
+ this.addCidr(this.specialUseCidrs, cidr);
2376
+ }
2377
+ }
2378
+ security;
2379
+ allowedCidrs = new net.BlockList();
2380
+ specialUseCidrs = new net.BlockList();
2381
+ allowedHosts;
2382
+ /**
2383
+ * Checks whether a network URL is allowed before connecting.
2384
+ */
2385
+ async assertNetworkUrlAllowed(url) {
2386
+ const parsed = new URL(url);
2387
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2388
+ return;
2389
+ }
2390
+ const hostname = normalizeHostname(parsed.hostname);
2391
+ const ipFamily = net.isIP(hostname);
2392
+ if (this.security.network.mode === "allowlist") {
2393
+ if (ipFamily !== 0) {
2394
+ const family = ipFamily === 6 ? "ipv6" : "ipv4";
2395
+ if (this.allowedCidrs.check(hostname, family)) return;
2396
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2397
+ }
2398
+ if (matchesAnyHostPattern(hostname, this.allowedHosts)) {
2399
+ return;
2400
+ }
2401
+ const addresses2 = await resolveAddresses(hostname);
2402
+ const allAllowedByCidr = addresses2.length > 0 && addresses2.every((address) => {
2403
+ const family = net.isIP(address.address);
2404
+ if (family === 0) return false;
2405
+ return this.allowedCidrs.check(address.address, family === 6 ? "ipv6" : "ipv4");
2406
+ });
2407
+ if (allAllowedByCidr) return;
2408
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2409
+ }
2410
+ if (this.security.network.allowPrivateNetworks) {
2411
+ return;
2412
+ }
2413
+ if (ipFamily !== 0) {
2414
+ this.assertSpecialUseAddressAllowed(hostname, url);
2415
+ return;
2416
+ }
2417
+ if (looksLikeIpLiteral(hostname)) {
2418
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2419
+ }
2420
+ if (matchesAnyHostPattern(hostname, this.allowedHosts)) {
2421
+ return;
2422
+ }
2423
+ const addresses = await resolveAddresses(hostname);
2424
+ for (const address of addresses) {
2425
+ this.assertSpecialUseAddressAllowed(address.address, url);
2426
+ }
2427
+ }
2428
+ /**
2429
+ * Checks whether TLS certificate validation may be bypassed for a URL.
2430
+ */
2431
+ shouldAllowInvalidTls(url) {
2432
+ try {
2433
+ const parsed = new URL(url);
2434
+ return parsed.protocol === "https:" && this.security.network.allowInvalidTls;
2435
+ } catch {
2436
+ return false;
2437
+ }
2438
+ }
2439
+ /**
2440
+ * Resolves and validates a file URL against the configured file access policy.
2441
+ */
2442
+ async resolveFileAccess(url, additionalAllowedRoots = []) {
2443
+ const filePath = fileUrlToPathLoose(url);
2444
+ const resolved = await resolveArchiveAwarePath(filePath);
2445
+ const accessPath = resolved.archivePath ?? filePath;
2446
+ const bypassRoots = await this.expandRoots(additionalAllowedRoots);
2447
+ const matchedBypassRoot = await this.findContainingRoot(
2448
+ accessPath,
2449
+ bypassRoots,
2450
+ false
2451
+ );
2452
+ let matchedRoot = matchedBypassRoot;
2453
+ if (this.security.fileAccess.mode === "disabled" && !matchedBypassRoot) {
2454
+ throw new AccessPolicyError(`Security policy blocked local file access for ${url}`);
2455
+ }
2456
+ if (this.security.fileAccess.mode === "allowedRoots" && !matchedBypassRoot) {
2457
+ const configuredRoots = await this.expandRoots(
2458
+ this.security.fileAccess.allowedRoots
2459
+ );
2460
+ if (configuredRoots.length === 0) {
2461
+ throw new AccessPolicyError(
2462
+ `Security policy blocked local file access for ${url}`
2463
+ );
2464
+ }
2465
+ matchedRoot = await this.findContainingRoot(
2466
+ accessPath,
2467
+ configuredRoots,
2468
+ this.security.fileAccess.followSymlinks
2469
+ );
2470
+ if (!matchedRoot) {
2471
+ throw new AccessPolicyError(
2472
+ `Security policy blocked local file access for ${url}`
2473
+ );
2474
+ }
2475
+ }
2476
+ if (!this.security.fileAccess.followSymlinks && !matchedBypassRoot) {
2477
+ const symlinkPath = await findSymlinkInPath(accessPath);
2478
+ if (symlinkPath) {
2479
+ throw new AccessPolicyError(`Security policy blocked symlink access for ${url}`);
2480
+ }
2481
+ }
2482
+ if (!this.security.fileAccess.includeHidden) {
2483
+ if (hasHiddenSegmentBelowRoot(filePath, matchedRoot)) {
2484
+ throw new AccessPolicyError(
2485
+ `Security policy blocked hidden file access for ${url}`
2486
+ );
2487
+ }
2488
+ if (resolved.virtualArchivePath && hasHiddenArchiveSegment(resolved.virtualArchivePath)) {
2489
+ throw new AccessPolicyError(
2490
+ `Security policy blocked hidden archive entry access for ${url}`
2491
+ );
2492
+ }
2493
+ }
2494
+ return {
2495
+ filePath,
2496
+ accessPath,
2497
+ virtualArchivePath: resolved.virtualArchivePath
2498
+ };
2499
+ }
2500
+ /**
2501
+ * Throws if `address` falls inside a blocked special-use range and is not
2502
+ * explicitly permitted by `allowedCidrs`. Used both for direct-IP targets
2503
+ * and for revalidating DNS-resolved addresses (open mode) and allowlisted
2504
+ * hostnames (allowlist mode, to close DNS-rebinding gaps).
2505
+ */
2506
+ assertSpecialUseAddressAllowed(address, url) {
2507
+ const family = net.isIP(address);
2508
+ if (family === 0) {
2509
+ return;
2510
+ }
2511
+ const type = family === 6 ? "ipv6" : "ipv4";
2512
+ if (!this.specialUseCidrs.check(address, type)) {
2513
+ return;
2514
+ }
2515
+ if (this.allowedCidrs.check(address, type)) {
2516
+ return;
2517
+ }
2518
+ throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
2519
+ }
2520
+ addCidr(blockList, cidr) {
2521
+ const [network, prefix] = cidr.split("/");
2522
+ const family = net.isIP(network);
2523
+ if (family === 0 || prefix === void 0) {
2524
+ return;
2525
+ }
2526
+ blockList.addSubnet(
2527
+ network,
2528
+ Number.parseInt(prefix, 10),
2529
+ family === 6 ? "ipv6" : "ipv4"
2530
+ );
2531
+ }
2532
+ async expandRoots(roots) {
2533
+ const expanded = [];
2534
+ for (const root of roots) {
2535
+ const value = await expandConfiguredRoot(root);
2536
+ if (value) {
2537
+ expanded.push(value);
2538
+ }
2539
+ }
2540
+ return expanded;
2541
+ }
2542
+ async findContainingRoot(accessPath, roots, followSymlinks) {
2543
+ const resolvedAccessPath = await resolveContainmentPath(accessPath, followSymlinks);
2544
+ for (const root of roots) {
2545
+ const resolvedRoot = await resolveContainmentPath(root, followSymlinks);
2546
+ if (pathContains(resolvedRoot, resolvedAccessPath)) {
2547
+ return resolvedRoot;
2548
+ }
2549
+ }
2550
+ return null;
2551
+ }
2552
+ }
2553
+ async function resolveAddresses(hostname) {
2554
+ try {
2555
+ const result = await lookup(hostname, { all: true, verbatim: true });
2556
+ return Array.isArray(result) ? result : [];
2557
+ } catch {
2558
+ return [];
2559
+ }
1943
2560
  }
1944
- class ScraperError extends Error {
1945
- constructor(message, isRetryable = false, cause) {
1946
- super(message);
1947
- this.isRetryable = isRetryable;
1948
- this.cause = cause;
1949
- this.name = this.constructor.name;
1950
- if (cause?.stack) {
1951
- this.stack = `${this.stack}
1952
- Caused by: ${cause.stack}`;
2561
+ function normalizeHostname(hostname) {
2562
+ return hostname.toLowerCase().replace(/^\[(.*)]$/, "$1");
2563
+ }
2564
+ function looksLikeIpLiteral(hostname) {
2565
+ return hostname.includes(":") || /^\d+(?:\.\d+){0,3}$/.test(hostname);
2566
+ }
2567
+ async function findSymlinkInPath(targetPath) {
2568
+ const resolved = path.resolve(targetPath);
2569
+ const root = path.parse(resolved).root;
2570
+ const relative = path.relative(root, resolved);
2571
+ const segments = relative.split(path.sep).filter(Boolean);
2572
+ let current = root;
2573
+ for (const segment of segments) {
2574
+ current = path.join(current, segment);
2575
+ const stats = await fs$1.lstat(current).catch(() => null);
2576
+ if (stats?.isSymbolicLink()) {
2577
+ return current;
1953
2578
  }
1954
2579
  }
2580
+ return null;
1955
2581
  }
1956
- class InvalidUrlError extends ScraperError {
1957
- constructor(url, cause) {
1958
- super(`Invalid URL: ${url}`, false, cause);
2582
+ function fileUrlToPathLoose(url) {
2583
+ let filePath = url.replace(/^file:\/\/\/?/, "");
2584
+ filePath = decodeURIComponent(filePath);
2585
+ if (!filePath.startsWith("/") && process.platform !== "win32") {
2586
+ filePath = `/${filePath}`;
1959
2587
  }
2588
+ return filePath;
1960
2589
  }
1961
- class RedirectError extends ScraperError {
1962
- constructor(originalUrl, redirectUrl, statusCode) {
1963
- super(
1964
- `Redirect detected from ${originalUrl} to ${redirectUrl} (status: ${statusCode})`,
1965
- false
1966
- );
1967
- this.originalUrl = originalUrl;
1968
- this.redirectUrl = redirectUrl;
1969
- this.statusCode = statusCode;
2590
+ const USER_DIR_TOKENS = {
2591
+ $DOCUMENTS: "Documents",
2592
+ $DOWNLOADS: "Downloads",
2593
+ $DESKTOP: "Desktop"
2594
+ };
2595
+ async function expandConfiguredRoot(root) {
2596
+ if (root === "$HOME") {
2597
+ const homeDir = os.homedir();
2598
+ return homeDir ? path.resolve(homeDir) : null;
2599
+ }
2600
+ if (root === "$CWD") {
2601
+ return path.resolve(process.cwd());
2602
+ }
2603
+ const subdir = USER_DIR_TOKENS[root];
2604
+ if (subdir !== void 0) {
2605
+ const homeDir = os.homedir();
2606
+ if (!homeDir) {
2607
+ return null;
2608
+ }
2609
+ const candidate = path.join(homeDir, subdir);
2610
+ const stats = await fs$1.stat(candidate).catch(() => null);
2611
+ if (!stats?.isDirectory()) {
2612
+ return null;
2613
+ }
2614
+ return path.resolve(candidate);
1970
2615
  }
2616
+ return path.resolve(root);
1971
2617
  }
1972
- class ChallengeError extends ScraperError {
1973
- constructor(url, statusCode, challengeType) {
1974
- super(
1975
- `Challenge detected for ${url} (status: ${statusCode}, type: ${challengeType})`,
1976
- false
1977
- );
1978
- this.url = url;
1979
- this.statusCode = statusCode;
1980
- this.challengeType = challengeType;
2618
+ async function resolveArchiveAwarePath(filePath) {
2619
+ let currentPath = filePath;
2620
+ while (currentPath !== "/" && currentPath !== "." && path.dirname(currentPath) !== currentPath) {
2621
+ const stats = await fs$1.lstat(currentPath).catch(() => null);
2622
+ if (stats?.isFile() && looksLikeArchivePath(currentPath)) {
2623
+ const virtualArchivePath = filePath.substring(currentPath.length).replace(/^\/+/, "").replace(/^\\+/, "");
2624
+ return {
2625
+ archivePath: currentPath,
2626
+ virtualArchivePath: virtualArchivePath || null
2627
+ };
2628
+ }
2629
+ if (stats) {
2630
+ return { archivePath: null, virtualArchivePath: null };
2631
+ }
2632
+ currentPath = path.dirname(currentPath);
1981
2633
  }
2634
+ return { archivePath: null, virtualArchivePath: null };
1982
2635
  }
1983
- class TlsCertificateError extends ScraperError {
1984
- constructor(url, code, cause) {
1985
- super(
1986
- `TLS certificate validation failed for ${url}${code ? ` (${code})` : ""}. The remote site may have an incomplete or untrusted certificate chain.`,
1987
- false,
1988
- cause
1989
- );
1990
- this.url = url;
1991
- this.code = code;
2636
+ async function resolveContainmentPath(targetPath, followSymlinks) {
2637
+ if (!followSymlinks) {
2638
+ return path.resolve(targetPath);
2639
+ }
2640
+ return fs$1.realpath(targetPath).catch(() => path.resolve(targetPath));
2641
+ }
2642
+ function looksLikeArchivePath(filePath) {
2643
+ return ARCHIVE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
2644
+ }
2645
+ function pathContains(root, candidate) {
2646
+ if (root === candidate) {
2647
+ return true;
2648
+ }
2649
+ const relative = path.relative(root, candidate);
2650
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
2651
+ }
2652
+ function hasHiddenSegmentBelowRoot(targetPath, matchedRoot) {
2653
+ const resolved = path.resolve(targetPath);
2654
+ let segments;
2655
+ if (matchedRoot) {
2656
+ const resolvedRoot = path.resolve(matchedRoot);
2657
+ if (resolved === resolvedRoot) return false;
2658
+ const relative = path.relative(resolvedRoot, resolved);
2659
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
2660
+ segments = resolved.split(path.sep).filter(Boolean);
2661
+ } else {
2662
+ segments = relative.split(path.sep).filter(Boolean);
2663
+ }
2664
+ } else {
2665
+ segments = resolved.split(path.sep).filter(Boolean);
1992
2666
  }
2667
+ return segments.some((segment) => segment.startsWith("."));
2668
+ }
2669
+ function hasHiddenArchiveSegment(archivePath) {
2670
+ return archivePath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
1993
2671
  }
1994
2672
  class MimeTypeUtils {
1995
2673
  /**
@@ -2500,28 +3178,53 @@ var FetchStatus = /* @__PURE__ */ ((FetchStatus2) => {
2500
3178
  })(FetchStatus || {});
2501
3179
  class BrowserFetcher {
2502
3180
  browser = null;
2503
- page = null;
2504
3181
  fingerprintGenerator;
2505
3182
  defaultTimeoutMs;
3183
+ accessPolicy;
2506
3184
  constructor(scraperConfig) {
2507
3185
  this.defaultTimeoutMs = scraperConfig.browserTimeoutMs;
2508
3186
  this.fingerprintGenerator = new FingerprintGenerator();
3187
+ this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
2509
3188
  }
2510
3189
  canFetch(source) {
2511
3190
  return source.startsWith("http://") || source.startsWith("https://");
2512
3191
  }
3192
+ async isRequestAllowed(url) {
3193
+ try {
3194
+ await this.accessPolicy.assertNetworkUrlAllowed(url);
3195
+ return true;
3196
+ } catch {
3197
+ return false;
3198
+ }
3199
+ }
2513
3200
  async fetch(source, options) {
3201
+ let page = null;
3202
+ let browserContext = null;
2514
3203
  try {
2515
- await this.ensureBrowserReady();
2516
- if (!this.page) {
2517
- throw new ScraperError("Failed to create browser page", false);
2518
- }
2519
- if (options?.headers) {
2520
- await this.page.setExtraHTTPHeaders(options.headers);
2521
- }
3204
+ await this.accessPolicy.assertNetworkUrlAllowed(source);
3205
+ const browser = await this.ensureBrowserReady();
3206
+ const fingerprintHeaders = this.fingerprintGenerator.generateHeaders();
3207
+ browserContext = await browser.newContext({
3208
+ ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
3209
+ "https://browser-context.local"
3210
+ )
3211
+ });
3212
+ page = await browserContext.newPage();
3213
+ await page.setViewportSize({ width: 1920, height: 1080 });
3214
+ await page.route("**/*", async (route) => {
3215
+ const requestUrl = route.request().url();
3216
+ if (!await this.isRequestAllowed(requestUrl)) {
3217
+ return await route.abort("blockedbyclient");
3218
+ }
3219
+ return await route.continue();
3220
+ });
3221
+ await page.setExtraHTTPHeaders({
3222
+ ...fingerprintHeaders,
3223
+ ...options?.headers
3224
+ });
2522
3225
  const timeout = options?.timeout || this.defaultTimeoutMs;
2523
3226
  logger.debug(`Navigating to ${source} with browser...`);
2524
- const response = await this.page.goto(source, {
3227
+ const response = await page.goto(source, {
2525
3228
  waitUntil: "networkidle",
2526
3229
  timeout
2527
3230
  });
@@ -2534,8 +3237,9 @@ class BrowserFetcher {
2534
3237
  throw new ScraperError(`Redirect blocked: ${source} -> ${location}`, false);
2535
3238
  }
2536
3239
  }
2537
- const finalUrl = this.page.url();
2538
- const content = await this.page.content();
3240
+ const finalUrl = page.url();
3241
+ await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
3242
+ const content = await page.content();
2539
3243
  const contentBuffer = Buffer.from(content, "utf-8");
2540
3244
  const contentType = response.headers()["content-type"] || "text/html";
2541
3245
  const { mimeType, charset } = MimeTypeUtils.parseContentType(contentType);
@@ -2560,6 +3264,10 @@ class BrowserFetcher {
2560
3264
  false,
2561
3265
  error instanceof Error ? error : void 0
2562
3266
  );
3267
+ } finally {
3268
+ await page?.unroute("**/*").catch(() => void 0);
3269
+ await page?.close().catch(() => void 0);
3270
+ await browserContext?.close().catch(() => void 0);
2563
3271
  }
2564
3272
  }
2565
3273
  static async launchBrowser() {
@@ -2574,27 +3282,13 @@ class BrowserFetcher {
2574
3282
  logger.debug("Launching browser...");
2575
3283
  this.browser = await BrowserFetcher.launchBrowser();
2576
3284
  }
2577
- if (!this.page) {
2578
- this.page = await this.browser.newPage();
2579
- const dynamicHeaders = this.fingerprintGenerator.generateHeaders();
2580
- await this.page.setExtraHTTPHeaders(dynamicHeaders);
2581
- await this.page.setViewportSize({ width: 1920, height: 1080 });
2582
- }
3285
+ return this.browser;
2583
3286
  }
2584
3287
  /**
2585
3288
  * Close the browser and clean up resources.
2586
3289
  * Always attempts cleanup even if browser is disconnected to reap zombie processes.
2587
3290
  */
2588
3291
  async close() {
2589
- if (this.page) {
2590
- try {
2591
- await this.page.close();
2592
- } catch (error) {
2593
- logger.warn(`⚠️ Error closing browser page: ${error}`);
2594
- } finally {
2595
- this.page = null;
2596
- }
2597
- }
2598
3292
  if (this.browser) {
2599
3293
  try {
2600
3294
  await this.browser.close();
@@ -2608,6 +3302,10 @@ class BrowserFetcher {
2608
3302
  }
2609
3303
  }
2610
3304
  class FileFetcher {
3305
+ accessPolicy;
3306
+ constructor(scraperConfig) {
3307
+ this.accessPolicy = scraperConfig ? new ScraperAccessPolicy(scraperConfig.security) : null;
3308
+ }
2611
3309
  canFetch(source) {
2612
3310
  return source.startsWith("file://");
2613
3311
  }
@@ -2617,11 +3315,10 @@ class FileFetcher {
2617
3315
  * Supports conditional fetching via ETag comparison for efficient refresh operations.
2618
3316
  */
2619
3317
  async fetch(source, options) {
2620
- let filePath = source.replace(/^file:\/\/\/?/, "");
2621
- filePath = decodeURIComponent(filePath);
2622
- if (!filePath.startsWith("/") && process.platform !== "win32") {
2623
- filePath = `/${filePath}`;
2624
- }
3318
+ const filePath = this.accessPolicy ? (await this.accessPolicy.resolveFileAccess(
3319
+ source,
3320
+ options?.internalAllowedFileRoots
3321
+ )).filePath : fileUrlToPathLoose(source);
2625
3322
  try {
2626
3323
  const stats = await fs$1.stat(filePath);
2627
3324
  const currentEtag = crypto.createHash("md5").update(stats.mtime.toISOString()).digest("hex");
@@ -2674,6 +3371,7 @@ class PipelineError extends Error {
2674
3371
  Caused by: ${cause.stack}`;
2675
3372
  }
2676
3373
  }
3374
+ cause;
2677
3375
  }
2678
3376
  class PipelineStateError extends PipelineError {
2679
3377
  }
@@ -2682,6 +3380,7 @@ class CancellationError extends PipelineError {
2682
3380
  super(message);
2683
3381
  }
2684
3382
  }
3383
+ const MAX_REDIRECTS = 5;
2685
3384
  class HttpFetcher {
2686
3385
  maxRetriesDefault;
2687
3386
  baseDelayDefaultMs;
@@ -2729,10 +3428,12 @@ class HttpFetcher {
2729
3428
  "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
2730
3429
  ];
2731
3430
  fingerprintGenerator;
3431
+ accessPolicy;
2732
3432
  constructor(scraperConfig) {
2733
3433
  this.maxRetriesDefault = scraperConfig.fetcher.maxRetries;
2734
3434
  this.baseDelayDefaultMs = scraperConfig.fetcher.baseDelayMs;
2735
3435
  this.fingerprintGenerator = new FingerprintGenerator();
3436
+ this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
2736
3437
  }
2737
3438
  canFetch(source) {
2738
3439
  return source.startsWith("http://") || source.startsWith("https://");
@@ -2757,85 +3458,126 @@ class HttpFetcher {
2757
3458
  return result;
2758
3459
  }
2759
3460
  async performFetch(source, options, maxRetries = this.maxRetriesDefault, baseDelay = this.baseDelayDefaultMs, followRedirects = true) {
3461
+ await this.accessPolicy.assertNetworkUrlAllowed(source);
2760
3462
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
2761
3463
  try {
2762
- const fingerprint = this.fingerprintGenerator.generateHeaders();
2763
- const headers = {
2764
- ...fingerprint,
2765
- ...options?.headers
2766
- // User-provided headers override generated ones
2767
- };
2768
- if (options?.etag) {
2769
- headers["If-None-Match"] = options.etag;
2770
- logger.debug(
2771
- `Conditional request for ${source} with If-None-Match: ${options.etag}`
3464
+ let currentUrl = source;
3465
+ let redirectCount = 0;
3466
+ while (true) {
3467
+ const fingerprint = this.fingerprintGenerator.generateHeaders();
3468
+ const headers = {
3469
+ ...fingerprint,
3470
+ ...options?.headers
3471
+ // User-provided headers override generated ones
3472
+ };
3473
+ if (options?.etag) {
3474
+ headers["If-None-Match"] = options.etag;
3475
+ logger.debug(
3476
+ `Conditional request for ${source} with If-None-Match: ${options.etag}`
3477
+ );
3478
+ }
3479
+ const config = {
3480
+ responseType: "arraybuffer",
3481
+ headers: {
3482
+ ...headers,
3483
+ // Override Accept-Encoding to exclude zstd which Axios doesn't handle automatically
3484
+ // This prevents servers from sending zstd-compressed content that would appear as binary garbage
3485
+ "Accept-Encoding": "gzip, deflate, br"
3486
+ },
3487
+ timeout: options?.timeout,
3488
+ signal: options?.signal,
3489
+ // Pass signal to axios
3490
+ // Redirects are handled manually so every target can be revalidated before connect.
3491
+ maxRedirects: 0,
3492
+ decompress: true,
3493
+ // Allow 304 responses to be handled as successful responses
3494
+ validateStatus: (status) => {
3495
+ return status >= 200 && status < 400 || status === 304;
3496
+ }
3497
+ };
3498
+ if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) {
3499
+ config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
3500
+ }
3501
+ const response = await axios.get(currentUrl, config);
3502
+ if (response.status === 304) {
3503
+ logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
3504
+ return {
3505
+ content: Buffer.from(""),
3506
+ mimeType: "text/plain",
3507
+ source: currentUrl,
3508
+ status: FetchStatus.NOT_MODIFIED
3509
+ };
3510
+ }
3511
+ if (response.status >= 300 && response.status < 400) {
3512
+ const location = response.headers.location;
3513
+ if (!location) {
3514
+ throw new ScraperError(
3515
+ `Redirect response for ${currentUrl} did not include a location header`,
3516
+ false
3517
+ );
3518
+ }
3519
+ if (!followRedirects) {
3520
+ throw new RedirectError(currentUrl, location, response.status);
3521
+ }
3522
+ if (redirectCount >= MAX_REDIRECTS) {
3523
+ throw new ScraperError(
3524
+ `Too many redirects while fetching ${source}`,
3525
+ false
3526
+ );
3527
+ }
3528
+ const redirectUrl = new URL(location, currentUrl).href;
3529
+ await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
3530
+ currentUrl = redirectUrl;
3531
+ redirectCount += 1;
3532
+ continue;
3533
+ }
3534
+ const contentTypeHeader = response.headers["content-type"];
3535
+ const { mimeType, charset } = MimeTypeUtils.parseContentType(
3536
+ typeof contentTypeHeader === "string" ? contentTypeHeader : void 0
2772
3537
  );
2773
- }
2774
- const config = {
2775
- responseType: "arraybuffer",
2776
- headers: {
2777
- ...headers,
2778
- // Override Accept-Encoding to exclude zstd which Axios doesn't handle automatically
2779
- // This prevents servers from sending zstd-compressed content that would appear as binary garbage
2780
- "Accept-Encoding": "gzip, deflate, br"
2781
- },
2782
- timeout: options?.timeout,
2783
- signal: options?.signal,
2784
- // Pass signal to axios
2785
- // Axios follows redirects by default, we need to explicitly disable it if needed
2786
- maxRedirects: followRedirects ? 5 : 0,
2787
- decompress: true,
2788
- // Allow 304 responses to be handled as successful responses
2789
- validateStatus: (status) => {
2790
- return status >= 200 && status < 300 || status === 304;
3538
+ const rawContentEncoding = response.headers["content-encoding"];
3539
+ const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
3540
+ let content;
3541
+ if (response.data instanceof ArrayBuffer) {
3542
+ content = Buffer.from(response.data);
3543
+ } else if (Buffer.isBuffer(response.data)) {
3544
+ content = response.data;
3545
+ } else if (typeof response.data === "string") {
3546
+ content = Buffer.from(response.data, "utf-8");
3547
+ } else {
3548
+ content = Buffer.from(response.data);
2791
3549
  }
2792
- };
2793
- const response = await axios.get(source, config);
2794
- if (response.status === 304) {
2795
- logger.debug(`HTTP 304 Not Modified for ${source}`);
3550
+ const finalUrl = (
3551
+ // Node follow-redirects style
3552
+ response.request?.res?.responseUrl || // Some adapters may expose directly
3553
+ response.request?.responseUrl || // Fallback to axios recorded config URL
3554
+ response.config?.url || currentUrl
3555
+ );
3556
+ await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
3557
+ const etag = response.headers.etag || response.headers.ETag;
3558
+ if (etag) {
3559
+ logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
3560
+ }
3561
+ const lastModified = response.headers["last-modified"];
3562
+ const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
2796
3563
  return {
2797
- content: Buffer.from(""),
2798
- mimeType: "text/plain",
2799
- source,
2800
- status: FetchStatus.NOT_MODIFIED
3564
+ content,
3565
+ mimeType,
3566
+ charset,
3567
+ encoding: contentEncoding,
3568
+ source: finalUrl,
3569
+ etag,
3570
+ lastModified: lastModifiedISO,
3571
+ status: FetchStatus.SUCCESS
2801
3572
  };
2802
3573
  }
2803
- const contentTypeHeader = response.headers["content-type"];
2804
- const { mimeType, charset } = MimeTypeUtils.parseContentType(contentTypeHeader);
2805
- const contentEncoding = response.headers["content-encoding"];
2806
- let content;
2807
- if (response.data instanceof ArrayBuffer) {
2808
- content = Buffer.from(response.data);
2809
- } else if (Buffer.isBuffer(response.data)) {
2810
- content = response.data;
2811
- } else if (typeof response.data === "string") {
2812
- content = Buffer.from(response.data, "utf-8");
2813
- } else {
2814
- content = Buffer.from(response.data);
3574
+ } catch (error) {
3575
+ if (error instanceof RedirectError || error instanceof ChallengeError) {
3576
+ throw error;
2815
3577
  }
2816
- const finalUrl = (
2817
- // Node follow-redirects style
2818
- response.request?.res?.responseUrl || // Some adapters may expose directly
2819
- response.request?.responseUrl || // Fallback to axios recorded config URL
2820
- response.config?.url || source
2821
- );
2822
- const etag = response.headers.etag || response.headers.ETag;
2823
- if (etag) {
2824
- logger.debug(`Received ETag for ${source}: ${etag}`);
3578
+ if (error instanceof ScraperError && !error.isRetryable) {
3579
+ throw error;
2825
3580
  }
2826
- const lastModified = response.headers["last-modified"];
2827
- const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
2828
- return {
2829
- content,
2830
- mimeType,
2831
- charset,
2832
- encoding: contentEncoding,
2833
- source: finalUrl,
2834
- etag,
2835
- lastModified: lastModifiedISO,
2836
- status: FetchStatus.SUCCESS
2837
- };
2838
- } catch (error) {
2839
3581
  const axiosError = error;
2840
3582
  const status = axiosError.response?.status;
2841
3583
  const code = axiosError.code;
@@ -2906,10 +3648,11 @@ class HttpFetcher {
2906
3648
  class AutoDetectFetcher {
2907
3649
  httpFetcher;
2908
3650
  browserFetcher;
2909
- fileFetcher = new FileFetcher();
3651
+ fileFetcher;
2910
3652
  constructor(scraperConfig) {
2911
3653
  this.httpFetcher = new HttpFetcher(scraperConfig);
2912
3654
  this.browserFetcher = new BrowserFetcher(scraperConfig);
3655
+ this.fileFetcher = new FileFetcher(scraperConfig);
2913
3656
  }
2914
3657
  /**
2915
3658
  * Check if this fetcher can handle the given source.
@@ -3293,6 +4036,7 @@ class CodeContentSplitter {
3293
4036
  constructor(options) {
3294
4037
  this.options = options;
3295
4038
  }
4039
+ options;
3296
4040
  async split(content) {
3297
4041
  const language = content.match(/^```(\w+)\n/)?.[1];
3298
4042
  const strippedContent = content.replace(/^```(\w*)\n/, "").replace(/```\s*$/, "");
@@ -3328,6 +4072,7 @@ class TextContentSplitter {
3328
4072
  constructor(options) {
3329
4073
  this.options = options;
3330
4074
  }
4075
+ options;
3331
4076
  /**
3332
4077
  * Splits text content into chunks while trying to preserve semantic boundaries.
3333
4078
  * Prefers paragraph breaks, then line breaks, finally falling back to word boundaries.
@@ -3455,6 +4200,7 @@ class ListContentSplitter {
3455
4200
  this.options = options;
3456
4201
  this.textSplitter = new TextContentSplitter(options);
3457
4202
  }
4203
+ options;
3458
4204
  textSplitter;
3459
4205
  async split(content) {
3460
4206
  if (content.length <= this.options.chunkSize) {
@@ -3524,6 +4270,7 @@ class TableContentSplitter {
3524
4270
  constructor(options) {
3525
4271
  this.options = options;
3526
4272
  }
4273
+ options;
3527
4274
  /**
3528
4275
  * Splits table content into chunks while preserving table structure
3529
4276
  */
@@ -3638,6 +4385,8 @@ class SemanticMarkdownSplitter {
3638
4385
  // Lists prefer to stay together, so use preferred size
3639
4386
  });
3640
4387
  }
4388
+ preferredChunkSize;
4389
+ maxChunkSize;
3641
4390
  turndownService;
3642
4391
  textSplitter;
3643
4392
  codeSplitter;
@@ -4031,8 +4780,10 @@ class DocumentPipeline extends BasePipeline {
4031
4780
  };
4032
4781
  } catch (error) {
4033
4782
  const errorName = error instanceof Error ? error.name : "UnknownError";
4783
+ const reasons = collectErrorReasons(error);
4034
4784
  const safeMessage = `Failed to convert document: ${errorName}`;
4035
- logger.warn(`${safeMessage} for ${rawContent.source}`);
4785
+ const detail = reasons.length > 0 ? ` — ${reasons.join(" | ")}` : "";
4786
+ logger.error(`❌ ${safeMessage} (${mimeType}) for ${rawContent.source}${detail}`);
4036
4787
  return {
4037
4788
  title: null,
4038
4789
  contentType: rawContent.mimeType,
@@ -4098,6 +4849,25 @@ class DocumentPipeline extends BasePipeline {
4098
4849
  }
4099
4850
  }
4100
4851
  }
4852
+ const MAX_ERROR_DETAIL_LENGTH = 500;
4853
+ function collectErrorReasons(error) {
4854
+ const messages = [];
4855
+ const seen = /* @__PURE__ */ new Set();
4856
+ let current = error;
4857
+ let depth = 0;
4858
+ while (current && !seen.has(current) && depth < 10) {
4859
+ seen.add(current);
4860
+ if (current instanceof Error && current.message) {
4861
+ const trimmed = current.message.replace(/\s+/g, " ").trim().slice(0, MAX_ERROR_DETAIL_LENGTH);
4862
+ if (trimmed && !messages.includes(trimmed)) {
4863
+ messages.push(trimmed);
4864
+ }
4865
+ }
4866
+ current = current.cause;
4867
+ depth++;
4868
+ }
4869
+ return messages;
4870
+ }
4101
4871
  class HtmlCheerioParserMiddleware {
4102
4872
  async process(context, next) {
4103
4873
  try {
@@ -4500,15 +5270,122 @@ class SimpleMemoryCache {
4500
5270
  this.cache.clear();
4501
5271
  }
4502
5272
  }
5273
+ const BLOCKLIST_NOT_BLOCKED = Object.freeze({ blocked: false });
5274
+ const SUBRESOURCE_BLOCKLIST = Object.freeze([
5275
+ // Analytics — page-view and event tracking SDKs; no content.
5276
+ { host: "google-analytics.com", category: "Analytics" },
5277
+ { host: "googletagmanager.com", category: "Analytics" },
5278
+ { host: "segment.io", category: "Analytics" },
5279
+ { host: "segment.com", category: "Analytics" },
5280
+ { host: "mixpanel.com", category: "Analytics" },
5281
+ { host: "amplitude.com", category: "Analytics" },
5282
+ { host: "plausible.io", category: "Analytics" },
5283
+ { host: "matomo.cloud", category: "Analytics" },
5284
+ { host: "stats.wp.com", category: "Analytics" },
5285
+ // Session Replay — record user interactions; never content.
5286
+ { host: "hotjar.com", category: "Session Replay" },
5287
+ { host: "fullstory.com", category: "Session Replay" },
5288
+ { host: "logrocket.com", category: "Session Replay" },
5289
+ { host: "lr-ingest.io", category: "Session Replay" },
5290
+ { host: "smartlook.com", category: "Session Replay" },
5291
+ // Chat Widgets — UI overlays the sanitizer strips post-fetch anyway.
5292
+ { host: "intercom.io", category: "Chat Widget" },
5293
+ { host: "intercomcdn.com", category: "Chat Widget" },
5294
+ { host: "widget.kapa.ai", category: "Chat Widget" },
5295
+ { host: "drift.com", category: "Chat Widget" },
5296
+ { host: "driftt.com", category: "Chat Widget" },
5297
+ { host: "crisp.chat", category: "Chat Widget" },
5298
+ { host: "tawk.to", category: "Chat Widget" },
5299
+ { host: "zdassets.com", category: "Chat Widget" },
5300
+ // Captcha — challenge runtimes; documentation pages don't need them.
5301
+ { host: "hcaptcha.com", category: "Captcha" },
5302
+ { host: "recaptcha.net", category: "Captcha" },
5303
+ // Social Embed runtimes — the embed-document iframe is allowed (document type
5304
+ // is exempt at the route handler); only the runtime JS is blocked.
5305
+ {
5306
+ host: "youtube-nocookie.com",
5307
+ pathPrefix: "/s/_/ytembeds/",
5308
+ category: "Social Embed"
5309
+ },
5310
+ { host: "platform.twitter.com", category: "Social Embed" },
5311
+ { host: "connect.facebook.net", category: "Social Embed" },
5312
+ { host: "platform.linkedin.com", category: "Social Embed" }
5313
+ ]);
5314
+ for (const entry of SUBRESOURCE_BLOCKLIST) {
5315
+ if (!entry.host || entry.host.includes("/") || entry.host.includes(":")) {
5316
+ throw new Error(
5317
+ `Invalid blocklist entry: host must be a bare hostname (got "${entry.host}")`
5318
+ );
5319
+ }
5320
+ if ("pathPrefix" in entry && !entry.pathPrefix.startsWith("/")) {
5321
+ throw new Error(
5322
+ `Invalid blocklist entry for "${entry.host}": pathPrefix must start with "/" (got "${entry.pathPrefix}")`
5323
+ );
5324
+ }
5325
+ }
5326
+ function hostMatches(requestHost, entryHost) {
5327
+ if (requestHost === entryHost) return true;
5328
+ return requestHost.endsWith(`.${entryHost}`);
5329
+ }
5330
+ function isBlockedSubresource(url) {
5331
+ let parsed;
5332
+ try {
5333
+ parsed = new URL(url);
5334
+ } catch {
5335
+ return BLOCKLIST_NOT_BLOCKED;
5336
+ }
5337
+ const host = parsed.hostname;
5338
+ for (const entry of SUBRESOURCE_BLOCKLIST) {
5339
+ if (!hostMatches(host, entry.host)) continue;
5340
+ if ("pathPrefix" in entry && !parsed.pathname.startsWith(entry.pathPrefix)) {
5341
+ continue;
5342
+ }
5343
+ return { blocked: true, category: entry.category };
5344
+ }
5345
+ return BLOCKLIST_NOT_BLOCKED;
5346
+ }
4503
5347
  class HtmlPlaywrightMiddleware {
4504
5348
  browser = null;
4505
5349
  config;
5350
+ accessPolicy;
4506
5351
  // Static LRU cache for all fetched resources, shared across instances
4507
5352
  static resourceCache = new SimpleMemoryCache(
4508
5353
  defaults.scraper.fetcher.maxCacheItems
4509
5354
  );
4510
5355
  constructor(config) {
4511
5356
  this.config = config;
5357
+ this.accessPolicy = new ScraperAccessPolicy(config.security);
5358
+ }
5359
+ async isRequestAllowed(url) {
5360
+ try {
5361
+ await this.accessPolicy.assertNetworkUrlAllowed(url);
5362
+ return true;
5363
+ } catch {
5364
+ return false;
5365
+ }
5366
+ }
5367
+ /**
5368
+ * Returns true if the request was handled (aborted) by the built-in tracker
5369
+ * blocklist; the caller should bail out of further processing in that case.
5370
+ * Returns false when the blocklist is disabled, when the request is a
5371
+ * top-level/iframe document navigation, or when no entry matches.
5372
+ */
5373
+ async tryBlocklistAbort(route, reqUrl) {
5374
+ if (!this.config.skipKnownTrackers) return false;
5375
+ if (route.request().resourceType() === "document") return false;
5376
+ const match = isBlockedSubresource(reqUrl);
5377
+ if (!match.blocked) return false;
5378
+ logger.debug(`Blocked sub-resource (${match.category}): ${reqUrl}`);
5379
+ try {
5380
+ await route.abort("blockedbyclient");
5381
+ } catch (error) {
5382
+ if (this.isRouteAlreadyHandledError(error)) {
5383
+ logger.debug(`Route already handled (blocklist abort): ${reqUrl}`);
5384
+ return true;
5385
+ }
5386
+ throw error;
5387
+ }
5388
+ return true;
4512
5389
  }
4513
5390
  /**
4514
5391
  * Initializes the Playwright browser instance.
@@ -4904,6 +5781,12 @@ class HtmlPlaywrightMiddleware {
4904
5781
  }
4905
5782
  })();
4906
5783
  const resourceType = route.request().resourceType();
5784
+ if (!await this.isRequestAllowed(reqUrl)) {
5785
+ return await route.abort("blockedbyclient");
5786
+ }
5787
+ if (await this.tryBlocklistAbort(route, reqUrl)) {
5788
+ return;
5789
+ }
4907
5790
  if (["image", "font", "media"].includes(resourceType)) {
4908
5791
  try {
4909
5792
  return await route.abort();
@@ -5028,6 +5911,9 @@ class HtmlPlaywrightMiddleware {
5028
5911
  logger.debug(`Cache miss for frame: ${resolvedUrl}`);
5029
5912
  let framePage = null;
5030
5913
  try {
5914
+ if (!await this.isRequestAllowed(resolvedUrl)) {
5915
+ return "";
5916
+ }
5031
5917
  framePage = await parentPage.context().newPage();
5032
5918
  await this.setupCachingRouteInterception(framePage);
5033
5919
  logger.debug(`Fetching frame content from: ${resolvedUrl}`);
@@ -5149,16 +6035,34 @@ ${frame.content}
5149
6035
  try {
5150
6036
  const browser = await this.ensureBrowser();
5151
6037
  if (credentials) {
5152
- browserContext = await browser.newContext({ httpCredentials: credentials });
6038
+ browserContext = await browser.newContext({
6039
+ httpCredentials: credentials,
6040
+ ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
6041
+ "https://browser-context.local"
6042
+ )
6043
+ });
5153
6044
  } else {
5154
- browserContext = await browser.newContext();
6045
+ browserContext = await browser.newContext({
6046
+ ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
6047
+ "https://browser-context.local"
6048
+ )
6049
+ });
5155
6050
  }
5156
6051
  page = await browserContext.newPage();
5157
6052
  logger.debug(`Playwright: Processing ${context.source}`);
5158
6053
  await this.injectShadowDOMExtractor(page);
6054
+ const initialRequestUrl = (() => {
6055
+ try {
6056
+ const initialUrl = new URL(context.source);
6057
+ initialUrl.hash = "";
6058
+ return initialUrl.toString();
6059
+ } catch {
6060
+ return context.source;
6061
+ }
6062
+ })();
5159
6063
  await page.route("**/*", async (route) => {
5160
6064
  const reqUrl = route.request().url();
5161
- if (reqUrl === context.source) {
6065
+ if (reqUrl === initialRequestUrl) {
5162
6066
  try {
5163
6067
  return await route.fulfill({
5164
6068
  status: 200,
@@ -5181,6 +6085,12 @@ ${frame.content}
5181
6085
  }
5182
6086
  })();
5183
6087
  const resourceType = route.request().resourceType();
6088
+ if (!await this.isRequestAllowed(reqUrl)) {
6089
+ return await route.abort("blockedbyclient");
6090
+ }
6091
+ if (await this.tryBlocklistAbort(route, reqUrl)) {
6092
+ return;
6093
+ }
5184
6094
  if (["image", "font", "media"].includes(resourceType)) {
5185
6095
  try {
5186
6096
  return await route.abort();
@@ -6378,6 +7288,7 @@ class PythonParser {
6378
7288
  constructor(treeSitterSizeLimit = defaults.splitter.treeSitterSizeLimit) {
6379
7289
  this.treeSitterSizeLimit = treeSitterSizeLimit;
6380
7290
  }
7291
+ treeSitterSizeLimit;
6381
7292
  name = "python";
6382
7293
  fileExtensions = [".py", ".pyi", ".pyw"];
6383
7294
  mimeTypes = [
@@ -6791,6 +7702,7 @@ class TypeScriptParser {
6791
7702
  constructor(treeSitterSizeLimit = defaults.splitter.treeSitterSizeLimit) {
6792
7703
  this.treeSitterSizeLimit = treeSitterSizeLimit;
6793
7704
  }
7705
+ treeSitterSizeLimit;
6794
7706
  // Unified extensions: TS + JS
6795
7707
  fileExtensions = [
6796
7708
  ".ts",
@@ -7821,13 +8733,15 @@ class ListLibrariesTool {
7821
8733
  const libraries = rawLibraries.map(({ library, versions }) => ({
7822
8734
  name: library,
7823
8735
  versions: versions.map((v) => ({
8736
+ id: v.id,
7824
8737
  version: v.ref.version,
7825
8738
  documentCount: v.counts.documents,
7826
8739
  uniqueUrlCount: v.counts.uniqueUrls,
7827
8740
  indexedAt: v.indexedAt,
7828
8741
  status: v.status,
7829
8742
  ...v.progress ? { progress: v.progress } : void 0,
7830
- sourceUrl: v.sourceUrl
8743
+ sourceUrl: v.sourceUrl,
8744
+ preserveHashes: v.preserveHashes
7831
8745
  }))
7832
8746
  }));
7833
8747
  return { libraries };
@@ -7839,7 +8753,7 @@ class RefreshVersionTool {
7839
8753
  this.pipeline = pipeline;
7840
8754
  }
7841
8755
  async execute(options) {
7842
- const { library, version, waitForCompletion = true } = options;
8756
+ const { library, version, preserveHashes, waitForCompletion = true } = options;
7843
8757
  let internalVersion;
7844
8758
  const partialVersionRegex = /^\d+(\.\d+)?$/;
7845
8759
  if (version === null || version === void 0) {
@@ -7868,7 +8782,9 @@ class RefreshVersionTool {
7868
8782
  internalVersion = internalVersion.toLowerCase();
7869
8783
  const pipeline = this.pipeline;
7870
8784
  const refreshVersion = internalVersion === "" ? null : internalVersion;
7871
- const jobId = await pipeline.enqueueRefreshJob(library, refreshVersion);
8785
+ const jobId = await pipeline.enqueueRefreshJob(library, refreshVersion, {
8786
+ preserveHashes
8787
+ });
7872
8788
  if (waitForCompletion) {
7873
8789
  try {
7874
8790
  await pipeline.waitForJobCompletion(jobId);
@@ -7893,6 +8809,8 @@ class RemoveTool {
7893
8809
  this.documentManagementService = documentManagementService;
7894
8810
  this.pipeline = pipeline;
7895
8811
  }
8812
+ documentManagementService;
8813
+ pipeline;
7896
8814
  /**
7897
8815
  * Executes the tool to remove the specified library version completely.
7898
8816
  * Aborts any QUEUED/RUNNING job for the same library+version before deleting.
@@ -7991,6 +8909,7 @@ class ScrapeTool {
7991
8909
  // Pass scrapeMode enum
7992
8910
  includePatterns: scraperOptions?.includePatterns,
7993
8911
  excludePatterns: scraperOptions?.excludePatterns,
8912
+ preserveHashes: scraperOptions?.preserveHashes,
7994
8913
  headers: scraperOptions?.headers,
7995
8914
  // <-- propagate headers
7996
8915
  clean: scraperOptions?.clean
@@ -8110,6 +9029,7 @@ class HierarchicalAssemblyStrategy {
8110
9029
  constructor(config) {
8111
9030
  this.config = config;
8112
9031
  }
9032
+ config;
8113
9033
  /**
8114
9034
  * Determines if this strategy can handle the given content type.
8115
9035
  * Handles structured content like source code, JSON, configuration files.
@@ -8528,6 +9448,7 @@ class MarkdownAssemblyStrategy {
8528
9448
  constructor(config) {
8529
9449
  this.config = config;
8530
9450
  }
9451
+ config;
8531
9452
  /**
8532
9453
  * Determines if this strategy can handle the given content type.
8533
9454
  * Handles markdown, HTML, plain text, and serves as fallback for unknown types.
@@ -9816,6 +10737,35 @@ class DocumentStore {
9816
10737
  const message = error.message.toLowerCase();
9817
10738
  return message.includes("maximum context length") || message.includes("too long") || message.includes("token limit") || message.includes("input is too large") || message.includes("exceeds") || message.includes("max") && message.includes("token");
9818
10739
  }
10740
+ getEmbeddingErrorHint(error) {
10741
+ if (this.isInputSizeError(error)) {
10742
+ return "The embedding input appears to exceed provider or model limits. Check model context size and reduce embedding batch size if needed.";
10743
+ }
10744
+ if (error instanceof Error) {
10745
+ const message = error.message.toLowerCase();
10746
+ if (message.includes("rate limit") || message.includes("429")) {
10747
+ return "The embedding provider appears to be rate limiting requests. Reduce concurrency or retry after the provider quota resets.";
10748
+ }
10749
+ if (message.includes("timed out") || message.includes("econnrefused") || message.includes("enotfound") || message.includes("etimedout") || message.includes("econnreset") || message.includes("network") || message.includes("fetch failed")) {
10750
+ return "The embedding service appears unreachable. Check that the provider endpoint is running and accessible.";
10751
+ }
10752
+ }
10753
+ return null;
10754
+ }
10755
+ createEmbeddingConnectionError(error, context) {
10756
+ const modelSpec = this.embeddingConfig?.modelSpec ?? "unknown";
10757
+ const errorHint = this.getEmbeddingErrorHint(error);
10758
+ const providerHint = this.embeddingConfig ? "Verify embedding provider configuration, model availability, credentials, quota, request size, and backend logs." : null;
10759
+ const hints = [errorHint, providerHint].filter((hint) => hint !== null);
10760
+ const hintText = hints.length > 0 ? `
10761
+ ${hints.join("\n ")}` : "";
10762
+ return new ConnectionError(
10763
+ `Failed to generate embeddings for ${context.url} using ${modelSpec}.
10764
+ Batch ${context.batchIndex}: ${context.batchTextCount} text(s), ${context.batchChars} chars, ${context.totalChunks} page chunk(s).
10765
+ Config: batchSize=${this.embeddingBatchSize}, batchChars=${this.embeddingBatchChars}, vectorDimension=${this.dbDimension}.` + hintText,
10766
+ error
10767
+ );
10768
+ }
9819
10769
  /**
9820
10770
  * Creates embeddings for an array of texts with automatic retry logic for size-related errors.
9821
10771
  * If a batch fails due to size limits:
@@ -9904,38 +10854,41 @@ class DocumentStore {
9904
10854
  let currentBatch = [];
9905
10855
  let currentBatchSize = 0;
9906
10856
  let batchCount = 0;
10857
+ const processEmbeddingBatch = async (isFinalBatch = false) => {
10858
+ batchCount++;
10859
+ const batchTexts = currentBatch;
10860
+ const batchChars = currentBatchSize;
10861
+ logger.debug(
10862
+ `Processing ${isFinalBatch ? "final " : ""}embedding batch ${batchCount}: ${batchTexts.length} texts, ${batchChars} chars`
10863
+ );
10864
+ try {
10865
+ const batchEmbeddings = await this.embedDocumentsWithRetry(batchTexts);
10866
+ rawEmbeddings.push(...batchEmbeddings);
10867
+ } catch (error) {
10868
+ throw this.createEmbeddingConnectionError(error, {
10869
+ url,
10870
+ batchIndex: batchCount,
10871
+ batchTextCount: batchTexts.length,
10872
+ batchChars,
10873
+ totalChunks: chunks.length
10874
+ });
10875
+ }
10876
+ currentBatch = [];
10877
+ currentBatchSize = 0;
10878
+ };
9907
10879
  for (const text of texts) {
9908
10880
  const textSize = text.length;
9909
10881
  if (currentBatchSize + textSize > maxBatchChars && currentBatch.length > 0) {
9910
- batchCount++;
9911
- logger.debug(
9912
- `Processing embedding batch ${batchCount}: ${currentBatch.length} texts, ${currentBatchSize} chars`
9913
- );
9914
- const batchEmbeddings = await this.embedDocumentsWithRetry(currentBatch);
9915
- rawEmbeddings.push(...batchEmbeddings);
9916
- currentBatch = [];
9917
- currentBatchSize = 0;
10882
+ await processEmbeddingBatch();
9918
10883
  }
9919
10884
  currentBatch.push(text);
9920
10885
  currentBatchSize += textSize;
9921
10886
  if (currentBatch.length >= this.embeddingBatchSize) {
9922
- batchCount++;
9923
- logger.debug(
9924
- `Processing embedding batch ${batchCount}: ${currentBatch.length} texts, ${currentBatchSize} chars`
9925
- );
9926
- const batchEmbeddings = await this.embedDocumentsWithRetry(currentBatch);
9927
- rawEmbeddings.push(...batchEmbeddings);
9928
- currentBatch = [];
9929
- currentBatchSize = 0;
10887
+ await processEmbeddingBatch();
9930
10888
  }
9931
10889
  }
9932
10890
  if (currentBatch.length > 0) {
9933
- batchCount++;
9934
- logger.debug(
9935
- `Processing final embedding batch ${batchCount}: ${currentBatch.length} texts, ${currentBatchSize} chars`
9936
- );
9937
- const batchEmbeddings = await this.embedDocumentsWithRetry(currentBatch);
9938
- rawEmbeddings.push(...batchEmbeddings);
10891
+ await processEmbeddingBatch(true);
9939
10892
  }
9940
10893
  paddedEmbeddings = rawEmbeddings.map((vector) => this.padVector(vector));
9941
10894
  }
@@ -9993,6 +10946,9 @@ class DocumentStore {
9993
10946
  });
9994
10947
  transaction();
9995
10948
  } catch (error) {
10949
+ if (error instanceof StoreError) {
10950
+ throw error;
10951
+ }
9996
10952
  throw new ConnectionError("Failed to add documents to store", error);
9997
10953
  }
9998
10954
  }
@@ -10134,6 +11090,14 @@ class DocumentStore {
10134
11090
  }
10135
11091
  const ftsQuery = this.escapeFtsQuery(query);
10136
11092
  const normalizedVersion = version.toLowerCase();
11093
+ const versionRow = this.statements.getVersionId.get(
11094
+ library.toLowerCase(),
11095
+ normalizedVersion
11096
+ );
11097
+ if (!versionRow) {
11098
+ return [];
11099
+ }
11100
+ const { id: versionId } = versionRow;
10137
11101
  if (this.isVectorSearchEnabled) {
10138
11102
  const rawEmbedding = await this.embeddings.embedQuery(query);
10139
11103
  const embedding = this.padVector(rawEmbedding);
@@ -10162,10 +11126,7 @@ class DocumentStore {
10162
11126
  FROM documents_fts f
10163
11127
  JOIN documents d ON f.rowid = d.id
10164
11128
  JOIN pages p ON d.page_id = p.id
10165
- JOIN versions v ON p.version_id = v.id
10166
- JOIN libraries l ON v.library_id = l.id
10167
- WHERE l.name = ?
10168
- AND COALESCE(v.name, '') = COALESCE(?, '')
11129
+ WHERE p.version_id = ?
10169
11130
  AND documents_fts MATCH ?
10170
11131
  ORDER BY fts_score
10171
11132
  LIMIT ?
@@ -10195,8 +11156,7 @@ class DocumentStore {
10195
11156
  normalizedVersion,
10196
11157
  JSON.stringify(embedding),
10197
11158
  vectorSearchK,
10198
- library.toLowerCase(),
10199
- normalizedVersion,
11159
+ versionId,
10200
11160
  ftsQuery,
10201
11161
  overfetchLimit
10202
11162
  );
@@ -10231,10 +11191,7 @@ class DocumentStore {
10231
11191
  FROM documents_fts f
10232
11192
  JOIN documents d ON f.rowid = d.id
10233
11193
  JOIN pages p ON d.page_id = p.id
10234
- JOIN versions v ON p.version_id = v.id
10235
- JOIN libraries l ON v.library_id = l.id
10236
- WHERE l.name = ?
10237
- AND COALESCE(v.name, '') = COALESCE(?, '')
11194
+ WHERE p.version_id = ?
10238
11195
  AND documents_fts MATCH ?
10239
11196
  AND NOT EXISTS (
10240
11197
  SELECT 1 FROM json_each(json_extract(d.metadata, '$.types')) je
@@ -10243,12 +11200,7 @@ class DocumentStore {
10243
11200
  ORDER BY fts_score
10244
11201
  LIMIT ?
10245
11202
  `);
10246
- const rawResults = stmt.all(
10247
- library.toLowerCase(),
10248
- normalizedVersion,
10249
- ftsQuery,
10250
- limit
10251
- );
11203
+ const rawResults = stmt.all(versionId, ftsQuery, limit);
10252
11204
  return rawResults.map((row, index) => {
10253
11205
  const result = {
10254
11206
  ...row,
@@ -10547,16 +11499,20 @@ class DocumentManagementService {
10547
11499
  const libMap = await this.store.queryLibraryVersions();
10548
11500
  const summaries = [];
10549
11501
  for (const [library, versions] of libMap) {
10550
- const vs = versions.map(
10551
- (v) => ({
10552
- id: v.versionId,
10553
- ref: { library, version: v.version },
10554
- status: v.status,
10555
- // Include progress only while indexing is active; set undefined for COMPLETED
10556
- progress: v.status === "completed" ? void 0 : { pages: v.progressPages, maxPages: v.progressMaxPages },
10557
- counts: { documents: v.documentCount, uniqueUrls: v.uniqueUrlCount },
10558
- indexedAt: v.indexedAt,
10559
- sourceUrl: v.sourceUrl ?? void 0
11502
+ const vs = await Promise.all(
11503
+ versions.map(async (v) => {
11504
+ const scraperOptions = await this.store.getScraperOptions(v.versionId);
11505
+ return {
11506
+ id: v.versionId,
11507
+ ref: { library, version: v.version },
11508
+ status: v.status,
11509
+ // Include progress only while indexing is active; set undefined for COMPLETED
11510
+ progress: v.status === "completed" ? void 0 : { pages: v.progressPages, maxPages: v.progressMaxPages },
11511
+ counts: { documents: v.documentCount, uniqueUrls: v.uniqueUrlCount },
11512
+ indexedAt: v.indexedAt,
11513
+ sourceUrl: v.sourceUrl ?? void 0,
11514
+ preserveHashes: scraperOptions?.options.preserveHashes
11515
+ };
10560
11516
  })
10561
11517
  );
10562
11518
  summaries.push({ library, versions: vs });
@@ -11122,7 +12078,10 @@ const enqueueScrapeInput = z.object({
11122
12078
  });
11123
12079
  const enqueueRefreshInput = z.object({
11124
12080
  library: nonEmptyTrimmed,
11125
- version: optionalTrimmed
12081
+ version: optionalTrimmed,
12082
+ options: z.object({
12083
+ preserveHashes: z.boolean().optional()
12084
+ }).optional()
11126
12085
  });
11127
12086
  const jobIdInput = z.object({ id: z.string().min(1) });
11128
12087
  const getJobsInput = z.object({
@@ -11152,7 +12111,8 @@ function createPipelineRouter(trpc) {
11152
12111
  }) => {
11153
12112
  const jobId = await ctx.pipeline.enqueueRefreshJob(
11154
12113
  input.library,
11155
- input.version ?? null
12114
+ input.version ?? null,
12115
+ input.options
11156
12116
  );
11157
12117
  return { jobId };
11158
12118
  }
@@ -11660,7 +12620,7 @@ const Layout = ({
11660
12620
  children,
11661
12621
  eventClientConfig
11662
12622
  }) => {
11663
- const versionString = version || "2.2.1";
12623
+ const versionString = version || "2.3.0";
11664
12624
  const versionInitializer = `versionUpdate({ currentVersion: ${`'${versionString}'`} })`;
11665
12625
  return /* @__PURE__ */ jsxs("html", { lang: "en", children: [
11666
12626
  /* @__PURE__ */ jsxs("head", { children: [
@@ -12449,6 +13409,7 @@ const ScrapeFormContent = ({
12449
13409
  const scrapeModeValue = initialValues?.scrapeMode || ScrapeMode.Auto;
12450
13410
  const followRedirectsValue = initialValues?.followRedirects ?? true;
12451
13411
  const ignoreErrorsValue = initialValues?.ignoreErrors ?? true;
13412
+ const preserveHashesValue = initialValues?.preserveHashes ?? scraperConfig?.preserveHashes ?? false;
12452
13413
  const excludePatternsText = initialValues?.excludePatterns !== void 0 ? initialValues.excludePatterns : defaultExcludePatterns?.join("\n") || "";
12453
13414
  const headersJson = JSON.stringify(initialValues?.headers || []);
12454
13415
  const closeButtonAttrs = isAddVersionMode ? {
@@ -12623,7 +13584,7 @@ const ScrapeFormContent = ({
12623
13584
  "div",
12624
13585
  {
12625
13586
  class: "bg-gray-50 dark:bg-gray-900 p-2 rounded-md",
12626
- "data-should-open": isAddVersionMode && (maxPagesValue || maxDepthValue || scopeValue !== "subpages" || includePatternsValue || excludePatternsText || scrapeModeValue !== ScrapeMode.Auto) ? "true" : "false",
13587
+ "data-should-open": isAddVersionMode && (maxPagesValue || maxDepthValue || scopeValue !== "subpages" || includePatternsValue || excludePatternsText || scrapeModeValue !== ScrapeMode.Auto || preserveHashesValue) ? "true" : "false",
12627
13588
  "x-data": "{ open: false }",
12628
13589
  "x-init": "open = $el.dataset.shouldOpen === 'true'",
12629
13590
  children: [
@@ -12860,7 +13821,28 @@ const ScrapeFormContent = ({
12860
13821
  )
12861
13822
  ]
12862
13823
  }
12863
- )
13824
+ )
13825
+ ] }),
13826
+ /* @__PURE__ */ jsxs("div", { class: "flex items-center", children: [
13827
+ /* @__PURE__ */ jsx(
13828
+ "input",
13829
+ {
13830
+ id: "preserveHashes",
13831
+ name: "preserveHashes",
13832
+ type: "checkbox",
13833
+ checked: preserveHashesValue,
13834
+ 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"
13835
+ }
13836
+ ),
13837
+ /* @__PURE__ */ jsx(
13838
+ "label",
13839
+ {
13840
+ for: "preserveHashes",
13841
+ class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
13842
+ children: "Preserve Hash Routes"
13843
+ }
13844
+ ),
13845
+ /* @__PURE__ */ jsx(Tooltip, { text: "Enable this for documentation sites that use hash fragments as client-side routes rather than same-page anchors." })
12864
13846
  ] }),
12865
13847
  /* @__PURE__ */ jsxs("div", { children: [
12866
13848
  /* @__PURE__ */ jsxs("div", { class: "flex items-center mb-1", children: [
@@ -12987,105 +13969,6 @@ const ScrapeForm = ({
12987
13969
  scraperConfig
12988
13970
  }
12989
13971
  ) });
12990
- const DEFAULT_FILE_EXCLUSIONS = [
12991
- // CHANGELOG files (case variations)
12992
- "**/CHANGELOG.md",
12993
- "**/changelog.md",
12994
- "**/CHANGELOG.mdx",
12995
- "**/changelog.mdx",
12996
- // LICENSE files (case variations)
12997
- "**/LICENSE",
12998
- "**/LICENSE.md",
12999
- "**/license.md",
13000
- // CODE_OF_CONDUCT files (case variations)
13001
- "**/CODE_OF_CONDUCT.md",
13002
- "**/code_of_conduct.md",
13003
- // Test files
13004
- "**/*.test.*",
13005
- "**/*.spec.*",
13006
- "**/*_test.py",
13007
- "**/*_test.go",
13008
- // Package manager lock files
13009
- "**/*.lock",
13010
- "**/package-lock.json",
13011
- "**/yarn.lock",
13012
- "**/pnpm-lock.yaml",
13013
- "**/go.sum",
13014
- // Build artifacts
13015
- "**/*.min.js",
13016
- "**/*.min.css",
13017
- "**/*.map",
13018
- "**/*.d.ts",
13019
- // IDE/System files
13020
- "**/.DS_Store",
13021
- "**/Thumbs.db",
13022
- "**/*.swp",
13023
- "**/*.swo",
13024
- // Internal config files (using regex pattern)
13025
- "/.*\\.(ini|cfg|conf|log|pid)$/"
13026
- ];
13027
- const DEFAULT_FOLDER_EXCLUSIONS = [
13028
- // Archive and deprecated content (matches anywhere in path)
13029
- "**/archive/**",
13030
- "**/archived/**",
13031
- "**/deprecated/**",
13032
- "**/legacy/**",
13033
- "**/old/**",
13034
- "**/outdated/**",
13035
- "**/previous/**",
13036
- "**/superseded/**",
13037
- // Specific paths that don't follow the general pattern
13038
- "docs/old/**",
13039
- // Test directories
13040
- "**/test/**",
13041
- "**/tests/**",
13042
- "**/__tests__/**",
13043
- "**/spec/**",
13044
- // Build output directories
13045
- "**/dist/**",
13046
- "**/build/**",
13047
- "**/out/**",
13048
- "**/target/**",
13049
- "**/.next/**",
13050
- "**/.nuxt/**",
13051
- // IDE directories
13052
- "**/.vscode/**",
13053
- "**/.idea/**",
13054
- // Internationalization folders - non-English locales
13055
- "**/i18n/ar*/**",
13056
- "**/i18n/de*/**",
13057
- "**/i18n/es*/**",
13058
- "**/i18n/fr*/**",
13059
- "**/i18n/hi*/**",
13060
- "**/i18n/it*/**",
13061
- "**/i18n/ja*/**",
13062
- "**/i18n/ko*/**",
13063
- "**/i18n/nl*/**",
13064
- "**/i18n/pl*/**",
13065
- "**/i18n/pt*/**",
13066
- "**/i18n/ru*/**",
13067
- "**/i18n/sv*/**",
13068
- "**/i18n/th*/**",
13069
- "**/i18n/tr*/**",
13070
- "**/i18n/vi*/**",
13071
- "**/i18n/zh*/**",
13072
- // Common locale folder patterns
13073
- "**/zh-cn/**",
13074
- "**/zh-hk/**",
13075
- "**/zh-mo/**",
13076
- "**/zh-sg/**",
13077
- "**/zh-tw/**"
13078
- ];
13079
- const DEFAULT_EXCLUSION_PATTERNS = [
13080
- ...DEFAULT_FILE_EXCLUSIONS,
13081
- ...DEFAULT_FOLDER_EXCLUSIONS
13082
- ];
13083
- function getEffectiveExclusionPatterns(userPatterns) {
13084
- if (userPatterns !== void 0) {
13085
- return userPatterns;
13086
- }
13087
- return DEFAULT_EXCLUSION_PATTERNS;
13088
- }
13089
13972
  function registerNewJobRoutes(server, scrapeTool, scraperConfig) {
13090
13973
  server.get("/web/jobs/new", async () => {
13091
13974
  return /* @__PURE__ */ jsx(
@@ -13146,6 +14029,7 @@ function registerNewJobRoutes(server, scrapeTool, scraperConfig) {
13146
14029
  maxDepth: body.maxDepth ? Number.parseInt(body.maxDepth, 10) : void 0,
13147
14030
  scope: body.scope,
13148
14031
  scrapeMode: body.scrapeMode,
14032
+ preserveHashes: body.preserveHashes === "on",
13149
14033
  // Checkboxes send 'on' when checked, otherwise undefined
13150
14034
  followRedirects: body.followRedirects === "on",
13151
14035
  ignoreErrors: body.ignoreErrors === "on",
@@ -13202,6 +14086,7 @@ const VersionDetailsRow = ({
13202
14086
  const indexedDate = version.indexedAt ? new Date(version.indexedAt).toLocaleDateString() : "N/A";
13203
14087
  const versionLabel = version.ref.version || "Latest";
13204
14088
  const versionParam = version.ref.version || "";
14089
+ const preserveHashes = version.preserveHashes ?? false;
13205
14090
  const sanitizedLibraryName = libraryName.replace(/[^a-zA-Z0-9-_]/g, "-");
13206
14091
  const sanitizedVersionParam = versionParam.replace(/[^a-zA-Z0-9-_]/g, "-");
13207
14092
  const rowId = `row-${sanitizedLibraryName}-${sanitizedVersionParam}`;
@@ -13258,6 +14143,7 @@ const VersionDetailsRow = ({
13258
14143
  "hx-post": `/web/libraries/${encodeURIComponent(libraryName)}/versions/${encodeURIComponent(versionParam)}/refresh`,
13259
14144
  "hx-swap": "none",
13260
14145
  "hx-trigger": "trigger-refresh",
14146
+ "hx-vals": JSON.stringify({ preserveHashes }),
13261
14147
  children: [
13262
14148
  /* @__PURE__ */ jsx(
13263
14149
  "svg",
@@ -13388,7 +14274,8 @@ const LibraryDetailCard = ({ library }) => {
13388
14274
  uniqueUrls: v.uniqueUrlCount
13389
14275
  },
13390
14276
  indexedAt: v.indexedAt,
13391
- sourceUrl: v.sourceUrl ?? void 0
14277
+ sourceUrl: v.sourceUrl ?? void 0,
14278
+ preserveHashes: v.preserveHashes
13392
14279
  };
13393
14280
  return /* @__PURE__ */ jsx(
13394
14281
  VersionDetailsRow,
@@ -13597,7 +14484,8 @@ function registerLibraryDetailRoutes(server, listLibrariesTool, searchTool, scra
13597
14484
  uniqueUrls: v.uniqueUrlCount
13598
14485
  },
13599
14486
  indexedAt: v.indexedAt,
13600
- sourceUrl: v.sourceUrl ?? void 0
14487
+ sourceUrl: v.sourceUrl ?? void 0,
14488
+ preserveHashes: v.preserveHashes
13601
14489
  };
13602
14490
  return /* @__PURE__ */ jsx(
13603
14491
  VersionDetailsRow,
@@ -13670,7 +14558,8 @@ function registerLibraryDetailRoutes(server, listLibrariesTool, searchTool, scra
13670
14558
  value
13671
14559
  })) : void 0,
13672
14560
  followRedirects: opts.followRedirects,
13673
- ignoreErrors: opts.ignoreErrors
14561
+ ignoreErrors: opts.ignoreErrors,
14562
+ preserveHashes: opts.preserveHashes
13674
14563
  };
13675
14564
  }
13676
14565
  }
@@ -13817,10 +14706,12 @@ function registerLibrariesRoutes(server, listLibrariesTool, removeTool, refreshV
13817
14706
  async (request, reply) => {
13818
14707
  const { libraryName, versionParam } = request.params;
13819
14708
  const version = versionParam === "latest" || versionParam === "" ? void 0 : versionParam;
14709
+ const preserveHashes = request.body?.preserveHashes === true || request.body?.preserveHashes === "true" ? true : request.body?.preserveHashes === false || request.body?.preserveHashes === "false" ? false : void 0;
13820
14710
  try {
13821
14711
  await refreshVersionTool.execute({
13822
14712
  library: libraryName,
13823
14713
  version,
14714
+ preserveHashes,
13824
14715
  waitForCompletion: false
13825
14716
  });
13826
14717
  const versionDisplay = version || "latest";
@@ -13976,6 +14867,9 @@ class AppServer {
13976
14867
  // Use our own logger
13977
14868
  });
13978
14869
  }
14870
+ docService;
14871
+ pipeline;
14872
+ eventBus;
13979
14873
  server;
13980
14874
  mcpServer = null;
13981
14875
  authManager = null;
@@ -14012,7 +14906,7 @@ class AppServer {
14012
14906
  try {
14013
14907
  if (telemetry.isEnabled()) {
14014
14908
  telemetry.setGlobalContext({
14015
- appVersion: "2.2.1",
14909
+ appVersion: "2.3.0",
14016
14910
  appPlatform: process.platform,
14017
14911
  appNodeVersion: process.version,
14018
14912
  appServicesEnabled: this.getActiveServicesList(),
@@ -14458,12 +15352,13 @@ class PipelineClient {
14458
15352
  );
14459
15353
  }
14460
15354
  }
14461
- async enqueueRefreshJob(library, version) {
15355
+ async enqueueRefreshJob(library, version, options) {
14462
15356
  try {
14463
15357
  const normalizedVersion = typeof version === "string" && version.trim().length === 0 ? null : version ?? null;
14464
15358
  const result = await this.client.enqueueRefreshJob.mutate({
14465
15359
  library,
14466
- version: normalizedVersion
15360
+ version: normalizedVersion,
15361
+ options
14467
15362
  });
14468
15363
  logger.debug(`Refresh job ${result.jobId} enqueued successfully`);
14469
15364
  return result.jobId;
@@ -14534,83 +15429,53 @@ class PipelineClient {
14534
15429
  logger.debug("PipelineClient.setCallbacks called - no-op for external worker");
14535
15430
  }
14536
15431
  }
14537
- function isRegexPattern(pattern) {
14538
- return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
14539
- }
14540
- function patternToRegExp(pattern) {
14541
- if (isRegexPattern(pattern)) {
14542
- return new RegExp(pattern.slice(1, -1));
14543
- }
14544
- const re = minimatch.makeRe(pattern, { dot: true });
14545
- if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
14546
- return re;
14547
- }
14548
- function matchesAnyPattern(path2, patterns) {
14549
- if (!patterns || patterns.length === 0) return false;
14550
- const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
14551
- return patterns.some((pattern) => {
14552
- if (isRegexPattern(pattern)) {
14553
- return patternToRegExp(pattern).test(normalizedPath);
14554
- }
14555
- const pathForMatch = normalizedPath.replace(/^\//, "");
14556
- const patternForMatch = pattern.startsWith("/") ? pattern.slice(1) : pattern;
14557
- return minimatch(pathForMatch, patternForMatch, { dot: true });
14558
- });
14559
- }
14560
- function extractPathAndQuery(url) {
14561
- try {
14562
- const u = new URL(url);
14563
- return u.pathname + (u.search || "");
14564
- } catch {
14565
- return url;
14566
- }
14567
- }
14568
- function shouldIncludeUrl(url, includePatterns, excludePatterns) {
14569
- const path2 = extractPathAndQuery(url);
14570
- const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
14571
- let basename;
14572
- if (url.startsWith("file://")) {
14573
- try {
14574
- const u = new URL(url);
14575
- basename = u.pathname ? u.pathname.split("/").pop() : void 0;
14576
- } catch {
14577
- }
14578
- }
14579
- const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
14580
- const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
14581
- if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns)))
14582
- return false;
14583
- if (!includePatterns || includePatterns.length === 0) return true;
14584
- return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
14585
- }
15432
+ const INDEX_FILE_PATTERN = /^index(\.[a-z0-9]+)?$/i;
14586
15433
  function computeBaseDirectory(pathname) {
14587
- if (pathname === "") return "/";
15434
+ if (pathname === "" || pathname === "/") return "/";
14588
15435
  if (pathname.endsWith("/")) return pathname;
14589
15436
  const lastSegment = pathname.split("/").at(-1) || "";
14590
- const looksLikeFile = lastSegment.includes(".");
14591
- if (looksLikeFile) {
15437
+ if (INDEX_FILE_PATTERN.test(lastSegment)) {
14592
15438
  return pathname.replace(/\/[^/]*$/, "/");
14593
15439
  }
14594
15440
  return `${pathname}/`;
14595
15441
  }
15442
+ function isPathDescendant(parentPath, childPath) {
15443
+ const normalizedParent = parentPath.endsWith("/") ? parentPath : `${parentPath}/`;
15444
+ if (childPath === normalizedParent) return true;
15445
+ if (`${childPath}/` === normalizedParent) return true;
15446
+ return childPath.startsWith(normalizedParent);
15447
+ }
15448
+ function stripTrailingDot(hostname) {
15449
+ return hostname.endsWith(".") ? hostname.slice(0, -1) : hostname;
15450
+ }
14596
15451
  function isInScope(baseUrl, targetUrl, scope) {
14597
15452
  if (baseUrl.protocol !== targetUrl.protocol) return false;
15453
+ const baseHostNoDot = normalizeHost(baseUrl.host, baseUrl.hostname);
15454
+ const targetHostNoDot = normalizeHost(targetUrl.host, targetUrl.hostname);
14598
15455
  switch (scope) {
14599
15456
  case "subpages": {
14600
- if (baseUrl.hostname !== targetUrl.hostname) return false;
15457
+ if (baseHostNoDot !== targetHostNoDot) return false;
14601
15458
  const baseDir = computeBaseDirectory(baseUrl.pathname);
14602
15459
  return targetUrl.pathname.startsWith(baseDir);
14603
15460
  }
14604
15461
  case "hostname":
14605
- return baseUrl.hostname === targetUrl.hostname;
15462
+ return baseHostNoDot === targetHostNoDot;
14606
15463
  case "domain": {
14607
- return extractPrimaryDomain(baseUrl.hostname) === extractPrimaryDomain(targetUrl.hostname);
15464
+ return extractPrimaryDomain(stripTrailingDot(baseUrl.hostname)) === extractPrimaryDomain(stripTrailingDot(targetUrl.hostname));
14608
15465
  }
14609
15466
  default:
14610
15467
  return false;
14611
15468
  }
14612
15469
  }
15470
+ function normalizeHost(host, hostname) {
15471
+ const stripped = stripTrailingDot(hostname);
15472
+ if (stripped === hostname) return host;
15473
+ return host.replace(hostname, stripped);
15474
+ }
15475
+ class FailureThresholdExceededError extends ScraperError {
15476
+ }
14613
15477
  class BaseScraperStrategy {
15478
+ static FAILURE_RATE_MIN_SAMPLE = 10;
14614
15479
  /**
14615
15480
  * Set of normalized URLs that have been marked for processing.
14616
15481
  *
@@ -14634,41 +15499,113 @@ class BaseScraperStrategy {
14634
15499
  effectiveTotal = 0;
14635
15500
  // Track effective total (limited by maxPages)
14636
15501
  canonicalBaseUrl;
15502
+ // Final URL after initial redirect (depth 0)
15503
+ completedChildPageAttempts = 0;
15504
+ failedChildPages = 0;
14637
15505
  options;
14638
15506
  config;
14639
15507
  constructor(config, options = {}) {
14640
15508
  this.config = config;
14641
15509
  this.options = options;
14642
15510
  }
15511
+ getUrlNormalizerOptions(scrapeOptions) {
15512
+ return {
15513
+ ...this.options.urlNormalizerOptions,
15514
+ removeHash: scrapeOptions.preserveHashes ? false : this.options.urlNormalizerOptions?.removeHash ?? true
15515
+ };
15516
+ }
14643
15517
  /**
14644
15518
  * Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.
14645
15519
  * Scope is checked first, then patterns.
14646
- */
14647
- shouldProcessUrl(url, options) {
14648
- if (options.scope) {
15520
+ *
15521
+ * `internalAllowedFileRoots` opts a queue item out of the protocol-strict
15522
+ * scope check: when a web URL has been accepted as an archive root and the
15523
+ * archive expands into `file://` members, those members are continuations of
15524
+ * the same accepted scrape and should not be rejected because they crossed
15525
+ * from `https:` to `file:`. The bypass is intentionally narrow — the
15526
+ * `file://` target must resolve inside one of the internal roots — so
15527
+ * arbitrary links injected into archive content cannot escape the archive
15528
+ * sandbox via this path. Downstream `resolveFileAccess` enforces the same
15529
+ * rule, but rejecting early here keeps unrelated `file://` URLs out of the
15530
+ * crawl queue entirely.
15531
+ */
15532
+ shouldProcessUrl(url, options, context = {}) {
15533
+ const isInternalArchiveMember = url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots);
15534
+ if (!isInternalArchiveMember) {
15535
+ const scope = options.scope ?? "subpages";
14649
15536
  try {
14650
15537
  const base = this.canonicalBaseUrl ?? new URL$1(options.url);
14651
15538
  const target = new URL$1(url);
14652
- if (!isInScope(base, target, options.scope)) return false;
15539
+ if (!isInScope(base, target, scope)) return false;
14653
15540
  } catch {
14654
15541
  return false;
14655
15542
  }
14656
15543
  }
14657
15544
  return shouldIncludeUrl(url, options.includePatterns, options.excludePatterns);
14658
15545
  }
15546
+ shouldCountTowardFailureThreshold(item, result) {
15547
+ return item.depth > 0 && !this.isRefreshDeletion(item, result);
15548
+ }
15549
+ isRefreshDeletion(item, result) {
15550
+ return item.pageId !== void 0 && result?.status === FetchStatus.NOT_FOUND;
15551
+ }
15552
+ recordChildPageCompletion(item, result) {
15553
+ if (!this.shouldCountTowardFailureThreshold(item, result)) {
15554
+ return;
15555
+ }
15556
+ this.completedChildPageAttempts++;
15557
+ }
15558
+ recordChildPageFailure(item) {
15559
+ if (item.depth === 0) {
15560
+ return;
15561
+ }
15562
+ this.completedChildPageAttempts++;
15563
+ this.failedChildPages++;
15564
+ }
15565
+ ensureFailureRateWithinThreshold() {
15566
+ if (this.completedChildPageAttempts < BaseScraperStrategy.FAILURE_RATE_MIN_SAMPLE || this.completedChildPageAttempts === 0) {
15567
+ return;
15568
+ }
15569
+ const failureRate = this.failedChildPages / this.completedChildPageAttempts;
15570
+ const threshold = this.config.scraper.abortOnFailureRate;
15571
+ if (failureRate > threshold) {
15572
+ throw new FailureThresholdExceededError(
15573
+ `Scrape aborted after ${this.failedChildPages}/${this.completedChildPageAttempts} child pages failed (${failureRate.toFixed(2)} > ${threshold.toFixed(2)})`,
15574
+ false
15575
+ );
15576
+ }
15577
+ }
14659
15578
  async processBatch(batch, baseUrl, options, progressCallback, signal) {
14660
15579
  const maxPages = options.maxPages ?? this.config.scraper.maxPages;
15580
+ let batchAbortError = null;
15581
+ const ensureFailureRateWithinThreshold = () => {
15582
+ try {
15583
+ this.ensureFailureRateWithinThreshold();
15584
+ } catch (error) {
15585
+ if (error instanceof FailureThresholdExceededError) {
15586
+ batchAbortError ??= error;
15587
+ }
15588
+ throw error;
15589
+ }
15590
+ };
15591
+ const throwIfBatchAborted = () => {
15592
+ if (batchAbortError) {
15593
+ throw batchAbortError;
15594
+ }
15595
+ if (signal?.aborted) {
15596
+ throw new CancellationError("Scraping cancelled during batch processing");
15597
+ }
15598
+ };
14661
15599
  const results = await Promise.all(
14662
15600
  batch.map(async (item) => {
14663
- if (signal?.aborted) {
14664
- throw new CancellationError("Scraping cancelled during batch processing");
14665
- }
15601
+ throwIfBatchAborted();
14666
15602
  const maxDepth = options.maxDepth ?? this.config.scraper.maxDepth;
14667
15603
  if (item.depth > maxDepth) {
14668
15604
  return [];
14669
15605
  }
14670
15606
  try {
14671
15607
  const result = await this.processItem(item, options, signal);
15608
+ throwIfBatchAborted();
14672
15609
  const shouldCount = item.pageId !== void 0 || result.content !== void 0;
14673
15610
  let currentPageCount = this.pageCount;
14674
15611
  if (shouldCount) {
@@ -14691,12 +15628,24 @@ class BaseScraperStrategy {
14691
15628
  pageId: item.pageId
14692
15629
  });
14693
15630
  }
15631
+ this.recordChildPageCompletion(item, result);
15632
+ ensureFailureRateWithinThreshold();
15633
+ throwIfBatchAborted();
14694
15634
  return [];
14695
15635
  }
14696
15636
  if (result.status === FetchStatus.NOT_FOUND) {
15637
+ const isRefreshDeletion = this.isRefreshDeletion(item, result);
15638
+ if (item.depth === 0 && !isRefreshDeletion) {
15639
+ throw new ScraperError(`Root page not found: ${item.url}`, false);
15640
+ }
15641
+ if (!isRefreshDeletion) {
15642
+ this.recordChildPageFailure(item);
15643
+ ensureFailureRateWithinThreshold();
15644
+ }
15645
+ throwIfBatchAborted();
14697
15646
  logger.debug(`Page deleted (404): ${item.url}`);
14698
15647
  if (shouldCount) {
14699
- await progressCallback({
15648
+ const progress = {
14700
15649
  pagesScraped: currentPageCount,
14701
15650
  totalPages: this.effectiveTotal,
14702
15651
  totalDiscovered: this.totalDiscovered,
@@ -14704,9 +15653,12 @@ class BaseScraperStrategy {
14704
15653
  depth: item.depth,
14705
15654
  maxDepth,
14706
15655
  result: null,
14707
- pageId: item.pageId,
14708
- deleted: true
14709
- });
15656
+ pageId: item.pageId
15657
+ };
15658
+ if (isRefreshDeletion) {
15659
+ progress.deleted = true;
15660
+ }
15661
+ await progressCallback(progress);
14710
15662
  }
14711
15663
  return [];
14712
15664
  }
@@ -14737,18 +15689,26 @@ class BaseScraperStrategy {
14737
15689
  },
14738
15690
  pageId: item.pageId
14739
15691
  });
15692
+ throwIfBatchAborted();
14740
15693
  }
14741
15694
  const nextItems = result.links || [];
14742
15695
  const linkBaseUrl = finalUrl ? new URL$1(finalUrl) : baseUrl;
15696
+ const internalAllowedFileRoots = result.internalAllowedFileRoots ?? item.internalAllowedFileRoots;
15697
+ this.recordChildPageCompletion(item, result);
15698
+ ensureFailureRateWithinThreshold();
15699
+ throwIfBatchAborted();
14743
15700
  return nextItems.map((value) => {
14744
15701
  try {
14745
15702
  const targetUrl = new URL$1(value, linkBaseUrl);
14746
- if (!this.shouldProcessUrl(targetUrl.href, options)) {
15703
+ if (!this.shouldProcessUrl(targetUrl.href, options, {
15704
+ internalAllowedFileRoots
15705
+ })) {
14747
15706
  return null;
14748
15707
  }
14749
15708
  return {
14750
15709
  url: targetUrl.href,
14751
- depth: item.depth + 1
15710
+ depth: item.depth + 1,
15711
+ ...internalAllowedFileRoots ? { internalAllowedFileRoots } : {}
14752
15712
  };
14753
15713
  } catch (_error) {
14754
15714
  logger.warn(`❌ Invalid URL: ${value}`);
@@ -14756,9 +15716,17 @@ class BaseScraperStrategy {
14756
15716
  return null;
14757
15717
  }).filter((item2) => item2 !== null);
14758
15718
  } catch (error) {
15719
+ if (error instanceof FailureThresholdExceededError || error instanceof CancellationError) {
15720
+ throw error;
15721
+ }
14759
15722
  if (item.depth === 0) {
14760
15723
  throw error;
14761
15724
  }
15725
+ if (batchAbortError) {
15726
+ throw batchAbortError;
15727
+ }
15728
+ this.recordChildPageFailure(item);
15729
+ ensureFailureRateWithinThreshold();
14762
15730
  if (options.ignoreErrors) {
14763
15731
  logger.error(`❌ Failed to process ${item.url}: ${error}`);
14764
15732
  return [];
@@ -14767,10 +15735,10 @@ class BaseScraperStrategy {
14767
15735
  }
14768
15736
  })
14769
15737
  );
14770
- const allLinks = results.flat();
15738
+ const allLinks = results.flat().filter((item) => item !== null);
14771
15739
  const uniqueLinks = [];
14772
15740
  for (const item of allLinks) {
14773
- const normalizedUrl = normalizeUrl(item.url, this.options.urlNormalizerOptions);
15741
+ const normalizedUrl = normalizeUrl(item.url, this.getUrlNormalizerOptions(options));
14774
15742
  if (!this.visited.has(normalizedUrl)) {
14775
15743
  this.visited.add(normalizedUrl);
14776
15744
  uniqueLinks.push(item);
@@ -14785,6 +15753,8 @@ class BaseScraperStrategy {
14785
15753
  async scrape(options, progressCallback, signal) {
14786
15754
  this.visited.clear();
14787
15755
  this.pageCount = 0;
15756
+ this.completedChildPageAttempts = 0;
15757
+ this.failedChildPages = 0;
14788
15758
  const initialQueue = options.initialQueue || [];
14789
15759
  const isRefreshMode = initialQueue.length > 0;
14790
15760
  this.canonicalBaseUrl = new URL$1(options.url);
@@ -14792,14 +15762,17 @@ class BaseScraperStrategy {
14792
15762
  const queue = [];
14793
15763
  const normalizedRootUrl = normalizeUrl(
14794
15764
  options.url,
14795
- this.options.urlNormalizerOptions
15765
+ this.getUrlNormalizerOptions(options)
14796
15766
  );
14797
15767
  if (isRefreshMode) {
14798
15768
  logger.debug(
14799
15769
  `Starting refresh mode with ${initialQueue.length} pre-populated pages`
14800
15770
  );
14801
15771
  for (const item of initialQueue) {
14802
- const normalizedUrl = normalizeUrl(item.url, this.options.urlNormalizerOptions);
15772
+ const normalizedUrl = normalizeUrl(
15773
+ item.url,
15774
+ this.getUrlNormalizerOptions(options)
15775
+ );
14803
15776
  if (!this.visited.has(normalizedUrl)) {
14804
15777
  this.visited.add(normalizedUrl);
14805
15778
  queue.push(item);
@@ -14845,6 +15818,21 @@ class BaseScraperStrategy {
14845
15818
  async cleanup() {
14846
15819
  }
14847
15820
  }
15821
+ function isFileUrlInsideRoots(url, roots) {
15822
+ if (!roots || roots.length === 0) return false;
15823
+ let target;
15824
+ try {
15825
+ target = path.resolve(fileUrlToPathLoose(url));
15826
+ } catch {
15827
+ return false;
15828
+ }
15829
+ return roots.some((root) => {
15830
+ const resolvedRoot = path.resolve(root);
15831
+ if (resolvedRoot === target) return true;
15832
+ const relative = path.relative(resolvedRoot, target);
15833
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
15834
+ });
15835
+ }
14848
15836
  class GitHubRepoProcessor {
14849
15837
  httpFetcher;
14850
15838
  pipelines;
@@ -15815,21 +16803,24 @@ async function getArchiveAdapter(filePath) {
15815
16803
  return null;
15816
16804
  }
15817
16805
  class LocalFileStrategy extends BaseScraperStrategy {
15818
- fileFetcher = new FileFetcher();
16806
+ fileFetcher;
15819
16807
  pipelines;
16808
+ accessPolicy;
15820
16809
  constructor(config) {
15821
16810
  super(config);
16811
+ this.fileFetcher = new FileFetcher(config.scraper);
15822
16812
  this.pipelines = PipelineFactory$1.createStandardPipelines(config);
16813
+ this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);
15823
16814
  }
15824
16815
  canHandle(url) {
15825
16816
  return url.startsWith("file://");
15826
16817
  }
15827
16818
  async processItem(item, options, _signal) {
15828
- let filePath = item.url.replace(/^file:\/\/\/?/, "");
15829
- filePath = decodeURIComponent(filePath);
15830
- if (!filePath.startsWith("/") && process.platform !== "win32") {
15831
- filePath = `/${filePath}`;
15832
- }
16819
+ const resolvedAccess = await this.accessPolicy.resolveFileAccess(
16820
+ item.url,
16821
+ options.internalAllowedFileRoots
16822
+ );
16823
+ const filePath = resolvedAccess.filePath;
15833
16824
  let stats = null;
15834
16825
  let archivePath = null;
15835
16826
  let innerPath = null;
@@ -15859,16 +16850,25 @@ class LocalFileStrategy extends BaseScraperStrategy {
15859
16850
  }
15860
16851
  if (stats?.isDirectory()) {
15861
16852
  const contents = await fs$1.readdir(filePath);
15862
- const links = contents.map((name) => {
15863
- const url = new URL(
15864
- `file://${path.join(filePath, name).replace(/\\/g, "/")}`
15865
- );
15866
- if (url.hostname !== "") {
15867
- url.pathname = `/${url.hostname}${url.pathname}`;
15868
- url.hostname = "";
15869
- }
15870
- return url.href;
15871
- }).filter((url) => {
16853
+ const visibleContents = this.config.scraper.security.fileAccess.includeHidden ? contents : contents.filter((name) => !name.startsWith("."));
16854
+ const linkEntries = await Promise.all(
16855
+ visibleContents.map(async (name) => {
16856
+ const entryPath = path.join(filePath, name);
16857
+ if (!this.config.scraper.security.fileAccess.followSymlinks) {
16858
+ const entryStats = await fs$1.lstat(entryPath).catch(() => null);
16859
+ if (entryStats?.isSymbolicLink()) {
16860
+ return null;
16861
+ }
16862
+ }
16863
+ const url = new URL(`file://${entryPath.replace(/\\/g, "/")}`);
16864
+ if (url.hostname !== "") {
16865
+ url.pathname = `/${url.hostname}${url.pathname}`;
16866
+ url.hostname = "";
16867
+ }
16868
+ return url.href;
16869
+ })
16870
+ );
16871
+ const links = linkEntries.filter((url) => Boolean(url)).filter((url) => {
15872
16872
  const allowed = this.shouldProcessUrl(url, options);
15873
16873
  if (!allowed) {
15874
16874
  logger.debug(`Skipping out-of-scope link: ${url}`);
@@ -15876,7 +16876,7 @@ class LocalFileStrategy extends BaseScraperStrategy {
15876
16876
  return allowed;
15877
16877
  });
15878
16878
  logger.debug(
15879
- `Found ${links.length} files in ${filePath} (from ${contents.length} entries)`
16879
+ `Found ${links.length} files in ${filePath} (from ${visibleContents.length} entries)`
15880
16880
  );
15881
16881
  return { url: item.url, links, status: FetchStatus.SUCCESS };
15882
16882
  }
@@ -15898,7 +16898,7 @@ class LocalFileStrategy extends BaseScraperStrategy {
15898
16898
  virtualUrl.pathname = `/${virtualUrl.hostname}${virtualUrl.pathname}`;
15899
16899
  virtualUrl.hostname = "";
15900
16900
  }
15901
- if (this.shouldProcessUrl(virtualUrl.href, options)) {
16901
+ if (this.shouldProcessUrl(virtualUrl.href, options) && this.isVisibleArchiveEntry(entry.path)) {
15902
16902
  links.push(virtualUrl.href);
15903
16903
  }
15904
16904
  }
@@ -15966,6 +16966,12 @@ class LocalFileStrategy extends BaseScraperStrategy {
15966
16966
  }
15967
16967
  return { archive: null, inner: null, adapter: null };
15968
16968
  }
16969
+ isVisibleArchiveEntry(entryPath) {
16970
+ if (this.config.scraper.security.fileAccess.includeHidden) {
16971
+ return true;
16972
+ }
16973
+ return !entryPath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
16974
+ }
15969
16975
  async processArchiveEntry(item, archivePath, innerPath, adapter, options) {
15970
16976
  logger.debug(`Reading archive entry: ${innerPath} inside ${archivePath}`);
15971
16977
  try {
@@ -16046,6 +17052,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
16046
17052
  pipelines;
16047
17053
  localFileStrategy;
16048
17054
  tempFiles = [];
17055
+ siblingwiseRedirectWarned = false;
16049
17056
  constructor(config, options = {}) {
16050
17057
  super(config, { urlNormalizerOptions: options.urlNormalizerOptions });
16051
17058
  this.shouldFollowLinkFn = options.shouldFollowLink;
@@ -16061,6 +17068,23 @@ class WebScraperStrategy extends BaseScraperStrategy {
16061
17068
  return false;
16062
17069
  }
16063
17070
  }
17071
+ restorePreservedHash(requestedUrl, actualUrl) {
17072
+ if (!requestedUrl.includes("#")) {
17073
+ return actualUrl;
17074
+ }
17075
+ try {
17076
+ const requested = new URL(requestedUrl);
17077
+ const actual = new URL(actualUrl);
17078
+ const normalizePathname = (pathname) => pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;
17079
+ if (requested.origin === actual.origin && normalizePathname(requested.pathname) === normalizePathname(actual.pathname) && requested.search === actual.search) {
17080
+ actual.hash = requested.hash;
17081
+ return actual.toString();
17082
+ }
17083
+ } catch {
17084
+ return actualUrl;
17085
+ }
17086
+ return actualUrl;
17087
+ }
16064
17088
  // Removed custom isInScope logic; using shared scope utility for consistent behavior
16065
17089
  /**
16066
17090
  * Processes a single queue item by fetching its content and processing it through pipelines.
@@ -16087,16 +17111,18 @@ class WebScraperStrategy extends BaseScraperStrategy {
16087
17111
  followRedirects: options.followRedirects,
16088
17112
  headers: options.headers,
16089
17113
  // Forward custom headers
16090
- etag: item.etag
17114
+ etag: item.etag,
16091
17115
  // Pass ETag for conditional requests
17116
+ ...item.internalAllowedFileRoots ? { internalAllowedFileRoots: item.internalAllowedFileRoots } : {}
16092
17117
  };
16093
17118
  const rawContent = await this.fetcher.fetch(url, fetchOptions);
17119
+ const effectiveSource = options.preserveHashes ? this.restorePreservedHash(url, rawContent.source) : rawContent.source;
16094
17120
  logger.debug(
16095
17121
  `Fetch result for ${url}: status=${rawContent.status}, etag=${rawContent.etag || "none"}`
16096
17122
  );
16097
17123
  if (rawContent.status !== FetchStatus.SUCCESS) {
16098
17124
  logger.debug(`Skipping pipeline for ${url} due to status: ${rawContent.status}`);
16099
- return { url: rawContent.source, links: [], status: rawContent.status };
17125
+ return { url: effectiveSource, links: [], status: rawContent.status };
16100
17126
  }
16101
17127
  let processed;
16102
17128
  for (const pipeline of this.pipelines) {
@@ -16105,7 +17131,11 @@ class WebScraperStrategy extends BaseScraperStrategy {
16105
17131
  logger.debug(
16106
17132
  `Selected ${pipeline.constructor.name} for content type "${rawContent.mimeType}" (${url})`
16107
17133
  );
16108
- processed = await pipeline.process(rawContent, options, this.fetcher);
17134
+ processed = await pipeline.process(
17135
+ { ...rawContent, source: effectiveSource },
17136
+ options,
17137
+ this.fetcher
17138
+ );
16109
17139
  break;
16110
17140
  }
16111
17141
  }
@@ -16113,7 +17143,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
16113
17143
  logger.warn(
16114
17144
  `⚠️ Unsupported content type "${rawContent.mimeType}" for URL ${url}. Skipping processing.`
16115
17145
  );
16116
- return { url: rawContent.source, links: [], status: FetchStatus.SUCCESS };
17146
+ return { url: effectiveSource, links: [], status: FetchStatus.SUCCESS };
16117
17147
  }
16118
17148
  for (const err of processed.errors ?? []) {
16119
17149
  logger.warn(`⚠️ Processing error for ${url}: ${err.message}`);
@@ -16123,13 +17153,26 @@ class WebScraperStrategy extends BaseScraperStrategy {
16123
17153
  `⚠️ No processable content found for ${url} after pipeline execution.`
16124
17154
  );
16125
17155
  return {
16126
- url: rawContent.source,
17156
+ url: effectiveSource,
16127
17157
  links: processed.links,
16128
17158
  status: FetchStatus.SUCCESS
16129
17159
  };
16130
17160
  }
16131
17161
  if (item.depth === 0) {
16132
- this.canonicalBaseUrl = new URL(rawContent.source);
17162
+ const final = new URL(effectiveSource);
17163
+ const userPath = new URL(options.url).pathname;
17164
+ if (isPathDescendant(userPath, final.pathname)) {
17165
+ this.canonicalBaseUrl = final;
17166
+ } else {
17167
+ if (!this.siblingwiseRedirectWarned) {
17168
+ logger.warn(
17169
+ `⚠️ 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.`
17170
+ );
17171
+ this.siblingwiseRedirectWarned = true;
17172
+ }
17173
+ final.pathname = userPath;
17174
+ this.canonicalBaseUrl = final;
17175
+ }
16133
17176
  }
16134
17177
  const filteredLinks = processed.links?.filter((link) => {
16135
17178
  try {
@@ -16150,7 +17193,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
16150
17193
  }
16151
17194
  }) ?? [];
16152
17195
  return {
16153
- url: rawContent.source,
17196
+ url: effectiveSource,
16154
17197
  etag: rawContent.etag,
16155
17198
  lastModified: rawContent.lastModified,
16156
17199
  sourceContentType: rawContent.mimeType,
@@ -16183,11 +17226,21 @@ class WebScraperStrategy extends BaseScraperStrategy {
16183
17226
  await fs$1.writeFile(tempFile, buffer);
16184
17227
  const localUrl = `file://${tempFile}`;
16185
17228
  const localItem = { ...item, url: localUrl };
16186
- const result = await this.localFileStrategy.processItem(localItem, options, signal);
17229
+ const localOptions = {
17230
+ ...options,
17231
+ internalAllowedFileRoots: [...options.internalAllowedFileRoots ?? [], tempFile]
17232
+ };
17233
+ const result = await this.localFileStrategy.processItem(
17234
+ localItem,
17235
+ localOptions,
17236
+ signal
17237
+ );
16187
17238
  return {
16188
17239
  ...result,
16189
- url: item.url
17240
+ url: item.url,
16190
17241
  // Keep original URL as the source of this item
17242
+ links: result.links,
17243
+ internalAllowedFileRoots: [tempFile]
16191
17244
  // links are file://...
16192
17245
  };
16193
17246
  }
@@ -16529,6 +17582,20 @@ class PipelineManager {
16529
17582
  scraperOptions: job.scraperOptions
16530
17583
  };
16531
17584
  }
17585
+ normalizeScraperOptions(options) {
17586
+ const normalizedOptions = {
17587
+ ...options,
17588
+ scrapeMode: options.scrapeMode ?? ScrapeMode.Auto,
17589
+ preserveHashes: options.preserveHashes ?? this.appConfig.scraper.preserveHashes
17590
+ };
17591
+ if (normalizedOptions.preserveHashes && normalizedOptions.scrapeMode === ScrapeMode.Fetch) {
17592
+ logger.warn(
17593
+ `⚠️ Upgrading scrape mode to '${ScrapeMode.Playwright}' for ${options.url} because preserved hash routes are incompatible with '${ScrapeMode.Fetch}'.`
17594
+ );
17595
+ normalizedOptions.scrapeMode = ScrapeMode.Playwright;
17596
+ }
17597
+ return normalizedOptions;
17598
+ }
16532
17599
  /**
16533
17600
  * Starts the pipeline manager's worker processing.
16534
17601
  */
@@ -16644,6 +17711,7 @@ class PipelineManager {
16644
17711
  );
16645
17712
  await this.cancelJob(job2.id);
16646
17713
  }
17714
+ const normalizedOptions = this.normalizeScraperOptions(options);
16647
17715
  const jobId = v4();
16648
17716
  const abortController = new AbortController();
16649
17717
  let resolveCompletion;
@@ -16674,8 +17742,8 @@ class PipelineManager {
16674
17742
  progressMaxPages: 0,
16675
17743
  errorMessage: null,
16676
17744
  updatedAt: /* @__PURE__ */ new Date(),
16677
- sourceUrl: options.url,
16678
- scraperOptions: options
17745
+ sourceUrl: normalizedOptions.url,
17746
+ scraperOptions: normalizedOptions
16679
17747
  };
16680
17748
  this.jobMap.set(jobId, job);
16681
17749
  this.jobQueue.push(jobId);
@@ -16697,7 +17765,7 @@ class PipelineManager {
16697
17765
  * If the version was never completed (interrupted or failed scrape), performs a
16698
17766
  * full re-scrape from scratch instead of a refresh to ensure completeness.
16699
17767
  */
16700
- async enqueueRefreshJob(library, version) {
17768
+ async enqueueRefreshJob(library, version, options) {
16701
17769
  const normalizedVersion = version ?? "";
16702
17770
  try {
16703
17771
  const versionId = await this.store.ensureVersion({
@@ -16716,7 +17784,7 @@ class PipelineManager {
16716
17784
  logger.info(
16717
17785
  `⚠️ Version ${library}@${normalizedVersion || "latest"} has status "${versionInfo.status}". Performing full re-scrape instead of refresh.`
16718
17786
  );
16719
- return this.enqueueJobWithStoredOptions(library, normalizedVersion);
17787
+ return this.enqueueJobWithStoredOptions(library, normalizedVersion, options);
16720
17788
  }
16721
17789
  const pages = await this.store.getPagesByVersionId(versionId);
16722
17790
  if (pages.length > 0) {
@@ -16747,6 +17815,7 @@ class PipelineManager {
16747
17815
  version: normalizedVersion,
16748
17816
  ...storedOptions?.options || {},
16749
17817
  // Include stored options if available (spread first)
17818
+ ...options?.preserveHashes !== void 0 ? { preserveHashes: options.preserveHashes } : {},
16750
17819
  // Override with refresh-specific options (these must come after the spread)
16751
17820
  initialQueue,
16752
17821
  // Pre-populated queue with existing pages
@@ -16766,7 +17835,7 @@ class PipelineManager {
16766
17835
  * Enqueues a job using stored scraper options from a previous indexing run.
16767
17836
  * If no stored options are found, throws an error.
16768
17837
  */
16769
- async enqueueJobWithStoredOptions(library, version) {
17838
+ async enqueueJobWithStoredOptions(library, version, options) {
16770
17839
  const normalizedVersion = version ?? "";
16771
17840
  try {
16772
17841
  const versionId = await this.store.ensureVersion({
@@ -16784,7 +17853,8 @@ class PipelineManager {
16784
17853
  url: stored.sourceUrl,
16785
17854
  library,
16786
17855
  version: normalizedVersion,
16787
- ...storedOptions
17856
+ ...storedOptions,
17857
+ ...options?.preserveHashes !== void 0 ? { preserveHashes: options.preserveHashes } : {}
16788
17858
  };
16789
17859
  logger.info(
16790
17860
  `🔄 Re-indexing ${library}@${normalizedVersion || "latest"} with stored options from ${stored.sourceUrl}`
@@ -17591,6 +18661,10 @@ function createRefreshCommand(cli) {
17591
18661
  type: "string",
17592
18662
  description: "Version of the library (optional)",
17593
18663
  alias: "v"
18664
+ }).option("preserve-hashes", {
18665
+ type: "boolean",
18666
+ description: "Override the stored hash-route setting for this refresh job",
18667
+ alias: "preserveHashes"
17594
18668
  }).option("embedding-model", {
17595
18669
  type: "string",
17596
18670
  description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
@@ -17608,6 +18682,7 @@ function createRefreshCommand(cli) {
17608
18682
  command: "refresh",
17609
18683
  library: argv.library,
17610
18684
  version: argv.version,
18685
+ preserveHashes: argv.preserveHashes,
17611
18686
  useServerUrl: !!argv.serverUrl
17612
18687
  });
17613
18688
  const library = argv.library;
@@ -17661,6 +18736,7 @@ function createRefreshCommand(cli) {
17661
18736
  const result = await refreshTool.execute({
17662
18737
  library,
17663
18738
  version,
18739
+ preserveHashes: argv.preserveHashes,
17664
18740
  waitForCompletion: true
17665
18741
  // Always wait for completion in CLI
17666
18742
  });
@@ -17791,6 +18867,10 @@ function createScrapeCommand(cli) {
17791
18867
  description: "HTML processing strategy",
17792
18868
  default: ScrapeMode.Auto,
17793
18869
  alias: "scrapeMode"
18870
+ }).option("preserve-hashes", {
18871
+ type: "boolean",
18872
+ description: "Preserve URL hash fragments for hash-routed SPA documentation sites",
18873
+ alias: "preserveHashes"
17794
18874
  }).option("include-pattern", {
17795
18875
  type: "string",
17796
18876
  array: true,
@@ -17836,6 +18916,7 @@ function createScrapeCommand(cli) {
17836
18916
  const maxPages = argv.maxPages ?? appConfig.scraper.maxPages;
17837
18917
  const maxDepth = argv.maxDepth ?? appConfig.scraper.maxDepth;
17838
18918
  const maxConcurrency = argv.maxConcurrency ?? appConfig.scraper.maxConcurrency;
18919
+ const preserveHashes = typeof argv.preserveHashes === "boolean" ? argv.preserveHashes : appConfig.scraper.preserveHashes;
17839
18920
  appConfig.scraper.maxPages = maxPages;
17840
18921
  appConfig.scraper.maxDepth = maxDepth;
17841
18922
  appConfig.scraper.maxConcurrency = maxConcurrency;
@@ -17849,6 +18930,7 @@ function createScrapeCommand(cli) {
17849
18930
  maxConcurrency,
17850
18931
  scope: argv.scope,
17851
18932
  scrapeMode: argv.scrapeMode,
18933
+ preserveHashes,
17852
18934
  followRedirects: argv.followRedirects,
17853
18935
  hasHeaders: argv.header.length > 0,
17854
18936
  hasIncludePatterns: argv.includePattern.length > 0,
@@ -17909,6 +18991,7 @@ function createScrapeCommand(cli) {
17909
18991
  scope: argv.scope,
17910
18992
  followRedirects: argv.followRedirects,
17911
18993
  scrapeMode: argv.scrapeMode,
18994
+ preserveHashes,
17912
18995
  includePatterns: argv.includePattern?.length > 0 ? argv.includePattern : void 0,
17913
18996
  excludePatterns: argv.excludePattern?.length > 0 ? argv.excludePattern : void 0,
17914
18997
  headers: Object.keys(headers).length > 0 ? headers : void 0,
@@ -18193,7 +19276,7 @@ function createCli(argv) {
18193
19276
  let globalEventBus = null;
18194
19277
  let globalTelemetryService = null;
18195
19278
  const commandStartTimes = /* @__PURE__ */ new Map();
18196
- const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.2.1").option("verbose", {
19279
+ const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.3.0").option("verbose", {
18197
19280
  type: "boolean",
18198
19281
  description: "Enable verbose (debug) logging",
18199
19282
  default: false
@@ -18254,7 +19337,7 @@ function createCli(argv) {
18254
19337
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
18255
19338
  const commandName = argv2._[0]?.toString() || "default";
18256
19339
  telemetry.setGlobalContext({
18257
- appVersion: "2.2.1",
19340
+ appVersion: "2.3.0",
18258
19341
  appPlatform: process.platform,
18259
19342
  appNodeVersion: process.version,
18260
19343
  appInterface: "cli",
@@ -18400,4 +19483,4 @@ export {
18400
19483
  cleanupCliCommand,
18401
19484
  runCli
18402
19485
  };
18403
- //# sourceMappingURL=main-C6In2ps7.js.map
19486
+ //# sourceMappingURL=main-CCLTqj8g.js.map