@arabold/docs-mcp-server 3.4.0 → 3.4.1

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.
@@ -1,15 +1,17 @@
1
+ import { t as normalizeEnvValue } from "./env-DAfCMXx2.js";
1
2
  import { i as setLogLevel, n as getLogLevelFromEnv, r as logger, t as LogLevel } from "./logger-DtB7mX3u.js";
2
- import { $ as normalizeVersionName, A as DimensionError, B as VersionNotFoundInStoreError, C as getProjectRoot, D as splitModelSpec, E as SUPPORTED_PROVIDERS, F as LibraryNotFoundInStoreError, G as VersionStatus, H as quoteName, I as MissingCredentialsError, J as libraryNamesMatch, K as denormalizeVersionName, L as PageNotFoundInStoreError, M as EmbeddingModelChangedError, N as InvalidLibraryNameError, O as AmbiguousPageInStoreError, P as LibraryAlreadyExistsError, Q as normalizeVersionLabel, R as StoreError, S as stripIpv6Brackets, T as EmbeddingConfig, U as EXISTING_TARGET_POLICIES, V as formatVersionLabel, W as UPDATED_AT_RESOLUTION_MS, X as normalizeLibraryDisplayName, Y as msSinceWritten, Z as normalizeLibraryName, _ as parseConfigValue, b as describePublicLocationWarnings, d as validatePort, et as normalizeVersionRef, f as defaults, g as loadConfig, h as isVectorDimensionExplicit, i as getEventBus, j as EmbeddingError, k as ConnectionError, l as resolveProtocol, m as isValidConfigPath, n as createAppServerConfig, o as handleEmbeddingModelChange, p as getConfigValue, q as describeLibraryNameProblem, r as ensurePlaywrightBrowsersInstalled, s as parseHeaders, t as checkAuthForProtocol, u as validateHost, v as setConfigValue, w as resolveStorePath, x as resolvePublicLocation, y as RESERVED_ROOT_SEGMENTS, z as VersionAlreadyExistsError } from "./utils-7a9aMv8E.js";
3
3
  import { n as formatBytes, r as fullTrim, t as escapeHtml } from "./string-n2Z12tl6.js";
4
+ import { createRequire } from "node:module";
4
5
  import { BedrockEmbeddings } from "@langchain/aws";
5
6
  import { GoogleGenerativeAIEmbeddings } from "@langchain/google-genai";
6
7
  import { VertexAIEmbeddings } from "@langchain/google-vertexai";
7
8
  import { AzureOpenAIEmbeddings, OpenAIEmbeddings } from "@langchain/openai";
8
9
  import { Embeddings } from "@langchain/core/embeddings";
9
10
  import crypto, { randomUUID } from "node:crypto";
10
- import fs, { statSync } from "node:fs";
11
+ import fs, { existsSync, statSync } from "node:fs";
11
12
  import path from "node:path";
12
- import { URL as URL$1 } from "node:url";
13
+ import { URL as URL$1, fileURLToPath } from "node:url";
14
+ import envPaths from "env-paths";
13
15
  import { PostHog } from "posthog-node";
14
16
  import yargs from "yargs";
15
17
  import { hideBin } from "yargs/helpers";
@@ -44,7 +46,7 @@ import iconv from "iconv-lite";
44
46
  import Parser from "tree-sitter";
45
47
  import Python from "tree-sitter-python";
46
48
  import TypeScript from "tree-sitter-typescript";
47
- import { exec } from "node:child_process";
49
+ import { exec, execFileSync } from "node:child_process";
48
50
  import { promisify } from "node:util";
49
51
  import { Readable } from "node:stream";
50
52
  import * as tar from "tar";
@@ -56,6 +58,7 @@ import * as sqliteVec from "sqlite-vec";
56
58
  import { createTRPCClient, createWSClient, httpBatchLink, splitLink, wsLink } from "@trpc/client";
57
59
  import superjson from "superjson";
58
60
  import { encode } from "@toon-format/toon";
61
+ import { createInterface } from "node:readline";
59
62
  import fastifyStatic from "@fastify/static";
60
63
  import Fastify from "fastify";
61
64
  import { WebSocketServer } from "ws";
@@ -67,6 +70,747 @@ import { fastifyTRPCPlugin } from "@trpc/server/adapters/fastify";
67
70
  import { applyWSSHandler } from "@trpc/server/adapters/ws";
68
71
  import { observable } from "@trpc/server/observable";
