@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.
@@ -1,7 +1,6 @@
1
- import { t as normalizeEnvValue } from "./env-DONvEfR5.js";
2
- import { i as setLogLevel, n as getLogLevelFromEnv, r as logger, t as LogLevel } from "./logger-BBxstTD7.js";
3
- import { _ as splitModelSpec, d as validatePort, g as SUPPORTED_PROVIDERS, h as EmbeddingConfig, i as getEventBus, l as resolveProtocol, m as resolveStorePath, n as createAppServerConfig, o as handleEmbeddingModelChange, p as getProjectRoot, r as ensurePlaywrightBrowsersInstalled, s as parseHeaders, t as checkAuthForProtocol, u as validateHost } from "./utils-DXo1A54z.js";
4
- import { n as formatBytes, r as fullTrim, t as escapeHtml } from "./string-B3iUfzt2.js";
1
+ 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
+ import { n as formatBytes, r as fullTrim, t as escapeHtml } from "./string-n2Z12tl6.js";
5
4
  import { BedrockEmbeddings } from "@langchain/aws";
6
5
  import { GoogleGenerativeAIEmbeddings } from "@langchain/google-genai";
7
6
  import { VertexAIEmbeddings } from "@langchain/google-vertexai";
@@ -11,7 +10,6 @@ import crypto, { randomUUID } from "node:crypto";
11
10
  import fs, { statSync } from "node:fs";
12
11
  import path from "node:path";
13
12
  import { URL as URL$1 } from "node:url";
14
- import envPaths from "env-paths";
15
13
  import { PostHog } from "posthog-node";
16
14
  import yargs from "yargs";
17
15
  import { hideBin } from "yargs/helpers";
@@ -69,350 +67,7 @@ import { fastifyTRPCPlugin } from "@trpc/server/adapters/fastify";
69
67
  import { applyWSSHandler } from "@trpc/server/adapters/ws";
70
68
  import { observable } from "@trpc/server/observable";
71
69
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
72
- //#region src/store/types.ts
73
- /**
74
- * Represents the possible states of a version's indexing status.
75
- * These statuses are stored in the database and persist across server restarts.
76
- */
77
- var VersionStatus = /* @__PURE__ */ function(VersionStatus) {
78
- VersionStatus["NOT_INDEXED"] = "not_indexed";
79
- VersionStatus["QUEUED"] = "queued";
80
- VersionStatus["RUNNING"] = "running";
81
- VersionStatus["COMPLETED"] = "completed";
82
- VersionStatus["FAILED"] = "failed";
83
- VersionStatus["CANCELLED"] = "cancelled";
84
- VersionStatus["UPDATING"] = "updating";
85
- return VersionStatus;
86
- }({});
87
- /**
88
- * Normalizes a version label for storage and lookup.
89
- *
90
- * This is the single write contract for version labels: trim surrounding
91
- * whitespace, lowercase, and treat an empty result as unversioned. The label is
92
- * otherwise stored verbatim — it is never validated, coerced or rejected, since
93
- * a version label is not guaranteed to be a semantic version (`stable` and
94
- * `1.20` are as legitimate as `1.20.0`).
95
- *
96
- * @param version Version label as supplied by a caller, if any.
97
- * @returns The normalized label, or an empty string for unversioned content.
98
- */
99
- function normalizeVersionLabel(version) {
100
- return (version ?? "").trim().toLowerCase();
101
- }
102
- /**
103
- * Computes a library's lookup key.
104
- *
105
- * The counterpart to {@link normalizeVersionLabel}: trim and lowercase (the
106
- * Unicode default lowercase mapping, without full case folding), so a library
107
- * is one row however its name was typed. The key is what `libraries.name`
108
- * stores and every lookup compares; the name as entered lives on as the display
109
- * name ({@link normalizeLibraryDisplayName}).
110
- *
111
- * @param library Library name as supplied by a caller.
112
- * @returns The lookup key.
113
- */
114
- function normalizeLibraryName(library) {
115
- return library.trim().toLowerCase();
116
- }
117
- /**
118
- * Whether two library names refer to the same library.
119
- *
120
- * The one comparison every caller-facing lookup uses, so the identity rule
121
- * lives in a single place.
122
- *
123
- * @param a A library name in any casing or padding.
124
- * @param b Another library name.
125
- */
126
- function libraryNamesMatch(a, b) {
127
- return normalizeLibraryName(a) === normalizeLibraryName(b);
128
- }
129
- /**
130
- * Computes a library's display name: the name as entered, trimmed only.
131
- *
132
- * Case, inner spacing, punctuation and non-ASCII characters are preserved, so
133
- * `Next.js Docs` is stored and shown exactly that way.
134
- *
135
- * @param library Library name as supplied by a caller.
136
- * @returns The display name to store for a new library.
137
- */
138
- function normalizeLibraryDisplayName(library) {
139
- return library.trim();
140
- }
141
- /** Unicode general category Cc: C0 controls, DEL and C1 controls such as tab, newline and ESC. */
142
- var CONTROL_CHARACTER = /\p{Cc}/u;
143
- /**
144
- * Explains why a name is unacceptable for a new library.
145
- *
146
- * Only creation is validated; existing libraries stay reachable under their
147
- * stored names. Format characters (Cf) are allowed because emoji sequences rely
148
- * on the zero-width joiner. Pure, so the web client can show the same message.
149
- *
150
- * @param displayName Name submitted for a new library; trimmed before checking.
151
- * @returns The broken rule as a short phrase, or `null` when the name is valid.
152
- */
153
- function describeLibraryNameProblem(displayName) {
154
- const name = normalizeLibraryDisplayName(displayName);
155
- if (name.length === 0) return "is empty";
156
- if (CONTROL_CHARACTER.test(name)) return "contains a control character";
157
- if ([...name].length > 100) return `is longer than 100 characters`;
158
- return null;
159
- }
160
- /**
161
- * What indexing does when its target library or version already exists.
162
- *
163
- * - `reject-library`: fail if the library exists at all (the web UI's "Add library").
164
- * - `reject-version`: fail if that version exists; create the library if needed (the default).
165
- * - `replace`: rebuild an existing version, or create it (`--replace`, `replace: true`, re-index, retry, refresh).
166
- */
167
- var EXISTING_TARGET_POLICIES = [
168
- "reject-library",
169
- "reject-version",
170
- "replace"
171
- ];
172
- /** Normalize a VersionRef (lowercase, trim; empty string for unversioned). */
173
- function normalizeVersionRef(ref) {
174
- return {
175
- library: normalizeLibraryName(ref.library),
176
- version: normalizeVersionLabel(ref.version)
177
- };
178
- }
179
- /**
180
- * `versions.updated_at` holds whole seconds (SQLite's `CURRENT_TIMESTAMP`), so
181
- * a write can read up to this much older than it happened.
182
- */
183
- var UPDATED_AT_RESOLUTION_MS = 1e3;
184
- /**
185
- * How long ago a version was last written, from its `updated_at` (UTC).
186
- *
187
- * @param version The version as read from the store.
188
- * @param now The current time, in milliseconds since the epoch.
189
- * @returns Milliseconds since the write, or `Infinity` when the version has no
190
- * readable `updated_at`.
191
- */
192
- function msSinceWritten(version, now) {
193
- const writtenAt = version.updated_at ? Date.parse(`${version.updated_at.replace(" ", "T")}Z`) : NaN;
194
- return Number.isNaN(writtenAt) ? Number.POSITIVE_INFINITY : now - writtenAt;
195
- }
196
- /**
197
- * Helper function to convert NULL version name to empty string for API compatibility.
198
- * Database stores NULL for unversioned content, but APIs expect empty string.
199
- */
200
- function normalizeVersionName(name) {
201
- return name ?? "";
202
- }
203
- /**
204
- * Helper function for version name normalization prior to storage.
205
- * Policy:
206
- * - Empty string represents the unversioned variant (stored as '').
207
- * - Names are lower-cased at call sites (see resolveLibraryAndVersionIds) to enforce
208
- * case-insensitive uniqueness; this function only preserves the empty-string rule.
209
- */
210
- function denormalizeVersionName(name) {
211
- return name === "" ? "" : name;
212
- }
213
- //#endregion
214
- //#region src/store/errors.ts
215
- /**
216
- * Base error class for all store-related errors.
217
- * Provides consistent error handling with optional cause tracking.
218
- */
219
- var StoreError = class extends Error {
220
- cause;
221
- constructor(message, cause) {
222
- super(cause ? `${message} caused by ${cause}` : message);
223
- this.cause = cause;
224
- this.name = this.constructor.name;
225
- const causeError = cause instanceof Error ? cause : cause ? new Error(String(cause)) : void 0;
226
- if (causeError?.stack) this.stack = causeError.stack;
227
- }
228
- };
229
- var CONTROL_CHARACTERS = new RegExp(CONTROL_CHARACTER.source, "gu");
230
- function escapeControlCharacter(char) {
231
- const code = char.charCodeAt(0);
232
- return code < 32 ? JSON.stringify(char).slice(1, -1) : `\\u${code.toString(16).padStart(4, "0")}`;
233
- }
234
- /**
235
- * Escapes every control character (Unicode Cc) in text that an error message
236
- * repeats, such as a library name or version, so it cannot carry terminal
237
- * control sequences or forge log lines. Other characters are left as they are.
238
- */
239
- function escapeControlCharacters(text) {
240
- return text.replace(CONTROL_CHARACTERS, escapeControlCharacter);
241
- }
242
- /**
243
- * Labels a library version as `name@version` for logs and messages, with
244
- * control characters escaped in both and unversioned documentation shown as
245
- * `latest`.
246
- */
247
- function formatVersionLabel(library, version) {
248
- return `${escapeControlCharacters(library)}@${escapeControlCharacters(version) || "latest"}`;
249
- }
250
- /**
251
- * Quotes a library name (or version) for an error message, with quotes,
252
- * backslashes and every control character escaped.
253
- */
254
- function quoteName(name) {
255
- return escapeControlCharacters(JSON.stringify(name));
256
- }
257
- /**
258
- * Error thrown when a requested library cannot be found in the store.
259
- * Includes suggestions for similar library names if available.
260
- */
261
- var LibraryNotFoundInStoreError = class extends StoreError {
262
- library;
263
- similarLibraries;
264
- constructor(library, similarLibraries = []) {
265
- let text = `Library ${escapeControlCharacters(library)} not found in store.`;
266
- if (similarLibraries.length > 0) text += ` Did you mean: ${similarLibraries.map(escapeControlCharacters).join(", ")}?`;
267
- super(text);
268
- this.library = library;
269
- this.similarLibraries = similarLibraries;
270
- }
271
- };
272
- /**
273
- * Error thrown when a specific version of a library cannot be found in the store.
274
- * Includes the list of available versions for better context.
275
- */
276
- var VersionNotFoundInStoreError = class extends StoreError {
277
- library;
278
- version;
279
- availableVersions;
280
- constructor(library, version, availableVersions) {
281
- let text = `${version ? `Version ${escapeControlCharacters(version)}` : "Version"} for library ${escapeControlCharacters(library)} not found in store.`;
282
- if (availableVersions.length > 0) text += ` Available versions: ${availableVersions.map(escapeControlCharacters).join(", ")}`;
283
- super(text);
284
- this.library = library;
285
- this.version = version;
286
- this.availableVersions = availableVersions;
287
- }
288
- };
289
- /**
290
- * Error thrown when a request to create a new library finds that library already exists.
291
- * Raised only for an explicit "Add library" request.
292
- */
293
- var LibraryAlreadyExistsError = class extends StoreError {
294
- library;
295
- constructor(library) {
296
- super(`Library ${quoteName(library)} already exists. Open it to add a version.`);
297
- this.library = library;
298
- }
299
- };
300
- /**
301
- * Error thrown when a scrape would clear an existing version without requesting replacement.
302
- */
303
- var VersionAlreadyExistsError = class extends StoreError {
304
- library;
305
- version;
306
- constructor(library, version) {
307
- const target = version ? `Version ${quoteName(version)} of library ${quoteName(library)}` : `Unversioned documentation for library ${quoteName(library)}`;
308
- super(`${target} already exists. To rebuild it, scrape again with --replace (CLI) or replace: true (MCP), or refresh it to update in place.`);
309
- this.library = library;
310
- this.version = version;
311
- }
312
- };
313
- /**
314
- * Error thrown when a new library's name breaks a naming rule.
315
- */
316
- var InvalidLibraryNameError = class extends StoreError {
317
- library;
318
- reason;
319
- constructor(library, reason) {
320
- super(`Invalid library name ${quoteName(library)}: ${reason}.`);
321
- this.library = library;
322
- this.reason = reason;
323
- }
324
- };
325
- /**
326
- * Error thrown when a requested page cannot be found in the store for a library/version.
327
- * Includes suggestions for similar page URLs if available.
328
- */
329
- var PageNotFoundInStoreError = class extends StoreError {
330
- library;
331
- version;
332
- pathOrUrl;
333
- suggestions;
334
- constructor(library, version, pathOrUrl, suggestions = []) {
335
- const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
336
- let text = `Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} not found in store.`;
337
- if (suggestions.length > 0) text += ` Did you mean: ${suggestions.map(escapeControlCharacters).join(", ")}?`;
338
- super(text);
339
- this.library = library;
340
- this.version = version;
341
- this.pathOrUrl = pathOrUrl;
342
- this.suggestions = suggestions;
343
- }
344
- };
345
- /**
346
- * Error thrown when a page path matches more than one stored page.
347
- * Lists the matching URLs so the caller can pass the full URL of the intended page.
348
- */
349
- var AmbiguousPageInStoreError = class extends StoreError {
350
- library;
351
- version;
352
- pathOrUrl;
353
- matches;
354
- constructor(library, version, pathOrUrl, matches) {
355
- const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : "";
356
- super(`Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} matches more than one page: ${matches.map(escapeControlCharacters).join(", ")}. Pass the full URL of the page to read.`);
357
- this.library = library;
358
- this.version = version;
359
- this.pathOrUrl = pathOrUrl;
360
- this.matches = matches;
361
- }
362
- };
363
- /**
364
- * Error thrown when an embedding model's vector dimension exceeds the database's fixed dimension.
365
- * This occurs when trying to use a model that produces vectors larger than the database can store.
366
- */
367
- var DimensionError = class extends StoreError {
368
- modelName;
369
- modelDimension;
370
- dbDimension;
371
- constructor(modelName, modelDimension, dbDimension) {
372
- super(`Model "${modelName}" produces ${modelDimension}-dimensional vectors, which exceeds the database's fixed dimension of ${dbDimension}. Please use a model with dimension ≤ ${dbDimension}.`);
373
- this.modelName = modelName;
374
- this.modelDimension = modelDimension;
375
- this.dbDimension = dbDimension;
376
- }
377
- };
378
- /**
379
- * Error thrown when there's a problem with database connectivity or operations.
380
- */
381
- var ConnectionError = class extends StoreError {};
382
- /**
383
- * Error thrown when the configured embedding model or vector dimension differs from the
384
- * values stored in the database metadata. This indicates that existing vectors are
385
- * incompatible with the new configuration and must be invalidated before proceeding.
386
- *
387
- * The CLI layer catches this error to either prompt the user interactively (TTY) or
388
- * fail startup entirely (non-interactive/MCP/stdio mode).
389
- */
390
- var EmbeddingModelChangedError = class extends StoreError {
391
- previousModel;
392
- previousDimension;
393
- currentModel;
394
- currentDimension;
395
- constructor(previousModel, previousDimension, currentModel, currentDimension) {
396
- super(`Embedding model change detected:\n Previous: ${previousModel} (${previousDimension} dimensions)\n Current: ${currentModel} (${currentDimension} dimensions)\n\nAll existing vectors are incompatible and must be invalidated.\nTo confirm this change, start the server interactively (with a TTY connected)\nand follow the prompts.`);
397
- this.previousModel = previousModel;
398
- this.previousDimension = previousDimension;
399
- this.currentModel = currentModel;
400
- this.currentDimension = currentDimension;
401
- }
402
- };
403
- /**
404
- * Error thrown when required credentials for an embedding provider are missing.
405
- * This allows the system to gracefully degrade to FTS-only search when vectorization is unavailable.
406
- */
407
- var MissingCredentialsError = class extends StoreError {
408
- provider;
409
- constructor(provider, missingCredentials) {
410
- super(`Missing credentials for ${provider} embedding provider. Required: ${missingCredentials.join(", ")}`);
411
- this.provider = provider;
412
- }
413
- };
414
- //#endregion
415
- //#region src/store/embeddings/FixedDimensionEmbeddings.ts
70
+ // src/store/embeddings/FixedDimensionEmbeddings.ts
416
71
  /**
417
72
  * Wrapper around an Embeddings implementation that ensures vectors have a fixed dimension.
418
73
  * - If a vector's dimension is greater than the target and truncation is allowed,
@@ -455,8 +110,7 @@ var FixedDimensionEmbeddings = class extends Embeddings {
455
110
  return (await this.embeddings.embedDocuments(documents)).map((vector) => this.normalizeVector(vector));
456
111
  }
457
112
  };
458
- //#endregion
459
- //#region src/store/embeddings/EmbeddingFactory.ts
113
+ // src/store/embeddings/EmbeddingFactory.ts
460
114
  /**
461
115
  * Error thrown when an invalid or unsupported embedding provider is specified.
462
116
  */
@@ -526,7 +180,7 @@ function createEmbeddingModel(providerAndModel, runtime) {
526
180
  if (!process.env.OPENAI_API_KEY) throw new MissingCredentialsError("openai", ["OPENAI_API_KEY"]);
527
181
  const apiKey = process.env.OPENAI_API_KEY;
528
182
  const baseURL = process.env.OPENAI_API_BASE;
529
- return new OpenAIEmbeddings({
183
+ const config = {
530
184
  ...baseConfig,
531
185
  apiKey,
532
186
  modelName: model,
@@ -537,7 +191,8 @@ function createEmbeddingModel(providerAndModel, runtime) {
537
191
  ...baseURL ? { baseURL } : {},
538
192
  timeout: requestTimeoutMs
539
193
  }
540
- });
194
+ };
195
+ return new OpenAIEmbeddings(config);
541
196
  }
542
197
  case "vertex":
543
198
  if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) throw new MissingCredentialsError("vertex", ["GOOGLE_APPLICATION_CREDENTIALS"]);
@@ -589,8 +244,7 @@ function createEmbeddingModel(providerAndModel, runtime) {
589
244
  default: throw new UnsupportedProviderError(provider);
590
245
  }
591
246
  }
592
- //#endregion
593
- //#region src/telemetry/sanitizer.ts
247
+ // src/telemetry/sanitizer.ts
594
248
  /**
595
249
  * Data sanitization utilities for privacy-first telemetry.
596
250
  * Events carry the host of a URL instead of the URL itself, and error messages
@@ -695,8 +349,7 @@ function sanitizeErrorForTracking(error) {
695
349
  sanitized.stack = [`${error.name}: ${message}`, ...frames].join("\n");
696
350
  return sanitized;
697
351
  }
698
- //#endregion
699
- //#region src/telemetry/TelemetryConfig.ts
352
+ // src/telemetry/TelemetryConfig.ts
700
353
  /**
701
354
  * Telemetry configuration management for enabling/disabling analytics collection.
702
355
  * Handles CLI flags, environment variables, and default settings.
@@ -744,8 +397,7 @@ function generateInstallationId(storePath) {
744
397
  function shouldEnableTelemetry() {
745
398
  return TelemetryConfig.getInstance().isEnabled();
746
399
  }
747
- //#endregion
748
- //#region src/events/types.ts
400
+ // src/events/types.ts
749
401
  /**
750
402
  * Event type enum used by the EventBusService.
751
403
  * These are the internal event identifiers.
@@ -757,8 +409,7 @@ var EventType = /* @__PURE__ */ function(EventType) {
757
409
  EventType["JOB_LIST_CHANGE"] = "JOB_LIST_CHANGE";
758
410
  return EventType;
759
411
  }({});
760
- //#endregion
761
- //#region src/pipeline/types.ts
412
+ // src/pipeline/types.ts
762
413
  /**
763
414
  * Represents the possible states of a pipeline job.
764
415
  */
@@ -771,8 +422,7 @@ var PipelineJobStatus = /* @__PURE__ */ function(PipelineJobStatus) {
771
422
  PipelineJobStatus["CANCELLED"] = "cancelled";
772
423
  return PipelineJobStatus;
773
424
  }({});
774
- //#endregion
775
- //#region src/telemetry/postHogClient.ts
425
+ // src/telemetry/postHogClient.ts
776
426
  /**
777
427
  * PostHog client wrapper for telemetry events.
778
428
  * Handles PostHog SDK integration and event capture with privacy-first configuration.
@@ -898,8 +548,7 @@ var PostHogClient = class PostHogClient {
898
548
  return this.enabled && !!this.client;
899
549
  }
900
550
  };
901
- //#endregion
902
- //#region src/telemetry/telemetry.ts
551
+ // src/telemetry/telemetry.ts
903
552
  /**
904
553
  * Telemtry wrapper for privacy-first telemetry using PostHog.
905
554
  * Provides global context and automatic data sanitization.
@@ -959,12 +608,6 @@ var Telemetry = class Telemetry {
959
608
  setGlobalContext(context) {
960
609
  this.globalContext = { ...context };
961
610
  }
962
- /**
963
- * Get current global context
964
- */
965
- getGlobalContext() {
966
- return { ...this.globalContext };
967
- }
968
611
  track(event, properties = {}) {
969
612
  if (!this.enabled) return;
970
613
  const enrichedProperties = {
@@ -1028,8 +671,7 @@ var telemetry = new Proxy({}, { get(_target, prop) {
1028
671
  if (typeof value === "function") return value.bind(instance);
1029
672
  return value;
1030
673
  } });
1031
- //#endregion
1032
- //#region src/telemetry/TelemetryService.ts
674
+ // src/telemetry/TelemetryService.ts
1033
675
  var TelemetryService = class {
1034
676
  eventBus;
1035
677
  unsubscribers = [];
@@ -1074,19 +716,16 @@ var TelemetryService = class {
1074
716
  throughputPagesPerSecond: duration && job.progressPages ? Math.round(job.progressPages / duration * 1e3) : 0
1075
717
  });
1076
718
  break;
1077
- case PipelineJobStatus.FAILED:
1078
- telemetry.track(TelemetryEvent.PIPELINE_JOB_FAILED, {
1079
- jobId: job.id,
1080
- library: job.library,
1081
- durationMs: duration,
1082
- pagesProcessed: job.progressPages || 0,
1083
- maxPagesConfigured: job.scraperOptions?.maxPages ?? null,
1084
- hasVersion: !!job.version,
1085
- hasError: !!job.error,
1086
- errorMessage: job.error ? sanitizeErrorMessage(job.error.message) : void 0
1087
- });
1088
- break;
1089
- default: break;
719
+ case PipelineJobStatus.FAILED: telemetry.track(TelemetryEvent.PIPELINE_JOB_FAILED, {
720
+ jobId: job.id,
721
+ library: job.library,
722
+ durationMs: duration,
723
+ pagesProcessed: job.progressPages || 0,
724
+ maxPagesConfigured: job.scraperOptions?.maxPages ?? null,
725
+ hasVersion: !!job.version,
726
+ hasError: !!job.error,
727
+ errorMessage: job.error ? sanitizeErrorMessage(job.error.message) : void 0
728
+ });
1090
729
  }
1091
730
  }
1092
731
  /**
@@ -1103,8 +742,7 @@ var TelemetryService = class {
1103
742
  logger.debug("TelemetryService shut down");
1104
743
  }
1105
744
  };
1106
- //#endregion
1107
- //#region src/events/EventBusService.ts
745
+ // src/events/EventBusService.ts
1108
746
  /**
1109
747
  * Central event bus service for application-wide event distribution.
1110
748
  *
@@ -1142,861 +780,13 @@ var EventBusService = class {
1142
780
  return () => this.emitter.off(eventType, listener);
1143
781
  }
1144
782
  /**
1145
- * Subscribe to events once (auto-unsubscribes after first event).
1146
- */
1147
- once(eventType, listener) {
1148
- this.emitter.once(eventType, listener);
1149
- }
1150
- /**
1151
783
  * Remove a specific listener.
1152
784
  */
1153
785
  off(eventType, listener) {
1154
786
  this.emitter.off(eventType, listener);
1155
787
  }
