@arabold/docs-mcp-server 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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";
@@ -24,7 +26,7 @@ import { lookup } from "node:dns/promises";
24
26
  import fs$1, { readFile } from "node:fs/promises";
25
27
  import net, { BlockList, isIP } from "node:net";
26
28
  import os from "node:os";
27
- import { Minimatch, minimatch } from "minimatch";
29
+ import { Minimatch } from "minimatch";
28
30
  import { HeaderGenerator } from "header-generator";
29
31
  import { chromium } from "playwright";
30
32
  import https from "node:https";
@@ -44,18 +46,19 @@ 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";
51
53
  import yauzl from "yauzl";
52
54
  import Fuse from "fuse.js";
53
55
  import semver from "semver";
54
- import Database from "better-sqlite3";
55
56
  import * as sqliteVec from "sqlite-vec";
57
+ import Database from "better-sqlite3";
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,801 @@ 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 rename targets a library with an indexing job in flight.
274
+ * The rename is refused rather than letting the job keep writing under the old name.
275
+ */
276
+ var LibraryBusyError = class extends StoreError {
277
+ library;
278
+ activeStatuses;
279
+ constructor(library, activeStatuses) {
280
+ super(`Library ${escapeControlCharacters(library)} has an indexing job in flight (${activeStatuses.join(", ")}); retry the rename when it finishes. If no server or scrape command is indexing it anymore, the job was interrupted: starting the server resumes or fails it.`);
281
+ this.library = library;
282
+ this.activeStatuses = activeStatuses;
283
+ }
284
+ };
285
+ /**
286
+ * Error thrown when a specific version of a library cannot be found in the store.
287
+ * Includes the list of available versions for better context.
288
+ */
289
+ var VersionNotFoundInStoreError = class extends StoreError {
290
+ library;
291
+ version;
292
+ availableVersions;
293
+ constructor(library, version, availableVersions) {
294
+ let text = `${version ? `Version ${escapeControlCharacters(version)}` : "Version"} for library ${escapeControlCharacters(library)} not found in store.`;
295
+ if (availableVersions.length > 0) text += ` Available versions: ${availableVersions.map(escapeControlCharacters).join(", ")}`;
296
+ super(text);
297
+ this.library = library;
298
+ this.version = version;
299
+ this.availableVersions = availableVersions;
300
+ }
301
+ };
302
+ /**
303
+ * Error thrown when a request to create a new library finds that library already exists.
304
+ * Raised only for an explicit "Add library" request.
305
+ */
306
+ var LibraryAlreadyExistsError = class extends StoreError {
307
+ library;
308
+ constructor(library) {
309
+ super(`Library ${quoteName(library)} already exists. Open it to add a version.`);
310
+ this.library = library;
311
+ }
312
+ };
313
+ /**
314
+ * Error thrown when a scrape would clear an existing version without requesting replacement.
315
+ */
316
+ var VersionAlreadyExistsError = class extends StoreError {
317
+ library;
318
+ version;
319
+ constructor(library, version) {
320
+ const target = version ? `Version ${quoteName(version)} of library ${quoteName(library)}` : `Unversioned documentation for library ${quoteName(library)}`;
321
+ super(`${target} already exists. To rebuild it, scrape again with --replace (CLI) or replace: true (MCP), or refresh it to update in place.`);
322
+ this.library = library;
323
+ this.version = version;
324
+ }
325
+ };
326
+ /**
327
+ * Error thrown when a new library's name breaks a naming rule.
328
+ */
329
+ var InvalidLibraryNameError = class extends StoreError {
330
+ library;
331
+ reason;
332
+ constructor(library, reason) {
333
+ super(`Invalid library name ${quoteName(library)}: ${reason}.`);
334
+ this.library = library;
335
+ this.reason = reason;
336
+ }
337
+ };
338
+ /**
339
+ * Error thrown when a requested page cannot be found in the store for a library/version.
340
+ * Includes suggestions for similar page URLs if available.
341
+ */
342
+ var PageNotFoundInStoreError = class extends StoreError {
343
+ library;
344
+ version;
345
+ pathOrUrl;
346
+ suggestions;
347
+ constructor(library, version, pathOrUrl, suggestions = []) {
348
+ const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
349
+ let text = `Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} not found in store.`;
350
+ if (suggestions.length > 0) text += ` Did you mean: ${suggestions.map(escapeControlCharacters).join(", ")}?`;
351
+ super(text);
352
+ this.library = library;
353
+ this.version = version;
354
+ this.pathOrUrl = pathOrUrl;
355
+ this.suggestions = suggestions;
356
+ }
357
+ };
358
+ /**
359
+ * Error thrown when a page path matches more than one stored page.
360
+ * Lists the matching URLs so the caller can pass the full URL of the intended page.
361
+ */
362
+ var AmbiguousPageInStoreError = class extends StoreError {
363
+ library;
364
+ version;
365
+ pathOrUrl;
366
+ matches;
367
+ constructor(library, version, pathOrUrl, matches) {
368
+ const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
369
+ 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.`);
370
+ this.library = library;
371
+ this.version = version;
372
+ this.pathOrUrl = pathOrUrl;
373
+ this.matches = matches;
374
+ }
375
+ };
376
+ /**
377
+ * Error thrown when an embedding model's vector dimension exceeds the database's fixed dimension.
378
+ * This occurs when trying to use a model that produces vectors larger than the database can store.
379
+ */
380
+ var DimensionError = class extends StoreError {
381
+ modelName;
382
+ modelDimension;
383
+ dbDimension;
384
+ constructor(modelName, modelDimension, dbDimension) {
385
+ super(`Model "${modelName}" produces ${modelDimension}-dimensional vectors, which exceeds the database's fixed dimension of ${dbDimension}. Please use a model with dimension ≤ ${dbDimension}.`);
386
+ this.modelName = modelName;
387
+ this.modelDimension = modelDimension;
388
+ this.dbDimension = dbDimension;
389
+ }
390
+ };
391
+ /**
392
+ * Error thrown when there's a problem with database connectivity or operations.
393
+ */
394
+ var ConnectionError = class extends StoreError {};
395
+ /**
396
+ * Error thrown when better-sqlite3's compiled binary cannot load. The package
397
+ * ships Node-API binaries for Windows, macOS and Linux (glibc and musl) on x64
398
+ * and arm64, which load under every supported Node.js version and under Bun.
399
+ * On another platform or architecture no binary exists, and on a damaged
400
+ * install the system cannot load it, so the package has to be reinstalled or
401
+ * built from source.
402
+ */
403
+ var NativeModuleUnavailableError = class extends StoreError {
404
+ constructor() {
405
+ super(`The SQLite native module (better-sqlite3) could not load on ${process.platform}-${process.arch}, so the database cannot open. better-sqlite3 ships prebuilt binaries for Windows, macOS and Linux on x64 and arm64. On one of those, reinstall the package. On another platform, build it from source with node-gyp: https://github.com/WiseLibs/better-sqlite3/blob/master/docs/compilation.md`);
406
+ }
407
+ };
408
+ /**
409
+ * Error thrown when the runtime provides an older Node-API version than
410
+ * better-sqlite3's binaries need. Node.js 22.0 to 22.13 provide Node-API 9,
411
+ * and loading the binary there crashes the process instead of throwing.
412
+ */
413
+ var NodeApiUnsupportedError = class extends StoreError {
414
+ available;
415
+ required;
416
+ constructor(available, required) {
417
+ super(`The SQLite native module (better-sqlite3) needs Node-API ${required}, but this runtime provides Node-API ${escapeControlCharacters(available)}, so the database cannot open. Update Node.js to 22.14 or later.`);
418
+ this.available = available;
419
+ this.required = required;
420
+ }
421
+ };
422
+ /**
423
+ * Tells whether an error means better-sqlite3's compiled binary failed to
424
+ * load: no binary exists for the platform, or the system could not load it.
425
+ * Node.js and Bun both report the path of the binary, which is either a
426
+ * compiled `build/Release/better_sqlite3.node` or a prebuilt
427
+ * `prebuilds/<platform>-<arch>.node` inside the package.
428
+ *
429
+ * @param error - The error thrown while opening the database
430
+ * @returns True when the error is about the binary
431
+ */
432
+ function isNativeModuleError(error) {
433
+ if (!(error instanceof Error) || !("code" in error)) return false;
434
+ return (error.code === "MODULE_NOT_FOUND" || error.code === "ERR_DLOPEN_FAILED") && /better-sqlite3[\\/](?:build|prebuilds)[\\/][^'"\s]*\.node/.test(error.message);
435
+ }
436
+ /**
437
+ * Error thrown when the embedding provider fails to embed a page's chunks.
438
+ * Nothing of the page is written when this is thrown.
439
+ */
440
+ var EmbeddingError = class extends ConnectionError {};
441
+ /**
442
+ * Names an embedding model with its vector dimension for model-change messages.
443
+ * @param model - The model specification.
444
+ * @param dimension - The vector dimension, or null when it is not known.
445
+ * @returns The model, followed by its dimension when known.
446
+ */
447
+ function describeEmbeddingModel(model, dimension) {
448
+ return dimension === null ? model : `${model} (${dimension} dimensions)`;
449
+ }
450
+ /**
451
+ * Error thrown when the configured embedding model or vector dimension differs from the
452
+ * values stored in the database metadata. This indicates that existing vectors are
453
+ * incompatible with the new configuration and must be invalidated before proceeding.
454
+ *
455
+ * The CLI layer catches this error to accept the change when `--accept-model-change`
456
+ * is set, prompt the user interactively (TTY), or fail startup entirely
457
+ * (non-interactive/MCP/stdio mode). A dimension is null when it is not known.
458
+ */
459
+ var EmbeddingModelChangedError = class extends StoreError {
460
+ previousModel;
461
+ previousDimension;
462
+ currentModel;
463
+ currentDimension;
464
+ constructor(previousModel, previousDimension, currentModel, currentDimension) {
465
+ 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.`);
466
+ this.previousModel = previousModel;
467
+ this.previousDimension = previousDimension;
468
+ this.currentModel = currentModel;
469
+ this.currentDimension = currentDimension;
470
+ }
471
+ };
472
+ /**
473
+ * Error thrown when required credentials for an embedding provider are missing.
474
+ * This allows the system to gracefully degrade to FTS-only search when vectorization is unavailable.
475
+ */
476
+ var MissingCredentialsError = class extends StoreError {
477
+ provider;
478
+ constructor(provider, missingCredentials) {
479
+ super(`Missing credentials for ${provider} embedding provider. Required: ${missingCredentials.join(", ")}`);
480
+ this.provider = provider;
481
+ }
482
+ };
483
+ // src/store/embeddings/EmbeddingConfig.ts
484
+ /**
485
+ * Shared embedding model configuration service.
486
+ * Provides synchronous parsing of embedding model configuration and known dimensions lookup.
487
+ * Eliminates code duplication between DocumentStore and telemetry systems.
488
+ *
489
+ * All model lookups are case-insensitive to handle variations in model name capitalization.
490
+ * Uses class-based approach to avoid mutable global state and improve testability.
491
+ */
492
+ /**
493
+ * The complete set of provider prefixes recognized in a model specification.
494
+ * Anything else before the first colon is part of the model name itself.
495
+ *
496
+ * This list is normative rather than descriptive: it decides which prefixes claim
497
+ * the provider slot, so adding an entry changes how existing specifications parse.
498
+ * A model literally named `<new-provider>:<tag>` served by an OpenAI-compatible
499
+ * endpoint would start resolving to the new provider, breaking that configuration
500
+ * on upgrade. Call provider additions out in the release notes.
501
+ *
502
+ * `EmbeddingProvider` is derived from this array so the two cannot drift apart.
503
+ */
504
+ var SUPPORTED_PROVIDERS = [
505
+ "openai",
506
+ "vertex",
507
+ "gemini",
508
+ "aws",
509
+ "microsoft"
510
+ ];
511
+ /**
512
+ * Split a model specification into its provider prefix and model name.
513
+ *
514
+ * Only a prefix that names a supported provider is treated as a provider, matched
515
+ * case-insensitively and resolved to its canonical lowercase form. Every other
516
+ * specification is an OpenAI-compatible model name, which keeps names that carry a
517
+ * tag or quantization suffix intact (e.g. "nomic-embed-text:latest" or
518
+ * "second-state/jina-embeddings-v3-GGUF:Q4_K_M").
519
+ *
520
+ * @param spec The full model specification.
521
+ * @returns The resolved provider and model name.
522
+ */
523
+ function splitModelSpec(spec) {
524
+ const colonIndex = spec.indexOf(":");
525
+ const prefix = spec.substring(0, colonIndex).toLowerCase();
526
+ const provider = colonIndex === -1 ? void 0 : SUPPORTED_PROVIDERS.find((name) => name === prefix);
527
+ return provider ? {
528
+ provider,
529
+ model: spec.substring(colonIndex + 1)
530
+ } : {
531
+ provider: "openai",
532
+ model: spec
533
+ };
534
+ }
535
+ /**
536
+ * Embedding configuration manager that handles model parsing and dimension caching.
537
+ * Encapsulates state to avoid global variable issues and improve testability.
538
+ */
539
+ var EmbeddingConfig = class EmbeddingConfig {
540
+ static instance = null;
541
+ /**
542
+ * Get the singleton instance of EmbeddingConfig.
543
+ * Creates the instance if it doesn't exist.
544
+ */
545
+ static getInstance() {
546
+ if (EmbeddingConfig.instance === null) EmbeddingConfig.instance = new EmbeddingConfig();
547
+ return EmbeddingConfig.instance;
548
+ }
549
+ /**
550
+ * Reset the singleton instance (useful for testing).
551
+ */
552
+ static resetInstance() {
553
+ EmbeddingConfig.instance = null;
554
+ }
555
+ /**
556
+ * Known dimensions for common embedding models.
557
+ * This avoids expensive API calls for dimension detection in telemetry.
558
+ *
559
+ * Note: The "openai" provider also supports OpenAI-compatible APIs like:
560
+ * - Ollama (local models)
561
+ * - LMStudio (local models)
562
+ * - Any service implementing OpenAI's embedding API
563
+ */
564
+ knownModelDimensions = {
565
+ "text-embedding-3-small": 1536,
566
+ "text-embedding-3-large": 3072,
567
+ "text-embedding-ada-002": 1536,
568
+ "text-embedding-004": 768,
569
+ "text-embedding-005": 768,
570
+ "textembedding-gecko@003": 768,
571
+ "textembedding-gecko@002": 768,
572
+ "textembedding-gecko@001": 768,
573
+ "text-embedding-preview-0409": 768,
574
+ "embedding-001": 768,
575
+ "gemini-embedding-2-preview": 3072,
576
+ "amazon.titan-embed-text-v1": 1536,
577
+ "amazon.titan-embed-text-v2:0": 1024,
578
+ "amazon.titan-embed-image-v1": 1024,
579
+ "cohere.embed-english-v3": 1024,
580
+ "cohere.embed-multilingual-v3": 1024,
581
+ "Cohere/Cohere-embed-v4.0": 1536,
582
+ "embed-v4.0": 1536,
583
+ "intfloat/multilingual-e5-large": 1024,
584
+ "multilingual-e5-large": 1024,
585
+ "text-embedding-multilingual-e5-large": 1024,
586
+ "sentence-transformers/all-MiniLM-L6-v2": 384,
587
+ "gemini-embedding-001": 3072,
588
+ "Qwen/Qwen3-Embedding-8B": 4096,
589
+ "Qwen/Qwen3-Embedding-4B": 2560,
590
+ "Qwen/Qwen3-Embedding-0.6B": 1024,
591
+ "Linq-AI-Research/Linq-Embed-Mistral": 4096,
592
+ "Alibaba-NLP/gte-Qwen2-7B-instruct": 3584,
593
+ "intfloat/multilingual-e5-large-instruct": 1024,
594
+ "Salesforce/SFR-Embedding-Mistral": 4096,
595
+ "text-multilingual-embedding-002": 768,
596
+ "GritLM/GritLM-7B": 4096,
597
+ "GritLM/GritLM-8x7B": 4096,
598
+ "intfloat/e5-mistral-7b-instruct": 4096,
599
+ "Cohere/Cohere-embed-multilingual-v3.0": 1024,
600
+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct": 8960,
601
+ "Lajavaness/bilingual-embedding-large": 1024,
602
+ "Salesforce/SFR-Embedding-2_R": 4096,
603
+ "NovaSearch/stella_en_1.5B_v5": 8960,
604
+ "NovaSearch/jasper_en_vision_language_v1": 8960,
605
+ "nvidia/NV-Embed-v2": 4096,
606
+ "OrdalieTech/Solon-embeddings-large-0.1": 1024,
607
+ "BAAI/bge-m3": 1024,
608
+ "HIT-TMG/KaLM-embedding-multilingual-mini-v1": 896,
609
+ "jinaai/jina-embeddings-v3": 1024,
610
+ "Alibaba-NLP/gte-multilingual-base": 768,
611
+ "Lajavaness/bilingual-embedding-base": 768,
612
+ "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1": 896,
613
+ "nvidia/NV-Embed-v1": 4096,
614
+ "Cohere/Cohere-embed-multilingual-light-v3.0": 384,
615
+ "manu/bge-m3-custom-fr": 1024,
616
+ "Lajavaness/bilingual-embedding-small": 384,
617
+ "Snowflake/snowflake-arctic-embed-l-v2.0": 1024,
618
+ "intfloat/multilingual-e5-base": 768,
619
+ "voyage-3-lite": 512,
620
+ "voyage-3": 1024,
621
+ "voyage-3-large": 1024,
622
+ "voyage-3.5": 1024,
623
+ "voyage-4": 1024,
624
+ "voyage-4-large": 1024,
625
+ "voyage-4-lite": 1024,
626
+ "voyage-code-3": 1024,
627
+ "intfloat/multilingual-e5-small": 384,
628
+ "Alibaba-NLP/gte-Qwen1.5-7B-instruct": 4096,
629
+ "Snowflake/snowflake-arctic-embed-m-v2.0": 768,
630
+ "deepvk/USER-bge-m3": 1024,
631
+ "Cohere/Cohere-embed-english-v3.0": 1024,
632
+ "Omartificial-Intelligence-Space/Arabic-labse-Matryoshka": 768,
633
+ "ibm-granite/granite-embedding-278m-multilingual": 768,
634
+ "NovaSearch/stella_en_400M_v5": 4096,
635
+ "omarelshehy/arabic-english-sts-matryoshka": 1024,
636
+ "sentence-transformers/paraphrase-multilingual-mpnet-base-v2": 768,
637
+ "Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka": 768,
638
+ "Haon-Chen/speed-embedding-7b-instruct": 4096,
639
+ "sentence-transformers/LaBSE": 768,
640
+ "WhereIsAI/UAE-Large-V1": 1024,
641
+ "ibm-granite/granite-embedding-107m-multilingual": 384,
642
+ "mixedbread-ai/mxbai-embed-large-v1": 1024,
643
+ "intfloat/e5-large-v2": 1024,
644
+ "avsolatorio/GIST-large-Embedding-v0": 1024,
645
+ "sdadas/mmlw-e5-large": 1024,
646
+ "nomic-ai/nomic-embed-text-v1": 768,
647
+ "nomic-embed-text-v1": 768,
648
+ "nomic-ai/nomic-embed-text-v1-ablated": 768,
649
+ "nomic-ai/nomic-embed-text-v2-moe": 768,
650
+ "nomic-ai/modernbert-embed-base": 768,
651
+ "nomic-ai/nomic-embed-code": 3584,
652
+ "intfloat/e5-base-v2": 768,
653
+ "BAAI/bge-large-en-v1.5": 1024,
654
+ "intfloat/e5-large": 1024,
655
+ "Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet": 384,
656
+ "Cohere/Cohere-embed-english-light-v3.0": 384,
657
+ "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2": 768,
658
+ "Gameselo/STS-multilingual-mpnet-base-v2": 768,
659
+ "thenlper/gte-large": 1024,
660
+ "avsolatorio/GIST-Embedding-v0": 768,
661
+ "nomic-ai/nomic-embed-text-v1-unsupervised": 768,
662
+ "infgrad/stella-base-en-v2": 768,
663
+ "avsolatorio/NoInstruct-small-Embedding-v0": 384,
664
+ "dwzhu/e5-base-4k": 768,
665
+ "sdadas/mmlw-e5-base": 768,
666
+ "voyage-multilingual-2": 1024,
667
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised": 4096,
668
+ "BAAI/bge-base-en-v1.5": 768,
669
+ "avsolatorio/GIST-small-Embedding-v0": 384,
670
+ "sdadas/mmlw-roberta-large": 1024,
671
+ "nomic-ai/nomic-embed-text-v1.5": 768,
672
+ "nomic-embed-text-v1.5": 768,
673
+ "text-embedding-nomic-embed-text-v1.5": 768,
674
+ "minishlab/potion-multilingual-128M": 256,
675
+ "shibing624/text2vec-base-multilingual": 384,
676
+ "thenlper/gte-base": 768,
677
+ "intfloat/e5-small-v2": 384,
678
+ "intfloat/e5-base": 768,
679
+ "sentence-transformers/static-similarity-mrl-multilingual-v1": 1024,
680
+ "manu/sentence_croissant_alpha_v0.3": 2048,
681
+ "BAAI/bge-small-en-v1.5": 512,
682
+ "thenlper/gte-small": 384,
683
+ "sdadas/mmlw-e5-small": 384,
684
+ "manu/sentence_croissant_alpha_v0.4": 2048,
685
+ "manu/sentence_croissant_alpha_v0.2": 2048,
686
+ "abhinand/MedEmbed-small-v0.1": 384,
687
+ "ibm-granite/granite-embedding-125m-english": 768,
688
+ "intfloat/e5-small": 384,
689
+ "voyage-large-2-instruct": 1024,
690
+ "sdadas/mmlw-roberta-base": 768,
691
+ "Snowflake/snowflake-arctic-embed-l": 1024,
692
+ "Mihaiii/Ivysaur": 384,
693
+ "Snowflake/snowflake-arctic-embed-m-long": 768,
694
+ "bigscience/sgpt-bloom-7b1-msmarco": 4096,
695
+ "avsolatorio/GIST-all-MiniLM-L6-v2": 384,
696
+ "sergeyzh/LaBSE-ru-turbo": 768,
697
+ "sentence-transformers/all-mpnet-base-v2": 768,
698
+ "Snowflake/snowflake-arctic-embed-m": 768,
699
+ "Snowflake/snowflake-arctic-embed-s": 384,
700
+ "sentence-transformers/all-MiniLM-L12-v2": 384,
701
+ "Mihaiii/gte-micro-v4": 384,
702
+ "Snowflake/snowflake-arctic-embed-m-v1.5": 768,
703
+ "cointegrated/LaBSE-en-ru": 768,
704
+ "Mihaiii/Bulbasaur": 384,
705
+ "ibm-granite/granite-embedding-30m-english": 384,
706
+ "deepfile/embedder-100p": 768,
707
+ "Jaume/gemma-2b-embeddings": 2048,
708
+ "OrlikB/KartonBERT-USE-base-v1": 768,
709
+ "izhx/udever-bloom-7b1": 4096,
710
+ "izhx/udever-bloom-1b1": 1024,
711
+ "brahmairesearch/slx-v0.1": 384,
712
+ "Mihaiii/Wartortle": 384,
713
+ "izhx/udever-bloom-3b": 2048,
714
+ "deepvk/USER-base": 768,
715
+ "ai-forever/ru-en-RoSBERTa": 1024,
716
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse": 4096,
717
+ "Mihaiii/Venusaur": 384,
718
+ "Snowflake/snowflake-arctic-embed-xs": 384,
719
+ "jinaai/jina-embedding-b-en-v1": 768,
720
+ "Mihaiii/gte-micro": 384,
721
+ "aari1995/German_Semantic_STS_V2": 1024,
722
+ "Mihaiii/Squirtle": 384,
723
+ "OrlikB/st-polish-kartonberta-base-alpha-v1": 768,
724
+ "sergeyzh/rubert-tiny-turbo": 312,
725
+ "minishlab/potion-base-8M": 256,
726
+ "minishlab/M2V_base_glove_subword": 256,
727
+ "jinaai/jina-embedding-s-en-v1": 512,
728
+ "minishlab/potion-base-4M": 128,
729
+ "minishlab/M2V_base_output": 256,
730
+ "DeepPavlov/rubert-base-cased-sentence": 768,
731
+ "jinaai/jina-embeddings-v2-small-en": 512,
732
+ "cointegrated/rubert-tiny2": 312,
733
+ "minishlab/M2V_base_glove": 256,
734
+ "cointegrated/rubert-tiny": 312,
735
+ "silma-ai/silma-embeddding-matryoshka-v0.1": 768,
736
+ "DeepPavlov/rubert-base-cased": 768,
737
+ "Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet": 768,
738
+ "izhx/udever-bloom-560m": 1024,
739
+ "minishlab/potion-base-2M": 64,
740
+ "DeepPavlov/distilrubert-small-cased-conversational": 768,
741
+ "consciousAI/cai-lunaris-text-embeddings": 1024,
742
+ "deepvk/deberta-v1-base": 768,
743
+ "Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka": 768,
744
+ "Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka": 768,
745
+ "ai-forever/sbert_large_mt_nlu_ru": 1024,
746
+ "ai-forever/sbert_large_nlu_ru": 1024,
747
+ "malenia1/ternary-weight-embedding": 1024,
748
+ "jinaai/jina-embeddings-v2-base-en": 768,
749
+ "VPLabs/SearchMap_Preview": 4096,
750
+ "Hum-Works/lodestone-base-4096-v1": 768,
751
+ "jinaai/jina-embeddings-v4": 2048
752
+ };
753
+ runtimeDetectedDimensionModels = /* @__PURE__ */ new Set([
754
+ "novasearch/stella_en_1.5b_v5",
755
+ "stella_en_1.5b_v5",
756
+ "novasearch/stella_en_400m_v5",
757
+ "dunzhang/stella_en_400m_v5",
758
+ "stella_en_400m_v5",
759
+ "novasearch/jasper_en_vision_language_v1",
760
+ "jasper_en_vision_language_v1"
761
+ ]);
762
+ /**
763
+ * Lowercase lookup map for case-insensitive model dimension queries.
764
+ * Built lazily from knownModelDimensions to ensure consistency.
765
+ */
766
+ modelLookup;
767
+ constructor() {
768
+ this.modelLookup = /* @__PURE__ */ new Map();
769
+ for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) this.modelLookup.set(model.toLowerCase(), dimensions);
770
+ }
771
+ /**
772
+ * Build the lookup keys to try for a model name, most specific first:
773
+ * the name itself, then with the namespace dropped, the tag dropped, and both.
774
+ *
775
+ * Dropping a trailing tag lets a quantized or tagged variant reuse the base
776
+ * model's dimensions (e.g. "nomic-ai/nomic-embed-text-v2-moe:latest"), which
777
+ * quantization does not change. Exact matches are tried first, so names whose
778
+ * own identifier contains a colon (e.g. "amazon.titan-embed-text-v2:0") still
779
+ * resolve to their own entry.
780
+ */
781
+ dimensionLookupKeys(normalized) {
782
+ const slashIndex = normalized.lastIndexOf("/");
783
+ const withoutNamespace = slashIndex > -1 ? normalized.substring(slashIndex + 1) : void 0;
784
+ const bases = withoutNamespace ? [normalized, withoutNamespace] : [normalized];
785
+ const withoutTag = (key) => {
786
+ const colonIndex = key.lastIndexOf(":");
787
+ return colonIndex > 0 ? [key.substring(0, colonIndex)] : [];
788
+ };
789
+ return [...bases, ...bases.flatMap(withoutTag)];
790
+ }
791
+ findKnownDimension(model) {
792
+ for (const key of this.dimensionLookupKeys(model.toLowerCase())) {
793
+ if (this.runtimeDetectedDimensionModels.has(key)) return null;
794
+ const dimensions = this.modelLookup?.get(key);
795
+ if (dimensions !== void 0) return dimensions;
796
+ }
797
+ return null;
798
+ }
799
+ /**
800
+ * Parse embedding model configuration from a provided model specification.
801
+ * This is a synchronous operation that extracts provider, model, and known dimensions.
802
+ *
803
+ * Supports various providers:
804
+ * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)
805
+ * - vertex: Google Cloud Vertex AI
806
+ * - gemini: Google Generative AI
807
+ * - aws: AWS Bedrock models
808
+ * - microsoft: Azure OpenAI
809
+ *
810
+ * @param modelSpec Model specification (e.g., "openai:text-embedding-3-small"), defaults to "text-embedding-3-small"
811
+ * @returns Parsed embedding model configuration
812
+ */
813
+ parse(modelSpec) {
814
+ const spec = normalizeEnvValue(modelSpec || "text-embedding-3-small");
815
+ const { provider, model } = splitModelSpec(spec);
816
+ return {
817
+ provider,
818
+ model,
819
+ dimensions: this.findKnownDimension(model),
820
+ modelSpec: spec
821
+ };
822
+ }
823
+ /**
824
+ * Get the known dimensions for a specific model.
825
+ * Returns null if the model dimensions are not known.
826
+ * Uses case-insensitive lookup.
827
+ *
828
+ * @param model The model name (e.g., "text-embedding-3-small")
829
+ * @returns Known dimensions or null
830
+ */
831
+ getKnownDimensions(model) {
832
+ return this.findKnownDimension(model);
833
+ }
834
+ /**
835
+ * Add or update known dimensions for a model.
836
+ * This can be used to cache discovered dimensions.
837
+ * Stores both original case and lowercase for consistent lookup.
838
+ *
839
+ * @param model The model name
840
+ * @param dimensions The dimensions to cache
841
+ */
842
+ setKnownDimensions(model, dimensions) {
843
+ this.knownModelDimensions[model] = dimensions;
844
+ if (this.modelLookup) this.modelLookup.set(model.toLowerCase(), dimensions);
845
+ }
846
+ /**
847
+ * Static method to parse embedding model configuration using the singleton instance.
848
+ * This maintains backward compatibility while using the class-based approach.
849
+ */
850
+ static parseEmbeddingConfig(modelSpec) {
851
+ return EmbeddingConfig.getInstance().parse(modelSpec);
852
+ }
853
+ /**
854
+ * Static method to get known model dimensions using the singleton instance.
855
+ * This maintains backward compatibility while using the class-based approach.
856
+ */
857
+ static getKnownModelDimensions(model) {
858
+ return EmbeddingConfig.getInstance().getKnownDimensions(model);
859
+ }
860
+ /**
861
+ * Static method to set known model dimensions using the singleton instance.
862
+ * This maintains backward compatibility while using the class-based approach.
863
+ */
864
+ static setKnownModelDimensions(model, dimensions) {
865
+ EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);
866
+ }
867
+ };
70
868
  // src/store/embeddings/FixedDimensionEmbeddings.ts
71
869
  /**
72
870
  * Wrapper around an Embeddings implementation that ensures vectors have a fixed dimension.
@@ -349,6 +1147,56 @@ function sanitizeErrorForTracking(error) {
349
1147
  sanitized.stack = [`${error.name}: ${message}`, ...frames].join("\n");
350
1148
  return sanitized;
351
1149
  }
1150
+ // src/utils/paths.ts
1151
+ var projectRoot = null;
1152
+ /**
1153
+ * Finds the project root directory by searching upwards from the current file
1154
+ * for a directory containing 'package.json'. Caches the result.
1155
+ *
1156
+ * @returns {string} The absolute path to the project root.
1157
+ * @throws {Error} If package.json cannot be found.
1158
+ */
1159
+ function getProjectRoot() {
1160
+ if (projectRoot) return projectRoot;
1161
+ const currentFilePath = fileURLToPath(import.meta.url);
1162
+ let currentDir = path.dirname(currentFilePath);
1163
+ while (true) {
1164
+ const packageJsonPath = path.join(currentDir, "package.json");
1165
+ if (fs.existsSync(packageJsonPath)) {
1166
+ projectRoot = currentDir;
1167
+ return currentDir;
1168
+ }
1169
+ const parentDir = path.dirname(currentDir);
1170
+ if (parentDir === currentDir) throw new Error("Could not find project root containing package.json.");
1171
+ currentDir = parentDir;
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Resolves the data storage path using the following priority:
1176
+ * 1. Provided storePath parameter
1177
+ * 2. Legacy .store directory in project root (if exists)
1178
+ * 3. Standard system data directory using env-paths
1179
+ *
1180
+ * @param storePath Optional custom storage path
1181
+ * @returns Resolved absolute path for data storage
1182
+ */
1183
+ function resolveStorePath(storePath) {
1184
+ let dbDir;
1185
+ if (storePath) dbDir = path.resolve(storePath);
1186
+ else {
1187
+ const projectRoot = getProjectRoot();
1188
+ const oldDbDir = path.join(projectRoot, ".store");
1189
+ const oldDbPath = path.join(oldDbDir, "documents.db");
1190
+ if (fs.existsSync(oldDbPath)) dbDir = oldDbDir;
1191
+ else dbDir = envPaths("docs-mcp-server", { suffix: "" }).data;
1192
+ }
1193
+ try {
1194
+ fs.mkdirSync(dbDir, { recursive: true });
1195
+ } catch (error) {
1196
+ logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);
1197
+ }
1198
+ return dbDir;
1199
+ }
352
1200
  // src/telemetry/TelemetryConfig.ts
353
1201
  /**
354
1202
  * Telemetry configuration management for enabling/disabling analytics collection.
@@ -764,28 +1612,861 @@ var EventBusService = class {
764
1612
  this.emitter = new EventEmitter();
765
1613
  this.emitter.setMaxListeners(100);
766
1614
  }
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);
1615
+ /**
1616
+ * Emit an event to all subscribers.
1617
+ */
1618
+ emit(eventType, payload) {
1619
+ logger.debug(`Event emitted: ${eventType}`);
1620
+ this.emitter.emit(eventType, payload);
1621
+ }
1622
+ /**
1623
+ * Subscribe to events of a specific type.
1624
+ * Returns an unsubscribe function.
1625
+ */
1626
+ on(eventType, listener) {
1627
+ this.emitter.on(eventType, listener);
1628
+ return () => this.emitter.off(eventType, listener);
1629
+ }
1630
+ /**
1631
+ * Remove a specific listener.
1632
+ */
1633
+ off(eventType, listener) {
1634
+ this.emitter.off(eventType, listener);
1635
+ }
1636
+ };
1637
+ // src/utils/serverOrigin.ts
1638
+ /**
1639
+ * Normalize a configured origin (`scheme://host[:port]`) into its canonical form.
1640
+ *
1641
+ * Empty strings are treated as absent so container environments can leave the
1642
+ * variable declared but unset.
1643
+ *
1644
+ * @param origin - The configured value.
1645
+ * @param settingName - The setting named in error messages.
1646
+ * @returns The canonical origin, or `undefined` when absent.
1647
+ * @throws Error naming the setting when the value is not an HTTP(S) origin.
1648
+ */
1649
+ function normalizePublicOrigin(origin, settingName = "server.publicOrigin") {
1650
+ const configured = parseConfiguredUrl(origin, settingName, "origin without path, query, or fragment");
1651
+ if (!configured) return;
1652
+ const { parsed } = configured;
1653
+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) throw new Error(`${settingName} must not include a path, query string, or fragment.`);
1654
+ return parsed.origin;
1655
+ }
1656
+ /**
1657
+ * First path segments of the server's own root routes, plus `oauth` for the
1658
+ * removed OAuth proxy endpoints. A public URL must not start with one:
1659
+ * stripping such a base path from a request the proxy already stripped would
1660
+ * remove the route itself (`/mcp` under a base path of `/mcp` would become
1661
+ * `/`). These paths also never fall back to the web UI, so clients probing the
1662
+ * removed endpoints get a clean 404 instead of an HTML page.
1663
+ */
1664
+ var RESERVED_ROOT_SEGMENTS = [
1665
+ "mcp",
1666
+ "api",
1667
+ "assets",
1668
+ ".well-known",
1669
+ "sse",
1670
+ "messages",
1671
+ "oauth"
1672
+ ];
1673
+ /**
1674
+ * Normalize a configured public URL: an absolute HTTP(S) URL that may carry a
1675
+ * path, returned without a trailing slash.
1676
+ *
1677
+ * Empty strings are treated as absent so container environments can leave the
1678
+ * variable declared but unset.
1679
+ *
1680
+ * @param value - The configured `server.publicUrl` value.
1681
+ * @returns The canonical URL (e.g. `https://example.com/docs`), or `undefined` when absent.
1682
+ * @throws Error naming `server.publicUrl` when the value has credentials, a query
1683
+ * string, a fragment, a non-HTTP(S) protocol, an empty path segment (`//`),
1684
+ * or a first path segment that collides with a route or file the server
1685
+ * serves at its root.
1686
+ */
1687
+ function normalizePublicUrl(value) {
1688
+ const configured = parseConfiguredUrl(value, "server.publicUrl", "URL without query string or fragment");
1689
+ if (!configured) return;
1690
+ const { parsed, trimmed } = configured;
1691
+ if (trimmed.includes("?") || trimmed.includes("#")) throw new Error("server.publicUrl must not include a query string or fragment.");
1692
+ if (parsed.pathname.includes("//")) throw new Error(`server.publicUrl path must not contain an empty segment ("//"): "${parsed.pathname}".`);
1693
+ const path = parsed.pathname.replace(/\/$/, "");
1694
+ const firstSegment = path.split("/")[1]?.toLowerCase();
1695
+ 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".`);
1696
+ return `${parsed.origin}${path}`;
1697
+ }
1698
+ /**
1699
+ * Parse a configured HTTP(S) URL and apply the checks every such setting shares.
1700
+ * Empty values count as absent.
1701
+ * @returns The parsed URL and the trimmed input, or `undefined` when absent.
1702
+ * @throws Error naming the setting when the value is not an HTTP(S) URL or has credentials.
1703
+ */
1704
+ function parseConfiguredUrl(value, settingName, expectedShape) {
1705
+ const trimmed = value?.trim();
1706
+ if (!trimmed) return;
1707
+ let parsed;
1708
+ try {
1709
+ parsed = new URL(trimmed);
1710
+ } catch {
1711
+ throw new Error(`${settingName} must be an absolute HTTP(S) ${expectedShape}.`);
1712
+ }
1713
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`${settingName} must use the http or https protocol.`);
1714
+ if (parsed.username || parsed.password) throw new Error(`${settingName} must not include credentials.`);
1715
+ return {
1716
+ parsed,
1717
+ trimmed
1718
+ };
1719
+ }
1720
+ /**
1721
+ * Resolve the public location from configuration: `server.publicUrl` first,
1722
+ * then the deprecated `server.publicOrigin`, then the bind-derived origin.
1723
+ *
1724
+ * @param config - The loaded application configuration.
1725
+ * @param port - The port this process listens on (used for the bind fallback).
1726
+ * @returns The resolved public location.
1727
+ * @throws Error when a configured value is invalid (configuration loading
1728
+ * normally rejects those earlier).
1729
+ */
1730
+ function resolvePublicLocation(config, port) {
1731
+ const configuredUrl = normalizePublicUrl(config.server.publicUrl) ?? normalizePublicOrigin(config.server.publicOrigin);
1732
+ const url = configuredUrl ?? buildBindOrigin(config.server.host, port);
1733
+ const origin = new URL(url).origin;
1734
+ return {
1735
+ configured: configuredUrl !== void 0,
1736
+ url,
1737
+ origin,
1738
+ basePath: url.slice(origin.length)
1739
+ };
1740
+ }
1741
+ /**
1742
+ * Describe deprecation problems with the configured public location, for the
1743
+ * caller to log at startup.
1744
+ *
1745
+ * @param config - The loaded application configuration.
1746
+ * @returns Warning messages; empty when nothing needs attention.
1747
+ */
1748
+ function describePublicLocationWarnings(config) {
1749
+ const hasUrl = Boolean(config.server.publicUrl?.trim());
1750
+ const hasOrigin = Boolean(config.server.publicOrigin?.trim());
1751
+ if (hasUrl && hasOrigin) return ["server.publicOrigin is ignored because server.publicUrl is also set. Remove server.publicOrigin."];
1752
+ if (hasOrigin) return ["server.publicOrigin is deprecated. Use server.publicUrl instead."];
1753
+ return [];
1754
+ }
1755
+ /**
1756
+ * Build an HTTP origin from the local bind host and port.
1757
+ *
1758
+ * The server itself listens over HTTP; deployments that terminate TLS should
1759
+ * configure server.publicUrl to advertise an HTTPS URL.
1760
+ */
1761
+ function buildBindOrigin(host, port) {
1762
+ const formattedHost = formatHostForUrl(host);
1763
+ return new URL(`http://${formattedHost}:${port}`).origin;
1764
+ }
1765
+ function formatHostForUrl(host) {
1766
+ const trimmed = host.trim();
1767
+ const unbracketed = stripIpv6Brackets(trimmed);
1768
+ if (unbracketed.includes(":")) return `[${unbracketed}]`;
1769
+ return trimmed;
1770
+ }
1771
+ /**
1772
+ * Remove the brackets around an IPv6 address literal, as URLs and `Host`
1773
+ * headers write it. Other values are returned unchanged.
1774
+ * @param host - A host, e.g. `[::1]` or `example.com`.
1775
+ * @returns The host without brackets, e.g. `::1`.
1776
+ */
1777
+ function stripIpv6Brackets(host) {
1778
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
1779
+ }
1780
+ // src/utils/config.ts
1781
+ var managedConfigVectorDimensionOmissionMarker = "docs-mcp-server-managed-vector-dimension-omitted";
1782
+ var managedConfigHeader = [
1783
+ `# ${managedConfigVectorDimensionOmissionMarker}`,
1784
+ "# embeddings.vectorDimension is omitted when it comes from generated defaults.",
1785
+ "# Add embeddings.vectorDimension explicitly to override native model dimensions.",
1786
+ ""
1787
+ ].join("\n");
1788
+ var vectorDimensionPath = ["embeddings", "vectorDimension"];
1789
+ var envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
1790
+ if (Array.isArray(value)) return value;
1791
+ const parsed = yaml.parse(value);
1792
+ if (Array.isArray(parsed)) return parsed.map((item) => String(item));
1793
+ return [value];
1794
+ }).pipe(z.array(z.string()));
1795
+ /**
1796
+ * Custom zod schema for boolean values that properly handles string representations.
1797
+ * Unlike z.coerce.boolean() which treats any non-empty string as true,
1798
+ * this schema correctly parses "false", "0", "no", "off" as false.
1799
+ */
1800
+ var envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
1801
+ if (typeof val === "boolean") return val;
1802
+ const lower = val.toLowerCase().trim();
1803
+ return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off" && lower !== "";
1804
+ }).pipe(z.boolean());
1805
+ /**
1806
+ * Parses a boolean environment variable the way configuration settings are
1807
+ * parsed: "false", "0", "no", "off" and blank are false, anything else true.
1808
+ * @param value - The variable's value.
1809
+ * @returns The boolean, or undefined when the variable is unset.
1810
+ */
1811
+ function parseEnvBoolean(value) {
1812
+ return value === void 0 ? void 0 : envBoolean.parse(value);
1813
+ }
1814
+ /**
1815
+ * Treats blank strings (empty env vars, `--flag ""`) as an absent value so that
1816
+ * defaults and fallbacks apply instead of an empty string.
1817
+ */
1818
+ var blankToUndefined = (value) => {
1819
+ if (typeof value !== "string") return value;
1820
+ const trimmed = value.trim();
1821
+ return trimmed.length > 0 ? trimmed : void 0;
1822
+ };
1823
+ /** Report a normalizer's error as the validation issue of the setting. */
1824
+ function addNormalizationIssue(ctx, error) {
1825
+ ctx.addIssue({
1826
+ code: z.ZodIssueCode.custom,
1827
+ message: error instanceof Error ? error.message : String(error)
1828
+ });
1829
+ }
1830
+ /**
1831
+ * An optional string setting that `normalize` validates and canonicalizes.
1832
+ * The normalizer treats empty values as absent and throws a message naming
1833
+ * the setting for invalid ones.
1834
+ */
1835
+ function normalizedStringSchema(normalize) {
1836
+ return z.string().optional().transform((value, ctx) => {
1837
+ try {
1838
+ return normalize(value);
1839
+ } catch (error) {
1840
+ addNormalizationIssue(ctx, error);
1841
+ return z.NEVER;
1842
+ }
1843
+ });
1844
+ }
1845
+ var publicOriginSchema = normalizedStringSchema(normalizePublicOrigin);
1846
+ var publicUrlSchema = normalizedStringSchema(normalizePublicUrl);
1847
+ /**
1848
+ * Browser origins allowed to call the MCP endpoint in addition to loopback and
1849
+ * the public URL's origin. Each entry must be an exact origin
1850
+ * (`scheme://host[:port]`); a trailing slash is ignored.
1851
+ */
1852
+ var allowedOriginsSchema = envStringArray.transform((values, ctx) => {
1853
+ const origins = [];
1854
+ for (const value of values) try {
1855
+ const origin = normalizePublicOrigin(value, "server.allowedOrigins");
1856
+ if (origin) origins.push(origin);
1857
+ } catch (error) {
1858
+ addNormalizationIssue(ctx, error);
1859
+ return z.NEVER;
1860
+ }
1861
+ return origins;
1862
+ });
1863
+ var DEFAULT_CONFIG = {
1864
+ app: {
1865
+ storePath: "",
1866
+ telemetryEnabled: true,
1867
+ readOnly: false,
1868
+ embeddingModel: "text-embedding-3-small"
1869
+ },
1870
+ server: {
1871
+ name: "docs-mcp-server",
1872
+ title: void 0,
1873
+ instructions: void 0,
1874
+ instructionsFile: void 0,
1875
+ protocol: "auto",
1876
+ host: "127.0.0.1",
1877
+ publicUrl: void 0,
1878
+ publicOrigin: void 0,
1879
+ allowedOrigins: [],
1880
+ ports: {
1881
+ default: 6280,
1882
+ worker: 8080,
1883
+ mcp: 6280,
1884
+ web: 6281
1885
+ },
1886
+ heartbeatMs: 3e4
1887
+ },
1888
+ auth: {
1889
+ enabled: false,
1890
+ issuerUrl: "",
1891
+ audience: ""
1892
+ },
1893
+ scraper: {
1894
+ maxPages: 1e3,
1895
+ maxDepth: 3,
1896
+ maxConcurrency: 3,
1897
+ jobHeartbeatMs: 15e3,
1898
+ abortOnFailureRate: .5,
1899
+ preserveHashes: false,
1900
+ skipKnownTrackers: true,
1901
+ pageTimeoutMs: 5e3,
1902
+ browserTimeoutMs: 3e4,
1903
+ htmlExtractor: "cheerio",
1904
+ fetcher: {
1905
+ maxRetries: 3,
1906
+ baseDelayMs: 1e3,
1907
+ timeoutMs: 3e4,
1908
+ maxCacheItems: 200,
1909
+ maxCacheItemSizeBytes: 512e3
1910
+ },
1911
+ document: { maxSize: 10485760 },
1912
+ security: {
1913
+ network: {
1914
+ mode: "open",
1915
+ allowPrivateNetworks: false,
1916
+ allowedHosts: [],
1917
+ allowedCidrs: [],
1918
+ allowInvalidTls: false
1919
+ },
1920
+ fileAccess: {
1921
+ mode: "allowedRoots",
1922
+ allowedRoots: ["$DOCUMENTS"],
1923
+ followSymlinks: false,
1924
+ includeHidden: false
1925
+ }
1926
+ }
1927
+ },
1928
+ splitter: {
1929
+ minChunkSize: 500,
1930
+ preferredChunkSize: 1500,
1931
+ maxChunkSize: 5e3,
1932
+ treeSitterSizeLimit: 3e4,
1933
+ json: {
1934
+ maxNestingDepth: 5,
1935
+ maxChunks: 1e3
1936
+ }
1937
+ },
1938
+ embeddings: {
1939
+ batchSize: 100,
1940
+ batchChars: 5e4,
1941
+ requestTimeoutMs: 3e4,
1942
+ initTimeoutMs: 3e4,
1943
+ vectorDimension: 1536
1944
+ },
1945
+ db: {
1946
+ migrationMaxRetries: 5,
1947
+ migrationRetryDelayMs: 300
1948
+ },
1949
+ search: {
1950
+ overfetchFactor: 2,
1951
+ weightVec: 1,
1952
+ weightFts: 1,
1953
+ vectorMultiplier: 10
1954
+ },
1955
+ assembly: {
1956
+ maxParentChainDepth: 10,
1957
+ childLimit: 3,
1958
+ precedingSiblingsLimit: 1,
1959
+ subsequentSiblingsLimit: 2,
1960
+ maxChunkDistance: 3
1961
+ }
1962
+ };
1963
+ var AppConfigSchema = z.object({
1964
+ app: z.object({
1965
+ storePath: z.string().default(DEFAULT_CONFIG.app.storePath),
1966
+ telemetryEnabled: envBoolean.default(DEFAULT_CONFIG.app.telemetryEnabled),
1967
+ readOnly: envBoolean.default(DEFAULT_CONFIG.app.readOnly),
1968
+ embeddingModel: z.string().default(DEFAULT_CONFIG.app.embeddingModel)
1969
+ }).default(DEFAULT_CONFIG.app),
1970
+ server: z.object({
1971
+ name: z.preprocess(blankToUndefined, z.string().default(DEFAULT_CONFIG.server.name)),
1972
+ title: z.preprocess(blankToUndefined, z.string().optional()),
1973
+ instructions: z.preprocess(blankToUndefined, z.string().optional()),
1974
+ instructionsFile: z.preprocess(blankToUndefined, z.string().optional()),
1975
+ protocol: z.string().default(DEFAULT_CONFIG.server.protocol),
1976
+ host: z.string().default(DEFAULT_CONFIG.server.host),
1977
+ publicUrl: publicUrlSchema.optional(),
1978
+ publicOrigin: publicOriginSchema.optional(),
1979
+ allowedOrigins: allowedOriginsSchema.default(DEFAULT_CONFIG.server.allowedOrigins),
1980
+ ports: z.object({
1981
+ default: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.default),
1982
+ worker: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.worker),
1983
+ mcp: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.mcp),
1984
+ web: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.web)
1985
+ }).default(DEFAULT_CONFIG.server.ports),
1986
+ heartbeatMs: z.coerce.number().int().default(DEFAULT_CONFIG.server.heartbeatMs)
1987
+ }).default({
1988
+ name: DEFAULT_CONFIG.server.name,
1989
+ protocol: DEFAULT_CONFIG.server.protocol,
1990
+ host: DEFAULT_CONFIG.server.host,
1991
+ allowedOrigins: DEFAULT_CONFIG.server.allowedOrigins,
1992
+ ports: DEFAULT_CONFIG.server.ports,
1993
+ heartbeatMs: DEFAULT_CONFIG.server.heartbeatMs
1994
+ }),
1995
+ auth: z.object({
1996
+ enabled: envBoolean.default(DEFAULT_CONFIG.auth.enabled),
1997
+ issuerUrl: z.string().default(DEFAULT_CONFIG.auth.issuerUrl),
1998
+ audience: z.string().default(DEFAULT_CONFIG.auth.audience)
1999
+ }).default(DEFAULT_CONFIG.auth),
2000
+ scraper: z.object({
2001
+ maxPages: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxPages),
2002
+ maxDepth: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxDepth),
2003
+ maxConcurrency: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxConcurrency),
2004
+ jobHeartbeatMs: z.coerce.number().int().positive().default(DEFAULT_CONFIG.scraper.jobHeartbeatMs),
2005
+ abortOnFailureRate: z.coerce.number().min(0).max(1).default(DEFAULT_CONFIG.scraper.abortOnFailureRate),
2006
+ preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),
2007
+ skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
2008
+ pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
2009
+ browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
2010
+ htmlExtractor: z.enum(["cheerio", "defuddle"]).default(DEFAULT_CONFIG.scraper.htmlExtractor),
2011
+ fetcher: z.object({
2012
+ maxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),
2013
+ baseDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),
2014
+ timeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.timeoutMs),
2015
+ maxCacheItems: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItems),
2016
+ maxCacheItemSizeBytes: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItemSizeBytes)
2017
+ }).default(DEFAULT_CONFIG.scraper.fetcher),
2018
+ document: z.object({ maxSize: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.document.maxSize) }).default(DEFAULT_CONFIG.scraper.document),
2019
+ security: z.object({
2020
+ network: z.object({
2021
+ mode: z.enum(["open", "allowlist"]).default(DEFAULT_CONFIG.scraper.security.network.mode),
2022
+ allowPrivateNetworks: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks),
2023
+ allowedHosts: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedHosts),
2024
+ allowedCidrs: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedCidrs),
2025
+ allowInvalidTls: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowInvalidTls)
2026
+ }).default(DEFAULT_CONFIG.scraper.security.network),
2027
+ fileAccess: z.object({
2028
+ mode: z.enum([
2029
+ "disabled",
2030
+ "allowedRoots",
2031
+ "unrestricted"
2032
+ ]).default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),
2033
+ allowedRoots: envStringArray.default(DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots),
2034
+ followSymlinks: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks),
2035
+ includeHidden: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden)
2036
+ }).default(DEFAULT_CONFIG.scraper.security.fileAccess)
2037
+ }).default(DEFAULT_CONFIG.scraper.security)
2038
+ }).default(DEFAULT_CONFIG.scraper),
2039
+ splitter: z.object({
2040
+ minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),
2041
+ preferredChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.preferredChunkSize),
2042
+ maxChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.maxChunkSize),
2043
+ treeSitterSizeLimit: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.treeSitterSizeLimit),
2044
+ json: z.object({
2045
+ maxNestingDepth: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxNestingDepth),
2046
+ maxChunks: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxChunks)
2047
+ }).default(DEFAULT_CONFIG.splitter.json)
2048
+ }).default(DEFAULT_CONFIG.splitter),
2049
+ embeddings: z.object({
2050
+ batchSize: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchSize),
2051
+ batchChars: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchChars),
2052
+ requestTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.requestTimeoutMs),
2053
+ initTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.initTimeoutMs),
2054
+ vectorDimension: z.coerce.number().int().min(1, "embedding dimension must be at least 1").default(DEFAULT_CONFIG.embeddings.vectorDimension)
2055
+ }).default(DEFAULT_CONFIG.embeddings),
2056
+ db: z.object({
2057
+ migrationMaxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationMaxRetries),
2058
+ migrationRetryDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationRetryDelayMs)
2059
+ }).default(DEFAULT_CONFIG.db),
2060
+ search: z.object({
2061
+ overfetchFactor: z.coerce.number().default(DEFAULT_CONFIG.search.overfetchFactor),
2062
+ weightVec: z.coerce.number().default(DEFAULT_CONFIG.search.weightVec),
2063
+ weightFts: z.coerce.number().default(DEFAULT_CONFIG.search.weightFts),
2064
+ vectorMultiplier: z.coerce.number().int().default(DEFAULT_CONFIG.search.vectorMultiplier)
2065
+ }).default(DEFAULT_CONFIG.search),
2066
+ assembly: z.object({
2067
+ maxParentChainDepth: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.maxParentChainDepth),
2068
+ childLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.childLimit),
2069
+ precedingSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.precedingSiblingsLimit),
2070
+ subsequentSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.subsequentSiblingsLimit),
2071
+ maxChunkDistance: z.coerce.number().int().min(0).default(DEFAULT_CONFIG.assembly.maxChunkDistance)
2072
+ }).default(DEFAULT_CONFIG.assembly)
2073
+ });
2074
+ var vectorDimensionExplicit = Symbol("vectorDimensionExplicit");
2075
+ var defaults = AppConfigSchema.parse({});
2076
+ var configMappings = [
2077
+ {
2078
+ path: ["server", "protocol"],
2079
+ env: ["DOCS_MCP_PROTOCOL"],
2080
+ cli: "protocol"
2081
+ },
2082
+ {
2083
+ path: ["app", "storePath"],
2084
+ env: ["DOCS_MCP_STORE_PATH"],
2085
+ cli: "storePath"
2086
+ },
2087
+ {
2088
+ path: ["app", "telemetryEnabled"],
2089
+ env: ["DOCS_MCP_TELEMETRY"]
2090
+ },
2091
+ {
2092
+ path: ["app", "readOnly"],
2093
+ env: ["DOCS_MCP_READ_ONLY"],
2094
+ cli: "readOnly"
2095
+ },
2096
+ {
2097
+ path: [
2098
+ "server",
2099
+ "ports",
2100
+ "default"
2101
+ ],
2102
+ env: ["DOCS_MCP_PORT", "PORT"],
2103
+ cli: "port"
2104
+ },
2105
+ {
2106
+ path: [
2107
+ "server",
2108
+ "ports",
2109
+ "worker"
2110
+ ],
2111
+ env: ["DOCS_MCP_PORT", "PORT"],
2112
+ cli: "port"
2113
+ },
2114
+ {
2115
+ path: [
2116
+ "server",
2117
+ "ports",
2118
+ "mcp"
2119
+ ],
2120
+ env: ["DOCS_MCP_PORT", "PORT"],
2121
+ cli: "port"
2122
+ },
2123
+ {
2124
+ path: [
2125
+ "server",
2126
+ "ports",
2127
+ "web"
2128
+ ],
2129
+ env: [
2130
+ "DOCS_MCP_WEB_PORT",
2131
+ "DOCS_MCP_PORT",
2132
+ "PORT"
2133
+ ],
2134
+ cli: "port"
2135
+ },
2136
+ {
2137
+ path: ["server", "host"],
2138
+ env: ["DOCS_MCP_HOST", "HOST"],
2139
+ cli: "host"
2140
+ },
2141
+ {
2142
+ path: ["server", "publicUrl"],
2143
+ env: ["DOCS_MCP_SERVER_PUBLIC_URL"],
2144
+ cli: "publicUrl"
2145
+ },
2146
+ {
2147
+ path: ["server", "publicOrigin"],
2148
+ env: ["DOCS_MCP_SERVER_PUBLIC_ORIGIN"],
2149
+ cli: "publicOrigin"
2150
+ },
2151
+ {
2152
+ path: ["server", "name"],
2153
+ env: ["DOCS_MCP_SERVER_NAME"],
2154
+ cli: "serverName"
2155
+ },
2156
+ {
2157
+ path: ["server", "title"],
2158
+ env: ["DOCS_MCP_SERVER_TITLE"],
2159
+ cli: "serverTitle"
2160
+ },
2161
+ {
2162
+ path: ["server", "instructions"],
2163
+ env: ["DOCS_MCP_SERVER_INSTRUCTIONS"],
2164
+ cli: "serverInstructions"
2165
+ },
2166
+ {
2167
+ path: ["server", "instructionsFile"],
2168
+ env: ["DOCS_MCP_SERVER_INSTRUCTIONS_FILE"],
2169
+ cli: "serverInstructionsFile"
2170
+ },
2171
+ {
2172
+ path: ["app", "embeddingModel"],
2173
+ env: ["DOCS_MCP_EMBEDDING_MODEL"],
2174
+ cli: "embeddingModel"
2175
+ },
2176
+ {
2177
+ path: ["auth", "enabled"],
2178
+ env: ["DOCS_MCP_AUTH_ENABLED"],
2179
+ cli: "authEnabled"
2180
+ },
2181
+ {
2182
+ path: ["auth", "issuerUrl"],
2183
+ env: ["DOCS_MCP_AUTH_ISSUER_URL"],
2184
+ cli: "authIssuerUrl"
2185
+ },
2186
+ {
2187
+ path: ["auth", "audience"],
2188
+ env: ["DOCS_MCP_AUTH_AUDIENCE"],
2189
+ cli: "authAudience"
2190
+ }
2191
+ ];
2192
+ var systemPaths = envPaths("docs-mcp-server", { suffix: "" });
2193
+ function loadConfig(cliArgs = {}, options = {}) {
2194
+ const explicitPath = cliArgs.config || options.configPath || process.env.DOCS_MCP_CONFIG;
2195
+ let configPath;
2196
+ let isReadOnlyConfig = false;
2197
+ if (explicitPath) {
2198
+ configPath = explicitPath;
2199
+ isReadOnlyConfig = true;
2200
+ } else {
2201
+ configPath = path.join(systemPaths.config, "config.yaml");
2202
+ isReadOnlyConfig = false;
2203
+ }
2204
+ logger.debug(`Using config file: ${configPath}`);
2205
+ const fileConfig = loadConfigFile(configPath) || {};
2206
+ const hasManagedVectorDimensionOmissionMarker = hasManagedConfigVectorDimensionOmissionMarker(configPath);
2207
+ const baseConfig = deepMerge(defaults, fileConfig);
2208
+ const envConfig = mapEnvToConfig();
2209
+ const cliConfig = mapCliToConfig(cliArgs);
2210
+ const vectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
2211
+ const fileVectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, {}, {}, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
2212
+ if (!isReadOnlyConfig) try {
2213
+ saveConfigFile(configPath, baseConfig, {
2214
+ managedDefaultConfig: true,
2215
+ omitVectorDimension: !fileVectorDimensionWasExplicit
2216
+ });
2217
+ } catch (error) {
2218
+ logger.warn(`Failed to save config file to ${configPath}: ${error}`);
2219
+ }
2220
+ const mergedInput = deepMerge(baseConfig, deepMerge(envConfig, cliConfig));
2221
+ if (!getAtPath(mergedInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(mergedInput, ["app", "embeddingModel"], "text-embedding-3-small");
2222
+ const parseResult = AppConfigSchema.safeParse(mergedInput);
2223
+ if (parseResult.success) return markVectorDimensionSource(parseResult.data, vectorDimensionWasExplicit);
2224
+ for (const setting of [
2225
+ "publicUrl",
2226
+ "publicOrigin",
2227
+ "allowedOrigins"
2228
+ ]) if (hasParseIssueAtPath(parseResult.error, ["server", setting])) throw new Error(`Invalid configuration for server.${setting}: ${parseResult.error.message}`);
2229
+ if (!isReadOnlyConfig && fs.existsSync(configPath)) {
2230
+ const quarantinePath = `${configPath}.invalid-${Date.now()}`;
2231
+ try {
2232
+ fs.renameSync(configPath, quarantinePath);
2233
+ logger.warn(`Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`);
2234
+ } catch (renameError) {
2235
+ logger.warn(`Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`);
2236
+ }
2237
+ } else logger.warn(`Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`);
2238
+ const fallbackInput = deepMerge(defaults, deepMerge(envConfig, cliConfig));
2239
+ if (!getAtPath(fallbackInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
2240
+ const fallbackConfig = markVectorDimensionSource(AppConfigSchema.parse(fallbackInput), wasVectorDimensionExplicit({}, envConfig, cliConfig, false, false));
2241
+ if (!isReadOnlyConfig) try {
2242
+ saveConfigFile(configPath, fallbackConfig, {
2243
+ managedDefaultConfig: true,
2244
+ omitVectorDimension: true
2245
+ });
2246
+ } catch (error) {
2247
+ logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
2248
+ }
2249
+ return fallbackConfig;
2250
+ }
2251
+ function hasManagedConfigVectorDimensionOmissionMarker(filePath) {
2252
+ if (!fs.existsSync(filePath)) return false;
2253
+ try {
2254
+ return fs.readFileSync(filePath, "utf8").includes(managedConfigVectorDimensionOmissionMarker);
2255
+ } catch {
2256
+ return false;
2257
+ }
2258
+ }
2259
+ /**
2260
+ * Returns true when the embedding vector dimension was set by user config,
2261
+ * environment, or CLI rather than coming from generated defaults.
2262
+ */
2263
+ function isVectorDimensionExplicit(config) {
2264
+ return config.embeddings[vectorDimensionExplicit] === true;
2265
+ }
2266
+ /**
2267
+ * Marks an AppConfig as having an explicit or default-derived vector dimension.
2268
+ */
2269
+ function markVectorDimensionSource(config, explicit) {
2270
+ Object.defineProperty(config.embeddings, vectorDimensionExplicit, {
2271
+ value: explicit,
2272
+ enumerable: false,
2273
+ configurable: true
2274
+ });
2275
+ return config;
2276
+ }
2277
+ function loadConfigFile(filePath) {
2278
+ if (!fs.existsSync(filePath)) return null;
2279
+ try {
2280
+ const content = fs.readFileSync(filePath, "utf8");
2281
+ if (filePath.endsWith(".json")) return JSON.parse(content);
2282
+ return yaml.parse(content) || {};
2283
+ } catch (error) {
2284
+ logger.warn(`Failed to parse config file ${filePath}: ${error}`);
2285
+ return null;
2286
+ }
2287
+ }
2288
+ function wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker) {
2289
+ if (getAtPath(envConfig, vectorDimensionPath) !== void 0 || getAtPath(cliConfig, vectorDimensionPath) !== void 0) return true;
2290
+ const fileValue = getAtPath(fileConfig, vectorDimensionPath);
2291
+ if (fileValue === void 0) return false;
2292
+ if (isReadOnlyConfig || fileValue !== DEFAULT_CONFIG.embeddings.vectorDimension || hasManagedVectorDimensionOmissionMarker) return true;
2293
+ return !looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig);
2294
+ }
2295
+ function looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig) {
2296
+ const embeddings = fileConfig.embeddings;
2297
+ if (typeof embeddings !== "object" || embeddings === null || Array.isArray(embeddings)) return false;
2298
+ return Object.keys(DEFAULT_CONFIG.embeddings).every((key) => Object.hasOwn(embeddings, key));
2299
+ }
2300
+ function saveConfigFile(filePath, config, options = {}) {
2301
+ const dir = path.dirname(filePath);
2302
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
2303
+ const configToWrite = cloneConfigValue(config);
2304
+ if (options.omitVectorDimension) unsetAtPath(configToWrite, vectorDimensionPath);
2305
+ let content;
2306
+ if (filePath.endsWith(".json")) content = JSON.stringify(configToWrite, null, 2);
2307
+ else {
2308
+ content = yaml.stringify(configToWrite);
2309
+ if (options.managedDefaultConfig) content = `${managedConfigHeader}${content}`;
2310
+ }
2311
+ logger.debug(`Updating config file at ${filePath}`);
2312
+ fs.writeFileSync(filePath, content, "utf8");
2313
+ }
2314
+ function mapEnvToConfig() {
2315
+ const config = {};
2316
+ for (const mapping of configMappings) if (mapping.env) {
2317
+ for (const envVar of mapping.env) if (process.env[envVar] !== void 0) {
2318
+ setAtPath(config, mapping.path, normalizeEnvValue(process.env[envVar]));
2319
+ break;
2320
+ }
2321
+ }
2322
+ for (const pathArr of ALL_CONFIG_LEAF_PATHS) {
2323
+ const envVar = pathToEnvVar(pathArr);
2324
+ if (process.env[envVar] !== void 0) setAtPath(config, pathArr, normalizeEnvValue(process.env[envVar]));
2325
+ }
2326
+ return config;
2327
+ }
2328
+ function mapCliToConfig(args) {
2329
+ const config = {};
2330
+ for (const mapping of configMappings) if (mapping.cli && args[mapping.cli] !== void 0) setAtPath(config, mapping.path, args[mapping.cli]);
2331
+ return config;
2332
+ }
2333
+ /**
2334
+ * Convert camelCase to UPPER_SNAKE_CASE
2335
+ * Example: "maxSize" → "MAX_SIZE", "maxNestingDepth" → "MAX_NESTING_DEPTH"
2336
+ */
2337
+ function camelToUpperSnake(str) {
2338
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
2339
+ }
2340
+ /**
2341
+ * Convert config path to environment variable name
2342
+ * Example: ["scraper", "document", "maxSize"] → "DOCS_MCP_SCRAPER_DOCUMENT_MAX_SIZE"
2343
+ */
2344
+ function pathToEnvVar(pathArr) {
2345
+ return `DOCS_MCP_${pathArr.map(camelToUpperSnake).join("_")}`;
2346
+ }
2347
+ /**
2348
+ * Recursively collect all leaf paths from a config object
2349
+ */
2350
+ function collectLeafPaths(obj, prefix = []) {
2351
+ const paths = [];
2352
+ for (const [key, value] of Object.entries(obj)) {
2353
+ const currentPath = [...prefix, key];
2354
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) paths.push(...collectLeafPaths(value, currentPath));
2355
+ else paths.push(currentPath);
2356
+ }
2357
+ return paths;
2358
+ }
2359
+ var ALL_CONFIG_LEAF_PATHS = collectLeafPaths(DEFAULT_CONFIG);
2360
+ function setAtPath(obj, pathArr, value) {
2361
+ let current = obj;
2362
+ for (let i = 0; i < pathArr.length - 1; i++) {
2363
+ const key = pathArr[i];
2364
+ if (current[key] === void 0 || typeof current[key] !== "object" || current[key] === null) current[key] = {};
2365
+ current = current[key];
2366
+ }
2367
+ current[pathArr[pathArr.length - 1]] = value;
2368
+ }
2369
+ function getAtPath(obj, pathArr) {
2370
+ let current = obj;
2371
+ for (const key of pathArr) {
2372
+ if (typeof current !== "object" || current === null) return void 0;
2373
+ current = current[key];
2374
+ }
2375
+ return current;
2376
+ }
2377
+ function unsetAtPath(obj, pathArr) {
2378
+ let current = obj;
2379
+ for (const key of pathArr.slice(0, -1)) {
2380
+ if (typeof current !== "object" || current === null) return;
2381
+ current = current[key];
773
2382
  }
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);
2383
+ if (typeof current === "object" && current !== null) delete current[pathArr[pathArr.length - 1]];
2384
+ }
2385
+ function cloneConfigValue(value) {
2386
+ if (Array.isArray(value)) return value.map((item) => cloneConfigValue(item));
2387
+ if (typeof value === "object" && value !== null) {
2388
+ const output = {};
2389
+ for (const [key, child] of Object.entries(value)) output[key] = cloneConfigValue(child);
2390
+ return output;
781
2391
  }
782
- /**
783
- * Remove a specific listener.
784
- */
785
- off(eventType, listener) {
786
- this.emitter.off(eventType, listener);
2392
+ return value;
2393
+ }
2394
+ function hasPath(obj, pathArr) {
2395
+ let current = obj;
2396
+ for (const key of pathArr) {
2397
+ if (typeof current !== "object" || current === null || !Object.hasOwn(current, key)) return false;
2398
+ current = current[key];
787
2399
  }
788
- };
2400
+ return true;
2401
+ }
2402
+ function hasParseIssueAtPath(error, pathArr) {
2403
+ return error.issues.some((issue) => issue.path.join(".") === pathArr.join("."));
2404
+ }
2405
+ function deepMerge(target, source) {
2406
+ if (typeof target !== "object" || target === null) return source;
2407
+ if (typeof source !== "object" || source === null) return target;
2408
+ if (Array.isArray(target) || Array.isArray(source)) return source;
2409
+ const t = target;
2410
+ const s = source;
2411
+ const output = { ...t };
2412
+ for (const key of Object.keys(s)) {
2413
+ const sValue = s[key];
2414
+ const tValue = t[key];
2415
+ 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);
2416
+ else output[key] = sValue;
2417
+ }
2418
+ return output;
2419
+ }
2420
+ /**
2421
+ * Check if a config path is valid by verifying it exists in DEFAULT_CONFIG
2422
+ */
2423
+ function isValidConfigPath(path) {
2424
+ return hasPath(DEFAULT_CONFIG, path.split("."));
2425
+ }
2426
+ /**
2427
+ * Get a config value by dot-separated path
2428
+ */
2429
+ function getConfigValue(config, path) {
2430
+ return getAtPath(config, path.split("."));
2431
+ }
2432
+ /**
2433
+ * Parse a string value to the appropriate type (number, boolean, or string)
2434
+ */
2435
+ function parseConfigValue(value) {
2436
+ const num = Number(value);
2437
+ if (!Number.isNaN(num) && value.trim() !== "") return num;
2438
+ const lower = value.toLowerCase();
2439
+ if (lower === "true") return true;
2440
+ if (lower === "false") return false;
2441
+ return value;
2442
+ }
2443
+ /**
2444
+ * Set a config value and persist to file.
2445
+ * Returns the path to the config file that was updated.
2446
+ * Validates the updated config against the schema before saving.
2447
+ */
2448
+ function setConfigValue(path, value) {
2449
+ const configPath = getDefaultConfigPath();
2450
+ const fileConfig = loadConfigFile(configPath) || {};
2451
+ const pathArr = path.split(".");
2452
+ const parsedValue = parseConfigValue(value);
2453
+ const updatedConfig = JSON.parse(JSON.stringify(fileConfig));
2454
+ setAtPath(updatedConfig, pathArr, parsedValue);
2455
+ try {
2456
+ AppConfigSchema.parse(updatedConfig);
2457
+ } catch (err) {
2458
+ const errorMsg = err instanceof Error ? err.message : String(err);
2459
+ throw new Error(`Invalid config value for "${path}": ${errorMsg}`);
2460
+ }
2461
+ saveConfigFile(configPath, updatedConfig);
2462
+ return configPath;
2463
+ }
2464
+ /**
2465
+ * Get the default system config path
2466
+ */
2467
+ function getDefaultConfigPath() {
2468
+ return path.join(systemPaths.config, "config.yaml");
2469
+ }
789
2470
  // src/events/RemoteEventProxy.ts