69
72
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
73
+ // src/store/types.ts
74
+ /**
75
+ * Represents the possible states of a version's indexing status.
76
+ * These statuses are stored in the database and persist across server restarts.
77
+ */
78
+ var VersionStatus = /* @__PURE__ */ function(VersionStatus) {
79
+ VersionStatus["NOT_INDEXED"] = "not_indexed";
80
+ VersionStatus["QUEUED"] = "queued";
81
+ VersionStatus["RUNNING"] = "running";
82
+ VersionStatus["COMPLETED"] = "completed";
83
+ VersionStatus["FAILED"] = "failed";
84
+ VersionStatus["CANCELLED"] = "cancelled";
85
+ VersionStatus["UPDATING"] = "updating";
86
+ return VersionStatus;
87
+ }({});
88
+ /**
89
+ * Normalizes a version label for storage and lookup.
90
+ *
91
+ * This is the single write contract for version labels: trim surrounding
92
+ * whitespace, lowercase, and treat an empty result as unversioned. The label is
93
+ * otherwise stored verbatim — it is never validated, coerced or rejected, since
94
+ * a version label is not guaranteed to be a semantic version (`stable` and
95
+ * `1.20` are as legitimate as `1.20.0`).
96
+ *
97
+ * @param version Version label as supplied by a caller, if any.
98
+ * @returns The normalized label, or an empty string for unversioned content.
99
+ */
100
+ function normalizeVersionLabel(version) {
101
+ return (version ?? "").trim().toLowerCase();
102
+ }
103
+ /**
104
+ * Computes a library's lookup key.
105
+ *
106
+ * The counterpart to {@link normalizeVersionLabel}: trim and lowercase (the
107
+ * Unicode default lowercase mapping, without full case folding), so a library
108
+ * is one row however its name was typed. The key is what `libraries.name`
109
+ * stores and every lookup compares; the name as entered lives on as the display
110
+ * name ({@link normalizeLibraryDisplayName}).
111
+ *
112
+ * @param library Library name as supplied by a caller.
113
+ * @returns The lookup key.
114
+ */
115
+ function normalizeLibraryName(library) {
116
+ return library.trim().toLowerCase();
117
+ }
118
+ /**
119
+ * Whether two library names refer to the same library.
120
+ *
121
+ * The one comparison every caller-facing lookup uses, so the identity rule
122
+ * lives in a single place.
123
+ *
124
+ * @param a A library name in any casing or padding.
125
+ * @param b Another library name.
126
+ */
127
+ function libraryNamesMatch(a, b) {
128
+ return normalizeLibraryName(a) === normalizeLibraryName(b);
129
+ }
130
+ /**
131
+ * Computes a library's display name: the name as entered, trimmed only.
132
+ *
133
+ * Case, inner spacing, punctuation and non-ASCII characters are preserved, so
134
+ * `Next.js Docs` is stored and shown exactly that way.
135
+ *
136
+ * @param library Library name as supplied by a caller.
137
+ * @returns The display name to store for a new library.
138
+ */
139
+ function normalizeLibraryDisplayName(library) {
140
+ return library.trim();
141
+ }
142
+ /** Unicode general category Cc: C0 controls, DEL and C1 controls such as tab, newline and ESC. */
143
+ var CONTROL_CHARACTER = /\p{Cc}/u;
144
+ /**
145
+ * Explains why a name is unacceptable for a new library.
146
+ *
147
+ * Only creation is validated; existing libraries stay reachable under their
148
+ * stored names. Format characters (Cf) are allowed because emoji sequences rely
149
+ * on the zero-width joiner. Pure, so the web client can show the same message.
150
+ *
151
+ * @param displayName Name submitted for a new library; trimmed before checking.
152
+ * @returns The broken rule as a short phrase, or `null` when the name is valid.
153
+ */
154
+ function describeLibraryNameProblem(displayName) {
155
+ const name = normalizeLibraryDisplayName(displayName);
156
+ if (name.length === 0) return "is empty";
157
+ if (CONTROL_CHARACTER.test(name)) return "contains a control character";
158
+ if ([...name].length > 100) return `is longer than 100 characters`;
159
+ return null;
160
+ }
161
+ /**
162
+ * What indexing does when its target library or version already exists.
163
+ *
164
+ * - `reject-library`: fail if the library exists at all (the web UI's "Add library").
165
+ * - `reject-version`: fail if that version exists; create the library if needed (the default).
166
+ * - `replace`: rebuild an existing version, or create it (`--replace`, `replace: true`, re-index, retry, refresh).
167
+ */
168
+ var EXISTING_TARGET_POLICIES = [
169
+ "reject-library",
170
+ "reject-version",
171
+ "replace"
172
+ ];
173
+ /** Normalize a VersionRef (lowercase, trim; empty string for unversioned). */
174
+ function normalizeVersionRef(ref) {
175
+ return {
176
+ library: normalizeLibraryName(ref.library),
177
+ version: normalizeVersionLabel(ref.version)
178
+ };
179
+ }
180
+ /**
181
+ * `versions.updated_at` holds whole seconds (SQLite's `CURRENT_TIMESTAMP`), so
182
+ * a write can read up to this much older than it happened.
183
+ */
184
+ var UPDATED_AT_RESOLUTION_MS = 1e3;
185
+ /**
186
+ * How long ago a version was last written, from its `updated_at` (UTC).
187
+ *
188
+ * @param version The version as read from the store.
189
+ * @param now The current time, in milliseconds since the epoch.
190
+ * @returns Milliseconds since the write, or `Infinity` when the version has no
191
+ * readable `updated_at`.
192
+ */
193
+ function msSinceWritten(version, now) {
194
+ const writtenAt = version.updated_at ? Date.parse(`${version.updated_at.replace(" ", "T")}Z`) : NaN;
195
+ return Number.isNaN(writtenAt) ? Number.POSITIVE_INFINITY : now - writtenAt;
196
+ }
197
+ /**
198
+ * Helper function to convert NULL version name to empty string for API compatibility.
199
+ * Database stores NULL for unversioned content, but APIs expect empty string.
200
+ */
201
+ function normalizeVersionName(name) {
202
+ return name ?? "";
203
+ }
204
+ /**
205
+ * Helper function for version name normalization prior to storage.
206
+ * Policy:
207
+ * - Empty string represents the unversioned variant (stored as '').
208
+ * - Names are lower-cased at call sites (see resolveLibraryAndVersionIds) to enforce
209
+ * case-insensitive uniqueness; this function only preserves the empty-string rule.
210
+ */
211
+ function denormalizeVersionName(name) {
212
+ return name === "" ? "" : name;
213
+ }
214
+ // src/store/errors.ts
215
+ /**
216
+ * Base error class for all store-related errors.
217
+ * Provides consistent error handling with optional cause tracking.
218
+ */
219
+ var StoreError = class extends Error {
220
+ cause;
221
+ constructor(message, cause) {
222
+ super(cause ? `${message} caused by ${cause}` : message);
223
+ this.cause = cause;
224
+ this.name = this.constructor.name;
225
+ const causeError = cause instanceof Error ? cause : cause ? new Error(String(cause)) : void 0;
226
+ if (causeError?.stack) this.stack = causeError.stack;
227
+ }
228
+ };
229
+ var CONTROL_CHARACTERS = new RegExp(CONTROL_CHARACTER.source, "gu");
230
+ function escapeControlCharacter(char) {
231
+ const code = char.charCodeAt(0);
232
+ return code < 32 ? JSON.stringify(char).slice(1, -1) : `\\u${code.toString(16).padStart(4, "0")}`;
233
+ }
234
+ /**
235
+ * Escapes every control character (Unicode Cc) in text that an error message
236
+ * repeats, such as a library name or version, so it cannot carry terminal
237
+ * control sequences or forge log lines. Other characters are left as they are.
238
+ */
239
+ function escapeControlCharacters(text) {
240
+ return text.replace(CONTROL_CHARACTERS, escapeControlCharacter);
241
+ }
242
+ /**
243
+ * Labels a library version as `name@version` for logs and messages, with
244
+ * control characters escaped in both and unversioned documentation shown as
245
+ * `latest`.
246
+ */
247
+ function formatVersionLabel(library, version) {
248
+ return `${escapeControlCharacters(library)}@${escapeControlCharacters(version) || "latest"}`;
249
+ }
250
+ /**
251
+ * Quotes a library name (or version) for an error message, with quotes,
252
+ * backslashes and every control character escaped.
253
+ */
254
+ function quoteName(name) {
255
+ return escapeControlCharacters(JSON.stringify(name));
256
+ }
257
+ /**
258
+ * Error thrown when a requested library cannot be found in the store.
259
+ * Includes suggestions for similar library names if available.
260
+ */
261
+ var LibraryNotFoundInStoreError = class extends StoreError {
262
+ library;
263
+ similarLibraries;
264
+ constructor(library, similarLibraries = []) {
265
+ let text = `Library ${escapeControlCharacters(library)} not found in store.`;
266
+ if (similarLibraries.length > 0) text += ` Did you mean: ${similarLibraries.map(escapeControlCharacters).join(", ")}?`;
267
+ super(text);
268
+ this.library = library;
269
+ this.similarLibraries = similarLibraries;
270
+ }
271
+ };
272
+ /**
273
+ * Error thrown when a specific version of a library cannot be found in the store.
274
+ * Includes the list of available versions for better context.
275
+ */
276
+ var VersionNotFoundInStoreError = class extends StoreError {
277
+ library;
278
+ version;
279
+ availableVersions;
280
+ constructor(library, version, availableVersions) {
281
+ let text = `${version ? `Version ${escapeControlCharacters(version)}` : "Version"} for library ${escapeControlCharacters(library)} not found in store.`;
282
+ if (availableVersions.length > 0) text += ` Available versions: ${availableVersions.map(escapeControlCharacters).join(", ")}`;
283
+ super(text);
284
+ this.library = library;
285
+ this.version = version;
286
+ this.availableVersions = availableVersions;
287
+ }
288
+ };
289
+ /**
290
+ * Error thrown when a request to create a new library finds that library already exists.
291
+ * Raised only for an explicit "Add library" request.
292
+ */
293
+ var LibraryAlreadyExistsError = class extends StoreError {
294
+ library;
295
+ constructor(library) {
296
+ super(`Library ${quoteName(library)} already exists. Open it to add a version.`);
297
+ this.library = library;
298
+ }
299
+ };
300
+ /**
301
+ * Error thrown when a scrape would clear an existing version without requesting replacement.
302
+ */
303
+ var VersionAlreadyExistsError = class extends StoreError {
304
+ library;
305
+ version;
306
+ constructor(library, version) {
307
+ const target = version ? `Version ${quoteName(version)} of library ${quoteName(library)}` : `Unversioned documentation for library ${quoteName(library)}`;
308
+ super(`${target} already exists. To rebuild it, scrape again with --replace (CLI) or replace: true (MCP), or refresh it to update in place.`);
309
+ this.library = library;
310
+ this.version = version;
311
+ }
312
+ };
313
+ /**
314
+ * Error thrown when a new library's name breaks a naming rule.
315
+ */
316
+ var InvalidLibraryNameError = class extends StoreError {
317
+ library;
318
+ reason;
319
+ constructor(library, reason) {
320
+ super(`Invalid library name ${quoteName(library)}: ${reason}.`);
321
+ this.library = library;
322
+ this.reason = reason;
323
+ }
324
+ };
325
+ /**
326
+ * Error thrown when a requested page cannot be found in the store for a library/version.
327
+ * Includes suggestions for similar page URLs if available.
328
+ */
329
+ var PageNotFoundInStoreError = class extends StoreError {
330
+ library;
331
+ version;
332
+ pathOrUrl;
333
+ suggestions;
334
+ constructor(library, version, pathOrUrl, suggestions = []) {
335
+ const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
336
+ let text = `Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} not found in store.`;
337
+ if (suggestions.length > 0) text += ` Did you mean: ${suggestions.map(escapeControlCharacters).join(", ")}?`;
338
+ super(text);
339
+ this.library = library;
340
+ this.version = version;
341
+ this.pathOrUrl = pathOrUrl;
342
+ this.suggestions = suggestions;
343
+ }
344
+ };
345
+ /**
346
+ * Error thrown when a page path matches more than one stored page.
347
+ * Lists the matching URLs so the caller can pass the full URL of the intended page.
348
+ */
349
+ var AmbiguousPageInStoreError = class extends StoreError {
350
+ library;
351
+ version;
352
+ pathOrUrl;
353
+ matches;
354
+ constructor(library, version, pathOrUrl, matches) {
355
+ const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
356
+ super(`Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} matches more than one page: ${matches.map(escapeControlCharacters).join(", ")}. Pass the full URL of the page to read.`);
357
+ this.library = library;
358
+ this.version = version;
359
+ this.pathOrUrl = pathOrUrl;
360
+ this.matches = matches;
361
+ }
362
+ };
363
+ /**
364
+ * Error thrown when an embedding model's vector dimension exceeds the database's fixed dimension.
365
+ * This occurs when trying to use a model that produces vectors larger than the database can store.
366
+ */
367
+ var DimensionError = class extends StoreError {
368
+ modelName;
369
+ modelDimension;
370
+ dbDimension;
371
+ constructor(modelName, modelDimension, dbDimension) {
372
+ super(`Model "${modelName}" produces ${modelDimension}-dimensional vectors, which exceeds the database's fixed dimension of ${dbDimension}. Please use a model with dimension ≤ ${dbDimension}.`);
373
+ this.modelName = modelName;
374
+ this.modelDimension = modelDimension;
375
+ this.dbDimension = dbDimension;
376
+ }
377
+ };
378
+ /**
379
+ * Error thrown when there's a problem with database connectivity or operations.
380
+ */
381
+ var ConnectionError = class extends StoreError {};
382
+ /**
383
+ * Error thrown when the embedding provider fails to embed a page's chunks.
384
+ * Nothing of the page is written when this is thrown.
385
+ */
386
+ var EmbeddingError = class extends ConnectionError {};
387
+ /**
388
+ * Names an embedding model with its vector dimension for model-change messages.
389
+ * @param model - The model specification.
390
+ * @param dimension - The vector dimension, or null when it is not known.
391
+ * @returns The model, followed by its dimension when known.
392
+ */
393
+ function describeEmbeddingModel(model, dimension) {
394
+ return dimension === null ? model : `${model} (${dimension} dimensions)`;
395
+ }
396
+ /**
397
+ * Error thrown when the configured embedding model or vector dimension differs from the
398
+ * values stored in the database metadata. This indicates that existing vectors are
399
+ * incompatible with the new configuration and must be invalidated before proceeding.
400
+ *
401
+ * The CLI layer catches this error to accept the change when `--accept-model-change`
402
+ * is set, prompt the user interactively (TTY), or fail startup entirely
403
+ * (non-interactive/MCP/stdio mode). A dimension is null when it is not known.
404
+ */
405
+ var EmbeddingModelChangedError = class extends StoreError {
406
+ previousModel;
407
+ previousDimension;
408
+ currentModel;
409
+ currentDimension;
410
+ constructor(previousModel, previousDimension, currentModel, currentDimension) {
411
+ super(`Embedding model change detected:\n Previous: ${describeEmbeddingModel(previousModel, previousDimension)}\n Current: ${describeEmbeddingModel(currentModel, currentDimension)}\n\nAll existing vectors are incompatible and must be invalidated.\nTo confirm this change, start the server once with --accept-model-change\n(or DOCS_MCP_ACCEPT_MODEL_CHANGE=true), or start it in a terminal and answer the prompt.`);
412
+ this.previousModel = previousModel;
413
+ this.previousDimension = previousDimension;
414
+ this.currentModel = currentModel;
415
+ this.currentDimension = currentDimension;
416
+ }
417
+ };
418
+ /**
419
+ * Error thrown when required credentials for an embedding provider are missing.
420
+ * This allows the system to gracefully degrade to FTS-only search when vectorization is unavailable.
421
+ */
422
+ var MissingCredentialsError = class extends StoreError {
423
+ provider;
424
+ constructor(provider, missingCredentials) {
425
+ super(`Missing credentials for ${provider} embedding provider. Required: ${missingCredentials.join(", ")}`);
426
+ this.provider = provider;
427
+ }
428
+ };
429
+ // src/store/embeddings/EmbeddingConfig.ts
430
+ /**
431
+ * Shared embedding model configuration service.
432
+ * Provides synchronous parsing of embedding model configuration and known dimensions lookup.
433
+ * Eliminates code duplication between DocumentStore and telemetry systems.
434
+ *
435
+ * All model lookups are case-insensitive to handle variations in model name capitalization.
436
+ * Uses class-based approach to avoid mutable global state and improve testability.
437
+ */
438
+ /**
439
+ * The complete set of provider prefixes recognized in a model specification.
440
+ * Anything else before the first colon is part of the model name itself.
441
+ *
442
+ * This list is normative rather than descriptive: it decides which prefixes claim
443
+ * the provider slot, so adding an entry changes how existing specifications parse.
444
+ * A model literally named `<new-provider>:<tag>` served by an OpenAI-compatible
445
+ * endpoint would start resolving to the new provider, breaking that configuration
446
+ * on upgrade. Call provider additions out in the release notes.
447
+ *
448
+ * `EmbeddingProvider` is derived from this array so the two cannot drift apart.
449
+ */
450
+ var SUPPORTED_PROVIDERS = [
451
+ "openai",
452
+ "vertex",
453
+ "gemini",
454
+ "aws",
455
+ "microsoft"
456
+ ];
457
+ /**
458
+ * Split a model specification into its provider prefix and model name.
459
+ *
460
+ * Only a prefix that names a supported provider is treated as a provider, matched
461
+ * case-insensitively and resolved to its canonical lowercase form. Every other
462
+ * specification is an OpenAI-compatible model name, which keeps names that carry a
463
+ * tag or quantization suffix intact (e.g. "nomic-embed-text:latest" or
464
+ * "second-state/jina-embeddings-v3-GGUF:Q4_K_M").
465
+ *
466
+ * @param spec The full model specification.
467
+ * @returns The resolved provider and model name.
468
+ */
469
+ function splitModelSpec(spec) {
470
+ const colonIndex = spec.indexOf(":");
471
+ const prefix = spec.substring(0, colonIndex).toLowerCase();
472
+ const provider = colonIndex === -1 ? void 0 : SUPPORTED_PROVIDERS.find((name) => name === prefix);
473
+ return provider ? {
474
+ provider,
475
+ model: spec.substring(colonIndex + 1)
476
+ } : {
477
+ provider: "openai",
478
+ model: spec
479
+ };
480
+ }
481
+ /**
482
+ * Embedding configuration manager that handles model parsing and dimension caching.
483
+ * Encapsulates state to avoid global variable issues and improve testability.
484
+ */
485
+ var EmbeddingConfig = class EmbeddingConfig {
486
+ static instance = null;
487
+ /**
488
+ * Get the singleton instance of EmbeddingConfig.
489
+ * Creates the instance if it doesn't exist.
490
+ */
491
+ static getInstance() {
492
+ if (EmbeddingConfig.instance === null) EmbeddingConfig.instance = new EmbeddingConfig();
493
+ return EmbeddingConfig.instance;
494
+ }
495
+ /**
496
+ * Reset the singleton instance (useful for testing).
497
+ */
498
+ static resetInstance() {
499
+ EmbeddingConfig.instance = null;
500
+ }
501
+ /**
502
+ * Known dimensions for common embedding models.
503
+ * This avoids expensive API calls for dimension detection in telemetry.
504
+ *
505
+ * Note: The "openai" provider also supports OpenAI-compatible APIs like:
506
+ * - Ollama (local models)
507
+ * - LMStudio (local models)
508
+ * - Any service implementing OpenAI's embedding API
509
+ */
510
+ knownModelDimensions = {
511
+ "text-embedding-3-small": 1536,
512
+ "text-embedding-3-large": 3072,
513
+ "text-embedding-ada-002": 1536,
514
+ "text-embedding-004": 768,
515
+ "text-embedding-005": 768,
516
+ "textembedding-gecko@003": 768,
517
+ "textembedding-gecko@002": 768,
518
+ "textembedding-gecko@001": 768,
519
+ "text-embedding-preview-0409": 768,
520
+ "embedding-001": 768,
521
+ "gemini-embedding-2-preview": 3072,
522
+ "amazon.titan-embed-text-v1": 1536,
523
+ "amazon.titan-embed-text-v2:0": 1024,
524
+ "amazon.titan-embed-image-v1": 1024,
525
+ "cohere.embed-english-v3": 1024,
526
+ "cohere.embed-multilingual-v3": 1024,
527
+ "Cohere/Cohere-embed-v4.0": 1536,
528
+ "embed-v4.0": 1536,
529
+ "intfloat/multilingual-e5-large": 1024,
530
+ "multilingual-e5-large": 1024,
531
+ "text-embedding-multilingual-e5-large": 1024,
532
+ "sentence-transformers/all-MiniLM-L6-v2": 384,
533
+ "gemini-embedding-001": 3072,
534
+ "Qwen/Qwen3-Embedding-8B": 4096,
535
+ "Qwen/Qwen3-Embedding-4B": 2560,
536
+ "Qwen/Qwen3-Embedding-0.6B": 1024,
537
+ "Linq-AI-Research/Linq-Embed-Mistral": 4096,
538
+ "Alibaba-NLP/gte-Qwen2-7B-instruct": 3584,
539
+ "intfloat/multilingual-e5-large-instruct": 1024,
540
+ "Salesforce/SFR-Embedding-Mistral": 4096,
541
+ "text-multilingual-embedding-002": 768,
542
+ "GritLM/GritLM-7B": 4096,
543
+ "GritLM/GritLM-8x7B": 4096,
544
+ "intfloat/e5-mistral-7b-instruct": 4096,
545
+ "Cohere/Cohere-embed-multilingual-v3.0": 1024,
546
+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct": 8960,
547
+ "Lajavaness/bilingual-embedding-large": 1024,
548
+ "Salesforce/SFR-Embedding-2_R": 4096,
549
+ "NovaSearch/stella_en_1.5B_v5": 8960,
550
+ "NovaSearch/jasper_en_vision_language_v1": 8960,
551
+ "nvidia/NV-Embed-v2": 4096,
552
+ "OrdalieTech/Solon-embeddings-large-0.1": 1024,
553
+ "BAAI/bge-m3": 1024,
554
+ "HIT-TMG/KaLM-embedding-multilingual-mini-v1": 896,
555
+ "jinaai/jina-embeddings-v3": 1024,
556
+ "Alibaba-NLP/gte-multilingual-base": 768,
557
+ "Lajavaness/bilingual-embedding-base": 768,
558
+ "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1": 896,
559
+ "nvidia/NV-Embed-v1": 4096,
560
+ "Cohere/Cohere-embed-multilingual-light-v3.0": 384,
561
+ "manu/bge-m3-custom-fr": 1024,
562
+ "Lajavaness/bilingual-embedding-small": 384,
563
+ "Snowflake/snowflake-arctic-embed-l-v2.0": 1024,
564
+ "intfloat/multilingual-e5-base": 768,
565
+ "voyage-3-lite": 512,
566
+ "voyage-3": 1024,
567
+ "voyage-3-large": 1024,
568
+ "voyage-3.5": 1024,
569
+ "voyage-4": 1024,
570
+ "voyage-4-large": 1024,
571
+ "voyage-4-lite": 1024,
572
+ "voyage-code-3": 1024,
573
+ "intfloat/multilingual-e5-small": 384,
574
+ "Alibaba-NLP/gte-Qwen1.5-7B-instruct": 4096,
575
+ "Snowflake/snowflake-arctic-embed-m-v2.0": 768,
576
+ "deepvk/USER-bge-m3": 1024,
577
+ "Cohere/Cohere-embed-english-v3.0": 1024,
578
+ "Omartificial-Intelligence-Space/Arabic-labse-Matryoshka": 768,
579
+ "ibm-granite/granite-embedding-278m-multilingual": 768,
580
+ "NovaSearch/stella_en_400M_v5": 4096,
581
+ "omarelshehy/arabic-english-sts-matryoshka": 1024,
582
+ "sentence-transformers/paraphrase-multilingual-mpnet-base-v2": 768,
583
+ "Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka": 768,
584
+ "Haon-Chen/speed-embedding-7b-instruct": 4096,
585
+ "sentence-transformers/LaBSE": 768,
586
+ "WhereIsAI/UAE-Large-V1": 1024,
587
+ "ibm-granite/granite-embedding-107m-multilingual": 384,
588
+ "mixedbread-ai/mxbai-embed-large-v1": 1024,
589
+ "intfloat/e5-large-v2": 1024,
590
+ "avsolatorio/GIST-large-Embedding-v0": 1024,
591
+ "sdadas/mmlw-e5-large": 1024,
592
+ "nomic-ai/nomic-embed-text-v1": 768,
593
+ "nomic-embed-text-v1": 768,
594
+ "nomic-ai/nomic-embed-text-v1-ablated": 768,
595
+ "nomic-ai/nomic-embed-text-v2-moe": 768,
596
+ "nomic-ai/modernbert-embed-base": 768,
597
+ "nomic-ai/nomic-embed-code": 3584,
598
+ "intfloat/e5-base-v2": 768,
599
+ "BAAI/bge-large-en-v1.5": 1024,
600
+ "intfloat/e5-large": 1024,
601
+ "Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet": 384,
602
+ "Cohere/Cohere-embed-english-light-v3.0": 384,
603
+ "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2": 768,
604
+ "Gameselo/STS-multilingual-mpnet-base-v2": 768,
605
+ "thenlper/gte-large": 1024,
606
+ "avsolatorio/GIST-Embedding-v0": 768,
607
+ "nomic-ai/nomic-embed-text-v1-unsupervised": 768,
608
+ "infgrad/stella-base-en-v2": 768,
609
+ "avsolatorio/NoInstruct-small-Embedding-v0": 384,
610
+ "dwzhu/e5-base-4k": 768,
611
+ "sdadas/mmlw-e5-base": 768,
612
+ "voyage-multilingual-2": 1024,
613
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised": 4096,
614
+ "BAAI/bge-base-en-v1.5": 768,
615
+ "avsolatorio/GIST-small-Embedding-v0": 384,
616
+ "sdadas/mmlw-roberta-large": 1024,
617
+ "nomic-ai/nomic-embed-text-v1.5": 768,
618
+ "nomic-embed-text-v1.5": 768,
619
+ "text-embedding-nomic-embed-text-v1.5": 768,
620
+ "minishlab/potion-multilingual-128M": 256,
621
+ "shibing624/text2vec-base-multilingual": 384,
622
+ "thenlper/gte-base": 768,
623
+ "intfloat/e5-small-v2": 384,
624
+ "intfloat/e5-base": 768,
625
+ "sentence-transformers/static-similarity-mrl-multilingual-v1": 1024,
626
+ "manu/sentence_croissant_alpha_v0.3": 2048,
627
+ "BAAI/bge-small-en-v1.5": 512,
628
+ "thenlper/gte-small": 384,
629
+ "sdadas/mmlw-e5-small": 384,
630
+ "manu/sentence_croissant_alpha_v0.4": 2048,
631
+ "manu/sentence_croissant_alpha_v0.2": 2048,
632
+ "abhinand/MedEmbed-small-v0.1": 384,
633
+ "ibm-granite/granite-embedding-125m-english": 768,
634
+ "intfloat/e5-small": 384,
635
+ "voyage-large-2-instruct": 1024,
636
+ "sdadas/mmlw-roberta-base": 768,
637
+ "Snowflake/snowflake-arctic-embed-l": 1024,
638
+ "Mihaiii/Ivysaur": 384,
639
+ "Snowflake/snowflake-arctic-embed-m-long": 768,
640
+ "bigscience/sgpt-bloom-7b1-msmarco": 4096,
641
+ "avsolatorio/GIST-all-MiniLM-L6-v2": 384,
642
+ "sergeyzh/LaBSE-ru-turbo": 768,
643
+ "sentence-transformers/all-mpnet-base-v2": 768,
644
+ "Snowflake/snowflake-arctic-embed-m": 768,
645
+ "Snowflake/snowflake-arctic-embed-s": 384,
646
+ "sentence-transformers/all-MiniLM-L12-v2": 384,
647
+ "Mihaiii/gte-micro-v4": 384,
648
+ "Snowflake/snowflake-arctic-embed-m-v1.5": 768,
649
+ "cointegrated/LaBSE-en-ru": 768,
650
+ "Mihaiii/Bulbasaur": 384,
651
+ "ibm-granite/granite-embedding-30m-english": 384,
652
+ "deepfile/embedder-100p": 768,
653
+ "Jaume/gemma-2b-embeddings": 2048,
654
+ "OrlikB/KartonBERT-USE-base-v1": 768,
655
+ "izhx/udever-bloom-7b1": 4096,
656
+ "izhx/udever-bloom-1b1": 1024,
657
+ "brahmairesearch/slx-v0.1": 384,
658
+ "Mihaiii/Wartortle": 384,
659
+ "izhx/udever-bloom-3b": 2048,
660
+ "deepvk/USER-base": 768,
661
+ "ai-forever/ru-en-RoSBERTa": 1024,
662
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse": 4096,
663
+ "Mihaiii/Venusaur": 384,
664
+ "Snowflake/snowflake-arctic-embed-xs": 384,
665
+ "jinaai/jina-embedding-b-en-v1": 768,
666
+ "Mihaiii/gte-micro": 384,
667
+ "aari1995/German_Semantic_STS_V2": 1024,
668
+ "Mihaiii/Squirtle": 384,
669
+ "OrlikB/st-polish-kartonberta-base-alpha-v1": 768,
670
+ "sergeyzh/rubert-tiny-turbo": 312,
671
+ "minishlab/potion-base-8M": 256,
672
+ "minishlab/M2V_base_glove_subword": 256,
673
+ "jinaai/jina-embedding-s-en-v1": 512,
674
+ "minishlab/potion-base-4M": 128,
675
+ "minishlab/M2V_base_output": 256,
676
+ "DeepPavlov/rubert-base-cased-sentence": 768,
677
+ "jinaai/jina-embeddings-v2-small-en": 512,
678
+ "cointegrated/rubert-tiny2": 312,
679
+ "minishlab/M2V_base_glove": 256,
680
+ "cointegrated/rubert-tiny": 312,
681
+ "silma-ai/silma-embeddding-matryoshka-v0.1": 768,
682
+ "DeepPavlov/rubert-base-cased": 768,
683
+ "Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet": 768,
684
+ "izhx/udever-bloom-560m": 1024,
685
+ "minishlab/potion-base-2M": 64,
686
+ "DeepPavlov/distilrubert-small-cased-conversational": 768,
687
+ "consciousAI/cai-lunaris-text-embeddings": 1024,
688
+ "deepvk/deberta-v1-base": 768,
689
+ "Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka": 768,
690
+ "Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka": 768,
691
+ "ai-forever/sbert_large_mt_nlu_ru": 1024,
692
+ "ai-forever/sbert_large_nlu_ru": 1024,
693
+ "malenia1/ternary-weight-embedding": 1024,
694
+ "jinaai/jina-embeddings-v2-base-en": 768,
695
+ "VPLabs/SearchMap_Preview": 4096,
696
+ "Hum-Works/lodestone-base-4096-v1": 768,
697
+ "jinaai/jina-embeddings-v4": 2048
698
+ };
699
+ runtimeDetectedDimensionModels = /* @__PURE__ */ new Set([
700
+ "novasearch/stella_en_1.5b_v5",
701
+ "stella_en_1.5b_v5",
702
+ "novasearch/stella_en_400m_v5",
703
+ "dunzhang/stella_en_400m_v5",
704
+ "stella_en_400m_v5",
705
+ "novasearch/jasper_en_vision_language_v1",
706
+ "jasper_en_vision_language_v1"
707
+ ]);
708
+ /**
709
+ * Lowercase lookup map for case-insensitive model dimension queries.
710
+ * Built lazily from knownModelDimensions to ensure consistency.
711
+ */
712
+ modelLookup;
713
+ constructor() {
714
+ this.modelLookup = /* @__PURE__ */ new Map();
715
+ for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) this.modelLookup.set(model.toLowerCase(), dimensions);
716
+ }
717
+ /**
718
+ * Build the lookup keys to try for a model name, most specific first:
719
+ * the name itself, then with the namespace dropped, the tag dropped, and both.
720
+ *
721
+ * Dropping a trailing tag lets a quantized or tagged variant reuse the base
722
+ * model's dimensions (e.g. "nomic-ai/nomic-embed-text-v2-moe:latest"), which
723
+ * quantization does not change. Exact matches are tried first, so names whose
724
+ * own identifier contains a colon (e.g. "amazon.titan-embed-text-v2:0") still
725
+ * resolve to their own entry.
726
+ */
727
+ dimensionLookupKeys(normalized) {
728
+ const slashIndex = normalized.lastIndexOf("/");
729
+ const withoutNamespace = slashIndex > -1 ? normalized.substring(slashIndex + 1) : void 0;
730
+ const bases = withoutNamespace ? [normalized, withoutNamespace] : [normalized];
731
+ const withoutTag = (key) => {
732
+ const colonIndex = key.lastIndexOf(":");
733
+ return colonIndex > 0 ? [key.substring(0, colonIndex)] : [];
734
+ };
735
+ return [...bases, ...bases.flatMap(withoutTag)];
736
+ }
737
+ findKnownDimension(model) {
738
+ for (const key of this.dimensionLookupKeys(model.toLowerCase())) {
739
+ if (this.runtimeDetectedDimensionModels.has(key)) return null;
740
+ const dimensions = this.modelLookup?.get(key);
741
+ if (dimensions !== void 0) return dimensions;
742
+ }
743
+ return null;
744
+ }
745
+ /**
746
+ * Parse embedding model configuration from a provided model specification.
747
+ * This is a synchronous operation that extracts provider, model, and known dimensions.
748
+ *
749
+ * Supports various providers:
750
+ * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)
751
+ * - vertex: Google Cloud Vertex AI
752
+ * - gemini: Google Generative AI
753
+ * - aws: AWS Bedrock models
754
+ * - microsoft: Azure OpenAI
755
+ *
756
+ * @param modelSpec Model specification (e.g., "openai:text-embedding-3-small"), defaults to "text-embedding-3-small"
757
+ * @returns Parsed embedding model configuration
758
+ */
759
+ parse(modelSpec) {
760
+ const spec = normalizeEnvValue(modelSpec || "text-embedding-3-small");
761
+ const { provider, model } = splitModelSpec(spec);
762
+ return {
763
+ provider,
764
+ model,
765
+ dimensions: this.findKnownDimension(model),
766
+ modelSpec: spec
767
+ };
768
+ }
769
+ /**
770
+ * Get the known dimensions for a specific model.
771
+ * Returns null if the model dimensions are not known.
772
+ * Uses case-insensitive lookup.
773
+ *
774
+ * @param model The model name (e.g., "text-embedding-3-small")
775
+ * @returns Known dimensions or null
776
+ */
777
+ getKnownDimensions(model) {
778
+ return this.findKnownDimension(model);
779
+ }
780
+ /**
781
+ * Add or update known dimensions for a model.
782
+ * This can be used to cache discovered dimensions.
783
+ * Stores both original case and lowercase for consistent lookup.
784
+ *
785
+ * @param model The model name
786
+ * @param dimensions The dimensions to cache
787
+ */
788
+ setKnownDimensions(model, dimensions) {
789
+ this.knownModelDimensions[model] = dimensions;
790
+ if (this.modelLookup) this.modelLookup.set(model.toLowerCase(), dimensions);
791
+ }
792
+ /**
793
+ * Static method to parse embedding model configuration using the singleton instance.
794
+ * This maintains backward compatibility while using the class-based approach.
795
+ */
796
+ static parseEmbeddingConfig(modelSpec) {
797
+ return EmbeddingConfig.getInstance().parse(modelSpec);
798
+ }
799
+ /**
800
+ * Static method to get known model dimensions using the singleton instance.
801
+ * This maintains backward compatibility while using the class-based approach.
802
+ */
803
+ static getKnownModelDimensions(model) {
804
+ return EmbeddingConfig.getInstance().getKnownDimensions(model);
805
+ }
806
+ /**
807
+ * Static method to set known model dimensions using the singleton instance.
808
+ * This maintains backward compatibility while using the class-based approach.
809
+ */
810
+ static setKnownModelDimensions(model, dimensions) {
811
+ EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);
812
+ }
813
+ };
70
814
  // src/store/embeddings/FixedDimensionEmbeddings.ts
