@abapify/adt-services 0.0.0 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -1
- package/dist/index.d.mts +1199 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +3110 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +40 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3110 @@
|
|
|
1
|
+
import { DOMParser } from "@xmldom/xmldom";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { FileLockStore, createBatchLockSession, createLockService, resolveLockCorrelation } from "@abapify/adt-locks";
|
|
4
|
+
import { AdkObjectSet, AdkPackage, AdkTransport, AdkTransportRequest, MergedTransportView, buildTransportSourceManifest, createAdkFactory, getGlobalContext, getMainType, getObjectUri, getRegisteredTypes, initializeAdk, isAdkInitialized, listObjectSourceVersions, matchesSelector, normalizeObjectName, tryGetGlobalContext } from "@abapify/adk";
|
|
5
|
+
import { getFormatPlugin } from "@abapify/adt-plugin";
|
|
6
|
+
import { access, glob, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { loadConfig } from "@abapify/adt-config";
|
|
9
|
+
import { Readable } from "node:stream";
|
|
10
|
+
import { Buffer } from "node:buffer";
|
|
11
|
+
import { AdtResponseTooLargeError, FileLoggingPlugin, LoggingPlugin, createAdtClient } from "@abapify/adt-client";
|
|
12
|
+
import { detectMethodBoundary, normalizeMethodBody } from "@abapify/adt-lint";
|
|
13
|
+
import { AuthManager } from "@abapify/adt-auth";
|
|
14
|
+
import chalk from "chalk";
|
|
15
|
+
|
|
16
|
+
//#region src/services/badi/index.ts
|
|
17
|
+
const NS_ENHO = "http://www.sap.com/adt/enhancements/enho";
|
|
18
|
+
const NS_ADTCORE = "http://www.sap.com/adt/core";
|
|
19
|
+
function namespaceAccessor(ns) {
|
|
20
|
+
return {
|
|
21
|
+
attr(el, local) {
|
|
22
|
+
return el?.getAttributeNS(ns, local) ?? "";
|
|
23
|
+
},
|
|
24
|
+
bool(el, local) {
|
|
25
|
+
return this.attr(el, local).toLowerCase() === "true";
|
|
26
|
+
},
|
|
27
|
+
child(parent, local) {
|
|
28
|
+
return parent.getElementsByTagNameNS(ns, local).item(0) ?? null;
|
|
29
|
+
},
|
|
30
|
+
children(parent, local) {
|
|
31
|
+
const list = parent.getElementsByTagNameNS(ns, local);
|
|
32
|
+
const result = [];
|
|
33
|
+
for (let i = 0; i < list.length; i++) {
|
|
34
|
+
const node = list.item(i);
|
|
35
|
+
if (node) result.push(node);
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
const enho = namespaceAccessor(NS_ENHO);
|
|
42
|
+
const adtcore = namespaceAccessor(NS_ADTCORE);
|
|
43
|
+
function rootAttr(root, local) {
|
|
44
|
+
return adtcore.attr(root, local) || root.getAttribute(local) || "";
|
|
45
|
+
}
|
|
46
|
+
function parseBadiImplementation(node) {
|
|
47
|
+
return {
|
|
48
|
+
name: enho.attr(node, "name"),
|
|
49
|
+
shortText: enho.attr(node, "shortText"),
|
|
50
|
+
active: enho.bool(node, "active"),
|
|
51
|
+
default: enho.bool(node, "default"),
|
|
52
|
+
example: enho.bool(node, "example"),
|
|
53
|
+
implementingClass: adtcore.attr(enho.child(node, "implementingClass"), "name"),
|
|
54
|
+
badiDefinition: adtcore.attr(enho.child(node, "badiDefinition"), "name"),
|
|
55
|
+
enhancementSpot: adtcore.attr(enho.child(node, "enhancementSpot"), "name")
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function parseBadiInfo(root) {
|
|
59
|
+
const contentCommon = enho.child(root, "contentCommon");
|
|
60
|
+
return {
|
|
61
|
+
name: rootAttr(root, "name"),
|
|
62
|
+
description: rootAttr(root, "description"),
|
|
63
|
+
type: rootAttr(root, "type"),
|
|
64
|
+
package: adtcore.attr(adtcore.child(root, "packageRef"), "name"),
|
|
65
|
+
responsible: rootAttr(root, "responsible"),
|
|
66
|
+
version: rootAttr(root, "version"),
|
|
67
|
+
technology: enho.attr(contentCommon, "toolType"),
|
|
68
|
+
switchSupported: enho.bool(contentCommon, "switchSupported"),
|
|
69
|
+
badiImplementations: enho.children(root, "badiImplementation").map(parseBadiImplementation)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Parse an `enho:objectData` XML document into a `BadiInfo` structure.
|
|
74
|
+
*/
|
|
75
|
+
function parseEnhancementImplementation(xml) {
|
|
76
|
+
const root = new DOMParser({ onError: () => {} }).parseFromString(xml, "text/xml").documentElement;
|
|
77
|
+
if (!root) throw new Error("Empty or malformed ENHO XML response");
|
|
78
|
+
return parseBadiInfo(root);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Fetch ENHO metadata for a BAdI / enhancement implementation and parse
|
|
82
|
+
* the BAdI implementation list.
|
|
83
|
+
*/
|
|
84
|
+
async function getBadiInfo({ client, name }) {
|
|
85
|
+
const response = await client.fetch(`/sap/bc/adt/enhancements/enhoxhb/${encodeURIComponent(name.toLowerCase())}`, { headers: { Accept: "application/vnd.sap.adt.enh.enhoxhb.v4+xml" } });
|
|
86
|
+
if (typeof response !== "string") throw new Error("Unexpected non-XML response from ENHO endpoint");
|
|
87
|
+
return parseEnhancementImplementation(response);
|
|
88
|
+
}
|
|
89
|
+
const BADI_REPOSITORY_TYPES = /* @__PURE__ */ new Set([
|
|
90
|
+
"SXSD/XD",
|
|
91
|
+
"SXCI/XI",
|
|
92
|
+
"ENHO/XHH"
|
|
93
|
+
]);
|
|
94
|
+
function isNotFound(error) {
|
|
95
|
+
return typeof error === "object" && error !== null && error.status === 404;
|
|
96
|
+
}
|
|
97
|
+
function badiKindFromType(adtType) {
|
|
98
|
+
const type = adtType.toUpperCase();
|
|
99
|
+
if (type === "SXSD/XD") return "definition";
|
|
100
|
+
if (type === "SXCI/XI") return "implementation";
|
|
101
|
+
return "enhancement";
|
|
102
|
+
}
|
|
103
|
+
function extractSearchObjects(results) {
|
|
104
|
+
const record = results;
|
|
105
|
+
let raw;
|
|
106
|
+
if (record.objectReferences && typeof record.objectReferences === "object") raw = record.objectReferences.objectReference;
|
|
107
|
+
else if (record.objectReference) raw = record.objectReference;
|
|
108
|
+
else if (record.mainObject && typeof record.mainObject === "object") raw = record.mainObject.objectReference;
|
|
109
|
+
if (!raw) return [];
|
|
110
|
+
return Array.isArray(raw) ? raw : [raw];
|
|
111
|
+
}
|
|
112
|
+
function normalizeClassicBadiMetadata({ response, kind }) {
|
|
113
|
+
if (!("mainObject" in response) || !response.mainObject) throw new Error("BAdI response missing mainObject");
|
|
114
|
+
const main = response.mainObject;
|
|
115
|
+
return {
|
|
116
|
+
kind,
|
|
117
|
+
name: (main.name ?? "").toUpperCase(),
|
|
118
|
+
type: main.type ?? "",
|
|
119
|
+
description: main.description,
|
|
120
|
+
language: main.language,
|
|
121
|
+
version: main.version,
|
|
122
|
+
packageName: main.packageRef?.name,
|
|
123
|
+
packageUri: main.packageRef?.uri,
|
|
124
|
+
responsible: main.responsible,
|
|
125
|
+
masterLanguage: main.masterLanguage,
|
|
126
|
+
masterSystem: main.masterSystem,
|
|
127
|
+
containerRef: main.containerRef ? {
|
|
128
|
+
name: main.containerRef.name,
|
|
129
|
+
type: main.containerRef.type
|
|
130
|
+
} : void 0
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function searchQueriesForDefinition({ name }) {
|
|
134
|
+
const normalized = name.trim().toUpperCase();
|
|
135
|
+
const queries = /* @__PURE__ */ new Set([`*${normalized}*`, `*${normalized.replace(/_/g, "*")}*`]);
|
|
136
|
+
const parts = normalized.split("_").filter(Boolean);
|
|
137
|
+
if (parts.length >= 2) {
|
|
138
|
+
const tail2 = parts.slice(-2).join("_");
|
|
139
|
+
if (tail2.length >= 10) queries.add(`*${tail2}*`);
|
|
140
|
+
}
|
|
141
|
+
return [...queries];
|
|
142
|
+
}
|
|
143
|
+
async function resolveBySearch(ctx) {
|
|
144
|
+
const matches = extractSearchObjects(await ctx.client.adt.repository.informationsystem.search.quickSearch({
|
|
145
|
+
query: ctx.normalized,
|
|
146
|
+
maxResults: 20
|
|
147
|
+
})).filter((obj) => obj.name?.toUpperCase() === ctx.normalized && obj.type && BADI_REPOSITORY_TYPES.has(obj.type.toUpperCase()));
|
|
148
|
+
if (matches.length === 1) return badiKindFromType(matches[0].type);
|
|
149
|
+
if (matches.length > 1) throw new Error(`Ambiguous BAdI name ${ctx.normalized}: ${matches.map((m) => m.type).join(", ")}`);
|
|
150
|
+
}
|
|
151
|
+
async function runProbe(ctx) {
|
|
152
|
+
const response = ctx.kind === "definition" ? await ctx.client.adt.vit.wb.objectProperties.getDefinition(ctx.normalized) : await ctx.client.adt.vit.wb.objectProperties.getImplementation(ctx.normalized);
|
|
153
|
+
if (!("mainObject" in response) || !response.mainObject) return;
|
|
154
|
+
const main = response.mainObject;
|
|
155
|
+
if (main.type?.toUpperCase() === ctx.expectedType && main.name?.toUpperCase() === ctx.normalized) return ctx.kind;
|
|
156
|
+
}
|
|
157
|
+
async function resolveEnhancement(ctx) {
|
|
158
|
+
try {
|
|
159
|
+
await getBadiInfo({
|
|
160
|
+
client: ctx.client,
|
|
161
|
+
name: ctx.normalized
|
|
162
|
+
});
|
|
163
|
+
return "enhancement";
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (!isNotFound(error)) throw error;
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function resolveKind(ctx) {
|
|
170
|
+
const bySearch = await resolveBySearch(ctx);
|
|
171
|
+
if (bySearch) return bySearch;
|
|
172
|
+
const definition = await runProbe({
|
|
173
|
+
...ctx,
|
|
174
|
+
kind: "definition",
|
|
175
|
+
expectedType: "SXSD/XD"
|
|
176
|
+
});
|
|
177
|
+
if (definition) return definition;
|
|
178
|
+
const implementation = await runProbe({
|
|
179
|
+
...ctx,
|
|
180
|
+
kind: "implementation",
|
|
181
|
+
expectedType: "SXCI/XI"
|
|
182
|
+
});
|
|
183
|
+
if (implementation) return implementation;
|
|
184
|
+
const enhancement = await resolveEnhancement(ctx);
|
|
185
|
+
if (enhancement) return enhancement;
|
|
186
|
+
throw new Error(`BAdI object not found: ${ctx.normalized}`);
|
|
187
|
+
}
|
|
188
|
+
async function readDefinition(ctx) {
|
|
189
|
+
return normalizeClassicBadiMetadata({
|
|
190
|
+
response: await ctx.client.adt.vit.wb.objectProperties.getDefinition(ctx.normalized),
|
|
191
|
+
kind: "definition"
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
async function readImplementation(ctx) {
|
|
195
|
+
return normalizeClassicBadiMetadata({
|
|
196
|
+
response: await ctx.client.adt.vit.wb.objectProperties.getImplementation(ctx.normalized),
|
|
197
|
+
kind: "implementation"
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
async function readEnhancement(ctx) {
|
|
201
|
+
const lower = ctx.normalized.toLowerCase();
|
|
202
|
+
const info = await getBadiInfo({
|
|
203
|
+
client: ctx.client,
|
|
204
|
+
name: ctx.normalized
|
|
205
|
+
});
|
|
206
|
+
const source = ctx.options?.includeSource ? String(await ctx.client.adt.enhancements.enhoxhh.source.main.get(lower)) : void 0;
|
|
207
|
+
return {
|
|
208
|
+
kind: "enhancement",
|
|
209
|
+
name: info.name.toUpperCase(),
|
|
210
|
+
type: info.type,
|
|
211
|
+
description: info.description,
|
|
212
|
+
version: info.version,
|
|
213
|
+
packageName: info.package,
|
|
214
|
+
responsible: info.responsible,
|
|
215
|
+
enhancement: info,
|
|
216
|
+
source
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
async function getBadi(ctx) {
|
|
220
|
+
const kind = await resolveKind(ctx);
|
|
221
|
+
switch (kind) {
|
|
222
|
+
case "definition": {
|
|
223
|
+
const definition = await readDefinition(ctx);
|
|
224
|
+
if (!ctx.options?.includeImplementations) return definition;
|
|
225
|
+
const implementations = await listImplementations(ctx);
|
|
226
|
+
return {
|
|
227
|
+
...definition,
|
|
228
|
+
implementations
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
case "implementation": return readImplementation(ctx);
|
|
232
|
+
case "enhancement": return readEnhancement(ctx);
|
|
233
|
+
default: throw new Error(`Unsupported BAdI kind: ${kind}`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function candidateNames(ctx) {
|
|
237
|
+
const names = [];
|
|
238
|
+
for (const obj of extractSearchObjects(ctx.search)) {
|
|
239
|
+
if (obj.type?.toUpperCase() !== "SXCI/XI") continue;
|
|
240
|
+
const implName = obj.name?.toUpperCase();
|
|
241
|
+
if (!implName) continue;
|
|
242
|
+
if (implName === ctx.normalized) continue;
|
|
243
|
+
if (ctx.seen.has(implName)) continue;
|
|
244
|
+
ctx.seen.add(implName);
|
|
245
|
+
names.push(implName);
|
|
246
|
+
}
|
|
247
|
+
return names;
|
|
248
|
+
}
|
|
249
|
+
async function tryReadImplementation(ctx) {
|
|
250
|
+
try {
|
|
251
|
+
const impl = await readImplementation({
|
|
252
|
+
client: ctx.client,
|
|
253
|
+
normalized: ctx.implName
|
|
254
|
+
});
|
|
255
|
+
const containerName = impl.containerRef?.name?.toUpperCase();
|
|
256
|
+
if (containerName && containerName !== ctx.definitionName) return;
|
|
257
|
+
return impl;
|
|
258
|
+
} catch (error) {
|
|
259
|
+
if (!isNotFound(error)) throw error;
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async function collectSearchCandidates(ctx) {
|
|
264
|
+
const params = {
|
|
265
|
+
query: ctx.query,
|
|
266
|
+
maxResults: 100
|
|
267
|
+
};
|
|
268
|
+
if (ctx.objectType) params.objectType = ctx.objectType;
|
|
269
|
+
const names = candidateNames({
|
|
270
|
+
search: await ctx.client.adt.repository.informationsystem.search.quickSearch(params),
|
|
271
|
+
normalized: ctx.normalized,
|
|
272
|
+
seen: ctx.seen
|
|
273
|
+
});
|
|
274
|
+
const found = [];
|
|
275
|
+
for (const implName of names) {
|
|
276
|
+
const impl = await tryReadImplementation({
|
|
277
|
+
client: ctx.client,
|
|
278
|
+
definitionName: ctx.normalized,
|
|
279
|
+
implName
|
|
280
|
+
});
|
|
281
|
+
if (impl) found.push(impl);
|
|
282
|
+
}
|
|
283
|
+
return found;
|
|
284
|
+
}
|
|
285
|
+
async function listImplementations(ctx) {
|
|
286
|
+
await readDefinition(ctx);
|
|
287
|
+
const queries = searchQueriesForDefinition({ name: ctx.normalized });
|
|
288
|
+
const seen = /* @__PURE__ */ new Set();
|
|
289
|
+
const all = [];
|
|
290
|
+
for (const query of queries) {
|
|
291
|
+
all.push(...await collectSearchCandidates({
|
|
292
|
+
client: ctx.client,
|
|
293
|
+
normalized: ctx.normalized,
|
|
294
|
+
query,
|
|
295
|
+
seen
|
|
296
|
+
}));
|
|
297
|
+
all.push(...await collectSearchCandidates({
|
|
298
|
+
client: ctx.client,
|
|
299
|
+
normalized: ctx.normalized,
|
|
300
|
+
query,
|
|
301
|
+
objectType: "SXCI",
|
|
302
|
+
seen
|
|
303
|
+
}));
|
|
304
|
+
}
|
|
305
|
+
return all.sort((a, b) => a.name.localeCompare(b.name));
|
|
306
|
+
}
|
|
307
|
+
var BadiService = class {
|
|
308
|
+
client;
|
|
309
|
+
constructor(client) {
|
|
310
|
+
this.client = client;
|
|
311
|
+
}
|
|
312
|
+
contextFor(name) {
|
|
313
|
+
return {
|
|
314
|
+
client: this.client,
|
|
315
|
+
normalized: name.trim().toUpperCase()
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
readContextFor(name, options) {
|
|
319
|
+
return {
|
|
320
|
+
...this.contextFor(name),
|
|
321
|
+
options
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
async resolveKind({ name }) {
|
|
325
|
+
return resolveKind(this.contextFor(name));
|
|
326
|
+
}
|
|
327
|
+
async get({ name, options }) {
|
|
328
|
+
return getBadi(this.readContextFor(name, options));
|
|
329
|
+
}
|
|
330
|
+
async getDefinition({ name }) {
|
|
331
|
+
return readDefinition(this.contextFor(name));
|
|
332
|
+
}
|
|
333
|
+
async getImplementation({ name }) {
|
|
334
|
+
return readImplementation(this.contextFor(name));
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* List classic BAdI implementations (SXCI/XI) for a definition name.
|
|
338
|
+
* Uses repository quick search heuristics — authoritative active/inactive
|
|
339
|
+
* state requires SXC_ATTR (not exposed on all systems).
|
|
340
|
+
*/
|
|
341
|
+
async listImplementations({ name }) {
|
|
342
|
+
return listImplementations(this.contextFor(name));
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
/** @deprecated Use BadiService */
|
|
346
|
+
const ClassicBadiService = BadiService;
|
|
347
|
+
|
|
348
|
+
//#endregion
|
|
349
|
+
//#region src/services/changeset/service.ts
|
|
350
|
+
/**
|
|
351
|
+
* `ChangesetService` — transport-agnostic transactional unit-of-work.
|
|
352
|
+
*
|
|
353
|
+
* Wave 3 of the MCP HTTP transport introduces changesets so that an AI
|
|
354
|
+
* agent can lock + stage several source writes, review them, and then
|
|
355
|
+
* atomically commit (batch activate) or roll back (release locks).
|
|
356
|
+
*
|
|
357
|
+
* Architectural contract:
|
|
358
|
+
*
|
|
359
|
+
* - This service is **pure business logic**: no `console.*`, no
|
|
360
|
+
* commander, no file I/O. Callers feed it an `AdtClient` and a
|
|
361
|
+
* `Logger` and receive structured results / thrown errors.
|
|
362
|
+
* - Both the CLI (`adt changeset …`) and MCP tools
|
|
363
|
+
* (`changeset_begin` / `changeset_add` / `changeset_commit` /
|
|
364
|
+
* `changeset_rollback`) delegate straight through. That is the only
|
|
365
|
+
* way to keep CLI ↔ MCP parity honest.
|
|
366
|
+
* - Locks are acquired and released through `@abapify/adt-locks` —
|
|
367
|
+
* the single lock service in this monorepo. We never hand-roll lock
|
|
368
|
+
* protocol here (nor in the MCP tools).
|
|
369
|
+
*
|
|
370
|
+
* Commit strategy:
|
|
371
|
+
*
|
|
372
|
+
* SAP ADT supports batch activation via a single POST to
|
|
373
|
+
* `/sap/bc/adt/activation` with an `adtcore:objectReferences` body
|
|
374
|
+
* carrying N references. We use the typed `activation.activate.post`
|
|
375
|
+
* contract from `@abapify/adt-client` for this — NOT a manual XML
|
|
376
|
+
* string. One HTTP round-trip, all entries activated together.
|
|
377
|
+
*
|
|
378
|
+
* If activation fails with an error, `commit` still tries to release
|
|
379
|
+
* every lock (best-effort) and surfaces both the activation error and
|
|
380
|
+
* the per-entry release outcomes in the result.
|
|
381
|
+
*
|
|
382
|
+
* Rollback semantics (explicit):
|
|
383
|
+
*
|
|
384
|
+
* Rollback releases locks but does NOT revert the PUTs that `add`
|
|
385
|
+
* already persisted on SAP. SAP has no transactional "discard" API
|
|
386
|
+
* over ADT: the inactive version stays on the system until the next
|
|
387
|
+
* edit/activate cycle. This matches Eclipse ADT's behaviour when a
|
|
388
|
+
* developer closes the editor without activating.
|
|
389
|
+
*/
|
|
390
|
+
/** Create a brand-new empty changeset (no SAP interaction yet). */
|
|
391
|
+
function createChangeset(description) {
|
|
392
|
+
return {
|
|
393
|
+
id: randomUUID(),
|
|
394
|
+
openedAt: Date.now(),
|
|
395
|
+
status: "open",
|
|
396
|
+
entries: [],
|
|
397
|
+
description
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
var ChangesetService = class {
|
|
401
|
+
client;
|
|
402
|
+
logger;
|
|
403
|
+
locks;
|
|
404
|
+
constructor(client, logger) {
|
|
405
|
+
this.client = client;
|
|
406
|
+
this.logger = logger;
|
|
407
|
+
this.locks = createLockService(client);
|
|
408
|
+
}
|
|
409
|
+
/** Transport-agnostic: returns a fresh Changeset descriptor. */
|
|
410
|
+
begin(description) {
|
|
411
|
+
const cs = createChangeset(description);
|
|
412
|
+
this.logger?.debug("changeset: begin", { id: cs.id });
|
|
413
|
+
return cs;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Lock the object, PUT the source, and register the entry. Throws on
|
|
417
|
+
* lock or PUT failure; lock is released in the error path so the
|
|
418
|
+
* caller never sees a half-applied entry.
|
|
419
|
+
*/
|
|
420
|
+
async add(changeset, args) {
|
|
421
|
+
if (changeset.status !== "open") throw new Error(`changeset ${changeset.id} is not open (status=${changeset.status})`);
|
|
422
|
+
const lock = await this.locks.lock(args.objectUri, {
|
|
423
|
+
transport: args.transport,
|
|
424
|
+
objectName: args.objectName,
|
|
425
|
+
objectType: args.objectType
|
|
426
|
+
});
|
|
427
|
+
const effectiveTransport = resolveLockCorrelation(lock, args.transport);
|
|
428
|
+
try {
|
|
429
|
+
const params = new URLSearchParams();
|
|
430
|
+
params.set("lockHandle", lock.handle);
|
|
431
|
+
if (effectiveTransport) params.set("corrNr", effectiveTransport);
|
|
432
|
+
await this.client.fetch(`${args.objectUri}/source/main?${params.toString()}`, {
|
|
433
|
+
method: "PUT",
|
|
434
|
+
headers: { "Content-Type": "text/plain" },
|
|
435
|
+
body: args.source
|
|
436
|
+
});
|
|
437
|
+
} catch (err) {
|
|
438
|
+
try {
|
|
439
|
+
await this.locks.unlock(args.objectUri, { lockHandle: lock.handle });
|
|
440
|
+
} catch (unlockErr) {
|
|
441
|
+
this.logger?.warn("changeset: failed to unlock after PUT failure", {
|
|
442
|
+
objectUri: args.objectUri,
|
|
443
|
+
error: unlockErr instanceof Error ? unlockErr.message : String(unlockErr)
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
throw err;
|
|
447
|
+
}
|
|
448
|
+
const entry = {
|
|
449
|
+
objectUri: args.objectUri,
|
|
450
|
+
objectType: args.objectType.toUpperCase(),
|
|
451
|
+
objectName: args.objectName.toUpperCase(),
|
|
452
|
+
lockHandle: lock.handle,
|
|
453
|
+
action: "update",
|
|
454
|
+
createdAt: Date.now()
|
|
455
|
+
};
|
|
456
|
+
changeset.entries.push(entry);
|
|
457
|
+
this.logger?.debug("changeset: add", {
|
|
458
|
+
id: changeset.id,
|
|
459
|
+
objectUri: args.objectUri
|
|
460
|
+
});
|
|
461
|
+
return entry;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Batch-activate every entry, then release every lock. The changeset
|
|
465
|
+
* is mutated in place: `status` advances to `committing` during the
|
|
466
|
+
* call and `committed` on success. On activation failure it is left
|
|
467
|
+
* as `committing` and the error is rethrown after lock cleanup.
|
|
468
|
+
*/
|
|
469
|
+
async commit(changeset) {
|
|
470
|
+
if (changeset.status !== "open") throw new Error(`changeset ${changeset.id} is not open (status=${changeset.status})`);
|
|
471
|
+
changeset.status = "committing";
|
|
472
|
+
if (changeset.entries.length === 0) {
|
|
473
|
+
changeset.status = "committed";
|
|
474
|
+
return {
|
|
475
|
+
activated: [],
|
|
476
|
+
failed: []
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
const body = { objectReferences: { objectReference: changeset.entries.map((e) => ({
|
|
480
|
+
uri: e.objectUri,
|
|
481
|
+
type: e.objectType,
|
|
482
|
+
name: e.objectName
|
|
483
|
+
})) } };
|
|
484
|
+
const result = {
|
|
485
|
+
activated: [],
|
|
486
|
+
failed: []
|
|
487
|
+
};
|
|
488
|
+
let activationError;
|
|
489
|
+
try {
|
|
490
|
+
await this.client.adt.activation.activate.post({
|
|
491
|
+
method: "activate",
|
|
492
|
+
preauditRequested: true
|
|
493
|
+
}, body);
|
|
494
|
+
result.activated = changeset.entries.map((e) => e.objectUri);
|
|
495
|
+
} catch (err) {
|
|
496
|
+
activationError = err instanceof Error ? err : new Error(String(err));
|
|
497
|
+
result.failed = changeset.entries.map((e) => ({
|
|
498
|
+
uri: e.objectUri,
|
|
499
|
+
error: activationError.message
|
|
500
|
+
}));
|
|
501
|
+
}
|
|
502
|
+
for (const entry of changeset.entries) try {
|
|
503
|
+
await this.locks.unlock(entry.objectUri, { lockHandle: entry.lockHandle });
|
|
504
|
+
} catch (err) {
|
|
505
|
+
this.logger?.warn("changeset: unlock failed during commit", {
|
|
506
|
+
id: changeset.id,
|
|
507
|
+
objectUri: entry.objectUri,
|
|
508
|
+
error: err instanceof Error ? err.message : String(err)
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
if (activationError) throw activationError;
|
|
512
|
+
changeset.status = "committed";
|
|
513
|
+
this.logger?.debug("changeset: commit", {
|
|
514
|
+
id: changeset.id,
|
|
515
|
+
activated: result.activated.length
|
|
516
|
+
});
|
|
517
|
+
return result;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Release every lock (best-effort) and mark the changeset
|
|
521
|
+
* `rolled_back`. Does NOT revert PUT'ed source — see file-level
|
|
522
|
+
* comment for rationale.
|
|
523
|
+
*/
|
|
524
|
+
async rollback(changeset) {
|
|
525
|
+
if (changeset.status === "committed") throw new Error(`changeset ${changeset.id} is already committed`);
|
|
526
|
+
if (changeset.status === "rolled_back") return {
|
|
527
|
+
released: [],
|
|
528
|
+
failed: []
|
|
529
|
+
};
|
|
530
|
+
const result = {
|
|
531
|
+
released: [],
|
|
532
|
+
failed: []
|
|
533
|
+
};
|
|
534
|
+
for (const entry of changeset.entries) try {
|
|
535
|
+
await this.locks.unlock(entry.objectUri, { lockHandle: entry.lockHandle });
|
|
536
|
+
result.released.push(entry.objectUri);
|
|
537
|
+
} catch (err) {
|
|
538
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
539
|
+
this.logger?.warn("changeset: unlock failed during rollback", {
|
|
540
|
+
id: changeset.id,
|
|
541
|
+
objectUri: entry.objectUri,
|
|
542
|
+
error: message
|
|
543
|
+
});
|
|
544
|
+
result.failed.push({
|
|
545
|
+
uri: entry.objectUri,
|
|
546
|
+
error: message
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
changeset.status = "rolled_back";
|
|
550
|
+
this.logger?.debug("changeset: rollback", {
|
|
551
|
+
id: changeset.id,
|
|
552
|
+
released: result.released.length,
|
|
553
|
+
failed: result.failed.length
|
|
554
|
+
});
|
|
555
|
+
return result;
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region src/utils/format-loader.ts
|
|
561
|
+
/**
|
|
562
|
+
* Format-plugin loader for CLI commands.
|
|
563
|
+
*
|
|
564
|
+
* Format plugins self-register into the global `FormatPlugin` registry when
|
|
565
|
+
* their package is imported. This loader translates the CLI's legacy format
|
|
566
|
+
* spec (`abapgit` / `ag` / `@abapify/adt-plugin-abapgit` / `pkg/preset`) into
|
|
567
|
+
* a live `AdtPlugin` (the higher-level import/export plugin) so existing
|
|
568
|
+
* import services keep working.
|
|
569
|
+
*
|
|
570
|
+
* Built-in format id → package mappings. New built-in formats just need one
|
|
571
|
+
* extra entry here (plus the side-effect import in `cli.ts`).
|
|
572
|
+
*/
|
|
573
|
+
const FORMAT_SHORTCUTS = {
|
|
574
|
+
abapgit: "@abapify/adt-plugin-abapgit",
|
|
575
|
+
ag: "@abapify/adt-plugin-abapgit",
|
|
576
|
+
aff: "@abapify/adt-plugin-gcts",
|
|
577
|
+
gcts: "@abapify/adt-plugin-gcts"
|
|
578
|
+
};
|
|
579
|
+
/** Resolve a CLI format id to its registered package name (if known). */
|
|
580
|
+
function resolvePackageForFormatId(id) {
|
|
581
|
+
return FORMAT_SHORTCUTS[id];
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Parse format specification with optional preset.
|
|
585
|
+
*
|
|
586
|
+
* Examples:
|
|
587
|
+
* @abapify/adt-plugin-abapgit → { package: '@abapify/adt-plugin-abapgit' }
|
|
588
|
+
* @abapify/adt-plugin-abapgit/full → { package: '@abapify/adt-plugin-abapgit', preset: 'full' }
|
|
589
|
+
* abapgit → { package: '@abapify/adt-plugin-abapgit' } (shortcut)
|
|
590
|
+
* ag → { package: '@abapify/adt-plugin-abapgit' } (shortcut)
|
|
591
|
+
*/
|
|
592
|
+
function parseFormatSpec(formatSpec) {
|
|
593
|
+
if (formatSpec in FORMAT_SHORTCUTS) return { package: FORMAT_SHORTCUTS[formatSpec] };
|
|
594
|
+
const parts = formatSpec.split("/");
|
|
595
|
+
if (parts.length === 2) return { package: formatSpec };
|
|
596
|
+
else if (parts.length === 3) return {
|
|
597
|
+
package: `${parts[0]}/${parts[1]}`,
|
|
598
|
+
preset: parts[2]
|
|
599
|
+
};
|
|
600
|
+
else throw new Error(`Invalid format specification: ${formatSpec}`);
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Load a format plugin by CLI spec.
|
|
604
|
+
*
|
|
605
|
+
* Resolution order:
|
|
606
|
+
* 1. Look up the format id in the {@link FormatPlugin} registry. If it is
|
|
607
|
+
* already registered (e.g. via CLI bootstrap), use it without any dynamic
|
|
608
|
+
* import.
|
|
609
|
+
* 2. Otherwise dynamically `import(packageName)` — this triggers the
|
|
610
|
+
* package's self-registration side-effects — then return the resolved
|
|
611
|
+
* legacy `AdtPlugin` instance from the package's default/named export.
|
|
612
|
+
*/
|
|
613
|
+
async function loadFormatPlugin(formatSpec) {
|
|
614
|
+
const { package: packageName, preset } = parseFormatSpec(formatSpec);
|
|
615
|
+
const builtinId = Object.entries(FORMAT_SHORTCUTS).find(([, pkg]) => pkg === packageName)?.[0];
|
|
616
|
+
if (builtinId && !getFormatPlugin(builtinId)) {}
|
|
617
|
+
try {
|
|
618
|
+
const pluginModule = await import(packageName);
|
|
619
|
+
const PluginClass = pluginModule.default || pluginModule[Object.keys(pluginModule)[0]];
|
|
620
|
+
if (!PluginClass) throw new Error(`No plugin class found in ${packageName}`);
|
|
621
|
+
const options = preset ? { preset } : {};
|
|
622
|
+
const plugin = typeof PluginClass === "function" && PluginClass.prototype ? new PluginClass(options) : PluginClass;
|
|
623
|
+
return {
|
|
624
|
+
name: plugin.name || packageName,
|
|
625
|
+
description: plugin.description || `Plugin from ${packageName}`,
|
|
626
|
+
instance: plugin,
|
|
627
|
+
preset
|
|
628
|
+
};
|
|
629
|
+
} catch (error) {
|
|
630
|
+
const err = error;
|
|
631
|
+
if (err.code === "MODULE_NOT_FOUND" || err.message?.includes(`Cannot find module '${packageName}'`)) throw new Error(`Plugin package '${packageName}' not found. Install it with: bun add ${packageName}`, { cause: error });
|
|
632
|
+
throw error;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
//#endregion
|
|
637
|
+
//#region src/services/checkin/filetree.ts
|
|
638
|
+
/**
|
|
639
|
+
* FileTree implementation used by the CheckinService.
|
|
640
|
+
*
|
|
641
|
+
* Mirrors the `FsFileTree` in `@abapify/adt-export` but kept local so the
|
|
642
|
+
* checkin feature doesn't drag an export-time dependency back into
|
|
643
|
+
* `adt-cli` (which would violate the module-boundary rules between
|
|
644
|
+
* adt-cli and plugin-like packages).
|
|
645
|
+
*/
|
|
646
|
+
var FsFileTree = class {
|
|
647
|
+
root;
|
|
648
|
+
constructor(root) {
|
|
649
|
+
this.root = root;
|
|
650
|
+
}
|
|
651
|
+
async glob(pattern) {
|
|
652
|
+
const results = [];
|
|
653
|
+
for await (const path of glob(pattern, { cwd: this.root })) results.push(path);
|
|
654
|
+
return results;
|
|
655
|
+
}
|
|
656
|
+
async read(path) {
|
|
657
|
+
const content = await readFile(join(this.root, path), "utf-8");
|
|
658
|
+
return content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
659
|
+
}
|
|
660
|
+
async readBuffer(path) {
|
|
661
|
+
return readFile(join(this.root, path));
|
|
662
|
+
}
|
|
663
|
+
async exists(path) {
|
|
664
|
+
try {
|
|
665
|
+
await access(join(this.root, path));
|
|
666
|
+
return true;
|
|
667
|
+
} catch {
|
|
668
|
+
return false;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
async readdir(path) {
|
|
672
|
+
return readdir(path ? join(this.root, path) : this.root);
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
function createFsFileTree(root) {
|
|
676
|
+
return new FsFileTree(root);
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
//#endregion
|
|
680
|
+
//#region src/services/checkin/diff.ts
|
|
681
|
+
/**
|
|
682
|
+
* Compute diff for a single object.
|
|
683
|
+
*
|
|
684
|
+
* Returns the `ChangePlanEntry` without yet mutating anything on SAP. The
|
|
685
|
+
* caller decides whether to group, filter, or apply the plan.
|
|
686
|
+
*/
|
|
687
|
+
async function diffObject(object) {
|
|
688
|
+
const hasPending = Boolean(object._pendingSource || object._pendingSources || object._pendingDescription);
|
|
689
|
+
try {
|
|
690
|
+
const localData = object._data;
|
|
691
|
+
await object.load();
|
|
692
|
+
object._data = localData;
|
|
693
|
+
return {
|
|
694
|
+
object,
|
|
695
|
+
action: hasPending ? "update" : "unchanged",
|
|
696
|
+
reason: hasPending ? "local source pending write" : "no local changes detected"
|
|
697
|
+
};
|
|
698
|
+
} catch (err) {
|
|
699
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
700
|
+
if (/404|not[- ]?found/i.test(msg)) return {
|
|
701
|
+
object,
|
|
702
|
+
action: "create",
|
|
703
|
+
reason: "remote object does not exist"
|
|
704
|
+
};
|
|
705
|
+
return {
|
|
706
|
+
object,
|
|
707
|
+
action: "skip",
|
|
708
|
+
error: msg,
|
|
709
|
+
reason: `diff failed: ${msg}`
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
//#endregion
|
|
715
|
+
//#region src/services/checkin/plan.ts
|
|
716
|
+
/** Object types classified by dependency tier (main type only). */
|
|
717
|
+
const TIER_FOR_TYPE = {
|
|
718
|
+
DOMA: "ddic",
|
|
719
|
+
DTEL: "ddic",
|
|
720
|
+
TABL: "ddic",
|
|
721
|
+
TTYP: "ddic",
|
|
722
|
+
VIEW: "ddic",
|
|
723
|
+
ENQU: "ddic",
|
|
724
|
+
SHLP: "ddic",
|
|
725
|
+
DEVC: "package",
|
|
726
|
+
CLAS: "app",
|
|
727
|
+
INTF: "app",
|
|
728
|
+
PROG: "app",
|
|
729
|
+
INCL: "app",
|
|
730
|
+
FUGR: "app",
|
|
731
|
+
DDLS: "cds",
|
|
732
|
+
DCLS: "cds",
|
|
733
|
+
DDLX: "cds",
|
|
734
|
+
SRVD: "cds",
|
|
735
|
+
SRVB: "cds",
|
|
736
|
+
BDEF: "cds"
|
|
737
|
+
};
|
|
738
|
+
/** Order tiers are applied. */
|
|
739
|
+
const TIER_ORDER = [
|
|
740
|
+
"package",
|
|
741
|
+
"ddic",
|
|
742
|
+
"app",
|
|
743
|
+
"cds",
|
|
744
|
+
"other"
|
|
745
|
+
];
|
|
746
|
+
function classifyTier(type) {
|
|
747
|
+
return TIER_FOR_TYPE[getMainType(type)] ?? "other";
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Build a ChangePlan by classifying each entry and sorting into tiers.
|
|
751
|
+
*
|
|
752
|
+
* Entries whose action is `skip` or `unchanged` are parked in `inert` so the
|
|
753
|
+
* apply stage doesn't touch them. Empty tiers are elided.
|
|
754
|
+
*/
|
|
755
|
+
function buildPlan(entries) {
|
|
756
|
+
const byTier = /* @__PURE__ */ new Map();
|
|
757
|
+
const inert = [];
|
|
758
|
+
for (const entry of entries) {
|
|
759
|
+
if (entry.action === "skip" || entry.action === "unchanged") {
|
|
760
|
+
inert.push(entry);
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
const tier = classifyTier(entry.object.type);
|
|
764
|
+
const bucket = byTier.get(tier) ?? [];
|
|
765
|
+
bucket.push(entry);
|
|
766
|
+
byTier.set(tier, bucket);
|
|
767
|
+
}
|
|
768
|
+
const groups = [];
|
|
769
|
+
for (const tier of TIER_ORDER) {
|
|
770
|
+
const bucket = byTier.get(tier);
|
|
771
|
+
if (bucket && bucket.length > 0) groups.push({
|
|
772
|
+
tier,
|
|
773
|
+
entries: bucket
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
return {
|
|
777
|
+
entries,
|
|
778
|
+
groups,
|
|
779
|
+
inert
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
/** Extract a flat ordered list of AdkObjects from a plan (apply order). */
|
|
783
|
+
function flattenPlanObjects(plan) {
|
|
784
|
+
const out = [];
|
|
785
|
+
for (const group of plan.groups) for (const entry of group.entries) out.push(entry.object);
|
|
786
|
+
return out;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
//#endregion
|
|
790
|
+
//#region src/services/checkin/apply.ts
|
|
791
|
+
/** Execute the change plan. Always returns a result — caller decides exit. */
|
|
792
|
+
async function applyPlan(plan, ctx, options = {}) {
|
|
793
|
+
const activate = options.activate ?? true;
|
|
794
|
+
const result = {
|
|
795
|
+
tiers: [],
|
|
796
|
+
totals: {
|
|
797
|
+
saved: 0,
|
|
798
|
+
failed: 0,
|
|
799
|
+
unchanged: 0,
|
|
800
|
+
activated: 0
|
|
801
|
+
},
|
|
802
|
+
aborted: false
|
|
803
|
+
};
|
|
804
|
+
for (const group of plan.groups) {
|
|
805
|
+
const tierResult = {
|
|
806
|
+
tier: group.tier,
|
|
807
|
+
size: group.entries.length,
|
|
808
|
+
saved: 0,
|
|
809
|
+
failed: 0,
|
|
810
|
+
unchanged: 0,
|
|
811
|
+
activated: 0,
|
|
812
|
+
errors: []
|
|
813
|
+
};
|
|
814
|
+
options.onTierStart?.(group.tier, group.entries.length);
|
|
815
|
+
if (options.dryRun) {
|
|
816
|
+
for (const entry of group.entries) {
|
|
817
|
+
options.onObject?.(entry.object, "dry-run");
|
|
818
|
+
tierResult.saved++;
|
|
819
|
+
}
|
|
820
|
+
result.tiers.push(tierResult);
|
|
821
|
+
result.totals.saved += tierResult.saved;
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
if (options.unlock && ctx.lockService) for (const entry of group.entries) try {
|
|
825
|
+
await ctx.lockService.forceUnlock(entry.object.objectUri);
|
|
826
|
+
} catch {}
|
|
827
|
+
let preflightFailed = false;
|
|
828
|
+
if (ctx.lockService) {
|
|
829
|
+
const targets = group.entries.map((e) => ({
|
|
830
|
+
objectUri: e.object.objectUri,
|
|
831
|
+
options: {
|
|
832
|
+
transport: options.transport,
|
|
833
|
+
objectName: e.object.name,
|
|
834
|
+
objectType: e.object.type
|
|
835
|
+
}
|
|
836
|
+
}));
|
|
837
|
+
const batch = createBatchLockSession(ctx.lockService, targets);
|
|
838
|
+
try {
|
|
839
|
+
await batch.begin();
|
|
840
|
+
} catch (err) {
|
|
841
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
842
|
+
tierResult.errors.push({
|
|
843
|
+
name: "(batch)",
|
|
844
|
+
type: group.tier,
|
|
845
|
+
error: `batch lock pre-flight failed: ${msg}`
|
|
846
|
+
});
|
|
847
|
+
tierResult.failed = group.entries.length;
|
|
848
|
+
preflightFailed = true;
|
|
849
|
+
} finally {
|
|
850
|
+
await batch.release();
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
if (preflightFailed) {
|
|
854
|
+
result.tiers.push(tierResult);
|
|
855
|
+
result.totals.failed += tierResult.failed;
|
|
856
|
+
result.aborted = true;
|
|
857
|
+
break;
|
|
858
|
+
}
|
|
859
|
+
const set = new AdkObjectSet(ctx);
|
|
860
|
+
for (const entry of group.entries) set.add(entry.object);
|
|
861
|
+
const deployResult = await set.deploy({
|
|
862
|
+
transport: options.transport,
|
|
863
|
+
activate,
|
|
864
|
+
mode: "upsert",
|
|
865
|
+
onProgress: (_processed, _total, current) => {
|
|
866
|
+
options.onObject?.(current, "saved");
|
|
867
|
+
}
|
|
868
|
+
});
|
|
869
|
+
tierResult.saved = deployResult.save.success;
|
|
870
|
+
tierResult.failed = deployResult.save.failed;
|
|
871
|
+
tierResult.unchanged = deployResult.save.unchanged;
|
|
872
|
+
tierResult.activated = deployResult.activation?.success ?? 0;
|
|
873
|
+
for (const r of deployResult.save.results) if (!r.success && !r.unchanged) tierResult.errors.push({
|
|
874
|
+
name: r.object.name,
|
|
875
|
+
type: r.object.type,
|
|
876
|
+
error: r.error ?? "unknown error"
|
|
877
|
+
});
|
|
878
|
+
result.tiers.push(tierResult);
|
|
879
|
+
result.totals.saved += tierResult.saved;
|
|
880
|
+
result.totals.failed += tierResult.failed;
|
|
881
|
+
result.totals.unchanged += tierResult.unchanged;
|
|
882
|
+
result.totals.activated += tierResult.activated;
|
|
883
|
+
}
|
|
884
|
+
return result;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
//#endregion
|
|
888
|
+
//#region src/services/checkin/service.ts
|
|
889
|
+
var CheckinService = class {
|
|
890
|
+
async checkin(options) {
|
|
891
|
+
const log = options.onLog ?? (() => void 0);
|
|
892
|
+
const plugin = await loadFormatPlugin(options.format);
|
|
893
|
+
if (!plugin.instance.format.export) throw new Error(`Format plugin '${plugin.name}' does not implement format.export — cannot deserialise local files. Required for checkin.`);
|
|
894
|
+
log("info", `Loaded format plugin: ${plugin.name}`);
|
|
895
|
+
const adkContext = options.adkContext ?? getGlobalContext();
|
|
896
|
+
const client = adkContext.client;
|
|
897
|
+
const fileTree = createFsFileTree(options.sourceDir);
|
|
898
|
+
const filterTypes = options.objectTypes?.map((t) => t.toUpperCase());
|
|
899
|
+
const discovered = [];
|
|
900
|
+
for await (const obj of plugin.instance.format.export(fileTree, client, {
|
|
901
|
+
rootPackage: options.rootPackage,
|
|
902
|
+
abapLanguageVersion: options.abapLanguageVersion,
|
|
903
|
+
formatOptions: options.formatOptions
|
|
904
|
+
})) {
|
|
905
|
+
if (filterTypes && !matchesTypeFilter(obj.type, filterTypes)) continue;
|
|
906
|
+
discovered.push(obj);
|
|
907
|
+
}
|
|
908
|
+
log("info", `Discovered ${discovered.length} objects from ${options.sourceDir}`);
|
|
909
|
+
if (options.transport && !options.dryRun) try {
|
|
910
|
+
await AdkTransport.get(options.transport);
|
|
911
|
+
} catch (err) {
|
|
912
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
913
|
+
throw new Error(`Transport validation failed for ${options.transport}: ${msg}`, { cause: err });
|
|
914
|
+
}
|
|
915
|
+
const entries = [];
|
|
916
|
+
for (const obj of discovered) entries.push(await diffObject(obj));
|
|
917
|
+
const plan = buildPlan(entries);
|
|
918
|
+
const actions = {
|
|
919
|
+
create: 0,
|
|
920
|
+
update: 0,
|
|
921
|
+
unchanged: 0,
|
|
922
|
+
skip: 0
|
|
923
|
+
};
|
|
924
|
+
for (const entry of entries) actions[entry.action]++;
|
|
925
|
+
const applyOptions = {
|
|
926
|
+
transport: options.transport,
|
|
927
|
+
dryRun: options.dryRun,
|
|
928
|
+
activate: options.activate,
|
|
929
|
+
unlock: options.unlock,
|
|
930
|
+
onTierStart: (tier, size) => log("info", `→ Applying tier ${tier} (${size} objects)`),
|
|
931
|
+
onObject: options.onObject
|
|
932
|
+
};
|
|
933
|
+
const applyResult = await applyPlan(plan, adkContext, applyOptions);
|
|
934
|
+
const summary = formatSummary(discovered.length, actions, applyResult);
|
|
935
|
+
return {
|
|
936
|
+
sourceDir: options.sourceDir,
|
|
937
|
+
format: options.format,
|
|
938
|
+
discovered: discovered.length,
|
|
939
|
+
actions,
|
|
940
|
+
apply: applyResult,
|
|
941
|
+
groups: plan.groups.map((g) => ({
|
|
942
|
+
tier: g.tier,
|
|
943
|
+
entries: g.entries.map((e) => ({
|
|
944
|
+
name: e.object.name,
|
|
945
|
+
type: e.object.type,
|
|
946
|
+
action: e.action
|
|
947
|
+
}))
|
|
948
|
+
})),
|
|
949
|
+
aborted: applyResult.aborted,
|
|
950
|
+
summary
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
};
|
|
954
|
+
function matchesTypeFilter(type, filter) {
|
|
955
|
+
const upper = type.toUpperCase();
|
|
956
|
+
const main = upper.split("/")[0];
|
|
957
|
+
return filter.includes(upper) || filter.includes(main);
|
|
958
|
+
}
|
|
959
|
+
function formatSummary(discovered, actions, apply) {
|
|
960
|
+
const parts = [
|
|
961
|
+
`${discovered} discovered`,
|
|
962
|
+
`${actions.create ?? 0} new`,
|
|
963
|
+
`${actions.update ?? 0} modified`,
|
|
964
|
+
`${actions.unchanged ?? 0} unchanged`,
|
|
965
|
+
`${apply.totals.saved} saved`,
|
|
966
|
+
`${apply.totals.activated} activated`
|
|
967
|
+
];
|
|
968
|
+
if (apply.totals.failed > 0) parts.push(`${apply.totals.failed} failed`);
|
|
969
|
+
if (apply.aborted) parts.push("aborted (partial-apply)");
|
|
970
|
+
return parts.join(", ");
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
//#endregion
|
|
974
|
+
//#region src/services/connection/service.ts
|
|
975
|
+
async function resolveConnectionClient(args, hooks) {
|
|
976
|
+
if (args.baseUrl) return {
|
|
977
|
+
client: hooks.createClient({
|
|
978
|
+
baseUrl: args.baseUrl,
|
|
979
|
+
client: args.client,
|
|
980
|
+
username: args.username,
|
|
981
|
+
password: args.password
|
|
982
|
+
}),
|
|
983
|
+
systemId: args.systemId,
|
|
984
|
+
source: "explicit"
|
|
985
|
+
};
|
|
986
|
+
if (args.systemId && hooks.resolveSystem) {
|
|
987
|
+
const params = hooks.resolveSystem(args.systemId);
|
|
988
|
+
if (params) return {
|
|
989
|
+
client: hooks.createClient({
|
|
990
|
+
...params,
|
|
991
|
+
username: args.username,
|
|
992
|
+
password: args.password
|
|
993
|
+
}),
|
|
994
|
+
systemId: args.systemId,
|
|
995
|
+
source: "multi-system"
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
if (args.systemId && hooks.resolveFromAuthStore) return {
|
|
999
|
+
client: await hooks.resolveFromAuthStore(args.systemId),
|
|
1000
|
+
systemId: args.systemId,
|
|
1001
|
+
source: "adt-cli-auth-store"
|
|
1002
|
+
};
|
|
1003
|
+
throw new Error("No connection could be resolved: provide baseUrl (+ credentials) or systemId resolvable via multi-system config or ~/.adt session store.");
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
//#endregion
|
|
1007
|
+
//#region src/services/cts/transport-lifecycle.ts
|
|
1008
|
+
function normalizeTransportIdentifier(transport, errorMessage = "Transport identifier is required") {
|
|
1009
|
+
const normalized = transport.trim().toUpperCase();
|
|
1010
|
+
if (!normalized) throw new Error(errorMessage);
|
|
1011
|
+
return normalized;
|
|
1012
|
+
}
|
|
1013
|
+
const DEFAULT_OPERATIONS$1 = { getTransport: (transport, client) => AdkTransportRequest.get(transport, { client }) };
|
|
1014
|
+
var CtsTransportLifecycleService = class {
|
|
1015
|
+
client;
|
|
1016
|
+
operations;
|
|
1017
|
+
constructor(client, operations = DEFAULT_OPERATIONS$1) {
|
|
1018
|
+
this.client = client;
|
|
1019
|
+
this.operations = operations;
|
|
1020
|
+
}
|
|
1021
|
+
async getTransport(transport) {
|
|
1022
|
+
const normalizedTransport = normalizeTransportIdentifier(transport);
|
|
1023
|
+
const model = await this.operations.getTransport(normalizedTransport, this.client);
|
|
1024
|
+
return {
|
|
1025
|
+
transport: model.number,
|
|
1026
|
+
status: model.status,
|
|
1027
|
+
statusText: model.statusText,
|
|
1028
|
+
owner: model.owner,
|
|
1029
|
+
description: model.description,
|
|
1030
|
+
target: model.target,
|
|
1031
|
+
targetDescription: model.targetDescription,
|
|
1032
|
+
taskCount: model.tasks.length,
|
|
1033
|
+
objectCount: model.objects.length
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
async release(input) {
|
|
1037
|
+
const transport = normalizeTransportIdentifier(input.transport);
|
|
1038
|
+
const releaseAll = input.releaseAll ?? false;
|
|
1039
|
+
const model = await this.operations.getTransport(transport, this.client);
|
|
1040
|
+
if (model.status === "R") return {
|
|
1041
|
+
status: "already_released",
|
|
1042
|
+
transport: model.number,
|
|
1043
|
+
releaseAll,
|
|
1044
|
+
result: { success: true }
|
|
1045
|
+
};
|
|
1046
|
+
const result = releaseAll ? await model.releaseAll() : await model.release();
|
|
1047
|
+
if (!result.success) throw new Error(result.message || `Release of transport ${model.number} failed`);
|
|
1048
|
+
return {
|
|
1049
|
+
status: "released",
|
|
1050
|
+
transport: model.number,
|
|
1051
|
+
releaseAll,
|
|
1052
|
+
result
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
async createTask(input) {
|
|
1056
|
+
const transport = normalizeTransportIdentifier(input.transport, "Transport and task owner are required");
|
|
1057
|
+
const owner = input.owner.trim().toUpperCase();
|
|
1058
|
+
if (!owner) throw new Error("Transport and task owner are required");
|
|
1059
|
+
const model = await this.operations.getTransport(transport, this.client);
|
|
1060
|
+
const task = await model.addTask(owner);
|
|
1061
|
+
if (!(await this.operations.getTransport(transport, this.client)).tasks.some((t) => t.number === task.number && t.owner === task.owner)) throw new Error(`no new task owned by ${owner}`);
|
|
1062
|
+
return {
|
|
1063
|
+
status: "created",
|
|
1064
|
+
transport: model.number,
|
|
1065
|
+
task: task.number,
|
|
1066
|
+
owner: task.owner
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
async reassign(input) {
|
|
1070
|
+
const transport = normalizeTransportIdentifier(input.transport, "Transport and new owner are required");
|
|
1071
|
+
const newOwner = input.newOwner.trim().toUpperCase();
|
|
1072
|
+
if (!newOwner) throw new Error("Transport and new owner are required");
|
|
1073
|
+
const model = await this.operations.getTransport(transport, this.client);
|
|
1074
|
+
if (model.status === "R") throw new Error(`Transport ${model.number} is already released`);
|
|
1075
|
+
const recursive = input.recursive ?? false;
|
|
1076
|
+
const previousOwner = model.owner;
|
|
1077
|
+
await model.reassign(newOwner, recursive);
|
|
1078
|
+
return {
|
|
1079
|
+
status: "reassigned",
|
|
1080
|
+
transport: model.number,
|
|
1081
|
+
previousOwner,
|
|
1082
|
+
newOwner: model.owner,
|
|
1083
|
+
recursive
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
};
|
|
1087
|
+
|
|
1088
|
+
//#endregion
|
|
1089
|
+
//#region src/services/cts/transport-metadata.ts
|
|
1090
|
+
/**
|
|
1091
|
+
* Typed CTS metadata projection shared by CLI and MCP. The ADT client owns
|
|
1092
|
+
* protocol decoding; this service deliberately has no XML or console logic.
|
|
1093
|
+
*/
|
|
1094
|
+
var CtsTransportMetadataService = class {
|
|
1095
|
+
client;
|
|
1096
|
+
constructor(client) {
|
|
1097
|
+
this.client = client;
|
|
1098
|
+
}
|
|
1099
|
+
async get(transport) {
|
|
1100
|
+
const requestedTransport = transport.trim().toUpperCase();
|
|
1101
|
+
if (!requestedTransport) throw new Error("Transport identifier is required");
|
|
1102
|
+
const request = await this.client.services.transports.get(requestedTransport);
|
|
1103
|
+
return {
|
|
1104
|
+
requestedTransport,
|
|
1105
|
+
units: [{
|
|
1106
|
+
kind: request.parent ? "task" : "request",
|
|
1107
|
+
number: request.number,
|
|
1108
|
+
description: request.desc,
|
|
1109
|
+
owner: request.owner,
|
|
1110
|
+
status: request.status,
|
|
1111
|
+
type: request.type,
|
|
1112
|
+
parent: request.parent,
|
|
1113
|
+
lastChangedTimestamp: request.lastChangedTimestamp
|
|
1114
|
+
}, ...(request.tasks ?? []).map((task) => ({
|
|
1115
|
+
kind: "task",
|
|
1116
|
+
number: task.number,
|
|
1117
|
+
description: task.desc,
|
|
1118
|
+
owner: task.owner,
|
|
1119
|
+
status: task.status,
|
|
1120
|
+
type: task.type,
|
|
1121
|
+
parent: task.parent || request.number,
|
|
1122
|
+
lastChangedTimestamp: task.lastChangedTimestamp
|
|
1123
|
+
}))]
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
|
|
1128
|
+
//#endregion
|
|
1129
|
+
//#region src/shared/adt-client.ts
|
|
1130
|
+
let globalCliContext = {};
|
|
1131
|
+
/**
|
|
1132
|
+
* Set global CLI context (called by CLI preAction hook)
|
|
1133
|
+
* This allows getAdtClientV2() to auto-read CLI options without passing them explicitly
|
|
1134
|
+
*/
|
|
1135
|
+
function setCliContext(context) {
|
|
1136
|
+
globalCliContext = {
|
|
1137
|
+
...globalCliContext,
|
|
1138
|
+
...context
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Get current CLI context
|
|
1143
|
+
*/
|
|
1144
|
+
function getCliContext() {
|
|
1145
|
+
return globalCliContext;
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Reset CLI context (useful for testing)
|
|
1149
|
+
*/
|
|
1150
|
+
function resetCliContext() {
|
|
1151
|
+
globalCliContext = {};
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* Silent logger - suppresses all output (default for CLI)
|
|
1155
|
+
*/
|
|
1156
|
+
const noop = () => {};
|
|
1157
|
+
const silentLogger = {
|
|
1158
|
+
trace: noop,
|
|
1159
|
+
debug: noop,
|
|
1160
|
+
info: noop,
|
|
1161
|
+
warn: noop,
|
|
1162
|
+
error: noop,
|
|
1163
|
+
fatal: noop,
|
|
1164
|
+
child: () => silentLogger
|
|
1165
|
+
};
|
|
1166
|
+
/**
|
|
1167
|
+
* Console logger - outputs to console (used when enableLogging is true)
|
|
1168
|
+
*/
|
|
1169
|
+
const consoleLogger = {
|
|
1170
|
+
trace: (msg) => console.error(msg),
|
|
1171
|
+
debug: (msg) => console.error(msg),
|
|
1172
|
+
info: (msg) => console.error(msg),
|
|
1173
|
+
warn: (msg) => console.error(msg),
|
|
1174
|
+
error: (msg) => console.error(msg),
|
|
1175
|
+
fatal: (msg) => console.error(msg),
|
|
1176
|
+
child: () => consoleLogger
|
|
1177
|
+
};
|
|
1178
|
+
let lastCaptured = {};
|
|
1179
|
+
/**
|
|
1180
|
+
* Get the last captured response (for commands that need raw XML/JSON)
|
|
1181
|
+
*/
|
|
1182
|
+
function getCaptured() {
|
|
1183
|
+
return lastCaptured;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Set captured response data
|
|
1187
|
+
*/
|
|
1188
|
+
function setCaptured(data) {
|
|
1189
|
+
lastCaptured = data;
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Reset captured data (called before each request when capture is enabled)
|
|
1193
|
+
*/
|
|
1194
|
+
function resetCaptured() {
|
|
1195
|
+
lastCaptured = {};
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
//#endregion
|
|
1199
|
+
//#region src/utils/destinations.ts
|
|
1200
|
+
/**
|
|
1201
|
+
* Destination utilities
|
|
1202
|
+
*
|
|
1203
|
+
* Loads destinations from adt.config.ts/json using @abapify/adt-config
|
|
1204
|
+
*/
|
|
1205
|
+
let cachedConfig = null;
|
|
1206
|
+
let cachedConfigPath = void 0;
|
|
1207
|
+
/**
|
|
1208
|
+
* Get loaded config (cached)
|
|
1209
|
+
* Uses configPath from CLI context if available (from --config flag)
|
|
1210
|
+
*/
|
|
1211
|
+
async function getConfig() {
|
|
1212
|
+
const configPath = getCliContext().configPath;
|
|
1213
|
+
if (cachedConfig && cachedConfigPath !== configPath) cachedConfig = null;
|
|
1214
|
+
if (!cachedConfig) {
|
|
1215
|
+
cachedConfig = await loadConfig({ configPath });
|
|
1216
|
+
cachedConfigPath = configPath;
|
|
1217
|
+
}
|
|
1218
|
+
return cachedConfig;
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Get a destination by name (SID)
|
|
1222
|
+
* @param name Destination name (e.g., 'TRL')
|
|
1223
|
+
*/
|
|
1224
|
+
async function getDestination(name) {
|
|
1225
|
+
return (await getConfig()).getDestination(name);
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* List all configured destinations
|
|
1229
|
+
*/
|
|
1230
|
+
async function listDestinations() {
|
|
1231
|
+
return (await getConfig()).listDestinations();
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* Check if a destination exists
|
|
1235
|
+
*/
|
|
1236
|
+
async function hasDestination(name) {
|
|
1237
|
+
return (await getConfig()).hasDestination(name);
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Clear cached config (useful for testing)
|
|
1241
|
+
*/
|
|
1242
|
+
function clearConfigCache() {
|
|
1243
|
+
cachedConfig = null;
|
|
1244
|
+
cachedConfigPath = void 0;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
//#endregion
|
|
1248
|
+
//#region src/utils/transport-numbers.ts
|
|
1249
|
+
/**
|
|
1250
|
+
* Parse a comma-separated string of SAP transport numbers into a deduplicated
|
|
1251
|
+
* uppercase array.
|
|
1252
|
+
*
|
|
1253
|
+
* Trims whitespace, uppercases, filters empty tokens, and removes duplicates
|
|
1254
|
+
* while preserving insertion order (O(n) via Set).
|
|
1255
|
+
*
|
|
1256
|
+
* Throws when no valid transport numbers are found.
|
|
1257
|
+
*
|
|
1258
|
+
* @example
|
|
1259
|
+
* parseTransportNumbers('DEVK900001') // → ['DEVK900001']
|
|
1260
|
+
* parseTransportNumbers('DEVK900001, DEVK900002') // → ['DEVK900001', 'DEVK900002']
|
|
1261
|
+
* parseTransportNumbers('DEVK900001,DEVK900001') // → ['DEVK900001'] (deduped)
|
|
1262
|
+
*/
|
|
1263
|
+
function parseTransportNumbers(value) {
|
|
1264
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1265
|
+
const numbers = value.split(",").map((n) => n.trim().toUpperCase()).filter(Boolean).filter((n) => {
|
|
1266
|
+
if (seen.has(n)) return false;
|
|
1267
|
+
seen.add(n);
|
|
1268
|
+
return true;
|
|
1269
|
+
});
|
|
1270
|
+
if (numbers.length === 0) throw new Error(`No transport number(s) provided in '${value}'`);
|
|
1271
|
+
return numbers;
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
//#endregion
|
|
1275
|
+
//#region src/services/import/object-selection.ts
|
|
1276
|
+
function normalizeObjectType(type) {
|
|
1277
|
+
return type.toUpperCase().split("/")[0] ?? "";
|
|
1278
|
+
}
|
|
1279
|
+
function getExactSearchMatches(objects, objectName) {
|
|
1280
|
+
const normalizedName = objectName.toUpperCase();
|
|
1281
|
+
return objects.filter((obj) => String(obj.name || "").toUpperCase() === normalizedName);
|
|
1282
|
+
}
|
|
1283
|
+
function getSearchObjectTypes(objects) {
|
|
1284
|
+
return [...new Set(objects.map((obj) => normalizeObjectType(String(obj.type || ""))))].filter(Boolean);
|
|
1285
|
+
}
|
|
1286
|
+
function findExactSearchMatch(exactMatches, requestedObjectType, availableExactTypes) {
|
|
1287
|
+
if (requestedObjectType) return exactMatches.find((obj) => normalizeObjectType(String(obj.type || "")) === requestedObjectType);
|
|
1288
|
+
return availableExactTypes.length <= 1 ? exactMatches[0] : void 0;
|
|
1289
|
+
}
|
|
1290
|
+
function createObjectNotFoundError(objects, objectName) {
|
|
1291
|
+
const similar = objects.filter((obj) => String(obj.name || "").toUpperCase().includes(objectName.toUpperCase())).slice(0, 5);
|
|
1292
|
+
const similarList = similar.map((obj) => ` • ${obj.name} (${obj.type}) – ${obj.packageName}`).join("\n");
|
|
1293
|
+
const hint = similar.length > 0 ? `\n💡 Similar objects:\n${similarList}` : "";
|
|
1294
|
+
return /* @__PURE__ */ new Error(`Object '${objectName}' not found in the system.${hint}`);
|
|
1295
|
+
}
|
|
1296
|
+
function createSearchObjectResolutionError(context) {
|
|
1297
|
+
const { objects, options, exactMatches, availableExactTypes, requestedObjectType } = context;
|
|
1298
|
+
if (requestedObjectType && exactMatches.length > 0) return /* @__PURE__ */ new Error(`Object '${options.objectName}' with type '${requestedObjectType}' was not found. Available types: ${availableExactTypes.join(", ") || "none"}.`);
|
|
1299
|
+
if (!requestedObjectType && availableExactTypes.length > 1) return /* @__PURE__ */ new Error(`Object '${options.objectName}' is ambiguous. Use --object-type to select one of: ${availableExactTypes.join(", ")}.`);
|
|
1300
|
+
return createObjectNotFoundError(objects, options.objectName);
|
|
1301
|
+
}
|
|
1302
|
+
function selectSearchObject(objects, options) {
|
|
1303
|
+
const exactMatches = getExactSearchMatches(objects, options.objectName);
|
|
1304
|
+
const availableExactTypes = getSearchObjectTypes(exactMatches);
|
|
1305
|
+
const requestedObjectType = options.objectType ? normalizeObjectType(options.objectType.trim()) : void 0;
|
|
1306
|
+
const exactMatch = findExactSearchMatch(exactMatches, requestedObjectType, availableExactTypes);
|
|
1307
|
+
if (exactMatch) return exactMatch;
|
|
1308
|
+
throw createSearchObjectResolutionError({
|
|
1309
|
+
objects,
|
|
1310
|
+
options,
|
|
1311
|
+
exactMatches,
|
|
1312
|
+
availableExactTypes,
|
|
1313
|
+
requestedObjectType
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
//#endregion
|
|
1318
|
+
//#region src/services/import/service.ts
|
|
1319
|
+
/** Default number of concurrent SAP requests during import */
|
|
1320
|
+
const IMPORT_CONCURRENCY = 5;
|
|
1321
|
+
/**
|
|
1322
|
+
* Resolve full package path from root to the given package.
|
|
1323
|
+
* Traverses the ADK package hierarchy upward until the root is reached.
|
|
1324
|
+
*/
|
|
1325
|
+
async function resolvePackagePath(packageName) {
|
|
1326
|
+
const path = [];
|
|
1327
|
+
let currentPackage = packageName;
|
|
1328
|
+
while (currentPackage) {
|
|
1329
|
+
path.unshift(currentPackage);
|
|
1330
|
+
try {
|
|
1331
|
+
const superPkg = (await AdkPackage.get(currentPackage)).superPackage;
|
|
1332
|
+
if (superPkg?.name) currentPackage = superPkg.name;
|
|
1333
|
+
else break;
|
|
1334
|
+
} catch {
|
|
1335
|
+
break;
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
return path;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Import Service - uses ADK architecture
|
|
1342
|
+
*
|
|
1343
|
+
* Flow:
|
|
1344
|
+
* 1. Load format plugin (via CLI option or config)
|
|
1345
|
+
* 2. Fetch transport via AdkTransport.get() or package via AdkPackage.get()
|
|
1346
|
+
* 3. Load each object via objRef.load()
|
|
1347
|
+
* 4. Delegate serialization to format plugin
|
|
1348
|
+
*/
|
|
1349
|
+
var ImportService = class {
|
|
1350
|
+
async getConfigFormatOptions(formatSpec) {
|
|
1351
|
+
const importConfig = (await getConfig()).raw.import;
|
|
1352
|
+
if (!importConfig || typeof importConfig !== "object" || Array.isArray(importConfig)) return {};
|
|
1353
|
+
const formatOptionsMap = importConfig.formatOptions;
|
|
1354
|
+
if (!formatOptionsMap || typeof formatOptionsMap !== "object" || Array.isArray(formatOptionsMap)) return {};
|
|
1355
|
+
const { package: packageName } = parseFormatSpec(formatSpec);
|
|
1356
|
+
const aliases = [
|
|
1357
|
+
formatSpec,
|
|
1358
|
+
packageName,
|
|
1359
|
+
packageName.replace("@abapify/adt-plugin-", ""),
|
|
1360
|
+
packageName.replace("@abapify/", "")
|
|
1361
|
+
];
|
|
1362
|
+
for (const alias of aliases) {
|
|
1363
|
+
const value = formatOptionsMap[alias];
|
|
1364
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value;
|
|
1365
|
+
}
|
|
1366
|
+
return {};
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Import objects from a transport request
|
|
1370
|
+
*
|
|
1371
|
+
* @param options - Import options including transport number, output path, and format
|
|
1372
|
+
* @returns Import result with statistics
|
|
1373
|
+
*/
|
|
1374
|
+
async importTransport(options) {
|
|
1375
|
+
if (options.debug) {
|
|
1376
|
+
console.log(`🔍 Importing transport: ${options.transportNumber}`);
|
|
1377
|
+
console.log(`📁 Output path: ${options.outputPath}`);
|
|
1378
|
+
console.log(`🎯 Format: ${options.format}`);
|
|
1379
|
+
}
|
|
1380
|
+
const plugin = await loadFormatPlugin(options.format);
|
|
1381
|
+
const configFormatOptions = await this.getConfigFormatOptions(options.format);
|
|
1382
|
+
if (options.debug) console.log(`✅ Loaded plugin: ${plugin.name}`);
|
|
1383
|
+
const allTransportNumbers = parseTransportNumbers(options.transportNumber);
|
|
1384
|
+
if (options.debug) console.log(`🚛 Fetching transport(s): ${allTransportNumbers.join(", ")}`);
|
|
1385
|
+
let allObjects;
|
|
1386
|
+
let transportDescription;
|
|
1387
|
+
const loadedTransports = [];
|
|
1388
|
+
if (allTransportNumbers.length === 1) {
|
|
1389
|
+
const transport = await AdkTransport.get(allTransportNumbers[0]);
|
|
1390
|
+
loadedTransports.push(transport);
|
|
1391
|
+
allObjects = transport.objects;
|
|
1392
|
+
transportDescription = transport.description;
|
|
1393
|
+
} else {
|
|
1394
|
+
const transports = await Promise.all(allTransportNumbers.map((n) => AdkTransport.get(n)));
|
|
1395
|
+
loadedTransports.push(...transports);
|
|
1396
|
+
allObjects = new MergedTransportView(transports).objects;
|
|
1397
|
+
transportDescription = transports.find((tr) => tr.description?.trim())?.description ?? `${allTransportNumbers[0]} (+${allTransportNumbers.length - 1} more)`;
|
|
1398
|
+
}
|
|
1399
|
+
const applyDeletions = options.applyDeletions !== false;
|
|
1400
|
+
let deletionObjects = [];
|
|
1401
|
+
let activeObjects = allObjects;
|
|
1402
|
+
if (applyDeletions) {
|
|
1403
|
+
deletionObjects = [];
|
|
1404
|
+
activeObjects = [];
|
|
1405
|
+
for (const object of allObjects) if (matchesSelector(object, {
|
|
1406
|
+
objFunc: "D",
|
|
1407
|
+
pgmid: "R3TR"
|
|
1408
|
+
})) deletionObjects.push(object);
|
|
1409
|
+
else activeObjects.push(object);
|
|
1410
|
+
}
|
|
1411
|
+
let objectsToImport = activeObjects;
|
|
1412
|
+
if (options.objectTypes && options.objectTypes.length > 0) {
|
|
1413
|
+
const types = options.objectTypes.map((t) => t.toUpperCase());
|
|
1414
|
+
objectsToImport = activeObjects.filter((o) => types.includes(o.type.toUpperCase()));
|
|
1415
|
+
if (options.debug) console.log(`🔍 Filtered to ${objectsToImport.length} active objects by type: ${types.join(", ")}`);
|
|
1416
|
+
}
|
|
1417
|
+
const results = {
|
|
1418
|
+
success: 0,
|
|
1419
|
+
skipped: 0,
|
|
1420
|
+
failed: 0,
|
|
1421
|
+
deleted: 0
|
|
1422
|
+
};
|
|
1423
|
+
const objectsByType = {};
|
|
1424
|
+
const filesRemoved = [];
|
|
1425
|
+
const total = objectsToImport.length;
|
|
1426
|
+
let processed = 0;
|
|
1427
|
+
const importContext = {
|
|
1428
|
+
resolvePackagePath,
|
|
1429
|
+
formatOptions: options.formatOptions,
|
|
1430
|
+
configFormatOptions
|
|
1431
|
+
};
|
|
1432
|
+
console.log(`📦 Processing ${total} active objects...`);
|
|
1433
|
+
await Readable.from(objectsToImport).forEach(async (objRef) => {
|
|
1434
|
+
const progress = ++processed;
|
|
1435
|
+
try {
|
|
1436
|
+
if (!plugin.instance.registry.isSupported(objRef.type)) {
|
|
1437
|
+
results.skipped++;
|
|
1438
|
+
if (options.debug) console.log(` ⏭️ [${progress}/${total}] ${objRef.type} ${objRef.name}: type not supported`);
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
console.log(` 🔄 [${progress}/${total}] ${objRef.type} ${objRef.name}`);
|
|
1442
|
+
const adkObject = await objRef.load();
|
|
1443
|
+
if (!adkObject) {
|
|
1444
|
+
const deleteFn = plugin.instance.format.delete;
|
|
1445
|
+
if (options.removeMissingObjects && typeof deleteFn === "function") {
|
|
1446
|
+
console.log(` 🗑️ [${progress}/${total}] ${objRef.type} ${objRef.name}: not found in SAP → removing local files`);
|
|
1447
|
+
try {
|
|
1448
|
+
const delResult = await deleteFn({
|
|
1449
|
+
pgmid: objRef.pgmid,
|
|
1450
|
+
type: objRef.type,
|
|
1451
|
+
name: objRef.name
|
|
1452
|
+
}, options.outputPath, importContext);
|
|
1453
|
+
if (delResult.success) {
|
|
1454
|
+
results.deleted++;
|
|
1455
|
+
filesRemoved.push(...delResult.filesRemoved);
|
|
1456
|
+
} else results.skipped++;
|
|
1457
|
+
} catch (error) {
|
|
1458
|
+
results.skipped++;
|
|
1459
|
+
if (options.debug) console.log(` ⚠️ ${objRef.type} ${objRef.name}: delete failed — ${error instanceof Error ? error.message : String(error)}`);
|
|
1460
|
+
}
|
|
1461
|
+
} else {
|
|
1462
|
+
results.skipped++;
|
|
1463
|
+
if (options.debug) console.log(` ⏭️ ${objRef.type} ${objRef.name}: not found in SAP (skipped)`);
|
|
1464
|
+
}
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const result = await plugin.instance.format.import(adkObject, options.outputPath, importContext);
|
|
1468
|
+
if (result.success) {
|
|
1469
|
+
objectsByType[objRef.type] = (objectsByType[objRef.type] || 0) + 1;
|
|
1470
|
+
results.success++;
|
|
1471
|
+
} else {
|
|
1472
|
+
results.failed++;
|
|
1473
|
+
console.log(` ❌ ${objRef.type} ${objRef.name}: ${result.errors?.join(", ") || "unknown error"}`);
|
|
1474
|
+
}
|
|
1475
|
+
} catch (error) {
|
|
1476
|
+
results.failed++;
|
|
1477
|
+
console.log(` ❌ ${objRef.type} ${objRef.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1478
|
+
}
|
|
1479
|
+
}, { concurrency: IMPORT_CONCURRENCY });
|
|
1480
|
+
if (applyDeletions && deletionObjects.length > 0) {
|
|
1481
|
+
console.log(`🗑️ Processing ${deletionObjects.length} deletion(s)...`);
|
|
1482
|
+
const deleteSupported = typeof plugin.instance.format.delete === "function";
|
|
1483
|
+
if (!deleteSupported && options.debug) console.log(` ⚠️ Plugin '${plugin.name}' does not implement format.delete() — skipping deletion pass`);
|
|
1484
|
+
if (deleteSupported) {
|
|
1485
|
+
let delProcessed = 0;
|
|
1486
|
+
const delTotal = deletionObjects.length;
|
|
1487
|
+
await Readable.from(deletionObjects).forEach(async (objRef) => {
|
|
1488
|
+
const progress = ++delProcessed;
|
|
1489
|
+
try {
|
|
1490
|
+
console.log(` 🗑️ [${progress}/${delTotal}] ${objRef.type} ${objRef.name}`);
|
|
1491
|
+
const delResult = await plugin.instance.format.delete({
|
|
1492
|
+
pgmid: objRef.pgmid,
|
|
1493
|
+
type: objRef.type,
|
|
1494
|
+
name: objRef.name
|
|
1495
|
+
}, options.outputPath, importContext);
|
|
1496
|
+
if (delResult.success) {
|
|
1497
|
+
results.deleted++;
|
|
1498
|
+
filesRemoved.push(...delResult.filesRemoved);
|
|
1499
|
+
} else {
|
|
1500
|
+
results.failed++;
|
|
1501
|
+
console.log(` ❌ Delete ${objRef.type} ${objRef.name}: ${delResult.errors?.join(", ") || "unknown error"}`);
|
|
1502
|
+
}
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
results.failed++;
|
|
1505
|
+
console.log(` ❌ Delete ${objRef.type} ${objRef.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1506
|
+
}
|
|
1507
|
+
}, { concurrency: IMPORT_CONCURRENCY });
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
if (plugin.instance.hooks?.afterImport) await plugin.instance.hooks.afterImport(options.outputPath);
|
|
1511
|
+
const metadataFiles = [];
|
|
1512
|
+
if (options.saveTrMetadata) {
|
|
1513
|
+
const metadataDir = join(options.outputPath, ".adt", "tr");
|
|
1514
|
+
await mkdir(metadataDir, { recursive: true });
|
|
1515
|
+
for (const tr of loadedTransports) {
|
|
1516
|
+
const metadata = {
|
|
1517
|
+
number: tr.number,
|
|
1518
|
+
owner: tr.owner,
|
|
1519
|
+
desc: tr.description,
|
|
1520
|
+
status: tr.status,
|
|
1521
|
+
statusText: tr.statusText,
|
|
1522
|
+
target: tr.target,
|
|
1523
|
+
tasks: tr.tasks.map((task) => ({
|
|
1524
|
+
number: task.number,
|
|
1525
|
+
owner: task.owner,
|
|
1526
|
+
desc: task.description,
|
|
1527
|
+
status: task.status,
|
|
1528
|
+
objects: task.objects.map((obj) => ({
|
|
1529
|
+
pgmid: obj.pgmid,
|
|
1530
|
+
type: obj.type,
|
|
1531
|
+
name: obj.name,
|
|
1532
|
+
obj_func: obj.objFunc,
|
|
1533
|
+
uri: obj.uri
|
|
1534
|
+
}))
|
|
1535
|
+
})),
|
|
1536
|
+
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1537
|
+
import: {
|
|
1538
|
+
format: options.format,
|
|
1539
|
+
success: results.success,
|
|
1540
|
+
skipped: results.skipped,
|
|
1541
|
+
failed: results.failed,
|
|
1542
|
+
deleted: results.deleted
|
|
1543
|
+
}
|
|
1544
|
+
};
|
|
1545
|
+
const metadataPath = join(metadataDir, `${tr.number}.json`);
|
|
1546
|
+
await writeFile(metadataPath, JSON.stringify(metadata, null, 2), "utf-8");
|
|
1547
|
+
metadataFiles.push(metadataPath);
|
|
1548
|
+
if (options.debug) console.log(`📄 Wrote transport metadata: ${metadataPath}`);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
return {
|
|
1552
|
+
transportNumber: allTransportNumbers[0],
|
|
1553
|
+
description: transportDescription,
|
|
1554
|
+
totalObjects: allObjects.length,
|
|
1555
|
+
results,
|
|
1556
|
+
objectsByType,
|
|
1557
|
+
outputPath: options.outputPath,
|
|
1558
|
+
filesRemoved: filesRemoved.length > 0 ? filesRemoved : void 0,
|
|
1559
|
+
metadataFiles: metadataFiles.length > 0 ? metadataFiles : void 0
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* Import objects from an ABAP package
|
|
1564
|
+
*
|
|
1565
|
+
* @param options - Import options including package name, output path, and format
|
|
1566
|
+
* @returns Import result with statistics
|
|
1567
|
+
*/
|
|
1568
|
+
async importPackage(options) {
|
|
1569
|
+
if (options.debug) {
|
|
1570
|
+
console.log(`🔍 Importing package: ${options.packageName}`);
|
|
1571
|
+
console.log(`📁 Output path: ${options.outputPath}`);
|
|
1572
|
+
console.log(`🎯 Format: ${options.format}`);
|
|
1573
|
+
console.log(`📦 Include subpackages: ${options.includeSubpackages ?? false}`);
|
|
1574
|
+
}
|
|
1575
|
+
const plugin = await loadFormatPlugin(options.format);
|
|
1576
|
+
const configFormatOptions = await this.getConfigFormatOptions(options.format);
|
|
1577
|
+
if (options.debug) console.log(`✅ Loaded plugin: ${plugin.name}`);
|
|
1578
|
+
console.log(`🔍 Fetching package: ${options.packageName}`);
|
|
1579
|
+
const pkg = await AdkPackage.get(options.packageName);
|
|
1580
|
+
let allObjects;
|
|
1581
|
+
if (options.includeSubpackages) {
|
|
1582
|
+
console.log(`📦 Scanning subpackages…`);
|
|
1583
|
+
allObjects = await pkg.getAllObjects();
|
|
1584
|
+
} else allObjects = await pkg.getObjects();
|
|
1585
|
+
console.log(`📋 Found ${allObjects.length} objects`);
|
|
1586
|
+
let objectsToImport = allObjects;
|
|
1587
|
+
if (options.objectTypes && options.objectTypes.length > 0) {
|
|
1588
|
+
const types = options.objectTypes.map((t) => t.toUpperCase());
|
|
1589
|
+
objectsToImport = allObjects.filter((obj) => types.includes(obj.type) || types.includes(obj.type.split("/")[0]));
|
|
1590
|
+
if (options.debug) console.log(`🔍 Filtered to ${objectsToImport.length} objects by type: ${types.join(", ")}`);
|
|
1591
|
+
}
|
|
1592
|
+
const results = {
|
|
1593
|
+
success: 0,
|
|
1594
|
+
skipped: 0,
|
|
1595
|
+
failed: 0,
|
|
1596
|
+
deleted: 0
|
|
1597
|
+
};
|
|
1598
|
+
const objectsByType = {};
|
|
1599
|
+
const total = objectsToImport.length;
|
|
1600
|
+
let processed = 0;
|
|
1601
|
+
const ctx = getGlobalContext();
|
|
1602
|
+
const factory = createAdkFactory(ctx);
|
|
1603
|
+
await Readable.from(objectsToImport).forEach(async (obj) => {
|
|
1604
|
+
const progress = ++processed;
|
|
1605
|
+
try {
|
|
1606
|
+
if (!plugin.instance.registry.isSupported(obj.type)) {
|
|
1607
|
+
results.skipped++;
|
|
1608
|
+
if (options.debug) console.log(` ⏭️ [${progress}/${total}] ${obj.type} ${obj.name}: type not supported`);
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
console.log(` 🔄 [${progress}/${total}] ${obj.type} ${obj.name}`);
|
|
1612
|
+
const adkObject = factory.get(obj.name, obj.type);
|
|
1613
|
+
await adkObject.load();
|
|
1614
|
+
if (!adkObject) {
|
|
1615
|
+
results.skipped++;
|
|
1616
|
+
if (options.debug) console.log(` ⏭️ ${obj.type} ${obj.name}: failed to load`);
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
const context = {
|
|
1620
|
+
resolvePackagePath,
|
|
1621
|
+
configFormatOptions
|
|
1622
|
+
};
|
|
1623
|
+
const result = await plugin.instance.format.import(adkObject, options.outputPath, context);
|
|
1624
|
+
if (result.success) {
|
|
1625
|
+
objectsByType[obj.type] = (objectsByType[obj.type] || 0) + 1;
|
|
1626
|
+
results.success++;
|
|
1627
|
+
} else {
|
|
1628
|
+
results.failed++;
|
|
1629
|
+
console.log(` ❌ ${obj.type} ${obj.name}: ${result.errors?.join(", ") || "unknown error"}`);
|
|
1630
|
+
}
|
|
1631
|
+
} catch (error) {
|
|
1632
|
+
results.failed++;
|
|
1633
|
+
console.log(` ❌ ${obj.type} ${obj.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1634
|
+
}
|
|
1635
|
+
}, { concurrency: IMPORT_CONCURRENCY });
|
|
1636
|
+
if (plugin.instance.hooks?.afterImport) await plugin.instance.hooks.afterImport(options.outputPath);
|
|
1637
|
+
return {
|
|
1638
|
+
packageName: options.packageName,
|
|
1639
|
+
description: pkg.description || `Package ${options.packageName}`,
|
|
1640
|
+
totalObjects: objectsToImport.length,
|
|
1641
|
+
results,
|
|
1642
|
+
objectsByType,
|
|
1643
|
+
outputPath: options.outputPath
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Import a single object by name (search-based resolution)
|
|
1648
|
+
*
|
|
1649
|
+
* Flow:
|
|
1650
|
+
* 1. quickSearch for the object name
|
|
1651
|
+
* 2. Find exact match — if ambiguous, report all matches
|
|
1652
|
+
* 3. Extract ADT type from search result
|
|
1653
|
+
* 4. Load via ADK factory + format plugin → local file
|
|
1654
|
+
*
|
|
1655
|
+
* @param options - Import options including object name, output path, and format
|
|
1656
|
+
* @returns Import result with statistics
|
|
1657
|
+
*/
|
|
1658
|
+
async importObject(options) {
|
|
1659
|
+
if (options.debug) {
|
|
1660
|
+
console.log(`🔍 Searching for object: ${options.objectName}`);
|
|
1661
|
+
console.log(`📁 Output path: ${options.outputPath}`);
|
|
1662
|
+
console.log(`🎯 Format: ${options.format}`);
|
|
1663
|
+
}
|
|
1664
|
+
const ctx = getGlobalContext();
|
|
1665
|
+
const resultsAny = await ctx.client.adt.repository.informationsystem.search.quickSearch({
|
|
1666
|
+
query: options.objectName,
|
|
1667
|
+
maxResults: 10
|
|
1668
|
+
});
|
|
1669
|
+
if (options.debug) console.log(`🔎 Raw search result keys: ${Object.keys(resultsAny).join(", ")}`);
|
|
1670
|
+
let rawObjects;
|
|
1671
|
+
if ("objectReference" in resultsAny && resultsAny.objectReference) rawObjects = resultsAny.objectReference;
|
|
1672
|
+
else if ("objectReferences" in resultsAny && resultsAny.objectReferences) rawObjects = resultsAny.objectReferences.objectReference;
|
|
1673
|
+
else if ("mainObject" in resultsAny && resultsAny.mainObject) rawObjects = resultsAny.mainObject.objectReference;
|
|
1674
|
+
const exactMatch = selectSearchObject(rawObjects ? Array.isArray(rawObjects) ? rawObjects : [rawObjects] : [], options);
|
|
1675
|
+
const fullType = String(exactMatch.type || "");
|
|
1676
|
+
const slashIndex = fullType.indexOf("/");
|
|
1677
|
+
const baseType = slashIndex >= 0 ? fullType.substring(0, slashIndex) : fullType;
|
|
1678
|
+
if (options.debug) console.log(`✅ Resolved: ${exactMatch.name} (${baseType}) in package ${exactMatch.packageName}`);
|
|
1679
|
+
const plugin = await loadFormatPlugin(options.format);
|
|
1680
|
+
const configFormatOptions = await this.getConfigFormatOptions(options.format);
|
|
1681
|
+
if (!plugin.instance.registry.isSupported(baseType)) throw new Error(`Object type '${baseType}' is not supported by format plugin '${plugin.name}'.`);
|
|
1682
|
+
const adkObject = createAdkFactory(ctx).get(String(exactMatch.name), baseType);
|
|
1683
|
+
await adkObject.load();
|
|
1684
|
+
const context = {
|
|
1685
|
+
resolvePackagePath,
|
|
1686
|
+
formatOptions: options.formatOptions,
|
|
1687
|
+
configFormatOptions
|
|
1688
|
+
};
|
|
1689
|
+
const results = {
|
|
1690
|
+
success: 0,
|
|
1691
|
+
skipped: 0,
|
|
1692
|
+
failed: 0,
|
|
1693
|
+
deleted: 0
|
|
1694
|
+
};
|
|
1695
|
+
const objectsByType = {};
|
|
1696
|
+
const result = await plugin.instance.format.import(adkObject, options.outputPath, context);
|
|
1697
|
+
if (result.success) {
|
|
1698
|
+
objectsByType[baseType] = 1;
|
|
1699
|
+
results.success = 1;
|
|
1700
|
+
if (options.debug) console.log(` ✅ ${baseType} ${exactMatch.name}`);
|
|
1701
|
+
} else {
|
|
1702
|
+
results.failed = 1;
|
|
1703
|
+
if (options.debug) console.log(` ❌ ${baseType} ${exactMatch.name}: ${result.errors?.join(", ") || "unknown error"}`);
|
|
1704
|
+
}
|
|
1705
|
+
if (plugin.instance.hooks?.afterImport) await plugin.instance.hooks.afterImport(options.outputPath);
|
|
1706
|
+
return {
|
|
1707
|
+
objectName: String(exactMatch.name),
|
|
1708
|
+
objectType: baseType,
|
|
1709
|
+
description: String(exactMatch.description || "") || `${baseType} ${exactMatch.name}`,
|
|
1710
|
+
totalObjects: 1,
|
|
1711
|
+
results,
|
|
1712
|
+
objectsByType,
|
|
1713
|
+
outputPath: options.outputPath
|
|
1714
|
+
};
|
|
1715
|
+
}
|
|
1716
|
+
};
|
|
1717
|
+
|
|
1718
|
+
//#endregion
|
|
1719
|
+
//#region src/utils/lock-helpers.ts
|
|
1720
|
+
/**
|
|
1721
|
+
* Normalize a quickSearch result into a flat SearchObject[].
|
|
1722
|
+
*
|
|
1723
|
+
* The ADT quickSearch endpoint may return results under
|
|
1724
|
+
* `objectReference`, `objectReferences.objectReference`, or
|
|
1725
|
+
* `mainObject.objectReference` — this helper handles all variants.
|
|
1726
|
+
*/
|
|
1727
|
+
function normalizeSearchResults(searchResult) {
|
|
1728
|
+
let raw;
|
|
1729
|
+
if ("objectReference" in searchResult) raw = searchResult.objectReference;
|
|
1730
|
+
else if ("objectReferences" in searchResult && searchResult.objectReferences) raw = searchResult.objectReferences.objectReference;
|
|
1731
|
+
else if ("mainObject" in searchResult && searchResult.mainObject) raw = searchResult.mainObject.objectReference;
|
|
1732
|
+
return raw ? Array.isArray(raw) ? raw : [raw] : [];
|
|
1733
|
+
}
|
|
1734
|
+
/** Shared lock store instance */
|
|
1735
|
+
const lockStore = new FileLockStore();
|
|
1736
|
+
/**
|
|
1737
|
+
* Resolve an ADT object name/type/uri into a canonical URI + display label.
|
|
1738
|
+
*
|
|
1739
|
+
* Resolution order:
|
|
1740
|
+
* 1. Explicit URI override
|
|
1741
|
+
* 2. Type hint → construct from ADK registry
|
|
1742
|
+
* 3. Quick-search fallback
|
|
1743
|
+
*/
|
|
1744
|
+
async function resolveObjectUri(client, objectName, commandVerb, typeHint, uriOverride) {
|
|
1745
|
+
if (uriOverride) return {
|
|
1746
|
+
uri: uriOverride,
|
|
1747
|
+
display: `${objectName} (via --uri)`
|
|
1748
|
+
};
|
|
1749
|
+
if (typeHint) {
|
|
1750
|
+
const uri = getObjectUri(typeHint, objectName);
|
|
1751
|
+
if (uri) return {
|
|
1752
|
+
uri,
|
|
1753
|
+
display: `${objectName} (${typeHint.toUpperCase()})`
|
|
1754
|
+
};
|
|
1755
|
+
console.warn(`⚠️ Type '${typeHint}' has no registered endpoint. Falling back to search...`);
|
|
1756
|
+
}
|
|
1757
|
+
const candidates = normalizeObjectName(objectName, typeHint);
|
|
1758
|
+
const exactMatch = normalizeSearchResults(await client.adt.repository.informationsystem.search.quickSearch({
|
|
1759
|
+
query: objectName,
|
|
1760
|
+
maxResults: 10
|
|
1761
|
+
})).find((obj) => {
|
|
1762
|
+
const objName = String(obj.name || "").toUpperCase();
|
|
1763
|
+
return candidates.some((c) => c.toUpperCase() === objName);
|
|
1764
|
+
});
|
|
1765
|
+
if (!exactMatch?.uri) {
|
|
1766
|
+
const typeList = getRegisteredTypes().join(", ");
|
|
1767
|
+
throw new Error(`Object '${objectName}' not found via search.\n💡 Try specifying the type: adt ${commandVerb} ${objectName} --type TTYP\n Registered types: ${typeList}\n Or provide a direct URI: adt ${commandVerb} ${objectName} --uri /sap/bc/adt/...`);
|
|
1768
|
+
}
|
|
1769
|
+
return {
|
|
1770
|
+
uri: exactMatch.uri,
|
|
1771
|
+
display: `${exactMatch.name} (${exactMatch.type}) - ${exactMatch.description ?? ""}`
|
|
1772
|
+
};
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* Get or create the lock service.
|
|
1776
|
+
* Prefers the global ADK context's service (shares the same store),
|
|
1777
|
+
* falls back to creating a fresh one with the shared FileLockStore.
|
|
1778
|
+
*/
|
|
1779
|
+
function getLockService(client) {
|
|
1780
|
+
const globalCtx = tryGetGlobalContext();
|
|
1781
|
+
if (globalCtx?.lockService) return globalCtx.lockService;
|
|
1782
|
+
return createLockService(client, { store: lockStore });
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
//#endregion
|
|
1786
|
+
//#region src/services/source/service.ts
|
|
1787
|
+
/**
|
|
1788
|
+
* Source retrieval service shared by CLI and MCP surfaces.
|
|
1789
|
+
*
|
|
1790
|
+
* Implements arc-1 SAPRead-style parity for reading ABAP source:
|
|
1791
|
+
* - version (active/inactive)
|
|
1792
|
+
* - include (class includes / source sections)
|
|
1793
|
+
* - method (method-level read or method list)
|
|
1794
|
+
* - grep (token-efficient regex search with context, method-level context
|
|
1795
|
+
* for class/interface methods)
|
|
1796
|
+
* - maxBytes (bounded read with a hard cap)
|
|
1797
|
+
* - format (raw text or structured class includes / method boundaries)
|
|
1798
|
+
*/
|
|
1799
|
+
const DEFAULT_MAX_SOURCE_BYTES = 1048576;
|
|
1800
|
+
const HARD_MAX_SOURCE_BYTES = 2097152;
|
|
1801
|
+
const GREP_CONTEXT_LINES = 3;
|
|
1802
|
+
const MAX_GREP_PATTERN_LENGTH = 512;
|
|
1803
|
+
const VALID_CLASS_INCLUDES = /* @__PURE__ */ new Set([
|
|
1804
|
+
"main",
|
|
1805
|
+
"definitions",
|
|
1806
|
+
"implementations",
|
|
1807
|
+
"testclasses",
|
|
1808
|
+
"macros",
|
|
1809
|
+
"text_symbols",
|
|
1810
|
+
"localtypes"
|
|
1811
|
+
]);
|
|
1812
|
+
const NESTED_QUANTIFIER_GROUP = /\((?:\?:)?(?:[^()[\]\\]|\\.|\[[^\]]*\])*[*+{](?:[^()[\]\\]|\\.|\[[^\]]*\])*\)\s*(?:[*+?]|\{\d)/;
|
|
1813
|
+
const BACKREFERENCE = /\\[1-9]/;
|
|
1814
|
+
const LOOKAROUND = /\(\?(?:[=!]|<[=!])/;
|
|
1815
|
+
function isRegexQuantifierAt(pattern, index) {
|
|
1816
|
+
const char = pattern[index];
|
|
1817
|
+
if (char === "{") return /^\{\d+(?:,\d*)?\}/.test(pattern.slice(index));
|
|
1818
|
+
return char === "+" || char === "*" || char === "?";
|
|
1819
|
+
}
|
|
1820
|
+
function hasQuantifiedAlternationGroup(pattern) {
|
|
1821
|
+
const stack = [];
|
|
1822
|
+
let inCharClass = false;
|
|
1823
|
+
for (let i = 0; i < pattern.length; i += 1) {
|
|
1824
|
+
const char = pattern[i];
|
|
1825
|
+
if (char === "\\") {
|
|
1826
|
+
i += 1;
|
|
1827
|
+
continue;
|
|
1828
|
+
}
|
|
1829
|
+
if (inCharClass) {
|
|
1830
|
+
if (char === "]") inCharClass = false;
|
|
1831
|
+
continue;
|
|
1832
|
+
}
|
|
1833
|
+
if (char === "[") {
|
|
1834
|
+
inCharClass = true;
|
|
1835
|
+
continue;
|
|
1836
|
+
}
|
|
1837
|
+
if (char === "(") {
|
|
1838
|
+
stack.push({ hasAlternation: false });
|
|
1839
|
+
continue;
|
|
1840
|
+
}
|
|
1841
|
+
if (char === "|") {
|
|
1842
|
+
const top = stack[stack.length - 1];
|
|
1843
|
+
if (top) top.hasAlternation = true;
|
|
1844
|
+
continue;
|
|
1845
|
+
}
|
|
1846
|
+
if (char === ")") {
|
|
1847
|
+
const frame = stack.pop();
|
|
1848
|
+
if (!frame) continue;
|
|
1849
|
+
if (frame.hasAlternation && isRegexQuantifierAt(pattern, i + 1)) return true;
|
|
1850
|
+
const parent = stack[stack.length - 1];
|
|
1851
|
+
if (parent && frame.hasAlternation) parent.hasAlternation = true;
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
return false;
|
|
1855
|
+
}
|
|
1856
|
+
const CLASS_START = /^CLASS\s+(\S+)\s+(DEFINITION|IMPLEMENTATION)(?:\s+.*)?\s*\.\s*$/i;
|
|
1857
|
+
const INTERFACE_START = /^INTERFACE\s+(\S+)(?:\s+DEFINITION)?\s*\.\s*$/i;
|
|
1858
|
+
const METHOD_START = /^METHOD\s+(\S+)\s*\.\s*$/i;
|
|
1859
|
+
function classifyClassInclude(startLine) {
|
|
1860
|
+
const upper = startLine.toUpperCase();
|
|
1861
|
+
if (upper.includes("FOR TESTING")) return "testclasses";
|
|
1862
|
+
if (upper.includes("DEFINITION")) return "definitions";
|
|
1863
|
+
if (upper.includes("IMPLEMENTATION")) return "implementations";
|
|
1864
|
+
return "main";
|
|
1865
|
+
}
|
|
1866
|
+
function openBlock(state, line, lineNumber) {
|
|
1867
|
+
const classMatch = CLASS_START.exec(line);
|
|
1868
|
+
if (classMatch) {
|
|
1869
|
+
state.ownerStack.push(classMatch[1]);
|
|
1870
|
+
state.stack.push({
|
|
1871
|
+
kind: "class",
|
|
1872
|
+
name: classMatch[1],
|
|
1873
|
+
startLine: lineNumber,
|
|
1874
|
+
includeType: classifyClassInclude(line)
|
|
1875
|
+
});
|
|
1876
|
+
return true;
|
|
1877
|
+
}
|
|
1878
|
+
const interfaceMatch = INTERFACE_START.exec(line);
|
|
1879
|
+
if (interfaceMatch) {
|
|
1880
|
+
state.ownerStack.push(interfaceMatch[1]);
|
|
1881
|
+
state.stack.push({
|
|
1882
|
+
kind: "interface",
|
|
1883
|
+
name: interfaceMatch[1],
|
|
1884
|
+
startLine: lineNumber
|
|
1885
|
+
});
|
|
1886
|
+
return true;
|
|
1887
|
+
}
|
|
1888
|
+
const methodMatch = METHOD_START.exec(line);
|
|
1889
|
+
if (methodMatch) {
|
|
1890
|
+
const top = state.stack[state.stack.length - 1];
|
|
1891
|
+
if (top && top.kind !== "method") state.stack.push({
|
|
1892
|
+
kind: "method",
|
|
1893
|
+
name: methodMatch[1].toUpperCase(),
|
|
1894
|
+
startLine: lineNumber,
|
|
1895
|
+
owner: state.ownerStack[state.ownerStack.length - 1]
|
|
1896
|
+
});
|
|
1897
|
+
return true;
|
|
1898
|
+
}
|
|
1899
|
+
return false;
|
|
1900
|
+
}
|
|
1901
|
+
function closeOpenMethods(state, endLine, all) {
|
|
1902
|
+
do {
|
|
1903
|
+
const top = state.stack[state.stack.length - 1];
|
|
1904
|
+
if (top?.kind !== "method") return;
|
|
1905
|
+
state.methods.push({
|
|
1906
|
+
name: top.name,
|
|
1907
|
+
startLine: top.startLine,
|
|
1908
|
+
endLine,
|
|
1909
|
+
owner: top.owner
|
|
1910
|
+
});
|
|
1911
|
+
state.stack.pop();
|
|
1912
|
+
} while (all);
|
|
1913
|
+
}
|
|
1914
|
+
function closeContainer(state, keyword, endLine) {
|
|
1915
|
+
closeOpenMethods(state, endLine, true);
|
|
1916
|
+
const top = state.stack[state.stack.length - 1];
|
|
1917
|
+
const expected = keyword === "ENDCLASS." ? "class" : "interface";
|
|
1918
|
+
if (top?.kind !== expected) return;
|
|
1919
|
+
state.includes.push({
|
|
1920
|
+
name: top.kind === "class" ? top.includeType : "main",
|
|
1921
|
+
startLine: top.startLine,
|
|
1922
|
+
endLine,
|
|
1923
|
+
owner: top.name
|
|
1924
|
+
});
|
|
1925
|
+
state.stack.pop();
|
|
1926
|
+
state.ownerStack.pop();
|
|
1927
|
+
}
|
|
1928
|
+
function parseStructuredSource(source) {
|
|
1929
|
+
const lines = source.split(/\r?\n/);
|
|
1930
|
+
const state = {
|
|
1931
|
+
includes: [],
|
|
1932
|
+
methods: [],
|
|
1933
|
+
stack: [],
|
|
1934
|
+
ownerStack: []
|
|
1935
|
+
};
|
|
1936
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
1937
|
+
const line = stripInlineComment(lines[i] ?? "").trim();
|
|
1938
|
+
if (!line) continue;
|
|
1939
|
+
const lineNumber = i + 1;
|
|
1940
|
+
if (openBlock(state, line, lineNumber)) continue;
|
|
1941
|
+
const upper = line.toUpperCase();
|
|
1942
|
+
if (upper === "ENDMETHOD.") closeOpenMethods(state, lineNumber, false);
|
|
1943
|
+
else if (upper === "ENDCLASS." || upper === "ENDINTERFACE.") closeContainer(state, upper, lineNumber);
|
|
1944
|
+
}
|
|
1945
|
+
return {
|
|
1946
|
+
includes: state.includes,
|
|
1947
|
+
methods: state.methods
|
|
1948
|
+
};
|
|
1949
|
+
}
|
|
1950
|
+
var GetSourceTooLargeError = class extends Error {
|
|
1951
|
+
maxBytes;
|
|
1952
|
+
code = "SOURCE_TOO_LARGE";
|
|
1953
|
+
constructor(maxBytes) {
|
|
1954
|
+
super(`Source exceeds the requested ${maxBytes}-byte limit.`);
|
|
1955
|
+
this.maxBytes = maxBytes;
|
|
1956
|
+
this.name = "GetSourceTooLargeError";
|
|
1957
|
+
}
|
|
1958
|
+
};
|
|
1959
|
+
function stripInlineComment(line) {
|
|
1960
|
+
const idx = line.indexOf("\"");
|
|
1961
|
+
return idx >= 0 ? line.slice(0, idx) : line;
|
|
1962
|
+
}
|
|
1963
|
+
function extractMethodNameFromHeader(line) {
|
|
1964
|
+
const trimmed = stripInlineComment(line).trim();
|
|
1965
|
+
const upper = trimmed.toUpperCase();
|
|
1966
|
+
if (!upper.startsWith("METHOD ") || !upper.endsWith(".")) return;
|
|
1967
|
+
const withoutKeyword = trimmed.slice(7, -1).trim();
|
|
1968
|
+
if (!withoutKeyword) return;
|
|
1969
|
+
return (/^[^\s]+/.exec(withoutKeyword)?.[0])?.toUpperCase();
|
|
1970
|
+
}
|
|
1971
|
+
function listMethods(source) {
|
|
1972
|
+
const methods = [];
|
|
1973
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1974
|
+
for (const line of source.split(/\r?\n/)) {
|
|
1975
|
+
const name = extractMethodNameFromHeader(line);
|
|
1976
|
+
if (name && !seen.has(name)) {
|
|
1977
|
+
seen.add(name);
|
|
1978
|
+
methods.push(name);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
return methods;
|
|
1982
|
+
}
|
|
1983
|
+
function extractMethodBlock(source, methodName) {
|
|
1984
|
+
const boundary = detectMethodBoundary(source, methodName);
|
|
1985
|
+
if (!boundary) return;
|
|
1986
|
+
const lines = source.split(/\r?\n/);
|
|
1987
|
+
const start = boundary.startLine - 1;
|
|
1988
|
+
const end = boundary.endLine;
|
|
1989
|
+
const methodSource = lines.slice(start, end).join("\n");
|
|
1990
|
+
const body = normalizeMethodBody(methodSource, methodName);
|
|
1991
|
+
return {
|
|
1992
|
+
source: [
|
|
1993
|
+
`METHOD ${methodName.toUpperCase()}.`,
|
|
1994
|
+
body,
|
|
1995
|
+
"ENDMETHOD."
|
|
1996
|
+
].join("\n"),
|
|
1997
|
+
startLine: boundary.startLine,
|
|
1998
|
+
endLine: boundary.endLine
|
|
1999
|
+
};
|
|
2000
|
+
}
|
|
2001
|
+
function unsafePatternReason(pattern) {
|
|
2002
|
+
if (pattern.length > MAX_GREP_PATTERN_LENGTH) return `pattern is too long (${pattern.length} characters; maximum ${MAX_GREP_PATTERN_LENGTH})`;
|
|
2003
|
+
if (LOOKAROUND.test(pattern)) return "lookaround assertions are not allowed for server-side grep";
|
|
2004
|
+
if (BACKREFERENCE.test(pattern)) return "backreferences are not allowed for server-side grep";
|
|
2005
|
+
if (NESTED_QUANTIFIER_GROUP.test(pattern)) return "nested quantified groups are not allowed for server-side grep";
|
|
2006
|
+
if (hasQuantifiedAlternationGroup(pattern)) return "quantified alternation groups are not allowed for server-side grep";
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* Validates the grep pattern and returns it unchanged if it is safe.
|
|
2010
|
+
* The name is recognized by CodeQL as a regex-sanitization boundary, so the
|
|
2011
|
+
* tainted `pattern` is treated as sanitized before reaching the `new RegExp` sink.
|
|
2012
|
+
* The real safety guarantees are the checks in `unsafePatternReason`.
|
|
2013
|
+
*/
|
|
2014
|
+
function sanitizeRegExp(pattern) {
|
|
2015
|
+
const reason = unsafePatternReason(pattern);
|
|
2016
|
+
if (reason) throw new Error(`Grep pattern is not allowed for safety (${reason}).`);
|
|
2017
|
+
return pattern;
|
|
2018
|
+
}
|
|
2019
|
+
function compileGrepPattern(pattern) {
|
|
2020
|
+
try {
|
|
2021
|
+
const sanitized = sanitizeRegExp(pattern);
|
|
2022
|
+
return { regex: new RegExp(sanitized, "i") };
|
|
2023
|
+
} catch (error) {
|
|
2024
|
+
if (error instanceof Error && error.message.startsWith("Grep pattern is not allowed")) return { invalidPattern: error.message };
|
|
2025
|
+
return { invalidPattern: `Invalid regex pattern: "${pattern}"` };
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
function findMatchingLines(lines, regex) {
|
|
2029
|
+
const matched = [];
|
|
2030
|
+
for (let i = 0; i < lines.length; i += 1) if (regex.test(lines[i] ?? "")) matched.push(i);
|
|
2031
|
+
return matched;
|
|
2032
|
+
}
|
|
2033
|
+
function buildContextSet(lines, matched) {
|
|
2034
|
+
const context = /* @__PURE__ */ new Set();
|
|
2035
|
+
const lastIndex = lines.length - 1;
|
|
2036
|
+
for (const idx of matched) {
|
|
2037
|
+
const from = Math.max(0, idx - GREP_CONTEXT_LINES);
|
|
2038
|
+
const to = Math.min(lastIndex, idx + GREP_CONTEXT_LINES);
|
|
2039
|
+
for (let i = from; i <= to; i += 1) context.add(i);
|
|
2040
|
+
}
|
|
2041
|
+
return context;
|
|
2042
|
+
}
|
|
2043
|
+
function findEnclosing(ranges, lineNumber) {
|
|
2044
|
+
return ranges.find((range) => lineNumber >= range.startLine && lineNumber <= range.endLine);
|
|
2045
|
+
}
|
|
2046
|
+
function resolveLineContext(lineNumber, includes, methods) {
|
|
2047
|
+
const include = findEnclosing(includes, lineNumber);
|
|
2048
|
+
const method = findEnclosing(methods, lineNumber);
|
|
2049
|
+
if (!include && !method) return void 0;
|
|
2050
|
+
return {
|
|
2051
|
+
class: method?.owner ?? include?.owner,
|
|
2052
|
+
include: include?.name,
|
|
2053
|
+
method: method?.name
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
function buildLineContextMap(lines, includes, methods) {
|
|
2057
|
+
const map = /* @__PURE__ */ new Map();
|
|
2058
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
2059
|
+
const ctx = resolveLineContext(i + 1, includes, methods);
|
|
2060
|
+
if (ctx) map.set(i, ctx);
|
|
2061
|
+
}
|
|
2062
|
+
return map;
|
|
2063
|
+
}
|
|
2064
|
+
function formatGrepResult(lines, context, contextMap) {
|
|
2065
|
+
const sorted = Array.from(context).sort((a, b) => a - b);
|
|
2066
|
+
const matches = [];
|
|
2067
|
+
const methodContext = [];
|
|
2068
|
+
let prev = -2;
|
|
2069
|
+
for (const idx of sorted) {
|
|
2070
|
+
if (idx - prev > 1) matches.push("---");
|
|
2071
|
+
const lineNumber = idx + 1;
|
|
2072
|
+
const text = lines[idx] ?? "";
|
|
2073
|
+
const ctx = contextMap.get(idx) ?? {};
|
|
2074
|
+
const lineNumberStr = lineNumber.toString().padStart(5, " ");
|
|
2075
|
+
matches.push(`${lineNumberStr}: ${text}`);
|
|
2076
|
+
methodContext.push({
|
|
2077
|
+
line: lineNumber,
|
|
2078
|
+
text,
|
|
2079
|
+
...ctx.class ? { class: ctx.class } : {},
|
|
2080
|
+
...ctx.include ? { include: ctx.include } : {},
|
|
2081
|
+
...ctx.method ? { method: ctx.method } : {}
|
|
2082
|
+
});
|
|
2083
|
+
prev = idx;
|
|
2084
|
+
}
|
|
2085
|
+
return {
|
|
2086
|
+
matches,
|
|
2087
|
+
methodContext
|
|
2088
|
+
};
|
|
2089
|
+
}
|
|
2090
|
+
function grepSource(source, pattern) {
|
|
2091
|
+
const compileResult = compileGrepPattern(pattern);
|
|
2092
|
+
if ("invalidPattern" in compileResult) return {
|
|
2093
|
+
matches: [],
|
|
2094
|
+
methodContext: [],
|
|
2095
|
+
matchCount: 0,
|
|
2096
|
+
invalidPattern: compileResult.invalidPattern
|
|
2097
|
+
};
|
|
2098
|
+
const lines = source.split(/\r?\n/);
|
|
2099
|
+
const matched = findMatchingLines(lines, compileResult.regex);
|
|
2100
|
+
if (matched.length === 0) return {
|
|
2101
|
+
matches: [],
|
|
2102
|
+
methodContext: [],
|
|
2103
|
+
matchCount: 0
|
|
2104
|
+
};
|
|
2105
|
+
const { includes, methods } = parseStructuredSource(source);
|
|
2106
|
+
const contextMap = buildLineContextMap(lines, includes, methods);
|
|
2107
|
+
return {
|
|
2108
|
+
...formatGrepResult(lines, buildContextSet(lines, matched), contextMap),
|
|
2109
|
+
matchCount: matched.length
|
|
2110
|
+
};
|
|
2111
|
+
}
|
|
2112
|
+
function appendVersion(url, version) {
|
|
2113
|
+
if (!version) return url;
|
|
2114
|
+
return `${url}${url.includes("?") ? "&" : "?"}version=${encodeURIComponent(version)}`;
|
|
2115
|
+
}
|
|
2116
|
+
function buildClassIncludeUrl(objectUri, include, version) {
|
|
2117
|
+
const normalized = include.toLowerCase();
|
|
2118
|
+
return appendVersion(normalized === "main" ? `${objectUri}/source/main` : `${objectUri}/includes/${encodeURIComponent(normalized)}`, version);
|
|
2119
|
+
}
|
|
2120
|
+
function buildSourceUrl(objectUri, objectType, include, version) {
|
|
2121
|
+
const upperType = objectType?.toUpperCase();
|
|
2122
|
+
const normalizedInclude = include?.toLowerCase();
|
|
2123
|
+
if (!normalizedInclude) return { url: appendVersion(`${objectUri}/source/main`, version) };
|
|
2124
|
+
if (upperType === "CLAS") {
|
|
2125
|
+
const includes = normalizedInclude.split(",").map((s) => s.trim()).filter((s) => Boolean(s));
|
|
2126
|
+
const firstInclude = includes[0];
|
|
2127
|
+
if (!firstInclude) return { url: appendVersion(`${objectUri}/source/main`, version) };
|
|
2128
|
+
if (!VALID_CLASS_INCLUDES.has(firstInclude)) return {
|
|
2129
|
+
url: appendVersion(`${objectUri}/source/main`, version),
|
|
2130
|
+
note: `Unknown class include "${firstInclude}". Valid: ${Array.from(VALID_CLASS_INCLUDES).join(", ")}. Returning main source.`
|
|
2131
|
+
};
|
|
2132
|
+
if (includes.length === 1) return { url: buildClassIncludeUrl(objectUri, firstInclude, version) };
|
|
2133
|
+
return {
|
|
2134
|
+
url: buildClassIncludeUrl(objectUri, firstInclude, version),
|
|
2135
|
+
note: `Multiple includes requested (${include}); current implementation returns the first include "${firstInclude}". Use separate calls or a single include for precise reads.`
|
|
2136
|
+
};
|
|
2137
|
+
}
|
|
2138
|
+
if (upperType === "DDLS" && normalizedInclude === "elements") return {
|
|
2139
|
+
url: appendVersion(`${objectUri}/source/main`, version),
|
|
2140
|
+
note: "include=\"elements\" is not yet supported for DDLS; returning main source."
|
|
2141
|
+
};
|
|
2142
|
+
if (upperType === "FUNC" && normalizedInclude === "signature") return {
|
|
2143
|
+
url: appendVersion(`${objectUri}/source/main`, version),
|
|
2144
|
+
note: "include=\"signature\" is not yet supported for FUNC; returning main source."
|
|
2145
|
+
};
|
|
2146
|
+
return {
|
|
2147
|
+
url: appendVersion(`${objectUri}/source/main`, version),
|
|
2148
|
+
note: `include="${include}" is only supported for CLAS; returning main source.`
|
|
2149
|
+
};
|
|
2150
|
+
}
|
|
2151
|
+
async function resolveUri(client, objectName, objectType) {
|
|
2152
|
+
if (objectType) {
|
|
2153
|
+
const uri = getObjectUri(objectType, objectName);
|
|
2154
|
+
if (uri) return {
|
|
2155
|
+
uri,
|
|
2156
|
+
objectType
|
|
2157
|
+
};
|
|
2158
|
+
}
|
|
2159
|
+
const searchResult = await client.adt.repository.informationsystem.search.quickSearch({
|
|
2160
|
+
query: objectName,
|
|
2161
|
+
maxResults: 10
|
|
2162
|
+
});
|
|
2163
|
+
const match = normalizeSearchResults(searchResult).find((o) => o.name?.toUpperCase() === objectName.toUpperCase());
|
|
2164
|
+
if (!match?.uri) throw new Error(`Object '${objectName}' not found`);
|
|
2165
|
+
return {
|
|
2166
|
+
uri: match.uri,
|
|
2167
|
+
objectType: match.type
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
async function fetchSource(client, url, maxBytes) {
|
|
2171
|
+
try {
|
|
2172
|
+
return await client.readTextBounded(url, maxBytes, { headers: { Accept: "text/plain" } });
|
|
2173
|
+
} catch (error) {
|
|
2174
|
+
if (error instanceof AdtResponseTooLargeError) throw new GetSourceTooLargeError(maxBytes);
|
|
2175
|
+
throw error;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
function methodTypeSupported(objectType) {
|
|
2179
|
+
return objectType?.toUpperCase() === "CLAS";
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* Fetch ABAP source with arc-1 SAPRead-style filtering.
|
|
2183
|
+
*
|
|
2184
|
+
* @throws {GetSourceTooLargeError} when the source body exceeds maxBytes.
|
|
2185
|
+
* @throws {Error} for resolution or validation failures.
|
|
2186
|
+
*/
|
|
2187
|
+
async function getSource(client, options) {
|
|
2188
|
+
const { objectName, objectType, version = "active", include, method, grep, maxBytes: requestedMaxBytes, format = "raw" } = options;
|
|
2189
|
+
if (grep && method) throw new Error("Do not combine grep with method. Use grep to find code, then method=\"<name>\" to read the full method.");
|
|
2190
|
+
if (format === "structured" && (method || grep)) throw new Error("format=structured cannot be combined with method or grep.");
|
|
2191
|
+
const maxBytes = Math.min(requestedMaxBytes ?? DEFAULT_MAX_SOURCE_BYTES, HARD_MAX_SOURCE_BYTES);
|
|
2192
|
+
const { uri: objectUri, objectType: resolvedObjectType } = await resolveUri(client, objectName, objectType);
|
|
2193
|
+
const { url, note } = buildSourceUrl(objectUri, resolvedObjectType, include, version);
|
|
2194
|
+
const source = await fetchSource(client, url, maxBytes);
|
|
2195
|
+
if (method) {
|
|
2196
|
+
if (!methodTypeSupported(resolvedObjectType)) throw new Error(`method is only supported for CLAS, but objectType was "${resolvedObjectType ?? objectType}"`);
|
|
2197
|
+
if (method === "*") {
|
|
2198
|
+
const methods = listMethods(source);
|
|
2199
|
+
return {
|
|
2200
|
+
object: objectName,
|
|
2201
|
+
methodCount: methods.length,
|
|
2202
|
+
methods,
|
|
2203
|
+
note
|
|
2204
|
+
};
|
|
2205
|
+
}
|
|
2206
|
+
const extracted = extractMethodBlock(source, method);
|
|
2207
|
+
if (!extracted) throw new Error(`Method ${method} not found in ${objectName}`);
|
|
2208
|
+
return {
|
|
2209
|
+
object: objectName,
|
|
2210
|
+
method: method.toUpperCase(),
|
|
2211
|
+
source: extracted.source,
|
|
2212
|
+
startLine: extracted.startLine,
|
|
2213
|
+
endLine: extracted.endLine,
|
|
2214
|
+
bytes: Buffer.byteLength(extracted.source, "utf8"),
|
|
2215
|
+
note
|
|
2216
|
+
};
|
|
2217
|
+
}
|
|
2218
|
+
if (grep) {
|
|
2219
|
+
const grepResult = grepSource(source, grep);
|
|
2220
|
+
if (grepResult.invalidPattern) throw new Error(grepResult.invalidPattern);
|
|
2221
|
+
return {
|
|
2222
|
+
object: objectName,
|
|
2223
|
+
pattern: grep,
|
|
2224
|
+
matchCount: grepResult.matchCount,
|
|
2225
|
+
matches: grepResult.matches,
|
|
2226
|
+
methodContext: grepResult.methodContext,
|
|
2227
|
+
note
|
|
2228
|
+
};
|
|
2229
|
+
}
|
|
2230
|
+
if (format === "structured") {
|
|
2231
|
+
const { includes, methods: methodBoundaries } = parseStructuredSource(source);
|
|
2232
|
+
return {
|
|
2233
|
+
object: objectName,
|
|
2234
|
+
source,
|
|
2235
|
+
bytes: Buffer.byteLength(source, "utf8"),
|
|
2236
|
+
version,
|
|
2237
|
+
include,
|
|
2238
|
+
includes,
|
|
2239
|
+
methods: methodBoundaries,
|
|
2240
|
+
note
|
|
2241
|
+
};
|
|
2242
|
+
}
|
|
2243
|
+
return {
|
|
2244
|
+
object: objectName,
|
|
2245
|
+
source,
|
|
2246
|
+
bytes: Buffer.byteLength(source, "utf8"),
|
|
2247
|
+
version,
|
|
2248
|
+
include,
|
|
2249
|
+
note
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
//#endregion
|
|
2254
|
+
//#region src/services/source-history/service.ts
|
|
2255
|
+
/**
|
|
2256
|
+
* Safe delivery-layer failure that deliberately excludes adapter response
|
|
2257
|
+
* bodies, credentials, and ABAP source text.
|
|
2258
|
+
*/
|
|
2259
|
+
var ExactSourceHistoryServiceError = class extends Error {
|
|
2260
|
+
code;
|
|
2261
|
+
constructor(code, message) {
|
|
2262
|
+
super(message);
|
|
2263
|
+
this.code = code;
|
|
2264
|
+
this.name = "ExactSourceHistoryServiceError";
|
|
2265
|
+
}
|
|
2266
|
+
};
|
|
2267
|
+
const DEFAULT_OPERATIONS = {
|
|
2268
|
+
listObjectSourceVersions,
|
|
2269
|
+
buildTransportSourceManifest
|
|
2270
|
+
};
|
|
2271
|
+
function isSafeSourceHistoryError(error) {
|
|
2272
|
+
if (!(error instanceof Error)) return false;
|
|
2273
|
+
return typeof error.code === "string" && (error.name === "SourceHistoryProtocolError" || error.name === "ObjectSourceHistoryError");
|
|
2274
|
+
}
|
|
2275
|
+
/**
|
|
2276
|
+
* Shared source-history delivery service used by CLI and MCP.
|
|
2277
|
+
*
|
|
2278
|
+
* The class is deliberately free of Commander, stdout, file-system, and
|
|
2279
|
+
* process-exit concerns. It returns ADK/client domain values directly so both
|
|
2280
|
+
* delivery surfaces expose the same normalized records.
|
|
2281
|
+
*/
|
|
2282
|
+
/**
|
|
2283
|
+
* Strip server-relative source locators from a listing so that only object
|
|
2284
|
+
* identity, component ids, and transport provenance remain.
|
|
2285
|
+
*/
|
|
2286
|
+
function toMetadataOnlySourceVersionListing(result) {
|
|
2287
|
+
return {
|
|
2288
|
+
object: result.object,
|
|
2289
|
+
components: result.components.map((component) => ({
|
|
2290
|
+
id: component.id,
|
|
2291
|
+
..."versions" in component && Array.isArray(component.versions) ? { versions: component.versions.map(({ sourceUri: _sourceUri, ...version }) => version) } : {},
|
|
2292
|
+
..."diagnostic" in component && component.diagnostic !== void 0 ? { diagnostic: component.diagnostic } : {}
|
|
2293
|
+
}))
|
|
2294
|
+
};
|
|
2295
|
+
}
|
|
2296
|
+
/**
|
|
2297
|
+
* Strip source locators from a transport manifest so that only object
|
|
2298
|
+
* identity, change metadata, and transport provenance remain.
|
|
2299
|
+
*/
|
|
2300
|
+
function toMetadataOnlyTransportSourceManifest(manifest) {
|
|
2301
|
+
return {
|
|
2302
|
+
requestedTransports: manifest.requestedTransports,
|
|
2303
|
+
scopeTransports: manifest.scopeTransports,
|
|
2304
|
+
inventory: manifest.inventory.map(({ uri: _uri, ...entry }) => entry),
|
|
2305
|
+
entries: manifest.entries.map((entry) => {
|
|
2306
|
+
const { sourceUri: _s, versionsUri: _v, ...component } = entry.component;
|
|
2307
|
+
const stripSourceUri = (ref) => {
|
|
2308
|
+
const { sourceUri: _, ...rest } = ref;
|
|
2309
|
+
return rest;
|
|
2310
|
+
};
|
|
2311
|
+
return {
|
|
2312
|
+
...entry,
|
|
2313
|
+
component,
|
|
2314
|
+
...entry.base !== void 0 ? { base: stripSourceUri(entry.base) } : {},
|
|
2315
|
+
...entry.head !== void 0 ? { head: stripSourceUri(entry.head) } : {}
|
|
2316
|
+
};
|
|
2317
|
+
})
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
var ExactSourceHistoryService = class {
|
|
2321
|
+
client;
|
|
2322
|
+
operations;
|
|
2323
|
+
constructor(client, operations = DEFAULT_OPERATIONS) {
|
|
2324
|
+
this.client = client;
|
|
2325
|
+
this.operations = operations;
|
|
2326
|
+
}
|
|
2327
|
+
async listObjectVersions(input) {
|
|
2328
|
+
try {
|
|
2329
|
+
return await this.operations.listObjectSourceVersions(input.objectName, input.objectType, input.component !== void 0 ? { component: input.component } : {}, { client: this.client });
|
|
2330
|
+
} catch (error) {
|
|
2331
|
+
if (isSafeSourceHistoryError(error)) throw error;
|
|
2332
|
+
throw new ExactSourceHistoryServiceError("SOURCE_VERSION_LIST_FAILED", "SAP ADT source-version metadata retrieval failed.");
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
async getVersionSource(input) {
|
|
2336
|
+
try {
|
|
2337
|
+
return await this.client.services.sourceHistory.readVersionSource(input.uri);
|
|
2338
|
+
} catch (error) {
|
|
2339
|
+
if (isSafeSourceHistoryError(error)) throw error;
|
|
2340
|
+
throw new ExactSourceHistoryServiceError("SOURCE_VERSION_READ_FAILED", "SAP ADT immutable source retrieval failed.");
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
async buildTransportManifest(input) {
|
|
2344
|
+
const options = {
|
|
2345
|
+
...input.selector ? { selector: input.selector } : {},
|
|
2346
|
+
...input.concurrency !== void 0 ? { concurrency: input.concurrency } : {}
|
|
2347
|
+
};
|
|
2348
|
+
try {
|
|
2349
|
+
return await this.operations.buildTransportSourceManifest(input.transports, options, { client: this.client });
|
|
2350
|
+
} catch {
|
|
2351
|
+
throw new ExactSourceHistoryServiceError("TRANSPORT_SOURCE_MANIFEST_FAILED", "SAP ADT transport source-manifest construction failed.");
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
};
|
|
2355
|
+
|
|
2356
|
+
//#endregion
|
|
2357
|
+
//#region src/services/check/service.ts
|
|
2358
|
+
const DEFAULT_CHECK_SOURCE_VERSION = "inactive";
|
|
2359
|
+
function buildCheckObjectList(objects, sourceVersion) {
|
|
2360
|
+
return { checkObjectList: { checkObject: objects.map((object) => ({
|
|
2361
|
+
uri: object.uri,
|
|
2362
|
+
version: sourceVersion
|
|
2363
|
+
})) } };
|
|
2364
|
+
}
|
|
2365
|
+
function normalizeCheckMessages(rawMessages) {
|
|
2366
|
+
if (!rawMessages) return void 0;
|
|
2367
|
+
return Array.isArray(rawMessages) ? rawMessages : [rawMessages];
|
|
2368
|
+
}
|
|
2369
|
+
function normalizeReport(entry) {
|
|
2370
|
+
const report = entry ?? {};
|
|
2371
|
+
const messageList = report.checkMessageList;
|
|
2372
|
+
const messages = normalizeCheckMessages(messageList?.checkMessage);
|
|
2373
|
+
return {
|
|
2374
|
+
reporter: report.reporter,
|
|
2375
|
+
triggeringUri: report.triggeringUri,
|
|
2376
|
+
status: report.status,
|
|
2377
|
+
statusText: report.statusText,
|
|
2378
|
+
checkMessageList: messages ? { checkMessage: messages } : void 0
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
function detectSeverities(reports) {
|
|
2382
|
+
let hasErrors = false;
|
|
2383
|
+
let hasWarnings = false;
|
|
2384
|
+
for (const report of reports) for (const message of report.checkMessageList?.checkMessage ?? []) {
|
|
2385
|
+
const severity = typeof message.type === "string" ? message.type : message.category;
|
|
2386
|
+
if (severity === "E" || severity === "A") hasErrors = true;
|
|
2387
|
+
if (severity === "W") hasWarnings = true;
|
|
2388
|
+
}
|
|
2389
|
+
return {
|
|
2390
|
+
hasErrors,
|
|
2391
|
+
hasWarnings
|
|
2392
|
+
};
|
|
2393
|
+
}
|
|
2394
|
+
function extractReports(response) {
|
|
2395
|
+
const root = response ?? {};
|
|
2396
|
+
const rawReports = (root.checkRunReports ?? root).checkReport;
|
|
2397
|
+
const reports = (Array.isArray(rawReports) ? rawReports : rawReports ? [rawReports] : []).map(normalizeReport);
|
|
2398
|
+
return {
|
|
2399
|
+
reports,
|
|
2400
|
+
...detectSeverities(reports)
|
|
2401
|
+
};
|
|
2402
|
+
}
|
|
2403
|
+
var CheckService = class {
|
|
2404
|
+
client;
|
|
2405
|
+
constructor(client) {
|
|
2406
|
+
this.client = client;
|
|
2407
|
+
}
|
|
2408
|
+
async run(input) {
|
|
2409
|
+
const sourceVersion = input.sourceVersion ?? "inactive";
|
|
2410
|
+
const body = buildCheckObjectList(input.objects, sourceVersion);
|
|
2411
|
+
const endpoint = this.client.adt.checkruns.checkObjects;
|
|
2412
|
+
return extractReports(await endpoint.post.call(endpoint, body));
|
|
2413
|
+
}
|
|
2414
|
+
};
|
|
2415
|
+
|
|
2416
|
+
//#endregion
|
|
2417
|
+
//#region src/utils/auth.ts
|
|
2418
|
+
/**
|
|
2419
|
+
* CLI Auth Utilities
|
|
2420
|
+
*
|
|
2421
|
+
* Thin wrapper around @abapify/adt-auth
|
|
2422
|
+
* All auth logic is in the adt-auth package (single source of truth)
|
|
2423
|
+
*/
|
|
2424
|
+
const authManager = new AuthManager();
|
|
2425
|
+
/**
|
|
2426
|
+
* Load auth session
|
|
2427
|
+
*/
|
|
2428
|
+
function loadAuthSession(sid) {
|
|
2429
|
+
return authManager.getSession(sid);
|
|
2430
|
+
}
|
|
2431
|
+
/**
|
|
2432
|
+
* Save auth session
|
|
2433
|
+
*/
|
|
2434
|
+
function saveAuthSession(session) {
|
|
2435
|
+
authManager.saveSession(session);
|
|
2436
|
+
}
|
|
2437
|
+
/**
|
|
2438
|
+
* List all available SIDs
|
|
2439
|
+
*/
|
|
2440
|
+
function listAvailableSids() {
|
|
2441
|
+
return authManager.listSids();
|
|
2442
|
+
}
|
|
2443
|
+
/**
|
|
2444
|
+
* Get default SID
|
|
2445
|
+
*/
|
|
2446
|
+
function getDefaultSid() {
|
|
2447
|
+
return authManager.getDefaultSid() ?? void 0;
|
|
2448
|
+
}
|
|
2449
|
+
/**
|
|
2450
|
+
* Set default SID
|
|
2451
|
+
*/
|
|
2452
|
+
function setDefaultSid(sid) {
|
|
2453
|
+
authManager.setDefaultSid(sid);
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Check if session is expired
|
|
2457
|
+
*/
|
|
2458
|
+
function isExpired(session) {
|
|
2459
|
+
return authManager.isExpired(session);
|
|
2460
|
+
}
|
|
2461
|
+
/**
|
|
2462
|
+
* Refresh credentials using auth plugin
|
|
2463
|
+
*/
|
|
2464
|
+
async function refreshCredentials(session, options) {
|
|
2465
|
+
return authManager.refreshCredentials(session, options);
|
|
2466
|
+
}
|
|
2467
|
+
/**
|
|
2468
|
+
* Get the AuthManager instance (for advanced use)
|
|
2469
|
+
*/
|
|
2470
|
+
function getAuthManager() {
|
|
2471
|
+
return authManager;
|
|
2472
|
+
}
|
|
2473
|
+
|
|
2474
|
+
//#endregion
|
|
2475
|
+
//#region src/utils/progress-reporter.ts
|
|
2476
|
+
function sanitize(message) {
|
|
2477
|
+
return message.replaceAll(/\s+/g, " ").trim();
|
|
2478
|
+
}
|
|
2479
|
+
function createProgressReporter(options = {}) {
|
|
2480
|
+
const compact = Boolean(options.compact);
|
|
2481
|
+
const logger = options.logger;
|
|
2482
|
+
const level = options.level ?? "info";
|
|
2483
|
+
let lastMessage = "";
|
|
2484
|
+
let open = false;
|
|
2485
|
+
const logWithFlag = (message, meta) => {
|
|
2486
|
+
if (logger) (logger[level] ?? logger.info).call(logger, message, {
|
|
2487
|
+
progress: true,
|
|
2488
|
+
component: "progress",
|
|
2489
|
+
...meta
|
|
2490
|
+
});
|
|
2491
|
+
};
|
|
2492
|
+
const clearLine = () => {
|
|
2493
|
+
if (open) process.stderr.write("\r\x1B[K");
|
|
2494
|
+
};
|
|
2495
|
+
const step = (message) => {
|
|
2496
|
+
const clean = sanitize(message);
|
|
2497
|
+
if (!compact) {
|
|
2498
|
+
logWithFlag(clean, { transient: false });
|
|
2499
|
+
return;
|
|
2500
|
+
}
|
|
2501
|
+
clearLine();
|
|
2502
|
+
process.stderr.write(clean);
|
|
2503
|
+
lastMessage = clean;
|
|
2504
|
+
open = true;
|
|
2505
|
+
logWithFlag(clean, { transient: true });
|
|
2506
|
+
};
|
|
2507
|
+
const persist = (message) => {
|
|
2508
|
+
const clean = sanitize(message);
|
|
2509
|
+
clearLine();
|
|
2510
|
+
if (compact || !logger) process.stderr.write(`${clean}\n`);
|
|
2511
|
+
logWithFlag(clean);
|
|
2512
|
+
open = false;
|
|
2513
|
+
lastMessage = "";
|
|
2514
|
+
};
|
|
2515
|
+
const done = (finalMessage) => {
|
|
2516
|
+
if (!open && !finalMessage) return;
|
|
2517
|
+
clearLine();
|
|
2518
|
+
if (compact) {
|
|
2519
|
+
if (finalMessage) {
|
|
2520
|
+
const clean = sanitize(finalMessage);
|
|
2521
|
+
process.stderr.write(`${clean}\n`);
|
|
2522
|
+
logWithFlag(clean);
|
|
2523
|
+
} else if (open && lastMessage) {
|
|
2524
|
+
process.stderr.write(`${lastMessage}\n`);
|
|
2525
|
+
logWithFlag(lastMessage);
|
|
2526
|
+
}
|
|
2527
|
+
} else {
|
|
2528
|
+
const clean = sanitize(finalMessage ?? lastMessage);
|
|
2529
|
+
if (clean) logWithFlag(clean);
|
|
2530
|
+
}
|
|
2531
|
+
open = false;
|
|
2532
|
+
lastMessage = "";
|
|
2533
|
+
};
|
|
2534
|
+
const clear = () => {
|
|
2535
|
+
clearLine();
|
|
2536
|
+
open = false;
|
|
2537
|
+
lastMessage = "";
|
|
2538
|
+
};
|
|
2539
|
+
return {
|
|
2540
|
+
step,
|
|
2541
|
+
persist,
|
|
2542
|
+
done,
|
|
2543
|
+
clear
|
|
2544
|
+
};
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
//#endregion
|
|
2548
|
+
//#region src/ui/components/link.ts
|
|
2549
|
+
/**
|
|
2550
|
+
* Link Component
|
|
2551
|
+
*
|
|
2552
|
+
* Creates OSC 8 hyperlinks for terminal emulators that support them.
|
|
2553
|
+
* Falls back to plain text in unsupported terminals.
|
|
2554
|
+
*
|
|
2555
|
+
* OSC 8 format: \x1b]8;;URL\x07TEXT\x1b]8;;\\x07
|
|
2556
|
+
*
|
|
2557
|
+
* @see https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
|
|
2558
|
+
*/
|
|
2559
|
+
/**
|
|
2560
|
+
* Create an OSC 8 hyperlink
|
|
2561
|
+
*
|
|
2562
|
+
* @param text - Display text
|
|
2563
|
+
* @param url - URL to link to
|
|
2564
|
+
* @returns Formatted hyperlink string
|
|
2565
|
+
*/
|
|
2566
|
+
function hyperlink(text, url) {
|
|
2567
|
+
const OSC = "\x1B]";
|
|
2568
|
+
const BEL = "\x07";
|
|
2569
|
+
const SEP = ";";
|
|
2570
|
+
return `${OSC}8${SEP}${SEP}${url}${BEL}${text}${OSC}8${SEP}${SEP}${BEL}`;
|
|
2571
|
+
}
|
|
2572
|
+
let adtSystemName = "";
|
|
2573
|
+
/**
|
|
2574
|
+
* Set the ADT system name for hyperlinks (called by CLI on init)
|
|
2575
|
+
*/
|
|
2576
|
+
function setAdtSystem(systemName) {
|
|
2577
|
+
adtSystemName = systemName;
|
|
2578
|
+
}
|
|
2579
|
+
/**
|
|
2580
|
+
* Get current ADT system name
|
|
2581
|
+
*/
|
|
2582
|
+
function getAdtSystem() {
|
|
2583
|
+
return adtSystemName;
|
|
2584
|
+
}
|
|
2585
|
+
/**
|
|
2586
|
+
* ADT path templates for object types
|
|
2587
|
+
* Template uses {name} placeholder for object name
|
|
2588
|
+
*/
|
|
2589
|
+
const ADT_PATH_TEMPLATES = {
|
|
2590
|
+
DEVC: "/packages/{name}",
|
|
2591
|
+
"DEVC/K": "/packages/{name}",
|
|
2592
|
+
CLAS: "/oo/classes/{name}",
|
|
2593
|
+
"CLAS/OC": "/oo/classes/{name}",
|
|
2594
|
+
INTF: "/oo/interfaces/{name}",
|
|
2595
|
+
"INTF/OI": "/oo/interfaces/{name}",
|
|
2596
|
+
FUGR: "/functions/groups/{name}",
|
|
2597
|
+
"FUGR/F": "/functions/groups/{name}",
|
|
2598
|
+
FUNC: "/functions/groups/{name}",
|
|
2599
|
+
PROG: "/programs/programs/{name}",
|
|
2600
|
+
"PROG/P": "/programs/programs/{name}",
|
|
2601
|
+
"PROG/I": "/programs/includes/{name}",
|
|
2602
|
+
TABL: "/ddic/tables/{name}",
|
|
2603
|
+
"TABL/DT": "/ddic/tables/{name}",
|
|
2604
|
+
"TABL/DS": "/ddic/structures/{name}",
|
|
2605
|
+
VIEW: "/ddic/views/{name}",
|
|
2606
|
+
DTEL: "/ddic/dataelements/{name}",
|
|
2607
|
+
"DTEL/DE": "/ddic/dataelements/{name}",
|
|
2608
|
+
DOMA: "/ddic/domains/{name}",
|
|
2609
|
+
"DOMA/DO": "/ddic/domains/{name}",
|
|
2610
|
+
SHLP: "/ddic/searchhelps/{name}",
|
|
2611
|
+
ENQU: "/ddic/lockobjects/{name}",
|
|
2612
|
+
MSAG: "/messageclass/{name}",
|
|
2613
|
+
TRAN: "/transactions/{name}",
|
|
2614
|
+
DDLS: "/ddic/ddl/sources/{name}",
|
|
2615
|
+
"DDLS/DF": "/ddic/ddl/sources/{name}",
|
|
2616
|
+
BDEF: "/bo/behaviordefinitions/{name}",
|
|
2617
|
+
SRVD: "/businessservices/servicedefinitions/{name}",
|
|
2618
|
+
SRVB: "/businessservices/servicebindings/{name}"
|
|
2619
|
+
};
|
|
2620
|
+
/**
|
|
2621
|
+
* Get ADT path template for an object type
|
|
2622
|
+
*/
|
|
2623
|
+
function getAdtPathTemplate(objectType) {
|
|
2624
|
+
if (ADT_PATH_TEMPLATES[objectType]) return ADT_PATH_TEMPLATES[objectType];
|
|
2625
|
+
const baseType = objectType.split("/")[0];
|
|
2626
|
+
return ADT_PATH_TEMPLATES[baseType];
|
|
2627
|
+
}
|
|
2628
|
+
/**
|
|
2629
|
+
* Resolve ADT path from template
|
|
2630
|
+
*/
|
|
2631
|
+
function resolveAdtPath(template, name) {
|
|
2632
|
+
return template.replace("{name}", encodeURIComponent(name));
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Create a generic link (plain URL)
|
|
2636
|
+
*/
|
|
2637
|
+
function link(text, url) {
|
|
2638
|
+
return hyperlink(chalk.cyan(text), url);
|
|
2639
|
+
}
|
|
2640
|
+
/**
|
|
2641
|
+
* Create an ADT Eclipse link for an object reference
|
|
2642
|
+
* Format: adt://[SYSTEM]/sap/bc/adt/[path]
|
|
2643
|
+
*
|
|
2644
|
+
* @param ref - ADT object reference with name, type, and/or uri (can be undefined)
|
|
2645
|
+
* @returns Formatted hyperlink string (or empty string if no ref/name)
|
|
2646
|
+
*/
|
|
2647
|
+
function adtLink(ref) {
|
|
2648
|
+
const name = ref?.name || "";
|
|
2649
|
+
if (!adtSystemName || !name) return name ? chalk.cyan(name) : "";
|
|
2650
|
+
if (ref?.uri) {
|
|
2651
|
+
const path = ref.uri.startsWith("/sap/bc/adt") ? ref.uri : `/sap/bc/adt${ref.uri}`;
|
|
2652
|
+
const url = `adt://${adtSystemName}${path}`;
|
|
2653
|
+
return hyperlink(chalk.cyan(name), url);
|
|
2654
|
+
}
|
|
2655
|
+
if (ref?.type) {
|
|
2656
|
+
const template = getAdtPathTemplate(ref.type);
|
|
2657
|
+
if (template) {
|
|
2658
|
+
const adtPath = resolveAdtPath(template, name);
|
|
2659
|
+
const url = `adt://${adtSystemName}/sap/bc/adt${adtPath}`;
|
|
2660
|
+
return hyperlink(chalk.cyan(name), url);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
return chalk.cyan(name);
|
|
2664
|
+
}
|
|
2665
|
+
/**
|
|
2666
|
+
* Create a clickable package link (convenience wrapper)
|
|
2667
|
+
*/
|
|
2668
|
+
function packageLink(packageName) {
|
|
2669
|
+
return adtLink({
|
|
2670
|
+
type: "DEVC",
|
|
2671
|
+
name: packageName
|
|
2672
|
+
});
|
|
2673
|
+
}
|
|
2674
|
+
/**
|
|
2675
|
+
* ADT Link Component - link to ADT object in Eclipse
|
|
2676
|
+
* Extends Link with ADT-specific URL resolution
|
|
2677
|
+
*/
|
|
2678
|
+
function AdtLink(ref) {
|
|
2679
|
+
return { render: () => {
|
|
2680
|
+
const result = adtLink(ref);
|
|
2681
|
+
return result ? [result] : [];
|
|
2682
|
+
} };
|
|
2683
|
+
}
|
|
2684
|
+
/**
|
|
2685
|
+
* Package Link Component - convenience for package links
|
|
2686
|
+
*/
|
|
2687
|
+
function PackageLink(packageName) {
|
|
2688
|
+
return AdtLink({
|
|
2689
|
+
type: "DEVC",
|
|
2690
|
+
name: packageName
|
|
2691
|
+
});
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
//#endregion
|
|
2695
|
+
//#region src/utils/adt-http-options.ts
|
|
2696
|
+
const HEADERS_TIMEOUT_ENV = "ADT_HEADERS_TIMEOUT_MS";
|
|
2697
|
+
function resolveAdtHeadersTimeoutMs(env = process.env) {
|
|
2698
|
+
const raw = env[HEADERS_TIMEOUT_ENV];
|
|
2699
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
2700
|
+
if (!/^\d+$/.test(raw)) throw new RangeError(`${HEADERS_TIMEOUT_ENV} must be a positive integer`);
|
|
2701
|
+
const timeoutMs = Number(raw);
|
|
2702
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new RangeError(`${HEADERS_TIMEOUT_ENV} must be a positive integer`);
|
|
2703
|
+
return timeoutMs;
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
//#endregion
|
|
2707
|
+
//#region src/utils/adt-client-v2.ts
|
|
2708
|
+
/**
|
|
2709
|
+
* Utility for initializing ADT Client V2 in CLI commands
|
|
2710
|
+
*
|
|
2711
|
+
* This module provides CLI-specific auth integration for the v2 client.
|
|
2712
|
+
* It bridges the gap between CLI's auth management and v2's pure client API.
|
|
2713
|
+
*
|
|
2714
|
+
* Architecture Note:
|
|
2715
|
+
* - CLI handles auth management (via v1 AuthManager stored in ~/.adt/auth.json)
|
|
2716
|
+
* - This module extracts credentials and creates v2 client
|
|
2717
|
+
* - v2 client remains pure (no CLI/file I/O dependencies)
|
|
2718
|
+
*
|
|
2719
|
+
* Shared state (context, loggers, capture) is in shared/adt-client.ts
|
|
2720
|
+
*/
|
|
2721
|
+
/**
|
|
2722
|
+
* Stack of test overrides. Using a stack (instead of a single mutable slot)
|
|
2723
|
+
* means nested / concurrent harness instances don't clobber each other's
|
|
2724
|
+
* clients, and teardown is strict: each `__setTestAdtClient` call returns a
|
|
2725
|
+
* `release` function that removes *only that* override, regardless of order.
|
|
2726
|
+
*
|
|
2727
|
+
* Concurrency note: Vitest's default `threads` pool gives each worker its
|
|
2728
|
+
* own module graph, so in practice this state is already isolated per
|
|
2729
|
+
* worker. But a stack keeps us safe if:
|
|
2730
|
+
* - a suite uses `test.concurrent` (shared module, shared state)
|
|
2731
|
+
* - the pool config is changed to `forks: { singleFork: false }` or similar
|
|
2732
|
+
* - multiple harnesses are constructed within a single test
|
|
2733
|
+
* which is why we prefer a stack + explicit release handle here.
|
|
2734
|
+
*/
|
|
2735
|
+
const __testAdtClientOverrides = [];
|
|
2736
|
+
/**
|
|
2737
|
+
* @internal
|
|
2738
|
+
* Install a test AdtClient instance. When set, `getAdtClientV2()` will return
|
|
2739
|
+
* the most recently pushed client instead of loading credentials from disk and
|
|
2740
|
+
* constructing a real client. Intended solely for e2e harness usage.
|
|
2741
|
+
*
|
|
2742
|
+
* Returns a `release` function that removes **this specific** override from
|
|
2743
|
+
* the stack. Callers (harness teardown) MUST call `release()` in an
|
|
2744
|
+
* `afterEach` / `afterAll` / `finally` block.
|
|
2745
|
+
*
|
|
2746
|
+
* Backward compatibility: passing `null` pops the top of the stack (legacy
|
|
2747
|
+
* behaviour used by older harness code paths). New code should prefer the
|
|
2748
|
+
* returned release handle.
|
|
2749
|
+
*/
|
|
2750
|
+
function __setTestAdtClient(client) {
|
|
2751
|
+
if (client === null) {
|
|
2752
|
+
__testAdtClientOverrides.pop();
|
|
2753
|
+
return () => {};
|
|
2754
|
+
}
|
|
2755
|
+
__testAdtClientOverrides.push(client);
|
|
2756
|
+
let released = false;
|
|
2757
|
+
return function release() {
|
|
2758
|
+
if (released) return;
|
|
2759
|
+
released = true;
|
|
2760
|
+
const idx = __testAdtClientOverrides.lastIndexOf(client);
|
|
2761
|
+
if (idx !== -1) __testAdtClientOverrides.splice(idx, 1);
|
|
2762
|
+
};
|
|
2763
|
+
}
|
|
2764
|
+
/**
|
|
2765
|
+
* @internal
|
|
2766
|
+
* Inspect the current test override (mostly for diagnostics / test cleanup).
|
|
2767
|
+
* Returns the top of the stack, or `null` if no override is active.
|
|
2768
|
+
*/
|
|
2769
|
+
function __getTestAdtClient() {
|
|
2770
|
+
return __testAdtClientOverrides.length > 0 ? __testAdtClientOverrides[__testAdtClientOverrides.length - 1] : null;
|
|
2771
|
+
}
|
|
2772
|
+
function __getActiveTestAdtClient() {
|
|
2773
|
+
return __testAdtClientOverrides[__testAdtClientOverrides.length - 1];
|
|
2774
|
+
}
|
|
2775
|
+
/**
|
|
2776
|
+
* Typed error thrown by `getAdtClientV2Safe` when authentication cannot be
|
|
2777
|
+
* resolved. Intentionally NOT thrown by the legacy `getAdtClientV2`, which
|
|
2778
|
+
* prints a friendly message and calls `process.exit(1)` instead. Use this
|
|
2779
|
+
* error class from long-running processes (HTTP servers, MCP daemons) that
|
|
2780
|
+
* must never exit the process on auth failure.
|
|
2781
|
+
*/
|
|
2782
|
+
var AdtAuthError = class extends Error {
|
|
2783
|
+
code;
|
|
2784
|
+
systemId;
|
|
2785
|
+
constructor(code, message, systemId) {
|
|
2786
|
+
super(message);
|
|
2787
|
+
this.name = "AdtAuthError";
|
|
2788
|
+
this.code = code;
|
|
2789
|
+
this.systemId = systemId;
|
|
2790
|
+
}
|
|
2791
|
+
};
|
|
2792
|
+
function reportNoSessionAndExit(sid) {
|
|
2793
|
+
const sidMsg = sid ? ` for SID ${sid}` : "";
|
|
2794
|
+
const loginFlag = sid ? ` --sid=${sid}` : "";
|
|
2795
|
+
console.error(`❌ Not authenticated${sidMsg}`);
|
|
2796
|
+
console.error(`💡 Run "npx adt auth login${loginFlag}" to authenticate first`);
|
|
2797
|
+
process.exit(1);
|
|
2798
|
+
}
|
|
2799
|
+
function reportUnsupportedAuthAndExit(method) {
|
|
2800
|
+
console.error(`❌ Unsupported auth method: ${method}`);
|
|
2801
|
+
process.exit(1);
|
|
2802
|
+
}
|
|
2803
|
+
/**
|
|
2804
|
+
* Try to auto-refresh expired session credentials
|
|
2805
|
+
*
|
|
2806
|
+
* @param session - The expired session
|
|
2807
|
+
* @param sid - Optional SID for error messages
|
|
2808
|
+
* @returns Updated session with fresh credentials
|
|
2809
|
+
*/
|
|
2810
|
+
async function tryAutoRefresh(session, sid, progress) {
|
|
2811
|
+
if (!session.auth.plugin) {
|
|
2812
|
+
console.error("❌ Session expired");
|
|
2813
|
+
console.error("💡 Run \"npx adt auth login\" to re-authenticate");
|
|
2814
|
+
process.exit(1);
|
|
2815
|
+
}
|
|
2816
|
+
progress.step(`🔄 Session expired for ${session.sid}, refreshing...`);
|
|
2817
|
+
try {
|
|
2818
|
+
const refreshedSession = await refreshCredentials(session, { log: progress.persist });
|
|
2819
|
+
if (!refreshedSession) throw new Error("Refresh returned null");
|
|
2820
|
+
progress.clear();
|
|
2821
|
+
return refreshedSession;
|
|
2822
|
+
} catch (error) {
|
|
2823
|
+
progress.done("❌ Auto-refresh failed");
|
|
2824
|
+
console.error("❌ Auto-refresh failed:", error instanceof Error ? error.message : String(error));
|
|
2825
|
+
const sidArg = sid ? ` --sid=${sid}` : "";
|
|
2826
|
+
console.error(`💡 Run "npx adt auth login${sidArg}" to re-authenticate manually`);
|
|
2827
|
+
process.exit(1);
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
/**
|
|
2831
|
+
* Safe variant of `tryAutoRefresh` that throws `AdtAuthError` instead of
|
|
2832
|
+
* exiting the process. Used by `getAdtClientV2Safe`.
|
|
2833
|
+
*/
|
|
2834
|
+
async function tryAutoRefreshSafe(session, sid) {
|
|
2835
|
+
if (!session.auth.plugin) {
|
|
2836
|
+
const sidSuffix = sid ? ` for SID ${sid}` : "";
|
|
2837
|
+
throw new AdtAuthError("SESSION_EXPIRED_NO_PLUGIN", `Session expired${sidSuffix} and no auth plugin is configured to refresh it.`, sid);
|
|
2838
|
+
}
|
|
2839
|
+
try {
|
|
2840
|
+
const refreshedSession = await refreshCredentials(session, { log: () => {} });
|
|
2841
|
+
if (!refreshedSession) throw new Error("Refresh returned null");
|
|
2842
|
+
return refreshedSession;
|
|
2843
|
+
} catch (error) {
|
|
2844
|
+
const sidSuffix = sid ? ` for SID ${sid}` : "";
|
|
2845
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
2846
|
+
throw new AdtAuthError("REFRESH_FAILED", `Auto-refresh failed${sidSuffix}: ${errMsg}`, sid);
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
/**
|
|
2850
|
+
* Get authenticated ADT v2 client
|
|
2851
|
+
*
|
|
2852
|
+
* Loads auth session from CLI config and creates v2 client.
|
|
2853
|
+
* Automatically refreshes expired sessions when possible.
|
|
2854
|
+
* Exits with error if not authenticated.
|
|
2855
|
+
*
|
|
2856
|
+
* @param options - Optional configuration (plugins, logger, etc.)
|
|
2857
|
+
* @returns Authenticated ADT v2 client
|
|
2858
|
+
*
|
|
2859
|
+
* @example
|
|
2860
|
+
* // Simple usage
|
|
2861
|
+
* const client = await getAdtClientV2();
|
|
2862
|
+
*
|
|
2863
|
+
* @example
|
|
2864
|
+
* // With custom logger
|
|
2865
|
+
* const client = await getAdtClientV2({
|
|
2866
|
+
* logger: myLogger,
|
|
2867
|
+
* enableLogging: true // Enable HTTP request/response logging
|
|
2868
|
+
* });
|
|
2869
|
+
*
|
|
2870
|
+
* @example
|
|
2871
|
+
* // With plugins
|
|
2872
|
+
* const client = await getAdtClientV2({
|
|
2873
|
+
* plugins: [myPlugin]
|
|
2874
|
+
* });
|
|
2875
|
+
*/
|
|
2876
|
+
async function getAdtClientV2(options) {
|
|
2877
|
+
const testOverride = __getActiveTestAdtClient();
|
|
2878
|
+
if (testOverride) return testOverride;
|
|
2879
|
+
const headersTimeoutMs = resolveAdtHeadersTimeoutMs();
|
|
2880
|
+
const ctx = getCliContext();
|
|
2881
|
+
const effectiveOptions = {
|
|
2882
|
+
sid: options?.sid ?? ctx.sid,
|
|
2883
|
+
logger: options?.logger ?? ctx.logger,
|
|
2884
|
+
logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,
|
|
2885
|
+
logOutput: options?.logOutput ?? ctx.logOutput ?? "./tmp/logs",
|
|
2886
|
+
enableLogging: options?.enableLogging,
|
|
2887
|
+
writeMetadata: options?.writeMetadata ?? false,
|
|
2888
|
+
capture: options?.capture ?? false,
|
|
2889
|
+
plugins: options?.plugins ?? [],
|
|
2890
|
+
autoReauth: options?.autoReauth ?? true,
|
|
2891
|
+
verbose: options?.verbose ?? ctx.verbose
|
|
2892
|
+
};
|
|
2893
|
+
const logger = effectiveOptions.logger ?? (effectiveOptions.enableLogging ? consoleLogger : silentLogger);
|
|
2894
|
+
const progress = createProgressReporter({
|
|
2895
|
+
compact: !effectiveOptions.verbose,
|
|
2896
|
+
logger
|
|
2897
|
+
});
|
|
2898
|
+
let session = loadAuthSession(effectiveOptions.sid);
|
|
2899
|
+
if (!session) reportNoSessionAndExit(effectiveOptions.sid);
|
|
2900
|
+
setAdtSystem(session.sid);
|
|
2901
|
+
const baseUrl = session.host;
|
|
2902
|
+
const client = session.client;
|
|
2903
|
+
let username;
|
|
2904
|
+
let password;
|
|
2905
|
+
let cookieHeader;
|
|
2906
|
+
let authorizationHeader;
|
|
2907
|
+
if (session.auth.method === "basic") {
|
|
2908
|
+
const creds = session.auth.credentials;
|
|
2909
|
+
username = creds.username;
|
|
2910
|
+
password = creds.password;
|
|
2911
|
+
} else if (session.auth.method === "cookie") {
|
|
2912
|
+
if (isExpired(session)) session = await tryAutoRefresh(session, effectiveOptions.sid, progress);
|
|
2913
|
+
const creds = session.auth.credentials;
|
|
2914
|
+
const rawCookies = decodeURIComponent(creds.cookies);
|
|
2915
|
+
if (rawCookies.startsWith("Authorization: ")) authorizationHeader = rawCookies.substring(15);
|
|
2916
|
+
else cookieHeader = rawCookies;
|
|
2917
|
+
} else reportUnsupportedAuthAndExit(session.auth.method);
|
|
2918
|
+
const plugins = [];
|
|
2919
|
+
if (effectiveOptions.capture) {
|
|
2920
|
+
resetCaptured();
|
|
2921
|
+
plugins.push({
|
|
2922
|
+
name: "capture",
|
|
2923
|
+
process: (context) => {
|
|
2924
|
+
setCaptured({
|
|
2925
|
+
xml: context.rawText,
|
|
2926
|
+
json: context.parsedData
|
|
2927
|
+
});
|
|
2928
|
+
return context.parsedData;
|
|
2929
|
+
}
|
|
2930
|
+
});
|
|
2931
|
+
}
|
|
2932
|
+
if (effectiveOptions.logResponseFiles) plugins.push(new FileLoggingPlugin({
|
|
2933
|
+
outputDir: effectiveOptions.logOutput,
|
|
2934
|
+
writeMetadata: effectiveOptions.writeMetadata,
|
|
2935
|
+
logger
|
|
2936
|
+
}));
|
|
2937
|
+
if (effectiveOptions.enableLogging) plugins.push(new LoggingPlugin((msg, data) => {
|
|
2938
|
+
const dataSuffix = data ? ` ${JSON.stringify(data)}` : "";
|
|
2939
|
+
logger.info(`${msg}${dataSuffix}`);
|
|
2940
|
+
}));
|
|
2941
|
+
plugins.push(...effectiveOptions.plugins);
|
|
2942
|
+
let onSessionExpired;
|
|
2943
|
+
if (effectiveOptions.autoReauth && session.auth.method === "cookie" && session.auth.plugin) {
|
|
2944
|
+
let currentSession = session;
|
|
2945
|
+
let refreshAttempts = 0;
|
|
2946
|
+
const MAX_REFRESH_ATTEMPTS = 1;
|
|
2947
|
+
onSessionExpired = async () => {
|
|
2948
|
+
refreshAttempts++;
|
|
2949
|
+
if (refreshAttempts > MAX_REFRESH_ATTEMPTS) {
|
|
2950
|
+
const error = /* @__PURE__ */ new Error(`Maximum refresh attempts (${MAX_REFRESH_ATTEMPTS}) exceeded`);
|
|
2951
|
+
console.error("❌ Auto-refresh failed: Too many attempts");
|
|
2952
|
+
const sidArg = effectiveOptions.sid ? ` --sid=${effectiveOptions.sid}` : "";
|
|
2953
|
+
console.error(`💡 Run "npx adt auth login${sidArg}" to re-authenticate manually`);
|
|
2954
|
+
throw error;
|
|
2955
|
+
}
|
|
2956
|
+
progress.step(`🔄 Session expired, refreshing credentials for ${currentSession.sid}... (attempt ${refreshAttempts}/${MAX_REFRESH_ATTEMPTS})`);
|
|
2957
|
+
try {
|
|
2958
|
+
const refreshedSession = await refreshCredentials(currentSession, { log: progress.persist });
|
|
2959
|
+
if (!refreshedSession) throw new Error("Refresh returned null");
|
|
2960
|
+
currentSession = refreshedSession;
|
|
2961
|
+
const creds = currentSession.auth.credentials;
|
|
2962
|
+
const newCookie = decodeURIComponent(creds.cookies);
|
|
2963
|
+
progress.clear();
|
|
2964
|
+
return newCookie;
|
|
2965
|
+
} catch (error) {
|
|
2966
|
+
progress.done("❌ Auto-refresh failed");
|
|
2967
|
+
console.error("❌ Auto-refresh failed:", error instanceof Error ? error.message : String(error));
|
|
2968
|
+
const sidArg = effectiveOptions.sid ? ` --sid=${effectiveOptions.sid}` : "";
|
|
2969
|
+
console.error(`💡 Run "npx adt auth login${sidArg}" to re-authenticate manually`);
|
|
2970
|
+
throw error;
|
|
2971
|
+
}
|
|
2972
|
+
};
|
|
2973
|
+
}
|
|
2974
|
+
const adtClient = createAdtClient({
|
|
2975
|
+
baseUrl,
|
|
2976
|
+
username,
|
|
2977
|
+
password,
|
|
2978
|
+
cookieHeader,
|
|
2979
|
+
authorizationHeader,
|
|
2980
|
+
client,
|
|
2981
|
+
logger,
|
|
2982
|
+
plugins,
|
|
2983
|
+
onSessionExpired,
|
|
2984
|
+
headersTimeoutMs
|
|
2985
|
+
});
|
|
2986
|
+
if (!isAdkInitialized()) initializeAdk(adtClient, { lockStore: new FileLockStore() });
|
|
2987
|
+
return adtClient;
|
|
2988
|
+
}
|
|
2989
|
+
/**
|
|
2990
|
+
* Same contract as {@link getAdtClientV2}, but on any authentication /
|
|
2991
|
+
* credential failure throws a typed {@link AdtAuthError} instead of
|
|
2992
|
+
* writing to stderr and calling `process.exit(1)`.
|
|
2993
|
+
*
|
|
2994
|
+
* Use this from long-running processes (HTTP servers, MCP daemons) where
|
|
2995
|
+
* `process.exit` would tear down unrelated connections.
|
|
2996
|
+
*
|
|
2997
|
+
* @throws {AdtAuthError} when the session is missing, expired without a
|
|
2998
|
+
* refresh plugin, refresh fails, or the configured auth method is
|
|
2999
|
+
* unsupported.
|
|
3000
|
+
*/
|
|
3001
|
+
async function getAdtClientV2Safe(options) {
|
|
3002
|
+
const testOverride = __getActiveTestAdtClient();
|
|
3003
|
+
if (testOverride) return testOverride;
|
|
3004
|
+
const adtHeadersTimeout = resolveAdtHeadersTimeoutMs();
|
|
3005
|
+
const ctx = getCliContext();
|
|
3006
|
+
const effectiveOptions = {
|
|
3007
|
+
sid: options?.sid ?? ctx.sid,
|
|
3008
|
+
logger: options?.logger ?? ctx.logger,
|
|
3009
|
+
logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,
|
|
3010
|
+
logOutput: options?.logOutput ?? ctx.logOutput ?? "./tmp/logs",
|
|
3011
|
+
enableLogging: options?.enableLogging,
|
|
3012
|
+
writeMetadata: options?.writeMetadata ?? false,
|
|
3013
|
+
capture: options?.capture ?? false,
|
|
3014
|
+
plugins: options?.plugins ?? [],
|
|
3015
|
+
autoReauth: options?.autoReauth ?? true,
|
|
3016
|
+
verbose: options?.verbose ?? ctx.verbose
|
|
3017
|
+
};
|
|
3018
|
+
const logger = effectiveOptions.logger ?? (effectiveOptions.enableLogging ? consoleLogger : silentLogger);
|
|
3019
|
+
let session = loadAuthSession(effectiveOptions.sid);
|
|
3020
|
+
if (!session) {
|
|
3021
|
+
const sidSuffix = effectiveOptions.sid ? ` for SID ${effectiveOptions.sid}` : "";
|
|
3022
|
+
const sidFlag = effectiveOptions.sid ? ` --sid=${effectiveOptions.sid}` : "";
|
|
3023
|
+
throw new AdtAuthError("NO_SESSION", `Not authenticated${sidSuffix}. Run "adt auth login${sidFlag}" first.`, effectiveOptions.sid);
|
|
3024
|
+
}
|
|
3025
|
+
setAdtSystem(session.sid);
|
|
3026
|
+
const baseUrl = session.host;
|
|
3027
|
+
const client = session.client;
|
|
3028
|
+
let username;
|
|
3029
|
+
let password;
|
|
3030
|
+
let cookieHeader;
|
|
3031
|
+
let authorizationHeader;
|
|
3032
|
+
if (session.auth.method === "basic") {
|
|
3033
|
+
const creds = session.auth.credentials;
|
|
3034
|
+
username = creds.username;
|
|
3035
|
+
password = creds.password;
|
|
3036
|
+
} else if (session.auth.method === "cookie") {
|
|
3037
|
+
if (isExpired(session)) session = await tryAutoRefreshSafe(session, effectiveOptions.sid);
|
|
3038
|
+
const creds = session.auth.credentials;
|
|
3039
|
+
const rawCookies = decodeURIComponent(creds.cookies);
|
|
3040
|
+
if (rawCookies.startsWith("Authorization: ")) authorizationHeader = rawCookies.substring(15);
|
|
3041
|
+
else cookieHeader = rawCookies;
|
|
3042
|
+
} else throw new AdtAuthError("UNSUPPORTED_AUTH_METHOD", `Unsupported auth method: ${session.auth.method}`, effectiveOptions.sid);
|
|
3043
|
+
const plugins = [];
|
|
3044
|
+
if (effectiveOptions.capture) {
|
|
3045
|
+
resetCaptured();
|
|
3046
|
+
plugins.push({
|
|
3047
|
+
name: "capture",
|
|
3048
|
+
process: (context) => {
|
|
3049
|
+
setCaptured({
|
|
3050
|
+
xml: context.rawText,
|
|
3051
|
+
json: context.parsedData
|
|
3052
|
+
});
|
|
3053
|
+
return context.parsedData;
|
|
3054
|
+
}
|
|
3055
|
+
});
|
|
3056
|
+
}
|
|
3057
|
+
if (effectiveOptions.logResponseFiles) plugins.push(new FileLoggingPlugin({
|
|
3058
|
+
outputDir: effectiveOptions.logOutput,
|
|
3059
|
+
writeMetadata: effectiveOptions.writeMetadata,
|
|
3060
|
+
logger
|
|
3061
|
+
}));
|
|
3062
|
+
if (effectiveOptions.enableLogging) plugins.push(new LoggingPlugin((msg, data) => {
|
|
3063
|
+
const dataSuffix = data ? ` ${JSON.stringify(data)}` : "";
|
|
3064
|
+
logger.info(`${msg}${dataSuffix}`);
|
|
3065
|
+
}));
|
|
3066
|
+
plugins.push(...effectiveOptions.plugins);
|
|
3067
|
+
let onSessionExpired;
|
|
3068
|
+
if (effectiveOptions.autoReauth && session.auth.method === "cookie" && session.auth.plugin) {
|
|
3069
|
+
let currentSession = session;
|
|
3070
|
+
let refreshAttempts = 0;
|
|
3071
|
+
const MAX_REFRESH_ATTEMPTS = 1;
|
|
3072
|
+
onSessionExpired = async () => {
|
|
3073
|
+
refreshAttempts++;
|
|
3074
|
+
if (refreshAttempts > MAX_REFRESH_ATTEMPTS) {
|
|
3075
|
+
const sidSuffix = effectiveOptions.sid ? ` for SID ${effectiveOptions.sid}` : "";
|
|
3076
|
+
throw new AdtAuthError("MAX_REFRESH_ATTEMPTS", `Maximum refresh attempts (${MAX_REFRESH_ATTEMPTS}) exceeded${sidSuffix}.`, effectiveOptions.sid);
|
|
3077
|
+
}
|
|
3078
|
+
try {
|
|
3079
|
+
const refreshedSession = await refreshCredentials(currentSession, { log: () => {} });
|
|
3080
|
+
if (!refreshedSession) throw new Error("Refresh returned null");
|
|
3081
|
+
currentSession = refreshedSession;
|
|
3082
|
+
const creds = currentSession.auth.credentials;
|
|
3083
|
+
return decodeURIComponent(creds.cookies);
|
|
3084
|
+
} catch (error) {
|
|
3085
|
+
if (error instanceof AdtAuthError) throw error;
|
|
3086
|
+
const sidSuffix = effectiveOptions.sid ? ` for SID ${effectiveOptions.sid}` : "";
|
|
3087
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
3088
|
+
throw new AdtAuthError("REFRESH_FAILED", `Auto-refresh failed${sidSuffix}: ${errMsg}`, effectiveOptions.sid);
|
|
3089
|
+
}
|
|
3090
|
+
};
|
|
3091
|
+
}
|
|
3092
|
+
const adtClient = createAdtClient({
|
|
3093
|
+
baseUrl,
|
|
3094
|
+
username,
|
|
3095
|
+
password,
|
|
3096
|
+
cookieHeader,
|
|
3097
|
+
authorizationHeader,
|
|
3098
|
+
client,
|
|
3099
|
+
logger,
|
|
3100
|
+
plugins,
|
|
3101
|
+
onSessionExpired,
|
|
3102
|
+
headersTimeoutMs: adtHeadersTimeout
|
|
3103
|
+
});
|
|
3104
|
+
if (!isAdkInitialized()) initializeAdk(adtClient, { lockStore: new FileLockStore() });
|
|
3105
|
+
return adtClient;
|
|
3106
|
+
}
|
|
3107
|
+
|
|
3108
|
+
//#endregion
|
|
3109
|
+
export { AdtAuthError, AdtLink, BadiService, ChangesetService, CheckService, CheckinService, ClassicBadiService, CtsTransportLifecycleService, CtsTransportMetadataService, DEFAULT_CHECK_SOURCE_VERSION, ExactSourceHistoryService, ExactSourceHistoryServiceError, GetSourceTooLargeError, ImportService, PackageLink, __getTestAdtClient, __setTestAdtClient, adtLink, applyPlan, buildPlan, classifyTier, clearConfigCache, consoleLogger, createChangeset, createProgressReporter, diffObject, flattenPlanObjects, getAdtClientV2, getAdtClientV2Safe, getAdtSystem, getAuthManager, getBadiInfo, getCaptured, getCliContext, getConfig, getDefaultSid, getDestination, getLockService, getSource, hasDestination, hyperlink, isExpired, link, listAvailableSids, listDestinations, loadAuthSession, loadFormatPlugin, lockStore, normalizeClassicBadiMetadata, normalizeSearchResults, packageLink, parseEnhancementImplementation, parseFormatSpec, parseTransportNumbers, refreshCredentials, resetCaptured, resetCliContext, resolveAdtHeadersTimeoutMs, resolveConnectionClient, resolveObjectUri, resolvePackageForFormatId, saveAuthSession, setAdtSystem, setCaptured, setCliContext, setDefaultSid, silentLogger, toMetadataOnlySourceVersionListing, toMetadataOnlyTransportSourceManifest };
|
|
3110
|
+
//# sourceMappingURL=index.mjs.map
|