790
2471
  /** First delay before subscribing again after the subscription itself ended. */
791
2472
  var RESUBSCRIBE_BASE_DELAY_MS = 1e3;
@@ -1190,11 +2871,20 @@ var ChallengeError = class extends ScraperError {
1190
2871
  url;
1191
2872
  statusCode;
1192
2873
  challengeType;
1193
- constructor(url, statusCode, challengeType) {
2874
+ responseUrl;
2875
+ /**
2876
+ * @param url The URL that was requested.
2877
+ * @param statusCode The status the challenge was served with.
2878
+ * @param challengeType The kind of challenge, such as "cloudflare".
2879
+ * @param responseUrl The URL whose response carried the challenge, which a
2880
+ * redirect may have moved to another host.
2881
+ */
2882
+ constructor(url, statusCode, challengeType, responseUrl = url) {
1194
2883
  super(`Challenge detected for ${url} (status: ${statusCode}, type: ${challengeType}): the site answered with a bot check instead of the page`, false);
1195
2884
  this.url = url;
1196
2885
  this.statusCode = statusCode;
1197
2886
  this.challengeType = challengeType;
2887
+ this.responseUrl = responseUrl;
1198
2888
  }
1199
2889
  };
1200
2890
  var TlsCertificateError = class extends ScraperError {
@@ -1209,9 +2899,19 @@ var TlsCertificateError = class extends ScraperError {
1209
2899
  /** An HTTP fetch that failed with a response, carrying that response's status. */
1210
2900
  var HttpStatusError = class extends ScraperError {
1211
2901
  statusCode;
1212
- constructor(message, isRetryable, statusCode, cause) {
2902
+ responseUrl;
2903
+ /**
2904
+ * @param message Describes the failure.
2905
+ * @param isRetryable Whether a later attempt may succeed.
2906
+ * @param statusCode The response's status.
2907
+ * @param cause The underlying error.
2908
+ * @param responseUrl The URL that answered with the status, when known; a
2909
+ * redirect may have moved it to another host.
2910
+ */
2911
+ constructor(message, isRetryable, statusCode, cause, responseUrl) {
1213
2912
  super(message, isRetryable, cause);
1214
2913
  this.statusCode = statusCode;
2914
+ this.responseUrl = responseUrl;
1215
2915
  }
1216
2916
  };
1217
2917
  var AccessPolicyError = class extends ScraperError {
@@ -1920,16 +3620,22 @@ function isRegexPattern(pattern) {
1920
3620
  return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
1921
3621
  }
1922
3622
  /**
1923
- * Converts a pattern string to a RegExp instance (auto-detects glob/regex).
1924
- * For globs, uses minimatch's internal conversion.
3623
+ * Converts a regex pattern string (wrapped in `/.../`) to a RegExp instance.
3624
+ *
3625
+ * Glob patterns cannot be converted: minimatch v11 removed `makeRe`, and no
3626
+ * RegExp equivalent exists. Use {@link matchesAnyPattern} or
3627
+ * {@link matchesAnyHostPattern} for glob matching instead; this function is
3628
+ * only for the `/.../` regex form (its internal callers branch on
3629
+ * {@link isRegexPattern} first, so they never hit the glob branch).
3630
+ *
3631
+ * @param pattern The pattern to convert; must be a `/.../` regex pattern.
3632
+ * @returns A compiled RegExp for the pattern.
1925
3633
  */
1926
3634
  function patternToRegExp(pattern) {
1927
3635
  const cached = regExpCache.get(pattern);
1928
3636
  if (cached) return cached;
1929
- let re;
1930
- if (isRegexPattern(pattern)) re = new RegExp(pattern.slice(1, -1));
1931
- else re = minimatch.makeRe(pattern, { dot: true });
1932
- if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
3637
+ if (!isRegexPattern(pattern)) throw new Error(`Invalid regex pattern: ${pattern}. Glob patterns cannot be converted to RegExp (minimatch v11 removed makeRe); use matchesAnyPattern for glob matching.`);
3638
+ const re = new RegExp(pattern.slice(1, -1));
1933
3639
  regExpCache.set(pattern, re);
1934
3640
  return re;
1935
3641
  }
@@ -2452,8 +4158,6 @@ var FingerprintGenerator = class {
2452
4158
  return this.headerGenerator.getHeaders();
2453
4159
  }
2454
4160
  };
2455
- // src/scraper/fetcher/headers.ts
2456
- var MARKDOWN_PREFERRED_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8";
2457
4161
  /**
2458
4162
  * Reads a header by name, ignoring case.
2459
4163
  *
@@ -2471,18 +4175,6 @@ function getHeader(headers, name) {
2471
4175
  for (const [header, value] of Object.entries(headers)) if (header.toLowerCase() === target) return value;
2472
4176
  }
2473
4177
  /**
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
4178
  * Connection-level headers, which the client that opens a connection sets for
2487
4179
  * itself. Chromium refuses to take them from a page: a navigation that carries
2488
4180
  * one fails with `net::ERR_INVALID_ARGUMENT`. Generated Firefox fingerprints
@@ -2735,6 +4427,33 @@ var ManagedBrowser = class ManagedBrowser {
2735
4427
  }
2736
4428
  }
2737
4429
  /**
4430
+ * Tells whether Playwright's own Chromium is installed: the headless shell a
4431
+ * launch uses by default, or the full build it falls back to.
4432
+ *
4433
+ * Playwright only reports the full build's path. The shell of the same
4434
+ * revision sits next to it, in `chromium_headless_shell-<revision>`, and
4435
+ * Playwright marks a finished download with an `INSTALLATION_COMPLETE` file.
4436
+ *
4437
+ * @returns True when a launch without an explicit executable can succeed.
4438
+ */
4439
+ static isPlaywrightChromiumInstalled() {
4440
+ let fullBuildPath;
4441
+ try {
4442
+ fullBuildPath = chromium.executablePath();
4443
+ } catch {
4444
+ return false;
4445
+ }
4446
+ if (fs.existsSync(fullBuildPath)) return true;
4447
+ for (let dir = fullBuildPath; path.dirname(dir) !== dir; dir = path.dirname(dir)) {
4448
+ const revision = /^chromium-(\d+)$/.exec(path.basename(dir))?.[1];
4449
+ if (revision) {
4450
+ const shellDir = path.join(path.dirname(dir), `chromium_headless_shell-${revision}`);
4451
+ return fs.existsSync(path.join(shellDir, "INSTALLATION_COMPLETE"));
4452
+ }
4453
+ }
4454
+ return false;
4455
+ }
4456
+ /**
2738
4457
  * Resolves the Chromium binary to launch.
2739
4458
  *
2740
4459
  * Playwright's own managed build is pinned to the installed Playwright
@@ -2747,9 +4466,7 @@ var ManagedBrowser = class ManagedBrowser {
2747
4466
  static resolveChromiumExecutablePath() {
2748
4467
  const configuredPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
2749
4468
  if (configuredPath) return configuredPath;
2750
- try {
2751
- if (fs.existsSync(chromium.executablePath())) return;
2752
- } catch {}
4469
+ if (ManagedBrowser.isPlaywrightChromiumInstalled()) return;
2753
4470
  const systemPath = [
2754
4471
  "/usr/lib/chromium/chromium",
2755
4472
  "/usr/bin/chromium",
@@ -2897,10 +4614,10 @@ var BrowserFetcher = class {
2897
4614
  page.on("requestfailed", (request) => {
2898
4615
  if (request.frame() === page?.mainFrame() && request.isNavigationRequest() && request.failure()?.errorText.includes("ERR_BLOCKED_BY_CLIENT")) blockedNavigation = request.url();
2899
4616
  });
2900
- const requestHeaders = withMarkdownPreferredAccept({
4617
+ const requestHeaders = {
2901
4618
  ...fingerprintHeaders,
2902
4619
  ...options?.headers
2903
- }, options?.headers);
4620
+ };
2904
4621
  await page.setExtraHTTPHeaders(withoutBrowserManagedHeaders(requestHeaders));
2905
4622
  const timeout = options?.timeout || this.defaultTimeoutMs;
2906
4623
  logger.debug(`Navigating to ${source} with browser...`);
@@ -3123,6 +4840,143 @@ var CancellationError = class extends PipelineError {
3123
4840
  super(message);
3124
4841
  }
3125
4842
  };
4843
+ // src/scraper/fetcher/HostBackoff.ts
4844
+ /**
4845
+ * Per-host pause for servers that ask the scraper to slow down.
4846
+ *
4847
+ * A crawl runs several requests at once. When one of them is throttled, the
4848
+ * others would go on requesting the same host at full speed, so a throttle
4849
+ * pauses the host rather than the one request that met it.
4850
+ */
4851
+ /**
4852
+ * The longest a host is paused for, whatever the server asks. A server asking
4853
+ * for an hour would otherwise park the crawl; capped, the request is retried
4854
+ * and fails if the server still refuses it.
4855
+ */
4856
+ var MAX_THROTTLE_DELAY_MS = 6e4;
4857
+ /**
4858
+ * Caps the doubling. Beyond this the pause is at its maximum anyway, and the
4859
+ * cap keeps a base delay of zero from multiplying into NaN.
4860
+ */
4861
+ var MAX_BACKOFF_EXPONENT = 16;
4862
+ /**
4863
+ * Parses a `Retry-After` header into a delay.
4864
+ *
4865
+ * Accepts both forms RFC 9110 allows: delta-seconds (`120`) and an HTTP-date
4866
+ * (`Wed, 21 Oct 2015 07:28:00 GMT`). A date in the past means no delay.
4867
+ *
4868
+ * @param value The header value as the response carried it.
4869
+ * @param now The current time in epoch milliseconds.
4870
+ * @returns The delay in milliseconds, or undefined when the header is missing
4871
+ * or unreadable.
4872
+ */
4873
+ function parseRetryAfter(value, now = Date.now()) {
4874
+ if (typeof value !== "string") return;
4875
+ const trimmed = value.trim();
4876
+ if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1e3;
4877
+ const date = /[a-z]/i.test(trimmed) ? Date.parse(trimmed) : NaN;
4878
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - now);
4879
+ }
4880
+ /**
4881
+ * Pauses every request to a host after the host throttles one of them.
4882
+ *
4883
+ * Shared by the fetchers of one crawl, so all of its workers wait out the same
4884
+ * pause. The pause doubles with each throttled response in a row and resets
4885
+ * once the host answers a request sent after the last throttle.
4886
+ */
4887
+ var HostBackoff = class {
4888
+ hosts = /* @__PURE__ */ new Map();
4889
+ /**
4890
+ * Waits until requests to the host of `url` may resume.
4891
+ *
4892
+ * @param url The URL about to be requested.
4893
+ * @param signal Aborts the wait.
4894
+ * @throws {CancellationError} When the signal aborts.
4895
+ */
4896
+ async wait(url, signal) {
4897
+ const host = hostOf(url);
4898
+ for (let state = this.hosts.get(host); state && state.resumeAt > Date.now(); state = this.hosts.get(host)) await sleep(state.resumeAt - Date.now(), signal);
4899
+ }
4900
+ /**
4901
+ * Records a throttled response and pauses its host.
4902
+ *
4903
+ * Without a `Retry-After`, the pause starts at `baseDelayMs` and doubles with
4904
+ * each throttle in a row, and is jittered down by up to half so the requests
4905
+ * of separate crawls do not retry in step.
4906
+ *
4907
+ * @param url The URL that was throttled.
4908
+ * @param baseDelayMs The pause after the first throttle, before jitter.
4909
+ * @param retryAfterMs The pause the server asked for, if it named one.
4910
+ * @returns How long the host is paused from now, in milliseconds.
4911
+ */
4912
+ throttle(url, baseDelayMs, retryAfterMs) {
4913
+ const host = hostOf(url);
4914
+ const now = Date.now();
4915
+ const state = this.hosts.get(host) ?? {
4916
+ resumeAt: 0,
4917
+ strikes: 0,
4918
+ throttledAt: 0
4919
+ };
4920
+ state.strikes++;
4921
+ state.throttledAt = now;
4922
+ let delay;
4923
+ if (retryAfterMs !== void 0) delay = Math.min(retryAfterMs, MAX_THROTTLE_DELAY_MS);
4924
+ else {
4925
+ const exponent = Math.min(state.strikes - 1, MAX_BACKOFF_EXPONENT);
4926
+ const nominal = Math.min(baseDelayMs * 2 ** exponent, MAX_THROTTLE_DELAY_MS);
4927
+ delay = nominal / 2 + Math.random() * nominal / 2;
4928
+ }
4929
+ state.resumeAt = Math.max(state.resumeAt, now + Math.round(delay));
4930
+ this.hosts.set(host, state);
4931
+ return state.resumeAt - now;
4932
+ }
4933
+ /**
4934
+ * Records a normal answer from the host, which ends its backoff.
4935
+ *
4936
+ * Only a request sent after the last throttle counts: one that was already
4937
+ * in flight says nothing about whether the host has recovered.
4938
+ *
4939
+ * @param url The URL that was answered.
4940
+ * @param sentAt When the request was sent, in epoch milliseconds.
4941
+ */
4942
+ recover(url, sentAt) {
4943
+ const host = hostOf(url);
4944
+ const state = this.hosts.get(host);
4945
+ if (state && sentAt > state.throttledAt) this.hosts.delete(host);
4946
+ }
4947
+ };
4948
+ /**
4949
+ * Returns the key a URL's pause is stored under.
4950
+ *
4951
+ * @param url An absolute URL.
4952
+ * @returns The URL's host, including any port.
4953
+ */
4954
+ function hostOf(url) {
4955
+ return new URL(url).host;
4956
+ }
4957
+ /**
4958
+ * Resolves after `ms` milliseconds, or rejects as soon as the signal aborts.
4959
+ *
4960
+ * @param ms The delay in milliseconds.
4961
+ * @param signal Aborts the delay.
4962
+ */
4963
+ function sleep(ms, signal) {
4964
+ return new Promise((resolve, reject) => {
4965
+ const onAbort = () => {
4966
+ clearTimeout(timer);
4967
+ reject(new CancellationError("Wait for a throttled host cancelled"));
4968
+ };
4969
+ const timer = setTimeout(() => {
4970
+ signal?.removeEventListener("abort", onAbort);
4971
+ resolve();
4972
+ }, ms);
4973
+ if (signal?.aborted) {
4974
+ onAbort();
4975
+ return;
4976
+ }
4977
+ signal?.addEventListener("abort", onAbort, { once: true });
4978
+ });
4979
+ }
3126
4980
  // src/scraper/fetcher/HttpFetcher.ts
3127
4981
  /**
3128
4982
  * Maximum number of redirects to follow in a single fetch. Matches the legacy
@@ -3131,7 +4985,16 @@ var CancellationError = class extends PipelineError {
3131
4985
  */
3132
4986
  var MAX_REDIRECTS = 5;
3133
4987
  /**
4988
+ * How much longer than other retries a throttled request waits when the server
4989
+ * names no delay. A retry after the usual second would most likely be
4990
+ * throttled again.
4991
+ */
4992
+ var THROTTLE_DELAY_FACTOR = 5;
4993
+ /**
3134
4994
  * Fetches content from remote sources using HTTP/HTTPS.
4995
+ *
4996
+ * A 429, or a 503 with `Retry-After`, pauses every request this fetcher sends
4997
+ * to that host (see {@link HostBackoff}).
3135
4998
  */
3136
4999
  var HttpFetcher = class {
3137
5000
  maxRetriesDefault;
@@ -3168,12 +5031,19 @@ var HttpFetcher = class {
3168
5031
  ];
3169
5032
  fingerprintGenerator;
3170
5033
  accessPolicy;
3171
- constructor(scraperConfig) {
5034
+ hostBackoff;
5035
+ /**
5036
+ * @param scraperConfig - Scraper settings, including the retry defaults.
5037
+ * @param hostBackoff - The per-host pause; pass one to share it with other
5038
+ * fetchers of the same crawl.
5039
+ */
5040
+ constructor(scraperConfig, hostBackoff = new HostBackoff()) {
3172
5041
  this.maxRetriesDefault = scraperConfig.fetcher.maxRetries;
3173
5042
  this.baseDelayDefaultMs = scraperConfig.fetcher.baseDelayMs;
3174
5043
  this.timeoutDefaultMs = scraperConfig.fetcher.timeoutMs;
3175
5044
  this.fingerprintGenerator = new FingerprintGenerator();
3176
5045
  this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
5046
+ this.hostBackoff = hostBackoff;
3177
5047
  }
3178
5048
  canFetch(source) {
3179
5049
  return source.startsWith("http://") || source.startsWith("https://");
@@ -3192,134 +5062,141 @@ var HttpFetcher = class {
3192
5062
  }
3193
5063
  async performFetch(source, options, maxRetries = this.maxRetriesDefault, baseDelay = this.baseDelayDefaultMs, followRedirects = true) {
3194
5064
  await this.accessPolicy.assertNetworkUrlAllowed(source);
3195
- for (let attempt = 0; attempt <= maxRetries; attempt++) try {
5065
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
3196
5066
  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;
5067
+ try {
5068
+ let redirectCount = 0;
5069
+ while (true) {
5070
+ const headers = {
5071
+ ...withoutConnectionHeaders(this.fingerprintGenerator.generateHeaders()),
5072
+ ...options?.headers
5073
+ };
5074
+ if (options?.etag) {
5075
+ headers["If-None-Match"] = options.etag;
5076
+ logger.debug(`Conditional request for ${source} with If-None-Match: ${options.etag}`);
3244
5077
  }
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`);
5078
+ const config = {
5079
+ responseType: "stream",
5080
+ headers: {
5081
+ ...headers,
5082
+ "Accept-Encoding": "gzip, deflate, br"
5083
+ },
5084
+ timeout: options?.timeout ?? this.timeoutDefaultMs,
5085
+ signal: options?.signal,
5086
+ maxRedirects: 0,
5087
+ decompress: true,
5088
+ validateStatus: (status) => {
5089
+ return status >= 200 && status < 400 || status === 304;
5090
+ }
5091
+ };
5092
+ if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
5093
+ await this.hostBackoff.wait(currentUrl, options?.signal);
5094
+ const sentAt = Date.now();
5095
+ const response = await axios.get(currentUrl, config);
5096
+ this.hostBackoff.recover(currentUrl, sentAt);
5097
+ let bodyConsumed = false;
5098
+ try {
5099
+ if (response.status === 304) {
5100
+ logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
5101
+ return {
5102
+ content: Buffer.from(""),
5103
+ mimeType: "text/plain",
5104
+ source: currentUrl,
5105
+ status: FetchStatus.NOT_MODIFIED
5106
+ };
5107
+ }
5108
+ if (response.status >= 300 && response.status < 400) {
5109
+ const location = response.headers.location;
5110
+ if (!location) throw new ScraperError(`Redirect response for ${currentUrl} did not include a location header`, false);
5111
+ if (!followRedirects) throw new RedirectError(currentUrl, location, response.status);
5112
+ if (redirectCount >= MAX_REDIRECTS) throw new ScraperError(`Too many redirects while fetching ${source}`, false);
5113
+ const redirectUrl = new URL(location, currentUrl).href;
5114
+ await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
5115
+ currentUrl = redirectUrl;
5116
+ redirectCount += 1;
5117
+ continue;
5118
+ }
5119
+ const contentTypeHeader = response.headers["content-type"];
5120
+ const { mimeType, charset } = MimeTypeUtils.parseContentType(typeof contentTypeHeader === "string" ? contentTypeHeader : void 0);
5121
+ const rawContentEncoding = response.headers["content-encoding"];
5122
+ const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
5123
+ const finalUrl = response.request?.res?.responseUrl || response.request?.responseUrl || response.config?.url || currentUrl;
5124
+ await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
5125
+ if (options?.acceptsMimeType && !options.acceptsMimeType(mimeType)) {
5126
+ logger.debug(`Skipping ${finalUrl}: ${mimeType} is not processable`);
5127
+ return {
5128
+ content: Buffer.from(""),
5129
+ mimeType,
5130
+ charset,
5131
+ source: finalUrl,
5132
+ status: FetchStatus.SKIPPED
5133
+ };
5134
+ }
5135
+ const etag = response.headers.etag || response.headers.ETag;
5136
+ if (etag) logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
5137
+ const lastModified = response.headers["last-modified"];
5138
+ const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
5139
+ const content = await readStreamToBuffer(response.data, options?.signal);
5140
+ bodyConsumed = true;
5141
+ const challengeType = MimeTypeUtils.isHtml(mimeType) ? detectChallengePage(content) : null;
5142
+ if (challengeType) throw new ChallengeError(source, response.status, challengeType, currentUrl);
3253
5143
  return {
3254
- content: Buffer.from(""),
5144
+ content,
3255
5145
  mimeType,
3256
5146
  charset,
5147
+ encoding: contentEncoding,
3257
5148
  source: finalUrl,
3258
- status: FetchStatus.SKIPPED
5149
+ etag,
5150
+ lastModified: lastModifiedISO,
5151
+ status: FetchStatus.SUCCESS
3259
5152
  };
5153
+ } finally {
5154
+ if (!bodyConsumed) destroyStream(response.data);
3260
5155
  }
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);
5156
+ }
5157
+ } catch (error) {
5158
+ if (error instanceof RedirectError || error instanceof ChallengeError) throw error;
5159
+ if (error instanceof ScraperError && !error.isRetryable) throw error;
5160
+ const axiosError = error;
5161
+ const status = axiosError.response?.status;
5162
+ const code = axiosError.code;
5163
+ const errorCause = error instanceof Error ? error : void 0;
5164
+ if (options?.signal?.aborted || code === "ERR_CANCELED") throw new CancellationError("HTTP fetch cancelled");
5165
+ if (status === 404) {
5166
+ logger.debug(`Resource not found (404): ${source}`);
3269
5167
  return {
3270
- content,
3271
- mimeType,
3272
- charset,
3273
- encoding: contentEncoding,
3274
- source: finalUrl,
3275
- etag,
3276
- lastModified: lastModifiedISO,
3277
- status: FetchStatus.SUCCESS
5168
+ content: Buffer.from(""),
5169
+ mimeType: "text/plain",
5170
+ source,
5171
+ status: FetchStatus.NOT_FOUND
3278
5172
  };
3279
- } finally {
3280
- if (!bodyConsumed) destroyStream(response.data);
3281
5173
  }
5174
+ if (!followRedirects && status && status >= 300 && status < 400) {
5175
+ const location = axiosError.response?.headers?.location;
5176
+ if (location) throw new RedirectError(source, location, status);
5177
+ }
5178
+ const retryAfterMs = parseRetryAfter(axiosError.response?.headers?.["retry-after"]);
5179
+ const throttleDelayMs = status === 429 || status === 503 && retryAfterMs !== void 0 ? this.hostBackoff.throttle(currentUrl, baseDelay * THROTTLE_DELAY_FACTOR, retryAfterMs) : void 0;
5180
+ if (status === 403 || status === 429) {
5181
+ const cfMitigated = axiosError.response?.headers?.["cf-mitigated"];
5182
+ const server = axiosError.response?.headers?.server;
5183
+ let responseBody = "";
5184
+ if (axiosError.response?.data) try {
5185
+ responseBody = (await readStreamToBuffer(axiosError.response.data)).toString("utf-8");
5186
+ } catch {}
5187
+ 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);
5188
+ }
5189
+ destroyStream(axiosError.response?.data);
5190
+ if (this.isTlsCertificateError(code)) throw new TlsCertificateError(source, code, errorCause);
5191
+ if (attempt < maxRetries && (status === void 0 || this.retryableStatusCodes.includes(status)) && !this.nonRetryableErrorCodes.includes(code ?? "")) {
5192
+ const delay = throttleDelayMs ?? baseDelay * 2 ** attempt;
5193
+ logger.warn(`⚠️ Attempt ${attempt + 1}/${maxRetries + 1} failed for ${source} (Status: ${status}, Code: ${code}). Retrying in ${delay}ms...`);
5194
+ if (throttleDelayMs === void 0) await this.delay(delay);
5195
+ continue;
5196
+ }
5197
+ const failureMessage = `Failed to fetch ${source} after ${attempt + 1} attempts: ${axiosError.message ?? "Unknown error"}`;
5198
+ throw status === void 0 ? new ScraperError(failureMessage, true, errorCause) : new HttpStatusError(failureMessage, true, status, errorCause, currentUrl);
3282
5199
  }
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
5200
  }
3324
5201
  throw new ScraperError(`Failed to fetch ${source} after ${maxRetries + 1} attempts`, true);
3325
5202
  }
@@ -3373,13 +5250,15 @@ var AutoDetectFetcher = class AutoDetectFetcher {
3373
5250
  httpFetcher;
3374
5251
  browserFetcher;
3375
5252
  fileFetcher;
5253
+ /** Pauses a host that throttled a request, for the browser fallback too. */
5254
+ hostBackoff = new HostBackoff();
3376
5255
  /**
3377
5256
  * @param scraperConfig - Scraper settings shared by all fetchers.
3378
5257
  * @param managedBrowser - The browser for the browser fallback; pass one to
3379
5258
  * share it with the HTML renderer.
3380
5259
  */
3381
5260
  constructor(scraperConfig, managedBrowser) {
3382
- this.httpFetcher = new HttpFetcher(scraperConfig);
5261
+ this.httpFetcher = new HttpFetcher(scraperConfig, this.hostBackoff);
3383
5262
  this.browserFetcher = new BrowserFetcher(scraperConfig, managedBrowser);
3384
5263
  this.fileFetcher = new FileFetcher(scraperConfig);
3385
5264
  }
@@ -3396,6 +5275,15 @@ var AutoDetectFetcher = class AutoDetectFetcher {
3396
5275
  return null;
3397
5276
  }
3398
5277
  /**
5278
+ * Returns the URL whose response caused a fetch failure.
5279
+ *
5280
+ * @param error The error the HTTP fetcher threw.
5281
+ * @returns The answering URL, or undefined when the error does not name one.
5282
+ */
5283
+ static responseUrl(error) {
5284
+ if (error instanceof ChallengeError || error instanceof HttpStatusError) return error.responseUrl;
5285
+ }
5286
+ /**
3399
5287
  * Check if this fetcher can handle the given source.
3400
5288
  * Returns true for any URL that any of the underlying fetchers can handle.
3401
5289
  */
@@ -3418,6 +5306,7 @@ var AutoDetectFetcher = class AutoDetectFetcher {
3418
5306
  const reason = AutoDetectFetcher.browserFallbackReason(error);
3419
5307
  if (reason) {
3420
5308
  logger.info(`🔄 ${reason} for ${source}, falling back to browser fetcher...`);
5309
+ for (const url of /* @__PURE__ */ new Set([source, AutoDetectFetcher.responseUrl(error)])) if (url) await this.hostBackoff.wait(url, options?.signal);
3421
5310
  return this.browserFetcher.fetch(source, options);
3422
5311
  }
3423
5312
  throw error;
@@ -3505,18 +5394,41 @@ function unwrapPlainTextPre(content) {
3505
5394
  return pre.text();
3506
5395
  }
3507
5396
  /**
3508
- * Returns true when a URL points to an llms.txt meta-file.
5397
+ * Returns the lower-cased last segment of a URL's path.
3509
5398
  * @param url The URL to inspect.
3510
- * @returns Whether the URL path basename is exactly llms.txt.
5399
+ * @returns The basename, or undefined for an unparsable URL or an empty path.
3511
5400
  */
3512
- function isLlmsTxtUrl(url) {
5401
+ function pathBasename(url) {
3513
5402
  try {
3514
- return new URL(url).pathname.split("/").filter(Boolean).at(-1)?.toLowerCase() === "llms.txt";
5403
+ return new URL(url).pathname.split("/").filter(Boolean).at(-1)?.toLowerCase();
3515
5404
  } catch {
3516
- return false;
5405
+ return;
3517
5406
  }
3518
5407
  }
3519
5408
  /**
5409
+ * Returns true when a URL points to an llms.txt meta-file.
5410
+ * @param url The URL to inspect.
5411
+ * @returns Whether the URL path basename is exactly llms.txt.
5412
+ */
5413
+ function isLlmsTxtUrl(url) {
5414
+ return pathBasename(url) === "llms.txt";
5415
+ }
5416
+ /**
5417
+ * Returns true when a URL points to a companion of llms.txt, such as
5418
+ * `llms-full.txt`, `llms-small.txt`, `llms-medium.txt` or `llms-ctx.txt`.
5419
+ *
5420
+ * The llms.txt proposal defines none of these. They are conventions that
5421
+ * documentation generators follow: the site's docs, complete, abridged or
5422
+ * expanded from the index, joined into one Markdown document whatever content
5423
+ * type the server sends.
5424
+ *
5425
+ * @param url The URL to inspect.
5426
+ * @returns Whether the URL path basename is `llms-<anything>.txt`.
5427
+ */
5428
+ function isLlmsTxtCompanionUrl(url) {
5429
+ return /^llms-.+\.txt$/.test(pathBasename(url) ?? "");
5430
+ }
5431
+ /**
3520
5432
  * Parses llms.txt Markdown into project metadata and curated links.
3521
5433
  * @param content The llms.txt Markdown content.
3522
5434
  * @returns Parsed llms.txt metadata and links, or an empty result for invalid content.
@@ -3800,7 +5712,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
3800
5712
  * crawl queue entirely.
3801
5713
  */
3802
5714
  shouldProcessUrl(url, options, context = {}) {
3803
- if (isLlmsTxtUrl(url)) return false;
5715
+ if (isLlmsTxtUrl(url) || isLlmsTxtCompanionUrl(url)) return false;
3804
5716
  if (!(url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots))) {
3805
5717
  const scope = options.scope ?? "subpages";
3806
5718
  try {
@@ -4327,140 +6239,105 @@ var MinimumChunkSizeError = class extends SplitterError {
4327
6239
  * Generic error for content splitting failures
4328
6240
  */
4329
6241
  var ContentSplitterError = class extends SplitterError {};
4330
- // src/splitter/splitters/CodeContentSplitter.ts
6242
+ // src/splitter/splitters/fenceState.ts
4331
6243
  /**
4332
- * Splits code content while preserving language information and formatting.
4333
- * Uses line boundaries for splitting and ensures each chunk is properly
4334
- * wrapped with language-specific code block markers.
6244
+ * Tracks whether a markdown string ends inside an open fenced code block. Used
6245
+ * by content splitters to avoid cutting chunks in the middle of a fence, which
6246
+ * would leave one chunk with an unmatched opener and the next chunk with an
6247
+ * unmatched closer.
6248
+ *
6249
+ * Follows CommonMark fence semantics for the cases that matter to us: a fence
6250
+ * is a line whose only leading non-whitespace content is three or more
6251
+ * identical backticks or three or more identical tildes. The closing fence
6252
+ * must use the same character and at least as many of them as the opener.
6253
+ * Backticks and tildes do not pair across types.
4335
6254
  */
4336
- var CodeContentSplitter = class {
4337
- options;
4338
- constructor(options) {
4339
- this.options = options;
4340
- }
4341
- async split(content) {
4342
- const infoString = (content.match(/^```([^\n]*)\n/)?.[1] ?? "").trimEnd();
4343
- const lines = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "").split("\n");
4344
- const chunks = [];
4345
- let currentChunkLines = [];
4346
- for (const line of lines) {
4347
- const singleLineSize = this.wrap(line, infoString).length;
4348
- if (singleLineSize > this.options.chunkSize) throw new MinimumChunkSizeError(singleLineSize, this.options.chunkSize);
4349
- currentChunkLines.push(line);
4350
- if (this.wrap(currentChunkLines.join("\n"), infoString).length > this.options.chunkSize && currentChunkLines.length > 1) {
4351
- const lastLine = currentChunkLines.pop();
4352
- chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
4353
- currentChunkLines = [lastLine];
4354
- }
4355
- }
4356
- if (currentChunkLines.length > 0) chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
4357
- return chunks;
4358
- }
4359
- wrap(content, infoString) {
4360
- return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
4361
- }
4362
- };
4363
- // src/splitter/splitters/fenceState.ts
4364
6255
  var FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
4365
- var FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
4366
- function splitLinesWithOffsets(text) {
4367
- const lines = [];
4368
- let offset = 0;
4369
- while (offset <= text.length) {
4370
- const nlIndex = text.indexOf("\n", offset);
4371
- if (nlIndex === -1) {
4372
- if (offset < text.length) lines.push({
4373
- content: text.slice(offset),
4374
- offset,
4375
- newlineLength: 0
4376
- });
4377
- return lines;
4378
- }
4379
- lines.push({
4380
- content: text.slice(offset, nlIndex),
4381
- offset,
4382
- newlineLength: 1
4383
- });
4384
- offset = nlIndex + 1;
4385
- }
4386
- return lines;
4387
- }
4388
- function isClosingFence(line, delimiter, openerCount) {
4389
- return new RegExp(`^${FENCE_PREFIX}\\${delimiter}{${openerCount},}[ \\t]*$`).test(line);
4390
- }
6256
+ var FENCE_OPENER = new RegExp(`^(${FENCE_PREFIX})(\`{3,}|~{3,})`);
4391
6257
  /**
4392
- * Scan the input and return non-overlapping fence regions. Each region covers
4393
- * the line containing the opener through the line containing the matching
4394
- * closer (inclusive of trailing newlines). Unclosed openers produce a region
4395
- * extending to the end of input.
6258
+ * Reads a fence opener from one line.
6259
+ *
6260
+ * @param line A single line, without its newline.
6261
+ * @returns The opener's parts, or null when the line does not open a fence.
4396
6262
  */
4397
- function findFenceRegions(text) {
4398
- const regions = [];
4399
- const lines = splitLinesWithOffsets(text);
4400
- let i = 0;
4401
- while (i < lines.length) {
4402
- const opener = FENCE_OPENER.exec(lines[i].content);
4403
- if (!opener) {
4404
- i += 1;
4405
- continue;
4406
- }
4407
- const delimiter = opener[1][0];
4408
- const count = opener[1].length;
4409
- const startOffset = lines[i].offset;
4410
- let closerLineIndex = -1;
4411
- for (let j = i + 1; j < lines.length; j++) if (isClosingFence(lines[j].content, delimiter, count)) {
4412
- closerLineIndex = j;
4413
- break;
4414
- }
4415
- if (closerLineIndex === -1) {
4416
- regions.push({
4417
- startOffset,
4418
- endOffset: text.length
4419
- });
4420
- break;
4421
- }
4422
- const closerLine = lines[closerLineIndex];
4423
- const endOffset = closerLine.offset + closerLine.content.length + closerLine.newlineLength;
4424
- regions.push({
4425
- startOffset,
4426
- endOffset
4427
- });
4428
- i = closerLineIndex + 1;
4429
- }
4430
- return regions;
6263
+ function parseFenceOpener(line) {
6264
+ const match = FENCE_OPENER.exec(line);
6265
+ if (!match) return null;
6266
+ return {
6267
+ prefix: match[1],
6268
+ delimiter: match[2][0],
6269
+ length: match[2].length
6270
+ };
4431
6271
  }
4432
6272
  /**
4433
- * Returns true if `chunk` ends while inside an open fence — i.e. its triple-
4434
- * backtick/tilde count is odd in a way that leaves a dangling opener.
6273
+ * Builds the pattern for the line that closes a fence: the same character, at
6274
+ * least as many of them, and as permissive about the prefix as the opener.
4435
6275
  */
4436
- function hasOpenFenceAtEnd(chunk) {
4437
- const regions = findFenceRegions(chunk);
4438
- if (regions.length === 0) return false;
4439
- const last = regions[regions.length - 1];
4440
- if (last.endOffset !== chunk.length) return false;
4441
- const lines = splitLinesWithOffsets(chunk.slice(last.startOffset));
4442
- if (lines.length < 2) return true;
4443
- const opener = FENCE_OPENER.exec(lines[0].content);
4444
- if (!opener) return false;
4445
- return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
6276
+ function closingFencePattern(opener) {
6277
+ return new RegExp(`^${FENCE_PREFIX}\\${opener.delimiter}{${opener.length},}[ \\t]*$`);
4446
6278
  }
6279
+ /**
6280
+ * Follows fence state across consecutive pieces of one text.
6281
+ *
6282
+ * Callers that join pieces in order can ask whether the text so far ends
6283
+ * inside a fence without rescanning it, which keeps a document with a long or
6284
+ * unclosed fence linear instead of quadratic.
6285
+ */
6286
+ var FenceTracker = class {
6287
+ /** Matches the line that closes the open fence, or null while none is open. */
6288
+ closer = null;
6289
+ partialLine = "";
6290
+ /**
6291
+ * Adds the next piece of the text.
6292
+ *
6293
+ * @param text The piece, joined directly after the previous one.
6294
+ */
6295
+ feed(text) {
6296
+ const lines = `${this.partialLine}${text}`.split("\n");
6297
+ this.partialLine = lines.pop() ?? "";
6298
+ for (const line of lines) this.closer = this.next(this.closer, line);
6299
+ }
6300
+ /**
6301
+ * Reports whether the text fed so far ends inside an open fence. A trailing
6302
+ * line without its newline counts as a whole line.
6303
+ *
6304
+ * @returns True when a fence is open at the end of the text.
6305
+ */
6306
+ isOpen() {
6307
+ return (this.partialLine ? this.next(this.closer, this.partialLine) : this.closer) !== null;
6308
+ }
6309
+ next(closer, line) {
6310
+ if (closer === null) {
6311
+ const opener = parseFenceOpener(line);
6312
+ return opener ? closingFencePattern(opener) : null;
6313
+ }
6314
+ return closer.test(line) ? null : closer;
6315
+ }
6316
+ };
4447
6317
  // src/splitter/splitters/TextContentSplitter.ts
4448
6318
  /**
4449
6319
  * Splits text content using a hierarchical approach:
4450
6320
  * 1. Try splitting by paragraphs (double newlines)
4451
- * 2. If chunks still too large, split by single newlines
4452
- * 3. Finally, use word boundaries via LangChain's splitter
6321
+ * 2. If chunks still too large, split by single newlines and merge them back
6322
+ * up to the chunk size
6323
+ * 3. Split only the lines that are still too large, at word boundaries
4453
6324
  *
4454
- * Across all strategies the splitter preserves fenced code block balance: if
4455
- * splitting would leave a chunk ending inside an open ``` or ~~~ fence, that
4456
- * chunk is merged with the following chunk until the fence closes. When this
4457
- * merging forces a chunk past `chunkSize`, the splitter accepts the oversize
4458
- * chunk and emits a warning rather than break the fence.
6325
+ * Text is split to stay within `chunkSize`. Across all strategies the splitter
6326
+ * also preserves fenced code block balance: a chunk never ends inside an open
6327
+ * ``` or ~~~ fence. A fenced block stays whole up to `maxChunkSize`, even when
6328
+ * that is larger than `chunkSize`. A block larger than `maxChunkSize` is cut at
6329
+ * line boundaries. With `rewrapFences`, each piece is closed and reopened with
6330
+ * the block's own opener line, the same way the Markdown code splitter re-wraps
6331
+ * a long code block; without it, nothing is added and the chunks join back to
6332
+ * the input. No chunk exceeds `maxChunkSize`, because an oversized chunk cannot
6333
+ * be embedded.
4459
6334
  */
4460
6335
  var TextContentSplitter = class {
4461
6336
  options;
6337
+ maxChunkSize;
4462
6338
  constructor(options) {
4463
6339
  this.options = options;
6340
+ this.maxChunkSize = Math.max(options.maxChunkSize ?? 0, options.chunkSize);
4464
6341
  }
4465
6342
  /**
4466
6343
  * Splits text content into chunks while trying to preserve semantic boundaries.
@@ -4469,28 +6346,38 @@ var TextContentSplitter = class {
4469
6346
  */
4470
6347
  async split(content) {
4471
6348
  if (content.length <= this.options.chunkSize) return [content];
4472
- const longestWord = content.split(/\s+/).reduce((max, word) => word.length > max.length ? word : max);
4473
- if (longestWord.length > this.options.chunkSize) throw new MinimumChunkSizeError(longestWord.length, this.options.chunkSize);
4474
- const paragraphChunks = this.mergeForFenceBalance(this.splitByParagraphs(content), "");
6349
+ const paragraphChunks = this.mergeForFenceBalance(this.splitByParagraphs(content));
4475
6350
  if (this.areChunksValid(paragraphChunks)) return paragraphChunks;
4476
- const lineChunks = this.mergeForFenceBalance(this.splitByLines(content), "");
4477
- if (this.areChunksValid(lineChunks)) return this.mergeChunks(lineChunks, "");
4478
- const wordChunks = this.mergeForFenceBalance(await this.splitByWords(content), " ");
4479
- const merged = this.mergeChunks(wordChunks, " ");
4480
- this.warnOversize(merged);
4481
- return merged;
6351
+ const units = this.mergeForFenceBalance(this.splitByLines(content)).flatMap((unit) => this.fitUnit(unit));
6352
+ return this.mergeChunks(units);
6353
+ }
6354
+ /**
6355
+ * Returns a line unit whole when it fits, or the pieces it is cut into. A
6356
+ * unit is either one fenced block, which may use up to `maxChunkSize`, or
6357
+ * one line with no fence in it, which is held to `chunkSize`.
6358
+ */
6359
+ fitUnit(unit) {
6360
+ if (unit.length <= this.options.chunkSize) return [unit];
6361
+ const firstLineEnd = unit.indexOf("\n");
6362
+ const opener = firstLineEnd === -1 ? null : parseFenceOpener(unit.slice(0, firstLineEnd));
6363
+ if (opener === null) return splitLongLine(unit, this.options.chunkSize, this.maxChunkSize);
6364
+ if (unit.length <= this.maxChunkSize) return [unit];
6365
+ return this.splitFencedBlock(unit, unit.slice(0, firstLineEnd + 1), opener);
4482
6366
  }
4483
6367
  /**
4484
6368
  * Walks `chunks` left to right and merges adjacent chunks whenever the running
4485
6369
  * buffer ends inside an open fenced code block. Guarantees that every emitted
4486
- * chunk has balanced fences (i.e. `hasOpenFenceAtEnd` returns false).
6370
+ * chunk has balanced fences, except a trailing fence the input never closes.
6371
+ * The chunks must be consecutive pieces of one text, joined without a separator.
4487
6372
  */
4488
- mergeForFenceBalance(chunks, separator) {
6373
+ mergeForFenceBalance(chunks) {
4489
6374
  const result = [];
6375
+ const fences = new FenceTracker();
4490
6376
  let buffer = "";
4491
6377
  for (const chunk of chunks) {
4492
- buffer = buffer ? `${buffer}${separator}${chunk}` : chunk;
4493
- if (!hasOpenFenceAtEnd(buffer)) {
6378
+ buffer += chunk;
6379
+ fences.feed(chunk);
6380
+ if (!fences.isOpen()) {
4494
6381
  result.push(buffer);
4495
6382
  buffer = "";
4496
6383
  }
@@ -4498,8 +6385,29 @@ var TextContentSplitter = class {
4498
6385
  if (buffer) result.push(buffer);
4499
6386
  return result;
4500
6387
  }
4501
- warnOversize(chunks) {
4502
- for (const chunk of chunks) if (chunk.length > this.options.chunkSize) logger.warn(`⚠ TextContentSplitter emitted oversize chunk to preserve fence balance: ${chunk.length} > ${this.options.chunkSize}`);
6388
+ /**
6389
+ * Cuts a fenced block larger than `maxChunkSize` into pieces within it. With
6390
+ * `rewrapFences` each piece is wrapped in the block's own fences; otherwise
6391
+ * the pieces are plain cuts that join back to the block.
6392
+ */
6393
+ splitFencedBlock(unit, openerLine, opener) {
6394
+ const closerLine = `${opener.prefix}${opener.delimiter.repeat(opener.length)}\n`;
6395
+ const room = this.maxChunkSize - openerLine.length - closerLine.length - 1;
6396
+ if (!this.options.rewrapFences || room <= 0) return this.packLines(unit, this.maxChunkSize);
6397
+ const pieces = this.packLines(unit.slice(openerLine.length), room);
6398
+ logger.debug(`Split a ${unit.length}-char fenced block into ${pieces.length} chunks of at most ${this.maxChunkSize} chars`);
6399
+ return pieces.map((piece, index) => {
6400
+ if (index === pieces.length - 1) return `${openerLine}${piece}`;
6401
+ return `${openerLine}${piece}${piece.endsWith("\n") ? closerLine : `\n${closerLine}`}`;
6402
+ });
6403
+ }
6404
+ /**
6405
+ * Cuts text at line boundaries into pieces of at most `limit` characters,
6406
+ * cutting a longer line with `splitLongLine`. The pieces join back to the text.
6407
+ */
6408
+ packLines(text, limit) {
6409
+ const lines = this.splitByLines(text).flatMap((line) => line.length <= limit ? [line] : splitLongLine(line, limit));
6410
+ return this.mergeChunks(lines, limit);
4503
6411
  }
4504
6412
  /**
4505
6413
  * Checks if all chunks are within the maximum size limit
@@ -4545,19 +6453,11 @@ var TextContentSplitter = class {
4545
6453
  return chunks;
4546
6454
  }
4547
6455
  /**
4548
- * Uses LangChain's recursive splitter for word-based splitting as a last resort
4549
- */
4550
- async splitByWords(text) {
4551
- return await new RecursiveCharacterTextSplitter({
4552
- chunkSize: this.options.chunkSize,
4553
- chunkOverlap: 0
4554
- }).splitText(text);
4555
- }
4556
- /**
4557
6456
  * Attempts to merge small chunks with previous chunks to minimize fragmentation.
4558
- * Only merges if combined size is within maxChunkSize.
6457
+ * Only merges if the combined size is within `limit`, which defaults to `chunkSize`.
6458
+ * The chunks are joined as they are, since each keeps its own newlines.
4559
6459
  */
4560
- mergeChunks(chunks, separator) {
6460
+ mergeChunks(chunks, limit = this.options.chunkSize) {
4561
6461
  const mergedChunks = [];
4562
6462
  let currentChunk = null;
4563
6463
  for (const chunk of chunks) {
@@ -4565,7 +6465,7 @@ var TextContentSplitter = class {
4565
6465
  currentChunk = chunk;
4566
6466
  continue;
4567
6467
  }
4568
- if (this.getChunkSize(currentChunk) + this.getChunkSize(chunk) + separator.length <= this.options.chunkSize) currentChunk = `${currentChunk}${separator}${chunk}`;
6468
+ if (this.getChunkSize(currentChunk) + this.getChunkSize(chunk) <= limit) currentChunk = `${currentChunk}${chunk}`;
4569
6469
  else {
4570
6470
  mergedChunks.push(currentChunk);
4571
6471
  currentChunk = chunk;
@@ -4581,13 +6481,82 @@ var TextContentSplitter = class {
4581
6481
  return content;
4582
6482
  }
4583
6483
  };
6484
+ /**
6485
+ * Cuts a line that is too long into pieces that join back to it.
6486
+ *
6487
+ * Each piece ends after the last space or tab within `limit`. When there is no
6488
+ * space to cut at, the line starts with one long token: it stays whole up to
6489
+ * `hardLimit`, and is cut inside only when it is longer still. A cut inside a
6490
+ * token is the last resort, used only when nothing else stays within the limit.
6491
+ *
6492
+ * @param line The line to cut.
6493
+ * @param limit The size each piece should stay within.
6494
+ * @param hardLimit The size no piece may exceed; defaults to `limit`.
6495
+ * @returns The pieces, in order.
6496
+ */
6497
+ function splitLongLine(line, limit, hardLimit = limit) {
6498
+ const hard = Math.max(hardLimit, limit);
6499
+ const pieces = [];
6500
+ let start = 0;
6501
+ while (line.length - start > limit) {
6502
+ const window = line.slice(start, start + limit);
6503
+ const lastSpace = Math.max(window.lastIndexOf(" "), window.lastIndexOf(" "));
6504
+ let cut;
6505
+ if (lastSpace > 0) cut = lastSpace + 1;
6506
+ else {
6507
+ const spaceAfter = line.slice(start + limit, start + hard).search(/[ \t]/);
6508
+ cut = spaceAfter === -1 ? Math.min(hard, line.length - start) : limit + spaceAfter + 1;
6509
+ }
6510
+ pieces.push(line.slice(start, start + cut));
6511
+ start += cut;
6512
+ }
6513
+ if (start < line.length) pieces.push(line.slice(start));
6514
+ return pieces;
6515
+ }
6516
+ // src/splitter/splitters/CodeContentSplitter.ts
6517
+ /**
6518
+ * Splits code content while preserving language information and formatting.
6519
+ * Uses line boundaries for splitting and ensures each chunk is properly
6520
+ * wrapped with language-specific code block markers.
6521
+ */
6522
+ var CodeContentSplitter = class {
6523
+ options;
6524
+ constructor(options) {
6525
+ this.options = options;
6526
+ }
6527
+ async split(content) {
6528
+ const infoString = (content.match(/^```([^\n]*)\n/)?.[1] ?? "").trimEnd();
6529
+ const strippedContent = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "");
6530
+ const room = this.options.chunkSize - this.wrap("", infoString).length;
6531
+ if (room <= 0) throw new MinimumChunkSizeError(this.wrap("", infoString).length, this.options.chunkSize);
6532
+ const lines = strippedContent.split("\n").flatMap((line) => line.length <= room ? [line] : splitLongLine(line, room));
6533
+ const chunks = [];
6534
+ let currentChunkLines = [];
6535
+ for (const line of lines) {
6536
+ currentChunkLines.push(line);
6537
+ if (this.wrap(currentChunkLines.join("\n"), infoString).length > this.options.chunkSize && currentChunkLines.length > 1) {
6538
+ const lastLine = currentChunkLines.pop();
6539
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6540
+ currentChunkLines = [lastLine];
6541
+ }
6542
+ }
6543
+ if (currentChunkLines.length > 0) chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6544
+ return chunks;
6545
+ }
6546
+ wrap(content, infoString) {
6547
+ return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
6548
+ }
6549
+ };
4584
6550
  // src/splitter/splitters/ListContentSplitter.ts
4585
6551
  var ListContentSplitter = class {
4586
6552
  options;
4587
6553
  textSplitter;
4588
6554
  constructor(options) {
4589
6555
  this.options = options;
4590
- this.textSplitter = new TextContentSplitter(options);
6556
+ this.textSplitter = new TextContentSplitter({
6557
+ rewrapFences: true,
6558
+ ...options
6559
+ });
4591
6560
  }
4592
6561
  async split(content) {
4593
6562
  if (content.length <= this.options.chunkSize) return [content];
@@ -4766,10 +6735,17 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
4766
6735
  return markdown;
4767
6736
  }
4768
6737
  });
4769
- this.textSplitter = new TextContentSplitter({ chunkSize: this.preferredChunkSize });
6738
+ this.textSplitter = new TextContentSplitter({
6739
+ chunkSize: this.preferredChunkSize,
6740
+ maxChunkSize: this.maxChunkSize,
6741
+ rewrapFences: true
6742
+ });
4770
6743
  this.codeSplitter = new CodeContentSplitter({ chunkSize: this.maxChunkSize });
4771
6744
  this.tableSplitter = new TableContentSplitter({ chunkSize: this.maxChunkSize });
4772
- this.listSplitter = new ListContentSplitter({ chunkSize: this.preferredChunkSize });
6745
+ this.listSplitter = new ListContentSplitter({
6746
+ chunkSize: this.preferredChunkSize,
6747
+ maxChunkSize: this.maxChunkSize
6748
+ });
4773
6749
  }
4774
6750
  /**
4775
6751
  * Main entry point for splitting markdown content
@@ -4876,7 +6852,7 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
4876
6852
  let currentSection = this.createRootSection();
4877
6853
  const sections = [];
4878
6854
  const stack = [currentSection];
4879
- for (const element of Array.from(body.children)) {
6855
+ for (let element = body.firstElementChild; element !== null; element = element.nextElementSibling) {
4880
6856
  const headingMatch = element.tagName.match(/H([1-6])/);
4881
6857
  if (headingMatch) {
4882
6858
  const level = Number.parseInt(headingMatch[1], 10);
@@ -6666,7 +8642,7 @@ function mergePlaywrightHeaders(requestHeaders, customHeaders, credentials, orig
6666
8642
  Authorization: `Basic ${basic}`
6667
8643
  };
6668
8644
  }
6669
- return withMarkdownPreferredAccept(headers, customHeaders);
8645
+ return headers;
6670
8646
  }
6671
8647
  // src/scraper/middleware/HtmlSanitizerMiddleware.ts
6672
8648
  /**
@@ -7355,7 +9331,7 @@ var TextDocumentSplitter = class {
7355
9331
  }
7356
9332
  }));
7357
9333
  } catch (error) {
7358
- if (!(error instanceof MinimumChunkSizeError) && error instanceof Error) console.warn(`Unexpected text splitting error: ${error.message}. Forcing character-based split.`);
9334
+ console.warn(`Unexpected text splitting error: ${error instanceof Error ? error.message : String(error)}. Forcing character-based split.`);
7359
9335
  const chunks = [];
7360
9336
  let offset = 0;
7361
9337
  while (offset < content.length) {
@@ -7716,29 +9692,29 @@ var MarkdownLinkExtractorMiddleware = class {
7716
9692
  */
7717
9693
  async process(context, next) {
7718
9694
  if (!Array.isArray(context.links)) context.links = [];
7719
- for (const link of extractMarkdownLinks(context.content)) if (!context.links.includes(link)) context.links.push(link);
9695
+ const seen = new Set(context.links);
9696
+ for (const link of extractMarkdownLinks(context.content)) if (!seen.has(link)) {
9697
+ seen.add(link);
9698
+ context.links.push(link);
9699
+ }
7720
9700
  await next();
7721
9701
  }
7722
9702
  };
7723
9703
  function extractMarkdownLinks(content) {
7724
- const links = [];
9704
+ const links = /* @__PURE__ */ new Set();
7725
9705
  const referenceDefinitions = /* @__PURE__ */ new Map();
7726
9706
  for (const match of content.matchAll(referenceDefinitionPattern)) {
7727
9707
  const label = normalizeReferenceLabel(match[1]);
7728
9708
  const target = cleanReferenceTarget(match[2]);
7729
9709
  if (label && target && !referenceDefinitions.has(label)) referenceDefinitions.set(label, target);
7730
9710
  }
7731
- for (const match of content.matchAll(inlineLinkPattern)) addUniqueLink(links, match[2]);
9711
+ for (const match of content.matchAll(inlineLinkPattern)) if (match[2]) links.add(match[2]);
7732
9712
  for (const match of content.matchAll(referenceLinkPattern)) {
7733
9713
  const target = referenceDefinitions.get(normalizeReferenceLabel(match[2]));
7734
- if (target) addUniqueLink(links, target);
9714
+ if (target) links.add(target);
7735
9715
  }
7736
9716
  return links;
7737
9717
  }
7738
- function addUniqueLink(links, target) {
7739
- if (!target || links.includes(target)) return;
7740
- links.push(target);
7741
- }
7742
9718
  function normalizeReferenceLabel(label) {
7743
9719
  return label?.trim().replace(/\s+/g, " ").toLowerCase() ?? "";
7744
9720
  }
@@ -10090,9 +12066,15 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
10090
12066
  * of them, while react.dev — the `text/plain` host — returns a real 404.
10091
12067
  * It cost the published Markdown of every such site and bought nothing.
10092
12068
  * Soft-error detection needs to read the body, and belongs elsewhere.
12069
+ *
12070
+ * The llms.txt companions (`llms-full.txt`, `llms-small.txt`, ...) are
12071
+ * Markdown by convention despite their extension, and servers send them as
12072
+ * `text/plain`. They are restated the same way but keep their own identity:
12073
+ * each is a document of its own, not a variant of another page. Other `.txt`
12074
+ * files stay plain text.
10093
12075
  */
10094
12076
  asMarkdownRepresentation(url, rawContent) {
10095
- if (!this.isMarkdownUrl(url) || !this.isAcceptableMarkdownVariant(rawContent)) return rawContent;
12077
+ if (!(this.isMarkdownUrl(url) || isLlmsTxtCompanionUrl(url)) || !this.isAcceptableMarkdownVariant(rawContent)) return rawContent;
10096
12078
  return MimeTypeUtils.isMarkdown(rawContent.mimeType) ? rawContent : {
10097
12079
  ...rawContent,
10098
12080
  mimeType: "text/markdown"
@@ -10777,6 +12759,8 @@ var PipelineManager = class {
10777
12759
  }
10778
12760
  /**
10779
12761
  * Converts internal job representation to public job interface.
12762
+ * The processed page content (`progress.result`) stays on the internal job: it
12763
+ * can weigh hundreds of kilobytes per job and no consumer of the public job reads it.
10780
12764
  */
10781
12765
  toPublicJob(job) {
10782
12766
  return {
@@ -10784,7 +12768,10 @@ var PipelineManager = class {
10784
12768
  library: job.library,
10785
12769
  version: job.version || null,
10786
12770
  status: job.status,
10787
- progress: job.progress,
12771
+ progress: job.progress ? {
12772
+ ...job.progress,
12773
+ result: null
12774
+ } : null,
10788
12775
  error: job.error ? { message: job.error.message } : null,
10789
12776
  createdAt: job.createdAt,
10790
12777
  startedAt: job.startedAt,
@@ -10999,50 +12986,57 @@ var PipelineManager = class {
10999
12986
  async registerScrapeJob(library, normalizedVersion, options, enqueue) {
11000
12987
  const requested = enqueue.onExisting ?? "reject-version";
11001
12988
  const policy = options.clean === false && requested === "reject-version" ? "replace" : requested;
11002
- const claimed = await this.store.claimVersion(library, normalizedVersion, policy);
11003
- await this.stopJobsFor(library, normalizedVersion);
11004
- const label = formatVersionLabel(claimed.library, normalizedVersion);
11005
- const normalizedOptions = this.normalizeScraperOptions(options);
11006
- const jobId = v4();
11007
- const abortController = new AbortController();
11008
- let resolveCompletion;
11009
- let rejectCompletion;
11010
- const completionPromise = new Promise((resolve, reject) => {
11011
- resolveCompletion = resolve;
11012
- rejectCompletion = reject;
11013
- });
11014
- completionPromise.catch(() => {});
11015
- const job = {
11016
- id: jobId,
11017
- library: claimed.library,
11018
- version: normalizedVersion,
11019
- versionId: claimed.versionId,
11020
- status: PipelineJobStatus.QUEUED,
11021
- progress: null,
11022
- error: null,
11023
- createdAt: /* @__PURE__ */ new Date(),
11024
- startedAt: null,
11025
- finishedAt: null,
11026
- abortController,
11027
- completionPromise,
11028
- resolveCompletion,
11029
- rejectCompletion,
11030
- progressPages: 0,
11031
- progressPagesIndexed: 0,
11032
- progressMaxPages: 0,
11033
- errorMessage: null,
11034
- updatedAt: /* @__PURE__ */ new Date(),
11035
- sourceUrl: normalizedOptions.url,
11036
- scraperOptions: normalizedOptions
11037
- };
11038
- this.jobMap.set(jobId, job);
11039
- this.jobQueue.push(jobId);
11040
- logger.info(`📝 Job enqueued: ${jobId} for ${label}`);
11041
- await this.updateJobStatus(job, PipelineJobStatus.QUEUED);
11042
- if (this.isRunning) this._processQueue().catch((error) => {
11043
- logger.error(`❌ Error in processQueue during enqueue: ${error}`);
11044
- });
11045
- return jobId;
12989
+ const claimed = await this.store.claimVersion(library, normalizedVersion, policy, { markQueued: true });
12990
+ let registered = false;
12991
+ try {
12992
+ await this.stopJobsFor(library, normalizedVersion);
12993
+ const label = formatVersionLabel(claimed.library, normalizedVersion);
12994
+ const normalizedOptions = this.normalizeScraperOptions(options);
12995
+ const jobId = v4();
12996
+ const abortController = new AbortController();
12997
+ let resolveCompletion;
12998
+ let rejectCompletion;
12999
+ const completionPromise = new Promise((resolve, reject) => {
13000
+ resolveCompletion = resolve;
13001
+ rejectCompletion = reject;
13002
+ });
13003
+ completionPromise.catch(() => {});
13004
+ const job = {
13005
+ id: jobId,
13006
+ library: claimed.library,
13007
+ version: normalizedVersion,
13008
+ versionId: claimed.versionId,
13009
+ status: PipelineJobStatus.QUEUED,
13010
+ progress: null,
13011
+ error: null,
13012
+ createdAt: /* @__PURE__ */ new Date(),
13013
+ startedAt: null,
13014
+ finishedAt: null,
13015
+ abortController,
13016
+ completionPromise,
13017
+ resolveCompletion,
13018
+ rejectCompletion,
13019
+ progressPages: 0,
13020
+ progressPagesIndexed: 0,
13021
+ progressMaxPages: 0,
13022
+ errorMessage: null,
13023
+ updatedAt: /* @__PURE__ */ new Date(),
13024
+ sourceUrl: normalizedOptions.url,
13025
+ scraperOptions: normalizedOptions
13026
+ };
13027
+ this.jobMap.set(jobId, job);
13028
+ this.jobQueue.push(jobId);
13029
+ registered = true;
13030
+ logger.info(`📝 Job enqueued: ${jobId} for ${label}`);
13031
+ await this.updateJobStatus(job, PipelineJobStatus.QUEUED);
13032
+ if (this.isRunning) this._processQueue().catch((error) => {
13033
+ logger.error(`❌ Error in processQueue during enqueue: ${error}`);
13034
+ });
13035
+ return jobId;
13036
+ } catch (error) {
13037
+ if (!registered && claimed.previousStatus) await this.store.restoreVersionStatusIfQueued(claimed.versionId, claimed.previousStatus).catch(() => {});
13038
+ throw error;
13039
+ }
11046
13040
  }
11047
13041
  /**
11048
13042
  * Enqueues a refresh job for an existing library version by re-scraping all pages
@@ -11344,7 +13338,10 @@ var PipelineManager = class {
11344
13338
  const publicJob = this.toPublicJob(job);
11345
13339
  this.eventBus.emit(EventType.JOB_PROGRESS, {
11346
13340
  job: publicJob,
11347
- progress
13341
+ progress: {
13342
+ ...progress,
13343
+ result: null
13344
+ }
11348
13345
  });
11349
13346
  logger.debug(`Job ${job.id} progress: ${progress.pagesScraped}/${progress.totalPages} processed, ${progress.pagesIndexed} indexed`);
11350
13347
  }
@@ -11416,6 +13413,12 @@ var DocumentManagementClient = class {
11416
13413
  async compact(options) {
11417
13414
  return this.client.compact.mutate(options ?? {});
11418
13415
  }
13416
+ async renameLibrary(library, newName) {
13417
+ return this.client.renameLibrary.mutate({
13418
+ library,
13419
+ newName
13420
+ });
13421
+ }
11419
13422
  async getVersionsByStatus(statuses) {
11420
13423
  return this.client.getVersionsByStatus.query({ statuses });
11421
13424
  }
@@ -12200,7 +14203,6 @@ async function applyMigrations(db, options) {
12200
14203
  db.pragma("synchronous = NORMAL");
12201
14204
  db.pragma("mmap_size = 268435456");
12202
14205
  db.pragma("cache_size = -64000");
12203
- db.pragma("temp_store = MEMORY");
12204
14206
  logger.debug("Applied safe migration pragmas");
12205
14207
  } catch (_error) {
12206
14208
  logger.warn("⚠️ Could not apply all migration pragmas");
@@ -12265,6 +14267,37 @@ async function applyMigrations(db, options) {
12265
14267
  logger.warn("⚠️ Could not apply all production database settings");
12266
14268
  }
12267
14269
  }
14270
+ // src/store/openDatabase.ts
14271
+ /**
14272
+ * Opens the SQLite database with better-sqlite3. The package ships Node-API
14273
+ * binaries for Windows, macOS and Linux (glibc and musl) on x64 and arm64, so
14274
+ * the binary loads under every Node.js version from 22.14 up and under Bun,
14275
+ * without an install script or a download.
14276
+ */
14277
+ /** The Node-API version better-sqlite3's binaries are built for. */
14278
+ var REQUIRED_NODE_API = 10;
14279
+ /**
14280
+ * Opens a better-sqlite3 database. Open databases only through this function,
14281
+ * so a binary that cannot load ends in one actionable error instead of a raw
14282
+ * module resolution failure or a crash.
14283
+ *
14284
+ * @param dbPath - Path of the database file, or `:memory:`
14285
+ * @param options - better-sqlite3 options, such as `readonly`
14286
+ * @returns The open database
14287
+ * @throws NodeApiUnsupportedError when the runtime provides an older Node-API version than the binary needs
14288
+ * @throws NativeModuleUnavailableError when no better-sqlite3 binary loads on this platform
14289
+ */
14290
+ function openDatabase(dbPath, options = {}) {
14291
+ const nodeApi = process.versions.napi;
14292
+ if (nodeApi !== void 0 && Number(nodeApi) < REQUIRED_NODE_API) throw new NodeApiUnsupportedError(nodeApi, REQUIRED_NODE_API);
14293
+ try {
14294
+ return new Database(dbPath, options);
14295
+ } catch (error) {
14296
+ if (!isNativeModuleError(error)) throw error;
14297
+ logger.debug(`Failed to load better-sqlite3: ${error}`);
14298
+ throw new NativeModuleUnavailableError();
14299
+ }
14300
+ }
12268
14301
  // src/store/DocumentStore.ts
12269
14302
  /**
12270
14303
  * How many full-text candidates are sorted by score alone before the
@@ -12275,6 +14308,13 @@ async function applyMigrations(db, options) {
12275
14308
  */
12276
14309
  var FTS_TIE_WINDOW_FACTOR = 2;
12277
14310
  /**
14311
+ * The shortest beginning of a text worth halving again when the provider keeps
14312
+ * rejecting it as too large. A provider that still refuses this little has a
14313
+ * limit far below any chunk size, which is a configuration fault to report
14314
+ * rather than retry.
14315
+ */
14316
+ var MIN_TRUNCATED_EMBEDDING_CHARS = 256;
14317
+ /**
12278
14318
  * Orders search results that score the same: by page URL, then by position on
12279
14319
  * the page. Without it, ties fall to storage order, which depends on when and
12280
14320
  * how fast each page was indexed.
@@ -12416,7 +14456,7 @@ var DocumentStore = class {
12416
14456
  this.embeddingBatchSize = this.config.embeddings.batchSize;
12417
14457
  this.embeddingBatchChars = this.config.embeddings.batchChars;
12418
14458
  this.embeddingInitTimeoutMs = this.config.embeddings.initTimeoutMs;
12419
- this.db = new Database(dbPath);
14459
+ this.db = openDatabase(dbPath);
12420
14460
  this.embeddingConfig = this.resolveEmbeddingConfig(appConfig.app.embeddingModel);
12421
14461
  }
12422
14462
  resolveEmbeddingConfig(modelSpec) {
@@ -12448,8 +14488,11 @@ var DocumentStore = class {
12448
14488
  getPageId: this.db.prepare("SELECT id, source_content_type FROM pages WHERE version_id = ? AND url = ?"),
12449
14489
  insertLibrary: this.db.prepare("INSERT INTO libraries (name, display_name) VALUES (?, ?)"),
12450
14490
  getLibraryIdByName: this.db.prepare("SELECT id, display_name FROM libraries WHERE name = ?"),
14491
+ renameLibrary: this.db.prepare("UPDATE libraries SET name = ?, display_name = ? WHERE id = ?"),
14492
+ getActiveVersionStatusesByLibraryId: this.db.prepare("SELECT DISTINCT status FROM versions WHERE library_id = ? AND status IN ('queued', 'running', 'updating')"),
12451
14493
  getLibraryById: this.db.prepare("SELECT * FROM libraries WHERE id = ?"),
12452
14494
  insertVersion: this.db.prepare("INSERT INTO versions (library_id, name, status) VALUES (?, ?, 'not_indexed') ON CONFLICT(library_id, name) DO NOTHING"),
14495
+ markVersionQueued: this.db.prepare("UPDATE versions SET status = 'queued' WHERE id = ?"),
12453
14496
  resolveVersionId: this.db.prepare("SELECT id FROM versions WHERE library_id = ? AND name = ?"),
12454
14497
  getVersionById: this.db.prepare("SELECT * FROM versions WHERE id = ?"),
12455
14498
  queryVersionsByLibraryId: this.db.prepare("SELECT * FROM versions WHERE library_id = ? ORDER BY name"),
@@ -12504,12 +14547,14 @@ var DocumentStore = class {
12504
14547
  -- the *first*-index time and never moves on refresh. Fall back to the
12505
14548
  -- oldest page for versions that predate status tracking.
12506
14549
  COALESCE(v.updated_at, MIN(p.created_at)) as indexedAt,
12507
- COUNT(d.id) as documentCount,
12508
- COUNT(DISTINCT p.url) as uniqueUrlCount
14550
+ -- Counts kept per page by migration 020's triggers, so the listing
14551
+ -- never reads the documents table. UNIQUE(version_id, url) makes
14552
+ -- each page of a version a distinct URL.
14553
+ COALESCE(SUM(p.chunk_count), 0) as documentCount,
14554
+ COUNT(p.id) as uniqueUrlCount
12509
14555
  FROM versions v
12510
14556
  JOIN libraries l ON v.library_id = l.id
12511
14557
  LEFT JOIN pages p ON p.version_id = v.id
12512
- LEFT JOIN documents d ON d.page_id = p.id
12513
14558
  GROUP BY v.id
12514
14559
  ORDER BY l.name, version`),
12515
14560
  getChildChunks: this.db.prepare(`
@@ -13094,7 +15139,7 @@ var DocumentStore = class {
13094
15139
  * @throws {VersionAlreadyExistsError} Policy `reject-version` and the version exists.
13095
15140
  * @throws {InvalidLibraryNameError} The library is new and its name fails validation.
13096
15141
  */
13097
- async claimVersion(library, version, policy) {
15142
+ async claimVersion(library, version, policy, options) {
13098
15143
  const label = normalizeVersionLabel(version);
13099
15144
  const storedVersion = denormalizeVersionName(label);
13100
15145
  return this.db.transaction(() => {
@@ -13102,6 +15147,15 @@ var DocumentStore = class {
13102
15147
  if (this.statements.insertVersion.run(libraryRow.id, storedVersion).changes === 0 && policy === "reject-version") throw new VersionAlreadyExistsError(libraryRow.displayName, label);
13103
15148
  const versionIdRow = this.statements.resolveVersionId.get(libraryRow.id, storedVersion);
13104
15149
  if (!versionIdRow) throw new StoreError(`Failed to resolve version_id for library: ${quoteName(library)}, version: ${quoteName(version)}`);
15150
+ if (options?.markQueued) {
15151
+ const current = this.statements.getVersionById.get(versionIdRow.id);
15152
+ this.statements.markVersionQueued.run(versionIdRow.id);
15153
+ return {
15154
+ versionId: versionIdRow.id,
15155
+ library: libraryRow.displayName,
15156
+ previousStatus: current.status
15157
+ };
15158
+ }
13105
15159
  return {
13106
15160
  versionId: versionIdRow.id,
13107
15161
  library: libraryRow.displayName
@@ -13175,6 +15229,18 @@ var DocumentStore = class {
13175
15229
  }
13176
15230
  }
13177
15231
  /**
15232
+ * Puts a version's status back, but only while it is still `queued`.
15233
+ * Used to undo the reservation a claim made when the enqueue fails before a
15234
+ * job is registered, without overwriting a status a job wrote in the meantime.
15235
+ */
15236
+ async restoreVersionStatusIfQueued(versionId, status) {
15237
+ try {
15238
+ this.db.prepare("UPDATE versions SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND status = ?").run(status, versionId, VersionStatus.QUEUED);
15239
+ } catch (error) {
15240
+ throw new StoreError(`Failed to restore version status: ${error}`);
15241
+ }
15242
+ }
15243
+ /**
13178
15244
  * Updates the progress counters for a version being indexed.
13179
15245
  * @param versionId The version ID to update
13180
15246
  * @param pages Current number of pages processed
@@ -13276,6 +15342,43 @@ var DocumentStore = class {
13276
15342
  }
13277
15343
  }
13278
15344
  /**
15345
+ * Renames a library in place: one transaction updates the lookup key and the
15346
+ * display name, leaving versions, pages, chunks and embeddings untouched.
15347
+ *
15348
+ * Runs as one IMMEDIATE transaction with no `await` inside, mirroring
15349
+ * {@link claimVersion}: the database decides a race, and a rename cannot
15350
+ * interleave with a concurrent claim or another rename.
15351
+ *
15352
+ * @param library Current library name, in any casing or padding.
15353
+ * @param newName New name as entered; the trimmed form becomes the display name.
15354
+ * @returns The previous and new display names, or `null` when the library does not exist.
15355
+ * @throws {InvalidLibraryNameError} The new name fails validation.
15356
+ * @throws {LibraryAlreadyExistsError} A different library already uses the new name.
15357
+ * @throws {LibraryBusyError} The library has an indexing job in flight.
15358
+ */
15359
+ async renameLibrary(library, newName) {
15360
+ const displayName = normalizeLibraryDisplayName(newName);
15361
+ const problem = describeLibraryNameProblem(displayName);
15362
+ if (problem) throw new InvalidLibraryNameError(displayName, problem);
15363
+ const oldKey = normalizeLibraryName(library);
15364
+ const newKey = normalizeLibraryName(newName);
15365
+ return this.db.transaction(() => {
15366
+ const row = this.statements.getLibraryIdByName.get(oldKey);
15367
+ if (!row) return null;
15368
+ const active = this.statements.getActiveVersionStatusesByLibraryId.all(row.id);
15369
+ if (active.length > 0) throw new LibraryBusyError(row.display_name, active.map((a) => a.status));
15370
+ if (newKey !== oldKey) {
15371
+ const conflict = this.statements.getLibraryIdByName.get(newKey);
15372
+ if (conflict) throw new LibraryAlreadyExistsError(conflict.display_name);
15373
+ }
15374
+ this.statements.renameLibrary.run(newKey, displayName, row.id);
15375
+ return {
15376
+ oldName: row.display_name,
15377
+ newName: displayName
15378
+ };
15379
+ }).immediate();
15380
+ }
15381
+ /**
13279
15382
  * Deletes a library by its ID.
13280
15383
  * This should only be called when the library has no remaining versions.
13281
15384
  * @param libraryId The library ID to delete
@@ -13407,18 +15510,19 @@ var DocumentStore = class {
13407
15510
  * Creates embeddings for an array of texts with automatic retry logic for size-related errors.
13408
15511
  * If a batch fails due to size limits:
13409
15512
  * - Batches with multiple texts are split in half and retried recursively
13410
- * - Single texts that are too large are truncated and retried once
15513
+ * - A single text that is too large is cut to its first half, again and
15514
+ * again, until the provider accepts it. The stored chunk keeps its full
15515
+ * text; only its vector is computed from the beginning.
13411
15516
  *
13412
15517
  * @param texts Array of texts to embed
13413
15518
  * @param isRetry Internal flag to prevent duplicate warning logs
13414
- * @param hasTruncatedSingleText Whether a single text has already been truncated once
13415
15519
  * @returns Array of embedding vectors
13416
15520
  */
13417
- async embedDocumentsWithRetry(texts, isRetry = false, hasTruncatedSingleText = false) {
15521
+ async embedDocumentsWithRetry(texts, isRetry = false) {
13418
15522
  if (texts.length === 0) return [];
15523
+ const embeddings = this.embeddings;
15524
+ if (embeddings === null) throw new StoreError("Embeddings are not initialized");
13419
15525
  try {
13420
- const embeddings = this.embeddings;
13421
- if (embeddings === null) throw new StoreError("Embeddings are not initialized");
13422
15526
  return await embeddings.embedDocuments(texts);
13423
15527
  } catch (error) {
13424
15528
  if (this.isInputSizeError(error)) {
@@ -13427,26 +15531,44 @@ var DocumentStore = class {
13427
15531
  const firstHalf = texts.slice(0, midpoint);
13428
15532
  const secondHalf = texts.slice(midpoint);
13429
15533
  if (!isRetry) logger.warn(`⚠️ Batch of ${texts.length} texts exceeded size limit, splitting into ${firstHalf.length} + ${secondHalf.length}`);
13430
- const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true, false), this.embedDocumentsWithRetry(secondHalf, true, false)]);
15534
+ const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true), this.embedDocumentsWithRetry(secondHalf, true)]);
13431
15535
  return [...firstEmbeddings, ...secondEmbeddings];
13432
- } else {
13433
- if (hasTruncatedSingleText) throw error;
13434
- const text = texts[0];
13435
- const midpoint = Math.floor(text.length / 2);
13436
- const firstHalf = text.substring(0, midpoint);
13437
- if (!isRetry) logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars).`);
13438
- try {
13439
- return await this.embedDocumentsWithRetry([firstHalf], true, true);
13440
- } catch (retryError) {
13441
- logger.error(`❌ Failed to embed even after splitting. Original length: ${text.length}`);
13442
- throw retryError;
13443
- }
13444
15536
  }
15537
+ return await this.embedBeginningOf(embeddings, texts[0]);
13445
15538
  }
13446
15539
  throw error;
13447
15540
  }
13448
15541
  }
13449
15542
  /**
15543
+ * Embeds the beginning of a single text the provider rejected as too large.
15544
+ *
15545
+ * The text is halved until the provider accepts it, since one halving is not
15546
+ * enough when a text is several times over the limit. The first halving
15547
+ * always runs; later ones stop below `MIN_TRUNCATED_EMBEDDING_CHARS`. The
15548
+ * beginning holds the title, URL and path header and typically the most
15549
+ * important context.
15550
+ *
15551
+ * @param embeddings The embedding model that rejected the text.
15552
+ * @param text The rejected text.
15553
+ * @returns The embedding of the longest beginning the provider accepted.
15554
+ */
15555
+ async embedBeginningOf(embeddings, text) {
15556
+ logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars), embedding its beginning only.`);
15557
+ let beginning = text.substring(0, Math.floor(text.length / 2));
15558
+ let lastError;
15559
+ do {
15560
+ try {
15561
+ return await embeddings.embedDocuments([beginning]);
15562
+ } catch (error) {
15563
+ lastError = error;
15564
+ if (!this.isInputSizeError(error)) break;
15565
+ }
15566
+ beginning = beginning.substring(0, Math.floor(beginning.length / 2));
15567
+ } while (beginning.length >= MIN_TRUNCATED_EMBEDDING_CHARS);
15568
+ logger.error(`❌ Failed to embed even after truncating. Original length: ${text.length}`);
15569
+ throw lastError;
15570
+ }
15571
+ /**
13450
15572
  * Removes the row a refreshed page was read from, when it is not the row now
13451
15573
  * being written.
13452
15574
  *
@@ -14356,6 +16478,14 @@ var DocumentManagementService = class DocumentManagementService {
14356
16478
  return this.store.claimInterruptedVersion(versionId, updatedAt);
14357
16479
  }
14358
16480
  /**
16481
+ * Puts a version's status back, but only while it is still `queued`, and tells
16482
+ * views the library list changed.
16483
+ */
16484
+ async restoreVersionStatusIfQueued(versionId, status) {
16485
+ await this.store.restoreVersionStatusIfQueued(versionId, status);
16486
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16487
+ }
16488
+ /**
14359
16489
  * Updates the status of a version, and tells views the library list changed.
14360
16490
  */
14361
16491
  async updateVersionStatus(versionId, status, errorMessage) {
@@ -14394,8 +16524,8 @@ var DocumentManagementService = class DocumentManagementService {
14394
16524
  * Creates or verifies the library and version an indexing job writes into, atomically.
14395
16525
  * See {@link DocumentStore.claimVersion} for the policy semantics and errors.
14396
16526
  */
14397
- async claimVersion(library, version, policy) {
14398
- return this.store.claimVersion(library, version, policy);
16527
+ async claimVersion(library, version, policy, options) {
16528
+ return this.store.claimVersion(library, version, policy, options);
14399
16529
  }
14400
16530
  /**
14401
16531
  * Looks up a version that must already exist, without creating anything.
@@ -14495,6 +16625,22 @@ var DocumentManagementService = class DocumentManagementService {
14495
16625
  return new LibraryNotFoundInStoreError(library, suggestions);
14496
16626
  }
14497
16627
  /**
16628
+ * Renames a library in place, keeping its versions and indexed content.
16629
+ *
16630
+ * @param library Current library name.
16631
+ * @param newName New name as entered; its trimmed form becomes the display name.
16632
+ * @returns The previous and new display names.
16633
+ * @throws {LibraryNotFoundInStoreError} If the library does not exist.
16634
+ */
16635
+ async renameLibrary(library, newName) {
16636
+ logger.info(`✏️ Renaming library: ${library} -> ${newName}`);
16637
+ const renamed = await this.store.renameLibrary(library, newName);
16638
+ if (!renamed) throw await this.libraryNotFound(library);
16639
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16640
+ logger.info(`✅ Renamed '${renamed.oldName}' to '${renamed.newName}'.`);
16641
+ return renamed;
16642
+ }
16643
+ /**
14498
16644
  * Returns every label stored for a library — semantic versions and opaque tags
14499
16645
  * alike — in canonical display order.
14500
16646
  *
@@ -15186,6 +17332,212 @@ function registerGlobalOutputOptions(yargs) {
15186
17332
  function reportCliError(message) {
15187
17333
  logger.error(message);
15188
17334
  }
17335
+ // src/cli/utils.ts
17336
+ /**
17337
+ * Shared CLI utilities and helper functions.
17338
+ */
17339
+ /**
17340
+ * Retrieves the global EventBusService from the arguments context.
17341
+ * @param argv The parsed arguments context.
17342
+ * @returns The global EventBusService.
17343
+ * @throws Error if EventBusService is not initialized.
17344
+ */
17345
+ function getEventBus(argv) {
17346
+ const eventBus = argv._eventBus;
17347
+ if (!eventBus) throw new Error("EventBusService not initialized");
17348
+ return eventBus;
17349
+ }
17350
+ /**
17351
+ * Ensures a Chromium for scraping is installed, unless a system Chromium path
17352
+ * is set.
17353
+ *
17354
+ * Any Chromium `ManagedBrowser` launches without an explicit path counts: the
17355
+ * headless shell or the full build. When neither is there, the headless shell
17356
+ * is installed with the CLI of the Playwright this package depends on, so it
17357
+ * matches that version. The install leaves other browsers alone, since another
17358
+ * process may be running them.
17359
+ */
17360
+ function ensurePlaywrightBrowsersInstalled() {
17361
+ if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === "1") {
17362
+ logger.debug("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.");
17363
+ return;
17364
+ }
17365
+ const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
17366
+ if (chromiumEnvPath && existsSync(chromiumEnvPath)) {
17367
+ logger.debug(`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`);
17368
+ return;
17369
+ }
17370
+ if (ManagedBrowser.isPlaywrightChromiumInstalled()) return;
17371
+ const playwrightCli = path.join(path.dirname(createRequire(import.meta.url).resolve("playwright/package.json")), "cli.js");
17372
+ try {
17373
+ logger.info("🌐 Installing Playwright Chromium browser... (this may take a moment)");
17374
+ execFileSync(process.execPath, [
17375
+ playwrightCli,
17376
+ "install",
17377
+ "chromium-headless-shell",
17378
+ "--no-remove"
17379
+ ], { stdio: "ignore" });
17380
+ } catch (error) {
17381
+ logger.debug(String(error));
17382
+ logger.error(`❌ Failed to install Playwright browsers automatically. Please run:\n node "${playwrightCli}" install --with-deps chromium-headless-shell\nand try again.`);
17383
+ process.exit(1);
17384
+ }
17385
+ }
17386
+ /**
17387
+ * Resolves the protocol based on auto-detection or explicit specification.
17388
+ * Auto-detection uses TTY status to determine appropriate protocol.
17389
+ */
17390
+ function resolveProtocol(protocol) {
17391
+ if (protocol === "auto") {
17392
+ if (!process.stdin.isTTY && !process.stdout.isTTY) return "stdio";
17393
+ return "http";
17394
+ }
17395
+ if (protocol === "stdio" || protocol === "http") return protocol;
17396
+ throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);
17397
+ }
17398
+ /**
17399
+ * Validates and parses port number
17400
+ */
17401
+ function validatePort(portString) {
17402
+ const port = Number.parseInt(portString, 10);
17403
+ if (Number.isNaN(port) || port < 1 || port > 65535) throw new Error("Invalid port number");
17404
+ return port;
17405
+ }
17406
+ /**
17407
+ * Validates host string for basic format checking
17408
+ */
17409
+ function validateHost(hostString) {
17410
+ const trimmed = hostString.trim();
17411
+ if (!trimmed) throw new Error("Host cannot be empty");
17412
+ if (trimmed.includes(" ") || trimmed.includes(" ") || trimmed.includes("\n")) throw new Error("Host cannot contain whitespace");
17413
+ return trimmed;
17414
+ }
17415
+ /**
17416
+ * Creates AppServerConfig based on service requirements.
17417
+ *
17418
+ * AppConfig is the source of truth for host/auth/telemetry/read-only settings.
17419
+ * AppServerConfig only selects which services to run and which port to bind to.
17420
+ * Whether the server runs jobs itself or uses a worker follows from the backend.
17421
+ *
17422
+ * @param options Which services to run, the port, and startup details.
17423
+ * @returns The server configuration.
17424
+ */
17425
+ function createAppServerConfig(options) {
17426
+ return {
17427
+ enableWebInterface: options.enableWebInterface ?? false,
17428
+ enableMcpServer: options.enableMcpServer ?? true,
17429
+ enableApiServer: options.enableApiServer ?? false,
17430
+ port: options.port,
17431
+ showLogo: options.showLogo ?? true,
17432
+ startupContext: options.startupContext
17433
+ };
17434
+ }
17435
+ /**
17436
+ * Parses custom headers from CLI options
17437
+ */
17438
+ function parseHeaders(headerOptions) {
17439
+ const headers = {};
17440
+ if (Array.isArray(headerOptions)) for (const entry of headerOptions) {
17441
+ const idx = entry.indexOf(":");
17442
+ if (idx > 0) {
17443
+ const name = entry.slice(0, idx).trim();
17444
+ const value = entry.slice(idx + 1).trim();
17445
+ if (name) headers[name] = value;
17446
+ }
17447
+ }
17448
+ return headers;
17449
+ }
17450
+ /**
17451
+ * Check the auth settings for the transport a command serves. Authentication
17452
+ * applies to MCP over HTTP only. Over stdio the host launching the process is
17453
+ * the trust boundary, so auth settings are ignored with a warning on stderr,
17454
+ * which never carries protocol data.
17455
+ * @param auth - The loaded auth settings.
17456
+ * @param protocol - The resolved transport.
17457
+ * @param port - The HTTP port, for the plain-HTTP warning.
17458
+ * @throws Error when an auth setting over HTTP is malformed.
17459
+ */
17460
+ function checkAuthForProtocol(auth, protocol, port) {
17461
+ if (!auth.enabled) return;
17462
+ if (protocol === "stdio") {
17463
+ console.error("⚠️ Authentication does not apply to MCP over stdio; auth settings are ignored.");
17464
+ return;
17465
+ }
17466
+ validateAuthConfig(auth);
17467
+ warnHttpUsage(port);
17468
+ }
17469
+ /**
17470
+ * Validates the format of auth settings that are present. Whether a setting
17471
+ * is required depends on what the process serves, so the server checks that
17472
+ * at startup.
17473
+ */
17474
+ function validateAuthConfig(authConfig) {
17475
+ const errors = [];
17476
+ if (authConfig.issuerUrl) try {
17477
+ if (new URL(authConfig.issuerUrl).protocol !== "https:") errors.push("Issuer URL must use HTTPS protocol");
17478
+ } catch {
17479
+ errors.push("Issuer URL must be a valid URL");
17480
+ }
17481
+ if (authConfig.audience) try {
17482
+ const url = new URL(authConfig.audience);
17483
+ if (url.protocol === "http:" && url.hostname !== "localhost") logger.warn("⚠️ Audience uses HTTP protocol - consider using HTTPS for production");
17484
+ if (url.hash) errors.push("Audience must not contain URL fragments");
17485
+ } catch {
17486
+ if (authConfig.audience.startsWith("urn:")) {
17487
+ const urnParts = authConfig.audience.split(":");
17488
+ if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) errors.push("URN audience must follow format: urn:namespace:specific-string");
17489
+ } else errors.push("Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)");
17490
+ }
17491
+ if (errors.length > 0) throw new Error(`Auth configuration validation failed:\n${errors.join("\n")}`);
17492
+ }
17493
+ /**
17494
+ * Warns about HTTP usage in production when auth is enabled.
17495
+ */
17496
+ function warnHttpUsage(port) {
17497
+ 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.");
17498
+ }
17499
+ /**
17500
+ * Prompts the user interactively to confirm an embedding model change.
17501
+ * Returns true if the user confirms (y/Y), false otherwise.
17502
+ */
17503
+ function promptModelChangeConfirmation(change) {
17504
+ return new Promise((resolve) => {
17505
+ 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`);
17506
+ const rl = createInterface({
17507
+ input: process.stdin,
17508
+ output: process.stderr
17509
+ });
17510
+ rl.question(" Proceed with model change? (y/N) ", (answer) => {
17511
+ rl.close();
17512
+ resolve(answer.trim().toLowerCase() === "y");
17513
+ });
17514
+ });
17515
+ }
17516
+ /**
17517
+ * Handles EmbeddingModelChangedError during service initialization.
17518
+ *
17519
+ * - When accepted (`--accept-model-change` or `DOCS_MCP_ACCEPT_MODEL_CHANGE`):
17520
+ * resolves the model change (invalidates vectors) without asking.
17521
+ * - In non-interactive mode (no TTY): re-throws the error to fail startup.
17522
+ * - In interactive mode (TTY): prompts the user for confirmation, then either
17523
+ * resolves the model change or exits.
17524
+ *
17525
+ * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()
17526
+ * @param service The DocumentManagementService instance (already partially initialized)
17527
+ * @param acceptFlag The value of `--accept-model-change`; when omitted,
17528
+ * `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides
17529
+ * @throws Re-throws the error in non-interactive mode or if the user rejects the change
17530
+ */
17531
+ async function handleEmbeddingModelChange(error, service, acceptFlag) {
17532
+ if (acceptFlag ?? parseEnvBoolean(process.env.DOCS_MCP_ACCEPT_MODEL_CHANGE) ?? false) {
17533
+ logger.warn(`⚠️ Accepting embedding model change without a prompt: ${describeEmbeddingModel(error.previousModel, error.previousDimension)} → ${describeEmbeddingModel(error.currentModel, error.currentDimension)}`);
17534
+ await service.resolveModelChange();
17535
+ return;
17536
+ }
17537
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
17538
+ if (!await promptModelChangeConfirmation(error)) throw new Error("Embedding model change rejected. Startup aborted.\nRestore the previous embedding model configuration to continue without changes.");
17539
+ await service.resolveModelChange();
17540
+ }
15189
17541
  // src/cli/commands/compact.ts
15190
17542
  function createCompactCommand(cli) {
15191
17543
  cli.command("compact", "Reclaim unused space in the document store (exclusive lock; may block searches)", (yargs) => {
@@ -15254,11 +17606,10 @@ function createConfigCommand(cli) {
15254
17606
  process.exitCode = 1;
15255
17607
  return;
15256
17608
  }
15257
- const config = loadConfig(argv, {
17609
+ const value = getConfigValue(loadConfig(argv, {
15258
17610
  configPath: argv.config,
15259
17611
  searchDir: argv.storePath
15260
- });
15261
- const value = getConfigValue(config, path);
17612
+ }), path);
15262
17613
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
15263
17614
  renderScalarOutput(value, argv);
15264
17615
  return;
@@ -15285,11 +17636,10 @@ function createConfigCommand(cli) {
15285
17636
  process.exitCode = 1;
15286
17637
  return;
15287
17638
  }
15288
- const config = loadConfig(argv, {
17639
+ const currentValue = getConfigValue(loadConfig(argv, {
15289
17640
  configPath: argv.config,
15290
17641
  searchDir: argv.storePath
15291
- });
15292
- const currentValue = getConfigValue(config, path);
17642
+ }), path);
15293
17643
  if (currentValue !== void 0 && currentValue !== null && typeof currentValue === "object" && !Array.isArray(currentValue)) {
15294
17644
  reportCliError(`Error: Config path '${path}' refers to an object. Use a more specific leaf path to set a scalar value.`);
15295
17645
  reportCliError("Hint: Run 'docs-mcp-server config' to inspect the current structure.");
@@ -15874,7 +18224,7 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
15874
18224
  const server = new McpServer({
15875
18225
  name,
15876
18226
  ...title !== void 0 ? { title } : {},
15877
- version: "3.4.0"
18227
+ version: "3.5.0"
15878
18228
  }, {
15879
18229
  capabilities: {
15880
18230
  tools: {},
@@ -16983,7 +19333,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
16983
19333
  const mcpEnabled = Boolean(serverConfig.enableMcpServer);
16984
19334
  const authEnabled = Boolean(appConfig.auth.enabled);
16985
19335
  return {
16986
- version: "3.4.0",
19336
+ version: "3.5.0",
16987
19337
  readOnly: Boolean(appConfig.app.readOnly),
16988
19338
  telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
16989
19339
  services: {
@@ -17147,6 +19497,18 @@ createPipelineRouter(t$3);
17147
19497
  * tRPC router exposing document data store operations via the worker API.
17148
19498
  * Only procedures actually used externally are included to keep surface minimal.
17149
19499
  */
19500
+ /**
19501
+ * Maps a rename failure a caller can act on to its tRPC code, mirroring the
19502
+ * pipeline router's enqueue mapping. Anything else passes through unchanged.
19503
+ */
19504
+ function toRenameError(error) {
19505
+ const code = error instanceof LibraryAlreadyExistsError || error instanceof LibraryBusyError ? "CONFLICT" : error instanceof InvalidLibraryNameError ? "BAD_REQUEST" : error instanceof LibraryNotFoundInStoreError ? "NOT_FOUND" : null;
19506
+ return code && error instanceof Error ? new TRPCError({
19507
+ code,
19508
+ message: error.message,
19509
+ cause: error
19510
+ }) : error;
19511
+ }
17150
19512
  var t$2 = initTRPC.context().create({ transformer: superjson });
17151
19513
  /** A required name, trimmed. */
17152
19514
  var nonEmpty = z.string().trim().min(1);
@@ -17208,6 +19570,16 @@ function createDataRouter(trpc) {
17208
19570
  }).optional()).mutation(async ({ ctx, input }) => {
17209
19571
  return await ctx.docService.compact(input);
17210
19572
  }),
19573
+ renameLibrary: tt.procedure.input(z.object({
19574
+ library: nonEmpty,
19575
+ newName: nonEmpty
19576
+ })).mutation(async ({ ctx, input }) => {
19577
+ try {
19578
+ return await ctx.docService.renameLibrary(input.library, input.newName);
19579
+ } catch (error) {
19580
+ throw toRenameError(error);
19581
+ }
19582
+ }),
17211
19583
  getVersionsByStatus: tt.procedure.input(z.object({ statuses: z.array(z.string()) })).query(async ({ ctx, input }) => {
17212
19584
  const statuses = input.statuses;
17213
19585
  return await ctx.docService.getVersionsByStatus(statuses);
@@ -17655,7 +20027,7 @@ var AppServer = class AppServer {
17655
20027
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
17656
20028
  if (telemetry.isEnabled()) {
17657
20029
  telemetry.setGlobalContext({
17658
- appVersion: "3.4.0",
20030
+ appVersion: "3.5.0",
17659
20031
  appPlatform: process.platform,
17660
20032
  appNodeVersion: process.version,
17661
20033
  appServicesEnabled: this.getActiveServicesList(),
@@ -18233,6 +20605,7 @@ function createFetchUrlCommand(cli) {
18233
20605
  configPath: argv.config,
18234
20606
  searchDir: argv.storePath
18235
20607
  });
20608
+ ensurePlaywrightBrowsersInstalled();
18236
20609
  renderTextOutput(await new FetchUrlTool(new AutoDetectFetcher(appConfig.scraper), appConfig).execute({
18237
20610
  url,
18238
20611
  followRedirects: argv.followRedirects,
@@ -18372,6 +20745,7 @@ function createMcpCommand(cli) {
18372
20745
  quiet: argv.quiet
18373
20746
  });
18374
20747
  checkAuthForProtocol(appConfig.auth, resolvedProtocol, appConfig.server.ports.mcp);
20748
+ ensurePlaywrightBrowsersInstalled();
18375
20749
  try {
18376
20750
  const serverUrl = argv.serverUrl;
18377
20751
  const backend = await openBackend({
@@ -18511,6 +20885,7 @@ function createRefreshCommand(cli) {
18511
20885
  configPath: argv.config,
18512
20886
  searchDir: argv.storePath
18513
20887
  });
20888
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
18514
20889
  const backend = await openBackend({
18515
20890
  serverUrl,
18516
20891
  eventBus: getEventBus(argv),
@@ -18585,6 +20960,88 @@ function createRemoveCommand(cli) {
18585
20960
  }
18586
20961
  });
18587
20962
  }
20963
+ // src/tools/RenameTool.ts
20964
+ /**
20965
+ * Tool to rename a library in place, keeping its versions and indexed content.
20966
+ * Shared by the CLI; the store refuses the rename while a job writes into the library.
20967
+ */
20968
+ var RenameTool = class {
20969
+ documentManagementService;
20970
+ /**
20971
+ * @param documentManagementService Renames the library, locally or against a worker.
20972
+ */
20973
+ constructor(documentManagementService) {
20974
+ this.documentManagementService = documentManagementService;
20975
+ }
20976
+ /**
20977
+ * Executes the rename of the specified library.
20978
+ * Names are compared case-insensitively, so a case-only change updates the display name.
20979
+ */
20980
+ async execute(args) {
20981
+ const { library, newName } = args;
20982
+ if (!library || typeof library !== "string" || library.trim() === "") throw new ValidationError("Library name is required and must be a non-empty string.", this.constructor.name);
20983
+ if (!newName || typeof newName !== "string" || newName.trim() === "") throw new ValidationError("The new name is required and must be a non-empty string.", this.constructor.name);
20984
+ logger.info(`✏️ Renaming library: ${library} -> ${newName}`);
20985
+ try {
20986
+ await this.documentManagementService.validateLibraryExists(library);
20987
+ const { oldName, newName: renamed } = await this.documentManagementService.renameLibrary(library, newName);
20988
+ const message = `Successfully renamed ${oldName} to ${renamed}.`;
20989
+ logger.info(`✅ ${message}`);
20990
+ return { message };
20991
+ } catch (error) {
20992
+ if (error instanceof ToolError) throw error;
20993
+ const errorMessage = `Failed to rename ${library} to ${newName}: ${error instanceof Error ? error.message : String(error)}`;
20994
+ logger.error(`❌ Error renaming library: ${errorMessage}`);
20995
+ throw new ToolError(errorMessage, this.constructor.name);
20996
+ }
20997
+ }
20998
+ };
20999
+ // src/cli/commands/rename.ts
21000
+ function createRenameCommand(cli) {
21001
+ cli.command("rename <library> <new-name>", "Rename a library in place, keeping its versions and indexed content", (yargs) => {
21002
+ return yargs.version(false).positional("library", {
21003
+ type: "string",
21004
+ description: "Current library name",
21005
+ demandOption: true
21006
+ }).positional("new-name", {
21007
+ type: "string",
21008
+ description: "New library name",
21009
+ demandOption: true
21010
+ }).option("server-url", {
21011
+ type: "string",
21012
+ description: "URL of external pipeline worker RPC (e.g., http://localhost:8080/api)",
21013
+ alias: "serverUrl"
21014
+ });
21015
+ }, async (argv) => {
21016
+ await telemetry.track(TelemetryEvent.CLI_COMMAND, {
21017
+ command: "rename",
21018
+ library: argv.library,
21019
+ newName: argv.newName,
21020
+ useServerUrl: !!argv.serverUrl
21021
+ });
21022
+ const library = argv.library;
21023
+ const newName = argv.newName;
21024
+ const serverUrl = argv.serverUrl;
21025
+ const appConfig = loadConfig(argv, {
21026
+ configPath: argv.config,
21027
+ searchDir: argv.storePath
21028
+ });
21029
+ const backend = await openBackend({
21030
+ serverUrl,
21031
+ eventBus: getEventBus(argv),
21032
+ appConfig
21033
+ });
21034
+ try {
21035
+ const { message } = await new RenameTool(backend.docService).execute({
21036
+ library,
21037
+ newName
21038
+ });
21039
+ renderTextOutput(message);
21040
+ } finally {
21041
+ await backend.close();
21042
+ }
21043
+ });
21044
+ }
18588
21045
  // src/cli/commands/scrape.ts
18589
21046
  function createScrapeCommand(cli) {
18590
21047
  cli.command("scrape <library> <url>", "Download and index documentation from a URL or local directory", (yargs) => {
@@ -18710,6 +21167,7 @@ function createScrapeCommand(cli) {
18710
21167
  hasExcludePatterns: argv.excludePattern.length > 0,
18711
21168
  useServerUrl: !!serverUrl
18712
21169
  });
21170
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
18713
21171
  const backend = await openBackend({
18714
21172
  serverUrl,
18715
21173
  eventBus: getEventBus(argv),
@@ -18857,6 +21315,7 @@ function createWebCommand(cli) {
18857
21315
  configPath: argv.config,
18858
21316
  searchDir: argv.storePath
18859
21317
  });
21318
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
18860
21319
  try {
18861
21320
  const backend = await openBackend({
18862
21321
  appConfig,
@@ -18964,6 +21423,7 @@ var COMMAND_FACTORIES = [
18964
21423
  createMcpCommand,
18965
21424
  createRefreshCommand,
18966
21425
  createRemoveCommand,
21426
+ createRenameCommand,
18967
21427
  createScrapeCommand,
18968
21428
  createSearchCommand,
18969
21429
  createWebCommand,
@@ -19008,14 +21468,13 @@ function registerGlobalOptions(cli) {
19008
21468
  function createCli(argv) {
19009
21469
  let globalEventBus = null;
19010
21470
  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) => {
21471
+ const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.5.0").middleware(async (argv) => {
19012
21472
  if (argv.verbose && argv.quiet) throw new Error("Arguments verbose and quiet are mutually exclusive");
19013
21473
  applyGlobalCliOutputMode({
19014
21474
  verbose: argv.verbose,
19015
21475
  quiet: argv.quiet
19016
21476
  });
19017
- const rawStorePath = argv.storePath || process.env.DOCS_MCP_STORE_PATH;
19018
- const resolvedStorePath = resolveStorePath(rawStorePath);
21477
+ const resolvedStorePath = resolveStorePath(argv.storePath || process.env.DOCS_MCP_STORE_PATH);
19019
21478
  argv.storePath = resolvedStorePath;
19020
21479
  const appConfig = loadConfig(argv, {
19021
21480
  configPath: argv.config,
@@ -19031,7 +21490,7 @@ function createCli(argv) {
19031
21490
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
19032
21491
  const commandName = argv._[0]?.toString() || "default";
19033
21492
  telemetry.setGlobalContext({
19034
- appVersion: "3.4.0",
21493
+ appVersion: "3.5.0",
19035
21494
  appPlatform: process.platform,
19036
21495
  appNodeVersion: process.version,
19037
21496
  appInterface: "cli",
@@ -19091,6 +21550,13 @@ var sigintHandler = async () => {
19091
21550
  }
19092
21551
  };
19093
21552
  /**
21553
+ * Waits until stdout and stderr have written everything queued so far. Writes
21554
+ * to a pipe are asynchronous, so exiting right away can cut off the output.
21555
+ */
21556
+ async function flushOutput() {
21557
+ await Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write("", () => resolve()))));
21558
+ }
21559
+ /**
19094
21560
  * Performs cleanup for CLI commands that don't start long-running services.
19095
21561
  * This ensures proper analytics shutdown and process exit to prevent hanging.
19096
21562
  */
@@ -19099,6 +21565,7 @@ async function cleanupCliCommand() {
19099
21565
  logger.debug("CLI command executed. Cleaning up...");
19100
21566
  process.removeListener("SIGINT", sigintHandler);
19101
21567
  await telemetry.shutdown();
21568
+ await flushOutput();
19102
21569
  process.exit();
19103
21570
  }
19104
21571
  }
@@ -19135,11 +21602,12 @@ async function runCli() {
19135
21602
  await Promise.allSettled(shutdownPromises);
19136
21603
  await closeActiveBackend().catch((e) => logger.error(`❌ Error closing backend: ${e}`));
19137
21604
  }
21605
+ await flushOutput();
19138
21606
  process.exit(1);
19139
21607
  }
19140
21608
  const appServer = getActiveAppServer();
19141
21609
  if (commandExecuted && !appServer) await cleanupCliCommand();
19142
21610
  }
19143
- export { cleanupCliCommand, runCli };
21611
+ export { runCli };
19144
21612
 
19145
- //# sourceMappingURL=main-BTCYUUTU.js.map
21613
+ //# sourceMappingURL=main-D3_JhsO7.js.map