71
815
  /**
72
816
  * Wrapper around an Embeddings implementation that ensures vectors have a fixed dimension.
@@ -349,6 +1093,56 @@ function sanitizeErrorForTracking(error) {
349
1093
  sanitized.stack = [`${error.name}: ${message}`, ...frames].join("\n");
350
1094
  return sanitized;
351
1095
  }
1096
+ // src/utils/paths.ts
1097
+ var projectRoot = null;
1098
+ /**
1099
+ * Finds the project root directory by searching upwards from the current file
1100
+ * for a directory containing 'package.json'. Caches the result.
1101
+ *
1102
+ * @returns {string} The absolute path to the project root.
1103
+ * @throws {Error} If package.json cannot be found.
1104
+ */
1105
+ function getProjectRoot() {
1106
+ if (projectRoot) return projectRoot;
1107
+ const currentFilePath = fileURLToPath(import.meta.url);
1108
+ let currentDir = path.dirname(currentFilePath);
1109
+ while (true) {
1110
+ const packageJsonPath = path.join(currentDir, "package.json");
1111
+ if (fs.existsSync(packageJsonPath)) {
1112
+ projectRoot = currentDir;
1113
+ return currentDir;
1114
+ }
1115
+ const parentDir = path.dirname(currentDir);
1116
+ if (parentDir === currentDir) throw new Error("Could not find project root containing package.json.");
1117
+ currentDir = parentDir;
1118
+ }
1119
+ }
1120
+ /**
1121
+ * Resolves the data storage path using the following priority:
1122
+ * 1. Provided storePath parameter
1123
+ * 2. Legacy .store directory in project root (if exists)
1124
+ * 3. Standard system data directory using env-paths
1125
+ *
1126
+ * @param storePath Optional custom storage path
1127
+ * @returns Resolved absolute path for data storage
1128
+ */
1129
+ function resolveStorePath(storePath) {
1130
+ let dbDir;
1131
+ if (storePath) dbDir = path.resolve(storePath);
1132
+ else {
1133
+ const projectRoot = getProjectRoot();
1134
+ const oldDbDir = path.join(projectRoot, ".store");
1135
+ const oldDbPath = path.join(oldDbDir, "documents.db");
1136
+ if (fs.existsSync(oldDbPath)) dbDir = oldDbDir;
1137
+ else dbDir = envPaths("docs-mcp-server", { suffix: "" }).data;
1138
+ }
1139
+ try {
1140
+ fs.mkdirSync(dbDir, { recursive: true });
1141
+ } catch (error) {
1142
+ logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);
1143
+ }
1144
+ return dbDir;
1145
+ }
352
1146
  // src/telemetry/TelemetryConfig.ts
