@coderule/clients 1.0.0 → 1.1.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.
package/dist/index.js CHANGED
@@ -1,16 +1,754 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
1
+ import * as crypto from 'crypto';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
15
  };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.fetch = exports.RetrievalHttpClient = exports.SyncHttpClient = exports.decodeJWT = exports.AuthHttpClient = void 0;
7
- var auth_client_1 = require("./clients/auth-client");
8
- Object.defineProperty(exports, "AuthHttpClient", { enumerable: true, get: function () { return auth_client_1.AuthHttpClient; } });
9
- Object.defineProperty(exports, "decodeJWT", { enumerable: true, get: function () { return auth_client_1.decodeJWT; } });
10
- var sync_client_1 = require("./clients/sync-client");
11
- Object.defineProperty(exports, "SyncHttpClient", { enumerable: true, get: function () { return sync_client_1.SyncHttpClient; } });
12
- var retrieval_client_1 = require("./clients/retrieval-client");
13
- Object.defineProperty(exports, "RetrievalHttpClient", { enumerable: true, get: function () { return retrieval_client_1.RetrievalHttpClient; } });
14
- var fetch_wrapper_1 = require("./utils/fetch-wrapper");
15
- Object.defineProperty(exports, "fetch", { enumerable: true, get: function () { return __importDefault(fetch_wrapper_1).default; } });
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // node_modules/tsup/assets/esm_shims.js
31
+ var init_esm_shims = __esm({
32
+ "node_modules/tsup/assets/esm_shims.js"() {
33
+ }
34
+ });
35
+
36
+ // src/polyfills/fetch-polyfill.ts
37
+ var fetch_polyfill_exports = {};
38
+ __export(fetch_polyfill_exports, {
39
+ AbortController: () => AbortController,
40
+ FormData: () => FormData,
41
+ Headers: () => Headers,
42
+ Request: () => Request,
43
+ Response: () => Response,
44
+ fetch: () => fetch
45
+ });
46
+ var nodeFetch, NodeHeaders, NodeRequest, NodeResponse, NodeFormData, NodeAbortController, fetch, Headers, Request, Response, FormData, AbortController;
47
+ var init_fetch_polyfill = __esm({
48
+ "src/polyfills/fetch-polyfill.ts"() {
49
+ init_esm_shims();
50
+ try {
51
+ const module = __require("node-fetch");
52
+ nodeFetch = module.default || module;
53
+ NodeHeaders = module.Headers;
54
+ NodeRequest = module.Request;
55
+ NodeResponse = module.Response;
56
+ try {
57
+ NodeFormData = // eslint-disable-next-line @typescript-eslint/no-require-imports
58
+ module.FormData || __require("formdata-polyfill/esm.min.js").FormData;
59
+ } catch {
60
+ NodeFormData = class FormData {
61
+ constructor() {
62
+ throw new Error(
63
+ "FormData is not available. Install formdata-polyfill if needed."
64
+ );
65
+ }
66
+ };
67
+ }
68
+ NodeAbortController = globalThis.AbortController || module.AbortController;
69
+ } catch {
70
+ throw new Error(
71
+ "For Node.js < 18, please install node-fetch: npm install node-fetch@2"
72
+ );
73
+ }
74
+ fetch = nodeFetch;
75
+ Headers = NodeHeaders;
76
+ Request = NodeRequest;
77
+ Response = NodeResponse;
78
+ FormData = NodeFormData;
79
+ AbortController = NodeAbortController;
80
+ }
81
+ });
82
+
83
+ // src/index.ts
84
+ init_esm_shims();
85
+
86
+ // src/clients/auth-client.ts
87
+ init_esm_shims();
88
+
89
+ // src/utils/fetch-wrapper.ts
90
+ init_esm_shims();
91
+ var hasNativeFetch = typeof globalThis.fetch !== "undefined";
92
+ var fetchModule;
93
+ if (hasNativeFetch) {
94
+ fetchModule = {
95
+ fetch: globalThis.fetch,
96
+ Headers: globalThis.Headers,
97
+ Request: globalThis.Request,
98
+ Response: globalThis.Response,
99
+ FormData: globalThis.FormData,
100
+ AbortController: globalThis.AbortController
101
+ };
102
+ } else {
103
+ try {
104
+ fetchModule = (init_fetch_polyfill(), __toCommonJS(fetch_polyfill_exports));
105
+ } catch {
106
+ throw new Error(
107
+ `This library requires Node.js 18+ or the node-fetch package.
108
+ Please either:
109
+ 1. Upgrade to Node.js 18 or later, or
110
+ 2. Install node-fetch: npm install node-fetch@2`
111
+ );
112
+ }
113
+ }
114
+ var fetch2 = fetchModule.fetch;
115
+ fetchModule.Headers;
116
+ fetchModule.Request;
117
+ fetchModule.Response;
118
+ var FormData2 = fetchModule.FormData;
119
+ var AbortController2 = fetchModule.AbortController;
120
+ var fetch_wrapper_default = fetch2;
121
+
122
+ // src/clients/auth-client.ts
123
+ var AuthHttpClient = class {
124
+ /**
125
+ * Initialize the Auth HTTP client
126
+ * @param baseUrl - Base URL of the Auth service (e.g., "http://localhost:8001")
127
+ * @param timeout - Request timeout in milliseconds (default: 30000)
128
+ */
129
+ constructor(baseUrl, timeout = 3e4) {
130
+ this.baseUrl = baseUrl.replace(/\/$/, "");
131
+ this.timeout = timeout;
132
+ }
133
+ /**
134
+ * Authenticate a token and receive a JWT
135
+ * @param token - Authentication token
136
+ * @returns Response containing JWT and expiration
137
+ * @throws Error on HTTP errors or connection errors
138
+ */
139
+ async authenticate(token) {
140
+ const url = `${this.baseUrl}/api/auth/authenticate`;
141
+ try {
142
+ const controller = new AbortController2();
143
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
144
+ const response = await fetch_wrapper_default(url, {
145
+ method: "POST",
146
+ headers: {
147
+ "Content-Type": "application/json"
148
+ },
149
+ body: JSON.stringify({ token }),
150
+ signal: controller.signal
151
+ });
152
+ clearTimeout(timeoutId);
153
+ if (!response.ok) {
154
+ const errorText = await response.text();
155
+ throw new Error(
156
+ `Authentication failed with status ${response.status}: ${errorText}`
157
+ );
158
+ }
159
+ const data = await response.json();
160
+ console.debug(
161
+ `Authentication successful, JWT expires at ${data.expires_at}`
162
+ );
163
+ return data;
164
+ } catch (error) {
165
+ if (error.name === "AbortError") {
166
+ throw new Error(`Request timeout after ${this.timeout}ms`);
167
+ }
168
+ console.error(`Authentication request failed: ${error.message}`);
169
+ throw error;
170
+ }
171
+ }
172
+ /**
173
+ * Check the health status of the Auth service
174
+ * @returns Health status information
175
+ * @throws Error on HTTP errors or connection errors
176
+ */
177
+ async health() {
178
+ const url = `${this.baseUrl}/api/auth/health`;
179
+ try {
180
+ const controller = new AbortController2();
181
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
182
+ const response = await fetch_wrapper_default(url, {
183
+ method: "GET",
184
+ signal: controller.signal
185
+ });
186
+ clearTimeout(timeoutId);
187
+ if (!response.ok) {
188
+ const errorText = await response.text();
189
+ throw new Error(
190
+ `Health check failed with status ${response.status}: ${errorText}`
191
+ );
192
+ }
193
+ const data = await response.json();
194
+ console.debug(`Health check: ${data.status}`);
195
+ return data;
196
+ } catch (error) {
197
+ if (error.name === "AbortError") {
198
+ throw new Error(`Request timeout after ${this.timeout}ms`);
199
+ }
200
+ console.error(`Health check request failed: ${error.message}`);
201
+ throw error;
202
+ }
203
+ }
204
+ /**
205
+ * Close the HTTP client connection (no-op for fetch)
206
+ */
207
+ close() {
208
+ }
209
+ };
210
+ function decodeJWT(jwtToken) {
211
+ try {
212
+ const parts = jwtToken.split(".");
213
+ if (parts.length !== 3) {
214
+ return null;
215
+ }
216
+ const payload = parts[1];
217
+ const paddedPayload = payload + "=".repeat((4 - payload.length % 4) % 4);
218
+ const base64 = paddedPayload.replace(/-/g, "+").replace(/_/g, "/");
219
+ const jsonString = Buffer.from(base64, "base64").toString("utf8");
220
+ const payloadObj = JSON.parse(jsonString);
221
+ if (payloadObj.exp) {
222
+ const now = Math.floor(Date.now() / 1e3);
223
+ if (payloadObj.exp < now) {
224
+ console.debug("JWT token is expired");
225
+ return null;
226
+ }
227
+ }
228
+ return payloadObj;
229
+ } catch (error) {
230
+ console.error("Failed to decode JWT:", error);
231
+ return null;
232
+ }
233
+ }
234
+
235
+ // src/clients/sync-client.ts
236
+ init_esm_shims();
237
+ var SyncHttpClient = class {
238
+ /**
239
+ * Initialize the Sync HTTP client
240
+ * @param baseUrl - Base URL of the Sync service (e.g., "http://localhost:8002")
241
+ * @param jwtToken - JWT token for authentication
242
+ * @param timeout - Request timeout in milliseconds (default: 60000)
243
+ */
244
+ constructor(baseUrl, jwtToken, timeout = 6e4) {
245
+ this.baseUrl = baseUrl.replace(/\/$/, "");
246
+ this.jwtToken = jwtToken;
247
+ this.timeout = timeout;
248
+ this.headers = {
249
+ Authorization: `Bearer ${jwtToken}`,
250
+ "Content-Type": "application/json"
251
+ };
252
+ }
253
+ /**
254
+ * Check the status of a snapshot
255
+ * @param snapshotHash - SHA256 hash of the snapshot
256
+ * @returns Snapshot status information
257
+ * @throws Error on HTTP errors or connection errors
258
+ */
259
+ async checkSnapshotStatus(snapshotHash) {
260
+ const url = `${this.baseUrl}/sync/v1/snapshots`;
261
+ try {
262
+ const controller = new AbortController2();
263
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
264
+ const response = await fetch_wrapper_default(url, {
265
+ method: "POST",
266
+ headers: this.headers,
267
+ body: JSON.stringify({ snapshot_hash: snapshotHash }),
268
+ signal: controller.signal
269
+ });
270
+ clearTimeout(timeoutId);
271
+ if (response.status === 404) {
272
+ return { status: "NOT_FOUND" };
273
+ }
274
+ if (!response.ok) {
275
+ const errorText = await response.text();
276
+ throw new Error(
277
+ `Failed to check snapshot with status ${response.status}: ${errorText}`
278
+ );
279
+ }
280
+ const data = await response.json();
281
+ return data;
282
+ } catch (error) {
283
+ if (error.name === "AbortError") {
284
+ throw new Error(`Request timeout after ${this.timeout}ms`);
285
+ }
286
+ console.error(`Request failed: ${error.message}`);
287
+ throw error;
288
+ }
289
+ }
290
+ /**
291
+ * Create a new snapshot or get its status if it exists
292
+ * @param snapshotHash - SHA256 hash of the snapshot
293
+ * @param files - List of file information with 'file_path' and 'file_hash'
294
+ * @returns Snapshot creation result or status
295
+ * @throws Error on HTTP errors or connection errors
296
+ */
297
+ async createSnapshot(snapshotHash, files) {
298
+ const url = `${this.baseUrl}/sync/v1/snapshots`;
299
+ try {
300
+ const controller = new AbortController2();
301
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
302
+ const response = await fetch_wrapper_default(url, {
303
+ method: "POST",
304
+ headers: this.headers,
305
+ body: JSON.stringify({
306
+ snapshot_hash: snapshotHash,
307
+ files
308
+ }),
309
+ signal: controller.signal
310
+ });
311
+ clearTimeout(timeoutId);
312
+ if (response.status === 422) {
313
+ const data2 = await response.json();
314
+ console.info(
315
+ `Snapshot ${snapshotHash.substring(0, 8)}... missing ${data2.missing_files?.length || 0} files`
316
+ );
317
+ return data2;
318
+ }
319
+ if (!response.ok) {
320
+ const errorText = await response.text();
321
+ throw new Error(
322
+ `Failed to create snapshot with status ${response.status}: ${errorText}`
323
+ );
324
+ }
325
+ const data = await response.json();
326
+ console.info(
327
+ `Snapshot ${snapshotHash.substring(0, 8)}... status: ${data.status}`
328
+ );
329
+ return data;
330
+ } catch (error) {
331
+ if (error.name === "AbortError") {
332
+ throw new Error(`Request timeout after ${this.timeout}ms`);
333
+ }
334
+ console.error(`Request failed: ${error.message}`);
335
+ throw error;
336
+ }
337
+ }
338
+ /**
339
+ * Upload file content to the service
340
+ * @param filesContent - Map of file_hash to object with 'path' and 'content'
341
+ * @returns Upload result with counts
342
+ * @throws Error on HTTP errors or connection errors
343
+ */
344
+ async uploadFileContent(filesContent) {
345
+ const url = `${this.baseUrl}/sync/v1/files/content`;
346
+ try {
347
+ const controller = new AbortController2();
348
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
349
+ const formData = new FormData2();
350
+ for (const [fileHash, fileData] of filesContent.entries()) {
351
+ const content = typeof fileData.content === "string" ? Buffer.from(fileData.content) : fileData.content;
352
+ const blob = new Blob([content], { type: "application/octet-stream" });
353
+ formData.append(fileHash, blob, fileData.path);
354
+ }
355
+ const uploadHeaders = { ...this.headers };
356
+ delete uploadHeaders["Content-Type"];
357
+ const response = await fetch_wrapper_default(url, {
358
+ method: "POST",
359
+ headers: uploadHeaders,
360
+ body: formData,
361
+ signal: controller.signal
362
+ });
363
+ clearTimeout(timeoutId);
364
+ if (!response.ok) {
365
+ const errorText = await response.text();
366
+ throw new Error(
367
+ `Failed to upload files with status ${response.status}: ${errorText}`
368
+ );
369
+ }
370
+ const data = await response.json();
371
+ console.info(
372
+ `Uploaded ${data.uploaded_count || 0} files, ${data.failed_count || 0} failed`
373
+ );
374
+ return data;
375
+ } catch (error) {
376
+ if (error.name === "AbortError") {
377
+ throw new Error(`Request timeout after ${this.timeout}ms`);
378
+ }
379
+ console.error(`Request failed: ${error.message}`);
380
+ throw error;
381
+ }
382
+ }
383
+ /**
384
+ * Calculate file hash from path and content
385
+ * @param filePath - Relative file path
386
+ * @param content - File content as Buffer or string
387
+ * @returns SHA256 hash of the file
388
+ */
389
+ static calculateFileHash(filePath, content) {
390
+ const contentBuffer = typeof content === "string" ? Buffer.from(content) : content;
391
+ const fileData = Buffer.concat([
392
+ Buffer.from(`${filePath}
393
+ `, "utf-8"),
394
+ contentBuffer
395
+ ]);
396
+ return crypto.createHash("sha256").update(fileData).digest("hex");
397
+ }
398
+ /**
399
+ * Calculate snapshot hash from file hashes
400
+ * @param fileHashes - Array of file SHA256 hashes
401
+ * @returns SHA256 hash of the snapshot
402
+ */
403
+ static calculateSnapshotHash(fileHashes) {
404
+ const snapshotData = fileHashes.sort().join("\n");
405
+ return crypto.createHash("sha256").update(snapshotData, "utf-8").digest("hex");
406
+ }
407
+ /**
408
+ * Check the health status of the Sync service
409
+ * @returns Health status information
410
+ * @throws Error on HTTP errors or connection errors
411
+ */
412
+ async health() {
413
+ const url = `${this.baseUrl}/sync/v1/health`;
414
+ try {
415
+ const controller = new AbortController2();
416
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
417
+ const response = await fetch_wrapper_default(url, {
418
+ method: "GET",
419
+ headers: { Authorization: `Bearer ${this.jwtToken}` },
420
+ signal: controller.signal
421
+ });
422
+ clearTimeout(timeoutId);
423
+ if (!response.ok) {
424
+ const errorText = await response.text();
425
+ throw new Error(
426
+ `Health check failed with status ${response.status}: ${errorText}`
427
+ );
428
+ }
429
+ const data = await response.json();
430
+ return data;
431
+ } catch (error) {
432
+ if (error.name === "AbortError") {
433
+ throw new Error(`Request timeout after ${this.timeout}ms`);
434
+ }
435
+ console.error(`Request failed: ${error.message}`);
436
+ throw error;
437
+ }
438
+ }
439
+ /**
440
+ * Close the HTTP client connection (no-op for fetch)
441
+ */
442
+ close() {
443
+ }
444
+ };
445
+
446
+ // src/clients/retrieval-client.ts
447
+ init_esm_shims();
448
+ var RetrievalHttpClient = class {
449
+ /**
450
+ * Initialize the Retrieval HTTP client
451
+ * @param uri - URI/URL for connecting to the HTTP server (e.g., "http://localhost:8004")
452
+ * @param timeout - Request timeout in milliseconds (default: 60000)
453
+ */
454
+ constructor(uri = "http://localhost:8004", timeout = 6e4) {
455
+ let processedUri = uri;
456
+ if (!uri.startsWith("http://") && !uri.startsWith("https://")) {
457
+ processedUri = `http://${uri}`;
458
+ }
459
+ const url = new URL(processedUri);
460
+ if (url.pathname && url.pathname !== "/") {
461
+ this.baseUrl = `${url.protocol}//${url.host}${url.pathname}`;
462
+ } else {
463
+ this.baseUrl = `${url.protocol}//${url.host}`;
464
+ }
465
+ this.timeout = timeout;
466
+ if (this.baseUrl.endsWith("/")) {
467
+ this.apiBase = `${this.baseUrl}api/retrieval/`;
468
+ } else {
469
+ this.apiBase = `${this.baseUrl}/api/retrieval/`;
470
+ }
471
+ console.debug(`Initialized HTTP client for ${this.baseUrl}`);
472
+ console.debug(`API base: ${this.apiBase}`);
473
+ }
474
+ /**
475
+ * Check the health status of the Retrieval service
476
+ * @returns Health status information
477
+ * @throws Error on connection errors
478
+ */
479
+ async healthCheck() {
480
+ const healthEndpoint = `${this.apiBase}health`;
481
+ console.debug(`Checking server health: ${healthEndpoint}`);
482
+ try {
483
+ const controller = new AbortController2();
484
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
485
+ const response = await fetch_wrapper_default(healthEndpoint, {
486
+ method: "GET",
487
+ signal: controller.signal
488
+ });
489
+ clearTimeout(timeoutId);
490
+ if (!response.ok) {
491
+ const errorText = await response.text();
492
+ throw new Error(
493
+ `Health check failed with status ${response.status}: ${errorText}`
494
+ );
495
+ }
496
+ const healthInfo = await response.json();
497
+ console.debug(`HTTP retrieval server status:`, healthInfo);
498
+ return {
499
+ status: healthInfo.status || "UNKNOWN",
500
+ database: healthInfo.database || "UNKNOWN",
501
+ embedder: healthInfo.embedder || "UNKNOWN",
502
+ cache_size: healthInfo.cache_size || 0,
503
+ cache_ttl: healthInfo.cache_ttl || 0,
504
+ version: healthInfo.version || "unknown"
505
+ };
506
+ } catch (error) {
507
+ if (error.name === "AbortError") {
508
+ throw new Error(`Request timeout after ${this.timeout}ms`);
509
+ }
510
+ console.error(`Error checking HTTP server health: ${error.message}`);
511
+ throw new Error(
512
+ `Unable to connect to HTTP server ${this.baseUrl}: ${error.message}`
513
+ );
514
+ }
515
+ }
516
+ /**
517
+ * Execute a retrieval query on a snapshot
518
+ * @param snapshotHash - SHA256 hash of the codebase snapshot
519
+ * @param queryText - Natural language query for retrieval
520
+ * @param budgetTokens - Maximum token budget for results (default: 3000)
521
+ * @param jwt - JWT token for authorization (required)
522
+ * @param options - Optional retrieval parameters
523
+ * @returns Retrieval results with formatted output
524
+ * @throws Error on query failures
525
+ */
526
+ async query(snapshotHash, queryText, budgetTokens = 3e3, jwt, options) {
527
+ if (!snapshotHash) {
528
+ throw new Error("Snapshot hash must be provided");
529
+ }
530
+ if (!queryText) {
531
+ throw new Error("Query text must be provided");
532
+ }
533
+ if (!jwt) {
534
+ throw new Error("JWT must be provided");
535
+ }
536
+ if (budgetTokens < 100) {
537
+ throw new Error("Budget tokens must be at least 100");
538
+ }
539
+ const startTime = Date.now();
540
+ const queryEndpoint = `${this.apiBase}query`;
541
+ try {
542
+ const controller = new AbortController2();
543
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
544
+ const requestBody = {
545
+ snapshot_hash: snapshotHash,
546
+ query: queryText,
547
+ budget_tokens: budgetTokens
548
+ };
549
+ if (options) {
550
+ requestBody.options = options;
551
+ }
552
+ const response = await fetch_wrapper_default(queryEndpoint, {
553
+ method: "POST",
554
+ headers: {
555
+ "Content-Type": "application/json",
556
+ Authorization: `Bearer ${jwt}`
557
+ },
558
+ body: JSON.stringify(requestBody),
559
+ signal: controller.signal
560
+ });
561
+ clearTimeout(timeoutId);
562
+ if (response.status === 404) {
563
+ const errorData = await response.json();
564
+ throw new Error(
565
+ errorData.detail || "Snapshot not found or access denied"
566
+ );
567
+ }
568
+ if (!response.ok) {
569
+ const errorText = await response.text();
570
+ throw new Error(
571
+ `Query failed with status ${response.status}: ${errorText}`
572
+ );
573
+ }
574
+ const result = await response.json();
575
+ const elapsedTime = (Date.now() - startTime) / 1e3;
576
+ const formatter = options?.formatter || "standard";
577
+ console.debug(
578
+ `Retrieval query completed for snapshot ${snapshotHash.substring(0, 8)}... Formatter: ${formatter}. Total time: ${elapsedTime.toFixed(2)}s`
579
+ );
580
+ return result;
581
+ } catch (error) {
582
+ if (error.name === "AbortError") {
583
+ throw new Error(`Request timeout after ${this.timeout}ms`);
584
+ }
585
+ console.error(`Error executing retrieval query: ${error.message}`);
586
+ throw new Error(`Failed to execute retrieval query: ${error.message}`);
587
+ }
588
+ }
589
+ /**
590
+ * Check if a snapshot is indexed and ready for retrieval
591
+ * @param snapshotHash - SHA256 hash of the snapshot to check
592
+ * @param jwt - JWT token for authorization (required)
593
+ * @returns Snapshot status information
594
+ * @throws Error on status check failures
595
+ */
596
+ async checkSnapshotStatus(snapshotHash, jwt) {
597
+ if (!snapshotHash) {
598
+ throw new Error("Snapshot hash must be provided");
599
+ }
600
+ if (!jwt) {
601
+ throw new Error("JWT must be provided");
602
+ }
603
+ const statusEndpoint = `${this.apiBase}snapshots/${snapshotHash}/status`;
604
+ try {
605
+ const controller = new AbortController2();
606
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
607
+ const response = await fetch_wrapper_default(statusEndpoint, {
608
+ method: "GET",
609
+ headers: {
610
+ Authorization: `Bearer ${jwt}`
611
+ },
612
+ signal: controller.signal
613
+ });
614
+ clearTimeout(timeoutId);
615
+ if (response.status === 404) {
616
+ return {
617
+ snapshot_hash: snapshotHash,
618
+ status: "NOT_FOUND",
619
+ message: "Snapshot not found or access denied"
620
+ };
621
+ }
622
+ if (!response.ok) {
623
+ const errorText = await response.text();
624
+ throw new Error(
625
+ `Status check failed with status ${response.status}: ${errorText}`
626
+ );
627
+ }
628
+ const statusInfo = await response.json();
629
+ console.debug(
630
+ `Snapshot ${snapshotHash.substring(0, 8)}... status: ${statusInfo.status}`
631
+ );
632
+ return statusInfo;
633
+ } catch (error) {
634
+ if (error.name === "AbortError") {
635
+ throw new Error(`Request timeout after ${this.timeout}ms`);
636
+ }
637
+ console.error(`Error checking snapshot status: ${error.message}`);
638
+ throw new Error(`Failed to check snapshot status: ${error.message}`);
639
+ }
640
+ }
641
+ /**
642
+ * Clear the graph cache (admin operation)
643
+ * @param jwt - JWT token for authorization (required)
644
+ * @returns true if cache cleared successfully
645
+ * @throws Error on cache clear failures
646
+ */
647
+ async clearCache(jwt) {
648
+ if (!jwt) {
649
+ throw new Error("JWT must be provided");
650
+ }
651
+ const cacheEndpoint = `${this.apiBase}cache`;
652
+ try {
653
+ const controller = new AbortController2();
654
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
655
+ const response = await fetch_wrapper_default(cacheEndpoint, {
656
+ method: "DELETE",
657
+ headers: {
658
+ Authorization: `Bearer ${jwt}`
659
+ },
660
+ signal: controller.signal
661
+ });
662
+ clearTimeout(timeoutId);
663
+ if (!response.ok) {
664
+ const errorText = await response.text();
665
+ throw new Error(
666
+ `Cache clear failed with status ${response.status}: ${errorText}`
667
+ );
668
+ }
669
+ console.info("Graph cache cleared successfully");
670
+ return true;
671
+ } catch (error) {
672
+ if (error.name === "AbortError") {
673
+ throw new Error(`Request timeout after ${this.timeout}ms`);
674
+ }
675
+ console.error(`Error clearing cache: ${error.message}`);
676
+ throw new Error(`Failed to clear cache: ${error.message}`);
677
+ }
678
+ }
679
+ /**
680
+ * Get cache statistics
681
+ * @param jwt - JWT token for authorization (required)
682
+ * @returns Cache statistics
683
+ * @throws Error on stats retrieval failures
684
+ */
685
+ async getCacheStats(jwt) {
686
+ if (!jwt) {
687
+ throw new Error("JWT must be provided");
688
+ }
689
+ const statsEndpoint = `${this.apiBase}cache/stats`;
690
+ try {
691
+ const controller = new AbortController2();
692
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
693
+ const response = await fetch_wrapper_default(statsEndpoint, {
694
+ method: "GET",
695
+ headers: {
696
+ Authorization: `Bearer ${jwt}`
697
+ },
698
+ signal: controller.signal
699
+ });
700
+ clearTimeout(timeoutId);
701
+ if (!response.ok) {
702
+ const errorText = await response.text();
703
+ throw new Error(
704
+ `Stats retrieval failed with status ${response.status}: ${errorText}`
705
+ );
706
+ }
707
+ const stats = await response.json();
708
+ console.debug(
709
+ `Cache stats: ${stats.cached_snapshots || 0} snapshots cached`
710
+ );
711
+ return stats;
712
+ } catch (error) {
713
+ if (error.name === "AbortError") {
714
+ throw new Error(`Request timeout after ${this.timeout}ms`);
715
+ }
716
+ console.error(`Error getting cache stats: ${error.message}`);
717
+ throw new Error(`Failed to get cache stats: ${error.message}`);
718
+ }
719
+ }
720
+ /**
721
+ * Convenience method for querying with specific options
722
+ * @param snapshotHash - SHA256 hash of the codebase snapshot
723
+ * @param queryText - Natural language query for retrieval
724
+ * @param jwt - JWT token for authorization (required)
725
+ * @param budgetTokens - Maximum token budget for results
726
+ * @param flowStrength - Flow intensity multiplier
727
+ * @param blendAlpha - Blending factor for scores
728
+ * @param hopDepth - Depth of local neighborhood
729
+ * @param maxIterations - Maximum flood-walk iterations
730
+ * @param split - Fraction of budget for full chunks
731
+ * @param formatter - Output format "standard" or "compact"
732
+ * @returns Retrieval results
733
+ */
734
+ async queryWithOptions(snapshotHash, queryText, jwt, budgetTokens = 3e3, flowStrength = 1.5, blendAlpha = 0.8, hopDepth = 2, maxIterations = 12, split = 0.8, formatter = "standard") {
735
+ const options = {
736
+ flow_strength: flowStrength,
737
+ blend_alpha: blendAlpha,
738
+ hop_depth: hopDepth,
739
+ max_iterations: maxIterations,
740
+ split,
741
+ formatter
742
+ };
743
+ return this.query(snapshotHash, queryText, budgetTokens, jwt, options);
744
+ }
745
+ /**
746
+ * Close the HTTP client connection (no-op for fetch)
747
+ */
748
+ close() {
749
+ }
750
+ };
751
+
752
+ export { AuthHttpClient, RetrievalHttpClient, SyncHttpClient, decodeJWT, fetch_wrapper_default as fetch };
753
+ //# sourceMappingURL=index.js.map
16
754
  //# sourceMappingURL=index.js.map