1156
- /**
1157
- * Remove all listeners for a specific event type, or all listeners if no type specified.
1158
- */
1159
- removeAllListeners(eventType) {
1160
- if (eventType === void 0) this.emitter.removeAllListeners();
1161
- else this.emitter.removeAllListeners(eventType);
1162
- }
1163
- /**
1164
- * Get the count of listeners for a specific event type.
1165
- */
1166
- listenerCount(eventType) {
1167
- return this.emitter.listenerCount(eventType);
1168
- }
1169
- };
1170
- //#endregion
1171
- //#region src/utils/serverOrigin.ts
1172
- /**
1173
- * Normalize a configured origin (`scheme://host[:port]`) into its canonical form.
1174
- *
1175
- * Empty strings are treated as absent so container environments can leave the
1176
- * variable declared but unset.
1177
- *
1178
- * @param origin - The configured value.
1179
- * @param settingName - The setting named in error messages.
1180
- * @returns The canonical origin, or `undefined` when absent.
1181
- * @throws Error naming the setting when the value is not an HTTP(S) origin.
1182
- */
1183
- function normalizePublicOrigin(origin, settingName = "server.publicOrigin") {
1184
- const configured = parseConfiguredUrl(origin, settingName, "origin without path, query, or fragment");
1185
- if (!configured) return;
1186
- const { parsed } = configured;
1187
- if (parsed.pathname !== "/" || parsed.search || parsed.hash) throw new Error(`${settingName} must not include a path, query string, or fragment.`);
1188
- return parsed.origin;
1189
- }
1190
- /**
1191
- * First path segments of the server's own root routes, plus `oauth` for the
1192
- * removed OAuth proxy endpoints. A public URL must not start with one:
1193
- * stripping such a base path from a request the proxy already stripped would
1194
- * remove the route itself (`/mcp` under a base path of `/mcp` would become
1195
- * `/`). These paths also never fall back to the web UI, so clients probing the
1196
- * removed endpoints get a clean 404 instead of an HTML page.
1197
- */
1198
- var RESERVED_ROOT_SEGMENTS = [
1199
- "mcp",
1200
- "api",
1201
- "assets",
1202
- ".well-known",
1203
- "sse",
1204
- "messages",
1205
- "oauth"
1206
- ];
1207
- /**
1208
- * Normalize a configured public URL: an absolute HTTP(S) URL that may carry a
1209
- * path, returned without a trailing slash.
1210
- *
1211
- * Empty strings are treated as absent so container environments can leave the
1212
- * variable declared but unset.
1213
- *
1214
- * @param value - The configured `server.publicUrl` value.
1215
- * @returns The canonical URL (e.g. `https://example.com/docs`), or `undefined` when absent.
1216
- * @throws Error naming `server.publicUrl` when the value has credentials, a query
1217
- * string, a fragment, a non-HTTP(S) protocol, an empty path segment (`//`),
1218
- * or a first path segment that collides with a route or file the server
1219
- * serves at its root.
1220
- */
1221
- function normalizePublicUrl(value) {
1222
- const configured = parseConfiguredUrl(value, "server.publicUrl", "URL without query string or fragment");
1223
- if (!configured) return;
1224
- const { parsed, trimmed } = configured;
1225
- if (trimmed.includes("?") || trimmed.includes("#")) throw new Error("server.publicUrl must not include a query string or fragment.");
1226
- if (parsed.pathname.includes("//")) throw new Error(`server.publicUrl path must not contain an empty segment ("//"): "${parsed.pathname}".`);
1227
- const path = parsed.pathname.replace(/\/$/, "");
1228
- const firstSegment = path.split("/")[1]?.toLowerCase();
1229
- 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".`);
1230
- return `${parsed.origin}${path}`;
1231
- }
1232
- /**
1233
- * Parse a configured HTTP(S) URL and apply the checks every such setting shares.
1234
- * Empty values count as absent.
1235
- * @returns The parsed URL and the trimmed input, or `undefined` when absent.
1236
- * @throws Error naming the setting when the value is not an HTTP(S) URL or has credentials.
1237
- */
1238
- function parseConfiguredUrl(value, settingName, expectedShape) {
1239
- const trimmed = value?.trim();
1240
- if (!trimmed) return;
1241
- let parsed;
1242
- try {
1243
- parsed = new URL(trimmed);
1244
- } catch {
1245
- throw new Error(`${settingName} must be an absolute HTTP(S) ${expectedShape}.`);
1246
- }
1247
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`${settingName} must use the http or https protocol.`);
1248
- if (parsed.username || parsed.password) throw new Error(`${settingName} must not include credentials.`);
1249
- return {
1250
- parsed,
1251
- trimmed
1252
- };
1253
- }
1254
- /**
1255
- * Resolve the public location from configuration: `server.publicUrl` first,
1256
- * then the deprecated `server.publicOrigin`, then the bind-derived origin.
1257
- *
1258
- * @param config - The loaded application configuration.
1259
- * @param port - The port this process listens on (used for the bind fallback).
1260
- * @returns The resolved public location.
1261
- * @throws Error when a configured value is invalid (configuration loading
1262
- * normally rejects those earlier).
1263
- */
1264
- function resolvePublicLocation(config, port) {
1265
- const configuredUrl = normalizePublicUrl(config.server.publicUrl) ?? normalizePublicOrigin(config.server.publicOrigin);
1266
- const url = configuredUrl ?? buildBindOrigin(config.server.host, port);
1267
- const origin = new URL(url).origin;
1268
- return {
1269
- configured: configuredUrl !== void 0,
1270
- url,
1271
- origin,
1272
- basePath: url.slice(origin.length)
1273
- };
1274
- }
1275
- /**
1276
- * Describe deprecation problems with the configured public location, for the
1277
- * caller to log at startup.
1278
- *
1279
- * @param config - The loaded application configuration.
1280
- * @returns Warning messages; empty when nothing needs attention.
1281
- */
1282
- function describePublicLocationWarnings(config) {
1283
- const hasUrl = Boolean(config.server.publicUrl?.trim());
1284
- const hasOrigin = Boolean(config.server.publicOrigin?.trim());
1285
- if (hasUrl && hasOrigin) return ["server.publicOrigin is ignored because server.publicUrl is also set. Remove server.publicOrigin."];
1286
- if (hasOrigin) return ["server.publicOrigin is deprecated. Use server.publicUrl instead."];
1287
- return [];
1288
- }
1289
- /**
1290
- * Build an HTTP origin from the local bind host and port.
1291
- *
1292
- * The server itself listens over HTTP; deployments that terminate TLS should
1293
- * configure server.publicUrl to advertise an HTTPS URL.
1294
- */
1295
- function buildBindOrigin(host, port) {
1296
- const formattedHost = formatHostForUrl(host);
1297
- return new URL(`http://${formattedHost}:${port}`).origin;
1298
- }
1299
- function formatHostForUrl(host) {
1300
- const trimmed = host.trim();
1301
- const unbracketed = stripIpv6Brackets(trimmed);
1302
- if (unbracketed.includes(":")) return `[${unbracketed}]`;
1303
- return trimmed;
1304
- }
1305
- /**
1306
- * Remove the brackets around an IPv6 address literal, as URLs and `Host`
1307
- * headers write it. Other values are returned unchanged.
1308
- * @param host - A host, e.g. `[::1]` or `example.com`.
1309
- * @returns The host without brackets, e.g. `::1`.
1310
- */
1311
- function stripIpv6Brackets(host) {
1312
- return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
1313
- }
1314
- //#endregion
1315
- //#region src/utils/config.ts
1316
- var managedConfigVectorDimensionOmissionMarker = "docs-mcp-server-managed-vector-dimension-omitted";
1317
- var managedConfigHeader = [
1318
- `# ${managedConfigVectorDimensionOmissionMarker}`,
1319
- "# embeddings.vectorDimension is omitted when it comes from generated defaults.",
1320
- "# Add embeddings.vectorDimension explicitly to override native model dimensions.",
1321
- ""
1322
- ].join("\n");
1323
- var vectorDimensionPath = ["embeddings", "vectorDimension"];
1324
- var envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
1325
- if (Array.isArray(value)) return value;
1326
- const parsed = yaml.parse(value);
1327
- if (Array.isArray(parsed)) return parsed.map((item) => String(item));
1328
- return [value];
1329
- }).pipe(z.array(z.string()));
1330
- /**
1331
- * Custom zod schema for boolean values that properly handles string representations.
1332
- * Unlike z.coerce.boolean() which treats any non-empty string as true,
1333
- * this schema correctly parses "false", "0", "no", "off" as false.
1334
- */
1335
- var envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
1336
- if (typeof val === "boolean") return val;
1337
- const lower = val.toLowerCase().trim();
1338
- return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off" && lower !== "";
1339
- }).pipe(z.boolean());
1340
- /**
1341
- * Treats blank strings (empty env vars, `--flag ""`) as an absent value so that
1342
- * defaults and fallbacks apply instead of an empty string.
1343
- */
1344
- var blankToUndefined = (value) => {
1345
- if (typeof value !== "string") return value;
1346
- const trimmed = value.trim();
1347
- return trimmed.length > 0 ? trimmed : void 0;
1348
- };
1349
- /** Report a normalizer's error as the validation issue of the setting. */
1350
- function addNormalizationIssue(ctx, error) {
1351
- ctx.addIssue({
1352
- code: z.ZodIssueCode.custom,
1353
- message: error instanceof Error ? error.message : String(error)
1354
- });
1355
- }
1356
- /**
1357
- * An optional string setting that `normalize` validates and canonicalizes.
1358
- * The normalizer treats empty values as absent and throws a message naming
1359
- * the setting for invalid ones.
1360
- */
1361
- function normalizedStringSchema(normalize) {
1362
- return z.string().optional().transform((value, ctx) => {
1363
- try {
1364
- return normalize(value);
1365
- } catch (error) {
1366
- addNormalizationIssue(ctx, error);
1367
- return z.NEVER;
1368
- }
1369
- });
1370
- }
1371
- var publicOriginSchema = normalizedStringSchema(normalizePublicOrigin);
1372
- var publicUrlSchema = normalizedStringSchema(normalizePublicUrl);
1373
- /**
1374
- * Browser origins allowed to call the MCP endpoint in addition to loopback and
1375
- * the public URL's origin. Each entry must be an exact origin
1376
- * (`scheme://host[:port]`); a trailing slash is ignored.
1377
- */
1378
- var allowedOriginsSchema = envStringArray.transform((values, ctx) => {
1379
- const origins = [];
1380
- for (const value of values) try {
1381
- const origin = normalizePublicOrigin(value, "server.allowedOrigins");
1382
- if (origin) origins.push(origin);
1383
- } catch (error) {
1384
- addNormalizationIssue(ctx, error);
1385
- return z.NEVER;
1386
- }
1387
- return origins;
1388
- });
1389
- var DEFAULT_CONFIG = {
1390
- app: {
1391
- storePath: "",
1392
- telemetryEnabled: true,
1393
- readOnly: false,
1394
- embeddingModel: "text-embedding-3-small"
1395
- },
1396
- server: {
1397
- name: "docs-mcp-server",
1398
- title: void 0,
1399
- instructions: void 0,
1400
- instructionsFile: void 0,
1401
- protocol: "auto",
1402
- host: "127.0.0.1",
1403
- publicUrl: void 0,
1404
- publicOrigin: void 0,
1405
- allowedOrigins: [],
1406
- ports: {
1407
- default: 6280,
1408
- worker: 8080,
1409
- mcp: 6280,
1410
- web: 6281
1411
- },
1412
- heartbeatMs: 3e4
1413
- },
1414
- auth: {
1415
- enabled: false,
1416
- issuerUrl: "",
1417
- audience: ""
1418
- },
1419
- scraper: {
1420
- maxPages: 1e3,
1421
- maxDepth: 3,
1422
- maxConcurrency: 3,
1423
- jobHeartbeatMs: 15e3,
1424
- abortOnFailureRate: .5,
1425
- preserveHashes: false,
1426
- skipKnownTrackers: true,
1427
- pageTimeoutMs: 5e3,
1428
- browserTimeoutMs: 3e4,
1429
- htmlExtractor: "cheerio",
1430
- fetcher: {
1431
- maxRetries: 3,
1432
- baseDelayMs: 1e3,
1433
- timeoutMs: 3e4,
1434
- maxCacheItems: 200,
1435
- maxCacheItemSizeBytes: 500 * 1024
1436
- },
1437
- document: { maxSize: 10 * 1024 * 1024 },
1438
- security: {
1439
- network: {
1440
- mode: "open",
1441
- allowPrivateNetworks: false,
1442
- allowedHosts: [],
1443
- allowedCidrs: [],
1444
- allowInvalidTls: false
1445
- },
1446
- fileAccess: {
1447
- mode: "allowedRoots",
1448
- allowedRoots: ["$DOCUMENTS"],
1449
- followSymlinks: false,
1450
- includeHidden: false
1451
- }
1452
- }
1453
- },
1454
- splitter: {
1455
- minChunkSize: 500,
1456
- preferredChunkSize: 1500,
1457
- maxChunkSize: 5e3,
1458
- treeSitterSizeLimit: 3e4,
1459
- json: {
1460
- maxNestingDepth: 5,
1461
- maxChunks: 1e3
1462
- }
1463
- },
1464
- embeddings: {
1465
- batchSize: 100,
1466
- batchChars: 5e4,
1467
- requestTimeoutMs: 3e4,
1468
- initTimeoutMs: 3e4,
1469
- vectorDimension: 1536
1470
- },
1471
- db: {
1472
- migrationMaxRetries: 5,
1473
- migrationRetryDelayMs: 300
1474
- },
1475
- search: {
1476
- overfetchFactor: 2,
1477
- weightVec: 1,
1478
- weightFts: 1,
1479
- vectorMultiplier: 10
1480
- },
1481
- sandbox: { defaultTimeoutMs: 5e3 },
1482
- assembly: {
1483
- maxParentChainDepth: 10,
1484
- childLimit: 3,
1485
- precedingSiblingsLimit: 1,
1486
- subsequentSiblingsLimit: 2,
1487
- maxChunkDistance: 3
1488
- }
1489
788
  };
1490
- var AppConfigSchema = z.object({
1491
- app: z.object({
1492
- storePath: z.string().default(DEFAULT_CONFIG.app.storePath),
1493
- telemetryEnabled: envBoolean.default(DEFAULT_CONFIG.app.telemetryEnabled),
1494
- readOnly: envBoolean.default(DEFAULT_CONFIG.app.readOnly),
1495
- embeddingModel: z.string().default(DEFAULT_CONFIG.app.embeddingModel)
1496
- }).default(DEFAULT_CONFIG.app),
1497
- server: z.object({
1498
- name: z.preprocess(blankToUndefined, z.string().default(DEFAULT_CONFIG.server.name)),
1499
- title: z.preprocess(blankToUndefined, z.string().optional()),
1500
- instructions: z.preprocess(blankToUndefined, z.string().optional()),
1501
- instructionsFile: z.preprocess(blankToUndefined, z.string().optional()),
1502
- protocol: z.string().default(DEFAULT_CONFIG.server.protocol),
1503
- host: z.string().default(DEFAULT_CONFIG.server.host),
1504
- publicUrl: publicUrlSchema.optional(),
1505
- publicOrigin: publicOriginSchema.optional(),
1506
- allowedOrigins: allowedOriginsSchema.default(DEFAULT_CONFIG.server.allowedOrigins),
1507
- ports: z.object({
1508
- default: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.default),
1509
- worker: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.worker),
1510
- mcp: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.mcp),
1511
- web: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.web)
1512
- }).default(DEFAULT_CONFIG.server.ports),
1513
- heartbeatMs: z.coerce.number().int().default(DEFAULT_CONFIG.server.heartbeatMs)
1514
- }).default({
1515
- name: DEFAULT_CONFIG.server.name,
1516
- protocol: DEFAULT_CONFIG.server.protocol,
1517
- host: DEFAULT_CONFIG.server.host,
1518
- allowedOrigins: DEFAULT_CONFIG.server.allowedOrigins,
1519
- ports: DEFAULT_CONFIG.server.ports,
1520
- heartbeatMs: DEFAULT_CONFIG.server.heartbeatMs
1521
- }),
1522
- auth: z.object({
1523
- enabled: envBoolean.default(DEFAULT_CONFIG.auth.enabled),
1524
- issuerUrl: z.string().default(DEFAULT_CONFIG.auth.issuerUrl),
1525
- audience: z.string().default(DEFAULT_CONFIG.auth.audience)
1526
- }).default(DEFAULT_CONFIG.auth),
1527
- scraper: z.object({
1528
- maxPages: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxPages),
1529
- maxDepth: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxDepth),
1530
- maxConcurrency: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxConcurrency),
1531
- jobHeartbeatMs: z.coerce.number().int().positive().default(DEFAULT_CONFIG.scraper.jobHeartbeatMs),
1532
- abortOnFailureRate: z.coerce.number().min(0).max(1).default(DEFAULT_CONFIG.scraper.abortOnFailureRate),
1533
- preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),
1534
- skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
1535
- pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
1536
- browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
1537
- htmlExtractor: z.enum(["cheerio", "defuddle"]).default(DEFAULT_CONFIG.scraper.htmlExtractor),
1538
- fetcher: z.object({
1539
- maxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),
1540
- baseDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),
1541
- timeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.timeoutMs),
1542
- maxCacheItems: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItems),
1543
- maxCacheItemSizeBytes: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItemSizeBytes)
1544
- }).default(DEFAULT_CONFIG.scraper.fetcher),
1545
- document: z.object({ maxSize: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.document.maxSize) }).default(DEFAULT_CONFIG.scraper.document),
1546
- security: z.object({
1547
- network: z.object({
1548
- mode: z.enum(["open", "allowlist"]).default(DEFAULT_CONFIG.scraper.security.network.mode),
1549
- allowPrivateNetworks: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks),
1550
- allowedHosts: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedHosts),
1551
- allowedCidrs: envStringArray.default(DEFAULT_CONFIG.scraper.security.network.allowedCidrs),
1552
- allowInvalidTls: envBoolean.default(DEFAULT_CONFIG.scraper.security.network.allowInvalidTls)
1553
- }).default(DEFAULT_CONFIG.scraper.security.network),
1554
- fileAccess: z.object({
1555
- mode: z.enum([
1556
- "disabled",
1557
- "allowedRoots",
1558
- "unrestricted"
1559
- ]).default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),
1560
- allowedRoots: envStringArray.default(DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots),
1561
- followSymlinks: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks),
1562
- includeHidden: envBoolean.default(DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden)
1563
- }).default(DEFAULT_CONFIG.scraper.security.fileAccess)
1564
- }).default(DEFAULT_CONFIG.scraper.security)
1565
- }).default(DEFAULT_CONFIG.scraper),
1566
- splitter: z.object({
1567
- minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),
1568
- preferredChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.preferredChunkSize),
1569
- maxChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.maxChunkSize),
1570
- treeSitterSizeLimit: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.treeSitterSizeLimit),
1571
- json: z.object({
1572
- maxNestingDepth: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxNestingDepth),
1573
- maxChunks: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.json.maxChunks)
1574
- }).default(DEFAULT_CONFIG.splitter.json)
1575
- }).default(DEFAULT_CONFIG.splitter),
1576
- embeddings: z.object({
1577
- batchSize: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchSize),
1578
- batchChars: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchChars),
1579
- requestTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.requestTimeoutMs),
1580
- initTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.initTimeoutMs),
1581
- vectorDimension: z.coerce.number().int().min(1, "embedding dimension must be at least 1").default(DEFAULT_CONFIG.embeddings.vectorDimension)
1582
- }).default(DEFAULT_CONFIG.embeddings),
1583
- db: z.object({
1584
- migrationMaxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationMaxRetries),
1585
- migrationRetryDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.db.migrationRetryDelayMs)
1586
- }).default(DEFAULT_CONFIG.db),
1587
- search: z.object({
1588
- overfetchFactor: z.coerce.number().default(DEFAULT_CONFIG.search.overfetchFactor),
1589
- weightVec: z.coerce.number().default(DEFAULT_CONFIG.search.weightVec),
1590
- weightFts: z.coerce.number().default(DEFAULT_CONFIG.search.weightFts),
1591
- vectorMultiplier: z.coerce.number().int().default(DEFAULT_CONFIG.search.vectorMultiplier)
1592
- }).default(DEFAULT_CONFIG.search),
1593
- sandbox: z.object({ defaultTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.sandbox.defaultTimeoutMs) }).default(DEFAULT_CONFIG.sandbox),
1594
- assembly: z.object({
1595
- maxParentChainDepth: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.maxParentChainDepth),
1596
- childLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.childLimit),
1597
- precedingSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.precedingSiblingsLimit),
1598
- subsequentSiblingsLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.subsequentSiblingsLimit),
1599
- maxChunkDistance: z.coerce.number().int().min(0).default(DEFAULT_CONFIG.assembly.maxChunkDistance)
1600
- }).default(DEFAULT_CONFIG.assembly)
1601
- });
1602
- var vectorDimensionExplicit = Symbol("vectorDimensionExplicit");
1603
- var defaults = AppConfigSchema.parse({});
1604
- var configMappings = [
1605
- {
1606
- path: ["server", "protocol"],
1607
- env: ["DOCS_MCP_PROTOCOL"],
1608
- cli: "protocol"
1609
- },
1610
- {
1611
- path: ["app", "storePath"],
1612
- env: ["DOCS_MCP_STORE_PATH"],
1613
- cli: "storePath"
1614
- },
1615
- {
1616
- path: ["app", "telemetryEnabled"],
1617
- env: ["DOCS_MCP_TELEMETRY"]
1618
- },
1619
- {
1620
- path: ["app", "readOnly"],
1621
- env: ["DOCS_MCP_READ_ONLY"],
1622
- cli: "readOnly"
1623
- },
1624
- {
1625
- path: [
1626
- "server",
1627
- "ports",
1628
- "default"
1629
- ],
1630
- env: ["DOCS_MCP_PORT", "PORT"],
1631
- cli: "port"
1632
- },
1633
- {
1634
- path: [
1635
- "server",
1636
- "ports",
1637
- "worker"
1638
- ],
1639
- env: ["DOCS_MCP_PORT", "PORT"],
1640
- cli: "port"
1641
- },
1642
- {
1643
- path: [
1644
- "server",
1645
- "ports",
1646
- "mcp"
1647
- ],
1648
- env: ["DOCS_MCP_PORT", "PORT"],
1649
- cli: "port"
1650
- },
1651
- {
1652
- path: [
1653
- "server",
1654
- "ports",
1655
- "web"
1656
- ],
1657
- env: [
1658
- "DOCS_MCP_WEB_PORT",
1659
- "DOCS_MCP_PORT",
1660
- "PORT"
1661
- ],
1662
- cli: "port"
1663
- },
1664
- {
1665
- path: ["server", "host"],
1666
- env: ["DOCS_MCP_HOST", "HOST"],
1667
- cli: "host"
1668
- },
1669
- {
1670
- path: ["server", "publicUrl"],
1671
- env: ["DOCS_MCP_SERVER_PUBLIC_URL"],
1672
- cli: "publicUrl"
1673
- },
1674
- {
1675
- path: ["server", "publicOrigin"],
1676
- env: ["DOCS_MCP_SERVER_PUBLIC_ORIGIN"],
1677
- cli: "publicOrigin"
1678
- },
1679
- {
1680
- path: ["server", "name"],
1681
- env: ["DOCS_MCP_SERVER_NAME"],
1682
- cli: "serverName"
1683
- },
1684
- {
1685
- path: ["server", "title"],
1686
- env: ["DOCS_MCP_SERVER_TITLE"],
1687
- cli: "serverTitle"
1688
- },
1689
- {
1690
- path: ["server", "instructions"],
1691
- env: ["DOCS_MCP_SERVER_INSTRUCTIONS"],
1692
- cli: "serverInstructions"
1693
- },
1694
- {
1695
- path: ["server", "instructionsFile"],
1696
- env: ["DOCS_MCP_SERVER_INSTRUCTIONS_FILE"],
1697
- cli: "serverInstructionsFile"
1698
- },
1699
- {
1700
- path: ["app", "embeddingModel"],
1701
- env: ["DOCS_MCP_EMBEDDING_MODEL"],
1702
- cli: "embeddingModel"
1703
- },
1704
- {
1705
- path: ["auth", "enabled"],
1706
- env: ["DOCS_MCP_AUTH_ENABLED"],
1707
- cli: "authEnabled"
1708
- },
1709
- {
1710
- path: ["auth", "issuerUrl"],
1711
- env: ["DOCS_MCP_AUTH_ISSUER_URL"],
1712
- cli: "authIssuerUrl"
1713
- },
1714
- {
1715
- path: ["auth", "audience"],
1716
- env: ["DOCS_MCP_AUTH_AUDIENCE"],
1717
- cli: "authAudience"
1718
- }
1719
- ];
1720
- var systemPaths = envPaths("docs-mcp-server", { suffix: "" });
1721
- function loadConfig(cliArgs = {}, options = {}) {
1722
- const explicitPath = cliArgs.config || options.configPath || process.env.DOCS_MCP_CONFIG;
1723
- let configPath;
1724
- let isReadOnlyConfig = false;
1725
- if (explicitPath) {
1726
- configPath = explicitPath;
1727
- isReadOnlyConfig = true;
1728
- } else {
1729
- configPath = path.join(systemPaths.config, "config.yaml");
1730
- isReadOnlyConfig = false;
1731
- }
1732
- logger.debug(`Using config file: ${configPath}`);
1733
- const fileConfig = loadConfigFile(configPath) || {};
1734
- const hasManagedVectorDimensionOmissionMarker = hasManagedConfigVectorDimensionOmissionMarker(configPath);
1735
- const baseConfig = deepMerge(defaults, fileConfig);
1736
- const envConfig = mapEnvToConfig();
1737
- const cliConfig = mapCliToConfig(cliArgs);
1738
- const vectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
1739
- const fileVectorDimensionWasExplicit = wasVectorDimensionExplicit(fileConfig, {}, {}, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker);
1740
- if (!isReadOnlyConfig) try {
1741
- saveConfigFile(configPath, baseConfig, {
1742
- managedDefaultConfig: true,
1743
- omitVectorDimension: !fileVectorDimensionWasExplicit
1744
- });
1745
- } catch (error) {
1746
- logger.warn(`Failed to save config file to ${configPath}: ${error}`);
1747
- }
1748
- const mergedInput = deepMerge(baseConfig, deepMerge(envConfig, cliConfig));
1749
- if (!getAtPath(mergedInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(mergedInput, ["app", "embeddingModel"], "text-embedding-3-small");
1750
- const parseResult = AppConfigSchema.safeParse(mergedInput);
1751
- if (parseResult.success) return markVectorDimensionSource(parseResult.data, vectorDimensionWasExplicit);
1752
- for (const setting of [
1753
- "publicUrl",
1754
- "publicOrigin",
1755
- "allowedOrigins"
1756
- ]) if (hasParseIssueAtPath(parseResult.error, ["server", setting])) throw new Error(`Invalid configuration for server.${setting}: ${parseResult.error.message}`);
1757
- if (!isReadOnlyConfig && fs.existsSync(configPath)) {
1758
- const quarantinePath = `${configPath}.invalid-${Date.now()}`;
1759
- try {
1760
- fs.renameSync(configPath, quarantinePath);
1761
- logger.warn(`Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`);
1762
- } catch (renameError) {
1763
- logger.warn(`Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`);
1764
- }
1765
- } else logger.warn(`Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`);
1766
- const fallbackInput = deepMerge(defaults, deepMerge(envConfig, cliConfig));
1767
- if (!getAtPath(fallbackInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
1768
- const fallbackConfig = markVectorDimensionSource(AppConfigSchema.parse(fallbackInput), wasVectorDimensionExplicit({}, envConfig, cliConfig, false, false));
1769
- if (!isReadOnlyConfig) try {
1770
- saveConfigFile(configPath, fallbackConfig, {
1771
- managedDefaultConfig: true,
1772
- omitVectorDimension: true
1773
- });
1774
- } catch (error) {
1775
- logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
1776
- }
1777
- return fallbackConfig;
1778
- }
1779
- function hasManagedConfigVectorDimensionOmissionMarker(filePath) {
1780
- if (!fs.existsSync(filePath)) return false;
1781
- try {
1782
- return fs.readFileSync(filePath, "utf8").includes(managedConfigVectorDimensionOmissionMarker);
1783
- } catch {
1784
- return false;
1785
- }
1786
- }
1787
- /**
1788
- * Returns true when the embedding vector dimension was set by user config,
1789
- * environment, or CLI rather than coming from generated defaults.
1790
- */
1791
- function isVectorDimensionExplicit(config) {
1792
- return config.embeddings[vectorDimensionExplicit] === true;
1793
- }
1794
- /**
1795
- * Marks an AppConfig as having an explicit or default-derived vector dimension.
1796
- */
1797
- function markVectorDimensionSource(config, explicit) {
1798
- Object.defineProperty(config.embeddings, vectorDimensionExplicit, {
1799
- value: explicit,
1800
- enumerable: false,
1801
- configurable: true
1802
- });
1803
- return config;
1804
- }
1805
- function loadConfigFile(filePath) {
1806
- if (!fs.existsSync(filePath)) return null;
1807
- try {
1808
- const content = fs.readFileSync(filePath, "utf8");
1809
- if (filePath.endsWith(".json")) return JSON.parse(content);
1810
- return yaml.parse(content) || {};
1811
- } catch (error) {
1812
- logger.warn(`Failed to parse config file ${filePath}: ${error}`);
1813
- return null;
1814
- }
1815
- }
1816
- function wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker) {
1817
- if (getAtPath(envConfig, vectorDimensionPath) !== void 0 || getAtPath(cliConfig, vectorDimensionPath) !== void 0) return true;
1818
- const fileValue = getAtPath(fileConfig, vectorDimensionPath);
1819
- if (fileValue === void 0) return false;
1820
- if (isReadOnlyConfig || fileValue !== DEFAULT_CONFIG.embeddings.vectorDimension || hasManagedVectorDimensionOmissionMarker) return true;
1821
- return !looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig);
1822
- }
1823
- function looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig) {
1824
- const embeddings = fileConfig.embeddings;
1825
- if (typeof embeddings !== "object" || embeddings === null || Array.isArray(embeddings)) return false;
1826
- return Object.keys(DEFAULT_CONFIG.embeddings).every((key) => Object.hasOwn(embeddings, key));
1827
- }
1828
- function saveConfigFile(filePath, config, options = {}) {
1829
- const dir = path.dirname(filePath);
1830
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
1831
- const configToWrite = cloneConfigValue(config);
1832
- if (options.omitVectorDimension) unsetAtPath(configToWrite, vectorDimensionPath);
1833
- let content;
1834
- if (filePath.endsWith(".json")) content = JSON.stringify(configToWrite, null, 2);
1835
- else {
1836
- content = yaml.stringify(configToWrite);
1837
- if (options.managedDefaultConfig) content = `${managedConfigHeader}${content}`;
1838
- }
1839
- logger.debug(`Updating config file at ${filePath}`);
1840
- fs.writeFileSync(filePath, content, "utf8");
1841
- }
1842
- function mapEnvToConfig() {
1843
- const config = {};
1844
- for (const mapping of configMappings) if (mapping.env) {
1845
- for (const envVar of mapping.env) if (process.env[envVar] !== void 0) {
1846
- setAtPath(config, mapping.path, normalizeEnvValue(process.env[envVar]));
1847
- break;
1848
- }
1849
- }
1850
- for (const pathArr of ALL_CONFIG_LEAF_PATHS) {
1851
- const envVar = pathToEnvVar(pathArr);
1852
- if (process.env[envVar] !== void 0) setAtPath(config, pathArr, normalizeEnvValue(process.env[envVar]));
1853
- }
1854
- return config;
1855
- }
1856
- function mapCliToConfig(args) {
1857
- const config = {};
1858
- for (const mapping of configMappings) if (mapping.cli && args[mapping.cli] !== void 0) setAtPath(config, mapping.path, args[mapping.cli]);
1859
- return config;
1860
- }
1861
- /**
1862
- * Convert camelCase to UPPER_SNAKE_CASE
1863
- * Example: "maxSize" → "MAX_SIZE", "maxNestingDepth" → "MAX_NESTING_DEPTH"
1864
- */
1865
- function camelToUpperSnake(str) {
1866
- return str.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
1867
- }
1868
- /**
1869
- * Convert config path to environment variable name
1870
- * Example: ["scraper", "document", "maxSize"] → "DOCS_MCP_SCRAPER_DOCUMENT_MAX_SIZE"
1871
- */
1872
- function pathToEnvVar(pathArr) {
1873
- return `DOCS_MCP_${pathArr.map(camelToUpperSnake).join("_")}`;
1874
- }
1875
- /**
1876
- * Recursively collect all leaf paths from a config object
1877
- */
1878
- function collectLeafPaths(obj, prefix = []) {
1879
- const paths = [];
1880
- for (const [key, value] of Object.entries(obj)) {
1881
- const currentPath = [...prefix, key];
1882
- if (value !== null && typeof value === "object" && !Array.isArray(value)) paths.push(...collectLeafPaths(value, currentPath));
1883
- else paths.push(currentPath);
1884
- }
1885
- return paths;
1886
- }
1887
- var ALL_CONFIG_LEAF_PATHS = collectLeafPaths(DEFAULT_CONFIG);
1888
- function setAtPath(obj, pathArr, value) {
1889
- let current = obj;
1890
- for (let i = 0; i < pathArr.length - 1; i++) {
1891
- const key = pathArr[i];
1892
- if (current[key] === void 0 || typeof current[key] !== "object" || current[key] === null) current[key] = {};
1893
- current = current[key];
1894
- }
1895
- current[pathArr[pathArr.length - 1]] = value;
1896
- }
1897
- function getAtPath(obj, pathArr) {
1898
- let current = obj;
1899
- for (const key of pathArr) {
1900
- if (typeof current !== "object" || current === null) return void 0;
1901
- current = current[key];
1902
- }
1903
- return current;
1904
- }
1905
- function unsetAtPath(obj, pathArr) {
1906
- let current = obj;
1907
- for (const key of pathArr.slice(0, -1)) {
1908
- if (typeof current !== "object" || current === null) return;
1909
- current = current[key];
1910
- }
1911
- if (typeof current === "object" && current !== null) delete current[pathArr[pathArr.length - 1]];
1912
- }
1913
- function cloneConfigValue(value) {
1914
- if (Array.isArray(value)) return value.map((item) => cloneConfigValue(item));
1915
- if (typeof value === "object" && value !== null) {
1916
- const output = {};
1917
- for (const [key, child] of Object.entries(value)) output[key] = cloneConfigValue(child);
1918
- return output;
1919
- }
1920
- return value;
1921
- }
1922
- function hasPath(obj, pathArr) {
1923
- let current = obj;
1924
- for (const key of pathArr) {
1925
- if (typeof current !== "object" || current === null || !Object.hasOwn(current, key)) return false;
1926
- current = current[key];
1927
- }
1928
- return true;
1929
- }
1930
- function hasParseIssueAtPath(error, pathArr) {
1931
- return error.issues.some((issue) => issue.path.join(".") === pathArr.join("."));
1932
- }
1933
- function deepMerge(target, source) {
1934
- if (typeof target !== "object" || target === null) return source;
1935
- if (typeof source !== "object" || source === null) return target;
1936
- if (Array.isArray(target) || Array.isArray(source)) return source;
1937
- const t = target;
1938
- const s = source;
1939
- const output = { ...t };
1940
- for (const key of Object.keys(s)) {
1941
- const sValue = s[key];
1942
- const tValue = t[key];
1943
- 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);
1944
- else output[key] = sValue;
1945
- }
1946
- return output;
1947
- }
1948
- /**
1949
- * Check if a config path is valid by verifying it exists in DEFAULT_CONFIG
1950
- */
1951
- function isValidConfigPath(path) {
1952
- return hasPath(DEFAULT_CONFIG, path.split("."));
1953
- }
1954
- /**
1955
- * Get a config value by dot-separated path
1956
- */
1957
- function getConfigValue(config, path) {
1958
- return getAtPath(config, path.split("."));
1959
- }
1960
- /**
1961
- * Parse a string value to the appropriate type (number, boolean, or string)
1962
- */
1963
- function parseConfigValue(value) {
1964
- const num = Number(value);
1965
- if (!Number.isNaN(num) && value.trim() !== "") return num;
1966
- const lower = value.toLowerCase();
1967
- if (lower === "true") return true;
1968
- if (lower === "false") return false;
1969
- return value;
1970
- }
1971
- /**
1972
- * Set a config value and persist to file.
1973
- * Returns the path to the config file that was updated.
1974
- * Validates the updated config against the schema before saving.
1975
- */
1976
- function setConfigValue(path, value) {
1977
- const configPath = getDefaultConfigPath();
1978
- const fileConfig = loadConfigFile(configPath) || {};
1979
- const pathArr = path.split(".");
1980
- const parsedValue = parseConfigValue(value);
1981
- const updatedConfig = JSON.parse(JSON.stringify(fileConfig));
1982
- setAtPath(updatedConfig, pathArr, parsedValue);
1983
- try {
1984
- AppConfigSchema.parse(updatedConfig);
1985
- } catch (err) {
1986
- const errorMsg = err instanceof Error ? err.message : String(err);
1987
- throw new Error(`Invalid config value for "${path}": ${errorMsg}`);
1988
- }
1989
- saveConfigFile(configPath, updatedConfig);
1990
- return configPath;
1991
- }
1992
- /**
1993
- * Get the default system config path
1994
- */
1995
- function getDefaultConfigPath() {
1996
- return path.join(systemPaths.config, "config.yaml");
1997
- }
1998
- //#endregion
1999
- //#region src/events/RemoteEventProxy.ts
789
+ // src/events/RemoteEventProxy.ts
2000
790
  /** First delay before subscribing again after the subscription itself ended. */
