@abapify/adt-server 0.0.0 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2124 @@
1
+ import { A as sourceVersionReadResponse, D as parsePageQuery, E as parsePackageTreeQuery, I as transportSourceManifestBody, L as transportSourceManifestResponse, M as transportListResponse, N as transportObjectsResponse, O as parseTransportSearchQuery, P as transportPathParameter, S as packageSearchResult, T as parsePackageSearchQuery, _ as objectSourceReadBody, a as atcDocumentationReadResponse, b as packagePathParameter, c as atcRunResponse, d as objectMetadataResponse, f as objectNamePathParameter, g as objectSourceHistoryResponse, h as objectSearchResult, i as atcDocumentationReadBody, j as transportDetailResponse, k as sourceVersionReadBody, l as badiResponse, n as MAX_PACKAGE_SEARCH_RESULTS, o as atcFindingResponse, p as objectPageResponse, r as MAX_SOURCE_BYTES, s as atcRunBody, t as MAX_ATC_DOCUMENTATION_BYTES, v as objectTypePathParameter, w as parseObjectSearchQuery, y as packagePageResponse } from "./rest-schemas-Dwj5ck3i.mjs";
2
+ import http from "node:http";
3
+ import { createDestinationContextRegistry, createHttpMcpHandler, createMcpInvocationVerifier, resolveObjectUri } from "@abapify/adt-mcp";
4
+ import { createCipheriv, createDecipheriv, createHash, createHmac, createPublicKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
5
+ import { AdtResponseTooLargeError, SourceVersionTooLargeError, assertAdtUri, createAdtClient, runWithAdtAbortSignal } from "@abapify/adt-client";
6
+ import { z } from "zod";
7
+ import { readFile } from "node:fs/promises";
8
+ import { request } from "node:https";
9
+ import { BadiService, ExactSourceHistoryService } from "@abapify/adt-services";
10
+
11
+ //#region src/sealed-capability.ts
12
+ function assertSecret(value, name) {
13
+ const secret = value?.trim();
14
+ if (!secret) throw new Error(`${name} secret is required and must be a stable, deployment-shared value.`);
15
+ return secret;
16
+ }
17
+ const REST_CAPABILITY_DEFAULT_TTL_MS = 3e5;
18
+ const REST_CAPABILITY_DEFAULT_MAX_LENGTH = 8192;
19
+ function throwInvalidTtl(maxTtlMs) {
20
+ throw new Error(`Capability TTL must be between 1ms and ${maxTtlMs}ms.`);
21
+ }
22
+ function isValidCapability(payload, destination, now) {
23
+ if (!payload) return false;
24
+ if (payload.d !== destination) return false;
25
+ if (payload.e <= now) return false;
26
+ return true;
27
+ }
28
+ function createRestSealedCapabilityService(options) {
29
+ return createSealedCapabilityService({
30
+ ...options,
31
+ maxTtlMs: options.maxTtlMs ?? 3e5,
32
+ maxCapabilityLength: options.maxCapabilityLength ?? 8192,
33
+ version: options.version ?? "v1"
34
+ });
35
+ }
36
+ function createSealedCapabilityService(options) {
37
+ const secret = assertSecret(options.secret, options.namespace);
38
+ const now = options.now ?? Date.now;
39
+ const ttlMs = options.ttlMs ?? options.maxTtlMs;
40
+ if (!Number.isSafeInteger(ttlMs)) throwInvalidTtl(options.maxTtlMs);
41
+ if (ttlMs < 1 || ttlMs > options.maxTtlMs) throwInvalidTtl(options.maxTtlMs);
42
+ const key = createHash("sha256").update(secret).digest();
43
+ function isSealedCapabilityPayload(parsed) {
44
+ if (parsed.v !== 1) return false;
45
+ if (typeof parsed.d !== "string") return false;
46
+ if (typeof parsed.u !== "string") return false;
47
+ if (!Number.isSafeInteger(parsed.e)) return false;
48
+ return parsed.d.length > 0 && options.validateUri(parsed.u);
49
+ }
50
+ function parsePayload(value) {
51
+ let parsed;
52
+ try {
53
+ parsed = JSON.parse(value);
54
+ } catch {
55
+ return;
56
+ }
57
+ if (!parsed || typeof parsed !== "object") return void 0;
58
+ const record = parsed;
59
+ if (!isSealedCapabilityPayload(record)) return void 0;
60
+ return record;
61
+ }
62
+ function isBase64UrlSafe(value) {
63
+ return /^[A-Za-z0-9_-]+$/u.test(value);
64
+ }
65
+ function parseCapabilityParts(capability) {
66
+ const [namespace, version, encodedIv, encodedCiphertext, extra] = capability.split(".");
67
+ if (namespace !== options.namespace) return void 0;
68
+ if (version !== options.version) return void 0;
69
+ if (!encodedIv) return void 0;
70
+ if (!encodedCiphertext) return void 0;
71
+ if (extra !== void 0) return void 0;
72
+ if (!isBase64UrlSafe(encodedIv)) return void 0;
73
+ if (!isBase64UrlSafe(encodedCiphertext)) return void 0;
74
+ return {
75
+ namespace,
76
+ version,
77
+ encodedIv,
78
+ encodedCiphertext
79
+ };
80
+ }
81
+ function decryptCiphertext(encodedIv, encodedCiphertext) {
82
+ try {
83
+ const initializationVector = Buffer.from(encodedIv, "base64url");
84
+ const encrypted = Buffer.from(encodedCiphertext, "base64url");
85
+ if (initializationVector.length !== 12) return void 0;
86
+ if (encrypted.length <= 16) return void 0;
87
+ const decipher = createDecipheriv("aes-256-gcm", key, initializationVector, { authTagLength: 16 });
88
+ decipher.setAuthTag(encrypted.subarray(-16));
89
+ return Buffer.concat([decipher.update(encrypted.subarray(0, -16)), decipher.final()]).toString("utf8");
90
+ } catch {
91
+ return;
92
+ }
93
+ }
94
+ function unseal(capability) {
95
+ const parts = parseCapabilityParts(capability);
96
+ if (!parts) return void 0;
97
+ const plaintext = decryptCiphertext(parts.encodedIv, parts.encodedCiphertext);
98
+ if (!plaintext) return void 0;
99
+ return parsePayload(plaintext);
100
+ }
101
+ return {
102
+ issue(destination, uri) {
103
+ if (!destination || !options.validateUri(uri)) throw options.createError();
104
+ const initializationVector = randomBytes(12);
105
+ const cipher = createCipheriv("aes-256-gcm", key, initializationVector);
106
+ const ciphertext = Buffer.concat([
107
+ cipher.update(JSON.stringify({
108
+ v: 1,
109
+ d: destination,
110
+ u: uri,
111
+ e: now() + ttlMs
112
+ }), "utf8"),
113
+ cipher.final(),
114
+ cipher.getAuthTag()
115
+ ]);
116
+ const capability = `${options.namespace}.${options.version}.${initializationVector.toString("base64url")}.${ciphertext.toString("base64url")}`;
117
+ if (capability.length > options.maxCapabilityLength) throw options.createError();
118
+ return capability;
119
+ },
120
+ resolve(capability, destination) {
121
+ const payload = unseal(capability);
122
+ if (!isValidCapability(payload, destination, now())) throw options.createError();
123
+ return payload.u;
124
+ }
125
+ };
126
+ }
127
+
128
+ //#endregion
129
+ //#region src/atc-documentation-capabilities.ts
130
+ const DOCUMENTATION_URI = /^\/sap\/bc\/adt\/documentation\/atc\/documents\/itemid\/[A-Za-z0-9_-]+\/index\/\d+$/u;
131
+ var RestAtcDocumentationCapabilityError = class extends Error {
132
+ constructor() {
133
+ super("ATC documentation capability is unavailable.");
134
+ this.name = "RestAtcDocumentationCapabilityError";
135
+ }
136
+ };
137
+ function isTrustedDocumentationUri(value) {
138
+ return value === value.trim() && DOCUMENTATION_URI.test(value);
139
+ }
140
+ /**
141
+ * Issues short-lived encrypted capabilities for one trusted ATC-documentation
142
+ * relation. The ADT URI is neither visible in nor chosen by the REST client.
143
+ */
144
+ function createRestAtcDocumentationCapabilityService(options) {
145
+ const service = createRestSealedCapabilityService({
146
+ secret: options.secret,
147
+ now: options.now,
148
+ ttlMs: options.ttlMs,
149
+ namespace: "atcdoc",
150
+ validateUri: isTrustedDocumentationUri,
151
+ createError: () => new RestAtcDocumentationCapabilityError()
152
+ });
153
+ return {
154
+ issue(input) {
155
+ return service.issue(input.destination, input.documentationUri);
156
+ },
157
+ resolve(input) {
158
+ return { documentationUri: service.resolve(input.documentationCapability, input.destination) };
159
+ }
160
+ };
161
+ }
162
+
163
+ //#endregion
164
+ //#region src/source-capabilities.ts
165
+ const ADT_PATH_PREFIX = "/sap/bc/adt/";
166
+ var RestSourceCapabilityError = class extends Error {
167
+ constructor() {
168
+ super("Source capability is unavailable.");
169
+ this.name = "RestSourceCapabilityError";
170
+ }
171
+ };
172
+ function isSafeAdtSourceUri(value) {
173
+ return value.startsWith(ADT_PATH_PREFIX) && value === value.trim() && !/[\\\s\u0000-\u0008\u000e-\u001f\u007f]/u.test(value);
174
+ }
175
+ /**
176
+ * Issues short-lived encrypted immutable-source capabilities. The source URI
177
+ * is never a client-controlled input and is not readable from the capability.
178
+ */
179
+ function createRestSourceCapabilityService(options) {
180
+ const service = createRestSealedCapabilityService({
181
+ secret: options.secret,
182
+ now: options.now,
183
+ ttlMs: options.ttlMs,
184
+ namespace: "src",
185
+ validateUri: isSafeAdtSourceUri,
186
+ createError: () => new RestSourceCapabilityError()
187
+ });
188
+ return {
189
+ issue(input) {
190
+ return service.issue(input.destination, input.sourceUri);
191
+ },
192
+ resolve(input) {
193
+ return { sourceUri: service.resolve(input.sourceCapability, input.destination) };
194
+ }
195
+ };
196
+ }
197
+
198
+ //#endregion
199
+ //#region src/page-cursors.ts
200
+ const MAX_CURSOR_LENGTH = 4096;
201
+ var RestPageCursorError = class extends Error {
202
+ constructor() {
203
+ super("Invalid or mismatched page cursor.");
204
+ this.name = "RestPageCursorError";
205
+ }
206
+ };
207
+ function compare(left, right) {
208
+ if (left < right) return -1;
209
+ if (left > right) return 1;
210
+ return 0;
211
+ }
212
+ /**
213
+ * Creates integrity-protected, query-bound cursors for bounded fresh REST
214
+ * snapshots. Cursors contain no ADT URI, credentials, source or SAP body.
215
+ */
216
+ function createRestPageCursorService(options) {
217
+ const secret = assertSecret(options.secret, "Page cursor");
218
+ const now = options.now ?? Date.now;
219
+ const sign = (encoded) => createHmac("sha256", secret).update(encoded).digest("base64url");
220
+ const encode = (payload) => {
221
+ const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
222
+ return `${encoded}.${sign(encoded)}`;
223
+ };
224
+ const decodeCursorParts = (cursor) => {
225
+ if (typeof cursor !== "string") return void 0;
226
+ if (cursor.length > MAX_CURSOR_LENGTH) return void 0;
227
+ const [encoded, signature, ...extra] = cursor.split(".");
228
+ if (!encoded) return void 0;
229
+ if (!signature) return void 0;
230
+ if (extra.length > 0) return void 0;
231
+ return {
232
+ encoded,
233
+ signature
234
+ };
235
+ };
236
+ const isCursorSignatureValid = (encoded, signature) => {
237
+ const expected = Buffer.from(sign(encoded));
238
+ const actual = Buffer.from(signature);
239
+ if (expected.length !== actual.length) return false;
240
+ return timingSafeEqual(expected, actual);
241
+ };
242
+ const parseCursorPayload = (encoded, fingerprint) => {
243
+ let payload;
244
+ try {
245
+ payload = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
246
+ } catch {
247
+ return;
248
+ }
249
+ if (payload.v !== 1) return void 0;
250
+ if (payload.fingerprint !== fingerprint) return void 0;
251
+ if (typeof payload.afterKey !== "string") return void 0;
252
+ if (payload.afterKey.length === 0) return void 0;
253
+ return payload.afterKey;
254
+ };
255
+ const decode = (cursor, fingerprint) => {
256
+ const parts = decodeCursorParts(cursor);
257
+ if (!parts) throw new RestPageCursorError();
258
+ if (!isCursorSignatureValid(parts.encoded, parts.signature)) throw new RestPageCursorError();
259
+ const afterKey = parseCursorPayload(parts.encoded, fingerprint);
260
+ if (!afterKey) throw new RestPageCursorError();
261
+ return afterKey;
262
+ };
263
+ return { paginate(input) {
264
+ if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 200) throw new RestPageCursorError();
265
+ const afterKey = input.cursor ? decode(input.cursor, input.fingerprint) : void 0;
266
+ const sorted = [...input.data].sort((left, right) => compare(input.keyOf(left), input.keyOf(right)));
267
+ for (let index = 1; index < sorted.length; index += 1) if (input.keyOf(sorted[index - 1]) === input.keyOf(sorted[index])) throw new Error("REST live result contains duplicate pagination key");
268
+ const remaining = afterKey ? sorted.filter((item) => compare(input.keyOf(item), afterKey) > 0) : sorted;
269
+ const data = remaining.slice(0, input.limit);
270
+ return {
271
+ data,
272
+ nextCursor: data.length > 0 && data.length < remaining.length ? encode({
273
+ v: 1,
274
+ fingerprint: input.fingerprint,
275
+ afterKey: input.keyOf(data.at(-1))
276
+ }) : null,
277
+ truncated: input.truncated,
278
+ observedAt: new Date(now()).toISOString()
279
+ };
280
+ } };
281
+ }
282
+
283
+ //#endregion
284
+ //#region src/request-handler.ts
285
+ const MAX_JSON_BODY_BYTES = 65536;
286
+ var InvalidJsonBodyError = class extends Error {};
287
+ var InvalidPathParameterError = class extends Error {};
288
+ async function readJsonBody(request) {
289
+ const chunks = [];
290
+ let size = 0;
291
+ for await (const chunk of request) {
292
+ const bytes = Buffer.from(chunk);
293
+ size += bytes.length;
294
+ if (size > MAX_JSON_BODY_BYTES) throw new InvalidJsonBodyError();
295
+ chunks.push(bytes);
296
+ }
297
+ try {
298
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
299
+ } catch {
300
+ throw new InvalidJsonBodyError();
301
+ }
302
+ }
303
+ function readQuery(request) {
304
+ const url = new URL(request.url ?? "/", "https://adt-server.invalid");
305
+ return Object.fromEntries(url.searchParams.entries());
306
+ }
307
+ function decodePathParameter(value) {
308
+ try {
309
+ return decodeURIComponent(value);
310
+ } catch {
311
+ throw new InvalidPathParameterError();
312
+ }
313
+ }
314
+ function writeProblem(response, status, title) {
315
+ response.writeHead(status, { "content-type": "application/problem+json" });
316
+ response.end(JSON.stringify({
317
+ title,
318
+ status
319
+ }));
320
+ }
321
+ function sendJson(response, data) {
322
+ response.writeHead(200, { "content-type": "application/json" });
323
+ response.end(JSON.stringify(data));
324
+ }
325
+ function writeNotFound(response) {
326
+ writeProblem(response, 404, "Not found");
327
+ }
328
+ function parseObjectType(raw) {
329
+ return objectTypePathParameter.parse(decodePathParameter(raw));
330
+ }
331
+ function parseObjectName(raw) {
332
+ return objectNamePathParameter.parse(decodePathParameter(raw));
333
+ }
334
+ function parsePackageName(raw) {
335
+ return packagePathParameter.parse(decodePathParameter(raw));
336
+ }
337
+ function validateObjectSource(result, maxBytes) {
338
+ if (typeof result.source !== "string") throw new Error("Bounded object source operation returned an invalid body");
339
+ if (result.bytes !== Buffer.byteLength(result.source, "utf8")) throw new Error("Bounded object source operation returned an invalid body");
340
+ if (result.bytes > maxBytes) throw new Error("Bounded object source operation returned an invalid body");
341
+ }
342
+ function validateSourceVersionResult(result, maxBytes) {
343
+ if (typeof result.source !== "string") throw new Error("Bounded source operation returned an invalid body");
344
+ if (result.bytes !== Buffer.byteLength(result.source, "utf8")) throw new Error("Bounded source operation returned an invalid body");
345
+ if (result.bytes > maxBytes) throw new Error("Bounded source operation returned an invalid body");
346
+ }
347
+ function validateAtcDocumentationResult(result, maxBytes) {
348
+ if (typeof result.html !== "string") throw new Error("Bounded ATC documentation operation returned an invalid body");
349
+ if (result.bytes !== Buffer.byteLength(result.html, "utf8")) throw new Error("Bounded ATC documentation operation returned an invalid body");
350
+ if (result.bytes > maxBytes) throw new Error("Bounded ATC documentation operation returned an invalid body");
351
+ }
352
+ const knownErrorRules = [
353
+ {
354
+ test: (e) => e instanceof z.ZodError,
355
+ status: 400,
356
+ title: "Invalid request"
357
+ },
358
+ {
359
+ test: (e) => e instanceof InvalidJsonBodyError,
360
+ status: 400,
361
+ title: "Invalid request"
362
+ },
363
+ {
364
+ test: (e) => e instanceof InvalidPathParameterError,
365
+ status: 400,
366
+ title: "Invalid request"
367
+ },
368
+ {
369
+ test: (e) => e instanceof RestPageCursorError,
370
+ status: 400,
371
+ title: "Invalid request"
372
+ },
373
+ {
374
+ test: (e) => e instanceof RestAtcDocumentationCapabilityError,
375
+ status: 404,
376
+ title: "Documentation unavailable"
377
+ },
378
+ {
379
+ test: (e) => e instanceof AdtResponseTooLargeError,
380
+ status: 413,
381
+ title: "Documentation too large"
382
+ },
383
+ {
384
+ test: (e) => e instanceof RestSourceCapabilityError,
385
+ status: 404,
386
+ title: "Source unavailable"
387
+ },
388
+ {
389
+ test: (e) => e instanceof SourceVersionTooLargeError,
390
+ status: 413,
391
+ title: "Source too large"
392
+ }
393
+ ];
394
+ function handleKnownError(response, error) {
395
+ for (const rule of knownErrorRules) if (rule.test(error)) {
396
+ writeProblem(response, rule.status, rule.title);
397
+ return true;
398
+ }
399
+ return false;
400
+ }
401
+ function toRestTransportSourceManifest(manifest, capabilities, destination) {
402
+ const toVersion = (version) => {
403
+ const { sourceUri, ...metadata } = version;
404
+ return {
405
+ ...metadata,
406
+ sourceCapability: capabilities.issue({
407
+ destination,
408
+ sourceUri
409
+ })
410
+ };
411
+ };
412
+ return {
413
+ requestedTransports: manifest.requestedTransports,
414
+ scopeTransports: manifest.scopeTransports,
415
+ inventory: manifest.inventory.map(({ uri: _uri, ...entry }) => entry),
416
+ entries: manifest.entries.map((entry) => {
417
+ const { component: { sourceUri: _sourceUri, versionsUri: _versionsUri, ...component }, base, head, ...metadata } = entry;
418
+ return {
419
+ ...metadata,
420
+ component,
421
+ ...base ? { base: toVersion(base) } : {},
422
+ ...head ? { head: toVersion(head) } : {}
423
+ };
424
+ })
425
+ };
426
+ }
427
+ function toRestAtcRun(result, capabilities, destination) {
428
+ return {
429
+ checkVariant: result.checkVariant,
430
+ findings: result.findings.map(({ documentationUri, ...finding }) => {
431
+ return {
432
+ ...atcFindingResponse.strip().parse(finding),
433
+ ...documentationUri ? { documentationCapability: capabilities.issue({
434
+ destination,
435
+ documentationUri
436
+ }) } : {}
437
+ };
438
+ })
439
+ };
440
+ }
441
+ async function ensureRestAuthorized(ctx, request, response) {
442
+ if (!ctx.options.restAuthorizer) {
443
+ writeNotFound(response);
444
+ return false;
445
+ }
446
+ let authorized;
447
+ try {
448
+ authorized = await ctx.options.restAuthorizer.authorize(request);
449
+ } catch {
450
+ authorized = false;
451
+ }
452
+ if (!authorized) {
453
+ writeProblem(response, 401, "Unauthorized");
454
+ return false;
455
+ }
456
+ return true;
457
+ }
458
+ async function handleMcp(ctx, request, response) {
459
+ if (!ctx.mcpHandler) {
460
+ writeNotFound(response);
461
+ return;
462
+ }
463
+ await ctx.mcpHandler.handle(request, response);
464
+ }
465
+ async function handleHealth(_ctx, _request, response) {
466
+ sendJson(response, { status: "ok" });
467
+ }
468
+ async function handleReady(_ctx, _request, response) {
469
+ sendJson(response, { status: "ready" });
470
+ }
471
+ async function handleOpenApiJson(_ctx, _request, response) {
472
+ const { openApiDocument } = await import("./openapi-DRrSJgE_.mjs");
473
+ sendJson(response, openApiDocument);
474
+ }
475
+ async function handleOpenApiYaml(_ctx, _request, response) {
476
+ const { openApiYaml } = await import("./openapi-DRrSJgE_.mjs");
477
+ response.writeHead(200, { "content-type": "application/yaml" });
478
+ response.end(openApiYaml());
479
+ }
480
+ async function handleListDestinations(ctx, _request, response) {
481
+ sendJson(response, { data: await ctx.options.operations.listDestinations() });
482
+ }
483
+ async function handleTransportList(ctx, request, response, match) {
484
+ try {
485
+ const destination = match[1];
486
+ sendJson(response, transportListResponse.parse(await ctx.options.operations.listTransports(destination, parseTransportSearchQuery(readQuery(request)))));
487
+ } catch (error) {
488
+ if (handleKnownError(response, error)) return;
489
+ throw error;
490
+ }
491
+ }
492
+ async function handlePackageSearch(ctx, request, response, match) {
493
+ try {
494
+ const destination = match[1];
495
+ const { criteria, page } = parsePackageSearchQuery(readQuery(request));
496
+ const result = packageSearchResult.parse(await ctx.options.operations.searchPackages(destination, criteria));
497
+ sendJson(response, packagePageResponse.parse(ctx.pageCursors.paginate({
498
+ ...result,
499
+ ...page,
500
+ fingerprint: `packages:${destination}:${criteria.q ?? "*"}:${criteria.maxResults ?? 5e3}`,
501
+ keyOf: (entry) => entry.name
502
+ })));
503
+ } catch (error) {
504
+ if (handleKnownError(response, error)) return;
505
+ throw error;
506
+ }
507
+ }
508
+ async function handleObjectSearch(ctx, request, response, match) {
509
+ try {
510
+ const destination = match[1];
511
+ const { criteria, page } = parseObjectSearchQuery(readQuery(request));
512
+ const result = objectSearchResult.parse(await ctx.options.operations.searchObjects(destination, criteria));
513
+ sendJson(response, objectPageResponse.parse(ctx.pageCursors.paginate({
514
+ ...result,
515
+ ...page,
516
+ fingerprint: `objects:${destination}:${criteria.query ?? "*"}:${criteria.packageName ?? ""}:${criteria.objectType ?? ""}:${criteria.maxResults ?? 5e3}`,
517
+ keyOf: (entry) => entry.canonicalKey
518
+ })));
519
+ } catch (error) {
520
+ if (handleKnownError(response, error)) return;
521
+ throw error;
522
+ }
523
+ }
524
+ async function handlePackageObjects(ctx, request, response, match) {
525
+ try {
526
+ const destination = match[1];
527
+ const packageName = parsePackageName(match[2]);
528
+ const page = parsePageQuery(readQuery(request));
529
+ const result = objectSearchResult.parse(await ctx.options.operations.listPackageObjects(destination, packageName));
530
+ sendJson(response, objectPageResponse.parse(ctx.pageCursors.paginate({
531
+ ...result,
532
+ ...page,
533
+ fingerprint: `package-objects:${destination}:${packageName.toUpperCase()}:5000`,
534
+ keyOf: (entry) => entry.canonicalKey
535
+ })));
536
+ } catch (error) {
537
+ if (handleKnownError(response, error)) return;
538
+ throw error;
539
+ }
540
+ }
541
+ async function handlePackageTree(ctx, request, response, match) {
542
+ try {
543
+ const destination = match[1];
544
+ const { rootPackage, page } = parsePackageTreeQuery(readQuery(request));
545
+ const result = packageSearchResult.parse(await ctx.options.operations.getPackageTree(destination, rootPackage));
546
+ sendJson(response, packagePageResponse.parse(ctx.pageCursors.paginate({
547
+ ...result,
548
+ ...page,
549
+ fingerprint: `package-tree:${destination}:${rootPackage}`,
550
+ keyOf: (entry) => `${entry.name === rootPackage ? "0" : "1"}:${entry.name}`
551
+ })));
552
+ } catch (error) {
553
+ if (handleKnownError(response, error)) return;
554
+ throw error;
555
+ }
556
+ }
557
+ async function handleObjectMetadata(ctx, request, response, match) {
558
+ try {
559
+ const destination = match[1];
560
+ const objectType = parseObjectType(match[2]);
561
+ const objectName = parseObjectName(match[3]);
562
+ z.object({}).strict().parse(readQuery(request));
563
+ if (!ctx.options.operations.getObjectMetadata) {
564
+ writeNotFound(response);
565
+ return;
566
+ }
567
+ sendJson(response, objectMetadataResponse.parse(await ctx.options.operations.getObjectMetadata(destination, objectType, objectName)));
568
+ } catch (error) {
569
+ if (handleKnownError(response, error)) return;
570
+ throw error;
571
+ }
572
+ }
573
+ async function handleBadiRead(ctx, request, response, match) {
574
+ try {
575
+ const destination = match[1];
576
+ const badiName = parseObjectName(match[2]);
577
+ const query = z.object({ implementations: z.enum(["true", "false"]).optional().transform((value) => value === "true") }).strict().parse(readQuery(request));
578
+ if (!ctx.options.operations.getBadi) {
579
+ writeNotFound(response);
580
+ return;
581
+ }
582
+ sendJson(response, badiResponse.parse(await ctx.options.operations.getBadi(destination, badiName, { includeImplementations: query.implementations })));
583
+ } catch (error) {
584
+ if (handleKnownError(response, error)) return;
585
+ throw error;
586
+ }
587
+ }
588
+ async function handleObjectSourceHistory(ctx, request, response, match) {
589
+ try {
590
+ const destination = match[1];
591
+ const objectType = parseObjectType(match[2]);
592
+ const objectName = parseObjectName(match[3]);
593
+ z.object({}).strict().parse(readQuery(request));
594
+ if (!ctx.options.operations.getObjectSourceHistory) {
595
+ writeNotFound(response);
596
+ return;
597
+ }
598
+ sendJson(response, objectSourceHistoryResponse.parse(await ctx.options.operations.getObjectSourceHistory(destination, objectType, objectName)));
599
+ } catch (error) {
600
+ if (handleKnownError(response, error)) return;
601
+ throw error;
602
+ }
603
+ }
604
+ async function handleObjectSourceRead(ctx, request, response, match) {
605
+ try {
606
+ const destination = match[1];
607
+ const objectType = parseObjectType(match[2]);
608
+ const objectName = parseObjectName(match[3]);
609
+ const input = objectSourceReadBody.parse(await readJsonBody(request));
610
+ if (!ctx.options.operations.readObjectSource) {
611
+ writeNotFound(response);
612
+ return;
613
+ }
614
+ const result = await ctx.options.operations.readObjectSource({
615
+ destination,
616
+ objectType,
617
+ objectName,
618
+ ...input.version ? { version: input.version } : {}
619
+ });
620
+ validateObjectSource(result, MAX_SOURCE_BYTES);
621
+ sendJson(response, sourceVersionReadResponse.parse(result));
622
+ } catch (error) {
623
+ if (handleKnownError(response, error)) return;
624
+ throw error;
625
+ }
626
+ }
627
+ async function handleAtcRun(ctx, request, response, match) {
628
+ try {
629
+ const destination = match[1];
630
+ if (!ctx.options.operations.runAtc) {
631
+ writeNotFound(response);
632
+ return;
633
+ }
634
+ const input = atcRunBody.parse(await readJsonBody(request));
635
+ const result = await ctx.options.operations.runAtc({
636
+ destination,
637
+ ...input
638
+ });
639
+ sendJson(response, atcRunResponse.parse(toRestAtcRun(result, ctx.atcDocumentationCapabilities, destination)));
640
+ } catch (error) {
641
+ if (handleKnownError(response, error)) return;
642
+ throw error;
643
+ }
644
+ }
645
+ async function handleAtcDocumentationRead(ctx, request, response, match) {
646
+ try {
647
+ const destination = match[1];
648
+ if (!ctx.options.operations.readAtcFindingDocumentation) {
649
+ writeNotFound(response);
650
+ return;
651
+ }
652
+ const input = atcDocumentationReadBody.parse(await readJsonBody(request));
653
+ const maxBytes = input.maxBytes ?? 1048576;
654
+ const { documentationUri } = ctx.atcDocumentationCapabilities.resolve({
655
+ documentationCapability: input.documentationCapability,
656
+ destination
657
+ });
658
+ const result = await ctx.options.operations.readAtcFindingDocumentation({
659
+ destination,
660
+ documentationUri,
661
+ maxBytes
662
+ });
663
+ validateAtcDocumentationResult(result, maxBytes);
664
+ sendJson(response, atcDocumentationReadResponse.parse(result));
665
+ } catch (error) {
666
+ if (handleKnownError(response, error)) return;
667
+ throw error;
668
+ }
669
+ }
670
+ async function handleTransportDetail(ctx, _request, response, match) {
671
+ try {
672
+ const destination = match[1];
673
+ const transport = transportPathParameter.parse(match[2]);
674
+ if (!ctx.options.operations.getTransportDetail) {
675
+ writeNotFound(response);
676
+ return;
677
+ }
678
+ sendJson(response, transportDetailResponse.parse(await ctx.options.operations.getTransportDetail(destination, transport)));
679
+ } catch (error) {
680
+ if (handleKnownError(response, error)) return;
681
+ throw error;
682
+ }
683
+ }
684
+ async function handleTransportObjects(ctx, _request, response, match) {
685
+ try {
686
+ const destination = match[1];
687
+ const transport = transportPathParameter.parse(match[2]);
688
+ if (!ctx.options.operations.listTransportObjects) {
689
+ writeNotFound(response);
690
+ return;
691
+ }
692
+ sendJson(response, transportObjectsResponse.parse(await ctx.options.operations.listTransportObjects(destination, transport)));
693
+ } catch (error) {
694
+ if (handleKnownError(response, error)) return;
695
+ throw error;
696
+ }
697
+ }
698
+ async function handleTransportSourceManifest(ctx, request, response, match) {
699
+ try {
700
+ const destination = match[1];
701
+ if (!ctx.options.operations.buildTransportSourceManifest) {
702
+ writeNotFound(response);
703
+ return;
704
+ }
705
+ const input = transportSourceManifestBody.parse(await readJsonBody(request));
706
+ const manifest = await ctx.options.operations.buildTransportSourceManifest(destination, input);
707
+ sendJson(response, transportSourceManifestResponse.parse(toRestTransportSourceManifest(manifest, ctx.sourceCapabilities, destination)));
708
+ } catch (error) {
709
+ if (handleKnownError(response, error)) return;
710
+ throw error;
711
+ }
712
+ }
713
+ async function handleSourceVersionRead(ctx, request, response, match) {
714
+ try {
715
+ const destination = match[1];
716
+ if (!ctx.options.operations.readImmutableSource) {
717
+ writeNotFound(response);
718
+ return;
719
+ }
720
+ const input = sourceVersionReadBody.parse(await readJsonBody(request));
721
+ const source = ctx.sourceCapabilities.resolve({
722
+ sourceCapability: input.sourceCapability,
723
+ destination
724
+ });
725
+ const result = await ctx.options.operations.readImmutableSource({
726
+ destination,
727
+ sourceUri: source.sourceUri,
728
+ maxBytes: input.maxBytes
729
+ });
730
+ validateSourceVersionResult(result, input.maxBytes);
731
+ sendJson(response, sourceVersionReadResponse.parse(result));
732
+ } catch (error) {
733
+ if (handleKnownError(response, error)) return;
734
+ throw error;
735
+ }
736
+ }
737
+ const defaultRoutes = [
738
+ {
739
+ pattern: /^\/mcp\/?$/u,
740
+ requiresRest: false,
741
+ handler: handleMcp
742
+ },
743
+ {
744
+ method: "GET",
745
+ pattern: /^\/healthz$/u,
746
+ requiresRest: false,
747
+ handler: handleHealth
748
+ },
749
+ {
750
+ method: "GET",
751
+ pattern: /^\/readyz$/u,
752
+ requiresRest: false,
753
+ handler: handleReady
754
+ },
755
+ {
756
+ method: "GET",
757
+ pattern: /^\/openapi\.json$/u,
758
+ requiresRest: false,
759
+ handler: handleOpenApiJson
760
+ },
761
+ {
762
+ method: "GET",
763
+ pattern: /^\/openapi\.yaml$/u,
764
+ requiresRest: false,
765
+ handler: handleOpenApiYaml
766
+ },
767
+ {
768
+ method: "GET",
769
+ pattern: /^\/v1\/destinations$/u,
770
+ requiresRest: true,
771
+ handler: handleListDestinations
772
+ },
773
+ {
774
+ method: "GET",
775
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/transports$/u,
776
+ requiresRest: true,
777
+ handler: handleTransportList
778
+ },
779
+ {
780
+ method: "GET",
781
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/packages$/u,
782
+ requiresRest: true,
783
+ handler: handlePackageSearch
784
+ },
785
+ {
786
+ method: "GET",
787
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/objects$/u,
788
+ requiresRest: true,
789
+ handler: handleObjectSearch
790
+ },
791
+ {
792
+ method: "GET",
793
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/packages\/([^/]+)\/objects$/u,
794
+ requiresRest: true,
795
+ handler: handlePackageObjects
796
+ },
797
+ {
798
+ method: "GET",
799
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/packages\/tree$/u,
800
+ requiresRest: true,
801
+ handler: handlePackageTree
802
+ },
803
+ {
804
+ method: "GET",
805
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/objects\/([^/]+)\/([^/]+)$/u,
806
+ requiresRest: true,
807
+ handler: handleObjectMetadata
808
+ },
809
+ {
810
+ method: "GET",
811
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/badi\/([^/]+)$/u,
812
+ requiresRest: true,
813
+ handler: handleBadiRead
814
+ },
815
+ {
816
+ method: "GET",
817
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/objects\/([^/]+)\/([^/]+)\/source-history$/u,
818
+ requiresRest: true,
819
+ handler: handleObjectSourceHistory
820
+ },
821
+ {
822
+ method: "POST",
823
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/objects\/([^/]+)\/([^/]+)\/source:read$/u,
824
+ requiresRest: true,
825
+ handler: handleObjectSourceRead
826
+ },
827
+ {
828
+ method: "POST",
829
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/atc-runs$/u,
830
+ requiresRest: true,
831
+ handler: handleAtcRun
832
+ },
833
+ {
834
+ method: "POST",
835
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/atc-finding-documentation:read$/u,
836
+ requiresRest: true,
837
+ handler: handleAtcDocumentationRead
838
+ },
839
+ {
840
+ method: "GET",
841
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/transports\/([^/]+)$/u,
842
+ requiresRest: true,
843
+ handler: handleTransportDetail
844
+ },
845
+ {
846
+ method: "GET",
847
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/transports\/([^/]+)\/objects$/u,
848
+ requiresRest: true,
849
+ handler: handleTransportObjects
850
+ },
851
+ {
852
+ method: "POST",
853
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/transport-source-manifests$/u,
854
+ requiresRest: true,
855
+ handler: handleTransportSourceManifest
856
+ },
857
+ {
858
+ method: "POST",
859
+ pattern: /^\/v1\/destinations\/([a-z][a-z0-9-]{1,62})\/source-versions:read$/u,
860
+ requiresRest: true,
861
+ handler: handleSourceVersionRead
862
+ }
863
+ ];
864
+ function findRoute(method, path) {
865
+ for (const route of defaultRoutes) {
866
+ if (route.method && method !== route.method) continue;
867
+ const match = route.pattern.exec(path);
868
+ if (match) return {
869
+ route,
870
+ match
871
+ };
872
+ }
873
+ }
874
+ async function dispatchRoute(ctx, request, response, path) {
875
+ const found = findRoute(request.method, path);
876
+ if (!found) {
877
+ writeNotFound(response);
878
+ return;
879
+ }
880
+ const { route, match } = found;
881
+ if (route.requiresRest && !await ensureRestAuthorized(ctx, request, response)) return;
882
+ if (!route.requiresRest) {
883
+ await route.handler(ctx, request, response, match);
884
+ return;
885
+ }
886
+ await runWithRequestAbortSignal(request, response, () => route.handler(ctx, request, response, match));
887
+ }
888
+ async function runWithRequestAbortSignal(request, response, operation) {
889
+ const abortController = new AbortController();
890
+ const abort = () => {
891
+ if (!abortController.signal.aborted) abortController.abort();
892
+ };
893
+ const abortOnPrematureResponseClose = () => {
894
+ if (!response.writableEnded) abort();
895
+ };
896
+ request.once("aborted", abort);
897
+ response.once("close", abortOnPrematureResponseClose);
898
+ if (request.aborted || response.destroyed && !response.writableEnded) abort();
899
+ try {
900
+ return await runWithAdtAbortSignal(abortController.signal, operation);
901
+ } finally {
902
+ request.removeListener("aborted", abort);
903
+ response.removeListener("close", abortOnPrematureResponseClose);
904
+ }
905
+ }
906
+ function handleServerError(response, _error) {
907
+ if (response.headersSent) {
908
+ response.end();
909
+ return;
910
+ }
911
+ writeProblem(response, 500, "Internal server error");
912
+ }
913
+ function createRequestHandler(ctx) {
914
+ return (request, response) => {
915
+ const path = (request.url ?? "/").split("?", 1)[0];
916
+ dispatchRoute(ctx, request, response, path).catch((error) => handleServerError(response, error));
917
+ };
918
+ }
919
+
920
+ //#endregion
921
+ //#region src/server.ts
922
+ /**
923
+ * The ADT broker may return a direct adapter URI or a source capability
924
+ * previously issued by this same sidecar REST process. Redeem the latter
925
+ * before the MCP package can acquire a destination context or invoke SAP.
926
+ */
927
+ async function resolveMcpFrozenSource(resolveFrozenSource, sourceCapabilities, input) {
928
+ const resolved = await resolveFrozenSource(input);
929
+ if ("sourceUri" in resolved) return resolved;
930
+ return sourceCapabilities.resolve({
931
+ sourceCapability: resolved.sourceCapability,
932
+ destination: input.destination
933
+ });
934
+ }
935
+ function createServerSourceCapabilities(options) {
936
+ const mcpEnabled = !!options.mcp;
937
+ const restEnabled = !!options.restAuthorizer;
938
+ if (options.sourceCapabilities) return options.sourceCapabilities;
939
+ if (!mcpEnabled && !restEnabled) return void 0;
940
+ return createRestSourceCapabilityService({ secret: assertSecret(options.sourceCapabilitiesSecret, "sourceCapabilitiesSecret") });
941
+ }
942
+ function createServerAtcDocumentationCapabilities(options) {
943
+ if (options.atcDocumentationCapabilities) return options.atcDocumentationCapabilities;
944
+ if (!options.restAuthorizer) return void 0;
945
+ return createRestAtcDocumentationCapabilityService({ secret: assertSecret(options.atcDocumentationCapabilitiesSecret, "atcDocumentationCapabilitiesSecret") });
946
+ }
947
+ function createServerPageCursors(options) {
948
+ if (options.pageCursors) return options.pageCursors;
949
+ if (!options.restAuthorizer) return void 0;
950
+ return createRestPageCursorService({ secret: assertSecret(options.pageCursorSecret, "pageCursorSecret") });
951
+ }
952
+ function createServerMcpHandler(options, host, sourceCapabilities) {
953
+ if (!options.mcp) return void 0;
954
+ const mcpOptions = options.mcp;
955
+ return createHttpMcpHandler({
956
+ host,
957
+ allowedHosts: mcpOptions.allowedHosts,
958
+ authMode: "invocation",
959
+ invocationVerifier: mcpOptions.invocationVerifier,
960
+ destinationServer: {
961
+ destinationRegistry: mcpOptions.destinationRegistry,
962
+ requestIdentity: ({ invocation }) => {
963
+ if (!invocation) throw new Error("ADT Server MCP invocation is missing");
964
+ return {
965
+ principal: invocation.principal,
966
+ agentId: invocation.agentId
967
+ };
968
+ },
969
+ requestAccess: ({ invocation }) => invocation ? {
970
+ classes: invocation.classes,
971
+ destinationKeys: invocation.destinationKeys
972
+ } : void 0,
973
+ resolveFrozenSource: async (input) => {
974
+ if (!sourceCapabilities) throw new Error("Source capabilities are required for frozen source resolution");
975
+ return resolveMcpFrozenSource(mcpOptions.resolveFrozenSource, sourceCapabilities, input);
976
+ },
977
+ ...mcpOptions.consumeExecutionAuthorization ? { consumeExecutionAuthorization: mcpOptions.consumeExecutionAuthorization } : {},
978
+ ...mcpOptions.reportExecutionOutcome ? { reportExecutionOutcome: mcpOptions.reportExecutionOutcome } : {},
979
+ ...mcpOptions.executeWithDeadline ? { executeWithDeadline: mcpOptions.executeWithDeadline } : {}
980
+ }
981
+ });
982
+ }
983
+ async function startAdtServer(options) {
984
+ const host = options.host ?? "127.0.0.1";
985
+ const sourceCapabilities = createServerSourceCapabilities(options);
986
+ const atcDocumentationCapabilities = createServerAtcDocumentationCapabilities(options);
987
+ const pageCursors = createServerPageCursors(options);
988
+ const mcpHandler = createServerMcpHandler(options, host, sourceCapabilities);
989
+ const server = http.createServer(createRequestHandler({
990
+ options,
991
+ mcpHandler,
992
+ sourceCapabilities,
993
+ atcDocumentationCapabilities,
994
+ pageCursors
995
+ }));
996
+ await new Promise((resolve, reject) => {
997
+ server.once("error", reject);
998
+ server.listen(options.port ?? 3002, host, () => resolve());
999
+ });
1000
+ const address = server.address();
1001
+ let closed = false;
1002
+ return {
1003
+ url: `http://${host}:${address.port}`,
1004
+ close: async () => {
1005
+ if (closed) return;
1006
+ closed = true;
1007
+ const listenerClosed = new Promise((resolve) => server.close(() => resolve()));
1008
+ try {
1009
+ await mcpHandler?.close();
1010
+ await options.mcp?.destinationRegistry.shutdown();
1011
+ } finally {
1012
+ server.closeAllConnections();
1013
+ await listenerClosed;
1014
+ }
1015
+ }
1016
+ };
1017
+ }
1018
+
1019
+ //#endregion
1020
+ //#region src/broker.ts
1021
+ function isBrokerLease(value) {
1022
+ return typeof value === "object" && value !== null && typeof value.leaseId === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value.leaseId);
1023
+ }
1024
+ function record(value) {
1025
+ return value !== null && typeof value === "object" ? value : void 0;
1026
+ }
1027
+ function records(value) {
1028
+ return (Array.isArray(value) ? value : [value]).flatMap((entry) => {
1029
+ const parsed = record(entry);
1030
+ return parsed ? [parsed] : [];
1031
+ });
1032
+ }
1033
+ function stringField(value, key) {
1034
+ const field = value[key];
1035
+ return typeof field === "string" && field.trim() ? field.trim() : void 0;
1036
+ }
1037
+ function booleanField(value, key) {
1038
+ const field = value[key];
1039
+ return typeof field === "boolean" ? field : void 0;
1040
+ }
1041
+ function optionalText(value) {
1042
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1043
+ }
1044
+ function optionalAtcBoolean(value) {
1045
+ if (typeof value === "boolean") return value;
1046
+ if (value === "true") return true;
1047
+ if (value === "false") return false;
1048
+ }
1049
+ function atcLineFromLocation(value) {
1050
+ if (typeof value !== "string") return void 0;
1051
+ const match = /(?:^|[?&])start=(\d+)(?:&|$)/u.exec(value);
1052
+ if (!match) return void 0;
1053
+ const line = Number.parseInt(match[1], 10);
1054
+ return Number.isSafeInteger(line) && line > 0 ? line : void 0;
1055
+ }
1056
+ const ATC_DOCUMENTATION_URI = /^\/sap\/bc\/adt\/documentation\/atc\/documents\/itemid\/[A-Za-z0-9_-]+\/index\/\d+$/u;
1057
+ const ATC_FINDING_URI = /^\/sap\/bc\/adt\/atc\/findings\/itemid\/([A-Za-z0-9_-]+)\/index\/(\d+)$/u;
1058
+ function trustedAtcDocumentationUri(value) {
1059
+ return typeof value === "string" && ATC_DOCUMENTATION_URI.test(value) ? value : void 0;
1060
+ }
1061
+ function documentationUriForFinding(finding) {
1062
+ const link = records(finding.link).find((entry) => stringField(entry, "rel") === "http://www.sap.com/adt/relations/documentation");
1063
+ const linked = trustedAtcDocumentationUri(link && stringField(link, "href"));
1064
+ if (linked) return linked;
1065
+ const findingUri = stringField(finding, "uri");
1066
+ const match = findingUri && ATC_FINDING_URI.exec(findingUri);
1067
+ return match ? `/sap/bc/adt/documentation/atc/documents/itemid/${match[1]}/index/${match[2]}` : void 0;
1068
+ }
1069
+ function canonicalAtcFinding(object, finding) {
1070
+ const line = atcLineFromLocation(finding.location);
1071
+ const quickfixes = record(finding.quickfixes);
1072
+ return {
1073
+ checkId: stringField(finding, "checkId") ?? "",
1074
+ checkTitle: stringField(finding, "checkTitle") ?? "",
1075
+ messageText: stringField(finding, "messageTitle") ?? "",
1076
+ priority: Number.parseInt(stringField(finding, "priority") ?? "3", 10),
1077
+ objectType: stringField(object, "type") ?? "",
1078
+ objectName: stringField(object, "name") ?? "",
1079
+ ...line ? {
1080
+ lineStart: line,
1081
+ lineEnd: line
1082
+ } : {},
1083
+ ...optionalText(finding.messageId) ? { messageId: optionalText(finding.messageId) } : {},
1084
+ ...optionalText(object.packageName) ? { packageName: optionalText(object.packageName) } : {},
1085
+ ...optionalText(object.description) ? { objectDescription: optionalText(object.description) } : {},
1086
+ ...optionalText(finding.contactPerson) ? { contactPerson: optionalText(finding.contactPerson) } : {},
1087
+ ...optionalText(finding.processor) ? { processor: optionalText(finding.processor) } : {},
1088
+ ...optionalText(finding.lastChangedBy) ? { lastChangedBy: optionalText(finding.lastChangedBy) } : {},
1089
+ ...optionalText(finding.exemptionKind) ? { exemptionKind: optionalText(finding.exemptionKind) } : {},
1090
+ ...optionalText(finding.exemptionApproval) ? { exemptionApproval: optionalText(finding.exemptionApproval) } : {},
1091
+ ...optionalAtcBoolean(finding.noExemption) === void 0 ? {} : { noExemption: optionalAtcBoolean(finding.noExemption) },
1092
+ ...optionalText(finding.quickfixInfo) ? { quickfixInfo: optionalText(finding.quickfixInfo) } : {},
1093
+ ...quickfixes ? { quickfixes: {
1094
+ ...optionalAtcBoolean(quickfixes.manual) === void 0 ? {} : { manual: optionalAtcBoolean(quickfixes.manual) },
1095
+ ...optionalAtcBoolean(quickfixes.automatic) === void 0 ? {} : { automatic: optionalAtcBoolean(quickfixes.automatic) },
1096
+ ...optionalAtcBoolean(quickfixes.pseudo) === void 0 ? {} : { pseudo: optionalAtcBoolean(quickfixes.pseudo) }
1097
+ } } : {},
1098
+ ...typeof finding.checksum === "string" || typeof finding.checksum === "number" ? { checksum: String(finding.checksum) } : {},
1099
+ ...documentationUriForFinding(finding) ? { documentationUri: documentationUriForFinding(finding) } : {}
1100
+ };
1101
+ }
1102
+ function toCanonicalAtcFindings(response) {
1103
+ const worklist = record(response)?.worklist;
1104
+ return records(record(worklist)?.objects).flatMap((objects) => records(objects.object)).flatMap((object) => records(record(object.findings)?.finding).map((finding) => canonicalAtcFinding(object, finding)));
1105
+ }
1106
+ async function resolveAtcScopeUris(client, scope) {
1107
+ switch (scope.kind) {
1108
+ case "package": return [assertAdtUri(`/sap/bc/adt/packages/${scope.packageName.toUpperCase()}`)];
1109
+ case "transport_request": return [assertAdtUri(`/sap/bc/adt/cts/transportrequests/${scope.trkorr.toUpperCase()}`)];
1110
+ case "objects": return await Promise.all(scope.objects.map(async (object) => {
1111
+ const uri = await resolveObjectUri(client, object.objectName, adtSearchObjectType(object.objectType));
1112
+ if (!uri) throw new Error("ATC object is unavailable");
1113
+ return uri;
1114
+ }));
1115
+ }
1116
+ }
1117
+ async function resolveAtcVariant(client, requested) {
1118
+ if (requested) return requested;
1119
+ const properties = record(record(await client.adt.atc.customizing.get())?.customizing)?.properties;
1120
+ return stringField(records(record(properties)?.property).find((entry) => stringField(entry, "name") === "systemCheckVariant") ?? {}, "value") ?? "DEFAULT";
1121
+ }
1122
+ function extractAtcWorklistId(response) {
1123
+ if (typeof response === "string") {
1124
+ const match = /id="([^"]+)"/u.exec(response);
1125
+ if (match) return match[1];
1126
+ if (response.trim()) return response.trim();
1127
+ }
1128
+ const object = record(response);
1129
+ const worklistId = stringField(record(object?.worklist) ?? {}, "id");
1130
+ const runId = stringField(record(object?.worklistRun) ?? {}, "worklistId");
1131
+ if (worklistId) return worklistId;
1132
+ if (runId) return runId;
1133
+ throw new Error("ATC worklist is unavailable");
1134
+ }
1135
+ function normalizedObjectType(value) {
1136
+ return value.trim().toUpperCase().split("/", 1)[0]?.trim() || void 0;
1137
+ }
1138
+ function toCanonicalObjects(value) {
1139
+ return records(value).flatMap((entry) => {
1140
+ const objectType = normalizedObjectType(stringField(entry, "type") ?? "");
1141
+ const objectName = stringField(entry, "name")?.toUpperCase();
1142
+ if (!objectType || !objectName) return [];
1143
+ const optional = (key, outputKey) => {
1144
+ const field = stringField(entry, key);
1145
+ return field ? { [outputKey]: field } : {};
1146
+ };
1147
+ return [{
1148
+ canonicalKey: `${objectType}:${objectName}`,
1149
+ objectType,
1150
+ objectName,
1151
+ ...optional("pgmid", "pgmid"),
1152
+ ...optional("obj_info", "objInfo"),
1153
+ ...optional("obj_desc", "objDesc"),
1154
+ ...optional("lock_status", "lockStatus")
1155
+ }];
1156
+ });
1157
+ }
1158
+ function dedupeCanonicalObjects(values) {
1159
+ const seen = /* @__PURE__ */ new Set();
1160
+ return values.filter((value) => {
1161
+ const key = `${value.pgmid ?? ""}\u0000${value.canonicalKey}`;
1162
+ if (seen.has(key)) return false;
1163
+ seen.add(key);
1164
+ return true;
1165
+ });
1166
+ }
1167
+ function normalizeChangedAt(value) {
1168
+ if (typeof value !== "string" || !value.trim()) return void 0;
1169
+ const date = new Date(value);
1170
+ return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
1171
+ }
1172
+ function transportSummaryFromRequest(request, fallbackTrkorr) {
1173
+ const statusRaw = stringField(request, "status");
1174
+ return {
1175
+ trkorr: stringField(request, "number") ?? fallbackTrkorr,
1176
+ owner: stringField(request, "owner") ?? "",
1177
+ description: stringField(request, "desc") ?? "",
1178
+ status: mapTransportStatus(statusRaw),
1179
+ ...statusRaw ? { statusRaw } : {},
1180
+ ...stringField(request, "type") ? { trFunction: stringField(request, "type").toUpperCase() } : {},
1181
+ ...stringField(request, "target") ? { target: stringField(request, "target") } : {},
1182
+ ...stringField(request, "client") ? { client: stringField(request, "client") } : {},
1183
+ ...normalizeChangedAt(request.lastchanged_timestamp) ? { changedAt: normalizeChangedAt(request.lastchanged_timestamp) } : {}
1184
+ };
1185
+ }
1186
+ function toTransportDetail(response, transport) {
1187
+ const root = record(response)?.root;
1188
+ const request = record(record(root)?.request) ?? record(root) ?? record(response) ?? {};
1189
+ const summary = transportSummaryFromRequest(request, transport);
1190
+ const tasks = records(request.task).flatMap((task) => {
1191
+ const taskTrkorr = stringField(task, "number");
1192
+ if (!taskTrkorr) return [];
1193
+ return [{
1194
+ ...transportSummaryFromRequest(task, taskTrkorr),
1195
+ parentTrkorr: transport,
1196
+ objects: toCanonicalObjects(task.abap_object)
1197
+ }];
1198
+ });
1199
+ const allObjects = record(request.all_objects);
1200
+ return {
1201
+ ...summary,
1202
+ tasks,
1203
+ objects: dedupeCanonicalObjects(toCanonicalObjects(request.abap_object).concat(toCanonicalObjects(allObjects?.abap_object)))
1204
+ };
1205
+ }
1206
+ function quickSearchReferences(response) {
1207
+ const root = record(response) ?? {};
1208
+ return records(record(root.objectReferences)?.objectReference ?? root.objectReference ?? record(root.mainObject)?.objectReference);
1209
+ }
1210
+ const ADT_METADATA_ORIGIN = "https://adt.invalid";
1211
+ const ADT_METADATA_PATH_PREFIX = "/sap/bc/adt/";
1212
+ const RAW_METADATA_TRAVERSAL = /(?:^|\/)\.\.(?:\/|$)/u;
1213
+ const ENCODED_METADATA_TRAVERSAL_OR_CONTROL = /%(?:25)*(?:0[09ad]|20|2e|2f|5c)/iu;
1214
+ const METADATA_CONTROL_OR_SPACE = /[\s\u0000-\u0008\u000e-\u001f\u007f\\]/u;
1215
+ function objectMetadataCapability(relation) {
1216
+ if (relation.endsWith("/source")) return "source";
1217
+ if (relation.endsWith("/versions")) return "versions";
1218
+ if (relation.endsWith("/objectstructure")) return "structure";
1219
+ if (relation.endsWith("/sources/textelements")) return "text_elements";
1220
+ if (relation.endsWith("/enhancementImplementations")) return "enhancement_implementations";
1221
+ if (relation.endsWith("/enhancementOptions") || relation.endsWith("/enhancementOptionsOfMainObject")) return "enhancement_options";
1222
+ if (relation.endsWith("/abapsource/parser")) return "syntax";
1223
+ }
1224
+ /** Resolve only SAP-advertised relative metadata links, retaining the URI locally. */
1225
+ function resolveSafeMetadataHref(objectUri, href) {
1226
+ const rawHref = href.trim();
1227
+ if (rawHref !== href || !rawHref || rawHref.startsWith("//") || rawHref.includes("#") || METADATA_CONTROL_OR_SPACE.test(rawHref) || RAW_METADATA_TRAVERSAL.test(rawHref) || ENCODED_METADATA_TRAVERSAL_OR_CONTROL.test(rawHref)) return;
1228
+ const objectPath = objectUri.startsWith("/") ? objectUri : `/${objectUri}`;
1229
+ const basePath = rawHref.startsWith(".") ? objectPath : `${objectPath.replace(/\/$/u, "")}/`;
1230
+ try {
1231
+ const resolved = new URL(rawHref, `${ADT_METADATA_ORIGIN}${basePath}`);
1232
+ if (resolved.origin !== ADT_METADATA_ORIGIN || !resolved.pathname.startsWith(ADT_METADATA_PATH_PREFIX) || resolved.pathname.includes("\\")) return;
1233
+ return assertAdtUri(`${resolved.pathname}${resolved.search}`);
1234
+ } catch {
1235
+ return;
1236
+ }
1237
+ }
1238
+ function trustedObjectMetadataCapabilities(objectUri, links) {
1239
+ const capabilities = /* @__PURE__ */ new Map();
1240
+ for (const link of records(links)) {
1241
+ const relation = stringField(link, "rel");
1242
+ const href = stringField(link, "href");
1243
+ if (!relation || !href) continue;
1244
+ const capability = objectMetadataCapability(relation);
1245
+ const resolvedHref = resolveSafeMetadataHref(objectUri, href);
1246
+ if (!capability || !resolvedHref) continue;
1247
+ const mapped = {
1248
+ relation,
1249
+ capability,
1250
+ href: resolvedHref,
1251
+ ...stringField(link, "title") ? { title: stringField(link, "title") } : {},
1252
+ ...stringField(link, "type") ? { mediaType: stringField(link, "type") } : {},
1253
+ ...stringField(link, "etag") ? { etag: stringField(link, "etag") } : {}
1254
+ };
1255
+ capabilities.set(`${capability}\u0000${relation}`, mapped);
1256
+ }
1257
+ return [...capabilities.values()];
1258
+ }
1259
+ function toObjectMetadataCapabilities(objectUri, links) {
1260
+ return trustedObjectMetadataCapabilities(objectUri, links).map(({ href: _href, ...capability }) => capability);
1261
+ }
1262
+ function toCanonicalObjectMetadata(objectType, objectName, objectUri, response) {
1263
+ const properties = record(record(response)?.objectProperties) ?? {};
1264
+ const genericObject = record(properties.object) ?? {};
1265
+ const canonicalType = normalizedObjectType(objectType);
1266
+ if (!canonicalType) throw new Error("Object type is unavailable");
1267
+ const canonicalName = objectName.toUpperCase();
1268
+ const packageName = stringField(genericObject, "package");
1269
+ const description = stringField(genericObject, "text");
1270
+ return {
1271
+ object: {
1272
+ canonicalKey: `${canonicalType}:${canonicalName}`,
1273
+ objectType: canonicalType,
1274
+ objectName: canonicalName,
1275
+ ...packageName ? { packageName } : {},
1276
+ ...description ? { description } : {}
1277
+ },
1278
+ metadata: {
1279
+ ...stringField(genericObject, "type") ? { adtObjectType: stringField(genericObject, "type") } : {},
1280
+ ...description ? { description } : {},
1281
+ ...packageName ? { packageName } : {}
1282
+ },
1283
+ facets: records(properties.property).map((property) => ({
1284
+ ...stringField(property, "facet") ? { facet: stringField(property, "facet") } : {},
1285
+ ...stringField(property, "name") ? { name: stringField(property, "name") } : {},
1286
+ ...stringField(property, "displayName") ? { displayName: stringField(property, "displayName") } : {},
1287
+ ...stringField(property, "text") ? { text: stringField(property, "text") } : {},
1288
+ ...stringField(property, "version") ? { version: stringField(property, "version") } : {},
1289
+ ...booleanField(property, "hasChildrenOfSameFacet") === void 0 ? {} : { hasChildrenOfSameFacet: booleanField(property, "hasChildrenOfSameFacet") }
1290
+ })),
1291
+ capabilities: toObjectMetadataCapabilities(objectUri, genericObject.link)
1292
+ };
1293
+ }
1294
+ function isAdtNotFound(error) {
1295
+ return error instanceof Error && error.name === "AdtError" && "status" in error && error.status === 404;
1296
+ }
1297
+ function adtPrefixQuery(query) {
1298
+ const trimmed = query?.trim();
1299
+ if (!trimmed) return "*";
1300
+ return /[*?]/u.test(trimmed) ? trimmed : `${trimmed}*`;
1301
+ }
1302
+ function toPackageNodes(value) {
1303
+ const seen = /* @__PURE__ */ new Set();
1304
+ return quickSearchReferences(value).flatMap((entry) => {
1305
+ const type = stringField(entry, "type")?.toUpperCase();
1306
+ const name = stringField(entry, "name")?.toUpperCase();
1307
+ if (!type?.startsWith("DEVC") || !name || seen.has(name)) return [];
1308
+ seen.add(name);
1309
+ const parent = stringField(entry, "packageName")?.toUpperCase();
1310
+ const description = stringField(entry, "description");
1311
+ return [{
1312
+ name,
1313
+ ...parent && parent !== name ? { parent } : {},
1314
+ ...description ? { description } : {}
1315
+ }];
1316
+ });
1317
+ }
1318
+ /**
1319
+ * Normalise the ADT package-tree response. The typed upstream contract has a
1320
+ * `packageTree.treeNode` shape, distinct from repository quick-search rows.
1321
+ * Keep only package identity/parent/description; ADT links stay local.
1322
+ */
1323
+ function toPackageTreeNodes(value, rootPackage) {
1324
+ const nodes = records(record(record(value)?.packageTree)?.treeNode);
1325
+ const root = rootPackage.trim().toUpperCase();
1326
+ const deduped = /* @__PURE__ */ new Map();
1327
+ for (const node of nodes) {
1328
+ const type = stringField(node, "type")?.toUpperCase();
1329
+ const name = stringField(node, "name")?.toUpperCase();
1330
+ if (!name || type && !type.startsWith("DEVC")) continue;
1331
+ const superPackage = record(node.superPackageRef);
1332
+ const parent = superPackage ? stringField(superPackage, "name")?.toUpperCase() : void 0;
1333
+ const description = stringField(node, "description");
1334
+ const candidate = {
1335
+ name,
1336
+ ...name !== root && parent && parent !== name ? { parent } : {},
1337
+ ...description ? { description } : {}
1338
+ };
1339
+ const existing = deduped.get(name);
1340
+ if (!existing) deduped.set(name, candidate);
1341
+ else if (!existing.description && candidate.description) existing.description = candidate.description;
1342
+ }
1343
+ if (!deduped.has(root)) deduped.set(root, { name: root });
1344
+ return [...deduped.values()].sort((left, right) => {
1345
+ if (left.name === root) return -1;
1346
+ if (right.name === root) return 1;
1347
+ return left.name.localeCompare(right.name);
1348
+ });
1349
+ }
1350
+ /**
1351
+ * A package GET is the portable fallback for SAP releases that do not expose
1352
+ * the `$tree` capability. It contains the requested package plus direct
1353
+ * `subPackages.packageRef` children; keep the requested root as the public
1354
+ * tree anchor and never retain ADT links.
1355
+ */
1356
+ function toPackageMetadataNodes(value, requestedPackage) {
1357
+ const packageRecord = record(record(value)?.package);
1358
+ const root = stringField(packageRecord ?? {}, "name")?.toUpperCase() ?? requestedPackage.trim().toUpperCase();
1359
+ const rootDescription = stringField(packageRecord ?? {}, "description");
1360
+ const nodes = [{
1361
+ name: root,
1362
+ ...rootDescription ? { description: rootDescription } : {}
1363
+ }];
1364
+ const subPackages = record(packageRecord?.subPackages);
1365
+ const seen = /* @__PURE__ */ new Set([root]);
1366
+ for (const reference of records(subPackages?.packageRef)) {
1367
+ const name = stringField(reference, "name")?.toUpperCase();
1368
+ if (!name || seen.has(name)) continue;
1369
+ seen.add(name);
1370
+ const description = stringField(reference, "description");
1371
+ nodes.push({
1372
+ name,
1373
+ parent: root,
1374
+ ...description ? { description } : {}
1375
+ });
1376
+ }
1377
+ return nodes;
1378
+ }
1379
+ function isUnsupportedPackageTree(error) {
1380
+ return error instanceof Error && error.name === "AdtError" && "status" in error && [404, 406].includes(error.status);
1381
+ }
1382
+ async function getPackageTreeFromMetadata(client, rootPackage) {
1383
+ const root = rootPackage.trim().toUpperCase();
1384
+ const queued = /* @__PURE__ */ new Set([root]);
1385
+ const visited = /* @__PURE__ */ new Set();
1386
+ const queue = [root];
1387
+ const packages = /* @__PURE__ */ new Map();
1388
+ let truncated = false;
1389
+ while (queue.length > 0) {
1390
+ queue.sort((left, right) => left.localeCompare(right));
1391
+ const name = queue.shift();
1392
+ queued.delete(name);
1393
+ if (visited.has(name)) continue;
1394
+ visited.add(name);
1395
+ const [current, ...children] = toPackageMetadataNodes(await client.adt.packages.get(name), name);
1396
+ if (current) {
1397
+ const existing = packages.get(current.name);
1398
+ if (!existing) packages.set(current.name, current);
1399
+ else if (!existing.description && current.description) existing.description = current.description;
1400
+ }
1401
+ for (const child of children.toSorted((left, right) => left.name.localeCompare(right.name))) {
1402
+ const existing = packages.get(child.name);
1403
+ if (!existing && packages.size >= 5e3) {
1404
+ truncated = true;
1405
+ break;
1406
+ }
1407
+ if (!existing) packages.set(child.name, child);
1408
+ else if (!existing.description && child.description) existing.description = child.description;
1409
+ if (!visited.has(child.name) && !queued.has(child.name)) {
1410
+ queue.push(child.name);
1411
+ queued.add(child.name);
1412
+ }
1413
+ }
1414
+ if (truncated) break;
1415
+ }
1416
+ if (queue.length > 0) truncated = true;
1417
+ return {
1418
+ data: [...packages.values()].sort((left, right) => {
1419
+ if (left.name === root) return -1;
1420
+ if (right.name === root) return 1;
1421
+ return left.name.localeCompare(right.name);
1422
+ }),
1423
+ truncated
1424
+ };
1425
+ }
1426
+ function toCanonicalRepositoryObjects(value, packageName) {
1427
+ const seen = /* @__PURE__ */ new Set();
1428
+ const expectedPackageName = packageName?.toUpperCase();
1429
+ return quickSearchReferences(value).flatMap((entry) => {
1430
+ const objectType = normalizedObjectType(stringField(entry, "type") ?? "");
1431
+ const objectName = stringField(entry, "name")?.toUpperCase();
1432
+ if (!objectType || !objectName || objectType === "DEVC" || !stringField(entry, "uri")) return [];
1433
+ const canonicalKey = `${objectType}:${objectName}`;
1434
+ if (seen.has(canonicalKey)) return [];
1435
+ const packageName = stringField(entry, "packageName")?.toUpperCase();
1436
+ if (expectedPackageName && packageName && packageName !== expectedPackageName) return [];
1437
+ seen.add(canonicalKey);
1438
+ const description = stringField(entry, "description");
1439
+ return [{
1440
+ canonicalKey,
1441
+ objectType,
1442
+ objectName,
1443
+ ...packageName ? { packageName } : {},
1444
+ ...description ? { description } : {}
1445
+ }];
1446
+ });
1447
+ }
1448
+ function adtSearchObjectType(objectType) {
1449
+ const normalized = normalizedObjectType(objectType ?? "");
1450
+ return normalized === "REPS" ? "PROG" : normalized;
1451
+ }
1452
+ function mapTransportStatus(status) {
1453
+ switch (status) {
1454
+ case "R": return "released";
1455
+ case "D":
1456
+ case "L": return "modifiable";
1457
+ case "O":
1458
+ case "P": return "release_started";
1459
+ default: return status ? status.toLowerCase() : "";
1460
+ }
1461
+ }
1462
+ function toTransportSummary(header) {
1463
+ return {
1464
+ trkorr: header.TRKORR,
1465
+ owner: header.AS4USER ?? "",
1466
+ description: header.AS4TEXT ?? "",
1467
+ status: mapTransportStatus(header.TRSTATUS),
1468
+ ...header.TRSTATUS ? { statusRaw: header.TRSTATUS } : {},
1469
+ ...header.TRFUNCTION ? { trFunction: header.TRFUNCTION } : {},
1470
+ ...header.TARSYSTEM ? { target: header.TARSYSTEM } : {},
1471
+ ...header.CLIENT ? { client: header.CLIENT } : {},
1472
+ ...header.AS4DATE ? { changedAt: `${header.AS4DATE}T${header.AS4TIME ?? "00:00:00"}Z` } : {}
1473
+ };
1474
+ }
1475
+ function same(value, expected) {
1476
+ return (value ?? "").toLowerCase() === expected.toLowerCase();
1477
+ }
1478
+ function matchesText(transport, value) {
1479
+ if (value === "*") return true;
1480
+ if (value.endsWith("*")) {
1481
+ const prefix = value.slice(0, -1).trim();
1482
+ return prefix.length > 0 && transport.trkorr.toLowerCase().startsWith(prefix.toLowerCase());
1483
+ }
1484
+ return same(transport.trkorr, value) || `${transport.description} ${transport.owner}`.toLowerCase().includes(value.toLowerCase());
1485
+ }
1486
+ function transportMatchesCriteria(transport, criteria) {
1487
+ if (criteria.includeTasks === false && transport.trFunction && [
1488
+ "S",
1489
+ "R",
1490
+ "X",
1491
+ "Q"
1492
+ ].includes(transport.trFunction.toUpperCase())) return false;
1493
+ if (criteria.owner && !same(transport.owner, criteria.owner)) return false;
1494
+ if (criteria.type && !same(transport.trFunction, criteria.type)) return false;
1495
+ if (criteria.status && !same(transport.status, criteria.status)) return false;
1496
+ if (criteria.target && !same(transport.target, criteria.target)) return false;
1497
+ const date = transport.changedAt?.slice(0, 10);
1498
+ if (criteria.dateFrom && (!date || date < criteria.dateFrom)) return false;
1499
+ if (criteria.dateTo && (!date || date > criteria.dateTo)) return false;
1500
+ if (criteria.text && !matchesText(transport, criteria.text)) return false;
1501
+ return true;
1502
+ }
1503
+ function filterTransports(transports, criteria) {
1504
+ if (!criteria) return transports;
1505
+ return transports.filter((transport) => transportMatchesCriteria(transport, criteria));
1506
+ }
1507
+ function extractTransportHeaders(response) {
1508
+ const root = response;
1509
+ const headers = root.abap?.values?.DATA?.CTS_REQ_HEADER ?? root.values?.DATA?.CTS_REQ_HEADER;
1510
+ if (!headers) return [];
1511
+ return (Array.isArray(headers) ? headers : [headers]).flatMap((header) => header && typeof header === "object" && typeof header.TRKORR === "string" ? [header] : []);
1512
+ }
1513
+ function brokerLeaseHelpers(options) {
1514
+ const fetcher = options.fetch ?? globalThis.fetch;
1515
+ const readBrokerToken = async () => {
1516
+ const token = (await readFile(options.tokenFile, "utf8")).trim();
1517
+ if (!token) throw new Error("ADT Server broker token file is empty");
1518
+ return token;
1519
+ };
1520
+ const acquireLease = async (destination) => {
1521
+ const token = await readBrokerToken();
1522
+ const response = await fetcher(new URL("/internal/adt-server/destination-leases:acquire", options.baseUrl), {
1523
+ method: "POST",
1524
+ headers: {
1525
+ "content-type": "application/json",
1526
+ "x-adt-server-token": token
1527
+ },
1528
+ body: JSON.stringify({
1529
+ destination,
1530
+ correlationId: randomUUID()
1531
+ })
1532
+ });
1533
+ if (!response.ok) throw new Error(`Destination lease unavailable (${response.status})`);
1534
+ const lease = await response.json();
1535
+ if (!isBrokerLease(lease)) throw new Error("Destination lease unavailable");
1536
+ return lease;
1537
+ };
1538
+ const releaseLease = async (lease, operationName, outcome, durationMs, errorCode) => {
1539
+ const token = await readBrokerToken();
1540
+ const response = await fetcher(new URL("/internal/adt-server/destination-leases:release", options.baseUrl), {
1541
+ method: "POST",
1542
+ headers: {
1543
+ "content-type": "application/json",
1544
+ "x-adt-server-token": token
1545
+ },
1546
+ body: JSON.stringify({
1547
+ leaseId: lease.leaseId,
1548
+ operation: operationName,
1549
+ outcome,
1550
+ durationMs: Math.min(durationMs, 3e5),
1551
+ ...errorCode ? { errorCode } : {}
1552
+ })
1553
+ });
1554
+ if (!response.ok) throw new Error(`Destination lease release failed (${response.status})`);
1555
+ };
1556
+ return {
1557
+ fetcher,
1558
+ readBrokerToken,
1559
+ acquireLease,
1560
+ releaseLease
1561
+ };
1562
+ }
1563
+ /** ADT-private broker client. It exposes only safe summaries to the public server layer. */
1564
+ function createHttpBrokerOperations(options) {
1565
+ const { fetcher, readBrokerToken, acquireLease, releaseLease } = brokerLeaseHelpers(options);
1566
+ const createClient = options.createClient ?? ((connection) => clientFromConnection(connection, options.allowedUaaHosts));
1567
+ const request = async (path) => {
1568
+ const token = await readBrokerToken();
1569
+ const response = await fetcher(new URL(path, options.baseUrl), { headers: { "x-adt-server-token": token } });
1570
+ if (!response.ok) throw new Error(`ADT Server broker request failed (${response.status})`);
1571
+ return response;
1572
+ };
1573
+ const withClient = async (destination, operationName, operation) => {
1574
+ const lease = await acquireLease(destination);
1575
+ const startedAt = Date.now();
1576
+ let clientCreated = false;
1577
+ let outcome = "failed";
1578
+ let result;
1579
+ let operationError;
1580
+ try {
1581
+ const client = await createClient(lease.connection);
1582
+ clientCreated = true;
1583
+ result = await operation(client);
1584
+ outcome = "succeeded";
1585
+ } catch (error) {
1586
+ operationError = error;
1587
+ } finally {
1588
+ const errorCode = outcome === "failed" ? clientCreated ? "operation_failed" : "client_creation_failed" : void 0;
1589
+ try {
1590
+ await releaseLease(lease, operationName, outcome, Date.now() - startedAt, errorCode);
1591
+ } catch {}
1592
+ }
1593
+ if (operationError !== void 0) throw operationError;
1594
+ return result;
1595
+ };
1596
+ return {
1597
+ async listDestinations() {
1598
+ const body = await (await request("/internal/adt-server/destinations")).json();
1599
+ return Array.isArray(body.data) ? body.data : [];
1600
+ },
1601
+ async listTransports(destination, criteria) {
1602
+ return await withClient(destination, "list_transports", async (client) => {
1603
+ return filterTransports(extractTransportHeaders(await client.adt.cts.transports.find({
1604
+ _action: "FIND",
1605
+ user: "*",
1606
+ trfunction: "*"
1607
+ })).map(toTransportSummary), criteria);
1608
+ });
1609
+ },
1610
+ async getTransportDetail(destination, transport) {
1611
+ return await withClient(destination, "get_transport_detail", async (client) => toTransportDetail(await client.adt.cts.transportrequests.get(transport), transport));
1612
+ },
1613
+ async listTransportObjects(destination, transport) {
1614
+ return await withClient(destination, "list_transport_objects", async (client) => {
1615
+ const detail = toTransportDetail(await client.adt.cts.transportrequests.get(transport), transport);
1616
+ return dedupeCanonicalObjects([...detail.objects, ...detail.tasks.flatMap((task) => task.objects)]);
1617
+ });
1618
+ },
1619
+ async searchPackages(destination, criteria = {}) {
1620
+ return await withClient(destination, "search_packages", async (client) => {
1621
+ const cap = criteria.maxResults ?? 5e3;
1622
+ const response = await client.adt.repository.informationsystem.search.quickSearch({
1623
+ query: adtPrefixQuery(criteria.q),
1624
+ objectType: "DEVC",
1625
+ maxResults: cap + 1
1626
+ });
1627
+ return {
1628
+ data: toPackageNodes(response).slice(0, cap),
1629
+ truncated: quickSearchReferences(response).length >= cap
1630
+ };
1631
+ });
1632
+ },
1633
+ async getPackageTree(destination, rootPackage) {
1634
+ return await withClient(destination, "get_package_tree", async (client) => {
1635
+ const normalizedRoot = rootPackage.trim().toUpperCase();
1636
+ try {
1637
+ const packages = toPackageTreeNodes(await client.adt.packages.tree({
1638
+ packagename: normalizedRoot,
1639
+ type: "sub"
1640
+ }), normalizedRoot);
1641
+ return {
1642
+ data: packages.slice(0, MAX_PACKAGE_SEARCH_RESULTS),
1643
+ truncated: packages.length > MAX_PACKAGE_SEARCH_RESULTS
1644
+ };
1645
+ } catch (error) {
1646
+ if (!isUnsupportedPackageTree(error)) throw error;
1647
+ return await getPackageTreeFromMetadata(client, normalizedRoot);
1648
+ }
1649
+ });
1650
+ },
1651
+ async searchObjects(destination, criteria = {}) {
1652
+ return await withClient(destination, "search_objects", async (client) => {
1653
+ const cap = criteria.maxResults ?? 5e3;
1654
+ const response = await client.adt.repository.informationsystem.search.quickSearch({
1655
+ query: adtPrefixQuery(criteria.query),
1656
+ maxResults: cap + 1,
1657
+ ...criteria.packageName ? { packageName: criteria.packageName.toUpperCase() } : {},
1658
+ ...adtSearchObjectType(criteria.objectType) ? { objectType: adtSearchObjectType(criteria.objectType) } : {}
1659
+ });
1660
+ return {
1661
+ data: toCanonicalRepositoryObjects(response).slice(0, cap),
1662
+ truncated: quickSearchReferences(response).length >= cap
1663
+ };
1664
+ });
1665
+ },
1666
+ async getObjectMetadata(destination, objectType, objectName) {
1667
+ return await withClient(destination, "get_object_metadata", async (client) => {
1668
+ const objectUri = await resolveObjectUri(client, objectName, adtSearchObjectType(objectType));
1669
+ if (!objectUri) throw new Error("Object metadata is unavailable");
1670
+ return toCanonicalObjectMetadata(objectType, objectName, objectUri, await client.adt.repository.informationsystem.objectProperties.values({
1671
+ uri: objectUri,
1672
+ facets: ["package", "appl"]
1673
+ }));
1674
+ });
1675
+ },
1676
+ async getBadi(destination, badiName, options) {
1677
+ return await withClient(destination, "get_badi", async (client) => {
1678
+ const { enhancement: _enhancement, source: _source, ...metadata } = await new BadiService(client).get({
1679
+ name: badiName,
1680
+ options: { includeImplementations: options?.includeImplementations }
1681
+ });
1682
+ return metadata;
1683
+ });
1684
+ },
1685
+ async getObjectSourceHistory(destination, objectType, objectName) {
1686
+ return await withClient(destination, "get_object_source_history", async (client) => {
1687
+ const objectUri = await resolveObjectUri(client, objectName, adtSearchObjectType(objectType));
1688
+ if (!objectUri) throw new Error("Object source history is unavailable");
1689
+ const genericObject = record(record(await client.adt.repository.informationsystem.objectProperties.values({
1690
+ uri: objectUri,
1691
+ facets: ["package", "appl"]
1692
+ }))?.objectProperties)?.object;
1693
+ const versions = trustedObjectMetadataCapabilities(objectUri, genericObject && record(genericObject)?.link).find((capability) => capability.capability === "versions");
1694
+ if (!versions) return {
1695
+ available: false,
1696
+ versions: []
1697
+ };
1698
+ return {
1699
+ available: true,
1700
+ versions: (await client.services.sourceHistory.listVersions(versions.href)).map(({ sourceUri: _sourceUri, ...version }) => ({ ...version }))
1701
+ };
1702
+ });
1703
+ },
1704
+ async readObjectSource(input) {
1705
+ return await withClient(input.destination, "read_object_source", async (client) => {
1706
+ const objectUri = await resolveObjectUri(client, input.objectName, adtSearchObjectType(input.objectType));
1707
+ if (!objectUri) throw new Error("Object source is unavailable");
1708
+ const sourcePath = `${objectUri.replace(/\/$/u, "")}/source/main` + (input.version ? `?version=${encodeURIComponent(input.version)}` : "");
1709
+ let source;
1710
+ try {
1711
+ source = await client.readTextBounded(sourcePath, MAX_SOURCE_BYTES, { headers: { Accept: "text/plain" } });
1712
+ } catch (error) {
1713
+ if (error instanceof AdtResponseTooLargeError) throw new SourceVersionTooLargeError(error.maxBytes, error.receivedBytes);
1714
+ if (isAdtNotFound(error)) return {
1715
+ bytes: 0,
1716
+ source: ""
1717
+ };
1718
+ throw error;
1719
+ }
1720
+ return {
1721
+ bytes: Buffer.byteLength(source, "utf8"),
1722
+ source
1723
+ };
1724
+ });
1725
+ },
1726
+ async listPackageObjects(destination, packageName) {
1727
+ return await withClient(destination, "list_package_objects", async (client) => {
1728
+ const cap = 5e3;
1729
+ const response = await client.adt.repository.informationsystem.search.quickSearch({
1730
+ query: "*",
1731
+ packageName: packageName.toUpperCase(),
1732
+ maxResults: 5001
1733
+ });
1734
+ return {
1735
+ data: toCanonicalRepositoryObjects(response, packageName).slice(0, cap),
1736
+ truncated: quickSearchReferences(response).length >= cap
1737
+ };
1738
+ });
1739
+ },
1740
+ async runAtc(input) {
1741
+ return await withClient(input.destination, "run_atc", async (client) => {
1742
+ const checkVariant = await resolveAtcVariant(client, input.variant);
1743
+ const worklistId = extractAtcWorklistId(await client.adt.atc.worklists.create({ checkVariant }));
1744
+ const targetUris = await resolveAtcScopeUris(client, input.scope);
1745
+ await client.adt.atc.runs.post({ worklistId }, { run: {
1746
+ maximumVerdicts: 1e4,
1747
+ objectSets: { objectSet: [{
1748
+ kind: "inclusive",
1749
+ objectReferences: { objectReference: targetUris.map((uri) => ({ uri })) }
1750
+ }] }
1751
+ } });
1752
+ return {
1753
+ checkVariant,
1754
+ findings: toCanonicalAtcFindings(await client.adt.atc.worklists.get(worklistId, { includeExemptedFindings: "false" }))
1755
+ };
1756
+ });
1757
+ },
1758
+ async readAtcFindingDocumentation(input) {
1759
+ return await withClient(input.destination, "read_atc_finding_documentation", async (client) => {
1760
+ const documentationUri = trustedAtcDocumentationUri(input.documentationUri);
1761
+ if (!documentationUri) throw new Error("ATC documentation is unavailable");
1762
+ const html = await client.readTextBounded(documentationUri, input.maxBytes, { headers: { Accept: "application/vnd.sap.adt.docu.v1+html" } });
1763
+ return {
1764
+ bytes: Buffer.byteLength(html, "utf8"),
1765
+ html
1766
+ };
1767
+ });
1768
+ },
1769
+ async buildTransportSourceManifest(destination, input) {
1770
+ return await withClient(destination, "build_transport_source_manifest", async (client) => await new ExactSourceHistoryService(client).buildTransportManifest(input));
1771
+ },
1772
+ async readImmutableSource(input) {
1773
+ return await withClient(input.destination, "read_immutable_source", async (client) => {
1774
+ const source = await client.services.sourceHistory.readVersionSourceBounded(input.sourceUri, input.maxBytes);
1775
+ return {
1776
+ bytes: Buffer.byteLength(source, "utf8"),
1777
+ source
1778
+ };
1779
+ });
1780
+ }
1781
+ };
1782
+ }
1783
+ function validateUaaUrl(uaaUrl, allowedUaaHosts) {
1784
+ let url;
1785
+ try {
1786
+ url = new URL(uaaUrl);
1787
+ } catch {
1788
+ throw new Error("BTP service key uaa.url is not a valid URL");
1789
+ }
1790
+ if (url.protocol !== "https:") throw new Error("BTP service key uaa.url must use https:");
1791
+ if (url.username || url.password || url.search || url.hash) throw new Error("BTP service key uaa.url must not contain credentials, query, or fragment");
1792
+ if (allowedUaaHosts && !allowedUaaHosts.includes(url.hostname)) throw new Error(`BTP service key uaa.url host ${url.hostname} is not allow-listed`);
1793
+ return url;
1794
+ }
1795
+ function postFormForJson(url, headers, body) {
1796
+ return new Promise((resolve, reject) => {
1797
+ const req = request(url, {
1798
+ method: "POST",
1799
+ headers
1800
+ }, (response) => {
1801
+ const chunks = [];
1802
+ response.on("data", (chunk) => chunks.push(chunk));
1803
+ response.on("end", () => {
1804
+ const text = Buffer.concat(chunks).toString("utf8");
1805
+ resolve({
1806
+ ok: response.statusCode !== void 0 && response.statusCode >= 200 && response.statusCode < 300,
1807
+ status: response.statusCode ?? 0,
1808
+ statusText: response.statusMessage ?? "",
1809
+ async json() {
1810
+ return JSON.parse(text);
1811
+ }
1812
+ });
1813
+ });
1814
+ });
1815
+ req.on("error", reject);
1816
+ req.write(body);
1817
+ req.end();
1818
+ });
1819
+ }
1820
+ async function clientFromConnection(connection, allowedUaaHosts) {
1821
+ if (connection.authMethod === "basic") {
1822
+ const username = connection.authConfig.username;
1823
+ const password = connection.authConfig.password;
1824
+ if (typeof username !== "string" || typeof password !== "string") throw new Error("Broker returned incomplete basic credentials");
1825
+ return createAdtClient({
1826
+ baseUrl: connection.baseUrl,
1827
+ client: connection.sapClient ?? void 0,
1828
+ username,
1829
+ password
1830
+ });
1831
+ }
1832
+ const serviceKey = connection.authConfig.serviceKey;
1833
+ if (!serviceKey?.uaa?.url || !serviceKey.uaa.clientid || !serviceKey.uaa.clientsecret) throw new Error("Broker returned incomplete BTP service key");
1834
+ const uaaUrl = validateUaaUrl(serviceKey.uaa.url, allowedUaaHosts);
1835
+ const credentials = Buffer.from(`${serviceKey.uaa.clientid}:${serviceKey.uaa.clientsecret}`).toString("base64");
1836
+ const tokenResponse = await postFormForJson(new URL("/oauth/token", uaaUrl), {
1837
+ authorization: `Basic ${credentials}`,
1838
+ "content-type": "application/x-www-form-urlencoded"
1839
+ }, "grant_type=client_credentials");
1840
+ if (!tokenResponse.ok) throw new Error("BTP token acquisition failed");
1841
+ const token = await tokenResponse.json();
1842
+ if (!token.access_token) throw new Error("BTP token response did not contain access_token");
1843
+ return createAdtClient({
1844
+ baseUrl: connection.baseUrl,
1845
+ client: connection.sapClient ?? void 0,
1846
+ authorizationHeader: `${token.token_type ?? "Bearer"} ${token.access_token}`
1847
+ });
1848
+ }
1849
+ /** Creates the opaque lease/provider pair consumed by shared MCP mode. */
1850
+ function createHttpDestinationContexts(options) {
1851
+ const { fetcher, readBrokerToken, acquireLease, releaseLease } = brokerLeaseHelpers(options);
1852
+ return {
1853
+ leaseProvider: { async acquire({ destination }) {
1854
+ const lease = await acquireLease(destination);
1855
+ let releasePromise;
1856
+ return {
1857
+ destination: lease.destination,
1858
+ version: lease.version,
1859
+ expiresAt: Date.parse(lease.expiresAt),
1860
+ material: lease.connection,
1861
+ release: async () => {
1862
+ releasePromise ??= releaseLease(lease, "mcp_destination_context", "succeeded", 0);
1863
+ await releasePromise;
1864
+ }
1865
+ };
1866
+ } },
1867
+ contextFactory: { async create({ lease }) {
1868
+ return {
1869
+ client: await clientFromConnection(lease.material),
1870
+ close: async () => void 0
1871
+ };
1872
+ } },
1873
+ async resolveFrozenSource(input) {
1874
+ const token = await readBrokerToken();
1875
+ const response = await fetcher(new URL("/internal/adt-server/frozen-source-references:resolve", options.baseUrl), {
1876
+ method: "POST",
1877
+ headers: {
1878
+ "content-type": "application/json",
1879
+ "x-adt-server-token": token
1880
+ },
1881
+ body: JSON.stringify(input)
1882
+ });
1883
+ if (!response.ok) throw new Error("Frozen source reference is unavailable");
1884
+ const body = await response.json();
1885
+ if (typeof body.sourceUri === "string" && body.sourceUri.startsWith("/sap/bc/adt/") && !/[\s\\\u0000-\u0008\u000e-\u001f\u007f]/u.test(body.sourceUri)) return { sourceUri: body.sourceUri };
1886
+ if (typeof body.sourceCapability === "string" && /^src\.v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u.test(body.sourceCapability)) return { sourceCapability: body.sourceCapability };
1887
+ throw new Error("Frozen source reference is unavailable");
1888
+ }
1889
+ };
1890
+ }
1891
+
1892
+ //#endregion
1893
+ //#region src/mcp-runtime.ts
1894
+ const INVOCATION_AUDIENCE = "adt-server-mcp";
1895
+ const MAX_TIMER_DELAY_MS = 2147483647;
1896
+ function scheduleDeadline(deadline, onDeadline) {
1897
+ let timer;
1898
+ const schedule = () => {
1899
+ const remaining = deadline - performance.now();
1900
+ if (remaining <= 0) {
1901
+ onDeadline();
1902
+ return;
1903
+ }
1904
+ timer = setTimeout(schedule, Math.min(remaining, MAX_TIMER_DELAY_MS));
1905
+ };
1906
+ schedule();
1907
+ return () => {
1908
+ if (timer !== void 0) clearTimeout(timer);
1909
+ };
1910
+ }
1911
+ /**
1912
+ * Aborts all SAP HTTP work in this async execution context at the signed
1913
+ * deadline, then waits for the tool operation to settle before returning.
1914
+ */
1915
+ async function executeWithDeadlineAndAbort(input) {
1916
+ if (!Number.isSafeInteger(input.maxDurationMs) || input.maxDurationMs <= 0) throw new RangeError("maxDurationMs must be a positive safe integer");
1917
+ const abortController = new AbortController();
1918
+ const deadline = performance.now() + input.maxDurationMs;
1919
+ let deadlineExceeded = false;
1920
+ const markDeadlineExceeded = () => {
1921
+ deadlineExceeded = true;
1922
+ if (!abortController.signal.aborted) abortController.abort(/* @__PURE__ */ new Error("safe_execute deadline exceeded"));
1923
+ };
1924
+ const clearDeadline = scheduleDeadline(deadline, markDeadlineExceeded);
1925
+ const deadlineHasPassed = () => deadlineExceeded || performance.now() >= deadline;
1926
+ try {
1927
+ const result = await runWithAdtAbortSignal(abortController.signal, input.operation);
1928
+ if (deadlineHasPassed()) {
1929
+ markDeadlineExceeded();
1930
+ throw new Error("safe_execute deadline exceeded");
1931
+ }
1932
+ return result;
1933
+ } catch (error) {
1934
+ if (deadlineHasPassed()) {
1935
+ markDeadlineExceeded();
1936
+ throw new Error("safe_execute deadline exceeded", { cause: error });
1937
+ }
1938
+ throw error;
1939
+ } finally {
1940
+ clearDeadline();
1941
+ }
1942
+ }
1943
+ function configuredValue(env, name) {
1944
+ return env[name]?.trim() || void 0;
1945
+ }
1946
+ function invocationConfiguration(env) {
1947
+ const publicKeyFile = configuredValue(env, "ADT_SERVER_MCP_PUBLIC_KEY_FILE");
1948
+ const keyId = configuredValue(env, "ADT_SERVER_MCP_KEY_ID");
1949
+ const issuer = configuredValue(env, "ADT_SERVER_MCP_ISSUER");
1950
+ const configuredCount = [
1951
+ publicKeyFile,
1952
+ keyId,
1953
+ issuer
1954
+ ].filter(Boolean).length;
1955
+ if (configuredCount === 0) return void 0;
1956
+ if (configuredCount !== 3) throw new Error("ADT_SERVER_MCP_PUBLIC_KEY_FILE, ADT_SERVER_MCP_KEY_ID, and ADT_SERVER_MCP_ISSUER must be configured together");
1957
+ return {
1958
+ publicKeyFile,
1959
+ keyId,
1960
+ issuer
1961
+ };
1962
+ }
1963
+ function allowedHostsFromEnv(env) {
1964
+ const configured = configuredValue(env, "ADT_SERVER_MCP_ALLOWED_HOSTS");
1965
+ if (!configured) return void 0;
1966
+ const hosts = configured.split(",").map((host) => host.trim());
1967
+ if (hosts.some((host) => !host)) throw new Error("ADT_SERVER_MCP_ALLOWED_HOSTS must be a comma-separated host list");
1968
+ return [...new Set(hosts)];
1969
+ }
1970
+ function createHttpAuthorizationConsumer(url, fetchImpl = globalThis.fetch) {
1971
+ const endpoint = new URL(url).toString();
1972
+ return async (input) => {
1973
+ return (await fetchImpl(endpoint, {
1974
+ method: "POST",
1975
+ headers: {
1976
+ "Content-Type": "application/json",
1977
+ Authorization: `Bearer ${input.authorizationToken}`
1978
+ },
1979
+ body: JSON.stringify(input)
1980
+ })).ok;
1981
+ };
1982
+ }
1983
+ function createHttpOutcomeReporter(url, fetchImpl = globalThis.fetch) {
1984
+ const endpoint = new URL(url).toString();
1985
+ return async (input) => {
1986
+ return (await fetchImpl(endpoint, {
1987
+ method: "POST",
1988
+ headers: {
1989
+ "Content-Type": "application/json",
1990
+ Authorization: `Bearer ${input.authorizationToken}`
1991
+ },
1992
+ body: JSON.stringify(input)
1993
+ })).ok;
1994
+ };
1995
+ }
1996
+ function safeExecuteHooksFromEnv(env, fetchImpl = globalThis.fetch) {
1997
+ const consumerUrl = configuredValue(env, "ADT_SERVER_MCP_AUTHORIZATION_CONSUMER_URL");
1998
+ const reporterUrl = configuredValue(env, "ADT_SERVER_MCP_OUTCOME_REPORTER_URL");
1999
+ return {
2000
+ consumeExecutionAuthorization: consumerUrl ? createHttpAuthorizationConsumer(consumerUrl, fetchImpl) : void 0,
2001
+ reportExecutionOutcome: reporterUrl ? createHttpOutcomeReporter(reporterUrl, fetchImpl) : void 0
2002
+ };
2003
+ }
2004
+ function safeExecuteEnabled(env) {
2005
+ const configured = configuredValue(env, "ADT_SERVER_MCP_SAFE_EXECUTE_ENABLED");
2006
+ if (configured === void 0 || configured === "false") return false;
2007
+ if (configured === "true") return true;
2008
+ throw new Error("ADT_SERVER_MCP_SAFE_EXECUTE_ENABLED must be exactly true or false");
2009
+ }
2010
+ async function loadP256PublicKey(file) {
2011
+ const pem = await readFile(file, "utf8");
2012
+ if (/-----BEGIN(?: EC)? PRIVATE KEY-----/u.test(pem)) throw new Error("ADT Server MCP public key file must contain only public key material");
2013
+ let publicKey;
2014
+ try {
2015
+ publicKey = createPublicKey(pem);
2016
+ } catch {
2017
+ throw new Error("ADT Server MCP public key file is invalid");
2018
+ }
2019
+ if (publicKey.type !== "public" || publicKey.asymmetricKeyType !== "ec" || publicKey.asymmetricKeyDetails?.namedCurve !== "prime256v1") throw new Error("ADT Server MCP requires an ES256 P-256 public key");
2020
+ return publicKey;
2021
+ }
2022
+ /**
2023
+ * Creates the optional, signed MCP sidecar configuration. A missing complete
2024
+ * configuration keeps MCP unavailable; a partial or invalid configuration
2025
+ * aborts startup rather than risking a weaker authentication mode.
2026
+ */
2027
+ async function createAdtServerMcpOptions(options) {
2028
+ const enableSafeExecute = safeExecuteEnabled(options.env);
2029
+ const invocation = invocationConfiguration(options.env);
2030
+ if (!invocation) {
2031
+ if (enableSafeExecute) throw new Error("ADT Server MCP safe_execute requires MCP invocation configuration");
2032
+ return;
2033
+ }
2034
+ const executeWithDeadline = options.executeWithDeadline ?? executeWithDeadlineAndAbort;
2035
+ const envHooks = enableSafeExecute ? safeExecuteHooksFromEnv(options.env) : void 0;
2036
+ const safeExecuteOptions = (() => {
2037
+ if (!enableSafeExecute) return {};
2038
+ const consumeExecutionAuthorization = options.consumeExecutionAuthorization ?? envHooks?.consumeExecutionAuthorization;
2039
+ const reportExecutionOutcome = options.reportExecutionOutcome ?? envHooks?.reportExecutionOutcome;
2040
+ if (!consumeExecutionAuthorization || !reportExecutionOutcome) throw new Error("ADT Server MCP safe_execute requires deployment-owned authorization and outcome hooks");
2041
+ return {
2042
+ consumeExecutionAuthorization,
2043
+ reportExecutionOutcome,
2044
+ executeWithDeadline
2045
+ };
2046
+ })();
2047
+ const publicKey = await loadP256PublicKey(invocation.publicKeyFile);
2048
+ const { leaseProvider, contextFactory, resolveFrozenSource } = createHttpDestinationContexts(options.brokerOptions);
2049
+ return {
2050
+ invocationVerifier: createMcpInvocationVerifier({
2051
+ publicKey,
2052
+ keyId: invocation.keyId,
2053
+ issuer: invocation.issuer,
2054
+ audience: INVOCATION_AUDIENCE
2055
+ }),
2056
+ destinationRegistry: createDestinationContextRegistry({
2057
+ leaseProvider,
2058
+ contextFactory
2059
+ }),
2060
+ resolveFrozenSource,
2061
+ ...safeExecuteOptions,
2062
+ allowedHosts: allowedHostsFromEnv(options.env)
2063
+ };
2064
+ }
2065
+
2066
+ //#endregion
2067
+ //#region src/rest-auth.ts
2068
+ function tokensMatch(expected, actual) {
2069
+ const expectedBytes = Buffer.from(expected, "utf8");
2070
+ const actualBytes = Buffer.from(actual, "utf8");
2071
+ return expectedBytes.length === actualBytes.length && timingSafeEqual(expectedBytes, actualBytes);
2072
+ }
2073
+ /**
2074
+ * Local-development REST auth. Production mesh authentication is supplied at
2075
+ * the deployment boundary; a sidecar never falls back to its broker token.
2076
+ */
2077
+ function createRestBearerAuthorizer(token) {
2078
+ const expected = token.trim();
2079
+ if (!expected) throw new Error("REST bearer token must not be empty");
2080
+ return { authorize(request) {
2081
+ const authorization = request.headers.authorization;
2082
+ if (!authorization?.startsWith("Bearer ")) return false;
2083
+ return tokensMatch(expected, authorization.slice(7));
2084
+ } };
2085
+ }
2086
+ /** An empty optional Compose secret keeps the REST surface fail-closed. */
2087
+ async function loadOptionalRestBearerAuthorizer(tokenFile) {
2088
+ if (!tokenFile) return void 0;
2089
+ const token = (await readFile(tokenFile, "utf8")).trim();
2090
+ return token ? createRestBearerAuthorizer(token) : void 0;
2091
+ }
2092
+
2093
+ //#endregion
2094
+ //#region src/rest-runtime.ts
2095
+ async function readOptionalMountedSecret(secretFile) {
2096
+ if (!secretFile) return void 0;
2097
+ return (await readFile(secretFile, "utf8")).trim() || void 0;
2098
+ }
2099
+ /**
2100
+ * REST remains disabled without a bearer secret. Once it is explicitly
2101
+ * enabled, its signed state must come from two independent mounted files so
2102
+ * source capabilities and page cursors survive a replica or process restart.
2103
+ */
2104
+ async function loadRestRuntimeSecurity(options) {
2105
+ const restAuthorizer = await loadOptionalRestBearerAuthorizer(options.tokenFile);
2106
+ if (!restAuthorizer) return {
2107
+ restAuthorizer: void 0,
2108
+ sourceCapabilities: void 0,
2109
+ atcDocumentationCapabilities: void 0,
2110
+ pageCursors: void 0
2111
+ };
2112
+ const [sourceSecret, pageCursorSecret] = await Promise.all([readOptionalMountedSecret(options.sourceSecretFile), readOptionalMountedSecret(options.pageCursorSecretFile)]);
2113
+ if (!sourceSecret || !pageCursorSecret) throw new Error("REST state secret files are required when REST bearer authentication is enabled.");
2114
+ return {
2115
+ restAuthorizer,
2116
+ sourceCapabilities: createRestSourceCapabilityService({ secret: sourceSecret }),
2117
+ atcDocumentationCapabilities: createRestAtcDocumentationCapabilityService({ secret: sourceSecret }),
2118
+ pageCursors: createRestPageCursorService({ secret: pageCursorSecret })
2119
+ };
2120
+ }
2121
+
2122
+ //#endregion
2123
+ export { createHttpDestinationContexts as a, createHttpBrokerOperations as i, createAdtServerMcpOptions as n, startAdtServer as o, executeWithDeadlineAndAbort as r, loadRestRuntimeSecurity as t };
2124
+ //# sourceMappingURL=rest-runtime-QwD2kRXE.mjs.map