353
1147
  /**
354
1148
  * Telemetry configuration management for enabling/disabling analytics collection.
@@ -744,48 +1538,881 @@ var TelemetryService = class {
744
1538
  };
745
1539
  // src/events/EventBusService.ts
746
1540
  /**
747
- * Central event bus service for application-wide event distribution.
748
- *
749
- * This service provides a pub/sub mechanism that can be used by any service
750
- * to emit and listen for events. Events emitted here can be:
751
- * - Consumed locally by in-process subscribers
752
- * - Broadcast to remote processes via tRPC subscriptions
753
- * - Forwarded to SSE clients via the web service
754
- *
755
- * This decouples event producers (like DocumentManagementService) from
756
- * consumers (like the Web UI), enabling a clean, scalable architecture.
1541
+ * Central event bus service for application-wide event distribution.
1542
+ *
1543
+ * This service provides a pub/sub mechanism that can be used by any service
1544
+ * to emit and listen for events. Events emitted here can be:
1545
+ * - Consumed locally by in-process subscribers
1546
+ * - Broadcast to remote processes via tRPC subscriptions
1547
+ * - Forwarded to SSE clients via the web service
1548
+ *
1549
+ * This decouples event producers (like DocumentManagementService) from
1550
+ * consumers (like the Web UI), enabling a clean, scalable architecture.
1551
+ */
1552
+ /**
1553
+ * Central event bus for application-wide events.
1554
+ */
1555
+ var EventBusService = class {
1556
+ emitter;
1557
+ constructor() {
1558
+ this.emitter = new EventEmitter();
1559
+ this.emitter.setMaxListeners(100);
1560
+ }
1561
+ /**
1562
+ * Emit an event to all subscribers.
1563
+ */
1564
+ emit(eventType, payload) {
1565
+ logger.debug(`Event emitted: ${eventType}`);
1566
+ this.emitter.emit(eventType, payload);
1567
+ }
1568
+ /**
1569
+ * Subscribe to events of a specific type.
1570
+ * Returns an unsubscribe function.
1571
+ */
1572
+ on(eventType, listener) {
1573
+ this.emitter.on(eventType, listener);
1574
+ return () => this.emitter.off(eventType, listener);
1575
+ }
1576
+ /**
1577
+ * Remove a specific listener.
1578
+ */
1579
+ off(eventType, listener) {
1580
+ this.emitter.off(eventType, listener);
1581
+ }
1582
+ };
1583
+ // src/utils/serverOrigin.ts
1584
+ /**
1585
+ * Normalize a configured origin (`scheme://host[:port]`) into its canonical form.
1586
+ *
1587
+ * Empty strings are treated as absent so container environments can leave the
1588
+ * variable declared but unset.
1589
+ *
1590
+ * @param origin - The configured value.
1591
+ * @param settingName - The setting named in error messages.
1592
+ * @returns The canonical origin, or `undefined` when absent.
1593
+ * @throws Error naming the setting when the value is not an HTTP(S) origin.
1594
+ */
1595
+ function normalizePublicOrigin(origin, settingName = "server.publicOrigin") {
1596
+ const configured = parseConfiguredUrl(origin, settingName, "origin without path, query, or fragment");
1597
+ if (!configured) return;
1598
+ const { parsed } = configured;
1599
+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) throw new Error(`${settingName} must not include a path, query string, or fragment.`);
1600
+ return parsed.origin;
1601
+ }
1602
+ /**
1603
+ * First path segments of the server's own root routes, plus `oauth` for the
1604
+ * removed OAuth proxy endpoints. A public URL must not start with one:
1605
+ * stripping such a base path from a request the proxy already stripped would
1606
+ * remove the route itself (`/mcp` under a base path of `/mcp` would become
1607
+ * `/`). These paths also never fall back to the web UI, so clients probing the
1608
+ * removed endpoints get a clean 404 instead of an HTML page.
1609
+ */
1610
+ var RESERVED_ROOT_SEGMENTS = [
1611
+ "mcp",
1612
+ "api",
1613
+ "assets",
1614
+ ".well-known",
1615
+ "sse",
1616
+ "messages",
1617
+ "oauth"
1618
+ ];
1619
+ /**
1620
+ * Normalize a configured public URL: an absolute HTTP(S) URL that may carry a
1621
+ * path, returned without a trailing slash.
1622
+ *
1623
+ * Empty strings are treated as absent so container environments can leave the
1624
+ * variable declared but unset.
1625
+ *
1626
+ * @param value - The configured `server.publicUrl` value.
1627
+ * @returns The canonical URL (e.g. `https://example.com/docs`), or `undefined` when absent.
1628
+ * @throws Error naming `server.publicUrl` when the value has credentials, a query
1629
+ * string, a fragment, a non-HTTP(S) protocol, an empty path segment (`//`),
1630
+ * or a first path segment that collides with a route or file the server
1631
+ * serves at its root.
1632
+ */
1633
+ function normalizePublicUrl(value) {
1634
+ const configured = parseConfiguredUrl(value, "server.publicUrl", "URL without query string or fragment");
1635
+ if (!configured) return;
1636
+ const { parsed, trimmed } = configured;
1637
+ if (trimmed.includes("?") || trimmed.includes("#")) throw new Error("server.publicUrl must not include a query string or fragment.");
1638
+ if (parsed.pathname.includes("//")) throw new Error(`server.publicUrl path must not contain an empty segment ("//"): "${parsed.pathname}".`);
1639
+ const path = parsed.pathname.replace(/\/$/, "");
1640
+ const firstSegment = path.split("/")[1]?.toLowerCase();
1641
+ if (firstSegment && (RESERVED_ROOT_SEGMENTS.includes(firstSegment) || firstSegment.includes("."))) throw new Error(`server.publicUrl path must not start with "/${firstSegment}": the server reserves that path for its own routes and files, so requests could not be told apart. Choose a different path, such as "/docs".`);
1642
+ return `${parsed.origin}${path}`;
1643
+ }
1644
+ /**
1645
+ * Parse a configured HTTP(S) URL and apply the checks every such setting shares.
1646
+ * Empty values count as absent.
1647
+ * @returns The parsed URL and the trimmed input, or `undefined` when absent.
1648
+ * @throws Error naming the setting when the value is not an HTTP(S) URL or has credentials.
1649
+ */
1650
+ function parseConfiguredUrl(value, settingName, expectedShape) {
1651
+ const trimmed = value?.trim();
1652
+ if (!trimmed) return;
1653
+ let parsed;
1654
+ try {
1655
+ parsed = new URL(trimmed);
1656
+ } catch {
1657
+ throw new Error(`${settingName} must be an absolute HTTP(S) ${expectedShape}.`);
1658
+ }
1659
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`${settingName} must use the http or https protocol.`);
1660
+ if (parsed.username || parsed.password) throw new Error(`${settingName} must not include credentials.`);
1661
+ return {
1662
+ parsed,
1663
+ trimmed
1664
+ };
1665
+ }
1666
+ /**
1667
+ * Resolve the public location from configuration: `server.publicUrl` first,
1668
+ * then the deprecated `server.publicOrigin`, then the bind-derived origin.
1669
+ *
1670
+ * @param config - The loaded application configuration.
1671
+ * @param port - The port this process listens on (used for the bind fallback).
1672
+ * @returns The resolved public location.
1673
+ * @throws Error when a configured value is invalid (configuration loading
1674
+ * normally rejects those earlier).
1675
+ */
1676
+ function resolvePublicLocation(config, port) {
1677
+ const configuredUrl = normalizePublicUrl(config.server.publicUrl) ?? normalizePublicOrigin(config.server.publicOrigin);
1678
+ const url = configuredUrl ?? buildBindOrigin(config.server.host, port);
1679
+ const origin = new URL(url).origin;
1680
+ return {
1681
+ configured: configuredUrl !== void 0,
1682
+ url,
1683
+ origin,
1684
+ basePath: url.slice(origin.length)
1685
+ };
1686
+ }
1687
+ /**
1688
+ * Describe deprecation problems with the configured public location, for the
1689
+ * caller to log at startup.
1690
+ *
1691
+ * @param config - The loaded application configuration.
1692
+ * @returns Warning messages; empty when nothing needs attention.
1693
+ */
1694
+ function describePublicLocationWarnings(config) {
1695
+ const hasUrl = Boolean(config.server.publicUrl?.trim());
1696
+ const hasOrigin = Boolean(config.server.publicOrigin?.trim());
1697
+ if (hasUrl && hasOrigin) return ["server.publicOrigin is ignored because server.publicUrl is also set. Remove server.publicOrigin."];
1698
+ if (hasOrigin) return ["server.publicOrigin is deprecated. Use server.publicUrl instead."];
1699
+ return [];
1700
+ }
1701
+ /**
1702
+ * Build an HTTP origin from the local bind host and port.
1703
+ *
1704
+ * The server itself listens over HTTP; deployments that terminate TLS should
1705
+ * configure server.publicUrl to advertise an HTTPS URL.
1706
+ */
1707
+ function buildBindOrigin(host, port) {
1708
+ const formattedHost = formatHostForUrl(host);
1709
+ return new URL(`http://${formattedHost}:${port}`).origin;
1710
+ }
1711
+ function formatHostForUrl(host) {
1712
+ const trimmed = host.trim();
1713
+ const unbracketed = stripIpv6Brackets(trimmed);
1714
+ if (unbracketed.includes(":")) return `[${unbracketed}]`;
1715
+ return trimmed;
1716
+ }
1717
+ /**
1718
+ * Remove the brackets around an IPv6 address literal, as URLs and `Host`
1719
+ * headers write it. Other values are returned unchanged.
1720
+ * @param host - A host, e.g. `[::1]` or `example.com`.
1721
+ * @returns The host without brackets, e.g. `::1`.
1722
+ */
1723
+ function stripIpv6Brackets(host) {
1724
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
1725
+ }
1726
+ // src/utils/config.ts
1727
+ var managedConfigVectorDimensionOmissionMarker = "docs-mcp-server-managed-vector-dimension-omitted";
1728
+ var managedConfigHeader = [
1729
+ `# ${managedConfigVectorDimensionOmissionMarker}`,
1730
+ "# embeddings.vectorDimension is omitted when it comes from generated defaults.",
1731
+ "# Add embeddings.vectorDimension explicitly to override native model dimensions.",
1732
+ ""
1733
+ ].join("\n");
1734
+ var vectorDimensionPath = ["embeddings", "vectorDimension"];
1735
+ var envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
1736
+ if (Array.isArray(value)) return value;
1737
+ const parsed = yaml.parse(value);
1738
+ if (Array.isArray(parsed)) return parsed.map((item) => String(item));
1739
+ return [value];
1740
+ }).pipe(z.array(z.string()));
1741
+ /**
1742
+ * Custom zod schema for boolean values that properly handles string representations.
1743
+ * Unlike z.coerce.boolean() which treats any non-empty string as true,
1744
+ * this schema correctly parses "false", "0", "no", "off" as false.
1745
+ */
1746
+ var envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
1747
+ if (typeof val === "boolean") return val;
1748
+ const lower = val.toLowerCase().trim();
1749
+ return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off" && lower !== "";
1750
+ }).pipe(z.boolean());
1751
+ /**
1752
+ * Parses a boolean environment variable the way configuration settings are
1753
+ * parsed: "false", "0", "no", "off" and blank are false, anything else true.
1754
+ * @param value - The variable's value.
1755
+ * @returns The boolean, or undefined when the variable is unset.
1756
+ */
1757
+ function parseEnvBoolean(value) {
1758
+ return value === void 0 ? void 0 : envBoolean.parse(value);
1759
+ }
1760
+ /**
1761
+ * Treats blank strings (empty env vars, `--flag ""`) as an absent value so that
1762
+ * defaults and fallbacks apply instead of an empty string.
1763
+ */
1764
+ var blankToUndefined = (value) => {
1765
+ if (typeof value !== "string") return value;
1766
+ const trimmed = value.trim();
1767
+ return trimmed.length > 0 ? trimmed : void 0;
1768
+ };
1769
+ /** Report a normalizer's error as the validation issue of the setting. */
1770
+ function addNormalizationIssue(ctx, error) {
1771
+ ctx.addIssue({
1772
+ code: z.ZodIssueCode.custom,
1773
+ message: error instanceof Error ? error.message : String(error)
1774
+ });
1775
+ }
1776
+ /**
1777
+ * An optional string setting that `normalize` validates and canonicalizes.
1778
+ * The normalizer treats empty values as absent and throws a message naming
1779
+ * the setting for invalid ones.
1780
+ */
1781
+ function normalizedStringSchema(normalize) {
1782
+ return z.string().optional().transform((value, ctx) => {
1783
+ try {
1784
+ return normalize(value);
1785
+ } catch (error) {
1786
+ addNormalizationIssue(ctx, error);
1787
+ return z.NEVER;
1788
+ }
1789
+ });
1790
+ }
1791
+ var publicOriginSchema = normalizedStringSchema(normalizePublicOrigin);
1792
+ var publicUrlSchema = normalizedStringSchema(normalizePublicUrl);
1793
+ /**
1794
+ * Browser origins allowed to call the MCP endpoint in addition to loopback and
1795
+ * the public URL's origin. Each entry must be an exact origin
1796
+ * (`scheme://host[:port]`); a trailing slash is ignored.
1797
+ */
1798
+ var allowedOriginsSchema = envStringArray.transform((values, ctx) => {
1799
+ const origins = [];
1800
+ for (const value of values) try {
1801
+ const origin = normalizePublicOrigin(value, "server.allowedOrigins");
1802
+ if (origin) origins.push(origin);
1803
+ } catch (error) {
1804
+ addNormalizationIssue(ctx, error);
1805
+ return z.NEVER;
1806
+ }
1807
+ return origins;
1808
+ });
1809
+ var DEFAULT_CONFIG = {
1810
+ app: {
1811
+ storePath: "",
1812
+ telemetryEnabled: true,
1813
+ readOnly: false,
1814
+ embeddingModel: "text-embedding-3-small"
1815
+ },
1816
+ server: {
1817
+ name: "docs-mcp-server",
1818
+ title: void 0,
1819
+ instructions: void 0,
1820
+ instructionsFile: void 0,
1821
+ protocol: "auto",
1822
+ host: "127.0.0.1",
1823
+ publicUrl: void 0,
1824
+ publicOrigin: void 0,
1825
+ allowedOrigins: [],
1826
+ ports: {
1827
+ default: 6280,
1828
+ worker: 8080,
1829
+ mcp: 6280,
1830
+ web: 6281
1831
+ },
1832
+ heartbeatMs: 3e4
1833
+ },
1834
+ auth: {
1835
+ enabled: false,
1836
+ issuerUrl: "",
1837
+ audience: ""
1838
+ },
1839
+ scraper: {
1840
+ maxPages: 1e3,
1841
+ maxDepth: 3,
1842
+ maxConcurrency: 3,
1843
+ jobHeartbeatMs: 15e3,
1844
+ abortOnFailureRate: .5,
1845
+ preserveHashes: false,
1846
+ skipKnownTrackers: true,
1847
+ pageTimeoutMs: 5e3,
1848
+ browserTimeoutMs: 3e4,
1849
+ htmlExtractor: "cheerio",
1850
+ fetcher: {
1851
+ maxRetries: 3,
1852
+ baseDelayMs: 1e3,
1853
+ timeoutMs: 3e4,
1854
+ maxCacheItems: 200,
1855
+ maxCacheItemSizeBytes: 512e3
1856
+ },
1857
+ document: { maxSize: 10485760 },
1858
+ security: {
1859
+ network: {
1860
+ mode: "open",
1861
+ allowPrivateNetworks: false,
1862
+ allowedHosts: [],
1863
+ allowedCidrs: [],
1864
+ allowInvalidTls: false
1865
+ },
1866
+ fileAccess: {
1867
+ mode: "allowedRoots",
1868
+ allowedRoots: ["$DOCUMENTS"],
1869
+ followSymlinks: false,
1870
+ includeHidden: false
1871
+ }
1872
+ }
1873
+ },
1874
+ splitter: {
1875
+ minChunkSize: 500,
1876
+ preferredChunkSize: 1500,
1877
+ maxChunkSize: 5e3,
1878
+ treeSitterSizeLimit: 3e4,
1879
+ json: {
1880
+ maxNestingDepth: 5,
1881
+ maxChunks: 1e3
1882
+ }
1883
+ },
1884
+ embeddings: {
1885
+ batchSize: 100,
1886
+ batchChars: 5e4,
1887
+ requestTimeoutMs: 3e4,
1888
+ initTimeoutMs: 3e4,
1889
+ vectorDimension: 1536
1890
+ },
1891
+ db: {
1892
+ migrationMaxRetries: 5,
1893
+ migrationRetryDelayMs: 300
1894
+ },
1895
+ search: {
1896
+ overfetchFactor: 2,
1897
+ weightVec: 1,
1898
+ weightFts: 1,
1899
+ vectorMultiplier: 10
1900
+ },
1901
+ assembly: {
1902
+ maxParentChainDepth: 10,
1903
+ childLimit: 3,
1904
+ precedingSiblingsLimit: 1,
1905
+ subsequentSiblingsLimit: 2,
1906
+ maxChunkDistance: 3
1907
+ }
1908
+ };
1909
+ var AppConfigSchema = z.object({
1910
+ app: z.object({
1911
+ storePath: z.string().default(DEFAULT_CONFIG.app.storePath),
1912
+ telemetryEnabled: envBoolean.default(DEFAULT_CONFIG.app.telemetryEnabled),
1913
+ readOnly: envBoolean.default(DEFAULT_CONFIG.app.readOnly),
1914
+ embeddingModel: z.string().default(DEFAULT_CONFIG.app.embeddingModel)
1915
+ }).default(DEFAULT_CONFIG.app),
1916
+ server: z.object({
1917
+ name: z.preprocess(blankToUndefined, z.string().default(DEFAULT_CONFIG.server.name)),
1918
+ title: z.preprocess(blankToUndefined, z.string().optional()),
1919
+ instructions: z.preprocess(blankToUndefined, z.string().optional()),
1920
+ instructionsFile: z.preprocess(blankToUndefined, z.string().optional()),
1921
+ protocol: z.string().default(DEFAULT_CONFIG.server.protocol),
1922
+ host: z.string().default(DEFAULT_CONFIG.server.host),
1923
+ publicUrl: publicUrlSchema.optional(),
1924
+ publicOrigin: publicOriginSchema.optional(),
1925
+ allowedOrigins: allowedOriginsSchema.default(DEFAULT_CONFIG.server.allowedOrigins),
1926
+ ports: z.object({
1927
+ default: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.default),
1928
+ worker: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.worker),
1929
+ mcp: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.mcp),
1930
+ web: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.web)
1931
+ }).default(DEFAULT_CONFIG.server.ports),
1932
+ heartbeatMs: z.coerce.number().int().default(DEFAULT_CONFIG.server.heartbeatMs)
1933
+ }).default({
1934
+ name: DEFAULT_CONFIG.server.name,
1935
+ protocol: DEFAULT_CONFIG.server.protocol,
1936
+ host: DEFAULT_CONFIG.server.host,
1937
+ allowedOrigins: DEFAULT_CONFIG.server.allowedOrigins,
1938
+ ports: DEFAULT_CONFIG.server.ports,
1939
+ heartbeatMs: DEFAULT_CONFIG.server.heartbeatMs
1940
+ }),
1941
+ auth: z.object({
1942
+ enabled: envBoolean.default(DEFAULT_CONFIG.auth.enabled),
1943
+ issuerUrl: z.string().default(DEFAULT_CONFIG.auth.issuerUrl),
1944
+ audience: z.string().default(DEFAULT_CONFIG.auth.audience)
1945
+ }).default(DEFAULT_CONFIG.auth),
1946
+ scraper: z.object({
1947
+ maxPages: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxPages),
1948
+ maxDepth: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxDepth),
1949
+ maxConcurrency: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxConcurrency),
1950
+ jobHeartbeatMs: z.coerce.number().int().positive().default(DEFAULT_CONFIG.scraper.jobHeartbeatMs),
1951
+ abortOnFailureRate: z.coerce.number().min(0).max(1).default(DEFAULT_CONFIG.scraper.abortOnFailureRate),
1952
+ preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),
1953
+ skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
1954
+ pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
1955
+ browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
1956
+ htmlExtractor: z.enum(["cheerio", "defuddle"]).default(DEFAULT_CONFIG.scraper.htmlExtractor),
1957
+ fetcher: z.object({
1958
+ maxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),
1959
+ baseDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),
1960
+ timeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.timeoutMs),
1961
+ maxCacheItems: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItems),
1962
+ maxCacheItemSizeBytes: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItemSizeBytes)
1963
+ }).default(DEFAULT_CONFIG.scraper.fetcher),
1964
+ document: z.object({ maxSize: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.document.maxSize) }).default(DEFAULT_CONFIG.scraper.document),
1965
+ security: z.object({
1966
+ network: z.object({
1967
+ mode: z.enum(["open", "allowlist"]).default(DEFAULT_CONFIG.scraper.security.network.mode),
1968
+ allowPrivateNetworks: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks),
1969
+ allowedHosts: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedHosts),
1970
+ allowedCidrs: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedCidrs),
1971
+ allowInvalidTls: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowInvalidTls)
1972
+ }).default(DEFAULT_CONFIG.scraper.security.network),
1973
+ fileAccess: z.object({
1974
+ mode: z.enum([
1975
+ "disabled",
1976
+ "allowedRoots",
1977
+ "unrestricted"
1978
+ ]).default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),
1979
+ allowedRoots: envStringArray.default(DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots),
1980
+ followSymlinks: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks),
1981
+ includeHidden: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden)
1982
+ }).default(DEFAULT_CONFIG.scraper.security.fileAccess)
1983
+ }).default(DEFAULT_CONFIG.scraper.security)
1984
+ }).default(DEFAULT_CONFIG.scraper),
1985
+ splitter: z.object({
1986
+ minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),
1987
+ preferredChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.preferredChunkSize),
1988
+ maxChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.maxChunkSize),
1989
+ treeSitterSizeLimit: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.treeSitterSizeLimit),
1990
+ json: z.object({
1991
+ maxNestingDepth: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxNestingDepth),
1992
+ maxChunks: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxChunks)
1993
+ }).default(DEFAULT_CONFIG.splitter.json)
1994
+ }).default(DEFAULT_CONFIG.splitter),
1995
+ embeddings: z.object({
1996
+ batchSize: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchSize),
1997
+ batchChars: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchChars),
1998
+ requestTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.requestTimeoutMs),
1999
+ initTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.initTimeoutMs),
2000
+ vectorDimension: z.coerce.number().int().min(1, "embedding dimension must be at least 1").default(DEFAULT_CONFIG.embeddings.vectorDimension)
2001
+ }).default(DEFAULT_CONFIG.embeddings),
2002
+ db: z.object({
2003
+ migrationMaxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationMaxRetries),
2004
+ migrationRetryDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationRetryDelayMs)
2005
+ }).default(DEFAULT_CONFIG.db),
2006
+ search: z.object({
2007
+ overfetchFactor: z.coerce.number().default(DEFAULT_CONFIG.search.overfetchFactor),
2008
+ weightVec: z.coerce.number().default(DEFAULT_CONFIG.search.weightVec),
2009
+ weightFts: z.coerce.number().default(DEFAULT_CONFIG.search.weightFts),
2010
+ vectorMultiplier: z.coerce.number().int().default(DEFAULT_CONFIG.search.vectorMultiplier)
2011
+ }).default(DEFAULT_CONFIG.search),
2012
+ assembly: z.object({
2013
+ maxParentChainDepth: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.maxParentChainDepth),
2014
+ childLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.childLimit),
2015
+ precedingSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.precedingSiblingsLimit),
2016
+ subsequentSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.subsequentSiblingsLimit),
2017
+ maxChunkDistance: z.coerce.number().int().min(0).default(DEFAULT_CONFIG.assembly.maxChunkDistance)
2018
+ }).default(DEFAULT_CONFIG.assembly)
2019
+ });
2020
+ var vectorDimensionExplicit = Symbol("vectorDimensionExplicit");
2021
+ var defaults = AppConfigSchema.parse({});
2022
+ var configMappings = [
2023
+ {
2024
+ path: ["server", "protocol"],
2025
+ env: ["DOCS_MCP_PROTOCOL"],
2026
+ cli: "protocol"
2027
+ },
2028
+ {
2029
+ path: ["app", "storePath"],
2030
+ env: ["DOCS_MCP_STORE_PATH"],
2031
+ cli: "storePath"
2032
+ },
2033
+ {
2034
+ path: ["app", "telemetryEnabled"],
2035
+ env: ["DOCS_MCP_TELEMETRY"]
2036
+ },
2037
+ {
2038
+ path: ["app", "readOnly"],
2039
+ env: ["DOCS_MCP_READ_ONLY"],
2040
+ cli: "readOnly"
2041
+ },
2042
+ {
2043
+ path: [
2044
+ "server",
2045
+ "ports",
2046
+ "default"
2047
+ ],
2048
+ env: ["DOCS_MCP_PORT", "PORT"],
2049
+ cli: "port"
2050
+ },
2051
+ {
2052
+ path: [
2053
+ "server",
2054
+ "ports",
2055
+ "worker"
2056
+ ],
2057
+ env: ["DOCS_MCP_PORT", "PORT"],
2058
+ cli: "port"
2059
+ },
2060
+ {
2061
+ path: [
2062
+ "server",
2063
+ "ports",
2064
+ "mcp"
2065
+ ],
2066
+ env: ["DOCS_MCP_PORT", "PORT"],
2067
+ cli: "port"
2068
+ },
2069
+ {
2070
+ path: [
2071
+ "server",
2072
+ "ports",
2073
+ "web"
2074
+ ],
2075
+ env: [
2076
+ "DOCS_MCP_WEB_PORT",
2077
+ "DOCS_MCP_PORT",
2078
+ "PORT"
2079
+ ],
2080
+ cli: "port"
2081
+ },
2082
+ {
2083
+ path: ["server", "host"],
2084
+ env: ["DOCS_MCP_HOST", "HOST"],
2085
+ cli: "host"
2086
+ },
2087
+ {
2088
+ path: ["server", "publicUrl"],
2089
+ env: ["DOCS_MCP_SERVER_PUBLIC_URL"],
2090
+ cli: "publicUrl"
2091
+ },
2092
+ {
2093
+ path: ["server", "publicOrigin"],
2094
+ env: ["DOCS_MCP_SERVER_PUBLIC_ORIGIN"],
2095
+ cli: "publicOrigin"
2096
+ },
2097
+ {
2098
+ path: ["server", "name"],
2099
+ env: ["DOCS_MCP_SERVER_NAME"],
2100
+ cli: "serverName"
2101
+ },
2102
+ {
2103
+ path: ["server", "title"],
2104
+ env: ["DOCS_MCP_SERVER_TITLE"],
2105
+ cli: "serverTitle"
2106
+ },
2107
+ {
2108
+ path: ["server", "instructions"],
2109
+ env: ["DOCS_MCP_SERVER_INSTRUCTIONS"],
2110
+ cli: "serverInstructions"
2111
+ },
2112
+ {
2113
+ path: ["server", "instructionsFile"],
2114
+ env: ["DOCS_MCP_SERVER_INSTRUCTIONS_FILE"],
2115
+ cli: "serverInstructionsFile"
2116
+ },
2117
+ {
2118
+ path: ["app", "embeddingModel"],
2119
+ env: ["DOCS_MCP_EMBEDDING_MODEL"],
2120
+ cli: "embeddingModel"
2121
+ },
2122
+ {
2123
+ path: ["auth", "enabled"],
2124
+ env: ["DOCS_MCP_AUTH_ENABLED"],
2125
+ cli: "authEnabled"
2126
+ },
2127
+ {
2128
+ path: ["auth", "issuerUrl"],
2129
+ env: ["DOCS_MCP_AUTH_ISSUER_URL"],
2130
+ cli: "authIssuerUrl"
2131
+ },
2132
+ {
2133
+ path: ["auth", "audience"],
2134
+ env: ["DOCS_MCP_AUTH_AUDIENCE"],
2135
+ cli: "authAudience"
2136
+ }
2137
+ ];
2138
+ var systemPaths = envPaths("docs-mcp-server", { suffix: "" });
2139
+ function loadConfig(cliArgs = {}, options = {}) {
2140
+ const explicitPath = cliArgs.config || options.configPath || process.env.DOCS_MCP_CONFIG;
2141
+ let configPath;
2142
+ let isReadOnlyConfig = false;
2143
+ if (explicitPath) {
2144
+ configPath = explicitPath;
2145
+ isReadOnlyConfig = true;
2146
+ } else {
2147
+ configPath = path.join(systemPaths.config, "config.yaml");
2148
+ isReadOnlyConfig = false;
2149
+ }
2150
+ logger.debug(`Using config file: ${configPath}`);
2151
+ const fileConfig = loadConfigFile(configPath) || {};
2152
+ const hasManagedVectorDimensionOmissionMarker = hasManagedConfigVectorDimensionOmissionMarker(configPath);
2153
+ const baseConfig = deepMerge(defaults, fileConfig);
2154
+ const envConfig = mapEnvToConfig();
2155
+ const cliConfig = mapCliToConfig(cliArgs);
2156
+ const vectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
2157
+ const fileVectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, {}, {}, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
2158
+ if (!isReadOnlyConfig) try {
2159
+ saveConfigFile(configPath, baseConfig, {
2160
+ managedDefaultConfig: true,
2161
+ omitVectorDimension: !fileVectorDimensionWasExplicit
2162
+ });
2163
+ } catch (error) {
2164
+ logger.warn(`Failed to save config file to ${configPath}: ${error}`);
2165
+ }
2166
+ const mergedInput = deepMerge(baseConfig, deepMerge(envConfig, cliConfig));
2167
+ if (!getAtPath(mergedInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(mergedInput, ["app", "embeddingModel"], "text-embedding-3-small");
2168
+ const parseResult = AppConfigSchema.safeParse(mergedInput);
2169
+ if (parseResult.success) return markVectorDimensionSource(parseResult.data, vectorDimensionWasExplicit);
2170
+ for (const setting of [
2171
+ "publicUrl",
2172
+ "publicOrigin",
2173
+ "allowedOrigins"
2174
+ ]) if (hasParseIssueAtPath(parseResult.error, ["server", setting])) throw new Error(`Invalid configuration for server.${setting}: ${parseResult.error.message}`);
2175
+ if (!isReadOnlyConfig && fs.existsSync(configPath)) {
2176
+ const quarantinePath = `${configPath}.invalid-${Date.now()}`;
2177
+ try {
2178
+ fs.renameSync(configPath, quarantinePath);
2179
+ logger.warn(`Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`);
2180
+ } catch (renameError) {
2181
+ logger.warn(`Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`);
2182
+ }
2183
+ } else logger.warn(`Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`);
2184
+ const fallbackInput = deepMerge(defaults, deepMerge(envConfig, cliConfig));
2185
+ if (!getAtPath(fallbackInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
2186
+ const fallbackConfig = markVectorDimensionSource(AppConfigSchema.parse(fallbackInput), wasVectorDimensionExplicit({}, envConfig, cliConfig, false, false));
2187
+ if (!isReadOnlyConfig) try {
2188
+ saveConfigFile(configPath, fallbackConfig, {
2189
+ managedDefaultConfig: true,
2190
+ omitVectorDimension: true
2191
+ });
2192
+ } catch (error) {
2193
+ logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
2194
+ }
2195
+ return fallbackConfig;
2196
+ }
2197
+ function hasManagedConfigVectorDimensionOmissionMarker(filePath) {
2198
+ if (!fs.existsSync(filePath)) return false;
2199
+ try {
2200
+ return fs.readFileSync(filePath, "utf8").includes(managedConfigVectorDimensionOmissionMarker);
2201
+ } catch {
2202
+ return false;
2203
+ }
2204
+ }
2205
+ /**
2206
+ * Returns true when the embedding vector dimension was set by user config,
2207
+ * environment, or CLI rather than coming from generated defaults.
2208
+ */
2209
+ function isVectorDimensionExplicit(config) {
2210
+ return config.embeddings[vectorDimensionExplicit] === true;
2211
+ }
2212
+ /**
2213
+ * Marks an AppConfig as having an explicit or default-derived vector dimension.
2214
+ */
2215
+ function markVectorDimensionSource(config, explicit) {
2216
+ Object.defineProperty(config.embeddings, vectorDimensionExplicit, {
2217
+ value: explicit,
2218
+ enumerable: false,
2219
+ configurable: true
2220
+ });
2221
+ return config;
2222
+ }
2223
+ function loadConfigFile(filePath) {
2224
+ if (!fs.existsSync(filePath)) return null;
2225
+ try {
2226
+ const content = fs.readFileSync(filePath, "utf8");
2227
+ if (filePath.endsWith(".json")) return JSON.parse(content);
2228
+ return yaml.parse(content) || {};
2229
+ } catch (error) {
2230
+ logger.warn(`Failed to parse config file ${filePath}: ${error}`);
2231
+ return null;
2232
+ }
2233
+ }
2234
+ function wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker) {
2235
+ if (getAtPath(envConfig, vectorDimensionPath) !== void 0 || getAtPath(cliConfig, vectorDimensionPath) !== void 0) return true;
2236
+ const fileValue = getAtPath(fileConfig, vectorDimensionPath);
2237
+ if (fileValue === void 0) return false;
2238
+ if (isReadOnlyConfig || fileValue !== DEFAULT_CONFIG.embeddings.vectorDimension || hasManagedVectorDimensionOmissionMarker) return true;
2239
+ return !looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig);
2240
+ }
2241
+ function looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig) {
2242
+ const embeddings = fileConfig.embeddings;
2243
+ if (typeof embeddings !== "object" || embeddings === null || Array.isArray(embeddings)) return false;
2244
+ return Object.keys(DEFAULT_CONFIG.embeddings).every((key) => Object.hasOwn(embeddings, key));
2245
+ }
2246
+ function saveConfigFile(filePath, config, options = {}) {
2247
+ const dir = path.dirname(filePath);
2248
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
2249
+ const configToWrite = cloneConfigValue(config);
2250
+ if (options.omitVectorDimension) unsetAtPath(configToWrite, vectorDimensionPath);
2251
+ let content;
2252
+ if (filePath.endsWith(".json")) content = JSON.stringify(configToWrite, null, 2);
2253
+ else {
2254
+ content = yaml.stringify(configToWrite);
2255
+ if (options.managedDefaultConfig) content = `${managedConfigHeader}${content}`;
2256
+ }
2257
+ logger.debug(`Updating config file at ${filePath}`);
2258
+ fs.writeFileSync(filePath, content, "utf8");
2259
+ }
2260
+ function mapEnvToConfig() {
2261
+ const config = {};
2262
+ for (const mapping of configMappings) if (mapping.env) {
2263
+ for (const envVar of mapping.env) if (process.env[envVar] !== void 0) {
2264
+ setAtPath(config, mapping.path, normalizeEnvValue(process.env[envVar]));
2265
+ break;
2266
+ }
2267
+ }
2268
+ for (const pathArr of ALL_CONFIG_LEAF_PATHS) {
2269
+ const envVar = pathToEnvVar(pathArr);
2270
+ if (process.env[envVar] !== void 0) setAtPath(config, pathArr, normalizeEnvValue(process.env[envVar]));
2271
+ }
2272
+ return config;
2273
+ }
2274
+ function mapCliToConfig(args) {
2275
+ const config = {};
2276
+ for (const mapping of configMappings) if (mapping.cli && args[mapping.cli] !== void 0) setAtPath(config, mapping.path, args[mapping.cli]);
2277
+ return config;
2278
+ }
2279
+ /**
2280
+ * Convert camelCase to UPPER_SNAKE_CASE
2281
+ * Example: "maxSize" → "MAX_SIZE", "maxNestingDepth" → "MAX_NESTING_DEPTH"
757
2282
  */
2283
+ function camelToUpperSnake(str) {
2284
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
2285
+ }
758
2286
  /**
759
- * Central event bus for application-wide events.
2287
+ * Convert config path to environment variable name
2288
+ * Example: ["scraper", "document", "maxSize"] → "DOCS_MCP_SCRAPER_DOCUMENT_MAX_SIZE"
760
2289
  */
761
- var EventBusService = class {
762
- emitter;
763
- constructor() {
764
- this.emitter = new EventEmitter();
765
- this.emitter.setMaxListeners(100);
2290
+ function pathToEnvVar(pathArr) {
2291
+ return `DOCS_MCP_${pathArr.map(camelToUpperSnake).join("_")}`;
2292
+ }
2293
+ /**
2294
+ * Recursively collect all leaf paths from a config object
2295
+ */
2296
+ function collectLeafPaths(obj, prefix = []) {
2297
+ const paths = [];
2298
+ for (const [key, value] of Object.entries(obj)) {
2299
+ const currentPath = [...prefix, key];
2300
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) paths.push(...collectLeafPaths(value, currentPath));
2301
+ else paths.push(currentPath);
766
2302
  }
767
- /**
768
- * Emit an event to all subscribers.
769
- */
770
- emit(eventType, payload) {
771
- logger.debug(`Event emitted: ${eventType}`);
772
- this.emitter.emit(eventType, payload);
2303
+ return paths;
2304
+ }
2305
+ var ALL_CONFIG_LEAF_PATHS = collectLeafPaths(DEFAULT_CONFIG);
2306
+ function setAtPath(obj, pathArr, value) {
2307
+ let current = obj;
2308
+ for (let i = 0; i < pathArr.length - 1; i++) {
2309
+ const key = pathArr[i];
2310
+ if (current[key] === void 0 || typeof current[key] !== "object" || current[key] === null) current[key] = {};
2311
+ current = current[key];
2312
+ }
2313
+ current[pathArr[pathArr.length - 1]] = value;
2314
+ }
2315
+ function getAtPath(obj, pathArr) {
2316
+ let current = obj;
2317
+ for (const key of pathArr) {
2318
+ if (typeof current !== "object" || current === null) return void 0;
2319
+ current = current[key];
773
2320
  }
774
- /**
775
- * Subscribe to events of a specific type.
776
- * Returns an unsubscribe function.
777
- */
778
- on(eventType, listener) {
779
- this.emitter.on(eventType, listener);
780
- return () => this.emitter.off(eventType, listener);
2321
+ return current;
2322
+ }
2323
+ function unsetAtPath(obj, pathArr) {
2324
+ let current = obj;
2325
+ for (const key of pathArr.slice(0, -1)) {
2326
+ if (typeof current !== "object" || current === null) return;
2327
+ current = current[key];
781
2328
  }
782
- /**
783
- * Remove a specific listener.
784
- */
785
- off(eventType, listener) {
786
- this.emitter.off(eventType, listener);
2329
+ if (typeof current === "object" && current !== null) delete current[pathArr[pathArr.length - 1]];
2330
+ }
2331
+ function cloneConfigValue(value) {
2332
+ if (Array.isArray(value)) return value.map((item) => cloneConfigValue(item));
2333
+ if (typeof value === "object" && value !== null) {
2334
+ const output = {};
2335
+ for (const [key, child] of Object.entries(value)) output[key] = cloneConfigValue(child);
2336
+ return output;
787
2337
  }
788
- };
2338
+ return value;
2339
+ }
2340
+ function hasPath(obj, pathArr) {
2341
+ let current = obj;
2342
+ for (const key of pathArr) {
2343
+ if (typeof current !== "object" || current === null || !Object.hasOwn(current, key)) return false;
2344
+ current = current[key];
2345
+ }
2346
+ return true;
2347
+ }
2348
+ function hasParseIssueAtPath(error, pathArr) {
2349
+ return error.issues.some((issue) => issue.path.join(".") === pathArr.join("."));
2350
+ }
2351
+ function deepMerge(target, source) {
2352
+ if (typeof target !== "object" || target === null) return source;
2353
+ if (typeof source !== "object" || source === null) return target;
2354
+ if (Array.isArray(target) || Array.isArray(source)) return source;
2355
+ const t = target;
2356
+ const s = source;
2357
+ const output = { ...t };
2358
+ for (const key of Object.keys(s)) {
2359
+ const sValue = s[key];
2360
+ const tValue = t[key];
2361
+ if (typeof sValue === "object" && sValue !== null && !Array.isArray(sValue) && typeof tValue === "object" && tValue !== null && !Array.isArray(tValue) && key in t) output[key] = deepMerge(tValue, sValue);
2362
+ else output[key] = sValue;
2363
+ }
2364
+ return output;
2365
+ }
2366
+ /**
2367
+ * Check if a config path is valid by verifying it exists in DEFAULT_CONFIG
2368
+ */
2369
+ function isValidConfigPath(path) {
2370
+ return hasPath(DEFAULT_CONFIG, path.split("."));
2371
+ }
2372
+ /**
2373
+ * Get a config value by dot-separated path
2374
+ */
2375
+ function getConfigValue(config, path) {
2376
+ return getAtPath(config, path.split("."));
2377
+ }
2378
+ /**
2379
+ * Parse a string value to the appropriate type (number, boolean, or string)
2380
+ */
2381
+ function parseConfigValue(value) {
2382
+ const num = Number(value);
2383
+ if (!Number.isNaN(num) && value.trim() !== "") return num;
2384
+ const lower = value.toLowerCase();
2385
+ if (lower === "true") return true;
2386
+ if (lower === "false") return false;
2387
+ return value;
2388
+ }
2389
+ /**
2390
+ * Set a config value and persist to file.
2391
+ * Returns the path to the config file that was updated.
2392
+ * Validates the updated config against the schema before saving.
2393
+ */
2394
+ function setConfigValue(path, value) {
2395
+ const configPath = getDefaultConfigPath();
2396
+ const fileConfig = loadConfigFile(configPath) || {};
2397
+ const pathArr = path.split(".");
2398
+ const parsedValue = parseConfigValue(value);
2399
+ const updatedConfig = JSON.parse(JSON.stringify(fileConfig));
2400
+ setAtPath(updatedConfig, pathArr, parsedValue);
2401
+ try {
2402
+ AppConfigSchema.parse(updatedConfig);
2403
+ } catch (err) {
2404
+ const errorMsg = err instanceof Error ? err.message : String(err);
2405
+ throw new Error(`Invalid config value for "${path}": ${errorMsg}`);
2406
+ }
2407
+ saveConfigFile(configPath, updatedConfig);
2408
+ return configPath;
2409
+ }
2410
+ /**
2411
+ * Get the default system config path
2412
+ */
2413
+ function getDefaultConfigPath() {
2414
+ return path.join(systemPaths.config, "config.yaml");
2415
+ }
789
2416
  // src/events/RemoteEventProxy.ts
790
2417
  /** First delay before subscribing again after the subscription itself ended. */
791
2418
  var RESUBSCRIBE_BASE_DELAY_MS = 1e3;
@@ -1190,11 +2817,20 @@ var ChallengeError = class extends ScraperError {
1190
2817
  url;
1191
2818
  statusCode;
1192
2819
  challengeType;
1193
- constructor(url, statusCode, challengeType) {
2820
+ responseUrl;
2821
+ /**
2822
+ * @param url The URL that was requested.
2823
+ * @param statusCode The status the challenge was served with.
2824
+ * @param challengeType The kind of challenge, such as "cloudflare".
2825
+ * @param responseUrl The URL whose response carried the challenge, which a
2826
+ * redirect may have moved to another host.
2827
+ */
2828
+ constructor(url, statusCode, challengeType, responseUrl = url) {
1194
2829
  super(`Challenge detected for ${url} (status: ${statusCode}, type: ${challengeType}): the site answered with a bot check instead of the page`, false);
1195
2830
  this.url = url;
1196
2831
  this.statusCode = statusCode;
1197
2832
  this.challengeType = challengeType;
2833
+ this.responseUrl = responseUrl;
1198
2834
  }
1199
2835
  };
1200
2836
  var TlsCertificateError = class extends ScraperError {
@@ -1209,9 +2845,19 @@ var TlsCertificateError = class extends ScraperError {
1209
2845
  /** An HTTP fetch that failed with a response, carrying that response's status. */
1210
2846
  var HttpStatusError = class extends ScraperError {
1211
2847
  statusCode;
1212
- constructor(message, isRetryable, statusCode, cause) {
2848
+ responseUrl;
2849
+ /**
2850
+ * @param message Describes the failure.
2851
+ * @param isRetryable Whether a later attempt may succeed.
2852
+ * @param statusCode The response's status.
2853
+ * @param cause The underlying error.
2854
+ * @param responseUrl The URL that answered with the status, when known; a
2855
+ * redirect may have moved it to another host.
2856
+ */
2857
+ constructor(message, isRetryable, statusCode, cause, responseUrl) {
1213
2858
  super(message, isRetryable, cause);
1214
2859
  this.statusCode = statusCode;
2860
+ this.responseUrl = responseUrl;
1215
2861
  }
1216
2862
  };
1217
2863
  var AccessPolicyError = class extends ScraperError {
@@ -2452,8 +4098,6 @@ var FingerprintGenerator = class {
2452
4098
  return this.headerGenerator.getHeaders();
2453
4099
  }
2454
4100
  };
2455
- // src/scraper/fetcher/headers.ts
2456
- var MARKDOWN_PREFERRED_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8";
2457
4101
  /**
2458
4102
  * Reads a header by name, ignoring case.
2459
4103
  *
@@ -2471,18 +4115,6 @@ function getHeader(headers, name) {
2471
4115
  for (const [header, value] of Object.entries(headers)) if (header.toLowerCase() === target) return value;
2472
4116
  }
2473
4117
  /**
2474
- * Returns headers with a Markdown-preferred Accept default unless one was supplied.
2475
- * @param headers Existing request headers.
2476
- * @returns Headers with an Accept value suitable for web scraping.
2477
- */
2478
- function withMarkdownPreferredAccept(headers, callerHeaders = {}) {
2479
- if (Object.keys(callerHeaders).some((header) => header.toLowerCase() === "accept")) return headers;
2480
- return {
2481
- ...Object.fromEntries(Object.entries(headers).filter(([header]) => header.toLowerCase() !== "accept")),
2482
- Accept: MARKDOWN_PREFERRED_ACCEPT
2483
- };
2484
- }
2485
- /**
2486
4118
  * Connection-level headers, which the client that opens a connection sets for
2487
4119
  * itself. Chromium refuses to take them from a page: a navigation that carries
2488
4120
  * one fails with `net::ERR_INVALID_ARGUMENT`. Generated Firefox fingerprints
@@ -2735,6 +4367,33 @@ var ManagedBrowser = class ManagedBrowser {
2735
4367
  }
2736
4368
  }
2737
4369
  /**
4370
+ * Tells whether Playwright's own Chromium is installed: the headless shell a
4371
+ * launch uses by default, or the full build it falls back to.
4372
+ *
4373
+ * Playwright only reports the full build's path. The shell of the same
4374
+ * revision sits next to it, in `chromium_headless_shell-<revision>`, and
4375
+ * Playwright marks a finished download with an `INSTALLATION_COMPLETE` file.
4376
+ *
4377
+ * @returns True when a launch without an explicit executable can succeed.
4378
+ */
4379
+ static isPlaywrightChromiumInstalled() {
4380
+ let fullBuildPath;
4381
+ try {
4382
+ fullBuildPath = chromium.executablePath();
4383
+ } catch {
4384
+ return false;
4385
+ }
4386
+ if (fs.existsSync(fullBuildPath)) return true;
4387
+ for (let dir = fullBuildPath; path.dirname(dir) !== dir; dir = path.dirname(dir)) {
4388
+ const revision = /^chromium-(\d+)$/.exec(path.basename(dir))?.[1];
4389
+ if (revision) {
4390
+ const shellDir = path.join(path.dirname(dir), `chromium_headless_shell-${revision}`);
4391
+ return fs.existsSync(path.join(shellDir, "INSTALLATION_COMPLETE"));
4392
+ }
4393
+ }
4394
+ return false;
4395
+ }
4396
+ /**
2738
4397
  * Resolves the Chromium binary to launch.
2739
4398
  *
2740
4399
  * Playwright's own managed build is pinned to the installed Playwright
@@ -2747,9 +4406,7 @@ var ManagedBrowser = class ManagedBrowser {
2747
4406
  static resolveChromiumExecutablePath() {
2748
4407
  const configuredPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
2749
4408
  if (configuredPath) return configuredPath;
2750
- try {
2751
- if (fs.existsSync(chromium.executablePath())) return;
2752
- } catch {}
4409
+ if (ManagedBrowser.isPlaywrightChromiumInstalled()) return;
2753
4410
  const systemPath = [
2754
4411
  "/usr/lib/chromium/chromium",
2755
4412
  "/usr/bin/chromium",
@@ -2897,10 +4554,10 @@ var BrowserFetcher = class {
2897
4554
  page.on("requestfailed", (request) => {
2898
4555
  if (request.frame() === page?.mainFrame() && request.isNavigationRequest() && request.failure()?.errorText.includes("ERR_BLOCKED_BY_CLIENT")) blockedNavigation = request.url();
2899
4556
  });
2900
- const requestHeaders = withMarkdownPreferredAccept({
4557
+ const requestHeaders = {
2901
4558
  ...fingerprintHeaders,
2902
4559
  ...options?.headers
2903
- }, options?.headers);
4560
+ };
2904
4561
  await page.setExtraHTTPHeaders(withoutBrowserManagedHeaders(requestHeaders));
2905
4562
  const timeout = options?.timeout || this.defaultTimeoutMs;
2906
4563
  logger.debug(`Navigating to ${source} with browser...`);
@@ -3123,6 +4780,143 @@ var CancellationError = class extends PipelineError {
3123
4780
  super(message);
3124
4781
  }
3125
4782
  };
4783
+ // src/scraper/fetcher/HostBackoff.ts
4784
+ /**
4785
+ * Per-host pause for servers that ask the scraper to slow down.
4786
+ *
4787
+ * A crawl runs several requests at once. When one of them is throttled, the
4788
+ * others would go on requesting the same host at full speed, so a throttle
4789
+ * pauses the host rather than the one request that met it.
4790
+ */
4791
+ /**
4792
+ * The longest a host is paused for, whatever the server asks. A server asking
4793
+ * for an hour would otherwise park the crawl; capped, the request is retried
4794
+ * and fails if the server still refuses it.
4795
+ */
4796
+ var MAX_THROTTLE_DELAY_MS = 6e4;
4797
+ /**
4798
+ * Caps the doubling. Beyond this the pause is at its maximum anyway, and the
4799
+ * cap keeps a base delay of zero from multiplying into NaN.
4800
+ */
4801
+ var MAX_BACKOFF_EXPONENT = 16;
4802
+ /**
4803
+ * Parses a `Retry-After` header into a delay.
4804
+ *
4805
+ * Accepts both forms RFC 9110 allows: delta-seconds (`120`) and an HTTP-date
4806
+ * (`Wed, 21 Oct 2015 07:28:00 GMT`). A date in the past means no delay.
4807
+ *
4808
+ * @param value The header value as the response carried it.
4809
+ * @param now The current time in epoch milliseconds.
4810
+ * @returns The delay in milliseconds, or undefined when the header is missing
4811
+ * or unreadable.
4812
+ */
4813
+ function parseRetryAfter(value, now = Date.now()) {
4814
+ if (typeof value !== "string") return;
4815
+ const trimmed = value.trim();
4816
+ if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1e3;
4817
+ const date = /[a-z]/i.test(trimmed) ? Date.parse(trimmed) : NaN;
4818
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - now);
4819
+ }
4820
+ /**
4821
+ * Pauses every request to a host after the host throttles one of them.
4822
+ *
4823
+ * Shared by the fetchers of one crawl, so all of its workers wait out the same
4824
+ * pause. The pause doubles with each throttled response in a row and resets
4825
+ * once the host answers a request sent after the last throttle.
4826
+ */
4827
+ var HostBackoff = class {
4828
+ hosts = /* @__PURE__ */ new Map();
4829
+ /**
4830
+ * Waits until requests to the host of `url` may resume.
4831
+ *
4832
+ * @param url The URL about to be requested.
4833
+ * @param signal Aborts the wait.
4834
+ * @throws {CancellationError} When the signal aborts.
4835
+ */
4836
+ async wait(url, signal) {
4837
+ const host = hostOf(url);
4838
+ for (let state = this.hosts.get(host); state && state.resumeAt > Date.now(); state = this.hosts.get(host)) await sleep(state.resumeAt - Date.now(), signal);
4839
+ }
4840
+ /**
4841
+ * Records a throttled response and pauses its host.
4842
+ *
4843
+ * Without a `Retry-After`, the pause starts at `baseDelayMs` and doubles with
4844
+ * each throttle in a row, and is jittered down by up to half so the requests
4845
+ * of separate crawls do not retry in step.
4846
+ *
4847
+ * @param url The URL that was throttled.
4848
+ * @param baseDelayMs The pause after the first throttle, before jitter.
4849
+ * @param retryAfterMs The pause the server asked for, if it named one.
4850
+ * @returns How long the host is paused from now, in milliseconds.
4851
+ */
4852
+ throttle(url, baseDelayMs, retryAfterMs) {
4853
+ const host = hostOf(url);
4854
+ const now = Date.now();
4855
+ const state = this.hosts.get(host) ?? {
4856
+ resumeAt: 0,
4857
+ strikes: 0,
4858
+ throttledAt: 0
4859
+ };
4860
+ state.strikes++;
4861
+ state.throttledAt = now;
4862
+ let delay;
4863
+ if (retryAfterMs !== void 0) delay = Math.min(retryAfterMs, MAX_THROTTLE_DELAY_MS);
4864
+ else {
4865
+ const exponent = Math.min(state.strikes - 1, MAX_BACKOFF_EXPONENT);
4866
+ const nominal = Math.min(baseDelayMs * 2 ** exponent, MAX_THROTTLE_DELAY_MS);
4867
+ delay = nominal / 2 + Math.random() * nominal / 2;
4868
+ }
4869
+ state.resumeAt = Math.max(state.resumeAt, now + Math.round(delay));
4870
+ this.hosts.set(host, state);
4871
+ return state.resumeAt - now;
4872
+ }
4873
+ /**
4874
+ * Records a normal answer from the host, which ends its backoff.
4875
+ *
4876
+ * Only a request sent after the last throttle counts: one that was already
4877
+ * in flight says nothing about whether the host has recovered.
4878
+ *
4879
+ * @param url The URL that was answered.
4880
+ * @param sentAt When the request was sent, in epoch milliseconds.
4881
+ */
4882
+ recover(url, sentAt) {
4883
+ const host = hostOf(url);
4884
+ const state = this.hosts.get(host);
4885
+ if (state && sentAt > state.throttledAt) this.hosts.delete(host);
4886
+ }
4887
+ };
4888
+ /**
4889
+ * Returns the key a URL's pause is stored under.
4890
+ *
4891
+ * @param url An absolute URL.
4892
+ * @returns The URL's host, including any port.
4893
+ */
4894
+ function hostOf(url) {
4895
+ return new URL(url).host;
4896
+ }
4897
+ /**
4898
+ * Resolves after `ms` milliseconds, or rejects as soon as the signal aborts.
4899
+ *
4900
+ * @param ms The delay in milliseconds.
4901
+ * @param signal Aborts the delay.
4902
+ */
4903
+ function sleep(ms, signal) {
4904
+ return new Promise((resolve, reject) => {
4905
+ const onAbort = () => {
4906
+ clearTimeout(timer);
4907
+ reject(new CancellationError("Wait for a throttled host cancelled"));
4908
+ };
4909
+ const timer = setTimeout(() => {
4910
+ signal?.removeEventListener("abort", onAbort);
4911
+ resolve();
4912
+ }, ms);
4913
+ if (signal?.aborted) {
4914
+ onAbort();
4915
+ return;
4916
+ }
4917
+ signal?.addEventListener("abort", onAbort, { once: true });
4918
+ });
4919
+ }
3126
4920
  // src/scraper/fetcher/HttpFetcher.ts
3127
4921
  /**
3128
4922
  * Maximum number of redirects to follow in a single fetch. Matches the legacy
@@ -3131,7 +4925,16 @@ var CancellationError = class extends PipelineError {
3131
4925
  */
3132
4926
  var MAX_REDIRECTS = 5;
3133
4927
  /**
4928
+ * How much longer than other retries a throttled request waits when the server
4929
+ * names no delay. A retry after the usual second would most likely be
4930
+ * throttled again.
4931
+ */
4932
+ var THROTTLE_DELAY_FACTOR = 5;
4933
+ /**
3134
4934
  * Fetches content from remote sources using HTTP/HTTPS.
4935
+ *
4936
+ * A 429, or a 503 with `Retry-After`, pauses every request this fetcher sends
4937
+ * to that host (see {@link HostBackoff}).
3135
4938
  */
3136
4939
  var HttpFetcher = class {
3137
4940
  maxRetriesDefault;
@@ -3168,12 +4971,19 @@ var HttpFetcher = class {
3168
4971
  ];
3169
4972
  fingerprintGenerator;
3170
4973
  accessPolicy;
3171
- constructor(scraperConfig) {
4974
+ hostBackoff;
4975
+ /**
4976
+ * @param scraperConfig - Scraper settings, including the retry defaults.
4977
+ * @param hostBackoff - The per-host pause; pass one to share it with other
4978
+ * fetchers of the same crawl.
4979
+ */
4980
+ constructor(scraperConfig, hostBackoff = new HostBackoff()) {
3172
4981
  this.maxRetriesDefault = scraperConfig.fetcher.maxRetries;
3173
4982
  this.baseDelayDefaultMs = scraperConfig.fetcher.baseDelayMs;
3174
4983
  this.timeoutDefaultMs = scraperConfig.fetcher.timeoutMs;
3175
4984
  this.fingerprintGenerator = new FingerprintGenerator();
3176
4985
  this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
4986
+ this.hostBackoff = hostBackoff;
3177
4987
  }
3178
4988
  canFetch(source) {
3179
4989
  return source.startsWith("http://") || source.startsWith("https://");
@@ -3192,134 +5002,141 @@ var HttpFetcher = class {
3192
5002
  }
3193
5003
  async performFetch(source, options, maxRetries = this.maxRetriesDefault, baseDelay = this.baseDelayDefaultMs, followRedirects = true) {
3194
5004
  await this.accessPolicy.assertNetworkUrlAllowed(source);
3195
- for (let attempt = 0; attempt <= maxRetries; attempt++) try {
5005
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
3196
5006
  let currentUrl = source;
3197
- let redirectCount = 0;
3198
- while (true) {
3199
- const headers = withMarkdownPreferredAccept({
3200
- ...withoutConnectionHeaders(this.fingerprintGenerator.generateHeaders()),
3201
- ...options?.headers
3202
- }, options?.headers);
3203
- if (options?.etag) {
3204
- headers["If-None-Match"] = options.etag;
3205
- logger.debug(`Conditional request for ${source} with If-None-Match: ${options.etag}`);
3206
- }
3207
- const config = {
3208
- responseType: "stream",
3209
- headers: {
3210
- ...headers,
3211
- "Accept-Encoding": "gzip, deflate, br"
3212
- },
3213
- timeout: options?.timeout ?? this.timeoutDefaultMs,
3214
- signal: options?.signal,
3215
- maxRedirects: 0,
3216
- decompress: true,
3217
- validateStatus: (status) => {
3218
- return status >= 200 && status < 400 || status === 304;
3219
- }
3220
- };
3221
- if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
3222
- const response = await axios.get(currentUrl, config);
3223
- let bodyConsumed = false;
3224
- try {
3225
- if (response.status === 304) {
3226
- logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
3227
- return {
3228
- content: Buffer.from(""),
3229
- mimeType: "text/plain",
3230
- source: currentUrl,
3231
- status: FetchStatus.NOT_MODIFIED
3232
- };
3233
- }
3234
- if (response.status >= 300 && response.status < 400) {
3235
- const location = response.headers.location;
3236
- if (!location) throw new ScraperError(`Redirect response for ${currentUrl} did not include a location header`, false);
3237
- if (!followRedirects) throw new RedirectError(currentUrl, location, response.status);
3238
- if (redirectCount >= MAX_REDIRECTS) throw new ScraperError(`Too many redirects while fetching ${source}`, false);
3239
- const redirectUrl = new URL(location, currentUrl).href;
3240
- await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
3241
- currentUrl = redirectUrl;
3242
- redirectCount += 1;
3243
- continue;
5007
+ try {
5008
+ let redirectCount = 0;
5009
+ while (true) {
5010
+ const headers = {
5011
+ ...withoutConnectionHeaders(this.fingerprintGenerator.generateHeaders()),
5012
+ ...options?.headers
5013
+ };
5014
+ if (options?.etag) {
5015
+ headers["If-None-Match"] = options.etag;
5016
+ logger.debug(`Conditional request for ${source} with If-None-Match: ${options.etag}`);
3244
5017
  }
3245
- const contentTypeHeader = response.headers["content-type"];
3246
- const { mimeType, charset } = MimeTypeUtils.parseContentType(typeof contentTypeHeader === "string" ? contentTypeHeader : void 0);
3247
- const rawContentEncoding = response.headers["content-encoding"];
3248
- const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
3249
- const finalUrl = response.request?.res?.responseUrl || response.request?.responseUrl || response.config?.url || currentUrl;
3250
- await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
3251
- if (options?.acceptsMimeType && !options.acceptsMimeType(mimeType)) {
3252
- logger.debug(`Skipping ${finalUrl}: ${mimeType} is not processable`);
5018
+ const config = {
5019
+ responseType: "stream",
5020
+ headers: {
5021
+ ...headers,
5022
+ "Accept-Encoding": "gzip, deflate, br"
5023
+ },
5024
+ timeout: options?.timeout ?? this.timeoutDefaultMs,
5025
+ signal: options?.signal,
5026
+ maxRedirects: 0,
5027
+ decompress: true,
5028
+ validateStatus: (status) => {
5029
+ return status >= 200 && status < 400 || status === 304;
5030
+ }
5031
+ };
5032
+ if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
5033
+ await this.hostBackoff.wait(currentUrl, options?.signal);
5034
+ const sentAt = Date.now();
5035
+ const response = await axios.get(currentUrl, config);
5036
+ this.hostBackoff.recover(currentUrl, sentAt);
5037
+ let bodyConsumed = false;
5038
+ try {
5039
+ if (response.status === 304) {
5040
+ logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
5041
+ return {
5042
+ content: Buffer.from(""),
5043
+ mimeType: "text/plain",
5044
+ source: currentUrl,
5045
+ status: FetchStatus.NOT_MODIFIED
5046
+ };
5047
+ }
5048
+ if (response.status >= 300 && response.status < 400) {
5049
+ const location = response.headers.location;
5050
+ if (!location) throw new ScraperError(`Redirect response for ${currentUrl} did not include a location header`, false);
5051
+ if (!followRedirects) throw new RedirectError(currentUrl, location, response.status);
5052
+ if (redirectCount >= MAX_REDIRECTS) throw new ScraperError(`Too many redirects while fetching ${source}`, false);
5053
+ const redirectUrl = new URL(location, currentUrl).href;
5054
+ await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
5055
+ currentUrl = redirectUrl;
5056
+ redirectCount += 1;
5057
+ continue;
5058
+ }
5059
+ const contentTypeHeader = response.headers["content-type"];
5060
+ const { mimeType, charset } = MimeTypeUtils.parseContentType(typeof contentTypeHeader === "string" ? contentTypeHeader : void 0);
5061
+ const rawContentEncoding = response.headers["content-encoding"];
5062
+ const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
5063
+ const finalUrl = response.request?.res?.responseUrl || response.request?.responseUrl || response.config?.url || currentUrl;
5064
+ await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
5065
+ if (options?.acceptsMimeType && !options.acceptsMimeType(mimeType)) {
5066
+ logger.debug(`Skipping ${finalUrl}: ${mimeType} is not processable`);
5067
+ return {
5068
+ content: Buffer.from(""),
5069
+ mimeType,
5070
+ charset,
5071
+ source: finalUrl,
5072
+ status: FetchStatus.SKIPPED
5073
+ };
5074
+ }
5075
+ const etag = response.headers.etag || response.headers.ETag;
5076
+ if (etag) logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
5077
+ const lastModified = response.headers["last-modified"];
5078
+ const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
5079
+ const content = await readStreamToBuffer(response.data, options?.signal);
5080
+ bodyConsumed = true;
5081
+ const challengeType = MimeTypeUtils.isHtml(mimeType) ? detectChallengePage(content) : null;
5082
+ if (challengeType) throw new ChallengeError(source, response.status, challengeType, currentUrl);
3253
5083
  return {
3254
- content: Buffer.from(""),
5084
+ content,
3255
5085
  mimeType,
3256
5086
  charset,
5087
+ encoding: contentEncoding,
3257
5088
  source: finalUrl,
3258
- status: FetchStatus.SKIPPED
5089
+ etag,
5090
+ lastModified: lastModifiedISO,
5091
+ status: FetchStatus.SUCCESS
3259
5092
  };
5093
+ } finally {
5094
+ if (!bodyConsumed) destroyStream(response.data);
3260
5095
  }
3261
- const etag = response.headers.etag || response.headers.ETag;
3262
- if (etag) logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
3263
- const lastModified = response.headers["last-modified"];
3264
- const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
3265
- const content = await readStreamToBuffer(response.data, options?.signal);
3266
- bodyConsumed = true;
3267
- const challengeType = MimeTypeUtils.isHtml(mimeType) ? detectChallengePage(content) : null;
3268
- if (challengeType) throw new ChallengeError(source, response.status, challengeType);
5096
+ }
5097
+ } catch (error) {
5098
+ if (error instanceof RedirectError || error instanceof ChallengeError) throw error;
5099
+ if (error instanceof ScraperError && !error.isRetryable) throw error;
5100
+ const axiosError = error;
5101
+ const status = axiosError.response?.status;
5102
+ const code = axiosError.code;
5103
+ const errorCause = error instanceof Error ? error : void 0;
5104
+ if (options?.signal?.aborted || code === "ERR_CANCELED") throw new CancellationError("HTTP fetch cancelled");
5105
+ if (status === 404) {
5106
+ logger.debug(`Resource not found (404): ${source}`);
3269
5107
  return {
3270
- content,
3271
- mimeType,
3272
- charset,
3273
- encoding: contentEncoding,
3274
- source: finalUrl,
3275
- etag,
3276
- lastModified: lastModifiedISO,
3277
- status: FetchStatus.SUCCESS
5108
+ content: Buffer.from(""),
5109
+ mimeType: "text/plain",
5110
+ source,
5111
+ status: FetchStatus.NOT_FOUND
3278
5112
  };
3279
- } finally {
3280
- if (!bodyConsumed) destroyStream(response.data);
3281
5113
  }
5114
+ if (!followRedirects && status && status >= 300 && status < 400) {
5115
+ const location = axiosError.response?.headers?.location;
5116
+ if (location) throw new RedirectError(source, location, status);
5117
+ }
5118
+ const retryAfterMs = parseRetryAfter(axiosError.response?.headers?.["retry-after"]);
5119
+ const throttleDelayMs = status === 429 || status === 503 && retryAfterMs !== void 0 ? this.hostBackoff.throttle(currentUrl, baseDelay * THROTTLE_DELAY_FACTOR, retryAfterMs) : void 0;
5120
+ if (status === 403 || status === 429) {
5121
+ const cfMitigated = axiosError.response?.headers?.["cf-mitigated"];
5122
+ const server = axiosError.response?.headers?.server;
5123
+ let responseBody = "";
5124
+ if (axiosError.response?.data) try {
5125
+ responseBody = (await readStreamToBuffer(axiosError.response.data)).toString("utf-8");
5126
+ } catch {}
5127
+ if (cfMitigated === "challenge" || status === 403 && server === "cloudflare" || responseBody.includes("Enable JavaScript and cookies to continue") || responseBody.includes("Just a moment...") || responseBody.includes("cf_chl_opt")) throw new ChallengeError(source, status, "cloudflare", currentUrl);
5128
+ }
5129
+ destroyStream(axiosError.response?.data);
5130
+ if (this.isTlsCertificateError(code)) throw new TlsCertificateError(source, code, errorCause);
5131
+ if (attempt < maxRetries && (status === void 0 || this.retryableStatusCodes.includes(status)) && !this.nonRetryableErrorCodes.includes(code ?? "")) {
5132
+ const delay = throttleDelayMs ?? baseDelay * 2 ** attempt;
5133
+ logger.warn(`⚠️ Attempt ${attempt + 1}/${maxRetries + 1} failed for ${source} (Status: ${status}, Code: ${code}). Retrying in ${delay}ms...`);
5134
+ if (throttleDelayMs === void 0) await this.delay(delay);
5135
+ continue;
5136
+ }
5137
+ const failureMessage = `Failed to fetch ${source} after ${attempt + 1} attempts: ${axiosError.message ?? "Unknown error"}`;
5138
+ throw status === void 0 ? new ScraperError(failureMessage, true, errorCause) : new HttpStatusError(failureMessage, true, status, errorCause, currentUrl);
3282
5139
  }
3283
- } catch (error) {
3284
- if (error instanceof RedirectError || error instanceof ChallengeError) throw error;
3285
- if (error instanceof ScraperError && !error.isRetryable) throw error;
3286
- const axiosError = error;
3287
- const status = axiosError.response?.status;
3288
- const code = axiosError.code;
3289
- const errorCause = error instanceof Error ? error : void 0;
3290
- if (options?.signal?.aborted || code === "ERR_CANCELED") throw new CancellationError("HTTP fetch cancelled");
3291
- if (status === 404) {
3292
- logger.debug(`Resource not found (404): ${source}`);
3293
- return {
3294
- content: Buffer.from(""),
3295
- mimeType: "text/plain",
3296
- source,
3297
- status: FetchStatus.NOT_FOUND
3298
- };
3299
- }
3300
- if (!followRedirects && status && status >= 300 && status < 400) {
3301
- const location = axiosError.response?.headers?.location;
3302
- if (location) throw new RedirectError(source, location, status);
3303
- }
3304
- if (status === 403) {
3305
- const cfMitigated = axiosError.response?.headers?.["cf-mitigated"];
3306
- const server = axiosError.response?.headers?.server;
3307
- let responseBody = "";
3308
- if (axiosError.response?.data) try {
3309
- responseBody = (await readStreamToBuffer(axiosError.response.data)).toString("utf-8");
3310
- } catch {}
3311
- if (cfMitigated === "challenge" || server === "cloudflare" || responseBody.includes("Enable JavaScript and cookies to continue") || responseBody.includes("Just a moment...") || responseBody.includes("cf_chl_opt")) throw new ChallengeError(source, status, "cloudflare");
3312
- }
3313
- destroyStream(axiosError.response?.data);
3314
- if (this.isTlsCertificateError(code)) throw new TlsCertificateError(source, code, errorCause);
3315
- if (attempt < maxRetries && (status === void 0 || this.retryableStatusCodes.includes(status)) && !this.nonRetryableErrorCodes.includes(code ?? "")) {
3316
- const delay = baseDelay * 2 ** attempt;
3317
- logger.warn(`⚠️ Attempt ${attempt + 1}/${maxRetries + 1} failed for ${source} (Status: ${status}, Code: ${code}). Retrying in ${delay}ms...`);
3318
- await this.delay(delay);
3319
- continue;
3320
- }
3321
- const failureMessage = `Failed to fetch ${source} after ${attempt + 1} attempts: ${axiosError.message ?? "Unknown error"}`;
3322
- throw status === void 0 ? new ScraperError(failureMessage, true, errorCause) : new HttpStatusError(failureMessage, true, status, errorCause);
3323
5140
  }
3324
5141
  throw new ScraperError(`Failed to fetch ${source} after ${maxRetries + 1} attempts`, true);
3325
5142
  }
@@ -3373,13 +5190,15 @@ var AutoDetectFetcher = class AutoDetectFetcher {
3373
5190
  httpFetcher;
3374
5191
  browserFetcher;
3375
5192
  fileFetcher;
5193
+ /** Pauses a host that throttled a request, for the browser fallback too. */
5194
+ hostBackoff = new HostBackoff();
3376
5195
  /**
3377
5196
  * @param scraperConfig - Scraper settings shared by all fetchers.
3378
5197
  * @param managedBrowser - The browser for the browser fallback; pass one to
3379
5198
  * share it with the HTML renderer.
3380
5199
  */
3381
5200
  constructor(scraperConfig, managedBrowser) {
3382
- this.httpFetcher = new HttpFetcher(scraperConfig);
5201
+ this.httpFetcher = new HttpFetcher(scraperConfig, this.hostBackoff);
3383
5202
  this.browserFetcher = new BrowserFetcher(scraperConfig, managedBrowser);
3384
5203
  this.fileFetcher = new FileFetcher(scraperConfig);
3385
5204
  }
@@ -3396,6 +5215,15 @@ var AutoDetectFetcher = class AutoDetectFetcher {
3396
5215
  return null;
3397
5216
  }
3398
5217
  /**
5218
+ * Returns the URL whose response caused a fetch failure.
5219
+ *
5220
+ * @param error The error the HTTP fetcher threw.
5221
+ * @returns The answering URL, or undefined when the error does not name one.
5222
+ */
5223
+ static responseUrl(error) {
5224
+ if (error instanceof ChallengeError || error instanceof HttpStatusError) return error.responseUrl;
5225
+ }
5226
+ /**
3399
5227
  * Check if this fetcher can handle the given source.
3400
5228
  * Returns true for any URL that any of the underlying fetchers can handle.
3401
5229
  */
@@ -3418,6 +5246,7 @@ var AutoDetectFetcher = class AutoDetectFetcher {
3418
5246
  const reason = AutoDetectFetcher.browserFallbackReason(error);
3419
5247
  if (reason) {
3420
5248
  logger.info(`🔄 ${reason} for ${source}, falling back to browser fetcher...`);
5249
+ for (const url of /* @__PURE__ */ new Set([source, AutoDetectFetcher.responseUrl(error)])) if (url) await this.hostBackoff.wait(url, options?.signal);
3421
5250
  return this.browserFetcher.fetch(source, options);
3422
5251
  }
3423
5252
  throw error;
@@ -6666,7 +8495,7 @@ function mergePlaywrightHeaders(requestHeaders, customHeaders, credentials, orig
6666
8495
  Authorization: `Basic ${basic}`
6667
8496
  };
6668
8497
  }
6669
- return withMarkdownPreferredAccept(headers, customHeaders);
8498
+ return headers;
6670
8499
  }
6671
8500
  // src/scraper/middleware/HtmlSanitizerMiddleware.ts
6672
8501
  /**
@@ -15186,6 +17015,212 @@ function registerGlobalOutputOptions(yargs) {
15186
17015
  function reportCliError(message) {
15187
17016
  logger.error(message);
15188
17017
  }
17018
+ // src/cli/utils.ts
17019
+ /**
17020
+ * Shared CLI utilities and helper functions.
17021
+ */
17022
+ /**
17023
+ * Retrieves the global EventBusService from the arguments context.
17024
+ * @param argv The parsed arguments context.
17025
+ * @returns The global EventBusService.
17026
+ * @throws Error if EventBusService is not initialized.
17027
+ */
17028
+ function getEventBus(argv) {
17029
+ const eventBus = argv._eventBus;
17030
+ if (!eventBus) throw new Error("EventBusService not initialized");
17031
+ return eventBus;
17032
+ }
17033
+ /**
17034
+ * Ensures a Chromium for scraping is installed, unless a system Chromium path
17035
+ * is set.
17036
+ *
17037
+ * Any Chromium `ManagedBrowser` launches without an explicit path counts: the
17038
+ * headless shell or the full build. When neither is there, the headless shell
17039
+ * is installed with the CLI of the Playwright this package depends on, so it
17040
+ * matches that version. The install leaves other browsers alone, since another
17041
+ * process may be running them.
17042
+ */
17043
+ function ensurePlaywrightBrowsersInstalled() {
17044
+ if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === "1") {
17045
+ logger.debug("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.");
17046
+ return;
17047
+ }
17048
+ const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
17049
+ if (chromiumEnvPath && existsSync(chromiumEnvPath)) {
17050
+ logger.debug(`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`);
17051
+ return;
17052
+ }
17053
+ if (ManagedBrowser.isPlaywrightChromiumInstalled()) return;
17054
+ const playwrightCli = path.join(path.dirname(createRequire(import.meta.url).resolve("playwright/package.json")), "cli.js");
17055
+ try {
17056
+ logger.info("🌐 Installing Playwright Chromium browser... (this may take a moment)");
17057
+ execFileSync(process.execPath, [
17058
+ playwrightCli,
17059
+ "install",
17060
+ "chromium-headless-shell",
17061
+ "--no-remove"
17062
+ ], { stdio: "ignore" });
17063
+ } catch (error) {
17064
+ logger.debug(String(error));
17065
+ logger.error(`❌ Failed to install Playwright browsers automatically. Please run:\n node "${playwrightCli}" install --with-deps chromium-headless-shell\nand try again.`);
17066
+ process.exit(1);
17067
+ }
17068
+ }
17069
+ /**
17070
+ * Resolves the protocol based on auto-detection or explicit specification.
17071
+ * Auto-detection uses TTY status to determine appropriate protocol.
17072
+ */
17073
+ function resolveProtocol(protocol) {
17074
+ if (protocol === "auto") {
17075
+ if (!process.stdin.isTTY && !process.stdout.isTTY) return "stdio";
17076
+ return "http";
17077
+ }
17078
+ if (protocol === "stdio" || protocol === "http") return protocol;
17079
+ throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);
17080
+ }
17081
+ /**
17082
+ * Validates and parses port number
17083
+ */
17084
+ function validatePort(portString) {
17085
+ const port = Number.parseInt(portString, 10);
17086
+ if (Number.isNaN(port) || port < 1 || port > 65535) throw new Error("Invalid port number");
17087
+ return port;
17088
+ }
17089
+ /**
17090
+ * Validates host string for basic format checking
17091
+ */
17092
+ function validateHost(hostString) {
17093
+ const trimmed = hostString.trim();
17094
+ if (!trimmed) throw new Error("Host cannot be empty");
17095
+ if (trimmed.includes(" ") || trimmed.includes(" ") || trimmed.includes("\n")) throw new Error("Host cannot contain whitespace");
17096
+ return trimmed;
17097
+ }
17098
+ /**
17099
+ * Creates AppServerConfig based on service requirements.
17100
+ *
17101
+ * AppConfig is the source of truth for host/auth/telemetry/read-only settings.
17102
+ * AppServerConfig only selects which services to run and which port to bind to.
17103
+ * Whether the server runs jobs itself or uses a worker follows from the backend.
17104
+ *
17105
+ * @param options Which services to run, the port, and startup details.
17106
+ * @returns The server configuration.
17107
+ */
17108
+ function createAppServerConfig(options) {
17109
+ return {
17110
+ enableWebInterface: options.enableWebInterface ?? false,
17111
+ enableMcpServer: options.enableMcpServer ?? true,
17112
+ enableApiServer: options.enableApiServer ?? false,
17113
+ port: options.port,
17114
+ showLogo: options.showLogo ?? true,
17115
+ startupContext: options.startupContext
17116
+ };
17117
+ }
17118
+ /**
17119
+ * Parses custom headers from CLI options
17120
+ */
17121
+ function parseHeaders(headerOptions) {
17122
+ const headers = {};
17123
+ if (Array.isArray(headerOptions)) for (const entry of headerOptions) {
17124
+ const idx = entry.indexOf(":");
17125
+ if (idx > 0) {
17126
+ const name = entry.slice(0, idx).trim();
17127
+ const value = entry.slice(idx + 1).trim();
17128
+ if (name) headers[name] = value;
17129
+ }
17130
+ }
17131
+ return headers;
17132
+ }
17133
+ /**
17134
+ * Check the auth settings for the transport a command serves. Authentication
17135
+ * applies to MCP over HTTP only. Over stdio the host launching the process is
17136
+ * the trust boundary, so auth settings are ignored with a warning on stderr,
17137
+ * which never carries protocol data.
17138
+ * @param auth - The loaded auth settings.
17139
+ * @param protocol - The resolved transport.
17140
+ * @param port - The HTTP port, for the plain-HTTP warning.
17141
+ * @throws Error when an auth setting over HTTP is malformed.
17142
+ */
17143
+ function checkAuthForProtocol(auth, protocol, port) {
17144
+ if (!auth.enabled) return;
17145
+ if (protocol === "stdio") {
17146
+ console.error("⚠️ Authentication does not apply to MCP over stdio; auth settings are ignored.");
17147
+ return;
17148
+ }
17149
+ validateAuthConfig(auth);
17150
+ warnHttpUsage(port);
17151
+ }
17152
+ /**
17153
+ * Validates the format of auth settings that are present. Whether a setting
17154
+ * is required depends on what the process serves, so the server checks that
17155
+ * at startup.
17156
+ */
17157
+ function validateAuthConfig(authConfig) {
17158
+ const errors = [];
17159
+ if (authConfig.issuerUrl) try {
17160
+ if (new URL(authConfig.issuerUrl).protocol !== "https:") errors.push("Issuer URL must use HTTPS protocol");
17161
+ } catch {
17162
+ errors.push("Issuer URL must be a valid URL");
17163
+ }
17164
+ if (authConfig.audience) try {
17165
+ const url = new URL(authConfig.audience);
17166
+ if (url.protocol === "http:" && url.hostname !== "localhost") logger.warn("⚠️ Audience uses HTTP protocol - consider using HTTPS for production");
17167
+ if (url.hash) errors.push("Audience must not contain URL fragments");
17168
+ } catch {
17169
+ if (authConfig.audience.startsWith("urn:")) {
17170
+ const urnParts = authConfig.audience.split(":");
17171
+ if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) errors.push("URN audience must follow format: urn:namespace:specific-string");
17172
+ } else errors.push("Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)");
17173
+ }
17174
+ if (errors.length > 0) throw new Error(`Auth configuration validation failed:\n${errors.join("\n")}`);
17175
+ }
17176
+ /**
17177
+ * Warns about HTTP usage in production when auth is enabled.
17178
+ */
17179
+ function warnHttpUsage(port) {
17180
+ if (!(process.env.NODE_ENV !== "production" || port === 6280 || process.env.HOSTNAME?.includes("localhost"))) logger.warn("⚠️ Authentication is enabled but running over HTTP in production. Consider using HTTPS for security.");
17181
+ }
17182
+ /**
17183
+ * Prompts the user interactively to confirm an embedding model change.
17184
+ * Returns true if the user confirms (y/Y), false otherwise.
17185
+ */
17186
+ function promptModelChangeConfirmation(change) {
17187
+ return new Promise((resolve) => {
17188
+ console.error(`\n⚠️ Embedding model change detected:\n Previous: ${describeEmbeddingModel(change.previousModel, change.previousDimension)}\n Current: ${describeEmbeddingModel(change.currentModel, change.currentDimension)}\n\n All existing embedding vectors will be invalidated.\n Libraries must be re-scraped to restore vector search.\n Full-text search will continue working for all existing documents.\n`);
17189
+ const rl = createInterface({
17190
+ input: process.stdin,
17191
+ output: process.stderr
17192
+ });
17193
+ rl.question(" Proceed with model change? (y/N) ", (answer) => {
17194
+ rl.close();
17195
+ resolve(answer.trim().toLowerCase() === "y");
17196
+ });
17197
+ });
17198
+ }
17199
+ /**
17200
+ * Handles EmbeddingModelChangedError during service initialization.
17201
+ *
17202
+ * - When accepted (`--accept-model-change` or `DOCS_MCP_ACCEPT_MODEL_CHANGE`):
17203
+ * resolves the model change (invalidates vectors) without asking.
17204
+ * - In non-interactive mode (no TTY): re-throws the error to fail startup.
17205
+ * - In interactive mode (TTY): prompts the user for confirmation, then either
17206
+ * resolves the model change or exits.
17207
+ *
17208
+ * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()
17209
+ * @param service The DocumentManagementService instance (already partially initialized)
17210
+ * @param acceptFlag The value of `--accept-model-change`; when omitted,
17211
+ * `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides
17212
+ * @throws Re-throws the error in non-interactive mode or if the user rejects the change
17213
+ */
17214
+ async function handleEmbeddingModelChange(error, service, acceptFlag) {
17215
+ if (acceptFlag ?? parseEnvBoolean(process.env.DOCS_MCP_ACCEPT_MODEL_CHANGE) ?? false) {
17216
+ logger.warn(`⚠️ Accepting embedding model change without a prompt: ${describeEmbeddingModel(error.previousModel, error.previousDimension)} → ${describeEmbeddingModel(error.currentModel, error.currentDimension)}`);
17217
+ await service.resolveModelChange();
17218
+ return;
17219
+ }
17220
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
17221
+ if (!await promptModelChangeConfirmation(error)) throw new Error("Embedding model change rejected. Startup aborted.\nRestore the previous embedding model configuration to continue without changes.");
17222
+ await service.resolveModelChange();
17223
+ }
15189
17224
  // src/cli/commands/compact.ts
15190
17225
  function createCompactCommand(cli) {
15191
17226
  cli.command("compact", "Reclaim unused space in the document store (exclusive lock; may block searches)", (yargs) => {
@@ -15254,11 +17289,10 @@ function createConfigCommand(cli) {
15254
17289
  process.exitCode = 1;
15255
17290
  return;
15256
17291
  }
15257
- const config = loadConfig(argv, {
17292
+ const value = getConfigValue(loadConfig(argv, {
15258
17293
  configPath: argv.config,
15259
17294
  searchDir: argv.storePath
15260
- });
15261
- const value = getConfigValue(config, path);
17295
+ }), path);
15262
17296
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
15263
17297
  renderScalarOutput(value, argv);
15264
17298
  return;
@@ -15285,11 +17319,10 @@ function createConfigCommand(cli) {
15285
17319
  process.exitCode = 1;
15286
17320
  return;
15287
17321
  }
15288
- const config = loadConfig(argv, {
17322
+ const currentValue = getConfigValue(loadConfig(argv, {
15289
17323
  configPath: argv.config,
15290
17324
  searchDir: argv.storePath
15291
- });
15292
- const currentValue = getConfigValue(config, path);
17325
+ }), path);
15293
17326
  if (currentValue !== void 0 && currentValue !== null && typeof currentValue === "object" && !Array.isArray(currentValue)) {
15294
17327
  reportCliError(`Error: Config path '${path}' refers to an object. Use a more specific leaf path to set a scalar value.`);
15295
17328
  reportCliError("Hint: Run 'docs-mcp-server config' to inspect the current structure.");
@@ -15874,7 +17907,7 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
15874
17907
  const server = new McpServer({
15875
17908
  name,
15876
17909
  ...title !== void 0 ? { title } : {},
15877
- version: "3.4.0"
17910
+ version: "3.4.1"
15878
17911
  }, {
15879
17912
  capabilities: {
15880
17913
  tools: {},
@@ -16983,7 +19016,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
16983
19016
  const mcpEnabled = Boolean(serverConfig.enableMcpServer);
16984
19017
  const authEnabled = Boolean(appConfig.auth.enabled);
16985
19018
  return {
16986
- version: "3.4.0",
19019
+ version: "3.4.1",
16987
19020
  readOnly: Boolean(appConfig.app.readOnly),
16988
19021
  telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
16989
19022
  services: {
@@ -17655,7 +19688,7 @@ var AppServer = class AppServer {
17655
19688
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
17656
19689
  if (telemetry.isEnabled()) {
17657
19690
  telemetry.setGlobalContext({
17658
- appVersion: "3.4.0",
19691
+ appVersion: "3.4.1",
17659
19692
  appPlatform: process.platform,
17660
19693
  appNodeVersion: process.version,
17661
19694
  appServicesEnabled: this.getActiveServicesList(),
@@ -18233,6 +20266,7 @@ function createFetchUrlCommand(cli) {
18233
20266
  configPath: argv.config,
18234
20267
  searchDir: argv.storePath
18235
20268
  });
20269
+ ensurePlaywrightBrowsersInstalled();
18236
20270
  renderTextOutput(await new FetchUrlTool(new AutoDetectFetcher(appConfig.scraper), appConfig).execute({
18237
20271
  url,
18238
20272
  followRedirects: argv.followRedirects,
@@ -18372,6 +20406,7 @@ function createMcpCommand(cli) {
18372
20406
  quiet: argv.quiet
18373
20407
  });
18374
20408
  checkAuthForProtocol(appConfig.auth, resolvedProtocol, appConfig.server.ports.mcp);
20409
+ ensurePlaywrightBrowsersInstalled();
18375
20410
  try {
18376
20411
  const serverUrl = argv.serverUrl;
18377
20412
  const backend = await openBackend({
@@ -18511,6 +20546,7 @@ function createRefreshCommand(cli) {
18511
20546
  configPath: argv.config,
18512
20547
  searchDir: argv.storePath
18513
20548
  });
20549
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
18514
20550
  const backend = await openBackend({
18515
20551
  serverUrl,
18516
20552
  eventBus: getEventBus(argv),
@@ -18710,6 +20746,7 @@ function createScrapeCommand(cli) {
18710
20746
  hasExcludePatterns: argv.excludePattern.length > 0,
18711
20747
  useServerUrl: !!serverUrl
18712
20748
  });
20749
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
18713
20750
  const backend = await openBackend({
18714
20751
  serverUrl,
18715
20752
  eventBus: getEventBus(argv),
@@ -18857,6 +20894,7 @@ function createWebCommand(cli) {
18857
20894
  configPath: argv.config,
18858
20895
  searchDir: argv.storePath
18859
20896
  });
20897
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
18860
20898
  try {
18861
20899
  const backend = await openBackend({
18862
20900
  appConfig,
@@ -19008,14 +21046,13 @@ function registerGlobalOptions(cli) {
19008
21046
  function createCli(argv) {
19009
21047
  let globalEventBus = null;
19010
21048
  const commandStartTimes = /* @__PURE__ */ new Map();
19011
- const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.4.0").middleware(async (argv) => {
21049
+ const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.4.1").middleware(async (argv) => {
19012
21050
  if (argv.verbose && argv.quiet) throw new Error("Arguments verbose and quiet are mutually exclusive");
19013
21051
  applyGlobalCliOutputMode({
19014
21052
  verbose: argv.verbose,
19015
21053
  quiet: argv.quiet
19016
21054
  });
19017
- const rawStorePath = argv.storePath || process.env.DOCS_MCP_STORE_PATH;
19018
- const resolvedStorePath = resolveStorePath(rawStorePath);
21055
+ const resolvedStorePath = resolveStorePath(argv.storePath || process.env.DOCS_MCP_STORE_PATH);
19019
21056
  argv.storePath = resolvedStorePath;
19020
21057
  const appConfig = loadConfig(argv, {
19021
21058
  configPath: argv.config,
@@ -19031,7 +21068,7 @@ function createCli(argv) {
19031
21068
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
19032
21069
  const commandName = argv._[0]?.toString() || "default";
19033
21070
  telemetry.setGlobalContext({
19034
- appVersion: "3.4.0",
21071
+ appVersion: "3.4.1",
19035
21072
  appPlatform: process.platform,
19036
21073
  appNodeVersion: process.version,
19037
21074
  appInterface: "cli",
@@ -19140,6 +21177,6 @@ async function runCli() {
19140
21177
  const appServer = getActiveAppServer();
19141
21178
  if (commandExecuted && !appServer) await cleanupCliCommand();
19142
21179
  }
19143
- export { cleanupCliCommand, runCli };
21180
+ export { runCli };
19144
21181
 
19145
- //# sourceMappingURL=main-BTCYUUTU.js.map
21182
+ //# sourceMappingURL=main-Cb6JaTXM.js.map