2001
791
  var RESUBSCRIBE_BASE_DELAY_MS = 1e3;
2002
792
  /** Longest delay between attempts to subscribe again. */
@@ -2138,8 +928,7 @@ var RemoteEventProxy = class {
2138
928
  this.wasLive = true;
2139
929
  }
2140
930
  };
2141
- //#endregion
2142
- //#region src/pipeline/trpc/interfaces.ts
931
+ // src/pipeline/trpc/interfaces.ts
2143
932
  /**
2144
933
  * The tRPC codes the pipeline router gives enqueue errors a caller can act on:
2145
934
  * an existing target (409), an invalid library name (400) and an unknown
@@ -2151,8 +940,7 @@ var RELAYED_ENQUEUE_ERROR_CODES = [
2151
940
  "BAD_REQUEST",
2152
941
  "NOT_FOUND"
2153
942
  ];
2154
- //#endregion
2155
- //#region src/pipeline/PipelineClient.ts
943
+ // src/pipeline/PipelineClient.ts
2156
944
  /**
2157
945
  * Pipeline backed by a remote worker: every operation calls the worker's
2158
946
  * application API through a shared {@link ApiClient}.
@@ -2320,9 +1108,7 @@ var PipelineClient = class {
2320
1108
  case PipelineJobStatus.CANCELLED:
2321
1109
  finish();
2322
1110
  break;
2323
- case PipelineJobStatus.FAILED:
2324
- finish(new Error(job.error?.message || job.errorMessage || `Job ${jobId} failed`));
2325
- break;
1111
+ case PipelineJobStatus.FAILED: finish(new Error(job.error?.message || job.errorMessage || `Job ${jobId} failed`));
2326
1112
  }
2327
1113
  };
2328
1114
  const unsubscribe = this.eventBus.on(EventType.JOB_STATUS_CHANGE, (job) => {
@@ -2371,8 +1157,7 @@ var PipelineClient = class {
2371
1157
  });
2372
1158
  }
2373
1159
  };
2374
- //#endregion
2375
- //#region src/utils/errors.ts
1160
+ // src/utils/errors.ts
2376
1161
  var ScraperError = class extends Error {
2377
1162
  isRetryable;
2378
1163
  cause;
@@ -2434,8 +1219,28 @@ var AccessPolicyError = class extends ScraperError {
2434
1219
  super(message, false);
2435
1220
  }
2436
1221
  };
2437
- //#endregion
2438
- //#region src/utils/mimeTypeUtils.ts
1222
+ /**
1223
+ * Returns the first line of a thrown value's message.
1224
+ *
1225
+ * Playwright's messages run on with call logs and install hints; the first line
1226
+ * names the failure.
1227
+ *
1228
+ * @param error The thrown value.
1229
+ * @returns The first line, or the whole message when that line is empty.
1230
+ */
1231
+ function firstErrorLine(error) {
1232
+ const message = error instanceof Error ? error.message : String(error);
1233
+ return message.split("\n")[0] || message;
1234
+ }
1235
+ /** A page that had to be rendered in the browser could not be. */
1236
+ var RenderError = class extends ScraperError {
1237
+ url;
1238
+ constructor(url, cause) {
1239
+ super(`Playwright could not render ${url}: ${firstErrorLine(cause)}`, false, cause);
1240
+ this.url = url;
1241
+ }
1242
+ };
1243
+ // src/utils/mimeTypeUtils.ts
2439
1244
  /**
2440
1245
  * Extension-to-MIME overrides for types the `mime` package gets wrong or does
2441
1246
  * not know. See openspec/changes/refactor-mime-type-detection/design.md.
@@ -2879,8 +1684,7 @@ var MimeTypeUtils = class MimeTypeUtils {
2879
1684
  }[mimeType] || "";
2880
1685
  }
2881
1686
  };
2882
- //#endregion
2883
- //#region src/utils/url.ts
1687
+ // src/utils/url.ts
2884
1688
  var defaultNormalizerOptions = {
2885
1689
  removeHash: true,
2886
1690
  removeTrailingSlash: true,
@@ -2967,8 +1771,7 @@ function stripMarkdownExtension(url) {
2967
1771
  parsed.pathname = stripped;
2968
1772
  return parsed.toString();
2969
1773
  }
2970
- //#endregion
2971
- //#region src/scraper/utils/defaultPatterns.ts
1774
+ // src/scraper/utils/defaultPatterns.ts
2972
1775
  /**
2973
1776
  * Default exclusion patterns for documentation scraping.
2974
1777
  * These patterns are always applied unless user explicitly provides their own exclude patterns.
@@ -3069,8 +1872,7 @@ function getEffectiveExclusionPatterns(userPatterns) {
3069
1872
  if (userPatterns !== void 0) return userPatterns;
3070
1873
  return DEFAULT_EXCLUSION_PATTERNS;
3071
1874
  }
3072
- //#endregion
3073
- //#region src/scraper/utils/patternMatcher.ts
1875
+ // src/scraper/utils/patternMatcher.ts
3074
1876
  /**
3075
1877
  * Utility functions for pattern matching (glob and regex) for URL filtering.
3076
1878
  * Supports auto-detection and conversion of glob patterns to RegExp.
@@ -3200,8 +2002,7 @@ function shouldIncludeUrl(url, includePatterns, excludePatterns) {
3200
2002
  if (!includePatterns || includePatterns.length === 0) return true;
3201
2003
  return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
3202
2004
  }
3203
- //#endregion
3204
- //#region src/utils/accessPolicy.ts
2005
+ // src/utils/accessPolicy.ts
3205
2006
  var SPECIAL_USE_IPV4_CIDRS = [
3206
2007
  "0.0.0.0/8",
3207
2008
  "10.0.0.0/8",
@@ -3575,8 +2376,7 @@ function hasHiddenSegmentBelowRoot(targetPath, matchedRoot) {
3575
2376
  function hasHiddenArchiveSegment(archivePath) {
3576
2377
  return archivePath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
3577
2378
  }
3578
- //#endregion
3579
- //#region src/scraper/fetcher/challenge.ts
2379
+ // src/scraper/fetcher/challenge.ts
3580
2380
  /**
3581
2381
  * Recognition of bot-protection challenge pages that a site serves in place of
3582
2382
  * the requested document, with a success status.
@@ -3586,7 +2386,7 @@ function hasHiddenArchiveSegment(archivePath) {
3586
2386
  * carry their markers in the head, so a documentation page that merely
3587
2387
  * mentions them further down is not mistaken for one.
3588
2388
  */
3589
- var SCAN_LIMIT = 64 * 1024;
2389
+ var SCAN_LIMIT = 65536;
3590
2390
  /** The title of Fastly's client challenge page. */
3591
2391
  var FASTLY_CHALLENGE_TITLE = /<title>\s*Client Challenge\s*<\/title>/i;
3592
2392
  /** The path prefix Fastly serves the challenge's scripts and assets from. */
@@ -3607,8 +2407,7 @@ function detectChallengePage(html) {
3607
2407
  if (FASTLY_CHALLENGE_TITLE.test(head) && head.includes(FASTLY_CHALLENGE_ASSET_PATH)) return "fastly";
3608
2408
  return null;
3609
2409
  }
3610
- //#endregion
3611
- //#region src/scraper/fetcher/FingerprintGenerator.ts
2410
+ // src/scraper/fetcher/FingerprintGenerator.ts
3612
2411
  /**
3613
2412
  * Generates realistic browser-like HTTP headers to help avoid bot detection.
3614
2413
  * Uses the `header-generator` library for header generation.
@@ -3653,8 +2452,7 @@ var FingerprintGenerator = class {
3653
2452
  return this.headerGenerator.getHeaders();
3654
2453
  }
3655
2454
  };
3656
- //#endregion
3657
- //#region src/scraper/fetcher/headers.ts
2455
+ // src/scraper/fetcher/headers.ts
3658
2456
  var MARKDOWN_PREFERRED_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8";
3659
2457
  /**
3660
2458
  * Reads a header by name, ignoring case.
@@ -3685,9 +2483,10 @@ function withMarkdownPreferredAccept(headers, callerHeaders = {}) {
3685
2483
  };
3686
2484
  }
3687
2485
  /**
3688
- * Connection-level headers that Chromium refuses to take from a page. A
3689
- * navigation that carries one fails with `net::ERR_INVALID_ARGUMENT`.
3690
- * Generated Firefox fingerprints include `TE: trailers`.
2486
+ * Connection-level headers, which the client that opens a connection sets for
2487
+ * itself. Chromium refuses to take them from a page: a navigation that carries
2488
+ * one fails with `net::ERR_INVALID_ARGUMENT`. Generated Firefox fingerprints
2489
+ * include `TE: trailers`, and a few include `Connection: keep-alive`.
3691
2490
  */
