@arabold/docs-mcp-server 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1866 @@
1
+ import { t as normalizeEnvValue } from "./env-DAfCMXx2.js";
2
+ import { r as logger } from "./logger-DtB7mX3u.js";
3
+ import fs, { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import envPaths from "env-paths";
7
+ import yaml from "yaml";
8
+ import { z } from "zod";
9
+ import { chromium } from "playwright";
10
+ import { execSync } from "node:child_process";
11
+ import { createInterface } from "node:readline";
12
+ // src/store/types.ts
13
+ /**
14
+ * Represents the possible states of a version's indexing status.
15
+ * These statuses are stored in the database and persist across server restarts.
16
+ */
17
+ var VersionStatus = /* @__PURE__ */ function(VersionStatus) {
18
+ VersionStatus["NOT_INDEXED"] = "not_indexed";
19
+ VersionStatus["QUEUED"] = "queued";
20
+ VersionStatus["RUNNING"] = "running";
21
+ VersionStatus["COMPLETED"] = "completed";
22
+ VersionStatus["FAILED"] = "failed";
23
+ VersionStatus["CANCELLED"] = "cancelled";
24
+ VersionStatus["UPDATING"] = "updating";
25
+ return VersionStatus;
26
+ }({});
27
+ /**
28
+ * Normalizes a version label for storage and lookup.
29
+ *
30
+ * This is the single write contract for version labels: trim surrounding
31
+ * whitespace, lowercase, and treat an empty result as unversioned. The label is
32
+ * otherwise stored verbatim — it is never validated, coerced or rejected, since
33
+ * a version label is not guaranteed to be a semantic version (`stable` and
34
+ * `1.20` are as legitimate as `1.20.0`).
35
+ *
36
+ * @param version Version label as supplied by a caller, if any.
37
+ * @returns The normalized label, or an empty string for unversioned content.
38
+ */
39
+ function normalizeVersionLabel(version) {
40
+ return (version ?? "").trim().toLowerCase();
41
+ }
42
+ /**
43
+ * Computes a library's lookup key.
44
+ *
45
+ * The counterpart to {@link normalizeVersionLabel}: trim and lowercase (the
46
+ * Unicode default lowercase mapping, without full case folding), so a library
47
+ * is one row however its name was typed. The key is what `libraries.name`
48
+ * stores and every lookup compares; the name as entered lives on as the display
49
+ * name ({@link normalizeLibraryDisplayName}).
50
+ *
51
+ * @param library Library name as supplied by a caller.
52
+ * @returns The lookup key.
53
+ */
54
+ function normalizeLibraryName(library) {
55
+ return library.trim().toLowerCase();
56
+ }
57
+ /**
58
+ * Whether two library names refer to the same library.
59
+ *
60
+ * The one comparison every caller-facing lookup uses, so the identity rule
61
+ * lives in a single place.
62
+ *
63
+ * @param a A library name in any casing or padding.
64
+ * @param b Another library name.
65
+ */
66
+ function libraryNamesMatch(a, b) {
67
+ return normalizeLibraryName(a) === normalizeLibraryName(b);
68
+ }
69
+ /**
70
+ * Computes a library's display name: the name as entered, trimmed only.
71
+ *
72
+ * Case, inner spacing, punctuation and non-ASCII characters are preserved, so
73
+ * `Next.js Docs` is stored and shown exactly that way.
74
+ *
75
+ * @param library Library name as supplied by a caller.
76
+ * @returns The display name to store for a new library.
77
+ */
78
+ function normalizeLibraryDisplayName(library) {
79
+ return library.trim();
80
+ }
81
+ /** Unicode general category Cc: C0 controls, DEL and C1 controls such as tab, newline and ESC. */
82
+ var CONTROL_CHARACTER = /\p{Cc}/u;
83
+ /**
84
+ * Explains why a name is unacceptable for a new library.
85
+ *
86
+ * Only creation is validated; existing libraries stay reachable under their
87
+ * stored names. Format characters (Cf) are allowed because emoji sequences rely
88
+ * on the zero-width joiner. Pure, so the web client can show the same message.
89
+ *
90
+ * @param displayName Name submitted for a new library; trimmed before checking.
91
+ * @returns The broken rule as a short phrase, or `null` when the name is valid.
92
+ */
93
+ function describeLibraryNameProblem(displayName) {
94
+ const name = normalizeLibraryDisplayName(displayName);
95
+ if (name.length === 0) return "is empty";
96
+ if (CONTROL_CHARACTER.test(name)) return "contains a control character";
97
+ if ([...name].length > 100) return `is longer than 100 characters`;
98
+ return null;
99
+ }
100
+ /**
101
+ * What indexing does when its target library or version already exists.
102
+ *
103
+ * - `reject-library`: fail if the library exists at all (the web UI's "Add library").
104
+ * - `reject-version`: fail if that version exists; create the library if needed (the default).
105
+ * - `replace`: rebuild an existing version, or create it (`--replace`, `replace: true`, re-index, retry, refresh).
106
+ */
107
+ var EXISTING_TARGET_POLICIES = [
108
+ "reject-library",
109
+ "reject-version",
110
+ "replace"
111
+ ];
112
+ /** Normalize a VersionRef (lowercase, trim; empty string for unversioned). */
113
+ function normalizeVersionRef(ref) {
114
+ return {
115
+ library: normalizeLibraryName(ref.library),
116
+ version: normalizeVersionLabel(ref.version)
117
+ };
118
+ }
119
+ /**
120
+ * `versions.updated_at` holds whole seconds (SQLite's `CURRENT_TIMESTAMP`), so
121
+ * a write can read up to this much older than it happened.
122
+ */
123
+ var UPDATED_AT_RESOLUTION_MS = 1e3;
124
+ /**
125
+ * How long ago a version was last written, from its `updated_at` (UTC).
126
+ *
127
+ * @param version The version as read from the store.
128
+ * @param now The current time, in milliseconds since the epoch.
129
+ * @returns Milliseconds since the write, or `Infinity` when the version has no
130
+ * readable `updated_at`.
131
+ */
132
+ function msSinceWritten(version, now) {
133
+ const writtenAt = version.updated_at ? Date.parse(`${version.updated_at.replace(" ", "T")}Z`) : NaN;
134
+ return Number.isNaN(writtenAt) ? Number.POSITIVE_INFINITY : now - writtenAt;
135
+ }
136
+ /**
137
+ * Helper function to convert NULL version name to empty string for API compatibility.
138
+ * Database stores NULL for unversioned content, but APIs expect empty string.
139
+ */
140
+ function normalizeVersionName(name) {
141
+ return name ?? "";
142
+ }
143
+ /**
144
+ * Helper function for version name normalization prior to storage.
145
+ * Policy:
146
+ * - Empty string represents the unversioned variant (stored as '').
147
+ * - Names are lower-cased at call sites (see resolveLibraryAndVersionIds) to enforce
148
+ * case-insensitive uniqueness; this function only preserves the empty-string rule.
149
+ */
150
+ function denormalizeVersionName(name) {
151
+ return name === "" ? "" : name;
152
+ }
153
+ // src/store/errors.ts
154
+ /**
155
+ * Base error class for all store-related errors.
156
+ * Provides consistent error handling with optional cause tracking.
157
+ */
158
+ var StoreError = class extends Error {
159
+ cause;
160
+ constructor(message, cause) {
161
+ super(cause ? `${message} caused by ${cause}` : message);
162
+ this.cause = cause;
163
+ this.name = this.constructor.name;
164
+ const causeError = cause instanceof Error ? cause : cause ? new Error(String(cause)) : void 0;
165
+ if (causeError?.stack) this.stack = causeError.stack;
166
+ }
167
+ };
168
+ var CONTROL_CHARACTERS = new RegExp(CONTROL_CHARACTER.source, "gu");
169
+ function escapeControlCharacter(char) {
170
+ const code = char.charCodeAt(0);
171
+ return code < 32 ? JSON.stringify(char).slice(1, -1) : `\\u${code.toString(16).padStart(4, "0")}`;
172
+ }
173
+ /**
174
+ * Escapes every control character (Unicode Cc) in text that an error message
175
+ * repeats, such as a library name or version, so it cannot carry terminal
176
+ * control sequences or forge log lines. Other characters are left as they are.
177
+ */
178
+ function escapeControlCharacters(text) {
179
+ return text.replace(CONTROL_CHARACTERS, escapeControlCharacter);
180
+ }
181
+ /**
182
+ * Labels a library version as `name@version` for logs and messages, with
183
+ * control characters escaped in both and unversioned documentation shown as
184
+ * `latest`.
185
+ */
186
+ function formatVersionLabel(library, version) {
187
+ return `${escapeControlCharacters(library)}@${escapeControlCharacters(version) || "latest"}`;
188
+ }
189
+ /**
190
+ * Quotes a library name (or version) for an error message, with quotes,
191
+ * backslashes and every control character escaped.
192
+ */
193
+ function quoteName(name) {
194
+ return escapeControlCharacters(JSON.stringify(name));
195
+ }
196
+ /**
197
+ * Error thrown when a requested library cannot be found in the store.
198
+ * Includes suggestions for similar library names if available.
199
+ */
200
+ var LibraryNotFoundInStoreError = class extends StoreError {
201
+ library;
202
+ similarLibraries;
203
+ constructor(library, similarLibraries = []) {
204
+ let text = `Library ${escapeControlCharacters(library)} not found in store.`;
205
+ if (similarLibraries.length > 0) text += ` Did you mean: ${similarLibraries.map(escapeControlCharacters).join(", ")}?`;
206
+ super(text);
207
+ this.library = library;
208
+ this.similarLibraries = similarLibraries;
209
+ }
210
+ };
211
+ /**
212
+ * Error thrown when a specific version of a library cannot be found in the store.
213
+ * Includes the list of available versions for better context.
214
+ */
215
+ var VersionNotFoundInStoreError = class extends StoreError {
216
+ library;
217
+ version;
218
+ availableVersions;
219
+ constructor(library, version, availableVersions) {
220
+ let text = `${version ? `Version ${escapeControlCharacters(version)}` : "Version"} for library ${escapeControlCharacters(library)} not found in store.`;
221
+ if (availableVersions.length > 0) text += ` Available versions: ${availableVersions.map(escapeControlCharacters).join(", ")}`;
222
+ super(text);
223
+ this.library = library;
224
+ this.version = version;
225
+ this.availableVersions = availableVersions;
226
+ }
227
+ };
228
+ /**
229
+ * Error thrown when a request to create a new library finds that library already exists.
230
+ * Raised only for an explicit "Add library" request.
231
+ */
232
+ var LibraryAlreadyExistsError = class extends StoreError {
233
+ library;
234
+ constructor(library) {
235
+ super(`Library ${quoteName(library)} already exists. Open it to add a version.`);
236
+ this.library = library;
237
+ }
238
+ };
239
+ /**
240
+ * Error thrown when a scrape would clear an existing version without requesting replacement.
241
+ */
242
+ var VersionAlreadyExistsError = class extends StoreError {
243
+ library;
244
+ version;
245
+ constructor(library, version) {
246
+ const target = version ? `Version ${quoteName(version)} of library ${quoteName(library)}` : `Unversioned documentation for library ${quoteName(library)}`;
247
+ super(`${target} already exists. To rebuild it, scrape again with --replace (CLI) or replace: true (MCP), or refresh it to update in place.`);
248
+ this.library = library;
249
+ this.version = version;
250
+ }
251
+ };
252
+ /**
253
+ * Error thrown when a new library's name breaks a naming rule.
254
+ */
255
+ var InvalidLibraryNameError = class extends StoreError {
256
+ library;
257
+ reason;
258
+ constructor(library, reason) {
259
+ super(`Invalid library name ${quoteName(library)}: ${reason}.`);
260
+ this.library = library;
261
+ this.reason = reason;
262
+ }
263
+ };
264
+ /**
265
+ * Error thrown when a requested page cannot be found in the store for a library/version.
266
+ * Includes suggestions for similar page URLs if available.
267
+ */
268
+ var PageNotFoundInStoreError = class extends StoreError {
269
+ library;
270
+ version;
271
+ pathOrUrl;
272
+ suggestions;
273
+ constructor(library, version, pathOrUrl, suggestions = []) {
274
+ const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
275
+ let text = `Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} not found in store.`;
276
+ if (suggestions.length > 0) text += ` Did you mean: ${suggestions.map(escapeControlCharacters).join(", ")}?`;
277
+ super(text);
278
+ this.library = library;
279
+ this.version = version;
280
+ this.pathOrUrl = pathOrUrl;
281
+ this.suggestions = suggestions;
282
+ }
283
+ };
284
+ /**
285
+ * Error thrown when a page path matches more than one stored page.
286
+ * Lists the matching URLs so the caller can pass the full URL of the intended page.
287
+ */
288
+ var AmbiguousPageInStoreError = class extends StoreError {
289
+ library;
290
+ version;
291
+ pathOrUrl;
292
+ matches;
293
+ constructor(library, version, pathOrUrl, matches) {
294
+ const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
295
+ 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.`);
296
+ this.library = library;
297
+ this.version = version;
298
+ this.pathOrUrl = pathOrUrl;
299
+ this.matches = matches;
300
+ }
301
+ };
302
+ /**
303
+ * Error thrown when an embedding model's vector dimension exceeds the database's fixed dimension.
304
+ * This occurs when trying to use a model that produces vectors larger than the database can store.
305
+ */
306
+ var DimensionError = class extends StoreError {
307
+ modelName;
308
+ modelDimension;
309
+ dbDimension;
310
+ constructor(modelName, modelDimension, dbDimension) {
311
+ super(`Model "${modelName}" produces ${modelDimension}-dimensional vectors, which exceeds the database's fixed dimension of ${dbDimension}. Please use a model with dimension ≤ ${dbDimension}.`);
312
+ this.modelName = modelName;
313
+ this.modelDimension = modelDimension;
314
+ this.dbDimension = dbDimension;
315
+ }
316
+ };
317
+ /**
318
+ * Error thrown when there's a problem with database connectivity or operations.
319
+ */
320
+ var ConnectionError = class extends StoreError {};
321
+ /**
322
+ * Error thrown when the embedding provider fails to embed a page's chunks.
323
+ * Nothing of the page is written when this is thrown.
324
+ */
325
+ var EmbeddingError = class extends ConnectionError {};
326
+ /**
327
+ * Names an embedding model with its vector dimension for model-change messages.
328
+ * @param model - The model specification.
329
+ * @param dimension - The vector dimension, or null when it is not known.
330
+ * @returns The model, followed by its dimension when known.
331
+ */
332
+ function describeEmbeddingModel(model, dimension) {
333
+ return dimension === null ? model : `${model} (${dimension} dimensions)`;
334
+ }
335
+ /**
336
+ * Error thrown when the configured embedding model or vector dimension differs from the
337
+ * values stored in the database metadata. This indicates that existing vectors are
338
+ * incompatible with the new configuration and must be invalidated before proceeding.
339
+ *
340
+ * The CLI layer catches this error to accept the change when `--accept-model-change`
341
+ * is set, prompt the user interactively (TTY), or fail startup entirely
342
+ * (non-interactive/MCP/stdio mode). A dimension is null when it is not known.
343
+ */
344
+ var EmbeddingModelChangedError = class extends StoreError {
345
+ previousModel;
346
+ previousDimension;
347
+ currentModel;
348
+ currentDimension;
349
+ constructor(previousModel, previousDimension, currentModel, currentDimension) {
350
+ 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.`);
351
+ this.previousModel = previousModel;
352
+ this.previousDimension = previousDimension;
353
+ this.currentModel = currentModel;
354
+ this.currentDimension = currentDimension;
355
+ }
356
+ };
357
+ /**
358
+ * Error thrown when required credentials for an embedding provider are missing.
359
+ * This allows the system to gracefully degrade to FTS-only search when vectorization is unavailable.
360
+ */
361
+ var MissingCredentialsError = class extends StoreError {
362
+ provider;
363
+ constructor(provider, missingCredentials) {
364
+ super(`Missing credentials for ${provider} embedding provider. Required: ${missingCredentials.join(", ")}`);
365
+ this.provider = provider;
366
+ }
367
+ };
368
+ // src/store/embeddings/EmbeddingConfig.ts
369
+ /**
370
+ * Shared embedding model configuration service.
371
+ * Provides synchronous parsing of embedding model configuration and known dimensions lookup.
372
+ * Eliminates code duplication between DocumentStore and telemetry systems.
373
+ *
374
+ * All model lookups are case-insensitive to handle variations in model name capitalization.
375
+ * Uses class-based approach to avoid mutable global state and improve testability.
376
+ */
377
+ /**
378
+ * The complete set of provider prefixes recognized in a model specification.
379
+ * Anything else before the first colon is part of the model name itself.
380
+ *
381
+ * This list is normative rather than descriptive: it decides which prefixes claim
382
+ * the provider slot, so adding an entry changes how existing specifications parse.
383
+ * A model literally named `<new-provider>:<tag>` served by an OpenAI-compatible
384
+ * endpoint would start resolving to the new provider, breaking that configuration
385
+ * on upgrade. Call provider additions out in the release notes.
386
+ *
387
+ * `EmbeddingProvider` is derived from this array so the two cannot drift apart.
388
+ */
389
+ var SUPPORTED_PROVIDERS = [
390
+ "openai",
391
+ "vertex",
392
+ "gemini",
393
+ "aws",
394
+ "microsoft"
395
+ ];
396
+ /**
397
+ * Split a model specification into its provider prefix and model name.
398
+ *
399
+ * Only a prefix that names a supported provider is treated as a provider, matched
400
+ * case-insensitively and resolved to its canonical lowercase form. Every other
401
+ * specification is an OpenAI-compatible model name, which keeps names that carry a
402
+ * tag or quantization suffix intact (e.g. "nomic-embed-text:latest" or
403
+ * "second-state/jina-embeddings-v3-GGUF:Q4_K_M").
404
+ *
405
+ * @param spec The full model specification.
406
+ * @returns The resolved provider and model name.
407
+ */
408
+ function splitModelSpec(spec) {
409
+ const colonIndex = spec.indexOf(":");
410
+ const prefix = spec.substring(0, colonIndex).toLowerCase();
411
+ const provider = colonIndex === -1 ? void 0 : SUPPORTED_PROVIDERS.find((name) => name === prefix);
412
+ return provider ? {
413
+ provider,
414
+ model: spec.substring(colonIndex + 1)
415
+ } : {
416
+ provider: "openai",
417
+ model: spec
418
+ };
419
+ }
420
+ /**
421
+ * Embedding configuration manager that handles model parsing and dimension caching.
422
+ * Encapsulates state to avoid global variable issues and improve testability.
423
+ */
424
+ var EmbeddingConfig = class EmbeddingConfig {
425
+ static instance = null;
426
+ /**
427
+ * Get the singleton instance of EmbeddingConfig.
428
+ * Creates the instance if it doesn't exist.
429
+ */
430
+ static getInstance() {
431
+ if (EmbeddingConfig.instance === null) EmbeddingConfig.instance = new EmbeddingConfig();
432
+ return EmbeddingConfig.instance;
433
+ }
434
+ /**
435
+ * Reset the singleton instance (useful for testing).
436
+ */
437
+ static resetInstance() {
438
+ EmbeddingConfig.instance = null;
439
+ }
440
+ /**
441
+ * Known dimensions for common embedding models.
442
+ * This avoids expensive API calls for dimension detection in telemetry.
443
+ *
444
+ * Note: The "openai" provider also supports OpenAI-compatible APIs like:
445
+ * - Ollama (local models)
446
+ * - LMStudio (local models)
447
+ * - Any service implementing OpenAI's embedding API
448
+ */
449
+ knownModelDimensions = {
450
+ "text-embedding-3-small": 1536,
451
+ "text-embedding-3-large": 3072,
452
+ "text-embedding-ada-002": 1536,
453
+ "text-embedding-004": 768,
454
+ "text-embedding-005": 768,
455
+ "textembedding-gecko@003": 768,
456
+ "textembedding-gecko@002": 768,
457
+ "textembedding-gecko@001": 768,
458
+ "text-embedding-preview-0409": 768,
459
+ "embedding-001": 768,
460
+ "gemini-embedding-2-preview": 3072,
461
+ "amazon.titan-embed-text-v1": 1536,
462
+ "amazon.titan-embed-text-v2:0": 1024,
463
+ "amazon.titan-embed-image-v1": 1024,
464
+ "cohere.embed-english-v3": 1024,
465
+ "cohere.embed-multilingual-v3": 1024,
466
+ "Cohere/Cohere-embed-v4.0": 1536,
467
+ "embed-v4.0": 1536,
468
+ "intfloat/multilingual-e5-large": 1024,
469
+ "multilingual-e5-large": 1024,
470
+ "text-embedding-multilingual-e5-large": 1024,
471
+ "sentence-transformers/all-MiniLM-L6-v2": 384,
472
+ "gemini-embedding-001": 3072,
473
+ "Qwen/Qwen3-Embedding-8B": 4096,
474
+ "Qwen/Qwen3-Embedding-4B": 2560,
475
+ "Qwen/Qwen3-Embedding-0.6B": 1024,
476
+ "Linq-AI-Research/Linq-Embed-Mistral": 4096,
477
+ "Alibaba-NLP/gte-Qwen2-7B-instruct": 3584,
478
+ "intfloat/multilingual-e5-large-instruct": 1024,
479
+ "Salesforce/SFR-Embedding-Mistral": 4096,
480
+ "text-multilingual-embedding-002": 768,
481
+ "GritLM/GritLM-7B": 4096,
482
+ "GritLM/GritLM-8x7B": 4096,
483
+ "intfloat/e5-mistral-7b-instruct": 4096,
484
+ "Cohere/Cohere-embed-multilingual-v3.0": 1024,
485
+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct": 8960,
486
+ "Lajavaness/bilingual-embedding-large": 1024,
487
+ "Salesforce/SFR-Embedding-2_R": 4096,
488
+ "NovaSearch/stella_en_1.5B_v5": 8960,
489
+ "NovaSearch/jasper_en_vision_language_v1": 8960,
490
+ "nvidia/NV-Embed-v2": 4096,
491
+ "OrdalieTech/Solon-embeddings-large-0.1": 1024,
492
+ "BAAI/bge-m3": 1024,
493
+ "HIT-TMG/KaLM-embedding-multilingual-mini-v1": 896,
494
+ "jinaai/jina-embeddings-v3": 1024,
495
+ "Alibaba-NLP/gte-multilingual-base": 768,
496
+ "Lajavaness/bilingual-embedding-base": 768,
497
+ "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1": 896,
498
+ "nvidia/NV-Embed-v1": 4096,
499
+ "Cohere/Cohere-embed-multilingual-light-v3.0": 384,
500
+ "manu/bge-m3-custom-fr": 1024,
501
+ "Lajavaness/bilingual-embedding-small": 384,
502
+ "Snowflake/snowflake-arctic-embed-l-v2.0": 1024,
503
+ "intfloat/multilingual-e5-base": 768,
504
+ "voyage-3-lite": 512,
505
+ "voyage-3": 1024,
506
+ "voyage-3-large": 1024,
507
+ "voyage-3.5": 1024,
508
+ "voyage-4": 1024,
509
+ "voyage-4-large": 1024,
510
+ "voyage-4-lite": 1024,
511
+ "voyage-code-3": 1024,
512
+ "intfloat/multilingual-e5-small": 384,
513
+ "Alibaba-NLP/gte-Qwen1.5-7B-instruct": 4096,
514
+ "Snowflake/snowflake-arctic-embed-m-v2.0": 768,
515
+ "deepvk/USER-bge-m3": 1024,
516
+ "Cohere/Cohere-embed-english-v3.0": 1024,
517
+ "Omartificial-Intelligence-Space/Arabic-labse-Matryoshka": 768,
518
+ "ibm-granite/granite-embedding-278m-multilingual": 768,
519
+ "NovaSearch/stella_en_400M_v5": 4096,
520
+ "omarelshehy/arabic-english-sts-matryoshka": 1024,
521
+ "sentence-transformers/paraphrase-multilingual-mpnet-base-v2": 768,
522
+ "Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka": 768,
523
+ "Haon-Chen/speed-embedding-7b-instruct": 4096,
524
+ "sentence-transformers/LaBSE": 768,
525
+ "WhereIsAI/UAE-Large-V1": 1024,
526
+ "ibm-granite/granite-embedding-107m-multilingual": 384,
527
+ "mixedbread-ai/mxbai-embed-large-v1": 1024,
528
+ "intfloat/e5-large-v2": 1024,
529
+ "avsolatorio/GIST-large-Embedding-v0": 1024,
530
+ "sdadas/mmlw-e5-large": 1024,
531
+ "nomic-ai/nomic-embed-text-v1": 768,
532
+ "nomic-embed-text-v1": 768,
533
+ "nomic-ai/nomic-embed-text-v1-ablated": 768,
534
+ "nomic-ai/nomic-embed-text-v2-moe": 768,
535
+ "nomic-ai/modernbert-embed-base": 768,
536
+ "nomic-ai/nomic-embed-code": 3584,
537
+ "intfloat/e5-base-v2": 768,
538
+ "BAAI/bge-large-en-v1.5": 1024,
539
+ "intfloat/e5-large": 1024,
540
+ "Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet": 384,
541
+ "Cohere/Cohere-embed-english-light-v3.0": 384,
542
+ "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2": 768,
543
+ "Gameselo/STS-multilingual-mpnet-base-v2": 768,
544
+ "thenlper/gte-large": 1024,
545
+ "avsolatorio/GIST-Embedding-v0": 768,
546
+ "nomic-ai/nomic-embed-text-v1-unsupervised": 768,
547
+ "infgrad/stella-base-en-v2": 768,
548
+ "avsolatorio/NoInstruct-small-Embedding-v0": 384,
549
+ "dwzhu/e5-base-4k": 768,
550
+ "sdadas/mmlw-e5-base": 768,
551
+ "voyage-multilingual-2": 1024,
552
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised": 4096,
553
+ "BAAI/bge-base-en-v1.5": 768,
554
+ "avsolatorio/GIST-small-Embedding-v0": 384,
555
+ "sdadas/mmlw-roberta-large": 1024,
556
+ "nomic-ai/nomic-embed-text-v1.5": 768,
557
+ "nomic-embed-text-v1.5": 768,
558
+ "text-embedding-nomic-embed-text-v1.5": 768,
559
+ "minishlab/potion-multilingual-128M": 256,
560
+ "shibing624/text2vec-base-multilingual": 384,
561
+ "thenlper/gte-base": 768,
562
+ "intfloat/e5-small-v2": 384,
563
+ "intfloat/e5-base": 768,
564
+ "sentence-transformers/static-similarity-mrl-multilingual-v1": 1024,
565
+ "manu/sentence_croissant_alpha_v0.3": 2048,
566
+ "BAAI/bge-small-en-v1.5": 512,
567
+ "thenlper/gte-small": 384,
568
+ "sdadas/mmlw-e5-small": 384,
569
+ "manu/sentence_croissant_alpha_v0.4": 2048,
570
+ "manu/sentence_croissant_alpha_v0.2": 2048,
571
+ "abhinand/MedEmbed-small-v0.1": 384,
572
+ "ibm-granite/granite-embedding-125m-english": 768,
573
+ "intfloat/e5-small": 384,
574
+ "voyage-large-2-instruct": 1024,
575
+ "sdadas/mmlw-roberta-base": 768,
576
+ "Snowflake/snowflake-arctic-embed-l": 1024,
577
+ "Mihaiii/Ivysaur": 384,
578
+ "Snowflake/snowflake-arctic-embed-m-long": 768,
579
+ "bigscience/sgpt-bloom-7b1-msmarco": 4096,
580
+ "avsolatorio/GIST-all-MiniLM-L6-v2": 384,
581
+ "sergeyzh/LaBSE-ru-turbo": 768,
582
+ "sentence-transformers/all-mpnet-base-v2": 768,
583
+ "Snowflake/snowflake-arctic-embed-m": 768,
584
+ "Snowflake/snowflake-arctic-embed-s": 384,
585
+ "sentence-transformers/all-MiniLM-L12-v2": 384,
586
+ "Mihaiii/gte-micro-v4": 384,
587
+ "Snowflake/snowflake-arctic-embed-m-v1.5": 768,
588
+ "cointegrated/LaBSE-en-ru": 768,
589
+ "Mihaiii/Bulbasaur": 384,
590
+ "ibm-granite/granite-embedding-30m-english": 384,
591
+ "deepfile/embedder-100p": 768,
592
+ "Jaume/gemma-2b-embeddings": 2048,
593
+ "OrlikB/KartonBERT-USE-base-v1": 768,
594
+ "izhx/udever-bloom-7b1": 4096,
595
+ "izhx/udever-bloom-1b1": 1024,
596
+ "brahmairesearch/slx-v0.1": 384,
597
+ "Mihaiii/Wartortle": 384,
598
+ "izhx/udever-bloom-3b": 2048,
599
+ "deepvk/USER-base": 768,
600
+ "ai-forever/ru-en-RoSBERTa": 1024,
601
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse": 4096,
602
+ "Mihaiii/Venusaur": 384,
603
+ "Snowflake/snowflake-arctic-embed-xs": 384,
604
+ "jinaai/jina-embedding-b-en-v1": 768,
605
+ "Mihaiii/gte-micro": 384,
606
+ "aari1995/German_Semantic_STS_V2": 1024,
607
+ "Mihaiii/Squirtle": 384,
608
+ "OrlikB/st-polish-kartonberta-base-alpha-v1": 768,
609
+ "sergeyzh/rubert-tiny-turbo": 312,
610
+ "minishlab/potion-base-8M": 256,
611
+ "minishlab/M2V_base_glove_subword": 256,
612
+ "jinaai/jina-embedding-s-en-v1": 512,
613
+ "minishlab/potion-base-4M": 128,
614
+ "minishlab/M2V_base_output": 256,
615
+ "DeepPavlov/rubert-base-cased-sentence": 768,
616
+ "jinaai/jina-embeddings-v2-small-en": 512,
617
+ "cointegrated/rubert-tiny2": 312,
618
+ "minishlab/M2V_base_glove": 256,
619
+ "cointegrated/rubert-tiny": 312,
620
+ "silma-ai/silma-embeddding-matryoshka-v0.1": 768,
621
+ "DeepPavlov/rubert-base-cased": 768,
622
+ "Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet": 768,
623
+ "izhx/udever-bloom-560m": 1024,
624
+ "minishlab/potion-base-2M": 64,
625
+ "DeepPavlov/distilrubert-small-cased-conversational": 768,
626
+ "consciousAI/cai-lunaris-text-embeddings": 1024,
627
+ "deepvk/deberta-v1-base": 768,
628
+ "Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka": 768,
629
+ "Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka": 768,
630
+ "ai-forever/sbert_large_mt_nlu_ru": 1024,
631
+ "ai-forever/sbert_large_nlu_ru": 1024,
632
+ "malenia1/ternary-weight-embedding": 1024,
633
+ "jinaai/jina-embeddings-v2-base-en": 768,
634
+ "VPLabs/SearchMap_Preview": 4096,
635
+ "Hum-Works/lodestone-base-4096-v1": 768,
636
+ "jinaai/jina-embeddings-v4": 2048
637
+ };
638
+ runtimeDetectedDimensionModels = /* @__PURE__ */ new Set([
639
+ "novasearch/stella_en_1.5b_v5",
640
+ "stella_en_1.5b_v5",
641
+ "novasearch/stella_en_400m_v5",
642
+ "dunzhang/stella_en_400m_v5",
643
+ "stella_en_400m_v5",
644
+ "novasearch/jasper_en_vision_language_v1",
645
+ "jasper_en_vision_language_v1"
646
+ ]);
647
+ /**
648
+ * Lowercase lookup map for case-insensitive model dimension queries.
649
+ * Built lazily from knownModelDimensions to ensure consistency.
650
+ */
651
+ modelLookup;
652
+ constructor() {
653
+ this.modelLookup = /* @__PURE__ */ new Map();
654
+ for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) this.modelLookup.set(model.toLowerCase(), dimensions);
655
+ }
656
+ /**
657
+ * Build the lookup keys to try for a model name, most specific first:
658
+ * the name itself, then with the namespace dropped, the tag dropped, and both.
659
+ *
660
+ * Dropping a trailing tag lets a quantized or tagged variant reuse the base
661
+ * model's dimensions (e.g. "nomic-ai/nomic-embed-text-v2-moe:latest"), which
662
+ * quantization does not change. Exact matches are tried first, so names whose
663
+ * own identifier contains a colon (e.g. "amazon.titan-embed-text-v2:0") still
664
+ * resolve to their own entry.
665
+ */
666
+ dimensionLookupKeys(normalized) {
667
+ const slashIndex = normalized.lastIndexOf("/");
668
+ const withoutNamespace = slashIndex > -1 ? normalized.substring(slashIndex + 1) : void 0;
669
+ const bases = withoutNamespace ? [normalized, withoutNamespace] : [normalized];
670
+ const withoutTag = (key) => {
671
+ const colonIndex = key.lastIndexOf(":");
672
+ return colonIndex > 0 ? [key.substring(0, colonIndex)] : [];
673
+ };
674
+ return [...bases, ...bases.flatMap(withoutTag)];
675
+ }
676
+ findKnownDimension(model) {
677
+ for (const key of this.dimensionLookupKeys(model.toLowerCase())) {
678
+ if (this.runtimeDetectedDimensionModels.has(key)) return null;
679
+ const dimensions = this.modelLookup?.get(key);
680
+ if (dimensions !== void 0) return dimensions;
681
+ }
682
+ return null;
683
+ }
684
+ /**
685
+ * Parse embedding model configuration from a provided model specification.
686
+ * This is a synchronous operation that extracts provider, model, and known dimensions.
687
+ *
688
+ * Supports various providers:
689
+ * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)
690
+ * - vertex: Google Cloud Vertex AI
691
+ * - gemini: Google Generative AI
692
+ * - aws: AWS Bedrock models
693
+ * - microsoft: Azure OpenAI
694
+ *
695
+ * @param modelSpec Model specification (e.g., "openai:text-embedding-3-small"), defaults to "text-embedding-3-small"
696
+ * @returns Parsed embedding model configuration
697
+ */
698
+ parse(modelSpec) {
699
+ const spec = normalizeEnvValue(modelSpec || "text-embedding-3-small");
700
+ const { provider, model } = splitModelSpec(spec);
701
+ return {
702
+ provider,
703
+ model,
704
+ dimensions: this.findKnownDimension(model),
705
+ modelSpec: spec
706
+ };
707
+ }
708
+ /**
709
+ * Get the known dimensions for a specific model.
710
+ * Returns null if the model dimensions are not known.
711
+ * Uses case-insensitive lookup.
712
+ *
713
+ * @param model The model name (e.g., "text-embedding-3-small")
714
+ * @returns Known dimensions or null
715
+ */
716
+ getKnownDimensions(model) {
717
+ return this.findKnownDimension(model);
718
+ }
719
+ /**
720
+ * Add or update known dimensions for a model.
721
+ * This can be used to cache discovered dimensions.
722
+ * Stores both original case and lowercase for consistent lookup.
723
+ *
724
+ * @param model The model name
725
+ * @param dimensions The dimensions to cache
726
+ */
727
+ setKnownDimensions(model, dimensions) {
728
+ this.knownModelDimensions[model] = dimensions;
729
+ if (this.modelLookup) this.modelLookup.set(model.toLowerCase(), dimensions);
730
+ }
731
+ /**
732
+ * Static method to parse embedding model configuration using the singleton instance.
733
+ * This maintains backward compatibility while using the class-based approach.
734
+ */
735
+ static parseEmbeddingConfig(modelSpec) {
736
+ return EmbeddingConfig.getInstance().parse(modelSpec);
737
+ }
738
+ /**
739
+ * Static method to get known model dimensions using the singleton instance.
740
+ * This maintains backward compatibility while using the class-based approach.
741
+ */
742
+ static getKnownModelDimensions(model) {
743
+ return EmbeddingConfig.getInstance().getKnownDimensions(model);
744
+ }
745
+ /**
746
+ * Static method to set known model dimensions using the singleton instance.
747
+ * This maintains backward compatibility while using the class-based approach.
748
+ */
749
+ static setKnownModelDimensions(model, dimensions) {
750
+ EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);
751
+ }
752
+ };
753
+ // src/utils/paths.ts
754
+ var projectRoot = null;
755
+ /**
756
+ * Finds the project root directory by searching upwards from the current file
757
+ * for a directory containing 'package.json'. Caches the result.
758
+ *
759
+ * @returns {string} The absolute path to the project root.
760
+ * @throws {Error} If package.json cannot be found.
761
+ */
762
+ function getProjectRoot() {
763
+ if (projectRoot) return projectRoot;
764
+ const currentFilePath = fileURLToPath(import.meta.url);
765
+ let currentDir = path.dirname(currentFilePath);
766
+ while (true) {
767
+ const packageJsonPath = path.join(currentDir, "package.json");
768
+ if (fs.existsSync(packageJsonPath)) {
769
+ projectRoot = currentDir;
770
+ return currentDir;
771
+ }
772
+ const parentDir = path.dirname(currentDir);
773
+ if (parentDir === currentDir) throw new Error("Could not find project root containing package.json.");
774
+ currentDir = parentDir;
775
+ }
776
+ }
777
+ /**
778
+ * Resolves the data storage path using the following priority:
779
+ * 1. Provided storePath parameter
780
+ * 2. Legacy .store directory in project root (if exists)
781
+ * 3. Standard system data directory using env-paths
782
+ *
783
+ * @param storePath Optional custom storage path
784
+ * @returns Resolved absolute path for data storage
785
+ */
786
+ function resolveStorePath(storePath) {
787
+ let dbDir;
788
+ if (storePath) dbDir = path.resolve(storePath);
789
+ else {
790
+ const projectRoot = getProjectRoot();
791
+ const oldDbDir = path.join(projectRoot, ".store");
792
+ const oldDbPath = path.join(oldDbDir, "documents.db");
793
+ if (fs.existsSync(oldDbPath)) dbDir = oldDbDir;
794
+ else dbDir = envPaths("docs-mcp-server", { suffix: "" }).data;
795
+ }
796
+ try {
797
+ fs.mkdirSync(dbDir, { recursive: true });
798
+ } catch (error) {
799
+ logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);
800
+ }
801
+ return dbDir;
802
+ }
803
+ // src/utils/serverOrigin.ts
804
+ /**
805
+ * Normalize a configured origin (`scheme://host[:port]`) into its canonical form.
806
+ *
807
+ * Empty strings are treated as absent so container environments can leave the
808
+ * variable declared but unset.
809
+ *
810
+ * @param origin - The configured value.
811
+ * @param settingName - The setting named in error messages.
812
+ * @returns The canonical origin, or `undefined` when absent.
813
+ * @throws Error naming the setting when the value is not an HTTP(S) origin.
814
+ */
815
+ function normalizePublicOrigin(origin, settingName = "server.publicOrigin") {
816
+ const configured = parseConfiguredUrl(origin, settingName, "origin without path, query, or fragment");
817
+ if (!configured) return;
818
+ const { parsed } = configured;
819
+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) throw new Error(`${settingName} must not include a path, query string, or fragment.`);
820
+ return parsed.origin;
821
+ }
822
+ /**
823
+ * First path segments of the server's own root routes, plus `oauth` for the
824
+ * removed OAuth proxy endpoints. A public URL must not start with one:
825
+ * stripping such a base path from a request the proxy already stripped would
826
+ * remove the route itself (`/mcp` under a base path of `/mcp` would become
827
+ * `/`). These paths also never fall back to the web UI, so clients probing the
828
+ * removed endpoints get a clean 404 instead of an HTML page.
829
+ */
830
+ var RESERVED_ROOT_SEGMENTS = [
831
+ "mcp",
832
+ "api",
833
+ "assets",
834
+ ".well-known",
835
+ "sse",
836
+ "messages",
837
+ "oauth"
838
+ ];
839
+ /**
840
+ * Normalize a configured public URL: an absolute HTTP(S) URL that may carry a
841
+ * path, returned without a trailing slash.
842
+ *
843
+ * Empty strings are treated as absent so container environments can leave the
844
+ * variable declared but unset.
845
+ *
846
+ * @param value - The configured `server.publicUrl` value.
847
+ * @returns The canonical URL (e.g. `https://example.com/docs`), or `undefined` when absent.
848
+ * @throws Error naming `server.publicUrl` when the value has credentials, a query
849
+ * string, a fragment, a non-HTTP(S) protocol, an empty path segment (`//`),
850
+ * or a first path segment that collides with a route or file the server
851
+ * serves at its root.
852
+ */
853
+ function normalizePublicUrl(value) {
854
+ const configured = parseConfiguredUrl(value, "server.publicUrl", "URL without query string or fragment");
855
+ if (!configured) return;
856
+ const { parsed, trimmed } = configured;
857
+ if (trimmed.includes("?") || trimmed.includes("#")) throw new Error("server.publicUrl must not include a query string or fragment.");
858
+ if (parsed.pathname.includes("//")) throw new Error(`server.publicUrl path must not contain an empty segment ("//"): "${parsed.pathname}".`);
859
+ const path = parsed.pathname.replace(/\/$/, "");
860
+ const firstSegment = path.split("/")[1]?.toLowerCase();
861
+ 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".`);
862
+ return `${parsed.origin}${path}`;
863
+ }
864
+ /**
865
+ * Parse a configured HTTP(S) URL and apply the checks every such setting shares.
866
+ * Empty values count as absent.
867
+ * @returns The parsed URL and the trimmed input, or `undefined` when absent.
868
+ * @throws Error naming the setting when the value is not an HTTP(S) URL or has credentials.
869
+ */
870
+ function parseConfiguredUrl(value, settingName, expectedShape) {
871
+ const trimmed = value?.trim();
872
+ if (!trimmed) return;
873
+ let parsed;
874
+ try {
875
+ parsed = new URL(trimmed);
876
+ } catch {
877
+ throw new Error(`${settingName} must be an absolute HTTP(S) ${expectedShape}.`);
878
+ }
879
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`${settingName} must use the http or https protocol.`);
880
+ if (parsed.username || parsed.password) throw new Error(`${settingName} must not include credentials.`);
881
+ return {
882
+ parsed,
883
+ trimmed
884
+ };
885
+ }
886
+ /**
887
+ * Resolve the public location from configuration: `server.publicUrl` first,
888
+ * then the deprecated `server.publicOrigin`, then the bind-derived origin.
889
+ *
890
+ * @param config - The loaded application configuration.
891
+ * @param port - The port this process listens on (used for the bind fallback).
892
+ * @returns The resolved public location.
893
+ * @throws Error when a configured value is invalid (configuration loading
894
+ * normally rejects those earlier).
895
+ */
896
+ function resolvePublicLocation(config, port) {
897
+ const configuredUrl = normalizePublicUrl(config.server.publicUrl) ?? normalizePublicOrigin(config.server.publicOrigin);
898
+ const url = configuredUrl ?? buildBindOrigin(config.server.host, port);
899
+ const origin = new URL(url).origin;
900
+ return {
901
+ configured: configuredUrl !== void 0,
902
+ url,
903
+ origin,
904
+ basePath: url.slice(origin.length)
905
+ };
906
+ }
907
+ /**
908
+ * Describe deprecation problems with the configured public location, for the
909
+ * caller to log at startup.
910
+ *
911
+ * @param config - The loaded application configuration.
912
+ * @returns Warning messages; empty when nothing needs attention.
913
+ */
914
+ function describePublicLocationWarnings(config) {
915
+ const hasUrl = Boolean(config.server.publicUrl?.trim());
916
+ const hasOrigin = Boolean(config.server.publicOrigin?.trim());
917
+ if (hasUrl && hasOrigin) return ["server.publicOrigin is ignored because server.publicUrl is also set. Remove server.publicOrigin."];
918
+ if (hasOrigin) return ["server.publicOrigin is deprecated. Use server.publicUrl instead."];
919
+ return [];
920
+ }
921
+ /**
922
+ * Build an HTTP origin from the local bind host and port.
923
+ *
924
+ * The server itself listens over HTTP; deployments that terminate TLS should
925
+ * configure server.publicUrl to advertise an HTTPS URL.
926
+ */
927
+ function buildBindOrigin(host, port) {
928
+ const formattedHost = formatHostForUrl(host);
929
+ return new URL(`http://${formattedHost}:${port}`).origin;
930
+ }
931
+ function formatHostForUrl(host) {
932
+ const trimmed = host.trim();
933
+ const unbracketed = stripIpv6Brackets(trimmed);
934
+ if (unbracketed.includes(":")) return `[${unbracketed}]`;
935
+ return trimmed;
936
+ }
937
+ /**
938
+ * Remove the brackets around an IPv6 address literal, as URLs and `Host`
939
+ * headers write it. Other values are returned unchanged.
940
+ * @param host - A host, e.g. `[::1]` or `example.com`.
941
+ * @returns The host without brackets, e.g. `::1`.
942
+ */
943
+ function stripIpv6Brackets(host) {
944
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
945
+ }
946
+ // src/utils/config.ts
947
+ var managedConfigVectorDimensionOmissionMarker = "docs-mcp-server-managed-vector-dimension-omitted";
948
+ var managedConfigHeader = [
949
+ `# ${managedConfigVectorDimensionOmissionMarker}`,
950
+ "# embeddings.vectorDimension is omitted when it comes from generated defaults.",
951
+ "# Add embeddings.vectorDimension explicitly to override native model dimensions.",
952
+ ""
953
+ ].join("\n");
954
+ var vectorDimensionPath = ["embeddings", "vectorDimension"];
955
+ var envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
956
+ if (Array.isArray(value)) return value;
957
+ const parsed = yaml.parse(value);
958
+ if (Array.isArray(parsed)) return parsed.map((item) => String(item));
959
+ return [value];
960
+ }).pipe(z.array(z.string()));
961
+ /**
962
+ * Custom zod schema for boolean values that properly handles string representations.
963
+ * Unlike z.coerce.boolean() which treats any non-empty string as true,
964
+ * this schema correctly parses "false", "0", "no", "off" as false.
965
+ */
966
+ var envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
967
+ if (typeof val === "boolean") return val;
968
+ const lower = val.toLowerCase().trim();
969
+ return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off" && lower !== "";
970
+ }).pipe(z.boolean());
971
+ /**
972
+ * Parses a boolean environment variable the way configuration settings are
973
+ * parsed: "false", "0", "no", "off" and blank are false, anything else true.
974
+ * @param value - The variable's value.
975
+ * @returns The boolean, or undefined when the variable is unset.
976
+ */
977
+ function parseEnvBoolean(value) {
978
+ return value === void 0 ? void 0 : envBoolean.parse(value);
979
+ }
980
+ /**
981
+ * Treats blank strings (empty env vars, `--flag ""`) as an absent value so that
982
+ * defaults and fallbacks apply instead of an empty string.
983
+ */
984
+ var blankToUndefined = (value) => {
985
+ if (typeof value !== "string") return value;
986
+ const trimmed = value.trim();
987
+ return trimmed.length > 0 ? trimmed : void 0;
988
+ };
989
+ /** Report a normalizer's error as the validation issue of the setting. */
990
+ function addNormalizationIssue(ctx, error) {
991
+ ctx.addIssue({
992
+ code: z.ZodIssueCode.custom,
993
+ message: error instanceof Error ? error.message : String(error)
994
+ });
995
+ }
996
+ /**
997
+ * An optional string setting that `normalize` validates and canonicalizes.
998
+ * The normalizer treats empty values as absent and throws a message naming
999
+ * the setting for invalid ones.
1000
+ */
1001
+ function normalizedStringSchema(normalize) {
1002
+ return z.string().optional().transform((value, ctx) => {
1003
+ try {
1004
+ return normalize(value);
1005
+ } catch (error) {
1006
+ addNormalizationIssue(ctx, error);
1007
+ return z.NEVER;
1008
+ }
1009
+ });
1010
+ }
1011
+ var publicOriginSchema = normalizedStringSchema(normalizePublicOrigin);
1012
+ var publicUrlSchema = normalizedStringSchema(normalizePublicUrl);
1013
+ /**
1014
+ * Browser origins allowed to call the MCP endpoint in addition to loopback and
1015
+ * the public URL's origin. Each entry must be an exact origin
1016
+ * (`scheme://host[:port]`); a trailing slash is ignored.
1017
+ */
1018
+ var allowedOriginsSchema = envStringArray.transform((values, ctx) => {
1019
+ const origins = [];
1020
+ for (const value of values) try {
1021
+ const origin = normalizePublicOrigin(value, "server.allowedOrigins");
1022
+ if (origin) origins.push(origin);
1023
+ } catch (error) {
1024
+ addNormalizationIssue(ctx, error);
1025
+ return z.NEVER;
1026
+ }
1027
+ return origins;
1028
+ });
1029
+ var DEFAULT_CONFIG = {
1030
+ app: {
1031
+ storePath: "",
1032
+ telemetryEnabled: true,
1033
+ readOnly: false,
1034
+ embeddingModel: "text-embedding-3-small"
1035
+ },
1036
+ server: {
1037
+ name: "docs-mcp-server",
1038
+ title: void 0,
1039
+ instructions: void 0,
1040
+ instructionsFile: void 0,
1041
+ protocol: "auto",
1042
+ host: "127.0.0.1",
1043
+ publicUrl: void 0,
1044
+ publicOrigin: void 0,
1045
+ allowedOrigins: [],
1046
+ ports: {
1047
+ default: 6280,
1048
+ worker: 8080,
1049
+ mcp: 6280,
1050
+ web: 6281
1051
+ },
1052
+ heartbeatMs: 3e4
1053
+ },
1054
+ auth: {
1055
+ enabled: false,
1056
+ issuerUrl: "",
1057
+ audience: ""
1058
+ },
1059
+ scraper: {
1060
+ maxPages: 1e3,
1061
+ maxDepth: 3,
1062
+ maxConcurrency: 3,
1063
+ jobHeartbeatMs: 15e3,
1064
+ abortOnFailureRate: .5,
1065
+ preserveHashes: false,
1066
+ skipKnownTrackers: true,
1067
+ pageTimeoutMs: 5e3,
1068
+ browserTimeoutMs: 3e4,
1069
+ htmlExtractor: "cheerio",
1070
+ fetcher: {
1071
+ maxRetries: 3,
1072
+ baseDelayMs: 1e3,
1073
+ timeoutMs: 3e4,
1074
+ maxCacheItems: 200,
1075
+ maxCacheItemSizeBytes: 512e3
1076
+ },
1077
+ document: { maxSize: 10485760 },
1078
+ security: {
1079
+ network: {
1080
+ mode: "open",
1081
+ allowPrivateNetworks: false,
1082
+ allowedHosts: [],
1083
+ allowedCidrs: [],
1084
+ allowInvalidTls: false
1085
+ },
1086
+ fileAccess: {
1087
+ mode: "allowedRoots",
1088
+ allowedRoots: ["$DOCUMENTS"],
1089
+ followSymlinks: false,
1090
+ includeHidden: false
1091
+ }
1092
+ }
1093
+ },
1094
+ splitter: {
1095
+ minChunkSize: 500,
1096
+ preferredChunkSize: 1500,
1097
+ maxChunkSize: 5e3,
1098
+ treeSitterSizeLimit: 3e4,
1099
+ json: {
1100
+ maxNestingDepth: 5,
1101
+ maxChunks: 1e3
1102
+ }
1103
+ },
1104
+ embeddings: {
1105
+ batchSize: 100,
1106
+ batchChars: 5e4,
1107
+ requestTimeoutMs: 3e4,
1108
+ initTimeoutMs: 3e4,
1109
+ vectorDimension: 1536
1110
+ },
1111
+ db: {
1112
+ migrationMaxRetries: 5,
1113
+ migrationRetryDelayMs: 300
1114
+ },
1115
+ search: {
1116
+ overfetchFactor: 2,
1117
+ weightVec: 1,
1118
+ weightFts: 1,
1119
+ vectorMultiplier: 10
1120
+ },
1121
+ assembly: {
1122
+ maxParentChainDepth: 10,
1123
+ childLimit: 3,
1124
+ precedingSiblingsLimit: 1,
1125
+ subsequentSiblingsLimit: 2,
1126
+ maxChunkDistance: 3
1127
+ }
1128
+ };
1129
+ var AppConfigSchema = z.object({
1130
+ app: z.object({
1131
+ storePath: z.string().default(DEFAULT_CONFIG.app.storePath),
1132
+ telemetryEnabled: envBoolean.default(DEFAULT_CONFIG.app.telemetryEnabled),
1133
+ readOnly: envBoolean.default(DEFAULT_CONFIG.app.readOnly),
1134
+ embeddingModel: z.string().default(DEFAULT_CONFIG.app.embeddingModel)
1135
+ }).default(DEFAULT_CONFIG.app),
1136
+ server: z.object({
1137
+ name: z.preprocess(blankToUndefined, z.string().default(DEFAULT_CONFIG.server.name)),
1138
+ title: z.preprocess(blankToUndefined, z.string().optional()),
1139
+ instructions: z.preprocess(blankToUndefined, z.string().optional()),
1140
+ instructionsFile: z.preprocess(blankToUndefined, z.string().optional()),
1141
+ protocol: z.string().default(DEFAULT_CONFIG.server.protocol),
1142
+ host: z.string().default(DEFAULT_CONFIG.server.host),
1143
+ publicUrl: publicUrlSchema.optional(),
1144
+ publicOrigin: publicOriginSchema.optional(),
1145
+ allowedOrigins: allowedOriginsSchema.default(DEFAULT_CONFIG.server.allowedOrigins),
1146
+ ports: z.object({
1147
+ default: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.default),
1148
+ worker: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.worker),
1149
+ mcp: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.mcp),
1150
+ web: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.web)
1151
+ }).default(DEFAULT_CONFIG.server.ports),
1152
+ heartbeatMs: z.coerce.number().int().default(DEFAULT_CONFIG.server.heartbeatMs)
1153
+ }).default({
1154
+ name: DEFAULT_CONFIG.server.name,
1155
+ protocol: DEFAULT_CONFIG.server.protocol,
1156
+ host: DEFAULT_CONFIG.server.host,
1157
+ allowedOrigins: DEFAULT_CONFIG.server.allowedOrigins,
1158
+ ports: DEFAULT_CONFIG.server.ports,
1159
+ heartbeatMs: DEFAULT_CONFIG.server.heartbeatMs
1160
+ }),
1161
+ auth: z.object({
1162
+ enabled: envBoolean.default(DEFAULT_CONFIG.auth.enabled),
1163
+ issuerUrl: z.string().default(DEFAULT_CONFIG.auth.issuerUrl),
1164
+ audience: z.string().default(DEFAULT_CONFIG.auth.audience)
1165
+ }).default(DEFAULT_CONFIG.auth),
1166
+ scraper: z.object({
1167
+ maxPages: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxPages),
1168
+ maxDepth: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxDepth),
1169
+ maxConcurrency: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxConcurrency),
1170
+ jobHeartbeatMs: z.coerce.number().int().positive().default(DEFAULT_CONFIG.scraper.jobHeartbeatMs),
1171
+ abortOnFailureRate: z.coerce.number().min(0).max(1).default(DEFAULT_CONFIG.scraper.abortOnFailureRate),
1172
+ preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),
1173
+ skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
1174
+ pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
1175
+ browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
1176
+ htmlExtractor: z.enum(["cheerio", "defuddle"]).default(DEFAULT_CONFIG.scraper.htmlExtractor),
1177
+ fetcher: z.object({
1178
+ maxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),
1179
+ baseDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),
1180
+ timeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.timeoutMs),
1181
+ maxCacheItems: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItems),
1182
+ maxCacheItemSizeBytes: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItemSizeBytes)
1183
+ }).default(DEFAULT_CONFIG.scraper.fetcher),
1184
+ document: z.object({ maxSize: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.document.maxSize) }).default(DEFAULT_CONFIG.scraper.document),
1185
+ security: z.object({
1186
+ network: z.object({
1187
+ mode: z.enum(["open", "allowlist"]).default(DEFAULT_CONFIG.scraper.security.network.mode),
1188
+ allowPrivateNetworks: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks),
1189
+ allowedHosts: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedHosts),
1190
+ allowedCidrs: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedCidrs),
1191
+ allowInvalidTls: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowInvalidTls)
1192
+ }).default(DEFAULT_CONFIG.scraper.security.network),
1193
+ fileAccess: z.object({
1194
+ mode: z.enum([
1195
+ "disabled",
1196
+ "allowedRoots",
1197
+ "unrestricted"
1198
+ ]).default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),
1199
+ allowedRoots: envStringArray.default(DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots),
1200
+ followSymlinks: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks),
1201
+ includeHidden: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden)
1202
+ }).default(DEFAULT_CONFIG.scraper.security.fileAccess)
1203
+ }).default(DEFAULT_CONFIG.scraper.security)
1204
+ }).default(DEFAULT_CONFIG.scraper),
1205
+ splitter: z.object({
1206
+ minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),
1207
+ preferredChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.preferredChunkSize),
1208
+ maxChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.maxChunkSize),
1209
+ treeSitterSizeLimit: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.treeSitterSizeLimit),
1210
+ json: z.object({
1211
+ maxNestingDepth: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxNestingDepth),
1212
+ maxChunks: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxChunks)
1213
+ }).default(DEFAULT_CONFIG.splitter.json)
1214
+ }).default(DEFAULT_CONFIG.splitter),
1215
+ embeddings: z.object({
1216
+ batchSize: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchSize),
1217
+ batchChars: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchChars),
1218
+ requestTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.requestTimeoutMs),
1219
+ initTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.initTimeoutMs),
1220
+ vectorDimension: z.coerce.number().int().min(1, "embedding dimension must be at least 1").default(DEFAULT_CONFIG.embeddings.vectorDimension)
1221
+ }).default(DEFAULT_CONFIG.embeddings),
1222
+ db: z.object({
1223
+ migrationMaxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationMaxRetries),
1224
+ migrationRetryDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationRetryDelayMs)
1225
+ }).default(DEFAULT_CONFIG.db),
1226
+ search: z.object({
1227
+ overfetchFactor: z.coerce.number().default(DEFAULT_CONFIG.search.overfetchFactor),
1228
+ weightVec: z.coerce.number().default(DEFAULT_CONFIG.search.weightVec),
1229
+ weightFts: z.coerce.number().default(DEFAULT_CONFIG.search.weightFts),
1230
+ vectorMultiplier: z.coerce.number().int().default(DEFAULT_CONFIG.search.vectorMultiplier)
1231
+ }).default(DEFAULT_CONFIG.search),
1232
+ assembly: z.object({
1233
+ maxParentChainDepth: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.maxParentChainDepth),
1234
+ childLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.childLimit),
1235
+ precedingSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.precedingSiblingsLimit),
1236
+ subsequentSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.subsequentSiblingsLimit),
1237
+ maxChunkDistance: z.coerce.number().int().min(0).default(DEFAULT_CONFIG.assembly.maxChunkDistance)
1238
+ }).default(DEFAULT_CONFIG.assembly)
1239
+ });
1240
+ var vectorDimensionExplicit = Symbol("vectorDimensionExplicit");
1241
+ var defaults = AppConfigSchema.parse({});
1242
+ var configMappings = [
1243
+ {
1244
+ path: ["server", "protocol"],
1245
+ env: ["DOCS_MCP_PROTOCOL"],
1246
+ cli: "protocol"
1247
+ },
1248
+ {
1249
+ path: ["app", "storePath"],
1250
+ env: ["DOCS_MCP_STORE_PATH"],
1251
+ cli: "storePath"
1252
+ },
1253
+ {
1254
+ path: ["app", "telemetryEnabled"],
1255
+ env: ["DOCS_MCP_TELEMETRY"]
1256
+ },
1257
+ {
1258
+ path: ["app", "readOnly"],
1259
+ env: ["DOCS_MCP_READ_ONLY"],
1260
+ cli: "readOnly"
1261
+ },
1262
+ {
1263
+ path: [
1264
+ "server",
1265
+ "ports",
1266
+ "default"
1267
+ ],
1268
+ env: ["DOCS_MCP_PORT", "PORT"],
1269
+ cli: "port"
1270
+ },
1271
+ {
1272
+ path: [
1273
+ "server",
1274
+ "ports",
1275
+ "worker"
1276
+ ],
1277
+ env: ["DOCS_MCP_PORT", "PORT"],
1278
+ cli: "port"
1279
+ },
1280
+ {
1281
+ path: [
1282
+ "server",
1283
+ "ports",
1284
+ "mcp"
1285
+ ],
1286
+ env: ["DOCS_MCP_PORT", "PORT"],
1287
+ cli: "port"
1288
+ },
1289
+ {
1290
+ path: [
1291
+ "server",
1292
+ "ports",
1293
+ "web"
1294
+ ],
1295
+ env: [
1296
+ "DOCS_MCP_WEB_PORT",
1297
+ "DOCS_MCP_PORT",
1298
+ "PORT"
1299
+ ],
1300
+ cli: "port"
1301
+ },
1302
+ {
1303
+ path: ["server", "host"],
1304
+ env: ["DOCS_MCP_HOST", "HOST"],
1305
+ cli: "host"
1306
+ },
1307
+ {
1308
+ path: ["server", "publicUrl"],
1309
+ env: ["DOCS_MCP_SERVER_PUBLIC_URL"],
1310
+ cli: "publicUrl"
1311
+ },
1312
+ {
1313
+ path: ["server", "publicOrigin"],
1314
+ env: ["DOCS_MCP_SERVER_PUBLIC_ORIGIN"],
1315
+ cli: "publicOrigin"
1316
+ },
1317
+ {
1318
+ path: ["server", "name"],
1319
+ env: ["DOCS_MCP_SERVER_NAME"],
1320
+ cli: "serverName"
1321
+ },
1322
+ {
1323
+ path: ["server", "title"],
1324
+ env: ["DOCS_MCP_SERVER_TITLE"],
1325
+ cli: "serverTitle"
1326
+ },
1327
+ {
1328
+ path: ["server", "instructions"],
1329
+ env: ["DOCS_MCP_SERVER_INSTRUCTIONS"],
1330
+ cli: "serverInstructions"
1331
+ },
1332
+ {
1333
+ path: ["server", "instructionsFile"],
1334
+ env: ["DOCS_MCP_SERVER_INSTRUCTIONS_FILE"],
1335
+ cli: "serverInstructionsFile"
1336
+ },
1337
+ {
1338
+ path: ["app", "embeddingModel"],
1339
+ env: ["DOCS_MCP_EMBEDDING_MODEL"],
1340
+ cli: "embeddingModel"
1341
+ },
1342
+ {
1343
+ path: ["auth", "enabled"],
1344
+ env: ["DOCS_MCP_AUTH_ENABLED"],
1345
+ cli: "authEnabled"
1346
+ },
1347
+ {
1348
+ path: ["auth", "issuerUrl"],
1349
+ env: ["DOCS_MCP_AUTH_ISSUER_URL"],
1350
+ cli: "authIssuerUrl"
1351
+ },
1352
+ {
1353
+ path: ["auth", "audience"],
1354
+ env: ["DOCS_MCP_AUTH_AUDIENCE"],
1355
+ cli: "authAudience"
1356
+ }
1357
+ ];
1358
+ var systemPaths = envPaths("docs-mcp-server", { suffix: "" });
1359
+ function loadConfig(cliArgs = {}, options = {}) {
1360
+ const explicitPath = cliArgs.config || options.configPath || process.env.DOCS_MCP_CONFIG;
1361
+ let configPath;
1362
+ let isReadOnlyConfig = false;
1363
+ if (explicitPath) {
1364
+ configPath = explicitPath;
1365
+ isReadOnlyConfig = true;
1366
+ } else {
1367
+ configPath = path.join(systemPaths.config, "config.yaml");
1368
+ isReadOnlyConfig = false;
1369
+ }
1370
+ logger.debug(`Using config file: ${configPath}`);
1371
+ const fileConfig = loadConfigFile(configPath) || {};
1372
+ const hasManagedVectorDimensionOmissionMarker = hasManagedConfigVectorDimensionOmissionMarker(configPath);
1373
+ const baseConfig = deepMerge(defaults, fileConfig);
1374
+ const envConfig = mapEnvToConfig();
1375
+ const cliConfig = mapCliToConfig(cliArgs);
1376
+ const vectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
1377
+ const fileVectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, {}, {}, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
1378
+ if (!isReadOnlyConfig) try {
1379
+ saveConfigFile(configPath, baseConfig, {
1380
+ managedDefaultConfig: true,
1381
+ omitVectorDimension: !fileVectorDimensionWasExplicit
1382
+ });
1383
+ } catch (error) {
1384
+ logger.warn(`Failed to save config file to ${configPath}: ${error}`);
1385
+ }
1386
+ const mergedInput = deepMerge(baseConfig, deepMerge(envConfig, cliConfig));
1387
+ if (!getAtPath(mergedInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(mergedInput, ["app", "embeddingModel"], "text-embedding-3-small");
1388
+ const parseResult = AppConfigSchema.safeParse(mergedInput);
1389
+ if (parseResult.success) return markVectorDimensionSource(parseResult.data, vectorDimensionWasExplicit);
1390
+ for (const setting of [
1391
+ "publicUrl",
1392
+ "publicOrigin",
1393
+ "allowedOrigins"
1394
+ ]) if (hasParseIssueAtPath(parseResult.error, ["server", setting])) throw new Error(`Invalid configuration for server.${setting}: ${parseResult.error.message}`);
1395
+ if (!isReadOnlyConfig && fs.existsSync(configPath)) {
1396
+ const quarantinePath = `${configPath}.invalid-${Date.now()}`;
1397
+ try {
1398
+ fs.renameSync(configPath, quarantinePath);
1399
+ logger.warn(`Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`);
1400
+ } catch (renameError) {
1401
+ logger.warn(`Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`);
1402
+ }
1403
+ } else logger.warn(`Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`);
1404
+ const fallbackInput = deepMerge(defaults, deepMerge(envConfig, cliConfig));
1405
+ if (!getAtPath(fallbackInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
1406
+ const fallbackConfig = markVectorDimensionSource(AppConfigSchema.parse(fallbackInput), wasVectorDimensionExplicit({}, envConfig, cliConfig, false, false));
1407
+ if (!isReadOnlyConfig) try {
1408
+ saveConfigFile(configPath, fallbackConfig, {
1409
+ managedDefaultConfig: true,
1410
+ omitVectorDimension: true
1411
+ });
1412
+ } catch (error) {
1413
+ logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
1414
+ }
1415
+ return fallbackConfig;
1416
+ }
1417
+ function hasManagedConfigVectorDimensionOmissionMarker(filePath) {
1418
+ if (!fs.existsSync(filePath)) return false;
1419
+ try {
1420
+ return fs.readFileSync(filePath, "utf8").includes(managedConfigVectorDimensionOmissionMarker);
1421
+ } catch {
1422
+ return false;
1423
+ }
1424
+ }
1425
+ /**
1426
+ * Returns true when the embedding vector dimension was set by user config,
1427
+ * environment, or CLI rather than coming from generated defaults.
1428
+ */
1429
+ function isVectorDimensionExplicit(config) {
1430
+ return config.embeddings[vectorDimensionExplicit] === true;
1431
+ }
1432
+ /**
1433
+ * Marks an AppConfig as having an explicit or default-derived vector dimension.
1434
+ */
1435
+ function markVectorDimensionSource(config, explicit) {
1436
+ Object.defineProperty(config.embeddings, vectorDimensionExplicit, {
1437
+ value: explicit,
1438
+ enumerable: false,
1439
+ configurable: true
1440
+ });
1441
+ return config;
1442
+ }
1443
+ function loadConfigFile(filePath) {
1444
+ if (!fs.existsSync(filePath)) return null;
1445
+ try {
1446
+ const content = fs.readFileSync(filePath, "utf8");
1447
+ if (filePath.endsWith(".json")) return JSON.parse(content);
1448
+ return yaml.parse(content) || {};
1449
+ } catch (error) {
1450
+ logger.warn(`Failed to parse config file ${filePath}: ${error}`);
1451
+ return null;
1452
+ }
1453
+ }
1454
+ function wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker) {
1455
+ if (getAtPath(envConfig, vectorDimensionPath) !== void 0 || getAtPath(cliConfig, vectorDimensionPath) !== void 0) return true;
1456
+ const fileValue = getAtPath(fileConfig, vectorDimensionPath);
1457
+ if (fileValue === void 0) return false;
1458
+ if (isReadOnlyConfig || fileValue !== DEFAULT_CONFIG.embeddings.vectorDimension || hasManagedVectorDimensionOmissionMarker) return true;
1459
+ return !looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig);
1460
+ }
1461
+ function looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig) {
1462
+ const embeddings = fileConfig.embeddings;
1463
+ if (typeof embeddings !== "object" || embeddings === null || Array.isArray(embeddings)) return false;
1464
+ return Object.keys(DEFAULT_CONFIG.embeddings).every((key) => Object.hasOwn(embeddings, key));
1465
+ }
1466
+ function saveConfigFile(filePath, config, options = {}) {
1467
+ const dir = path.dirname(filePath);
1468
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
1469
+ const configToWrite = cloneConfigValue(config);
1470
+ if (options.omitVectorDimension) unsetAtPath(configToWrite, vectorDimensionPath);
1471
+ let content;
1472
+ if (filePath.endsWith(".json")) content = JSON.stringify(configToWrite, null, 2);
1473
+ else {
1474
+ content = yaml.stringify(configToWrite);
1475
+ if (options.managedDefaultConfig) content = `${managedConfigHeader}${content}`;
1476
+ }
1477
+ logger.debug(`Updating config file at ${filePath}`);
1478
+ fs.writeFileSync(filePath, content, "utf8");
1479
+ }
1480
+ function mapEnvToConfig() {
1481
+ const config = {};
1482
+ for (const mapping of configMappings) if (mapping.env) {
1483
+ for (const envVar of mapping.env) if (process.env[envVar] !== void 0) {
1484
+ setAtPath(config, mapping.path, normalizeEnvValue(process.env[envVar]));
1485
+ break;
1486
+ }
1487
+ }
1488
+ for (const pathArr of ALL_CONFIG_LEAF_PATHS) {
1489
+ const envVar = pathToEnvVar(pathArr);
1490
+ if (process.env[envVar] !== void 0) setAtPath(config, pathArr, normalizeEnvValue(process.env[envVar]));
1491
+ }
1492
+ return config;
1493
+ }
1494
+ function mapCliToConfig(args) {
1495
+ const config = {};
1496
+ for (const mapping of configMappings) if (mapping.cli && args[mapping.cli] !== void 0) setAtPath(config, mapping.path, args[mapping.cli]);
1497
+ return config;
1498
+ }
1499
+ /**
1500
+ * Convert camelCase to UPPER_SNAKE_CASE
1501
+ * Example: "maxSize" → "MAX_SIZE", "maxNestingDepth" → "MAX_NESTING_DEPTH"
1502
+ */
1503
+ function camelToUpperSnake(str) {
1504
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
1505
+ }
1506
+ /**
1507
+ * Convert config path to environment variable name
1508
+ * Example: ["scraper", "document", "maxSize"] → "DOCS_MCP_SCRAPER_DOCUMENT_MAX_SIZE"
1509
+ */
1510
+ function pathToEnvVar(pathArr) {
1511
+ return `DOCS_MCP_${pathArr.map(camelToUpperSnake).join("_")}`;
1512
+ }
1513
+ /**
1514
+ * Recursively collect all leaf paths from a config object
1515
+ */
1516
+ function collectLeafPaths(obj, prefix = []) {
1517
+ const paths = [];
1518
+ for (const [key, value] of Object.entries(obj)) {
1519
+ const currentPath = [...prefix, key];
1520
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) paths.push(...collectLeafPaths(value, currentPath));
1521
+ else paths.push(currentPath);
1522
+ }
1523
+ return paths;
1524
+ }
1525
+ var ALL_CONFIG_LEAF_PATHS = collectLeafPaths(DEFAULT_CONFIG);
1526
+ function setAtPath(obj, pathArr, value) {
1527
+ let current = obj;
1528
+ for (let i = 0; i < pathArr.length - 1; i++) {
1529
+ const key = pathArr[i];
1530
+ if (current[key] === void 0 || typeof current[key] !== "object" || current[key] === null) current[key] = {};
1531
+ current = current[key];
1532
+ }
1533
+ current[pathArr[pathArr.length - 1]] = value;
1534
+ }
1535
+ function getAtPath(obj, pathArr) {
1536
+ let current = obj;
1537
+ for (const key of pathArr) {
1538
+ if (typeof current !== "object" || current === null) return void 0;
1539
+ current = current[key];
1540
+ }
1541
+ return current;
1542
+ }
1543
+ function unsetAtPath(obj, pathArr) {
1544
+ let current = obj;
1545
+ for (const key of pathArr.slice(0, -1)) {
1546
+ if (typeof current !== "object" || current === null) return;
1547
+ current = current[key];
1548
+ }
1549
+ if (typeof current === "object" && current !== null) delete current[pathArr[pathArr.length - 1]];
1550
+ }
1551
+ function cloneConfigValue(value) {
1552
+ if (Array.isArray(value)) return value.map((item) => cloneConfigValue(item));
1553
+ if (typeof value === "object" && value !== null) {
1554
+ const output = {};
1555
+ for (const [key, child] of Object.entries(value)) output[key] = cloneConfigValue(child);
1556
+ return output;
1557
+ }
1558
+ return value;
1559
+ }
1560
+ function hasPath(obj, pathArr) {
1561
+ let current = obj;
1562
+ for (const key of pathArr) {
1563
+ if (typeof current !== "object" || current === null || !Object.hasOwn(current, key)) return false;
1564
+ current = current[key];
1565
+ }
1566
+ return true;
1567
+ }
1568
+ function hasParseIssueAtPath(error, pathArr) {
1569
+ return error.issues.some((issue) => issue.path.join(".") === pathArr.join("."));
1570
+ }
1571
+ function deepMerge(target, source) {
1572
+ if (typeof target !== "object" || target === null) return source;
1573
+ if (typeof source !== "object" || source === null) return target;
1574
+ if (Array.isArray(target) || Array.isArray(source)) return source;
1575
+ const t = target;
1576
+ const s = source;
1577
+ const output = { ...t };
1578
+ for (const key of Object.keys(s)) {
1579
+ const sValue = s[key];
1580
+ const tValue = t[key];
1581
+ 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);
1582
+ else output[key] = sValue;
1583
+ }
1584
+ return output;
1585
+ }
1586
+ /**
1587
+ * Check if a config path is valid by verifying it exists in DEFAULT_CONFIG
1588
+ */
1589
+ function isValidConfigPath(path) {
1590
+ return hasPath(DEFAULT_CONFIG, path.split("."));
1591
+ }
1592
+ /**
1593
+ * Get a config value by dot-separated path
1594
+ */
1595
+ function getConfigValue(config, path) {
1596
+ return getAtPath(config, path.split("."));
1597
+ }
1598
+ /**
1599
+ * Parse a string value to the appropriate type (number, boolean, or string)
1600
+ */
1601
+ function parseConfigValue(value) {
1602
+ const num = Number(value);
1603
+ if (!Number.isNaN(num) && value.trim() !== "") return num;
1604
+ const lower = value.toLowerCase();
1605
+ if (lower === "true") return true;
1606
+ if (lower === "false") return false;
1607
+ return value;
1608
+ }
1609
+ /**
1610
+ * Set a config value and persist to file.
1611
+ * Returns the path to the config file that was updated.
1612
+ * Validates the updated config against the schema before saving.
1613
+ */
1614
+ function setConfigValue(path, value) {
1615
+ const configPath = getDefaultConfigPath();
1616
+ const fileConfig = loadConfigFile(configPath) || {};
1617
+ const pathArr = path.split(".");
1618
+ const parsedValue = parseConfigValue(value);
1619
+ const updatedConfig = JSON.parse(JSON.stringify(fileConfig));
1620
+ setAtPath(updatedConfig, pathArr, parsedValue);
1621
+ try {
1622
+ AppConfigSchema.parse(updatedConfig);
1623
+ } catch (err) {
1624
+ const errorMsg = err instanceof Error ? err.message : String(err);
1625
+ throw new Error(`Invalid config value for "${path}": ${errorMsg}`);
1626
+ }
1627
+ saveConfigFile(configPath, updatedConfig);
1628
+ return configPath;
1629
+ }
1630
+ /**
1631
+ * Get the default system config path
1632
+ */
1633
+ function getDefaultConfigPath() {
1634
+ return path.join(systemPaths.config, "config.yaml");
1635
+ }
1636
+ // src/cli/utils.ts
1637
+ /**
1638
+ * Shared CLI utilities and helper functions.
1639
+ */
1640
+ /**
1641
+ * Retrieves the global EventBusService from the arguments context.
1642
+ * @param argv The parsed arguments context.
1643
+ * @returns The global EventBusService.
1644
+ * @throws Error if EventBusService is not initialized.
1645
+ */
1646
+ function getEventBus(argv) {
1647
+ const eventBus = argv._eventBus;
1648
+ if (!eventBus) throw new Error("EventBusService not initialized");
1649
+ return eventBus;
1650
+ }
1651
+ /**
1652
+ * Helper to extract GlobalOptions from the argv.
1653
+ * In Yargs, all options are in argv, so we just cast/pick.
1654
+ */
1655
+ function getGlobalOptions(argv) {
1656
+ return argv;
1657
+ }
1658
+ /**
1659
+ * Ensures that the Playwright browsers are installed, unless a system Chromium path is set.
1660
+ */
1661
+ function ensurePlaywrightBrowsersInstalled() {
1662
+ if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === "1") {
1663
+ logger.debug("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.");
1664
+ return;
1665
+ }
1666
+ const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
1667
+ if (chromiumEnvPath && existsSync(chromiumEnvPath)) {
1668
+ logger.debug(`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`);
1669
+ return;
1670
+ }
1671
+ try {
1672
+ const chromiumPath = chromium.executablePath();
1673
+ if (!chromiumPath || !existsSync(chromiumPath)) throw new Error("Playwright Chromium browser not found");
1674
+ } catch (error) {
1675
+ logger.debug(String(error));
1676
+ try {
1677
+ logger.info("🌐 Installing Playwright Chromium browser... (this may take a moment)");
1678
+ execSync("npm exec -y playwright install --no-shell --with-deps chromium", {
1679
+ stdio: "ignore",
1680
+ cwd: getProjectRoot()
1681
+ });
1682
+ } catch (_installErr) {
1683
+ logger.error("❌ Failed to install Playwright browsers automatically. Please run:\n npx playwright install --no-shell --with-deps chromium\nand try again.");
1684
+ process.exit(1);
1685
+ }
1686
+ }
1687
+ }
1688
+ /**
1689
+ * Resolves the protocol based on auto-detection or explicit specification.
1690
+ * Auto-detection uses TTY status to determine appropriate protocol.
1691
+ */
1692
+ function resolveProtocol(protocol) {
1693
+ if (protocol === "auto") {
1694
+ if (!process.stdin.isTTY && !process.stdout.isTTY) return "stdio";
1695
+ return "http";
1696
+ }
1697
+ if (protocol === "stdio" || protocol === "http") return protocol;
1698
+ throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);
1699
+ }
1700
+ /**
1701
+ * Validates and parses port number
1702
+ */
1703
+ function validatePort(portString) {
1704
+ const port = Number.parseInt(portString, 10);
1705
+ if (Number.isNaN(port) || port < 1 || port > 65535) throw new Error("Invalid port number");
1706
+ return port;
1707
+ }
1708
+ /**
1709
+ * Validates host string for basic format checking
1710
+ */
1711
+ function validateHost(hostString) {
1712
+ const trimmed = hostString.trim();
1713
+ if (!trimmed) throw new Error("Host cannot be empty");
1714
+ if (trimmed.includes(" ") || trimmed.includes(" ") || trimmed.includes("\n")) throw new Error("Host cannot contain whitespace");
1715
+ return trimmed;
1716
+ }
1717
+ /**
1718
+ * Creates AppServerConfig based on service requirements.
1719
+ *
1720
+ * AppConfig is the source of truth for host/auth/telemetry/read-only settings.
1721
+ * AppServerConfig only selects which services to run and which port to bind to.
1722
+ * Whether the server runs jobs itself or uses a worker follows from the backend.
1723
+ *
1724
+ * @param options Which services to run, the port, and startup details.
1725
+ * @returns The server configuration.
1726
+ */
1727
+ function createAppServerConfig(options) {
1728
+ return {
1729
+ enableWebInterface: options.enableWebInterface ?? false,
1730
+ enableMcpServer: options.enableMcpServer ?? true,
1731
+ enableApiServer: options.enableApiServer ?? false,
1732
+ port: options.port,
1733
+ showLogo: options.showLogo ?? true,
1734
+ startupContext: options.startupContext
1735
+ };
1736
+ }
1737
+ /**
1738
+ * Parses custom headers from CLI options
1739
+ */
1740
+ function parseHeaders(headerOptions) {
1741
+ const headers = {};
1742
+ if (Array.isArray(headerOptions)) for (const entry of headerOptions) {
1743
+ const idx = entry.indexOf(":");
1744
+ if (idx > 0) {
1745
+ const name = entry.slice(0, idx).trim();
1746
+ const value = entry.slice(idx + 1).trim();
1747
+ if (name) headers[name] = value;
1748
+ }
1749
+ }
1750
+ return headers;
1751
+ }
1752
+ /**
1753
+ * Check the auth settings for the transport a command serves. Authentication
1754
+ * applies to MCP over HTTP only. Over stdio the host launching the process is
1755
+ * the trust boundary, so auth settings are ignored with a warning on stderr,
1756
+ * which never carries protocol data.
1757
+ * @param auth - The loaded auth settings.
1758
+ * @param protocol - The resolved transport.
1759
+ * @param port - The HTTP port, for the plain-HTTP warning.
1760
+ * @throws Error when an auth setting over HTTP is malformed.
1761
+ */
1762
+ function checkAuthForProtocol(auth, protocol, port) {
1763
+ if (!auth.enabled) return;
1764
+ if (protocol === "stdio") {
1765
+ console.error("⚠️ Authentication does not apply to MCP over stdio; auth settings are ignored.");
1766
+ return;
1767
+ }
1768
+ validateAuthConfig(auth);
1769
+ warnHttpUsage(port);
1770
+ }
1771
+ /**
1772
+ * Validates the format of auth settings that are present. Whether a setting
1773
+ * is required depends on what the process serves, so the server checks that
1774
+ * at startup.
1775
+ */
1776
+ function validateAuthConfig(authConfig) {
1777
+ const errors = [];
1778
+ if (authConfig.issuerUrl) try {
1779
+ if (new URL(authConfig.issuerUrl).protocol !== "https:") errors.push("Issuer URL must use HTTPS protocol");
1780
+ } catch {
1781
+ errors.push("Issuer URL must be a valid URL");
1782
+ }
1783
+ if (authConfig.audience) try {
1784
+ const url = new URL(authConfig.audience);
1785
+ if (url.protocol === "http:" && url.hostname !== "localhost") logger.warn("⚠️ Audience uses HTTP protocol - consider using HTTPS for production");
1786
+ if (url.hash) errors.push("Audience must not contain URL fragments");
1787
+ } catch {
1788
+ if (authConfig.audience.startsWith("urn:")) {
1789
+ const urnParts = authConfig.audience.split(":");
1790
+ if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) errors.push("URN audience must follow format: urn:namespace:specific-string");
1791
+ } else errors.push("Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)");
1792
+ }
1793
+ if (errors.length > 0) throw new Error(`Auth configuration validation failed:\n${errors.join("\n")}`);
1794
+ }
1795
+ /**
1796
+ * Warns about HTTP usage in production when auth is enabled.
1797
+ */
1798
+ function warnHttpUsage(port) {
1799
+ 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.");
1800
+ }
1801
+ /**
1802
+ * Resolves embedding configuration from the provided model specification.
1803
+ * This function centralizes the logic for determining the embedding model.
1804
+ *
1805
+ * @param embeddingModel The embedding model specification string.
1806
+ * @returns Embedding configuration or null if config is unavailable.
1807
+ */
1808
+ function resolveEmbeddingContext(embeddingModel) {
1809
+ try {
1810
+ const modelSpec = embeddingModel;
1811
+ if (!modelSpec) {
1812
+ logger.debug("No embedding model specified. Embeddings are disabled.");
1813
+ return null;
1814
+ }
1815
+ logger.debug(`Resolving embedding configuration for model: ${modelSpec}`);
1816
+ return EmbeddingConfig.parseEmbeddingConfig(modelSpec);
1817
+ } catch (error) {
1818
+ logger.debug(`Failed to resolve embedding configuration: ${error}`);
1819
+ return null;
1820
+ }
1821
+ }
1822
+ /**
1823
+ * Prompts the user interactively to confirm an embedding model change.
1824
+ * Returns true if the user confirms (y/Y), false otherwise.
1825
+ */
1826
+ function promptModelChangeConfirmation(change) {
1827
+ return new Promise((resolve) => {
1828
+ 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`);
1829
+ const rl = createInterface({
1830
+ input: process.stdin,
1831
+ output: process.stderr
1832
+ });
1833
+ rl.question(" Proceed with model change? (y/N) ", (answer) => {
1834
+ rl.close();
1835
+ resolve(answer.trim().toLowerCase() === "y");
1836
+ });
1837
+ });
1838
+ }
1839
+ /**
1840
+ * Handles EmbeddingModelChangedError during service initialization.
1841
+ *
1842
+ * - When accepted (`--accept-model-change` or `DOCS_MCP_ACCEPT_MODEL_CHANGE`):
1843
+ * resolves the model change (invalidates vectors) without asking.
1844
+ * - In non-interactive mode (no TTY): re-throws the error to fail startup.
1845
+ * - In interactive mode (TTY): prompts the user for confirmation, then either
1846
+ * resolves the model change or exits.
1847
+ *
1848
+ * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()
1849
+ * @param service The DocumentManagementService instance (already partially initialized)
1850
+ * @param acceptFlag The value of `--accept-model-change`; when omitted,
1851
+ * `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides
1852
+ * @throws Re-throws the error in non-interactive mode or if the user rejects the change
1853
+ */
1854
+ async function handleEmbeddingModelChange(error, service, acceptFlag) {
1855
+ if (acceptFlag ?? parseEnvBoolean(process.env.DOCS_MCP_ACCEPT_MODEL_CHANGE) ?? false) {
1856
+ logger.warn(`⚠️ Accepting embedding model change without a prompt: ${describeEmbeddingModel(error.previousModel, error.previousDimension)} → ${describeEmbeddingModel(error.currentModel, error.currentDimension)}`);
1857
+ await service.resolveModelChange();
1858
+ return;
1859
+ }
1860
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
1861
+ if (!await promptModelChangeConfirmation(error)) throw new Error("Embedding model change rejected. Startup aborted.\nRestore the previous embedding model configuration to continue without changes.");
1862
+ await service.resolveModelChange();
1863
+ }
1864
+ export { normalizeVersionName as $, DimensionError as A, VersionNotFoundInStoreError as B, getProjectRoot as C, splitModelSpec as D, SUPPORTED_PROVIDERS as E, LibraryNotFoundInStoreError as F, VersionStatus as G, quoteName as H, MissingCredentialsError as I, libraryNamesMatch as J, denormalizeVersionName as K, PageNotFoundInStoreError as L, EmbeddingModelChangedError as M, InvalidLibraryNameError as N, AmbiguousPageInStoreError as O, LibraryAlreadyExistsError as P, normalizeVersionLabel as Q, StoreError as R, stripIpv6Brackets as S, EmbeddingConfig as T, EXISTING_TARGET_POLICIES as U, formatVersionLabel as V, UPDATED_AT_RESOLUTION_MS as W, normalizeLibraryDisplayName as X, msSinceWritten as Y, normalizeLibraryName as Z, parseConfigValue as _, getGlobalOptions as a, describePublicLocationWarnings as b, resolveEmbeddingContext as c, validatePort as d, normalizeVersionRef as et, defaults as f, loadConfig as g, isVectorDimensionExplicit as h, getEventBus as i, EmbeddingError as j, ConnectionError as k, resolveProtocol as l, isValidConfigPath as m, createAppServerConfig as n, handleEmbeddingModelChange as o, getConfigValue as p, describeLibraryNameProblem as q, ensurePlaywrightBrowsersInstalled as r, parseHeaders as s, checkAuthForProtocol as t, validateHost as u, setConfigValue as v, resolveStorePath as w, resolvePublicLocation as x, RESERVED_ROOT_SEGMENTS as y, VersionAlreadyExistsError as z };
1865
+
1866
+ //# sourceMappingURL=utils-7a9aMv8E.js.map