3692
2491
  var CONNECTION_HEADERS = /* @__PURE__ */ new Set([
3693
2492
  "connection",
@@ -3702,6 +2501,20 @@ var CONNECTION_HEADERS = /* @__PURE__ */ new Set([
3702
2501
  "upgrade"
3703
2502
  ]);
3704
2503
  /**
2504
+ * Returns headers without the connection-level ones.
2505
+ *
2506
+ * A generated fingerprint copies a browser's headers, connection-level ones
2507
+ * included. The HTTP client that sends the request manages its own connection
2508
+ * and sets these itself: a copied `Connection: keep-alive` asks the server to
2509
+ * hold open a connection the client may never reuse.
2510
+ *
2511
+ * @param headers Request headers, such as a generated fingerprint.
2512
+ * @returns The headers minus any connection-level entry, in any letter case.
2513
+ */
2514
+ function withoutConnectionHeaders(headers) {
2515
+ return Object.fromEntries(Object.entries(headers).filter(([header]) => !CONNECTION_HEADERS.has(header.toLowerCase())));
2516
+ }
2517
+ /**
3705
2518
  * Returns headers without the ones Chromium sets for itself.
3706
2519
  *
3707
2520
  * A browser sets the `Sec-Fetch-*` family with values that fit each request: a
@@ -3717,13 +2530,9 @@ var CONNECTION_HEADERS = /* @__PURE__ */ new Set([
3717
2530
  * any letter case.
3718
2531
  */
3719
2532
  function withoutBrowserManagedHeaders(headers) {
3720
- return Object.fromEntries(Object.entries(headers).filter(([header]) => {
3721
- const name = header.toLowerCase();
3722
- return !name.startsWith("sec-fetch-") && !CONNECTION_HEADERS.has(name);
3723
- }));
2533
+ return Object.fromEntries(Object.entries(withoutConnectionHeaders(headers)).filter(([header]) => !header.toLowerCase().startsWith("sec-fetch-")));
3724
2534
  }
3725
- //#endregion
3726
- //#region src/utils/timeout.ts
2535
+ // src/utils/timeout.ts
3727
2536
  /**
3728
2537
  * Waits for an operation, rejecting if it takes longer than the given time.
3729
2538
  * The operation itself keeps running; only the wait is bounded.
@@ -3745,8 +2554,7 @@ async function withTimeout(operation, timeoutMs, description) {
3745
2554
  if (timeout) clearTimeout(timeout);
3746
2555
  }
3747
2556
  }
3748
- //#endregion
3749
- //#region src/scraper/fetcher/ManagedBrowser.ts
2557
+ // src/scraper/fetcher/ManagedBrowser.ts
3750
2558
  /**
3751
2559
  * Process IDs of the browsers `ManagedBrowser.launch()` started. Playwright's
3752
2560
  * `Browser` does not expose its process, so the ID is read over CDP at launch,
@@ -3964,8 +2772,7 @@ var ManagedBrowser = class ManagedBrowser {
3964
2772
  }
3965
2773
  }
3966
2774
  };
3967
- //#endregion
3968
- //#region src/scraper/fetcher/types.ts
2775
+ // src/scraper/fetcher/types.ts
3969
2776
  /**
3970
2777
  * Semantic status of a fetch operation, abstracting HTTP status codes
3971
2778
  * into meaningful states for content processing.
@@ -3997,8 +2804,7 @@ var FetchStatus = /* @__PURE__ */ function(FetchStatus) {
3997
2804
  FetchStatus["SKIPPED"] = "skipped";
3998
2805
  return FetchStatus;
3999
2806
  }({});
4000
- //#endregion
4001
- //#region src/scraper/fetcher/BrowserFetcher.ts
2807
+ // src/scraper/fetcher/BrowserFetcher.ts
4002
2808
  /**
4003
2809
  * Maximum redirects to follow via the request API. Matches Playwright's own
4004
2810
  * default (20) — redirects are followed manually only so every hop can be
@@ -4112,7 +2918,7 @@ var BrowserFetcher = class {
4112
2918
  } catch (error) {
4113
2919
  const message = error instanceof Error ? error.message : String(error);
4114
2920
  if (/ERR_BLOCKED_BY_CLIENT/.test(message)) throw new AccessPolicyError(`Security policy blocked network access to ${blockedNavigation ?? source}`);
4115
- if (!/frame was detached/i.test(message) && /ERR_INVALID_ARGUMENT|ERR_ABORTED|Download is starting/i.test(message)) return await this.fetchViaRequest(page, source, options, timeout, requestHeaders);
2921
+ if (!(/frame was detached/i.test(message) || !this.managedBrowser.isCurrent(browser)) && /ERR_INVALID_ARGUMENT|ERR_ABORTED|Download is starting/i.test(message)) return await this.fetchViaRequest(page, source, options, timeout, requestHeaders);
4116
2922
  throw error;
4117
2923
  }
4118
2924
  await page.waitForLoadState("networkidle", { timeout: Math.min(timeout, 5e3) }).catch(() => void 0);
@@ -4249,8 +3055,7 @@ var BrowserFetcher = class {
4249
3055
  await this.managedBrowser.close();
4250
3056
  }
4251
3057
  };
4252
- //#endregion
4253
- //#region src/scraper/fetcher/FileFetcher.ts
3058
+ // src/scraper/fetcher/FileFetcher.ts
4254
3059
  /**
4255
3060
  * Fetches content from local file system.
4256
3061
  */
@@ -4299,8 +3104,7 @@ var FileFetcher = class {
4299
3104
  }
4300
3105
  }
4301
3106
  };
4302
- //#endregion
4303
- //#region src/pipeline/errors.ts
3107
+ // src/pipeline/errors.ts
4304
3108
  var PipelineError = class extends Error {
4305
3109
  cause;
4306
3110
  constructor(message, cause) {
@@ -4319,8 +3123,7 @@ var CancellationError = class extends PipelineError {
4319
3123
  super(message);
4320
3124
  }
4321
3125
  };
4322
- //#endregion
4323
- //#region src/scraper/fetcher/HttpFetcher.ts
3126
+ // src/scraper/fetcher/HttpFetcher.ts
4324
3127
  /**
4325
3128
  * Maximum number of redirects to follow in a single fetch. Matches the legacy
4326
3129
  * axios default; kept here as a named constant because redirects are now
@@ -4394,7 +3197,7 @@ var HttpFetcher = class {
4394
3197
  let redirectCount = 0;
4395
3198
  while (true) {
4396
3199
  const headers = withMarkdownPreferredAccept({
4397
- ...this.fingerprintGenerator.generateHeaders(),
3200
+ ...withoutConnectionHeaders(this.fingerprintGenerator.generateHeaders()),
4398
3201
  ...options?.headers
4399
3202
  }, options?.headers);
4400
3203
  if (options?.etag) {
@@ -4556,8 +3359,7 @@ async function readStreamToBuffer(stream, signal) {
4556
3359
  }
4557
3360
  return Buffer.concat(chunks);
4558
3361
  }
4559
- //#endregion
4560
- //#region src/scraper/fetcher/AutoDetectFetcher.ts
3362
+ // src/scraper/fetcher/AutoDetectFetcher.ts
4561
3363
  /** Statuses anti-bot layers return that a real browser can often get past. */
4562
3364
  var ANTI_BOT_STATUS_CODES = /* @__PURE__ */ new Set([403, 429]);
4563
3365
  /**
@@ -4629,8 +3431,7 @@ var AutoDetectFetcher = class AutoDetectFetcher {
4629
3431
  await Promise.allSettled([this.browserFetcher.close()]);
4630
3432
  }
4631
3433
  };
4632
- //#endregion
4633
- //#region src/scraper/types.ts
3434
+ // src/scraper/types.ts
4634
3435
  /**
4635
3436
  * Enum defining the available HTML processing strategies.
4636
3437
  */
@@ -4672,8 +3473,7 @@ var PageOutcome = /* @__PURE__ */ function(PageOutcome) {
4672
3473
  PageOutcome["Failed"] = "failed";
4673
3474
  return PageOutcome;
4674
3475
  }({});
4675
- //#endregion
4676
- //#region src/scraper/utils/llmsTxtParser.ts
3476
+ // src/scraper/utils/llmsTxtParser.ts
4677
3477
  var emptyLlmsTxtResult = () => ({
4678
3478
  sections: [],
4679
3479
  links: []
@@ -4781,8 +3581,7 @@ function parseLlmsTxt(content) {
4781
3581
  if (result.links.length === 0) return emptyLlmsTxtResult();
4782
3582
  return result;
4783
3583
  }
4784
- //#endregion
4785
- //#region src/scraper/utils/scope.ts
3584
+ // src/scraper/utils/scope.ts
4786
3585
  var INDEX_FILE_PATTERN = /^index(\.[a-z0-9]+)?$/i;
4787
3586
  /**
4788
3587
  * Extensions that mark a URL's last segment as a page rather than a directory.
@@ -4876,8 +3675,7 @@ function normalizeHost(host, hostname) {
4876
3675
  if (stripped === hostname) return host;
4877
3676
  return host.replace(hostname, stripped);
4878
3677
  }
4879
- //#endregion
4880
- //#region src/scraper/strategies/BaseScraperStrategy.ts
3678
+ // src/scraper/strategies/BaseScraperStrategy.ts
4881
3679
  var FailureThresholdExceededError = class extends ScraperError {};
4882
3680
  var BaseScraperStrategy = class BaseScraperStrategy {
4883
3681
  static FAILURE_RATE_MIN_SAMPLE = 10;
@@ -4977,6 +3775,16 @@ var BaseScraperStrategy = class BaseScraperStrategy {
4977
3775
  };
4978
3776
  }
4979
3777
  /**
3778
+ * Returns the URL that `scope` is measured from: the root after any redirect
3779
+ * on its first fetch, or else the URL the scrape started from.
3780
+ *
3781
+ * @param options Scraper options naming the URL the scrape started from.
3782
+ * @returns The scope base URL.
3783
+ */
3784
+ getScopeBaseUrl(options) {
3785
+ return this.canonicalBaseUrl ?? new URL$1(options.url);
3786
+ }
3787
+ /**
4980
3788
  * Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.
4981
3789
  * Scope is checked first, then patterns.
4982
3790
  *
@@ -4996,7 +3804,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
4996
3804
  if (!(url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots))) {
4997
3805
  const scope = options.scope ?? "subpages";
4998
3806
  try {
4999
- if (!isInScope(this.canonicalBaseUrl ?? new URL$1(options.url), new URL$1(url), scope)) return false;
3807
+ if (!isInScope(this.getScopeBaseUrl(options), new URL$1(url), scope)) return false;
5000
3808
  } catch {
5001
3809
  return false;
5002
3810
  }
@@ -5078,27 +3886,32 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5078
3886
  this.pagesIndexed++;
5079
3887
  } else this.retuneEffectiveTotal(options);
5080
3888
  logger.info(`🌐 Scraping page ${pagesScraped}/${this.effectiveTotal} (depth ${item.depth}/${maxDepth}): ${item.url}`);
5081
- await progressCallback({
5082
- pagesScraped,
5083
- totalPages: this.effectiveTotal,
5084
- totalDiscovered: this.totalDiscovered,
5085
- pagesIndexed: this.pagesIndexed,
5086
- currentUrl: item.url,
5087
- depth: item.depth,
5088
- maxDepth,
5089
- outcome,
5090
- result: null,
5091
- pageId: item.pageId,
5092
- ...extra,
5093
- ...extra.result ? { result: {
5094
- ...extra.result,
5095
- isAdditionalRepresentation: alreadyStored
5096
- } } : {},
5097
- ...extra.emptyPage ? { emptyPage: {
5098
- ...extra.emptyPage,
5099
- isAdditionalRepresentation: alreadyStored
5100
- } } : {}
5101
- });
3889
+ try {
3890
+ await progressCallback({
3891
+ pagesScraped,
3892
+ totalPages: this.effectiveTotal,
3893
+ totalDiscovered: this.totalDiscovered,
3894
+ pagesIndexed: this.pagesIndexed,
3895
+ currentUrl: item.url,
3896
+ depth: item.depth,
3897
+ maxDepth,
3898
+ outcome,
3899
+ result: null,
3900
+ pageId: item.pageId,
3901
+ ...extra,
3902
+ ...extra.result ? { result: {
3903
+ ...extra.result,
3904
+ isAdditionalRepresentation: alreadyStored
3905
+ } } : {},
3906
+ ...extra.emptyPage ? { emptyPage: {
3907
+ ...extra.emptyPage,
3908
+ isAdditionalRepresentation: alreadyStored
3909
+ } } : {}
3910
+ });
3911
+ } catch (error) {
3912
+ crawl.abortError ??= error instanceof Error ? error : new Error(String(error));
3913
+ throw error;
3914
+ }
5102
3915
  };
5103
3916
  try {
5104
3917
  const result = await this.processItem(item, options, signal);
@@ -5167,6 +3980,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5167
3980
  const wasPage = result.isContainer !== true;
5168
3981
  await report(PageOutcome.Empty, {
5169
3982
  currentUrl: finalUrl,
3983
+ ...!wasPage && item.pageId !== void 0 ? { deleted: true } : {},
5170
3984
  emptyPage: !wasPage ? void 0 : {
5171
3985
  url: finalUrl,
5172
3986
  contentUrl: result.contentUrl ?? (result.url && result.url !== finalUrl ? result.url : void 0),
@@ -5337,8 +4151,7 @@ function isFileUrlInsideRoots(url, roots) {
5337
4151
  return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
5338
4152
  });
5339
4153
  }
5340
- //#endregion
5341
- //#region src/utils/dom.ts
4154
+ // src/utils/dom.ts
5342
4155
  /**
5343
4156
  * Creates a JSDOM instance with a pre-configured virtual console to suppress console noise.
5344
4157
  * This utility simplifies the setup of JSDOM by providing a standard configuration.
@@ -5354,13 +4167,13 @@ function createJSDOM(html, options) {
5354
4167
  virtualConsole.on("info", () => {});
5355
4168
  virtualConsole.on("debug", () => {});
5356
4169
  virtualConsole.on("log", () => {});
5357
- return new JSDOM(html, {
4170
+ const finalOptions = {
5358
4171
  virtualConsole,
5359
4172
  ...options
5360
- });
4173
+ };
4174
+ return new JSDOM(html, finalOptions);
5361
4175
  }
5362
- //#endregion
5363
- //#region src/splitter/GreedySplitter.ts
4176
+ // src/splitter/GreedySplitter.ts
5364
4177
  /**
5365
4178
  * Takes small document chunks and greedily concatenates them into larger, more meaningful units
5366
4179
  * while preserving document structure and semantic boundaries.
@@ -5496,8 +4309,7 @@ var GreedySplitter = class {
5496
4309
  return common;
5497
4310
  }
5498
4311
  };
5499
- //#endregion
5500
- //#region src/splitter/errors.ts
4312
+ // src/splitter/errors.ts
5501
4313
  /**
5502
4314
  * Base error class for all splitter-related errors
5503
4315
  */
@@ -5515,8 +4327,7 @@ var MinimumChunkSizeError = class extends SplitterError {
5515
4327
  * Generic error for content splitting failures
5516
4328
  */
5517
4329
  var ContentSplitterError = class extends SplitterError {};
5518
- //#endregion
5519
- //#region src/splitter/splitters/CodeContentSplitter.ts
4330
+ // src/splitter/splitters/CodeContentSplitter.ts
5520
4331
  /**
5521
4332
  * Splits code content while preserving language information and formatting.
5522
4333
  * Uses line boundaries for splitting and ensures each chunk is properly
@@ -5549,8 +4360,7 @@ var CodeContentSplitter = class {
5549
4360
  return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
5550
4361
  }
5551
4362
  };
5552
- //#endregion
5553
- //#region src/splitter/splitters/fenceState.ts
4363
+ // src/splitter/splitters/fenceState.ts
5554
4364
  var FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
5555
4365
  var FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
5556
4366
  function splitLinesWithOffsets(text) {
@@ -5634,8 +4444,7 @@ function hasOpenFenceAtEnd(chunk) {
5634
4444
  if (!opener) return false;
5635
4445
  return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
5636
4446
  }
5637
- //#endregion
5638
- //#region src/splitter/splitters/TextContentSplitter.ts
4447
+ // src/splitter/splitters/TextContentSplitter.ts
5639
4448
  /**
5640
4449
  * Splits text content using a hierarchical approach:
5641
4450
  * 1. Try splitting by paragraphs (double newlines)
@@ -5772,8 +4581,7 @@ var TextContentSplitter = class {
5772
4581
  return content;
5773
4582
  }
5774
4583
  };
5775
- //#endregion
5776
- //#region src/splitter/splitters/ListContentSplitter.ts
4584
+ // src/splitter/splitters/ListContentSplitter.ts
5777
4585
  var ListContentSplitter = class {
5778
4586
  options;
5779
4587
  textSplitter;
@@ -5823,8 +4631,7 @@ var ListContentSplitter = class {
5823
4631
  return mergedChunks;
5824
4632
  }
5825
4633
  };
5826
- //#endregion
5827
- //#region src/splitter/splitters/TableContentSplitter.ts
4634
+ // src/splitter/splitters/TableContentSplitter.ts
5828
4635
  /**
5829
4636
  * Splits table content while preserving headers and table formatting.
5830
4637
  * Each chunk maintains the table structure with headers and separator row.
@@ -5888,8 +4695,7 @@ var TableContentSplitter = class {
5888
4695
  return separator.includes("|") && /^\|?[\s-|]+\|?$/.test(separator);
5889
4696
  }
5890
4697
  };
5891
- //#endregion
5892
- //#region src/splitter/SemanticMarkdownSplitter.ts
4698
+ // src/splitter/SemanticMarkdownSplitter.ts
5893
4699
  /**
5894
4700
  * Removes an explicit anchor annotation from the end of a heading.
5895
4701
  *
@@ -6238,8 +5044,7 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
6238
5044
  return window.document;
6239
5045
  }
6240
5046
  };
6241
- //#endregion
6242
- //#region src/scraper/pipelines/BasePipeline.ts
5047
+ // src/scraper/pipelines/BasePipeline.ts
6243
5048
  /**
6244
5049
  * Base class for content processing pipelines.
6245
5050
  * Provides common functionality for executing middleware stacks.
@@ -6268,8 +5073,12 @@ var BasePipeline = class {
6268
5073
  * Executes a middleware stack on the given context.
6269
5074
  * This is a utility method used by derived pipeline classes.
6270
5075
  *
5076
+ * A middleware error is recorded in `context.errors` and the pipeline goes on
5077
+ * with what is left, except a `ScraperError`, which fails the page.
5078
+ *
6271
5079
  * @param middleware - The middleware stack to execute
6272
5080
  * @param context - The context to process
5081
+ * @throws {ScraperError} When a middleware throws one.
6273
5082
  */
6274
5083
  async executeMiddlewareStack(middleware, context) {
6275
5084
  let index = -1;
@@ -6283,12 +5092,12 @@ var BasePipeline = class {
6283
5092
  try {
6284
5093
  await dispatch(0);
6285
5094
  } catch (error) {
5095
+ if (error instanceof ScraperError) throw error;
6286
5096
  context.errors.push(error instanceof Error ? error : new Error(String(error)));
6287
5097
  }
6288
5098
  }
6289
5099
  };
6290
- //#endregion
6291
- //#region src/scraper/pipelines/DocumentPipeline.ts
5100
+ // src/scraper/pipelines/DocumentPipeline.ts
6292
5101
  /**
6293
5102
  * DocumentPipeline - Processes binary document formats using Xberg for text extraction,
6294
5103
  * then splits semantically.
@@ -6461,8 +5270,7 @@ function collectErrorReasons(error) {
6461
5270
  }
6462
5271
  return messages;
6463
5272
  }
6464
- //#endregion
6465
- //#region src/scraper/middleware/HtmlCheerioParserMiddleware.ts
5273
+ // src/scraper/middleware/HtmlCheerioParserMiddleware.ts
6466
5274
  /**
6467
5275
  * Middleware to parse HTML string/buffer content into a Cheerio object.
6468
5276
  * It populates the `context.dom` property.
@@ -6482,8 +5290,7 @@ var HtmlCheerioParserMiddleware = class {
6482
5290
  }
6483
5291
  }
6484
5292
  };
6485
- //#endregion
6486
- //#region src/scraper/middleware/HtmlLinkExtractorMiddleware.ts
5293
+ // src/scraper/middleware/HtmlLinkExtractorMiddleware.ts
6487
5294
  /**
6488
5295
  * Middleware to extract links (href attributes from <a> tags) from HTML content using Cheerio.
6489
5296
  * It expects the Cheerio API object to be available in `context.dom`.
@@ -6548,8 +5355,7 @@ var HtmlLinkExtractorMiddleware = class {
6548
5355
  await next();
6549
5356
  }
6550
5357
  };
6551
- //#endregion
6552
- //#region src/scraper/middleware/HtmlMetadataExtractorMiddleware.ts
5358
+ // src/scraper/middleware/HtmlMetadataExtractorMiddleware.ts
6553
5359
  /**
6554
5360
  * Middleware to extract the title from HTML content using Cheerio.
6555
5361
  * Assumes context.dom (Cheerio API object) is populated by a preceding middleware
@@ -6582,8 +5388,7 @@ var HtmlMetadataExtractorMiddleware = class {
6582
5388
  await next();
6583
5389
  }
6584
5390
  };
6585
- //#endregion
6586
- //#region src/scraper/middleware/HtmlNormalizationMiddleware.ts
5391
+ // src/scraper/middleware/HtmlNormalizationMiddleware.ts
6587
5392
  /**
6588
5393
  * Middleware that normalizes URLs and links in HTML content after DOM parsing.
6589
5394
  *
@@ -6774,8 +5579,7 @@ var HtmlNormalizationMiddleware = class {
6774
5579
  $element.replaceWith(htmlContent);
6775
5580
  }
6776
5581
  };
6777
- //#endregion
6778
- //#region src/scraper/utils/SimpleMemoryCache.ts
5582
+ // src/scraper/utils/SimpleMemoryCache.ts
6779
5583
  /**
6780
5584
  * A simple in-memory LRU (Least Recently Used) cache.
6781
5585
  * When the cache reaches maxSize, the oldest (least recently used) entry is evicted.
@@ -6845,8 +5649,7 @@ var SimpleMemoryCache = class {
6845
5649
  this.cache.clear();
6846
5650
  }
6847
5651
  };
6848
- //#endregion
6849
- //#region src/scraper/middleware/subresourceBlocklist.ts
5652
+ // src/scraper/middleware/subresourceBlocklist.ts
6850
5653
  var BLOCKLIST_NOT_BLOCKED = Object.freeze({ blocked: false });
6851
5654
  var SUBRESOURCE_BLOCKLIST = Object.freeze([
6852
5655
  {
@@ -7000,8 +5803,7 @@ function isBlockedSubresource(url) {
7000
5803
  }
7001
5804
  return BLOCKLIST_NOT_BLOCKED;
7002
5805
  }
7003
- //#endregion
7004
- //#region src/scraper/middleware/HtmlPlaywrightMiddleware.ts
5806
+ // src/scraper/middleware/HtmlPlaywrightMiddleware.ts
7005
5807
  /**
7006
5808
  * Most redirects a sub-resource fetch follows. Matches Playwright's own default
7007
5809
  * (20): the renderer follows redirects itself only to check every hop against
@@ -7435,10 +6237,6 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7435
6237
  if (!(error instanceof Error)) return false;
7436
6238
  return error.message.includes("Target page, context or browser has been closed");
7437
6239
  }
7438
- formatRouteError(error) {
7439
- const message = error instanceof Error ? error.message : String(error);
7440
- return message.split("\n")[0] || message;
7441
- }
7442
6240
  isSpeculativePrefetch(route) {
7443
6241
  const headers = route.request().headers();
7444
6242
  return headers["next-router-prefetch"] === "1" || headers.purpose?.toLowerCase() === "prefetch" || headers["sec-purpose"]?.toLowerCase().includes("prefetch") === true;
@@ -7486,7 +6284,7 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7486
6284
  await route.continue(options);
7487
6285
  } catch (error) {
7488
6286
  if (this.ignoreRouteLifecycleError(error, "continue", reqUrl)) return;
7489
- const errorMessage = this.formatRouteError(error);
6287
+ const errorMessage = firstErrorLine(error);
7490
6288
  logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
7491
6289
  await this.abortRoute(route, reqUrl, "abort after continue error", "failed");
7492
6290
  }
@@ -7559,7 +6357,7 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7559
6357
  await this.fulfillRoute(route, reqUrl, { response }, "fulfill");
7560
6358
  } catch (error) {
7561
6359
  if (this.ignoreRouteLifecycleError(error, `fetch ${resourceType}`, reqUrl)) return;
7562
- const errorMessage = this.formatRouteError(error);
6360
+ const errorMessage = firstErrorLine(error);
7563
6361
  logger.debug(`Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`);
7564
6362
  await this.abortRoute(route, reqUrl, "abort after error", "failed");
7565
6363
  }
@@ -7692,9 +6490,11 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7692
6490
  * - Injects Authorization header for all same-origin requests if credentials are present and not already set.
7693
6491
  * - Forwards all custom headers from context.options?.headers to Playwright requests.
7694
6492
  * - Waits for common loading indicators to disappear before extracting HTML.
6493
+ * - When rendering fails, `auto` mode records the error and keeps the fetched HTML.
7695
6494
  *
7696
6495
  * @param context The middleware context containing the HTML and source URL.
7697
6496
  * @param next The next middleware function in the pipeline.
6497
+ * @throws {RenderError} When rendering fails in `playwright` mode.
7698
6498
  */
7699
6499
  async process(context, next) {
7700
6500
  const contentType = context.options?.headers?.["content-type"] || context.contentType;
@@ -7721,7 +6521,9 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7721
6521
  renderedHtml = await withTimeout(this.renderPage(browser, context, handles), this.getRenderTimeoutMs(), `Playwright render for ${context.source}`);
7722
6522
  } catch (error) {
7723
6523
  logger.error(`❌ Playwright failed to render ${context.source}: ${error}`);
7724
- context.errors.push(error instanceof Error ? error : /* @__PURE__ */ new Error(`Playwright rendering failed: ${String(error)}`));
6524
+ const renderError = error instanceof Error ? error : /* @__PURE__ */ new Error(`Playwright rendering failed: ${String(error)}`);
6525
+ if (scrapeMode === ScrapeMode.Playwright) throw new RenderError(context.source, renderError);
6526
+ context.errors.push(renderError);
7725
6527
  } finally {
7726
6528
  const closed = await this.cleanupPageAndContext(handles.page, handles.browserContext, context.source);
7727
6529
  const failedBeforeContext = renderedHtml === null && handles.browserContext === null;
@@ -7730,7 +6532,7 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7730
6532
  if (renderedHtml !== null) {
7731
6533
  context.content = renderedHtml;
7732
6534
  logger.debug(`Playwright middleware updated content for ${context.source}. Proceeding.`);
7733
- } else logger.warn(`⚠️ Playwright rendering resulted in null content for ${context.source}. Proceeding without content update.`);
6535
+ }
7734
6536
  await next();
7735
6537
  }
7736
6538
  /**
@@ -7866,8 +6668,7 @@ function mergePlaywrightHeaders(requestHeaders, customHeaders, credentials, orig
7866
6668
  }
7867
6669
  return withMarkdownPreferredAccept(headers, customHeaders);
7868
6670
  }
7869
- //#endregion
7870
- //#region src/scraper/middleware/HtmlSanitizerMiddleware.ts
6671
+ // src/scraper/middleware/HtmlSanitizerMiddleware.ts
7871
6672
  /**
7872
6673
  * Minimum share of the sanitized body's visible text that the main-content
7873
6674
  * region must hold before extraction is scoped to it. Tuning value: measured
@@ -8113,8 +6914,7 @@ var HtmlSanitizerMiddleware = class {
8113
6914
  await next();
8114
6915
  }
8115
6916
  };
8116
- //#endregion
8117
- //#region src/scraper/middleware/HtmlToMarkdownMiddleware.ts
6917
+ // src/scraper/middleware/HtmlToMarkdownMiddleware.ts
8118
6918
  var maxGfmTableRows = 500;
8119
6919
  var maxGfmTableCells = 1e3;
8120
6920
  var maxGfmTableHtmlLength = 1e5;
@@ -8349,8 +7149,7 @@ var HtmlToMarkdownMiddleware = class {
8349
7149
  await next();
8350
7150
  }
8351
7151
  };
8352
- //#endregion
8353
- //#region src/scraper/utils/charset.ts
7152
+ // src/scraper/utils/charset.ts
8354
7153
  /**
8355
7154
  * Utility functions for enhanced charset detection and handling.
8356
7155
  */
@@ -8411,8 +7210,7 @@ function normalizeCharset(charset) {
8411
7210
  const normalized = charset.toLowerCase().trim();
8412
7211
  return CHARSET_ALIASES[normalized] || normalized;
8413
7212
  }
8414
- //#endregion
8415
- //#region src/scraper/utils/buffer.ts
7213
+ // src/scraper/utils/buffer.ts
8416
7214
  /**
8417
7215
  * Decodes a Buffer or string to a JavaScript string using the specified charset.
8418
7216
  * The charset should be the encoding as reported by the source (e.g., HTTP header).
@@ -8437,8 +7235,7 @@ function convertToString(content, charset) {
8437
7235
  }
8438
7236
  }
8439
7237
  }
8440
- //#endregion
8441
- //#region src/scraper/pipelines/HtmlPipeline.ts
7238
+ // src/scraper/pipelines/HtmlPipeline.ts
8442
7239
  /**
8443
7240
  * HtmlPipeline - Processes HTML content into Markdown chunks.
8444
7241
  * Uses Playwright for rendering if needed and Cheerio for semantic extraction.
@@ -8520,12 +7317,11 @@ var HtmlPipeline = class extends BasePipeline {
8520
7317
  function createLazyDefuddleMiddleware() {
8521
7318
  let real = null;
8522
7319
  return { async process(context, next) {
8523
- if (!real) real = new (await (import("./HtmlDefuddleMiddleware-BNIv3ibo.js"))).HtmlDefuddleMiddleware();
7320
+ if (!real) real = new (await (import("./HtmlDefuddleMiddleware-DxjoyIFY.js"))).HtmlDefuddleMiddleware();
8524
7321
  await real.process(context, next);
8525
7322
  } };
8526
7323
  }
8527
- //#endregion
8528
- //#region src/splitter/TextDocumentSplitter.ts
7324
+ // src/splitter/TextDocumentSplitter.ts
8529
7325
  /**
8530
7326
  * TextDocumentSplitter - Simple text-based document splitter
8531
7327
  *
@@ -8578,8 +7374,7 @@ var TextDocumentSplitter = class {
8578
7374
  }
8579
7375
  }
8580
7376
  };
8581
- //#endregion
8582
- //#region src/splitter/JsonDocumentSplitter.ts
7377
+ // src/splitter/JsonDocumentSplitter.ts
8583
7378
  /**
8584
7379
  * JsonDocumentSplitter - Concatenation-friendly JSON document splitting.
8585
7380
  *
@@ -8806,8 +7601,7 @@ var JsonDocumentSplitter = class {
8806
7601
  });
8807
7602
  }
8808
7603
  };
8809
- //#endregion
8810
- //#region src/scraper/pipelines/JsonPipeline.ts
7604
+ // src/scraper/pipelines/JsonPipeline.ts
8811
7605
  /**
8812
7606
  * Pipeline for processing JSON content with semantic, hierarchical splitting.
8813
7607
  * Uses JsonDocumentSplitter to produce structurally faithful chunks (preserving {level, path})
@@ -8907,8 +7701,7 @@ var JsonPipeline = class extends BasePipeline {
8907
7701
  return currentDepth;
8908
7702
  }
8909
7703
  };
8910
- //#endregion
8911
- //#region src/scraper/middleware/MarkdownLinkExtractorMiddleware.ts
7704
+ // src/scraper/middleware/MarkdownLinkExtractorMiddleware.ts
8912
7705
  var inlineLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\(([^)\s]+)(?:\s+"[^"]*"|\s+'[^']*'|\s+\([^)]*\))?\)/g;
8913
7706
  var referenceLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\[([^\]\n]+)\]/g;
8914
7707
  var referenceDefinitionPattern = /^\s{0,3}\[([^\]\n]+)\]:\s*(\S+)(?:\s+.*)?$/gm;
@@ -8953,8 +7746,7 @@ function cleanReferenceTarget(target) {
8953
7746
  if (!target) return "";
8954
7747
  return target.trim().replace(/^<(.+)>$/, "$1");
8955
7748
  }
8956
- //#endregion
8957
- //#region src/scraper/middleware/MarkdownMetadataExtractorMiddleware.ts
7749
+ // src/scraper/middleware/MarkdownMetadataExtractorMiddleware.ts
8958
7750
  /**
8959
7751
  * Middleware to extract the title from Markdown content.
8960
7752
  * Prioritizes YAML frontmatter 'title' field, falls back to first H1 heading.
@@ -8987,8 +7779,7 @@ var MarkdownMetadataExtractorMiddleware = class {
8987
7779
  await next();
8988
7780
  }
8989
7781
  };
8990
- //#endregion
8991
- //#region src/scraper/pipelines/MarkdownPipeline.ts
7782
+ // src/scraper/pipelines/MarkdownPipeline.ts
8992
7783
  /**
8993
7784
  * MarkdownPipeline - Processes Markdown content using middleware and semantic splitting.
8994
7785
  */
@@ -9031,37 +7822,7 @@ var MarkdownPipeline = class extends BasePipeline {
9031
7822
  };
9032
7823
  }
9033
7824
  };
9034
- //#endregion
9035
- //#region src/splitter/treesitter/parsers/types.ts
9036
- /**
9037
- * Universal tree-sitter parser size limit.
9038
- * Set to 30,000 characters to be safely under the observed 32,767 limit.
9039
- */
9040
- var StructuralNodeType = /* @__PURE__ */ function(StructuralNodeType) {
9041
- StructuralNodeType["FUNCTION_DECLARATION"] = "function_declaration";
9042
- StructuralNodeType["ARROW_FUNCTION"] = "arrow_function";
9043
- StructuralNodeType["METHOD_DEFINITION"] = "method_definition";
9044
- StructuralNodeType["CONSTRUCTOR"] = "constructor";
9045
- StructuralNodeType["CLASS_DECLARATION"] = "class_declaration";
9046
- StructuralNodeType["OBJECT_EXPRESSION"] = "object_expression";
9047
- StructuralNodeType["INTERFACE_DECLARATION"] = "interface_declaration";
9048
- StructuralNodeType["TYPE_ALIAS_DECLARATION"] = "type_alias_declaration";
9049
- StructuralNodeType["NAMESPACE_DECLARATION"] = "namespace_declaration";
9050
- StructuralNodeType["ENUM_DECLARATION"] = "enum_declaration";
9051
- StructuralNodeType["JSX_ELEMENT"] = "jsx_element";
9052
- StructuralNodeType["JSX_FRAGMENT"] = "jsx_fragment";
9053
- StructuralNodeType["JSX_EXPRESSION"] = "jsx_expression";
9054
- StructuralNodeType["VARIABLE_DECLARATION"] = "variable_declaration";
9055
- StructuralNodeType["EXPORT_STATEMENT"] = "export_statement";
9056
- StructuralNodeType["IMPORT_STATEMENT"] = "import_statement";
9057
- StructuralNodeType["IF_STATEMENT"] = "if_statement";
9058
- StructuralNodeType["FOR_STATEMENT"] = "for_statement";
9059
- StructuralNodeType["WHILE_STATEMENT"] = "while_statement";
9060
- StructuralNodeType["SWITCH_STATEMENT"] = "switch_statement";
9061
- return StructuralNodeType;
9062
- }({});
9063
- //#endregion
9064
- //#region src/splitter/treesitter/parsers/PythonParser.ts
7825
+ // src/splitter/treesitter/parsers/PythonParser.ts
9065
7826
  /**
9066
7827
  * Python parser for tree-sitter based source code splitting.
9067
7828
  *
@@ -9251,54 +8012,6 @@ var PythonParser = class {
9251
8012
  if (node.hasError && node.type === "ERROR") acc.push(node);
9252
8013
  for (const c of node.children) this.collectErrorNodes(c, acc);
9253
8014
  }
9254
- getNodeText(node, source) {
9255
- return source.slice(node.startIndex, node.endIndex);
9256
- }
9257
- getNodeLines(node, _source) {
9258
- return {
9259
- startLine: node.startPosition.row + 1,
9260
- endLine: node.endPosition.row + 1
9261
- };
9262
- }
9263
- /**
9264
- * Legacy structural node extraction (used by existing tests).
9265
- * Produces a flat list (no parent/child linking beyond simple push).
9266
- */
9267
- extractStructuralNodes(tree, source) {
9268
- const src = source ?? tree.rootNode.text;
9269
- const out = [];
9270
- const structuralTypes = /* @__PURE__ */ new Set([...STRUCTURAL_DECL_TYPES$1, ...CONTENT_DECL_TYPES$1]);
9271
- const visit = (node) => {
9272
- if (structuralTypes.has(node.type)) {
9273
- if (this.shouldSkipStructuralNode(node)) {
9274
- for (const child of node.children) visit(child);
9275
- return;
9276
- }
9277
- const name = extractName$1(node);
9278
- const { startLine, startByte } = findDocumentationStart$1(node, src);
9279
- const endLine = node.endPosition.row + 1;
9280
- const structuralNode = {
9281
- type: this.classifyStructuralNode(node),
9282
- name,
9283
- startLine,
9284
- endLine,
9285
- startByte,
9286
- endByte: node.endIndex,
9287
- children: [],
9288
- text: this.getNodeText(node, src),
9289
- indentLevel: 0,
9290
- modifiers: [],
9291
- documentation: void 0
9292
- };
9293
- out.push(structuralNode);
9294
- for (const child of node.children) visit(child);
9295
- return;
9296
- }
9297
- for (const child of node.children) visit(child);
9298
- };
9299
- visit(tree.rootNode);
9300
- return this.deduplicate(out);
9301
- }
9302
8015
  /**
9303
8016
  * Boundary extraction: produces CodeBoundary[] directly from AST.
9304
8017
  */
@@ -9347,31 +8060,8 @@ var PythonParser = class {
9347
8060
  shouldSkipStructuralNode(_node) {
9348
8061
  return false;
9349
8062
  }
9350
- classifyStructuralNode(node) {
9351
- switch (node.type) {
9352
- case "function_definition":
9353
- case "async_function_definition": return StructuralNodeType.FUNCTION_DECLARATION;
9354
- case "class_definition": return StructuralNodeType.CLASS_DECLARATION;
9355
- case "import_statement":
9356
- case "import_from_statement": return StructuralNodeType.IMPORT_STATEMENT;
9357
- default: return StructuralNodeType.VARIABLE_DECLARATION;
9358
- }
9359
- }
9360
- deduplicate(nodes) {
9361
- const seen = /* @__PURE__ */ new Set();
9362
- const out = [];
9363
- for (const n of nodes) {
9364
- const key = `${n.startByte}:${n.endByte}:${n.type}:${n.name}`;
9365
- if (seen.has(key)) continue;
9366
- seen.add(key);
9367
- out.push(n);
9368
- }
9369
- out.sort((a, b) => a.startByte - b.startByte);
9370
- return out;
9371
- }
9372
8063
  };
9373
- //#endregion
9374
- //#region src/splitter/treesitter/parsers/TypeScriptParser.ts
8064
+ // src/splitter/treesitter/parsers/TypeScriptParser.ts
9375
8065
  /**
9376
8066
  * Simplified standalone TypeScript (and JavaScript) parser.
9377
8067
  *
@@ -9379,7 +8069,6 @@ var PythonParser = class {
9379
8069
  * - Single, unified parser for .ts/.tsx/.js/.jsx (+ mjs/cjs/mts/cts)
9380
8070
  * - Direct boundary extraction aligned with canonical ruleset
9381
8071
  * - Minimal, predictable logic (no complex multi-phase traversals)
9382
- * - Retain legacy extractStructuralNodes() for existing tests
9383
8072
  *
9384
8073
  * This replaces the previous inheritance-heavy BaseLanguageParser design.
9385
8074
  */
@@ -9414,20 +8103,6 @@ var CONTENT_DECL_TYPES = /* @__PURE__ */ new Set([
9414
8103
  "variable_declarator"
9415
8104
  ]);
9416
8105
  /**
9417
- * Tokens considered modifiers (merged into name for static methods if needed).
9418
- */
9419
- var MODIFIER_TOKENS = /* @__PURE__ */ new Set([
9420
- "export",
9421
- "default",
9422
- "public",
9423
- "private",
9424
- "protected",
9425
- "readonly",
9426
- "abstract",
9427
- "async",
9428
- "static"
9429
- ]);
9430
- /**
9431
8106
  * Decide if node type is boundary-worthy (before suppression rules).
9432
8107
  */
9433
8108
  function isCandidateBoundary(node) {
@@ -9556,31 +8231,6 @@ function extractName(node) {
9556
8231
  }
9557
8232
  }
9558
8233
  /**
9559
- * Modifier extraction (scan children + backward tokens).
9560
- */
9561
- function extractModifiers(node) {
9562
- const mods = /* @__PURE__ */ new Set();
9563
- for (const c of node.children) if (MODIFIER_TOKENS.has(c.type)) mods.add(c.type);
9564
- let prev = node.previousSibling;
9565
- while (prev) {
9566
- if (prev.type === "comment") {
9567
- prev = prev.previousSibling;
9568
- continue;
9569
- }
9570
- if (/^\s*$/.test(prev.text)) {
9571
- prev = prev.previousSibling;
9572
- continue;
9573
- }
9574
- if (MODIFIER_TOKENS.has(prev.type)) {
9575
- mods.add(prev.type);
9576
- prev = prev.previousSibling;
9577
- continue;
9578
- }
9579
- break;
9580
- }
9581
- return Array.from(mods);
9582
- }
9583
- /**
9584
8234
  * Boundary classification mapping.
9585
8235
  */
9586
8236
  function classifyBoundaryKind(node) {
@@ -9680,55 +8330,6 @@ var TypeScriptParser = class {
9680
8330
  if (node.hasError && node.type === "ERROR") acc.push(node);
9681
8331
  for (const c of node.children) this.collectErrorNodes(c, acc);
9682
8332
  }
9683
- getNodeText(node, source) {
9684
- return source.slice(node.startIndex, node.endIndex);
9685
- }
9686
- getNodeLines(node, _source) {
9687
- return {
9688
- startLine: node.startPosition.row + 1,
9689
- endLine: node.endPosition.row + 1
9690
- };
9691
- }
9692
- /**
9693
- * Legacy structural node extraction (used by existing tests).
9694
- * Produces a flat list (no parent/child linking beyond simple push).
9695
- */
9696
- extractStructuralNodes(tree, source) {
9697
- const src = source ?? tree.rootNode.text;
9698
- const out = [];
9699
- const structuralTypes = /* @__PURE__ */ new Set([...STRUCTURAL_DECL_TYPES, ...CONTENT_DECL_TYPES]);
9700
- const visit = (node) => {
9701
- if (structuralTypes.has(node.type)) {
9702
- if (this.shouldSkipStructuralNode(node)) {
9703
- for (const child of node.children) visit(child);
9704
- return;
9705
- }
9706
- const name = extractName(node);
9707
- const modifiers = extractModifiers(node);
9708
- const { startLine, startByte } = findDocumentationStart(node, src);
9709
- const endLine = node.endPosition.row + 1;
9710
- const structuralNode = {
9711
- type: this.classifyStructuralNode(node),
9712
- name,
9713
- startLine,
9714
- endLine,
9715
- startByte,
9716
- endByte: node.endIndex,
9717
- children: [],
9718
- text: this.getNodeText(node, src),
9719
- indentLevel: 0,
9720
- modifiers,
9721
- documentation: void 0
9722
- };
9723
- out.push(structuralNode);
9724
- for (const child of node.children) visit(child);
9725
- return;
9726
- }
9727
- for (const child of node.children) visit(child);
9728
- };
9729
- visit(tree.rootNode);
9730
- return this.deduplicate(out);
9731
- }
9732
8333
  /**
9733
8334
  * Boundary extraction: produces CodeBoundary[] directly from AST.
9734
8335
  */
@@ -9806,45 +8407,8 @@ var TypeScriptParser = class {
9806
8407
  }
9807
8408
  return false;
9808
8409
  }
9809
- classifyStructuralNode(node) {
9810
- switch (node.type) {
9811
- case "function_declaration": return StructuralNodeType.FUNCTION_DECLARATION;
9812
- case "arrow_function": return StructuralNodeType.ARROW_FUNCTION;
9813
- case "method_definition":
9814
- case "method_signature":
9815
- case "abstract_method_signature": return StructuralNodeType.METHOD_DEFINITION;
9816
- case "constructor": return StructuralNodeType.CONSTRUCTOR;
9817
- case "class_declaration":
9818
- case "abstract_class_declaration": return StructuralNodeType.CLASS_DECLARATION;
9819
- case "interface_declaration": return StructuralNodeType.INTERFACE_DECLARATION;
9820
- case "type_alias_declaration": return StructuralNodeType.TYPE_ALIAS_DECLARATION;
9821
- case "enum_declaration": return StructuralNodeType.ENUM_DECLARATION;
9822
- case "namespace_declaration":
9823
- case "module_declaration":
9824
- case "internal_module": return StructuralNodeType.NAMESPACE_DECLARATION;
9825
- case "import_statement": return StructuralNodeType.IMPORT_STATEMENT;
9826
- case "export_statement": return StructuralNodeType.EXPORT_STATEMENT;
9827
- case "variable_declaration":
9828
- case "lexical_declaration":
9829
- case "variable_declarator": return StructuralNodeType.VARIABLE_DECLARATION;
9830
- default: return StructuralNodeType.VARIABLE_DECLARATION;
9831
- }
9832
- }
9833
- deduplicate(nodes) {
9834
- const seen = /* @__PURE__ */ new Set();
9835
- const out = [];
9836
- for (const n of nodes) {
9837
- const key = `${n.startByte}:${n.endByte}:${n.type}:${n.name}`;
9838
- if (seen.has(key)) continue;
9839
- seen.add(key);
9840
- out.push(n);
9841
- }
9842
- out.sort((a, b) => a.startByte - b.startByte);
9843
- return out;
9844
- }
9845
8410
  };
9846
- //#endregion
9847
- //#region src/splitter/treesitter/LanguageParserRegistry.ts
8411
+ // src/splitter/treesitter/LanguageParserRegistry.ts
9848
8412
  /**
9849
8413
  * LanguageParserRegistry - Registry for tree-sitter language parsers
9850
8414
  *
@@ -9881,42 +8445,6 @@ var LanguageParserRegistry = class {
9881
8445
  return language ? this.parsers.get(language) : void 0;
9882
8446
  }
9883
8447
  /**
9884
- * Check if a language is supported
9885
- */
9886
- isLanguageSupported(language) {
9887
- return this.parsers.has(language);
9888
- }
9889
- /**
9890
- * Check if a file extension is supported
9891
- */
9892
- isExtensionSupported(extension) {
9893
- return this.extensionMap.has(extension.toLowerCase());
9894
- }
9895
- /**
9896
- * Check if a MIME type is supported
9897
- */
9898
- isMimeTypeSupported(mimeType) {
9899
- return this.mimeTypeMap.has(mimeType.toLowerCase());
9900
- }
9901
- /**
9902
- * Get all supported languages
9903
- */
9904
- getSupportedLanguages() {
9905
- return Array.from(this.parsers.keys());
9906
- }
9907
- /**
9908
- * Get all supported file extensions
9909
- */
9910
- getSupportedExtensions() {
9911
- return Array.from(this.extensionMap.keys());
9912
- }
9913
- /**
9914
- * Get all supported MIME types
9915
- */
9916
- getSupportedMimeTypes() {
9917
- return Array.from(this.mimeTypeMap.keys());
9918
- }
9919
- /**
9920
8448
  * Register a new parser
9921
8449
  */
9922
8450
  registerParser(parser) {
@@ -9928,48 +8456,11 @@ var LanguageParserRegistry = class {
9928
8456
  const limit = this.treeSitterSizeLimit;
9929
8457
  const unified = new TypeScriptParser(limit);
9930
8458
  this.registerParser(unified);
9931
- const jsAlias = {
9932
- ...unified,
9933
- name: "javascript",
9934
- parse: unified.parse.bind(unified),
9935
- extractStructuralNodes: unified.extractStructuralNodes.bind(unified),
9936
- getNodeText: unified.getNodeText.bind(unified),
9937
- getNodeLines: unified.getNodeLines.bind(unified),
9938
- extractBoundaries: unified.extractBoundaries.bind(unified),
9939
- fileExtensions: [
9940
- ".js",
9941
- ".jsx",
9942
- ".mjs",
9943
- ".cjs"
9944
- ],
9945
- mimeTypes: [
9946
- "text/x-jsx",
9947
- "text/javascript",
9948
- "application/javascript",
9949
- "text/jsx",
9950
- "application/jsx"
9951
- ]
9952
- };
9953
- this.parsers.set("javascript", jsAlias);
9954
- for (const ext of [
9955
- ".js",
9956
- ".jsx",
9957
- ".mjs",
9958
- ".cjs"
9959
- ]) this.extensionMap.set(ext.toLowerCase(), "javascript");
9960
- for (const mt of [
9961
- "text/x-jsx",
9962
- "text/javascript",
9963
- "application/javascript",
9964
- "text/jsx",
9965
- "application/jsx"
9966
- ]) this.mimeTypeMap.set(mt.toLowerCase(), "javascript");
9967
8459
  const pythonParser = new PythonParser(limit);
9968
8460
  this.registerParser(pythonParser);
9969
8461
  }
9970
8462
  };
9971
- //#endregion
9972
- //#region src/splitter/treesitter/TreesitterSourceCodeSplitter.ts
8463
+ // src/splitter/treesitter/TreesitterSourceCodeSplitter.ts
9973
8464
  /**
9974
8465
  * Tree-sitter based source code splitter that provides semantic parsing
9975
8466
  * while maintaining compatibility with existing chunk patterns
@@ -10023,30 +8514,6 @@ var TreesitterSourceCodeSplitter = class {
10023
8514
  if (contentType.includes("jsx") || contentType.includes("tsx")) return this.registry.getParser("typescript");
10024
8515
  }
10025
8516
  /**
10026
- * Check if the content type is supported
10027
- */
10028
- isSupportedContentType(contentType) {
10029
- return this.getParserForContent(contentType) !== void 0;
10030
- }
10031
- /**
10032
- * Get the list of supported languages
10033
- */
10034
- getSupportedLanguages() {
10035
- return this.registry.getSupportedLanguages();
10036
- }
10037
- /**
10038
- * Get the list of supported file extensions
10039
- */
10040
- getSupportedExtensions() {
10041
- return this.registry.getSupportedExtensions();
10042
- }
10043
- /**
10044
- * Get the list of supported MIME types
10045
- */
10046
- getSupportedMimeTypes() {
10047
- return this.registry.getSupportedMimeTypes();
10048
- }
10049
- /**
10050
8517
  * Helper method to split content using TextContentSplitter only if needed
10051
8518
  * and create ContentChunks with the specified hierarchical path and level
10052
8519
  */
@@ -10126,8 +8593,10 @@ var TreesitterSourceCodeSplitter = class {
10126
8593
  level = 0;
10127
8594
  }
10128
8595
  let isStructural = boundary?.boundaryType === "structural";
10129
- if (isStructural && boundary) if (structuralBoundaryFirstChunk.has(boundary)) isStructural = false;
10130
- else structuralBoundaryFirstChunk.add(boundary);
8596
+ if (isStructural && boundary) {
8597
+ if (structuralBoundaryFirstChunk.has(boundary)) isStructural = false;
8598
+ else structuralBoundaryFirstChunk.add(boundary);
8599
+ }
10131
8600
  const segmentChunks = await this.splitContentIntoChunks(segment.content, path, level);
10132
8601
  for (const c of segmentChunks) {
10133
8602
  if (pendingWhitespace) {
@@ -10195,8 +8664,7 @@ var TreesitterSourceCodeSplitter = class {
10195
8664
  return innermost;
10196
8665
  }
10197
8666
  };
10198
- //#endregion
10199
- //#region src/scraper/pipelines/SourceCodePipeline.ts
8667
+ // src/scraper/pipelines/SourceCodePipeline.ts
10200
8668
  /**
10201
8669
  * Pipeline for processing source code content with semantic, structure-aware splitting.
10202
8670
  * Uses TreesitterSourceCodeSplitter for language-aware hierarchical chunking that preserves
@@ -10238,8 +8706,7 @@ var SourceCodePipeline = class extends BasePipeline {
10238
8706
  };
10239
8707
  }
10240
8708
  };
10241
- //#endregion
10242
- //#region src/scraper/pipelines/TextPipeline.ts
8709
+ // src/scraper/pipelines/TextPipeline.ts
10243
8710
  /**
10244
8711
  * TextPipeline - Processes plain text content with size optimization.
10245
8712
  */
@@ -10284,8 +8751,7 @@ var TextPipeline = class extends BasePipeline {
10284
8751
  };
10285
8752
  }
10286
8753
  };
10287
- //#endregion
10288
- //#region src/scraper/pipelines/PipelineFactory.ts
8754
+ // src/scraper/pipelines/PipelineFactory.ts
10289
8755
  /**
10290
8756
  * Factory class for creating content processing pipelines.
10291
8757
  * Provides standardized pipeline configurations used across different scraper strategies.
@@ -10313,8 +8779,7 @@ var PipelineFactory = class {
10313
8779
  ];
10314
8780
  }
10315
8781
  };
10316
- //#endregion
10317
- //#region src/scraper/strategies/GitHubRepoProcessor.ts
8782
+ // src/scraper/strategies/GitHubRepoProcessor.ts
10318
8783
  /**
10319
8784
  * GitHubRepoProcessor handles processing individual files from GitHub repositories.
10320
8785
  * It processes HTTPS blob URLs (https://github.com/owner/repo/blob/branch/filepath).
@@ -10418,8 +8883,7 @@ var GitHubRepoProcessor = class {
10418
8883
  await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));
10419
8884
  }
10420
8885
  };
10421
- //#endregion
10422
- //#region src/scraper/strategies/GitHubWikiProcessor.ts
8886
+ // src/scraper/strategies/GitHubWikiProcessor.ts
10423
8887
  /**
10424
8888
  * GitHubWikiProcessor handles scraping GitHub wiki pages using standard web scraping techniques.
10425
8889
  * GitHub wikis are separate from the main repository and are hosted at /wiki/ URLs.
@@ -10476,6 +8940,16 @@ var GitHubWikiProcessor = class {
10476
8940
  etag: item.etag,
10477
8941
  headers
10478
8942
  });
8943
+ const wikiInfo = this.parseGitHubWikiUrl(currentUrl);
8944
+ const wikiPath = `/${wikiInfo.owner}/${wikiInfo.repo}/wiki`;
8945
+ if (!new URL(rawContent.source, currentUrl).pathname.startsWith(wikiPath)) {
8946
+ logger.debug(`Wiki URL redirected out of the wiki: ${currentUrl}`);
8947
+ return {
8948
+ url: currentUrl,
8949
+ links: [],
8950
+ status: FetchStatus.NOT_FOUND
8951
+ };
8952
+ }
10479
8953
  if (rawContent.status !== FetchStatus.SUCCESS) return {
10480
8954
  url: currentUrl,
10481
8955
  links: [],
@@ -10501,8 +8975,6 @@ var GitHubWikiProcessor = class {
10501
8975
  }
10502
8976
  for (const err of processed.errors ?? []) logger.warn(`⚠️ Processing error for ${currentUrl}: ${err.message}`);
10503
8977
  const parsedUrl = new URL(currentUrl);
10504
- const wikiInfo = this.parseGitHubWikiUrl(currentUrl);
10505
- const pageTitle = parsedUrl.pathname.replace(`/${wikiInfo.owner}/${wikiInfo.repo}/wiki`, "").replace(/^\//, "") || "Home";
10506
8978
  const wikiLinks = (processed.links || []).filter((link) => {
10507
8979
  if (!link || link.trim() === "" || link === "invalid-url" || link === "not-a-url-at-all") return false;
10508
8980
  return true;
@@ -10515,14 +8987,14 @@ var GitHubWikiProcessor = class {
10515
8987
  }).filter((link) => link !== null).filter((link) => {
10516
8988
  try {
10517
8989
  const linkUrl = new URL(link);
10518
- return linkUrl.hostname === parsedUrl.hostname && linkUrl.pathname.startsWith(`/${wikiInfo.owner}/${wikiInfo.repo}/wiki`);
8990
+ return linkUrl.hostname === parsedUrl.hostname && linkUrl.pathname.startsWith(wikiPath);
10519
8991
  } catch {
10520
8992
  return false;
10521
8993
  }
10522
8994
  });
10523
8995
  return {
10524
8996
  url: currentUrl,
10525
- title: pageTitle,
8997
+ title: processed.title,
10526
8998
  etag: rawContent.etag,
10527
8999
  lastModified: rawContent.lastModified,
10528
9000
  contentType: rawContent.mimeType,
@@ -10546,8 +9018,7 @@ var GitHubWikiProcessor = class {
10546
9018
  await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));
10547
9019
  }
10548
9020
  };
10549
- //#endregion
10550
- //#region src/scraper/strategies/github-auth.ts
9021
+ // src/scraper/strategies/github-auth.ts
10551
9022
  var execAsync = promisify(exec);
10552
9023
  /**
10553
9024
  * Resolves GitHub authentication headers using a cascading fallback mechanism.
@@ -10594,8 +9065,7 @@ async function resolveGitHubAuth(explicitHeaders) {
10594
9065
  } catch {}
10595
9066
  return explicitHeaders ?? {};
10596
9067
  }
10597
- //#endregion
10598
- //#region src/scraper/strategies/GitHubScraperStrategy.ts
9068
+ // src/scraper/strategies/GitHubScraperStrategy.ts
10599
9069
  /** Text-based file extensions recognized for GitHub repository scraping. */
10600
9070
  var TEXT_EXTENSIONS = /* @__PURE__ */ new Set([
10601
9071
  ".md",
@@ -10818,19 +9288,6 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
10818
9288
  this.wikiProcessor = new GitHubWikiProcessor(config);
10819
9289
  this.repoProcessor = new GitHubRepoProcessor(config);
10820
9290
  }
10821
- canHandle(url) {
10822
- if (url.startsWith("github-file://")) return true;
10823
- try {
10824
- const { hostname, pathname } = new URL(url);
10825
- if (!["github.com", "www.github.com"].includes(hostname)) return false;
10826
- if (pathname.match(/^\/([^/]+)\/([^/]+)\/?$/)) return true;
10827
- if (pathname.match(/^\/([^/]+)\/([^/]+)\/tree\//)) return true;
10828
- if (pathname.match(/^\/([^/]+)\/([^/]+)\/blob\//)) return true;
10829
- return false;
10830
- } catch {
10831
- return false;
10832
- }
10833
- }
10834
9291
  /**
10835
9292
  * Parses a GitHub URL to extract repository information.
10836
9293
  */
@@ -10990,6 +9447,21 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
10990
9447
  if (statusCode === 401) throw new ScraperError(`GitHub authentication failed for "${owner}/${repo}". Your token is invalid or expired. Please check your GITHUB_TOKEN or GH_TOKEN environment variable.`, false, error);
10991
9448
  if (statusCode === 403) throw new ScraperError(`GitHub access denied for "${owner}/${repo}". Your token may lack the required permissions, or you may be rate-limited. Please check your GITHUB_TOKEN or GH_TOKEN.`, false, error);
10992
9449
  }
9450
+ /**
9451
+ * Measures scope from the repository root rather than the URL the scrape
9452
+ * started from.
9453
+ *
9454
+ * A `/tree/<branch>` URL names a branch, but the files discovered under it
9455
+ * live at `/blob/<branch>/...` and the wiki at `/wiki`, so measured from the
9456
+ * tree URL the default `subpages` scope rejects every one of them.
9457
+ *
9458
+ * @param options Scraper options naming the GitHub URL the scrape started from.
9459
+ * @returns The repository root URL.
9460
+ */
9461
+ getScopeBaseUrl(options) {
9462
+ const { owner, repo } = this.parseGitHubUrl(options.url);
9463
+ return new URL(`/${owner}/${repo}`, options.url);
9464
+ }
10993
9465
  async processItem(item, options, signal) {
10994
9466
  if (item.url.startsWith("github-file://")) {
10995
9467
  logger.info(`🗑️ Legacy github-file:// URL detected, marking as deleted: ${item.url}`);
@@ -11007,30 +9479,27 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11007
9479
  if (item.depth === 0) {
11008
9480
  const repoInfo = this.parseGitHubUrl(options.url);
11009
9481
  const { owner, repo } = repoInfo;
9482
+ if (repoInfo.isBlob && repoInfo.filePath) {
9483
+ logger.debug(`Single file URL detected: ${owner}/${repo}/${repoInfo.filePath} - indexing file only`);
9484
+ return await this.repoProcessor.process(item, options, headers, signal);
9485
+ }
11010
9486
  logger.debug(`Discovering GitHub repository ${owner}/${repo}`);
11011
9487
  const discoveredLinks = [];
11012
- if ("isBlob" in repoInfo && repoInfo.isBlob && repoInfo.filePath) {
11013
- const { branch = "main", filePath } = repoInfo;
11014
- logger.debug(`Single file URL detected: ${owner}/${repo}/${filePath} - indexing file only`);
11015
- discoveredLinks.push(`https://github.com/${owner}/${repo}/blob/${branch}/${filePath}`);
11016
- return {
11017
- url: item.url,
11018
- links: discoveredLinks,
11019
- status: FetchStatus.SUCCESS
11020
- };
9488
+ if (!repoInfo.subPath) {
9489
+ const wikiUrl = new URL(`/${owner}/${repo}/wiki`, options.url).href;
9490
+ discoveredLinks.push(wikiUrl);
9491
+ logger.debug(`Discovered wiki URL: ${wikiUrl}`);
11021
9492
  }
11022
- const wikiUrl = `${options.url.replace(/\/$/, "")}/wiki`;
11023
- discoveredLinks.push(wikiUrl);
11024
- logger.debug(`Discovered wiki URL: ${wikiUrl}`);
11025
9493
  const { tree, resolvedBranch } = await this.fetchRepositoryTree(repoInfo, headers, signal);
11026
9494
  const fileItems = tree.tree.filter((treeItem) => this.isWithinSubPath(treeItem.path, repoInfo.subPath)).filter((treeItem) => this.shouldProcessFile(treeItem, options));
11027
9495
  logger.debug(`Discovered ${fileItems.length} processable files in repository (branch: ${resolvedBranch})`);
11028
9496
  const fileUrls = fileItems.map((treeItem) => `https://github.com/${owner}/${repo}/blob/${resolvedBranch}/${treeItem.path}`);
11029
9497
  discoveredLinks.push(...fileUrls);
11030
- logger.debug(`Discovery complete: ${fileUrls.length} repo file(s) + 1 wiki URL = ${discoveredLinks.length} total URLs`);
9498
+ logger.debug(`Discovery complete: ${fileUrls.length} repo file(s), ${discoveredLinks.length} total URLs`);
11031
9499
  return {
11032
9500
  url: item.url,
11033
9501
  links: discoveredLinks,
9502
+ isContainer: true,
11034
9503
  status: FetchStatus.SUCCESS
11035
9504
  };
11036
9505
  }
@@ -11048,11 +9517,11 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11048
9517
  status: FetchStatus.SUCCESS
11049
9518
  };
11050
9519
  }
11051
- logger.debug(`No further processing for URL at depth ${item.depth}: ${item.url}`);
9520
+ logger.debug(`Not a GitHub file or wiki page at depth ${item.depth}: ${item.url}`);
11052
9521
  return {
11053
9522
  url: item.url,
11054
9523
  links: [],
11055
- status: FetchStatus.SUCCESS
9524
+ status: FetchStatus.NOT_FOUND
11056
9525
  };
11057
9526
  }
11058
9527
  async scrape(options, progressCallback, signal) {
@@ -11069,8 +9538,7 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11069
9538
  await Promise.all([this.wikiProcessor.cleanup(), this.repoProcessor.cleanup()]);
11070
9539
  }
11071
9540
  };
11072
- //#endregion
11073
- //#region src/utils/archive/TarAdapter.ts
9541
+ // src/utils/archive/TarAdapter.ts
11074
9542
  var TarAdapter = class {
11075
9543
  filePath;
11076
9544
  constructor(filePath) {
@@ -11143,8 +9611,7 @@ var TarAdapter = class {
11143
9611
  return Promise.resolve();
11144
9612
  }
11145
9613
  };
11146
- //#endregion
11147
- //#region src/utils/archive/ZipAdapter.ts
9614
+ // src/utils/archive/ZipAdapter.ts
11148
9615
  var ZipAdapter = class {
11149
9616
  zipfile = null;
11150
9617
  filePath;
@@ -11239,8 +9706,7 @@ var ZipAdapter = class {
11239
9706
  this.entriesCache = null;
11240
9707
  }
11241
9708
  };
11242
- //#endregion
11243
- //#region src/utils/archive/ArchiveFactory.ts
9709
+ // src/utils/archive/ArchiveFactory.ts
11244
9710
  /**
11245
9711
  * Returns an appropriate archive adapter for the given file path based on its
11246
9712
  * extension, or `null` if the file is not a recognized archive format.
@@ -11257,8 +9723,7 @@ async function getArchiveAdapter(filePath) {
11257
9723
  if (ext === ".tar" || ext === ".gz" || ext === ".tgz") return new TarAdapter(filePath);
11258
9724
  return null;
11259
9725
  }
11260
- //#endregion
11261
- //#region src/scraper/strategies/LocalFileStrategy.ts
9726
+ // src/scraper/strategies/LocalFileStrategy.ts
11262
9727
  /**
11263
9728
  * Orders two names by Unicode code point, which is the byte order of their
11264
9729
  * UTF-8 encoding, so the result is the same on every platform and locale.
@@ -11288,9 +9753,6 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11288
9753
  this.pipelines = PipelineFactory.createStandardPipelines(config);
11289
9754
  this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);
11290
9755
  }
11291
- canHandle(url) {
11292
- return url.startsWith("file://");
11293
- }
11294
9756
  async processItem(item, options, _signal) {
11295
9757
  const filePath = (await this.accessPolicy.resolveFileAccess(item.url, options.internalAllowedFileRoots)).filePath;
11296
9758
  let stats = null;
@@ -11504,8 +9966,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11504
9966
  await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));
11505
9967
  }
11506
9968
  };
11507
- //#endregion
11508
- //#region src/scraper/pipelines/capability.ts
9969
+ // src/scraper/pipelines/capability.ts
11509
9970
  /**
11510
9971
  * Builds the single predicate used to decide whether content is worth fetching.
11511
9972
  *
@@ -11525,8 +9986,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11525
9986
  function createMimeTypeCapabilityPredicate(pipelines) {
11526
9987
  return (mimeType) => pipelines.some((pipeline) => pipeline.canProcess(mimeType));
11527
9988
  }
11528
- //#endregion
11529
- //#region src/scraper/strategies/WebScraperStrategy.ts
9989
+ // src/scraper/strategies/WebScraperStrategy.ts
11530
9990
  /**
11531
9991
  * Web scraper strategy that normalizes URLs, fetches content with automatic
11532
9992
  * fetcher selection, and routes content through pipelines. Requires resolved
@@ -11565,14 +10025,6 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
11565
10025
  this.canProcessMimeType = createMimeTypeCapabilityPredicate(this.pipelines);
11566
10026
  this.localFileStrategy = new LocalFileStrategy(config);
11567
10027
  }
11568
- canHandle(url) {
11569
- try {
11570
- const parsedUrl = new URL(url);
11571
- return parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:";
11572
- } catch {
11573
- return false;
11574
- }
11575
- }
11576
10028
  restorePreservedHash(requestedUrl, actualUrl) {
11577
10029
  if (!requestedUrl.includes("#")) return actualUrl;
11578
10030
  try {
@@ -11975,18 +10427,9 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
11975
10427
  ]);
11976
10428
  }
11977
10429
  };
11978
- //#endregion
11979
- //#region src/scraper/strategies/NpmScraperStrategy.ts
10430
+ // src/scraper/strategies/NpmScraperStrategy.ts
11980
10431
  var NpmScraperStrategy = class {
11981
10432
  defaultStrategy;
11982
- canHandle(url) {
11983
- const { hostname } = new URL(url);
11984
- return [
11985
- "npmjs.org",
11986
- "npmjs.com",
11987
- "www.npmjs.com"
11988
- ].includes(hostname);
11989
- }
11990
10433
  constructor(config) {
11991
10434
  this.defaultStrategy = new WebScraperStrategy(config, { urlNormalizerOptions: {
11992
10435
  removeHash: true,
@@ -12004,14 +10447,9 @@ var NpmScraperStrategy = class {
12004
10447
  await this.defaultStrategy.cleanup();
12005
10448
  }
12006
10449
  };
12007
- //#endregion
12008
- //#region src/scraper/strategies/PyPiScraperStrategy.ts
10450
+ // src/scraper/strategies/PyPiScraperStrategy.ts
12009
10451
  var PyPiScraperStrategy = class {
12010
10452
  defaultStrategy;
12011
- canHandle(url) {
12012
- const { hostname } = new URL(url);
12013
- return ["pypi.org", "www.pypi.org"].includes(hostname);
12014
- }
12015
10453
  constructor(config) {
12016
10454
  this.defaultStrategy = new WebScraperStrategy(config, { urlNormalizerOptions: {
12017
10455
  removeHash: true,
@@ -12029,8 +10467,7 @@ var PyPiScraperStrategy = class {
12029
10467
  await this.defaultStrategy.cleanup();
12030
10468
  }
12031
10469
  };
12032
- //#endregion
12033
- //#region src/scraper/ScraperRegistry.ts
10470
+ // src/scraper/ScraperRegistry.ts
12034
10471
  /**
12035
10472
  * Factory for creating scraper strategy instances.
12036
10473
  * Each call to getStrategy() returns a fresh instance to ensure
@@ -12114,8 +10551,7 @@ function isWebUrl(url) {
12114
10551
  return false;
12115
10552
  }
12116
10553
  }
12117
- //#endregion
12118
- //#region src/scraper/ScraperService.ts
10554
+ // src/scraper/ScraperService.ts
12119
10555
  /**
12120
10556
  * Orchestrates document scraping operations using registered scraping strategies.
12121
10557
  * Automatically selects appropriate strategy based on URL patterns.
@@ -12151,8 +10587,7 @@ var ScraperService = class {
12151
10587
  if (cleanupErrorToThrow) throw cleanupErrorToThrow;
12152
10588
  }
12153
10589
  };
12154
- //#endregion
12155
- //#region src/pipeline/PipelineWorker.ts
10590
+ // src/pipeline/PipelineWorker.ts
12156
10591
  /**
12157
10592
  * Executes a single document processing job.
12158
10593
  * Handles scraping, storing documents, and reporting progress/errors via callbacks.
@@ -12219,7 +10654,10 @@ var PipelineWorker = class {
12219
10654
  */
12220
10655
  async recordEmptyPage(job, callbacks, library, version, progress) {
12221
10656
  const { emptyPage } = progress;
12222
- if (!emptyPage) return;
10657
+ if (!emptyPage) {
10658
+ await this.removeDeletedPage(job, callbacks, progress);
10659
+ return;
10660
+ }
12223
10661
  if (emptyPage.pipelineFailed) {
12224
10662
  logger.debug(`[${job.id}] Extraction failed with no content, leaving stored page untouched: ${progress.currentUrl}`);
12225
10663
  return;
@@ -12270,11 +10708,11 @@ var PipelineWorker = class {
12270
10708
  } catch (docError) {
12271
10709
  logger.error(`❌ [${job.id}] Failed to process content ${progress.currentUrl}: ${docError}`);
12272
10710
  await callbacks.onJobError?.(job, docError instanceof Error ? docError : new Error(String(docError)), progress.result);
10711
+ if (docError instanceof EmbeddingError) throw docError;
12273
10712
  }
12274
10713
  }
12275
10714
  };
12276
- //#endregion
12277
- //#region src/pipeline/PipelineManager.ts
10715
+ // src/pipeline/PipelineManager.ts
12278
10716
  /**
12279
10717
  * PipelineManager orchestrates a queue of scraping/indexing jobs.
12280
10718
  * - Controls concurrency, recovery, and job lifecycle
@@ -12751,9 +11189,7 @@ var PipelineManager = class {
12751
11189
  case PipelineJobStatus.CANCELLED:
12752
11190
  logger.warn(`⚠️ Job ${jobId} cannot be cancelled in its current state: ${job.status}`);
12753
11191
  break;
12754
- default:
12755
- logger.error(`❌ Unhandled job status for cancellation: ${job.status}`);
12756
- break;
11192
+ default: logger.error(`❌ Unhandled job status for cancellation: ${job.status}`);
12757
11193
  }
12758
11194
  }
12759
11195
  /**
@@ -12913,8 +11349,7 @@ var PipelineManager = class {
12913
11349
  logger.debug(`Job ${job.id} progress: ${progress.pagesScraped}/${progress.totalPages} processed, ${progress.pagesIndexed} indexed`);
12914
11350
  }
12915
11351
  };
12916
- //#endregion
12917
- //#region src/store/DocumentManagementClient.ts
11352
+ // src/store/DocumentManagementClient.ts
12918
11353
  /**
12919
11354
  * How long the health report waits for the worker's embedding config before the
12920
11355
  * last known value stands in; a worker that drops traffic would otherwise hold
@@ -13058,8 +11493,7 @@ var DocumentManagementClient = class {
13058
11493
  });
13059
11494
  }
13060
11495
  };
13061
- //#endregion
13062
- //#region src/utils/version.ts
11496
+ // src/utils/version.ts
13063
11497
  /**
13064
11498
  * Version label classification and comparison utilities.
13065
11499
  *
@@ -13180,14 +11614,37 @@ function compareVersionsDescending(a, b) {
13180
11614
  function sortVersionsDescending(versions) {
13181
11615
  return [...versions].sort(compareVersionsDescending);
13182
11616
  }
13183
- //#endregion
13184
- //#region src/store/assembly/strategies/HierarchicalAssemblyStrategy.ts
11617
+ // src/store/assembly/strategies/HierarchicalAssemblyStrategy.ts
11618
+ /** Returns a chunk's path, or the root path when it has none. */
11619
+ function pathOf(chunk) {
11620
+ return chunk.metadata.path ?? [];
11621
+ }
11622
+ /** Returns whether `path` begins with every segment of `prefix`. */
11623
+ function startsWithPath(path, prefix) {
11624
+ return path.length >= prefix.length && prefix.every((segment, index) => segment === path[index]);
11625
+ }
11626
+ /** Returns whether two paths have the same segments. */
11627
+ function isSamePath(a, b) {
11628
+ return a.length === b.length && startsWithPath(a, b);
11629
+ }
11630
+ /** Returns the longest path that every given path starts with. */
11631
+ function commonPrefix(paths) {
11632
+ const [first = [], ...rest] = paths;
11633
+ let length = 0;
11634
+ while (length < first.length && rest.every((path) => path[length] === first[length])) length++;
11635
+ return first.slice(0, length);
11636
+ }
11637
+ /** Returns whether a chunk opens a declaration such as a class or namespace. */
11638
+ function isStructural(chunk) {
11639
+ return chunk.metadata.types?.includes("structural") ?? false;
11640
+ }
13185
11641
  /**
13186
11642
  * Assembly strategy for structured content (source code, JSON, config files).
13187
11643
  *
13188
- * Uses selective subtree reassembly: for single matches, walks up the complete parent
13189
- * hierarchy to the root. For multiple matches within the same document, finds the common
13190
- * ancestor and reconstructs only the relevant subtrees, avoiding inclusion of excessive
11644
+ * Uses selective subtree reassembly: a single match brings the structure that contains
11645
+ * it, such as its class or JSON object, with the opening and closing chunks of the scopes
11646
+ * around it. Multiple matches within the same document bring only their own subtrees,
11647
+ * inside the opening and closing chunks of their scopes, avoiding inclusion of excessive
13191
11648
  * unrelated content. Simple concatenation leverages splitter concatenation guarantees.
13192
11649
  */
13193
11650
  var HierarchicalAssemblyStrategy = class {
@@ -13206,9 +11663,9 @@ var HierarchicalAssemblyStrategy = class {
13206
11663
  return false;
13207
11664
  }
13208
11665
  /**
13209
- * Selects chunks using selective subtree reassembly for multiple matches within documents.
13210
- * For single matches: uses existing parent chain logic.
13211
- * For multiple matches in same document: finds common ancestor and reconstructs minimal subtree.
11666
+ * Selects the chunks to reassemble around the matches of each document.
11667
+ * For a single match: the subtree of its container plus the boundaries of the enclosing scopes.
11668
+ * For multiple matches in same document: each match's subtree plus the boundaries of its scopes.
13212
11669
  */
13213
11670
  async selectChunks(library, version, initialChunks, documentStore) {
13214
11671
  if (initialChunks.length === 0) return [];
@@ -13220,36 +11677,19 @@ var HierarchicalAssemblyStrategy = class {
13220
11677
  chunksByDocument.get(url)?.push(chunk);
13221
11678
  }
13222
11679
  const allChunkIds = /* @__PURE__ */ new Set();
13223
- for (const [_url, documentChunks] of Array.from(chunksByDocument.entries())) if (documentChunks.length === 1) {
13224
- const matched = documentChunks[0];
13225
- let promotedAncestor = await this.findStructuralAncestor(library, version, matched, documentStore) ?? matched;
13226
- try {
13227
- const path = matched.metadata.path || [];
13228
- if (promotedAncestor === matched && path.length > 0) {
13229
- const topLevelPath = [path[0]];
13230
- const containerIds = await this.findContainerChunks(library, version, matched, topLevelPath, documentStore);
13231
- if (containerIds.length > 0) {
13232
- const topChunks = await documentStore.findChunksByIds(library, version, [containerIds[0]]);
13233
- if (topChunks.length > 0) promotedAncestor = topChunks[0];
13234
- }
13235
- }
13236
- } catch (e) {
13237
- logger.warn(`Top-level function promotion failed for chunk ${matched.id}: ${e}`);
13238
- }
13239
- allChunkIds.add(matched.id);
13240
- const ancestorParentChain = await this.walkToRoot(library, version, promotedAncestor, documentStore);
13241
- for (const id of ancestorParentChain) allChunkIds.add(id);
13242
- const subtreeIds = await this.findSubtreeChunks(library, version, promotedAncestor, documentStore);
13243
- for (const id of subtreeIds) allChunkIds.add(id);
13244
- } else {
11680
+ for (const [url, documentChunks] of Array.from(chunksByDocument.entries())) {
13245
11681
  for (const matched of documentChunks) allChunkIds.add(matched.id);
13246
- const subtreeIds = await this.selectSubtreeChunks(library, version, documentChunks, documentStore);
13247
- for (const id of subtreeIds) allChunkIds.add(id);
11682
+ const pageChunks = await documentStore.findChunksByUrl(library, version, url);
11683
+ const matchedIds = new Set(documentChunks.map((matched) => matched.id));
11684
+ const matchIndices = pageChunks.flatMap((chunk, index) => matchedIds.has(chunk.id) ? [index] : []);
11685
+ if (matchIndices.length === 0) continue;
11686
+ const selected = documentChunks.length === 1 ? this.selectAroundMatch(pageChunks, matchIndices[0], MimeTypeUtils.isJson(documentChunks[0].content_type ?? "")) : this.selectAroundMatches(pageChunks, matchIndices);
11687
+ for (const chunk of selected) allChunkIds.add(chunk.id);
13248
11688
  }
13249
11689
  const chunkIds = Array.from(allChunkIds);
13250
11690
  return await documentStore.findChunksByIds(library, version, chunkIds);
13251
11691
  } catch (error) {
13252
- logger.warn(`Hierarchical parent chain walking failed, falling back to basic selection: ${error}`);
11692
+ logger.warn(`Hierarchical chunk selection failed, falling back to basic selection: ${error}`);
13253
11693
  return this.fallbackSelection(library, version, initialChunks, documentStore);
13254
11694
  }
13255
11695
  }
@@ -13257,189 +11697,201 @@ var HierarchicalAssemblyStrategy = class {
13257
11697
  * Assembles chunks using simple concatenation.
13258
11698
  * Relies on splitter concatenation guarantees - chunks are designed to join seamlessly.
13259
11699
  */
13260
- assembleContent(chunks, debug = false) {
13261
- if (debug) return chunks.map((chunk) => `=== #${chunk.id} ${chunk.metadata.path?.join("/")} [${chunk.metadata.level}] ===\n` + chunk.content).join("");
11700
+ assembleContent(chunks) {
13262
11701
  return chunks.map((chunk) => chunk.content).join("");
13263
11702
  }
13264
11703
  /**
13265
- * Walks up the parent hierarchy from a chunk to collect the complete parent chain.
13266
- * Includes the chunk itself and every parent until reaching the root.
13267
- * Protected against circular references and infinite loops.
11704
+ * Selects the chunks around a single match: the subtree of its container (for code
11705
+ * its structural ancestor, such as its class; for JSON the object or array holding
11706
+ * it) and the opening and closing chunks of the scopes that enclose that container.
13268
11707
  *
13269
- * Handles hierarchical gaps by attempting to find ancestors at progressively shorter
13270
- * path lengths when direct parent lookup fails (e.g., when intermediate chunks
13271
- * have been merged or are missing).
13272
- */
13273
- async walkToRoot(library, version, chunk, documentStore) {
13274
- const chainIds = [];
13275
- const visited = /* @__PURE__ */ new Set();
13276
- let currentChunk = chunk;
13277
- const { maxParentChainDepth } = this.config.assembly;
13278
- let depth = 0;
13279
- while (currentChunk && depth < maxParentChainDepth) {
13280
- const currentId = currentChunk.id;
13281
- if (visited.has(currentId)) {
13282
- logger.warn(`Circular reference detected in parent chain for chunk ${currentId}`);
13283
- break;
13284
- }
13285
- visited.add(currentId);
13286
- chainIds.push(currentId);
13287
- depth++;
13288
- let parentChunk = await documentStore.findParentChunk(library, version, currentId);
13289
- if (!parentChunk) parentChunk = await this.findAncestorWithGaps(library, version, currentChunk.url, currentChunk.metadata.path ?? [], documentStore);
13290
- currentChunk = parentChunk;
13291
- }
13292
- if (depth >= maxParentChainDepth) logger.warn(`Maximum parent chain depth (${maxParentChainDepth}) reached for chunk ${chunk.id}`);
13293
- return chainIds;
13294
- }
13295
- /**
13296
- * Attempts to find ancestors when there are gaps in the hierarchy.
13297
- * Tries progressively shorter path prefixes to find existing ancestor chunks.
13298
- */
13299
- async findAncestorWithGaps(library, version, url, path, documentStore) {
13300
- if (path.length <= 1) return null;
13301
- for (let pathLength = path.length - 1; pathLength > 0; pathLength--) {
13302
- const ancestorPath = path.slice(0, pathLength);
13303
- try {
13304
- const potentialAncestors = await this.findChunksByPathPrefix(library, version, url, ancestorPath, documentStore);
13305
- if (potentialAncestors.length > 0) return potentialAncestors[0];
13306
- } catch (error) {
13307
- logger.debug(`Failed to find ancestor with path ${ancestorPath.join("/")}: ${error}`);
13308
- }
13309
- }
13310
- return null;
13311
- }
13312
- /**
13313
- * Finds chunks that have an exact path match or are prefixes of the given path.
13314
- * This is a more flexible version of findChunksByPath that can handle gaps.
11708
+ * @param pageChunks All chunks of one page, in document order.
11709
+ * @param matchIndex Position of the match.
11710
+ * @param isJson Whether the page is JSON.
13315
11711
  */
13316
- async findChunksByPathPrefix(library, version, url, targetPath, documentStore) {
13317
- try {
13318
- const allChunks = await documentStore.findChunksByUrl(library, version, url);
13319
- if (allChunks.length === 0) return [];
13320
- return allChunks.filter((chunk) => {
13321
- const chunkPath = chunk.metadata.path || [];
13322
- if (chunk.url !== url) return false;
13323
- if (chunkPath.length !== targetPath.length) return false;
13324
- return chunkPath.every((part, index) => part === targetPath[index]);
13325
- });
13326
- } catch (error) {
13327
- logger.warn(`Error in findChunksByPathPrefix: ${error}`);
13328
- return [];
13329
- }
11712
+ selectAroundMatch(pageChunks, matchIndex, isJson) {
11713
+ const containerIndex = isJson ? this.findJsonContainer(pageChunks, matchIndex) : this.findCodeContainer(pageChunks, matchIndex);
11714
+ return this.selectSubtree(pageChunks, containerIndex);
13330
11715
  }
13331
11716
  /**
13332
- * Finds the nearest structural ancestor (types includes "structural") for a chunk.
13333
- * If none exists (e.g. the matched chunk itself is structural or at top), returns null.
13334
- */
13335
- async findStructuralAncestor(library, version, chunk, documentStore) {
13336
- let current = chunk;
13337
- const isStructural = (c) => !!c && Array.isArray(c.metadata?.types) && c.metadata.types.includes("structural");
13338
- if (isStructural(current)) return current;
13339
- while (true) {
13340
- const parent = await documentStore.findParentChunk(library, version, current.id);
13341
- if (!parent) return null;
13342
- if (isStructural(parent)) return parent;
13343
- current = parent;
11717
+ * Selects the chunks around several matches in one page: each match's subtree with
11718
+ * the opening and closing chunks of the scopes that enclose it, but none of their
11719
+ * other members. Within the scope that holds all matches, the chunks at that scope's
11720
+ * own path, such as fields or statements, are included as well.
11721
+ *
11722
+ * @param pageChunks All chunks of one page, in document order.
11723
+ * @param matchIndices Positions of the matches, in document order.
11724
+ */
11725
+ selectAroundMatches(pageChunks, matchIndices) {
11726
+ const selected = matchIndices.flatMap((index) => this.selectSubtree(pageChunks, index));
11727
+ const commonPath = commonPrefix(matchIndices.map((index) => pathOf(pageChunks[index])));
11728
+ const commonScope = commonPath.length > 0 ? this.findScopeStart(pageChunks, matchIndices[0], commonPath) : void 0;
11729
+ if (commonScope !== void 0) {
11730
+ const scope = this.containerRange(pageChunks, commonScope);
11731
+ for (const chunk of pageChunks.slice(scope.start, scope.end)) if (isSamePath(pathOf(chunk), commonPath)) selected.push(chunk);
11732
+ }
11733
+ return selected;
11734
+ }
11735
+ /**
11736
+ * Selects the subtree that the chunk at `index` opens, through its closing chunk, and
11737
+ * the opening and closing chunks of the scopes that enclose it. A chunk that opens
11738
+ * nothing, such as a field or statement that follows other members of its scope, comes
11739
+ * back on its own inside its scope's opening and closing chunks.
11740
+ */
11741
+ selectSubtree(pageChunks, index) {
11742
+ if (!this.opensContainer(pageChunks, index)) {
11743
+ const scopeStart = this.findScopeStart(pageChunks, index, pathOf(pageChunks[index]));
11744
+ const scope = scopeStart === void 0 ? [] : this.scopeBoundaries(pageChunks, this.containerRange(pageChunks, scopeStart));
11745
+ return [
11746
+ pageChunks[index],
11747
+ ...scope,
11748
+ ...this.findEnclosingScopeBoundaries(pageChunks, scopeStart ?? index)
11749
+ ];
13344
11750
  }
11751
+ const subtree = this.containerRange(pageChunks, index);
11752
+ return [...pageChunks.slice(subtree.start, subtree.end), ...this.findEnclosingScopeBoundaries(pageChunks, subtree.start)];
13345
11753
  }
13346
11754
  /**
13347
- * Selects chunks for selective subtree reassembly when multiple matches exist in the same document.
13348
- * Finds the common ancestor and reconstructs only the relevant subtrees.
11755
+ * Returns whether the chunk at `index` opens a container: no chunk nested deeper in its
11756
+ * path comes before it in the run of chunks inside that path. A field between two
11757
+ * methods carries its class's path but follows the first method, so it opens nothing.
13349
11758
  */
13350
- async selectSubtreeChunks(library, version, documentChunks, documentStore) {
13351
- const chunkIds = /* @__PURE__ */ new Set();
13352
- const commonAncestorPath = this.findCommonAncestorPath(documentChunks);
13353
- if (commonAncestorPath.length === 0) {
13354
- logger.warn("No common ancestor found for multiple matches, using individual parent chains");
13355
- for (const chunk of documentChunks) {
13356
- const parentChain = await this.walkToRoot(library, version, chunk, documentStore);
13357
- for (const id of parentChain) chunkIds.add(id);
13358
- }
13359
- return Array.from(chunkIds);
11759
+ opensContainer(pageChunks, index) {
11760
+ const path = pathOf(pageChunks[index]);
11761
+ if (path.length === 0) return true;
11762
+ for (let previous = index - 1; previous >= 0; previous--) {
11763
+ const previousPath = pathOf(pageChunks[previous]);
11764
+ if (!startsWithPath(previousPath, path)) return true;
11765
+ if (previousPath.length > path.length) return false;
13360
11766
  }
13361
- const containerIds = await this.findContainerChunks(library, version, documentChunks[0], commonAncestorPath, documentStore);
13362
- for (const id of containerIds) chunkIds.add(id);
13363
- for (const chunk of documentChunks) {
13364
- const subtreeIds = await this.findSubtreeChunks(library, version, chunk, documentStore);
13365
- for (const id of subtreeIds) chunkIds.add(id);
13366
- }
13367
- return Array.from(chunkIds);
11767
+ return true;
13368
11768
  }
13369
11769
  /**
13370
- * Finds the common ancestor path from a list of chunks by finding the longest common prefix.
11770
+ * Finds the code container to reconstruct for a single match: the innermost scope
11771
+ * around the match, the match's own included, whose opening chunk is structural (a
11772
+ * class, interface, enum or namespace). Without one, as for a match in a top-level
11773
+ * function, it is the top-level element named by the first path segment, otherwise
11774
+ * the match itself.
11775
+ *
11776
+ * @param pageChunks All chunks of one page, in document order.
11777
+ * @param matchIndex Position of the match.
11778
+ * @returns The position of the container's opening chunk.
13371
11779
  */
13372
- findCommonAncestorPath(chunks) {
13373
- if (chunks.length === 0) return [];
13374
- if (chunks.length === 1) return chunks[0].metadata.path ?? [];
13375
- const paths = chunks.map((chunk) => chunk.metadata.path ?? []);
13376
- if (paths.length === 0) return [];
13377
- const minLength = Math.min(...paths.map((path) => path.length));
13378
- const commonPrefix = [];
13379
- for (let i = 0; i < minLength; i++) {
13380
- const currentElement = paths[0][i];
13381
- if (paths.every((path) => path[i] === currentElement)) commonPrefix.push(currentElement);
13382
- else break;
11780
+ findCodeContainer(pageChunks, matchIndex) {
11781
+ const path = pathOf(pageChunks[matchIndex]);
11782
+ let topLevel;
11783
+ for (let length = path.length; length > 0; length--) {
11784
+ const start = this.findScopeStart(pageChunks, matchIndex, path.slice(0, length));
11785
+ if (start === void 0) continue;
11786
+ if (isStructural(pageChunks[start])) return start;
11787
+ if (length === 1) topLevel = start;
13383
11788
  }
13384
- return commonPrefix;
11789
+ return topLevel ?? matchIndex;
13385
11790
  }
13386
11791
  /**
13387
- * Finds the container chunks (opening/closing) for a given ancestor path.
11792
+ * Finds the JSON object or array to reconstruct for a single match: the one the match
11793
+ * opens, otherwise the one that contains it. Unlike code, a match is not promoted to
11794
+ * the top level, which in JSON is the whole document.
11795
+ *
11796
+ * The JSON splitter puts a key whose value is an object or array at the key's path,
11797
+ * followed by a chunk at the same path that begins with the opening bracket: the
11798
+ * bracket alone, or, past `splitter.json.maxNestingDepth`, the whole value serialized
11799
+ * as text. That chunk marks an object or array even when it is empty. A primitive
11800
+ * value never begins with a bracket.
11801
+ *
11802
+ * @param pageChunks All chunks of one page, in document order.
11803
+ * @param matchIndex Position of the match.
11804
+ * @returns The position of a chunk that opens the container.
11805
+ */
11806
+ findJsonContainer(pageChunks, matchIndex) {
11807
+ const path = pathOf(pageChunks[matchIndex]);
11808
+ const own = this.containerRange(pageChunks, matchIndex);
11809
+ if (pageChunks.slice(own.start, own.end).some((chunk) => isSamePath(pathOf(chunk), path) && /^[[{]/.test(chunk.content.trim())) || path.length <= 1) return matchIndex;
11810
+ return this.findScopeStart(pageChunks, own.start, path.slice(0, -1)) ?? matchIndex;
11811
+ }
11812
+ /**
11813
+ * Finds the chunks that open and close each scope enclosing a container, innermost
11814
+ * first and up to `assembly.maxParentChainDepth` scopes. A scope opens where the run
11815
+ * of chunks inside its path begins, so the members and statements between its
11816
+ * declaration and the container are left out. A scope with no chunk at its own path,
11817
+ * such as a level the splitter skipped, adds nothing.
11818
+ *
11819
+ * @param pageChunks All chunks of one page, in document order.
11820
+ * @param containerStart Position of the container's first chunk.
11821
+ * @returns The scopes' opening and closing chunks.
13388
11822
  */
13389
- async findContainerChunks(library, version, referenceChunk, ancestorPath, documentStore) {
13390
- const containerIds = [];
13391
- try {
13392
- const ancestorChunks = await this.findChunksByExactPath(library, version, referenceChunk.url, ancestorPath, documentStore);
13393
- for (const chunk of ancestorChunks) containerIds.push(chunk.id);
13394
- } catch (error) {
13395
- logger.warn(`Failed to find container chunks for path ${ancestorPath.join("/")}: ${error}`);
11823
+ findEnclosingScopeBoundaries(pageChunks, containerStart) {
11824
+ const path = pathOf(pageChunks[containerStart]);
11825
+ const { maxParentChainDepth } = this.config.assembly;
11826
+ const boundaries = [];
11827
+ let index = containerStart;
11828
+ for (let length = path.length - 1; length > 0 && path.length - length < maxParentChainDepth; length--) {
11829
+ const start = this.findScopeStart(pageChunks, index, path.slice(0, length));
11830
+ if (start === void 0) continue;
11831
+ index = start;
11832
+ boundaries.push(...this.scopeBoundaries(pageChunks, this.containerRange(pageChunks, start)));
13396
11833
  }
13397
- return containerIds;
11834
+ return boundaries;
13398
11835
  }
13399
11836
  /**
13400
- * Finds all chunks with an exact path match within a specific document.
13401
- * More efficient than searching across all chunks by first filtering by URL.
11837
+ * Finds where the scope with the given path opens, looking back from the chunk at
11838
+ * `index`: the first chunk of the run of chunks inside that path.
11839
+ *
11840
+ * @param pageChunks All chunks of one page, in document order.
11841
+ * @param index Position of a chunk inside the scope.
11842
+ * @param scopePath Path of the scope.
11843
+ * @returns The position of the scope's opening chunk, or undefined when the run does
11844
+ * not begin with a chunk at the scope's own path.
13402
11845
  */
13403
- async findChunksByExactPath(library, version, url, path, documentStore) {
13404
- try {
13405
- if (path.length === 0) {
13406
- logger.debug("Root path requested - no chunks found");
13407
- return [];
13408
- }
13409
- const allChunks = await documentStore.findChunksByUrl(library, version, url);
13410
- if (allChunks.length === 0) return [];
13411
- const matchingChunks = allChunks.filter((chunk) => {
13412
- const chunkPath = chunk.metadata.path ?? [];
13413
- if (chunkPath.length !== path.length) return false;
13414
- return chunkPath.every((part, index) => part === path[index]);
13415
- });
13416
- logger.debug(`Found ${matchingChunks.length} chunks for exact path: ${path.join("/")}`);
13417
- return matchingChunks;
13418
- } catch (error) {
13419
- logger.warn(`Error finding chunks for exact path ${path.join("/")}: ${error}`);
13420
- return [];
13421
- }
11846
+ findScopeStart(pageChunks, index, scopePath) {
11847
+ let start = index;
11848
+ while (start > 0 && startsWithPath(pathOf(pageChunks[start - 1]), scopePath)) start--;
11849
+ return isSamePath(pathOf(pageChunks[start]), scopePath) ? start : void 0;
13422
11850
  }
13423
11851
  /**
13424
- * Finds all chunks in the subtree rooted at the given chunk.
13425
- */
13426
- async findSubtreeChunks(library, version, rootChunk, documentStore) {
13427
- const subtreeIds = [];
13428
- const visited = /* @__PURE__ */ new Set();
13429
- const queue = [rootChunk];
13430
- while (queue.length > 0) {
13431
- const currentId = queue.shift().id;
13432
- if (visited.has(currentId)) continue;
13433
- visited.add(currentId);
13434
- subtreeIds.push(currentId);
13435
- try {
13436
- const children = await documentStore.findChildChunks(library, version, currentId, 1e3);
13437
- queue.push(...children);
13438
- } catch (error) {
13439
- logger.warn(`Failed to find children for chunk ${currentId}: ${error}`);
13440
- }
13441
- }
13442
- return subtreeIds;
11852
+ * Returns the chunks that open and close a scope: those at the scope's own path before
11853
+ * its first nested member (a class declaration, or a JSON key and its bracket) and
11854
+ * after its last one (a closing brace). A scope without nested members has none.
11855
+ *
11856
+ * @param pageChunks All chunks of one page, in document order.
11857
+ * @param scope Range of the scope, as found by `containerRange`.
11858
+ */
11859
+ scopeBoundaries(pageChunks, scope) {
11860
+ const depth = pathOf(pageChunks[scope.start]).length;
11861
+ const isOwn = (index) => pathOf(pageChunks[index]).length === depth;
11862
+ let firstNested = scope.start;
11863
+ while (firstNested < scope.end && isOwn(firstNested)) firstNested++;
11864
+ if (firstNested === scope.end) return [];
11865
+ let lastNested = scope.end - 1;
11866
+ while (isOwn(lastNested)) lastNested--;
11867
+ return [...pageChunks.slice(scope.start, firstNested), ...pageChunks.slice(lastNested + 1, scope.end)];
11868
+ }
11869
+ /**
11870
+ * Finds the container that the chunk at `index` belongs to. The container opens with
11871
+ * the chunk and the chunks right before it that carry the same path (such as a JSON
11872
+ * key and its bracket), and holds the chunks right after it whose path starts with
11873
+ * that path. The run ends at the first chunk outside the container, so it holds the
11874
+ * nested members and the closing chunk, which repeats the container's path, but no
11875
+ * unrelated code. A chunk with an empty path is global code and contains nothing else.
11876
+ *
11877
+ * @param pageChunks All chunks of one page, in document order.
11878
+ * @param index Position of a chunk that opens the container.
11879
+ * @returns The container's range in `pageChunks`.
11880
+ */
11881
+ containerRange(pageChunks, index) {
11882
+ const rootPath = pathOf(pageChunks[index]);
11883
+ if (rootPath.length === 0) return {
11884
+ start: index,
11885
+ end: index + 1
11886
+ };
11887
+ let start = index;
11888
+ while (start > 0 && isSamePath(pathOf(pageChunks[start - 1]), rootPath)) start--;
11889
+ let end = index + 1;
11890
+ while (end < pageChunks.length && startsWithPath(pathOf(pageChunks[end]), rootPath)) end++;
11891
+ return {
11892
+ start,
11893
+ end
11894
+ };
13443
11895
  }
13444
11896
  /**
13445
11897
  * Fallback selection method when parent chain walking fails.
@@ -13462,8 +11914,7 @@ var HierarchicalAssemblyStrategy = class {
13462
11914
  return await documentStore.findChunksByIds(library, version, Array.from(chunkIds));
13463
11915
  }
13464
11916
  };
13465
- //#endregion
13466
- //#region src/store/assembly/strategies/MarkdownAssemblyStrategy.ts
11917
+ // src/store/assembly/strategies/MarkdownAssemblyStrategy.ts
13467
11918
  /**
13468
11919
  * Assembly strategy that preserves the current behavior for markdown and text content.
13469
11920
  *
@@ -13525,8 +11976,7 @@ var MarkdownAssemblyStrategy = class {
13525
11976
  return relatedIds;
13526
11977
  }
13527
11978
  };
13528
- //#endregion
13529
- //#region src/store/assembly/ContentAssemblyStrategyFactory.ts
11979
+ // src/store/assembly/ContentAssemblyStrategyFactory.ts
13530
11980
  /**
13531
11981
  * Creates the appropriate assembly strategy based on content MIME type.
13532
11982
  *
@@ -13540,8 +11990,7 @@ function createContentAssemblyStrategy(mimeType, config) {
13540
11990
  for (const strategy of strategies) if (strategy.canHandle(mimeType)) return strategy;
13541
11991
  return new MarkdownAssemblyStrategy(config);
13542
11992
  }
13543
- //#endregion
13544
- //#region src/store/DocumentRetrieverService.ts
11993
+ // src/store/DocumentRetrieverService.ts
13545
11994
  var DocumentRetrieverService = class {
13546
11995
  documentStore;
13547
11996
  config;
@@ -13636,15 +12085,14 @@ var DocumentRetrieverService = class {
13636
12085
  return clusters;
13637
12086
  }
13638
12087
  };
13639
- //#endregion
13640
- //#region src/store/applyMigrations.ts
12088
+ // src/store/applyMigrations.ts
13641
12089
  var MIGRATIONS_DIR = path.join(getProjectRoot(), "db", "migrations");
13642
12090
  var MIGRATIONS_TABLE = "_schema_migrations";
13643
12091
  var MIGRATION_STEP_MARKER = /^\s*--\s*@migration-step\s+(.+?)\s*$/;
13644
12092
  var VECTOR_PARTITION_MIGRATION = "014-rebuild-vector-partition-keys.sql";
13645
12093
  var DEFAULT_VECTOR_DIMENSION = 1536;
13646
12094
  var VECTOR_DIMENSION_TOKEN = "__DOCUMENTS_VEC_DIMENSION__";
13647
- var WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
12095
+ var WAL_SIZE_LIMIT_BYTES = 67108864;
13648
12096
  /**
13649
12097
  * Splits migration SQL into executable blocks using full-line migration markers.
13650
12098
  * SQL before the first marker is treated as an implicit prepare block, and SQL
@@ -13817,8 +12265,7 @@ async function applyMigrations(db, options) {
13817
12265
  logger.warn("⚠️ Could not apply all production database settings");
13818
12266
  }
13819
12267
  }
13820
- //#endregion
13821
- //#region src/store/DocumentStore.ts
12268
+ // src/store/DocumentStore.ts
13822
12269
  /**
13823
12270
  * How many full-text candidates are sorted by score alone before the
13824
12271
  * deterministic tie-break, as a multiple of the candidates kept. Sorting every
@@ -14073,8 +12520,12 @@ var DocumentStore = class {
14073
12520
  WHERE l.name = ?
14074
12521
  AND COALESCE(v.name, '') = COALESCE(?, '')
14075
12522
  AND p.url = ?
12523
+ -- A child's path is the parent's path plus one element. Compare the path
12524
+ -- without its last element as JSON instead of using LIKE, so ["AB","X"]
12525
+ -- is never a child of ["A"] and % or _ in a segment stay literal.
12526
+ -- The length check keeps an empty-path chunk from matching an empty parent.
14076
12527
  AND json_array_length(json_extract(d.metadata, '$.path')) = ?
14077
- AND json_extract(d.metadata, '$.path') LIKE ? || '%'
12528
+ AND json_remove(json_extract(d.metadata, '$.path'), '$[#-1]') = json(?)
14078
12529
  AND d.sort_order > (SELECT sort_order FROM documents WHERE id = ?)
14079
12530
  ORDER BY d.sort_order
14080
12531
  LIMIT ?
@@ -14197,7 +12648,10 @@ var DocumentStore = class {
14197
12648
  const currentDimension = String(this.dbDimension);
14198
12649
  const modelChanged = stored.model !== currentModel;
14199
12650
  const dimensionChanged = stored.dimension !== null && stored.dimension !== currentDimension;
14200
- if (modelChanged || dimensionChanged) throw new EmbeddingModelChangedError(stored.model, stored.dimension ?? "unknown", currentModel, currentDimension);
12651
+ if (modelChanged || dimensionChanged) {
12652
+ const currentDimensionKnown = !modelChanged || this.embeddingConfig.dimensions !== null || isVectorDimensionExplicit(this.config);
12653
+ throw new EmbeddingModelChangedError(stored.model, stored.dimension, currentModel, currentDimensionKnown ? currentDimension : null);
12654
+ }
14201
12655
  }
14202
12656
  /**
14203
12657
  * Invalidates all existing embedding vectors after a confirmed model/dimension change.
@@ -14947,7 +13401,7 @@ var DocumentStore = class {
14947
13401
  const modelSpec = this.embeddingConfig?.modelSpec ?? "unknown";
14948
13402
  const hints = [this.getEmbeddingErrorHint(error), this.embeddingConfig ? "Verify embedding provider configuration, model availability, credentials, quota, request size, and backend logs." : null].filter((hint) => hint !== null);
14949
13403
  const hintText = hints.length > 0 ? `\n ${hints.join("\n ")}` : "";
14950
- return new ConnectionError(`Failed to generate embeddings for ${context.url} using ${modelSpec}.\n Batch ${context.batchIndex}: ${context.batchTextCount} text(s), ${context.batchChars} chars, ${context.totalChunks} page chunk(s).\n Config: batchSize=${this.embeddingBatchSize}, batchChars=${this.embeddingBatchChars}, vectorDimension=${this.dbDimension}.` + hintText, error);
13404
+ return new EmbeddingError(`Failed to generate embeddings for ${context.url} using ${modelSpec}.\n Batch ${context.batchIndex}: ${context.batchTextCount} text(s), ${context.batchChars} chars, ${context.totalChunks} page chunk(s).\n Config: batchSize=${this.embeddingBatchSize}, batchChars=${this.embeddingBatchChars}, vectorDimension=${this.dbDimension}.` + hintText, error);
14951
13405
  }
14952
13406
  /**
14953
13407
  * Creates embeddings for an array of texts with automatic retry logic for size-related errors.
@@ -14967,24 +13421,26 @@ var DocumentStore = class {
14967
13421
  if (embeddings === null) throw new StoreError("Embeddings are not initialized");
14968
13422
  return await embeddings.embedDocuments(texts);
14969
13423
  } catch (error) {
14970
- if (this.isInputSizeError(error)) if (texts.length > 1) {
14971
- const midpoint = Math.floor(texts.length / 2);
14972
- const firstHalf = texts.slice(0, midpoint);
14973
- const secondHalf = texts.slice(midpoint);
14974
- if (!isRetry) logger.warn(`⚠️ Batch of ${texts.length} texts exceeded size limit, splitting into ${firstHalf.length} + ${secondHalf.length}`);
14975
- const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true, false), this.embedDocumentsWithRetry(secondHalf, true, false)]);
14976
- return [...firstEmbeddings, ...secondEmbeddings];
14977
- } else {
14978
- if (hasTruncatedSingleText) throw error;
14979
- const text = texts[0];
14980
- const midpoint = Math.floor(text.length / 2);
14981
- const firstHalf = text.substring(0, midpoint);
14982
- if (!isRetry) logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars).`);
14983
- try {
14984
- return await this.embedDocumentsWithRetry([firstHalf], true, true);
14985
- } catch (retryError) {
14986
- logger.error(`❌ Failed to embed even after splitting. Original length: ${text.length}`);
14987
- throw retryError;
13424
+ if (this.isInputSizeError(error)) {
13425
+ if (texts.length > 1) {
13426
+ const midpoint = Math.floor(texts.length / 2);
13427
+ const firstHalf = texts.slice(0, midpoint);
13428
+ const secondHalf = texts.slice(midpoint);
13429
+ 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)]);
13431
+ 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
+ }
14988
13444
  }
14989
13445
  }
14990
13446
  throw error;
@@ -15481,7 +13937,14 @@ var DocumentStore = class {
15481
13937
  }
15482
13938
  }
15483
13939
  /**
15484
- * Finds child chunks of a given document based on path hierarchy.
13940
+ * Finds the child chunks of a chunk: the chunks on the same page, after it in
13941
+ * document order, whose path extends its path by exactly one element.
13942
+ *
13943
+ * @param library Library name.
13944
+ * @param version Version label.
13945
+ * @param id ID of the parent chunk.
13946
+ * @param limit Maximum number of children to return.
13947
+ * @returns The children in document order, or an empty array if the parent does not exist.
15485
13948
  */
15486
13949
  async findChildChunks(library, version, id, limit) {
15487
13950
  try {
@@ -15776,8 +14239,7 @@ var DocumentStore = class {
15776
14239
  }
15777
14240
  }
15778
14241
  };
15779
- //#endregion
15780
- //#region src/store/DocumentManagementService.ts
14242
+ // src/store/DocumentManagementService.ts
15781
14243
  /** Upper bound on the pages listed when a path matches more than one. */
15782
14244
  var MAX_AMBIGUOUS_PAGE_MATCHES = 10;
15783
14245
  /**
@@ -16322,7 +14784,7 @@ var DocumentManagementService = class DocumentManagementService {
16322
14784
  * where to continue.
16323
14785
  *
16324
14786
  * @param library Library name.
16325
- * @param version Version or version range; resolved like `searchStore`.
14787
+ * @param version Version or version range, resolved like `findBestVersion`.
16326
14788
  * @param pathOrUrl Page URL or path.
16327
14789
  * @param options `startChunk` to continue reading, `maxChars` to bound the size.
16328
14790
  * @returns The assembled window and its position within the page.
@@ -16357,7 +14819,7 @@ var DocumentManagementService = class DocumentManagementService {
16357
14819
  * Lists the stored pages of a library version.
16358
14820
  *
16359
14821
  * @param library Library name.
16360
- * @param version Version or version range; resolved like `searchStore`.
14822
+ * @param version Version or version range, resolved like `findBestVersion`.
16361
14823
  * @param options `contains` filters URLs; `limit` (default 50) and `offset` paginate.
16362
14824
  * @returns One page of results and whether more follow.
16363
14825
  */
@@ -16496,8 +14958,7 @@ var DocumentManagementService = class DocumentManagementService {
16496
14958
  return this.store.getVersionComposition(normalized.library, normalized.version);
16497
14959
  }
16498
14960
  };
16499
- //#endregion
16500
- //#region src/services/apiClient.ts
14961
+ // src/services/apiClient.ts
16501
14962
  /**
16502
14963
  * Client for the merged application API (`AppRouter`) served at `/api`.
16503
14964
  *
@@ -16585,8 +15046,7 @@ async function pingApi(api, apiUrl) {
16585
15046
  throw new Error(`Failed to connect to server at ${apiUrl.replace(/\/$/, "")}.\n\nPlease verify the server URL includes the correct port (default 8080) and ends with '/api' (e.g., 'http://localhost:8080/api').`);
16586
15047
  }
16587
15048
  }
16588
- //#endregion
16589
- //#region src/services/backend.ts
15049
+ // src/services/backend.ts
16590
15050
  async function openBackend(options) {
16591
15051
  const closer = new Closer();
16592
15052
  try {
@@ -16675,8 +15135,7 @@ var Closer = class {
16675
15135
  if (firstError !== void 0) throw firstError;
16676
15136
  }
16677
15137
  };
16678
- //#endregion
16679
- //#region src/cli/output.ts
15138
+ // src/cli/output.ts
16680
15139
  function isInteractiveOutput() {
16681
15140
  return !!process.stdout.isTTY && !!process.stderr.isTTY;
16682
15141
  }
@@ -16727,8 +15186,7 @@ function registerGlobalOutputOptions(yargs) {
16727
15186
  function reportCliError(message) {
16728
15187
  logger.error(message);
16729
15188
  }
16730
- //#endregion
16731
- //#region src/cli/commands/compact.ts
15189
+ // src/cli/commands/compact.ts
16732
15190
  function createCompactCommand(cli) {
16733
15191
  cli.command("compact", "Reclaim unused space in the document store (exclusive lock; may block searches)", (yargs) => {
16734
15192
  return yargs.option("force", {
@@ -16769,8 +15227,7 @@ function createCompactCommand(cli) {
16769
15227
  }
16770
15228
  });
16771
15229
  }
16772
- //#endregion
16773
- //#region src/cli/commands/config.ts
15230
+ // src/cli/commands/config.ts
16774
15231
  function validateConfigPath(path) {
16775
15232
  return isValidConfigPath(path);
16776
15233
  }
@@ -16797,10 +15254,11 @@ function createConfigCommand(cli) {
16797
15254
  process.exitCode = 1;
16798
15255
  return;
16799
15256
  }
16800
- const value = getConfigValue(loadConfig(argv, {
15257
+ const config = loadConfig(argv, {
16801
15258
  configPath: argv.config,
16802
15259
  searchDir: argv.storePath
16803
- }), path);
15260
+ });
15261
+ const value = getConfigValue(config, path);
16804
15262
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
16805
15263
  renderScalarOutput(value, argv);
16806
15264
  return;
@@ -16827,10 +15285,11 @@ function createConfigCommand(cli) {
16827
15285
  process.exitCode = 1;
16828
15286
  return;
16829
15287
  }
16830
- const currentValue = getConfigValue(loadConfig(argv, {
15288
+ const config = loadConfig(argv, {
16831
15289
  configPath: argv.config,
16832
15290
  searchDir: argv.storePath
16833
- }), path);
15291
+ });
15292
+ const currentValue = getConfigValue(config, path);
16834
15293
  if (currentValue !== void 0 && currentValue !== null && typeof currentValue === "object" && !Array.isArray(currentValue)) {
16835
15294
  reportCliError(`Error: Config path '${path}' refers to an object. Use a more specific leaf path to set a scalar value.`);
16836
15295
  reportCliError("Hint: Run 'docs-mcp-server config' to inspect the current structure.");
@@ -16848,8 +15307,7 @@ function createConfigCommand(cli) {
16848
15307
  }
16849
15308
  });
16850
15309
  }
16851
- //#endregion
16852
- //#region src/auth/JwtAccessTokenVerifier.ts
15310
+ // src/auth/JwtAccessTokenVerifier.ts
16853
15311
  /**
16854
15312
  * Verifies OAuth 2.0 access tokens for the MCP endpoint, which acts as a
16855
15313
  * resource server: a token is accepted only when it is a JWT signed with a key
@@ -16975,8 +15433,7 @@ var JwtAccessTokenVerifier = class JwtAccessTokenVerifier {
16975
15433
  };
16976
15434
  }
16977
15435
  };
16978
- //#endregion
16979
- //#region src/auth/protectedResourceMetadata.ts
15436
+ // src/auth/protectedResourceMetadata.ts
16980
15437
  /**
16981
15438
  * OAuth 2.0 Protected Resource Metadata (RFC 9728) for the MCP endpoint, and
16982
15439
  * the pieces of the discovery challenge that point clients at it.
@@ -17041,8 +15498,7 @@ function protectedResourceMetadataUrl(publicUrl, endpointPath) {
17041
15498
  function missingTokenChallenge(resourceMetadataUrl) {
17042
15499
  return `Bearer resource_metadata="${resourceMetadataUrl.replaceAll(/[\\"]/g, "\\$&")}"`;
17043
15500
  }
17044
- //#endregion
17045
- //#region src/app/originPolicy.ts
15501
+ // src/app/originPolicy.ts
17046
15502
  /**
17047
15503
  * Build the origin policy. Loopback origins, the public URL's origin and each
17048
15504
  * allowed origin (matched exactly) are allowed.
@@ -17159,8 +15615,7 @@ function isLoopbackBindHost(host) {
17159
15615
  if (family === 0) return unbracketed === "localhost";
17160
15616
  return LOOPBACK_ADDRESSES.check(unbracketed, family === 6 ? "ipv6" : "ipv4");
17161
15617
  }
17162
- //#endregion
17163
- //#region src/tools/errors.ts
15618
+ // src/tools/errors.ts
17164
15619
  var ToolError = class extends Error {
17165
15620
  toolName;
17166
15621
  constructor(message, toolName) {
@@ -17174,8 +15629,7 @@ var ToolError = class extends Error {
17174
15629
  * This indicates a client-side issue with the request parameters.
17175
15630
  */
17176
15631
  var ValidationError = class extends ToolError {};
17177
- //#endregion
17178
- //#region src/mcp/defaultInstructions.ts
15632
+ // src/mcp/defaultInstructions.ts
17179
15633
  /**
17180
15634
  * Built-in instructions sent to MCP clients when no instructions are configured.
17181
15635
  * Tool descriptions each explain one tool; this text explains how the tools work
@@ -17200,8 +15654,7 @@ function buildDefaultInstructions(readOnly) {
17200
15654
  readOnly ? READ_ONLY : INDEX
17201
15655
  ].join("\n");
17202
15656
  }
17203
- //#endregion
17204
- //#region src/mcp/utils.ts
15657
+ // src/mcp/utils.ts
17205
15658
  /**
17206
15659
  * Creates a success response object in the format expected by the MCP server.
17207
15660
  * @param text The text content of the response.
@@ -17230,8 +15683,7 @@ function createError(errorOrText) {
17230
15683
  isError: true
17231
15684
  };
17232
15685
  }
17233
- //#endregion
17234
- //#region src/mcp/mcpServer.ts
15686
+ // src/mcp/mcpServer.ts
17235
15687
  /**
17236
15688
  * Splits a comma-separated pattern string into an array of patterns. Commas
17237
15689
  * inside `{}`, `[]`, or `()` (regex quantifiers, glob brace expansion,
@@ -17422,7 +15874,7 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
17422
15874
  const server = new McpServer({
17423
15875
  name,
17424
15876
  ...title !== void 0 ? { title } : {},
17425
- version: "3.3.0"
15877
+ version: "3.4.0"
17426
15878
  }, {
17427
15879
  capabilities: {
17428
15880
  tools: {},
@@ -17841,8 +16293,7 @@ ${r.content}\n`);
17841
16293
  }
17842
16294
  return server;
17843
16295
  }
17844
- //#endregion
17845
- //#region src/tools/CancelJobTool.ts
16296
+ // src/tools/CancelJobTool.ts
17846
16297
  /**
17847
16298
  * Tool for attempting to cancel a pipeline job.
17848
16299
  */
@@ -17890,8 +16341,7 @@ var CancelJobTool = class {
17890
16341
  }
17891
16342
  }
17892
16343
  };
17893
- //#endregion
17894
- //#region src/tools/FetchUrlTool.ts
16344
+ // src/tools/FetchUrlTool.ts
17895
16345
  /**
17896
16346
  * Tool for fetching a single URL and converting its content to Markdown.
17897
16347
  * Unlike scrape_docs, this tool only processes one page without crawling
@@ -17962,14 +16412,14 @@ var FetchUrlTool = class {
17962
16412
  } catch (error) {
17963
16413
  if (error instanceof ToolError) throw error;
17964
16414
  if (error instanceof ChallengeError) throw new ToolError(`Unable to fetch the URL "${url}": the site answered with a ${error.challengeType} bot challenge instead of the page, which cannot be passed automatically.`, this.constructor.name);
16415
+ if (error instanceof RenderError) throw new ToolError(`${error.message}. Use scrape mode "auto" to read the page as fetched instead.`, this.constructor.name);
17965
16416
  throw new ToolError(`Unable to fetch or process the URL "${url}". Please verify the URL is correct and accessible.`, this.constructor.name);
17966
16417
  } finally {
17967
16418
  await Promise.allSettled([...this.pipelines.map((pipeline) => pipeline.close()), this.fetcher.close()]);
17968
16419
  }
17969
16420
  }
17970
16421
  };
17971
- //#endregion
17972
- //#region src/tools/FindVersionTool.ts
16422
+ // src/tools/FindVersionTool.ts
17973
16423
  /**
17974
16424
  * Tool for finding the best matching version of a library in the store.
17975
16425
  * Supports exact version matches and X-Range patterns (e.g., '5.x', '5.2.x').
@@ -18003,8 +16453,7 @@ var FindVersionTool = class {
18003
16453
  };
18004
16454
  }
18005
16455
  };
18006
- //#endregion
18007
- //#region src/tools/GetJobInfoTool.ts
16456
+ // src/tools/GetJobInfoTool.ts
18008
16457
  /**
18009
16458
  * Tool for retrieving simplified information about a specific pipeline job.
18010
16459
  */
@@ -18049,8 +16498,7 @@ var GetJobInfoTool = class {
18049
16498
  } };
18050
16499
  }
18051
16500
  };
18052
- //#endregion
18053
- //#region src/tools/ListJobsTool.ts
16501
+ // src/tools/ListJobsTool.ts
18054
16502
  /**
18055
16503
  * Tool for listing pipeline jobs managed by the pipeline.
18056
16504
  * Allows filtering jobs by their status.
@@ -18093,8 +16541,7 @@ var ListJobsTool = class {
18093
16541
  }) };
18094
16542
  }
18095
16543
  };
18096
- //#endregion
18097
- //#region src/tools/ListLibrariesTool.ts
16544
+ // src/tools/ListLibrariesTool.ts
18098
16545
  /**
18099
16546
  * Tool for listing all available libraries and their indexed versions in the store.
18100
16547
  */
@@ -18120,8 +16567,7 @@ var ListLibrariesTool = class {
18120
16567
  })) };
18121
16568
  }
18122
16569
  };
18123
- //#endregion
18124
- //#region src/tools/ListPagesTool.ts
16570
+ // src/tools/ListPagesTool.ts
18125
16571
  /**
18126
16572
  * Tool for listing indexed pages and documentation sitemap for a library version.
18127
16573
  */
@@ -18144,8 +16590,7 @@ var ListPagesTool = class {
18144
16590
  });
18145
16591
  }
18146
16592
  };
18147
- //#endregion
18148
- //#region src/tools/ReadPageTool.ts
16593
+ // src/tools/ReadPageTool.ts
18149
16594
  /**
18150
16595
  * Strips what agents tend to copy along with a link: the HTML-escaped `&lt;…&gt;`
18151
16596
  * wrapper, angle brackets and quotes, `./` and `../` prefixes, and Windows
@@ -18178,8 +16623,7 @@ var ReadPageTool = class {
18178
16623
  });
18179
16624
  }
18180
16625
  };
18181
- //#endregion
18182
- //#region src/tools/RefreshVersionTool.ts
16626
+ // src/tools/RefreshVersionTool.ts
18183
16627
  /**
18184
16628
  * Tool for refreshing an existing library version by re-scraping all pages
18185
16629
  * and using ETag comparison to skip unchanged content.
@@ -18209,8 +16653,7 @@ var RefreshVersionTool = class {
18209
16653
  return { jobId };
18210
16654
  }
18211
16655
  };
18212
- //#endregion
18213
- //#region src/tools/RemoveTool.ts
16656
+ // src/tools/RemoveTool.ts
18214
16657
  /**
18215
16658
  * Tool to remove indexed documentation for a specific library version.
18216
16659
  * This class provides the core logic, intended to be called by the McpServer.
@@ -18253,8 +16696,7 @@ var RemoveTool = class {
18253
16696
  }
18254
16697
  }
18255
16698
  };
18256
- //#endregion
18257
- //#region src/tools/ScrapeTool.ts
16699
+ // src/tools/ScrapeTool.ts
18258
16700
  /**
18259
16701
  * Tool for enqueuing documentation scraping jobs via the pipeline.
18260
16702
  */
@@ -18302,8 +16744,7 @@ var ScrapeTool = class {
18302
16744
  return { jobId };
18303
16745
  }
18304
16746
  };
18305
- //#endregion
18306
- //#region src/tools/SearchTool.ts
16747
+ // src/tools/SearchTool.ts
18307
16748
  /**
18308
16749
  * Tool for searching indexed documentation.
18309
16750
  * Supports exact version matches and version range patterns.
@@ -18340,8 +16781,7 @@ var SearchTool = class {
18340
16781
  }
18341
16782
  }
18342
16783
  };
18343
- //#endregion
18344
- //#region src/mcp/tools.ts
16784
+ // src/mcp/tools.ts
18345
16785
  /**
18346
16786
  * Initializes and returns the shared tool instances.
18347
16787
  * This should be called after initializeServices has completed.
@@ -18366,8 +16806,7 @@ async function initializeTools(docService, pipeline, config) {
18366
16806
  fetchUrl: new FetchUrlTool(new AutoDetectFetcher(config.scraper), config)
18367
16807
  };
18368
16808
  }
18369
- //#endregion
18370
- //#region src/services/mcpService.ts
16809
+ // src/services/mcpService.ts
18371
16810
  /** Path of the MCP endpoint, relative to the public URL. */
18372
16811
  var MCP_ENDPOINT_PATH = "/mcp";
18373
16812
  /** Path of the deprecated HTTP+SSE transport's event stream, relative to the public URL. */
@@ -18531,8 +16970,7 @@ function registerLegacySseTransport(server, deps, createServer) {
18531
16970
  await Promise.all([...sessions.values()].map((transport) => transport.close()));
18532
16971
  });
18533
16972
  }
18534
- //#endregion
18535
- //#region src/services/systemInfo.ts
16973
+ // src/services/systemInfo.ts
18536
16974
  /**
18537
16975
  * Assembles the {@link SystemInfo} snapshot from server + app configuration.
18538
16976
  * @param serverConfig - Service composition/runtime wiring for this process.
@@ -18545,7 +16983,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
18545
16983
  const mcpEnabled = Boolean(serverConfig.enableMcpServer);
18546
16984
  const authEnabled = Boolean(appConfig.auth.enabled);
18547
16985
  return {
18548
- version: "3.3.0",
16986
+ version: "3.4.0",
18549
16987
  readOnly: Boolean(appConfig.app.readOnly),
18550
16988
  telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
18551
16989
  services: {
@@ -18579,8 +17017,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
18579
17017
  }
18580
17018
  };
18581
17019
  }
18582
- //#endregion
18583
- //#region src/events/trpc/router.ts
17020
+ // src/events/trpc/router.ts
18584
17021
  /**
18585
17022
  * tRPC router for event subscriptions.
18586
17023
  * Allows remote processes to subscribe to application events via tRPC.
@@ -18616,8 +17053,7 @@ subscribe: tt.procedure.input(z.object({ events: z.array(z.nativeEnum(EventType)
18616
17053
  }) });
18617
17054
  }
18618
17055
  createEventsRouter(t$4);
18619
- //#endregion
18620
- //#region src/pipeline/trpc/router.ts
17056
+ // src/pipeline/trpc/router.ts
18621
17057
  /**
18622
17058
  * tRPC router exposing pipeline procedures for external workers.
18623
17059
  * Provides a minimal RPC surface to replace legacy REST endpoints.
@@ -18706,8 +17142,7 @@ function createPipelineRouter(trpc) {
18706
17142
  });
18707
17143
  }
18708
17144
  createPipelineRouter(t$3);
18709
- //#endregion
18710
- //#region src/store/trpc/router.ts
17145
+ // src/store/trpc/router.ts
18711
17146
  /**
18712
17147
  * tRPC router exposing document data store operations via the worker API.
18713
17148
  * Only procedures actually used externally are included to keep surface minimal.
@@ -18849,8 +17284,7 @@ function createDataRouter(trpc) {
18849
17284
  });
18850
17285
  }
18851
17286
  createDataRouter(t$2);
18852
- //#endregion
18853
- //#region src/services/systemHealthRouter.ts
17287
+ // src/services/systemHealthRouter.ts
18854
17288
  /**
18855
17289
  * tRPC router exposing a single `getSystemHealth` query that composes the
18856
17290
  * server's startup {@link SystemInfo} snapshot with the small amount of
@@ -18902,8 +17336,7 @@ getSystemHealth: tt.procedure.query(async ({ ctx }) => {
18902
17336
  }) });
18903
17337
  }
18904
17338
  createSystemHealthRouter(t$1);
18905
- //#endregion
18906
- //#region src/services/appRouter.ts
17339
+ // src/services/appRouter.ts
18907
17340
  /**
18908
17341
  * Canonical tRPC router builder for the merged application API.
18909
17342
  * Combines the health check, pipeline, data store, and events routers into a
@@ -18938,11 +17371,30 @@ removeDocs: t.procedure.input(z.object({
18938
17371
  library: input.library,
18939
17372
  version: input.version ?? void 0
18940
17373
  })) });
17374
+ const searchRouter = t.router({
17375
+ /**
17376
+ * Searches a library as `search_docs` does: the version resolves to the
17377
+ * best stored match first, and an omitted or empty one to the newest. The
17378
+ * data router's `search` stays literal, since remote clients send it a
17379
+ * version the tool has already resolved.
17380
+ */
17381
+ searchDocs: t.procedure.input(z.object({
17382
+ library: nonEmpty,
17383
+ version: optionalVersion,
17384
+ query: nonEmpty,
17385
+ limit: z.number().int().positive().max(50).optional()
17386
+ })).query(({ ctx, input }) => new SearchTool(ctx.docService).execute({
17387
+ library: input.library,
17388
+ version: input.version ?? void 0,
17389
+ query: input.query,
17390
+ limit: input.limit
17391
+ })) });
18941
17392
  return t.router({
18942
17393
  ...healthRouter._def.procedures,
18943
17394
  ...createPipelineRouter(t)._def.procedures,
18944
17395
  ...createDataRouter(t)._def.procedures,
18945
17396
  ...removalRouter._def.procedures,
17397
+ ...searchRouter._def.procedures,
18946
17398
  ...createSystemHealthRouter(t)._def.procedures,
18947
17399
  events: createEventsRouter(t)
18948
17400
  });
@@ -18963,8 +17415,7 @@ function createAppRouterContext(deps) {
18963
17415
  isWorkerConnected: deps.isWorkerConnected
18964
17416
  };
18965
17417
  }
18966
- //#endregion
18967
- //#region src/services/trpcService.ts
17418
+ // src/services/trpcService.ts
18968
17419
  /**
18969
17420
  * Fastify service to register unified tRPC API at /api.
18970
17421
  * Merges pipeline, data store, and events routers under a single endpoint.
@@ -19019,8 +17470,7 @@ function applyTrpcWebSocketHandler(wss, pipeline, docService, eventBus, systemIn
19019
17470
  })
19020
17471
  });
19021
17472
  }
19022
- //#endregion
19023
- //#region src/utils/banner.ts
17473
+ // src/utils/banner.ts
19024
17474
  /**
19025
17475
  * ASCII art banner for console startup display.
19026
17476
  * Uses ANSI colors: gray (dim) top line, bright white bottom line.
@@ -19035,8 +17485,7 @@ function printBanner() {
19035
17485
  console.log(BANNER);
19036
17486
  console.log();
19037
17487
  }
19038
- //#endregion
19039
- //#region src/app/basePath.ts
17488
+ // src/app/basePath.ts
19040
17489
  /**
19041
17490
  * Helpers for serving the application under the path of its public URL, e.g.
19042
17491
  * `https://example.com/docs`, behind proxies that either forward or strip that
@@ -19111,8 +17560,7 @@ function isApiSocketPath(url, basePath) {
19111
17560
  const pathname = stripBasePath(url, basePath).split("?")[0];
19112
17561
  return pathname === "/" || isUnderPath(pathname, "/api");
19113
17562
  }
19114
- //#endregion
19115
- //#region src/app/AppServer.ts
17563
+ // src/app/AppServer.ts
19116
17564
  /**
19117
17565
  * Central application server that can be configured to run different combinations of services.
19118
17566
  * This replaces the separate server implementations with a single, modular approach.
@@ -19207,7 +17655,7 @@ var AppServer = class AppServer {
19207
17655
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
19208
17656
  if (telemetry.isEnabled()) {
19209
17657
  telemetry.setGlobalContext({
19210
- appVersion: "3.3.0",
17658
+ appVersion: "3.4.0",
19211
17659
  appPlatform: process.platform,
19212
17660
  appNodeVersion: process.version,
19213
17661
  appServicesEnabled: this.getActiveServicesList(),
@@ -19518,8 +17966,7 @@ function refuseUpgrade(socket, status) {
19518
17966
  socket.once("finish", () => socket.destroy());
19519
17967
  socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
19520
17968
  }
19521
- //#endregion
19522
- //#region src/app/index.ts
17969
+ // src/app/index.ts
19523
17970
  /**
19524
17971
  * Starts an AppServer that serves `backend` with the given configuration.
19525
17972
  * Convenience function for CLI integration.
@@ -19534,8 +17981,7 @@ async function startAppServer(backend, serverConfig, appConfig) {
19534
17981
  await appServer.start();
19535
17982
  return appServer;
19536
17983
  }
19537
- //#endregion
19538
- //#region src/mcp/startStdioServer.ts
17984
+ // src/mcp/startStdioServer.ts
19539
17985
  /**
19540
17986
  * Starts the MCP server on the process's stdio.
19541
17987
  *
@@ -19555,8 +18001,7 @@ async function startStdioServer(tools, config) {
19555
18001
  logger.info("🤖 MCP server listening on stdio");
19556
18002
  return handle;
19557
18003
  }
19558
- //#endregion
19559
- //#region src/cli/options.ts
18004
+ // src/cli/options.ts
19560
18005
  /**
19561
18006
  * Declare `--public-url` and its deprecated alias `--public-origin`.
19562
18007
  * @param yargs - The command's builder.
@@ -19619,8 +18064,21 @@ function withServerIdentityOptions(yargs) {
19619
18064
  alias: "serverInstructionsFile"
19620
18065
  });
19621
18066
  }
19622
- //#endregion
19623
- //#region src/cli/services.ts
18067
+ /**
18068
+ * Declare `--accept-model-change`, which confirms a changed embedding model
18069
+ * without a prompt. Without the flag, `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides.
18070
+ * @param yargs - The command's builder.
18071
+ * @returns The builder, for chaining.
18072
+ */
18073
+ function withModelChangeOptions(yargs) {
18074
+ return yargs.option("accept-model-change", {
18075
+ type: "boolean",
18076
+ description: "Confirm a changed embedding model without a prompt; deletes all stored vectors",
18077
+ defaultDescription: "false",
18078
+ alias: "acceptModelChange"
18079
+ });
18080
+ }
18081
+ // src/cli/services.ts
19624
18082
  var activeAppServer = null;
19625
18083
  var activeMcpStdioServer = null;
19626
18084
  var activeBackend = null;
@@ -19653,10 +18111,9 @@ async function closeActiveBackend() {
19653
18111
  activeBackend = null;
19654
18112
  await backend?.close();
19655
18113
  }
19656
- //#endregion
19657
- //#region src/cli/commands/default.ts
18114
+ // src/cli/commands/default.ts
19658
18115
  function createDefaultAction(cli) {
19659
- cli.command(["$0", "server"], "Starts the Docs MCP server (Unified Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(yargs.option("protocol", {
18116
+ cli.command(["$0", "server"], "Starts the Docs MCP server (Unified Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(withModelChangeOptions(yargs).option("protocol", {
19660
18117
  type: "string",
19661
18118
  description: "Protocol for MCP server",
19662
18119
  choices: [
@@ -19711,7 +18168,7 @@ function createDefaultAction(cli) {
19711
18168
  appConfig,
19712
18169
  eventBus: getEventBus(argv),
19713
18170
  jobs: { interruptedJobs: appConfig.app.readOnly ? "leave" : argv.resume ? "recover" : "fail" },
19714
- onEmbeddingModelChange: handleEmbeddingModelChange
18171
+ onEmbeddingModelChange: (error, service) => handleEmbeddingModelChange(error, service, argv.acceptModelChange)
19715
18172
  });
19716
18173
  registerGlobalServices({ backend });
19717
18174
  if (resolvedProtocol === "stdio") {
@@ -19735,8 +18192,7 @@ function createDefaultAction(cli) {
19735
18192
  }
19736
18193
  });
19737
18194
  }
19738
- //#endregion
19739
- //#region src/cli/commands/fetchUrl.ts
18195
+ // src/cli/commands/fetchUrl.ts
19740
18196
  function createFetchUrlCommand(cli) {
19741
18197
  cli.command("fetch-url <url>", "Fetch a URL and transform it into Markdown format", (yargs) => {
19742
18198
  return yargs.positional("url", {
@@ -19785,8 +18241,7 @@ function createFetchUrlCommand(cli) {
19785
18241
  }));
19786
18242
  });
19787
18243
  }
19788
- //#endregion
19789
- //#region src/cli/commands/findVersion.ts
18244
+ // src/cli/commands/findVersion.ts
19790
18245
  function createFindVersionCommand(cli) {
19791
18246
  cli.command("find-version <library>", "Resolve and display the best matching documentation version for a library", (yargs) => {
19792
18247
  return yargs.version(false).positional("library", {
@@ -19834,8 +18289,7 @@ function createFindVersionCommand(cli) {
19834
18289
  }
19835
18290
  });
19836
18291
  }
19837
- //#endregion
19838
- //#region src/cli/commands/list.ts
18292
+ // src/cli/commands/list.ts
19839
18293
  function createListCommand(cli) {
19840
18294
  cli.command("list", "List all indexed libraries and their available versions", (yargs) => {
19841
18295
  return yargs.option("server-url", {
@@ -19866,10 +18320,9 @@ function createListCommand(cli) {
19866
18320
  }
19867
18321
  });
19868
18322
  }
19869
- //#endregion
19870
- //#region src/cli/commands/mcp.ts
18323
+ // src/cli/commands/mcp.ts
19871
18324
  function createMcpCommand(cli) {
19872
- cli.command("mcp", "Start the MCP server (Standalone Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(yargs.option("protocol", {
18325
+ cli.command("mcp", "Start the MCP server (Standalone Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(withModelChangeOptions(yargs).option("protocol", {
19873
18326
  type: "string",
19874
18327
  description: "Protocol for MCP server",
19875
18328
  choices: [
@@ -19926,7 +18379,7 @@ function createMcpCommand(cli) {
19926
18379
  eventBus: getEventBus(argv),
19927
18380
  serverUrl,
19928
18381
  jobs: { interruptedJobs: appConfig.app.readOnly ? "leave" : "fail" },
19929
- onEmbeddingModelChange: handleEmbeddingModelChange
18382
+ onEmbeddingModelChange: (error, service) => handleEmbeddingModelChange(error, service, argv.acceptModelChange)
19930
18383
  });
19931
18384
  registerGlobalServices({ backend });
19932
18385
  if (resolvedProtocol === "stdio") {
@@ -19954,8 +18407,7 @@ function createMcpCommand(cli) {
19954
18407
  }
19955
18408
  });
19956
18409
  }
19957
- //#endregion
19958
- //#region src/cli/JobOutputFollower.ts
18410
+ // src/cli/JobOutputFollower.ts
19959
18411
  /**
19960
18412
  * Passes a command the status and progress events of the job it submitted, and
19961
18413
  * no others. A shared worker runs jobs for several clients, and a job can start
@@ -20020,8 +18472,7 @@ function followJobLogs(eventBus, verb) {
20020
18472
  }
20021
18473
  });
20022
18474
  }
20023
- //#endregion
20024
- //#region src/cli/commands/refresh.ts
18475
+ // src/cli/commands/refresh.ts
20025
18476
  function createRefreshCommand(cli) {
20026
18477
  cli.command("refresh <library>", "Update an existing library version by re-scraping changed pages", (yargs) => {
20027
18478
  return yargs.version(false).positional("library", {
@@ -20088,8 +18539,7 @@ function createRefreshCommand(cli) {
20088
18539
  }
20089
18540
  });
20090
18541
  }
20091
- //#endregion
20092
- //#region src/cli/commands/remove.ts
18542
+ // src/cli/commands/remove.ts
20093
18543
  function createRemoveCommand(cli) {
20094
18544
  cli.command("remove <library>", "Remove a library version from the index, and the library with its last version", (yargs) => {
20095
18545
  return yargs.version(false).positional("library", {
@@ -20135,8 +18585,7 @@ function createRemoveCommand(cli) {
20135
18585
  }
20136
18586
  });
20137
18587
  }
20138
- //#endregion
20139
- //#region src/cli/commands/scrape.ts
18588
+ // src/cli/commands/scrape.ts
20140
18589
  function createScrapeCommand(cli) {
20141
18590
  cli.command("scrape <library> <url>", "Download and index documentation from a URL or local directory", (yargs) => {
20142
18591
  return yargs.version(false).positional("library", {
@@ -20305,8 +18754,7 @@ function createScrapeCommand(cli) {
20305
18754
  }
20306
18755
  });
20307
18756
  }
20308
- //#endregion
20309
- //#region src/cli/commands/search.ts
18757
+ // src/cli/commands/search.ts
20310
18758
  function createSearchCommand(cli) {
20311
18759
  cli.command("search <library> <query>", "Query the documentation index used by the MCP server", (yargs) => {
20312
18760
  return yargs.version(false).positional("library", {
@@ -20377,8 +18825,7 @@ function createSearchCommand(cli) {
20377
18825
  }
20378
18826
  });
20379
18827
  }
20380
- //#endregion
20381
- //#region src/cli/commands/web.ts
18828
+ // src/cli/commands/web.ts
20382
18829
  function createWebCommand(cli) {
20383
18830
  cli.command("web", "Start the web dashboard (Standalone Mode)", (yargs) => {
20384
18831
  return withPublicUrlOptions(yargs.option("port", {
@@ -20433,11 +18880,10 @@ function createWebCommand(cli) {
20433
18880
  }
20434
18881
  });
20435
18882
  }
20436
- //#endregion
20437
- //#region src/cli/commands/worker.ts
18883
+ // src/cli/commands/worker.ts
20438
18884
  function createWorkerCommand(cli) {
20439
18885
  cli.command("worker", "Start a background worker for processing scraping jobs", (yargs) => {
20440
- return withPublicUrlOptions(yargs.option("port", {
18886
+ return withPublicUrlOptions(withModelChangeOptions(yargs).option("port", {
20441
18887
  type: "string",
20442
18888
  description: "Port for worker API"
20443
18889
  }).option("host", {
@@ -20473,7 +18919,8 @@ function createWorkerCommand(cli) {
20473
18919
  const backend = await openBackend({
20474
18920
  appConfig,
20475
18921
  eventBus: getEventBus(argv),
20476
- jobs: { interruptedJobs: argv.resume ?? true ? "recover" : "fail" }
18922
+ jobs: { interruptedJobs: argv.resume ?? true ? "recover" : "fail" },
18923
+ onEmbeddingModelChange: (error, service) => handleEmbeddingModelChange(error, service, argv.acceptModelChange)
20477
18924
  });
20478
18925
  registerGlobalServices({ backend });
20479
18926
  registerGlobalServices({ appServer: await startAppServer(backend, createAppServerConfig({
@@ -20491,8 +18938,7 @@ function createWorkerCommand(cli) {
20491
18938
  }
20492
18939
  });
20493
18940
  }
20494
- //#endregion
20495
- //#region src/cli/index.ts
18941
+ // src/cli/index.ts
20496
18942
  /**
20497
18943
  * Main CLI setup and command registration using Yargs.
20498
18944
  */
@@ -20562,13 +19008,14 @@ function registerGlobalOptions(cli) {
20562
19008
  function createCli(argv) {
20563
19009
  let globalEventBus = null;
20564
19010
  const commandStartTimes = /* @__PURE__ */ new Map();
20565
- const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.3.0").middleware(async (argv) => {
19011
+ const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.4.0").middleware(async (argv) => {
20566
19012
  if (argv.verbose && argv.quiet) throw new Error("Arguments verbose and quiet are mutually exclusive");
20567
19013
  applyGlobalCliOutputMode({
20568
19014
  verbose: argv.verbose,
20569
19015
  quiet: argv.quiet
20570
19016
  });
20571
- const resolvedStorePath = resolveStorePath(argv.storePath || process.env.DOCS_MCP_STORE_PATH);
19017
+ const rawStorePath = argv.storePath || process.env.DOCS_MCP_STORE_PATH;
19018
+ const resolvedStorePath = resolveStorePath(rawStorePath);
20572
19019
  argv.storePath = resolvedStorePath;
20573
19020
  const appConfig = loadConfig(argv, {
20574
19021
  configPath: argv.config,
@@ -20584,7 +19031,7 @@ function createCli(argv) {
20584
19031
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
20585
19032
  const commandName = argv._[0]?.toString() || "default";
20586
19033
  telemetry.setGlobalContext({
20587
- appVersion: "3.3.0",
19034
+ appVersion: "3.4.0",
20588
19035
  appPlatform: process.platform,
20589
19036
  appNodeVersion: process.version,
20590
19037
  appInterface: "cli",
@@ -20603,8 +19050,7 @@ function createCli(argv) {
20603
19050
  for (const registerCommand of COMMAND_FACTORIES) registerCommand(cli);
20604
19051
  return cli;
20605
19052
  }
20606
- //#endregion
20607
- //#region src/cli/main.ts
19053
+ // src/cli/main.ts
20608
19054
  /**
20609
19055
  * CLI main entry point with global shutdown and error handling.
20610
19056
  * Analytics is initialized immediately when imported for proper telemetry across all services.
@@ -20694,7 +19140,6 @@ async function runCli() {
20694
19140
  const appServer = getActiveAppServer();
20695
19141
  if (commandExecuted && !appServer) await cleanupCliCommand();
20696
19142
  }
20697
- //#endregion
20698
19143
  export { cleanupCliCommand, runCli };
20699
19144
 
20700
- //# sourceMappingURL=main-BoABX2b0.js.map
19145
+ //# sourceMappingURL=main-BTCYUUTU.js.map