@abapify/adt-export 0.4.34 → 0.4.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,870 @@
1
+ import { a as createFileTree, n as FilteredFileTree, o as findAbapGitRoot, s as resolveFilesRelativeToRoot, t as loadFormatPlugin } from "./format-plugin-DeQBEqwE.mjs";
2
+ import { AdkObjectSet, AdkPackage, tryGetGlobalContext } from "@abapify/adk";
3
+ import { FileLockStore, createLockService } from "@abapify/adt-locks";
4
+ // src/commands/export-collect.ts
5
+ /** Target package of an object, as assigned by the format plugin. */
6
+ function getTargetPackageName(obj) {
7
+ return obj._data?.packageRef?.name;
8
+ }
9
+ /**
10
+ * Early check: PREFIX folder logic requires an explicit --package flag.
11
+ * Fail before scanning files / loading plugins / authenticating with SAP.
12
+ */
13
+ async function checkPrefixFolderLogic(sourcePath, options, ctx) {
14
+ if (options.package) return;
15
+ const { readFileSync, existsSync } = await import("node:fs");
16
+ const { join } = await import("node:path");
17
+ const abapGitXmlPath = join(sourcePath, ".abapgit.xml");
18
+ if (!existsSync(abapGitXmlPath)) return;
19
+ const xml = readFileSync(abapGitXmlPath, "utf-8");
20
+ const { parseAbapGitMetadata } = await import("@abapify/adt-plugin-abapgit");
21
+ const { folderLogic } = parseAbapGitMetadata(xml);
22
+ if (folderLogic === "prefix") {
23
+ ctx.logger.error("❌ Root package is required for PREFIX folder logic.");
24
+ ctx.logger.info(" Use -p <PACKAGE> to specify the root ABAP package.");
25
+ ctx.logger.info(" Example: npx adt export -p ZABAPGIT_EXAMPLES");
26
+ process.exit(1);
27
+ }
28
+ }
29
+ /** Group object names by their target package. */
30
+ function groupObjectNamesByPackage(objectSet) {
31
+ const pkgMap = /* @__PURE__ */ new Map();
32
+ for (const obj of objectSet) {
33
+ const pkgName = getTargetPackageName(obj);
34
+ if (!pkgName) continue;
35
+ const names = pkgMap.get(pkgName);
36
+ if (names) names.push(obj.name);
37
+ else pkgMap.set(pkgName, [obj.name]);
38
+ }
39
+ return pkgMap;
40
+ }
41
+ /** Log package assignments (resolved by the format plugin). */
42
+ function logPackageAssignments(objectSet, effectiveRootPackage, ctx) {
43
+ const pkgMap = groupObjectNamesByPackage(objectSet);
44
+ if (pkgMap.size > 0) {
45
+ ctx.logger.info(`📦 Package resolution: ${effectiveRootPackage}`);
46
+ for (const [pkg, objects] of pkgMap) if (pkg !== effectiveRootPackage) ctx.logger.info(` 📁 ${pkg}: ${objects.join(", ")}`);
47
+ }
48
+ }
49
+ /**
50
+ * Derive the effective root package: either explicit --package or resolved
51
+ * from objects that already have packageRef (e.g., from .abapgit.xml).
52
+ *
53
+ * When --package is provided, it's used as the root for folder logic.
54
+ * When omitted, we look at objects that already have packageRef from the
55
+ * format plugin and pick the shortest (= root-most) one.
56
+ */
57
+ /** True when `pkgName` sits closer to the root than `current` (shorter name). */
58
+ function isRootMostPackage(current, pkgName) {
59
+ return !current || pkgName.length < current.length;
60
+ }
61
+ /** Root-most (shortest) package name referenced by the object set. */
62
+ function findRootMostPackage(objectSet) {
63
+ let rootMost;
64
+ for (const obj of objectSet) {
65
+ const pkgName = getTargetPackageName(obj);
66
+ if (pkgName && isRootMostPackage(rootMost, pkgName)) rootMost = pkgName;
67
+ }
68
+ return rootMost;
69
+ }
70
+ function resolveEffectiveRootPackage(objectSet, options, ctx) {
71
+ const effectiveRootPackage = options.package || findRootMostPackage(objectSet);
72
+ if (effectiveRootPackage) logPackageAssignments(objectSet, effectiveRootPackage, ctx);
73
+ return effectiveRootPackage;
74
+ }
75
+ /** Parse the comma-separated --types filter into normalized type names. */
76
+ function parseObjectTypesFilter(types) {
77
+ return types ? types.split(",").map((t) => t.trim().toUpperCase()) : void 0;
78
+ }
79
+ /** Build the ADK context, reusing the global lock service when available. */
80
+ function createAdkContext(client) {
81
+ const globalCtx = tryGetGlobalContext();
82
+ const lockStore = globalCtx?.lockStore ?? new FileLockStore();
83
+ return {
84
+ client,
85
+ lockStore,
86
+ lockService: globalCtx?.lockService ?? createLockService(client, { store: lockStore })
87
+ };
88
+ }
89
+ /** Match full type (CLAS/OC) or prefix (CLAS). */
90
+ function matchesObjectType(objType, objectTypes) {
91
+ const upper = objType.toUpperCase();
92
+ const prefix = upper.split("/")[0];
93
+ return objectTypes.includes(upper) || objectTypes.includes(prefix);
94
+ }
95
+ /** Build the --types filter callback for AdkObjectSet.fromGenerator. */
96
+ function createTypeFilter(objectTypes, result) {
97
+ if (!objectTypes) return void 0;
98
+ return (obj) => {
99
+ const included = matchesObjectType(obj.type, objectTypes);
100
+ if (!included) {
101
+ result.skipped++;
102
+ result.objects.push({
103
+ type: obj.type,
104
+ name: obj.name,
105
+ status: "skipped"
106
+ });
107
+ }
108
+ return included;
109
+ };
110
+ }
111
+ /**
112
+ * Load the format plugin, scan the file tree and collect the export
113
+ * objects into an AdkObjectSet (applying the optional type filter).
114
+ * Returns `null` when nothing survives filtering.
115
+ */
116
+ async function collectExportObjects(fileTree, options, result, ctx) {
117
+ const objectTypes = parseObjectTypesFilter(options.types);
118
+ ctx.logger.info(`📦 Loading format plugin: ${options.format}...`);
119
+ const plugin = await loadFormatPlugin(options.format);
120
+ if (!plugin.format.export) {
121
+ ctx.logger.error(`❌ Plugin '${plugin.name}' does not support export`);
122
+ ctx.logger.info(" The plugin needs to implement format.export(fileTree) generator");
123
+ process.exit(1);
124
+ }
125
+ const client = await ctx.getAdtClient();
126
+ const adkContext = createAdkContext(client);
127
+ ctx.logger.info("🔍 Scanning files and building object tree...");
128
+ const exportOptions = {
129
+ rootPackage: options.package,
130
+ abapLanguageVersion: options.abapLanguageVersion
131
+ };
132
+ const objectSet = await AdkObjectSet.fromGenerator(plugin.format.export(fileTree, client, exportOptions), adkContext, {
133
+ filter: createTypeFilter(objectTypes, result),
134
+ onObject: (obj) => {
135
+ result.discovered++;
136
+ ctx.logger.info(` 📄 ${obj.kind} ${obj.name}`);
137
+ }
138
+ });
139
+ result.discovered += result.skipped;
140
+ if (objectSet.isEmpty) {
141
+ ctx.logger.warn("⚠️ No objects to export after filtering");
142
+ return null;
143
+ }
144
+ return {
145
+ client,
146
+ adkContext,
147
+ objectSet
148
+ };
149
+ }
150
+ /**
151
+ * Resolve source/files, run the early PREFIX check and build the
152
+ * (filtered) export file tree.
153
+ */
154
+ async function prepareExportFiles(options, ctx) {
155
+ const specificFiles = options.files && options.files.length > 0 ? options.files : void 0;
156
+ let sourcePath = options.source;
157
+ if (specificFiles) {
158
+ const repoRoot = findAbapGitRoot(ctx.cwd);
159
+ if (!repoRoot) {
160
+ ctx.logger.error("❌ No .abapgit.xml found in any parent directory.");
161
+ ctx.logger.error(" Run this command from within an abapGit repository.");
162
+ process.exit(1);
163
+ }
164
+ sourcePath = repoRoot;
165
+ }
166
+ await checkPrefixFolderLogic(sourcePath, options, ctx);
167
+ ctx.logger.info("🚀 Starting export...");
168
+ ctx.logger.info(`📁 Source: ${sourcePath}`);
169
+ ctx.logger.info(`🎯 Format: ${options.format}`);
170
+ if (specificFiles) ctx.logger.info(`📄 Files: ${specificFiles.join(", ")}`);
171
+ if (options.transport) ctx.logger.info(`🚚 Transport: ${options.transport}`);
172
+ if (options.package) ctx.logger.info(`📦 Package: ${options.package}`);
173
+ if (options.dryRun) ctx.logger.info(`🔍 Mode: Dry run (no changes)`);
174
+ const fullFileTree = createFileTree(sourcePath);
175
+ let fileTree = fullFileTree;
176
+ if (specificFiles) {
177
+ const relFiles = resolveFilesRelativeToRoot(specificFiles, ctx.cwd, sourcePath);
178
+ fileTree = new FilteredFileTree(fullFileTree, relFiles);
179
+ }
180
+ return { fileTree };
181
+ }
182
+ // src/commands/export-deploy.ts
183
+ /**
184
+ * Display export results in console
185
+ */
186
+ function displayExportResults(result, logger) {
187
+ if (result.discovered === 0) {
188
+ logger.warn("⚠️ No objects found to export");
189
+ return;
190
+ }
191
+ logger.info("\n📊 Export Results:");
192
+ logger.info(` 📦 Discovered: ${result.discovered}`);
193
+ if (result.saved > 0) logger.info(` 💾 Saved: ${result.saved}`);
194
+ if (result.activated > 0) logger.info(` ✅ Activated: ${result.activated}`);
195
+ if (result.skipped > 0) logger.info(` ⏭️ Skipped: ${result.skipped}`);
196
+ if (result.failed > 0) logger.error(` ❌ Failed: ${result.failed}`);
197
+ const failed = result.objects.filter((o) => o.status === "failed");
198
+ if (failed.length > 0) {
199
+ logger.error("\n❌ Failed objects:");
200
+ for (const obj of failed.slice(0, 5)) logger.error(` ${obj.type} ${obj.name}: ${obj.error || "unknown error"}`);
201
+ if (failed.length > 5) logger.error(` ... (${failed.length - 5} more)`);
202
+ }
203
+ }
204
+ /**
205
+ * Verify that deployed objects ended up in the expected SAP packages.
206
+ *
207
+ * Reloads each object from SAP and compares its current package
208
+ * against the target package resolved from the abapGit folder structure.
209
+ */
210
+ async function verifyPackageAssignments(objectSet, logger) {
211
+ const verification = {
212
+ total: 0,
213
+ correct: 0,
214
+ mismatched: 0,
215
+ errors: 0,
216
+ details: []
217
+ };
218
+ for (const obj of objectSet) {
219
+ const targetPkg = obj._data?.packageRef?.name;
220
+ if (!targetPkg) continue;
221
+ verification.total++;
222
+ const detail = {
223
+ type: obj.type,
224
+ name: obj.name,
225
+ expectedPackage: targetPkg,
226
+ status: "error"
227
+ };
228
+ try {
229
+ await obj.load();
230
+ const actualPkg = obj.package;
231
+ detail.actualPackage = actualPkg ?? "";
232
+ if (actualPkg === targetPkg) {
233
+ detail.status = "correct";
234
+ verification.correct++;
235
+ } else {
236
+ detail.status = "mismatched";
237
+ verification.mismatched++;
238
+ logger.warn(` ⚠️ ${obj.name}: expected ${targetPkg}, got ${actualPkg ?? "(none)"}`);
239
+ }
240
+ } catch (err) {
241
+ detail.status = "error";
242
+ detail.error = err instanceof Error ? err.message : String(err);
243
+ verification.errors++;
244
+ logger.warn(` ⚠️ ${obj.name}: verification failed — ${detail.error}`);
245
+ }
246
+ verification.details.push(detail);
247
+ }
248
+ return verification;
249
+ }
250
+ /**
251
+ * Display verification results in console
252
+ */
253
+ function displayVerificationResults(verification, logger) {
254
+ logger.info(`\n📋 Package Verification Results:`);
255
+ logger.info(` Total: ${verification.total}`);
256
+ logger.info(` ✅ Correct: ${verification.correct}`);
257
+ if (verification.mismatched > 0) logger.error(` ❌ Mismatched: ${verification.mismatched}`);
258
+ if (verification.errors > 0) logger.warn(` ⚠️ Errors: ${verification.errors}`);
259
+ const mismatches = verification.details.filter((d) => d.status === "mismatched");
260
+ if (mismatches.length > 0) {
261
+ logger.error("\n❌ Package mismatches:");
262
+ for (const m of mismatches) logger.error(` ${m.type} ${m.name}: expected ${m.expectedPackage}, got ${m.actualPackage ?? "(none)"}`);
263
+ }
264
+ }
265
+ /** Map deploy save results onto the export result and log unchanged objects. */
266
+ function mapSaveResults(save, result, ctx) {
267
+ result.saved = save.success;
268
+ result.failed = save.failed;
269
+ for (const r of save.results) if (r.unchanged) {
270
+ result.skipped++;
271
+ result.objects.push({
272
+ type: r.object.type,
273
+ name: r.object.name,
274
+ status: "skipped",
275
+ error: "unchanged"
276
+ });
277
+ } else result.objects.push({
278
+ type: r.object.type,
279
+ name: r.object.name,
280
+ status: r.success ? "saved" : "failed",
281
+ error: r.error
282
+ });
283
+ if (save.unchanged > 0) {
284
+ const unchangedNames = save.results.filter((r) => r.unchanged).map((r) => r.object.name);
285
+ ctx.logger.info(`\n⏭️ ${save.unchanged} unchanged: ${unchangedNames.join(", ")}`);
286
+ }
287
+ }
288
+ /** Map activation results onto the export result. */
289
+ function mapActivationResults(activation, result, ctx) {
290
+ result.activated = activation.success;
291
+ if (activation.success > 0) ctx.logger.info(`\n✅ ${activation.success} objects activated`);
292
+ if (activation.failed > 0) {
293
+ ctx.logger.warn(`⚠️ ${activation.failed} objects failed activation`);
294
+ for (const msg of activation.messages) ctx.logger.warn(` ${msg}`);
295
+ }
296
+ }
297
+ /** Deploy the object set (or dry-run) and map the results. */
298
+ async function deployAndMapResults(objectSet, options, result, ctx) {
299
+ if (options.dryRun) {
300
+ for (const obj of objectSet) result.objects.push({
301
+ type: obj.type,
302
+ name: obj.name,
303
+ status: "saved"
304
+ });
305
+ result.saved = objectSet.size;
306
+ ctx.logger.info(`\n🔍 Dry run: ${objectSet.size} objects would be saved`);
307
+ return;
308
+ }
309
+ ctx.logger.info(`\n� Deploying ${objectSet.size} objects...`);
310
+ const deployResult = await objectSet.deploy({
311
+ transport: options.transport,
312
+ activate: options.activate,
313
+ mode: "upsert",
314
+ onProgress: (saved, total, obj) => {
315
+ if (obj._unchanged) ctx.logger.info(` ⏭️ [${saved}/${total}] ${obj.kind} ${obj.name} (unchanged)`);
316
+ else ctx.logger.info(` 💾 [${saved}/${total}] ${obj.kind} ${obj.name}`);
317
+ }
318
+ });
319
+ mapSaveResults(deployResult.save, result, ctx);
320
+ if (deployResult.activation) mapActivationResults(deployResult.activation, result, ctx);
321
+ }
322
+ // src/commands/export-packages.ts
323
+ /**
324
+ * Subpackage preparation for the export command: create missing subpackages,
325
+ * fix wrong super-package references and activate the fixed packages.
326
+ */
327
+ /** Rewrite the `<pak:superPackage .../>` tag attributes (ReDoS-free scan). */
328
+ function rewriteSuperPackageTag(xml, expectedSuper) {
329
+ const tagStart = xml.indexOf("<pak:superPackage");
330
+ if (tagStart === -1) return xml;
331
+ const tagEnd = xml.indexOf(">", tagStart);
332
+ if (tagEnd === -1) return xml;
333
+ const before = xml.slice(0, tagStart);
334
+ const tag = xml.slice(tagStart, tagEnd + 1);
335
+ const after = xml.slice(tagEnd + 1);
336
+ const replaceAttr = (src, attr, newValue) => {
337
+ const needle = `${attr}="`;
338
+ const a = src.indexOf(needle);
339
+ if (a === -1) return src;
340
+ const valStart = a + needle.length;
341
+ const valEnd = src.indexOf("\"", valStart);
342
+ if (valEnd === -1) return src;
343
+ return src.slice(0, valStart) + newValue + src.slice(valEnd);
344
+ };
345
+ let newTag = replaceAttr(tag, "adtcore:name", expectedSuper);
346
+ newTag = replaceAttr(newTag, "adtcore:uri", `/sap/bc/adt/packages/${expectedSuper.toLowerCase()}`);
347
+ return before + newTag + after;
348
+ }
349
+ /**
350
+ * Fix a wrong super package of an existing subpackage (e.g. from a prior
351
+ * buggy deploy) using the raw SAP ADT sequence:
352
+ * 1. LOCK (accessMode=MODIFY)
353
+ * 2. GET ?version=inactive
354
+ * 3. PUT ?lockHandle=... (with modified superPackage)
355
+ * 4. UNLOCK ?lockHandle=...
356
+ */
357
+ async function fixSuperPackage(plan, context, options) {
358
+ const { client, adkContext, ctx } = context;
359
+ const { pkgName, expectedSuper } = plan;
360
+ const pkgUri = `/sap/bc/adt/packages/${encodeURIComponent(pkgName)}`;
361
+ const acceptHeader = "application/vnd.sap.adt.packages.v2+xml, application/vnd.sap.adt.packages.v1+xml";
362
+ if (options.unlock) try {
363
+ const lockSvc = adkContext.lockService;
364
+ if (lockSvc) await lockSvc.forceUnlock(pkgUri);
365
+ } catch {}
366
+ const lockSvc = adkContext.lockService;
367
+ if (!lockSvc) throw new Error("lockService not available in context");
368
+ const lockHandle = (await lockSvc.lock(pkgUri, {
369
+ transport: options.transport,
370
+ objectName: pkgName,
371
+ objectType: "DEVC/K"
372
+ })).handle;
373
+ try {
374
+ const modifiedXml = rewriteSuperPackageTag(await client.fetch(`${pkgUri}?version=inactive`, {
375
+ method: "GET",
376
+ headers: { Accept: acceptHeader }
377
+ }), expectedSuper);
378
+ await client.fetch(`${pkgUri}?lockHandle=${encodeURIComponent(lockHandle)}`, {
379
+ method: "PUT",
380
+ headers: {
381
+ "Content-Type": "application/vnd.sap.adt.packages.v2+xml",
382
+ Accept: acceptHeader
383
+ },
384
+ body: modifiedXml
385
+ });
386
+ ctx.logger.info(` ✅ Fixed ${pkgName}`);
387
+ } finally {
388
+ try {
389
+ await lockSvc.unlock(pkgUri, { lockHandle });
390
+ } catch {}
391
+ }
392
+ }
393
+ /** Responsible inherited from the root package ('' when none). */
394
+ function inheritedResponsible(rootPkg) {
395
+ return rootPkg?.dataSync?.responsible ?? "";
396
+ }
397
+ /** The authenticated user, upper-cased (SAP's responsible format). */
398
+ function authenticatedUser(client) {
399
+ return client.username?.toUpperCase?.() ?? "";
400
+ }
401
+ /**
402
+ * Use root package's responsible, but fall back to the
403
+ * authenticated user when root is a system package like $TMP
404
+ * (whose responsible is 'SAP', which SAP rejects on creation).
405
+ */
406
+ function resolveResponsible(rootPkg, client) {
407
+ const responsible = inheritedResponsible(rootPkg);
408
+ return responsible !== "" && responsible.toUpperCase() !== "SAP" ? responsible : authenticatedUser(client);
409
+ }
410
+ /** True for common create failures where the hint below is actionable. */
411
+ function isActionableCreateError(errMsg) {
412
+ return [
413
+ "409",
414
+ "change request",
415
+ "authorization"
416
+ ].some((hint) => errMsg.includes(hint));
417
+ }
418
+ /** Log a failed AdkPackage.create; true when the package exists after all. */
419
+ async function handleCreateFailure(pkgName, createErr, context) {
420
+ const { adkContext, ctx } = context;
421
+ const errMsg = createErr instanceof Error ? createErr.message : String(createErr);
422
+ if (await AdkPackage.exists(pkgName, adkContext)) {
423
+ ctx.logger.info(` ✅ ${pkgName} already exists`);
424
+ return true;
425
+ }
426
+ ctx.logger.warn(` ⚠️ Failed to create ${pkgName}: ${errMsg}`);
427
+ if (isActionableCreateError(errMsg)) ctx.logger.warn(` 💡 Hint: Use -t <transport> for non-local packages, or -p '$TMP' for local development`);
428
+ return false;
429
+ }
430
+ /**
431
+ * Create a missing subpackage under `expectedSuper`, inheriting software
432
+ * component / transport layer / responsible from the root package.
433
+ * Returns true when the package is known to exist afterwards.
434
+ */
435
+ async function createSubpackage(plan, context, options) {
436
+ const { client, adkContext, ctx } = context;
437
+ const { pkgName, expectedSuper, rootPkg, transportConfig } = plan;
438
+ ctx.logger.info(` 📦 Creating subpackage ${pkgName} (in ${expectedSuper})...`);
439
+ try {
440
+ await AdkPackage.create(pkgName, {
441
+ description: pkgName,
442
+ responsible: resolveResponsible(rootPkg, client),
443
+ superPackage: { name: expectedSuper },
444
+ attributes: {
445
+ packageType: "development",
446
+ ...options.abapLanguageVersion ? { languageVersion: options.abapLanguageVersion } : {}
447
+ },
448
+ ...transportConfig ? { transport: transportConfig } : {}
449
+ }, { transport: options.transport }, adkContext);
450
+ ctx.logger.info(` ✅ Created ${pkgName}`);
451
+ return true;
452
+ } catch (createErr) {
453
+ return handleCreateFailure(pkgName, createErr, context);
454
+ }
455
+ }
456
+ /** Activate fixed packages so changes move from inactive → active. */
457
+ async function activateFixedPackages(fixedPackages, context) {
458
+ const { client, ctx } = context;
459
+ const activationXml = `<?xml version="1.0" encoding="UTF-8"?>\n<adtcore:objectReferences xmlns:adtcore="http://www.sap.com/adt/core">\n${fixedPackages.map((p) => ` <adtcore:objectReference adtcore:uri="/sap/bc/adt/packages/${encodeURIComponent(p)}" adtcore:type="DEVC/K" adtcore:name="${p}"/>`).join("\n")}\n</adtcore:objectReferences>`;
460
+ try {
461
+ await client.fetch("/sap/bc/adt/activation?method=activate&preauditRequested=true", {
462
+ method: "POST",
463
+ headers: {
464
+ "Content-Type": "application/xml",
465
+ Accept: "application/xml"
466
+ },
467
+ body: activationXml
468
+ });
469
+ ctx.logger.info(` ✅ Activated ${fixedPackages.length} fixed package(s)`);
470
+ } catch (actErr) {
471
+ ctx.logger.warn(` ⚠️ Package activation failed: ${actErr instanceof Error ? actErr.message : String(actErr)}`);
472
+ }
473
+ }
474
+ /**
475
+ * Expand the leaf packages into all intermediate packages of the PREFIX
476
+ * hierarchy and sort them top-down (shorter names first).
477
+ */
478
+ function expandSubpackageHierarchy(leafPackages, effectiveRootPackage) {
479
+ const allSubPkgs = /* @__PURE__ */ new Set();
480
+ const rootPrefix = effectiveRootPackage + "_";
481
+ for (const pkg of leafPackages) {
482
+ allSubPkgs.add(pkg);
483
+ if (pkg.startsWith(rootPrefix)) {
484
+ const parts = pkg.slice(rootPrefix.length).split("_");
485
+ let current = effectiveRootPackage;
486
+ for (const part of parts) {
487
+ current += "_" + part;
488
+ allSubPkgs.add(current);
489
+ }
490
+ }
491
+ }
492
+ return [...allSubPkgs].sort((a, b) => a.length - b.length);
493
+ }
494
+ /**
495
+ * Resolve the expected super package: the longest known package that is a
496
+ * proper prefix of `pkgName` (with '_' separator).
497
+ */
498
+ function resolveExpectedSuper(knownPackages, pkgName, root) {
499
+ let expectedSuper = root;
500
+ for (const candidate of knownPackages) if (pkgName.startsWith(candidate + "_") && candidate.length > expectedSuper.length) expectedSuper = candidate;
501
+ return expectedSuper;
502
+ }
503
+ /**
504
+ * Verify the super package of an existing subpackage and fix it when wrong
505
+ * (e.g. from a prior buggy deploy). Returns true when it was fixed.
506
+ */
507
+ async function verifyAndFixSuperPackage(plan, context, options) {
508
+ const { adkContext, ctx } = context;
509
+ const { pkgName, expectedSuper } = plan;
510
+ try {
511
+ const currentSuper = (await AdkPackage.get(pkgName, adkContext)).superPackage?.name ?? "";
512
+ if (currentSuper && currentSuper !== expectedSuper) {
513
+ ctx.logger.info(` 📦 Fixing ${pkgName}: ${currentSuper} → ${expectedSuper}`);
514
+ await fixSuperPackage(plan, context, options);
515
+ return true;
516
+ }
517
+ } catch (fixErr) {
518
+ ctx.logger.warn(` ⚠️ Could not fix super package for ${pkgName}: ${fixErr instanceof Error ? fixErr.message : String(fixErr)}`);
519
+ }
520
+ return false;
521
+ }
522
+ /** Unique target subpackage names from object targets (root excluded). */
523
+ function collectLeafPackages(objectSet, effectiveRootPackage) {
524
+ const leafPackages = /* @__PURE__ */ new Set();
525
+ for (const obj of objectSet) {
526
+ const pkgName = getTargetPackageName(obj);
527
+ if (pkgName && pkgName !== effectiveRootPackage) leafPackages.add(pkgName);
528
+ }
529
+ return leafPackages;
530
+ }
531
+ /** Software component / transport layer names inherited from the root package. */
532
+ function inheritedTransportNames(rootPkg) {
533
+ const transport = rootPkg?.transport;
534
+ return {
535
+ swComp: transport?.softwareComponent?.name ?? "",
536
+ trLayer: transport?.transportLayer?.name ?? ""
537
+ };
538
+ }
539
+ /** Build the transport config for AdkPackage.create (SAP needs both fields). */
540
+ function buildTransportConfig(rootPkg) {
541
+ const { swComp, trLayer } = inheritedTransportNames(rootPkg);
542
+ if (!swComp && !trLayer) return void 0;
543
+ return {
544
+ softwareComponent: { name: swComp },
545
+ transportLayer: { name: trLayer }
546
+ };
547
+ }
548
+ /**
549
+ * Pre-deploy: ensure subpackages exist.
550
+ *
551
+ * Collect all unique target packages and create any that don't exist on the
552
+ * SAP system yet. Packages are created top-down so that parent packages
553
+ * exist before their children (correct superPackage). Wrong super package
554
+ * references on existing packages are fixed and activated.
555
+ */
556
+ async function ensureSubpackages(objectSet, effectiveRootPackage, context, options) {
557
+ const { adkContext, ctx } = context;
558
+ const leafPackages = collectLeafPackages(objectSet, effectiveRootPackage);
559
+ if (leafPackages.size === 0) return;
560
+ const sortedPkgs = expandSubpackageHierarchy(leafPackages, effectiveRootPackage);
561
+ ctx.logger.info(`\n📦 Checking ${sortedPkgs.length} subpackage(s)...`);
562
+ const rootPkg = await AdkPackage.get(effectiveRootPackage, adkContext);
563
+ const transportConfig = buildTransportConfig(rootPkg);
564
+ const knownPackages = /* @__PURE__ */ new Set([effectiveRootPackage]);
565
+ const fixedPackages = [];
566
+ for (const pkgName of sortedPkgs) {
567
+ const assignment = {
568
+ pkgName,
569
+ expectedSuper: resolveExpectedSuper(knownPackages, pkgName, effectiveRootPackage)
570
+ };
571
+ if (await AdkPackage.exists(pkgName, adkContext)) {
572
+ knownPackages.add(pkgName);
573
+ if (await verifyAndFixSuperPackage(assignment, context, options)) fixedPackages.push(pkgName);
574
+ continue;
575
+ }
576
+ if (await createSubpackage({
577
+ ...assignment,
578
+ rootPkg,
579
+ transportConfig
580
+ }, context, options)) knownPackages.add(pkgName);
581
+ }
582
+ if (fixedPackages.length > 0) await activateFixedPackages(fixedPackages, context);
583
+ }
584
+ // src/commands/export-predeploy.ts
585
+ /**
586
+ * Pre-deploy steps for the export command: root-package validation,
587
+ * subpackage preparation, cleanup of skipped/misplaced objects and
588
+ * persisted-lock recovery.
589
+ */
590
+ /** Group objects by their target subpackage (root-package objects excluded). */
591
+ function groupObjectsByPackage(objectSet, effectiveRootPackage) {
592
+ const objectsByPkg = /* @__PURE__ */ new Map();
593
+ for (const obj of objectSet) {
594
+ const pkgName = getTargetPackageName(obj);
595
+ if (pkgName && pkgName !== effectiveRootPackage) {
596
+ if (!objectsByPkg.has(pkgName)) objectsByPkg.set(pkgName, []);
597
+ objectsByPkg.get(pkgName).push(obj);
598
+ }
599
+ }
600
+ return objectsByPkg;
601
+ }
602
+ /** Name of an object's parent (function group or container), upper-cased. */
603
+ function getParentName(obj) {
604
+ const groupName = obj.groupName;
605
+ const containerName = (obj._data?.containerRef?.name)?.toUpperCase();
606
+ return groupName?.toUpperCase() ?? containerName;
607
+ }
608
+ /**
609
+ * Remove child objects whose parent was removed (e.g., function modules
610
+ * whose parent function group was skipped).
611
+ */
612
+ function removeChildrenOfRemoved(objectSet, removedNames, removedObjects) {
613
+ if (removedNames.size === 0) return;
614
+ for (const obj of [...objectSet]) {
615
+ const parentName = getParentName(obj);
616
+ if (parentName && removedNames.has(parentName)) {
617
+ objectSet.remove(obj);
618
+ removedObjects.push(`${obj.kind} ${obj.name}`);
619
+ }
620
+ }
621
+ }
622
+ /** Log every skipped object and the packages that are missing on SAP. */
623
+ function logSkippedObjects(removedObjects, unavailablePackages, ctx) {
624
+ if (removedObjects.length === 0) return;
625
+ ctx.logger.warn(`\n⚠️ Skipping ${removedObjects.length} object(s) — target package does not exist:`);
626
+ for (const name of removedObjects) ctx.logger.warn(` ⏭️ ${name}`);
627
+ for (const pkg of unavailablePackages) ctx.logger.warn(` 📦 ${pkg} — create it first, or use -p <existing-package>`);
628
+ }
629
+ /** Sub-packages that do not exist on the SAP system. */
630
+ async function findUnavailablePackages(objectsByPkg, context) {
631
+ const { adkContext } = context;
632
+ const unavailablePackages = /* @__PURE__ */ new Set();
633
+ for (const [pkgName] of objectsByPkg) if (!await AdkPackage.exists(pkgName, adkContext)) unavailablePackages.add(pkgName);
634
+ return unavailablePackages;
635
+ }
636
+ /** Remove objects targeting any of the given packages. */
637
+ function removeObjectsTargetingPackages(objectSet, packages) {
638
+ const removedObjects = [];
639
+ const removedNames = /* @__PURE__ */ new Set();
640
+ for (const obj of [...objectSet]) {
641
+ const pkgName = getTargetPackageName(obj);
642
+ if (pkgName && packages.has(pkgName)) {
643
+ objectSet.remove(obj);
644
+ removedObjects.push(`${obj.kind} ${obj.name}`);
645
+ removedNames.add(obj.name.toUpperCase());
646
+ }
647
+ }
648
+ return {
649
+ removedObjects,
650
+ removedNames
651
+ };
652
+ }
653
+ /**
654
+ * Pre-deploy: remove objects targeting unavailable packages.
655
+ *
656
+ * If subpackage creation failed and the package doesn't exist, skip all
657
+ * objects targeting it to prevent cascade failures.
658
+ */
659
+ async function skipObjectsInUnavailablePackages(objectSet, effectiveRootPackage, context) {
660
+ const { ctx } = context;
661
+ const unavailablePackages = await findUnavailablePackages(groupObjectsByPackage(objectSet, effectiveRootPackage), context);
662
+ if (unavailablePackages.size === 0) return;
663
+ const { removedObjects, removedNames } = removeObjectsTargetingPackages(objectSet, unavailablePackages);
664
+ removeChildrenOfRemoved(objectSet, removedNames, removedObjects);
665
+ logSkippedObjects(removedObjects, unavailablePackages, ctx);
666
+ }
667
+ /** Load the object's current package from SAP, keeping local _data intact. */
668
+ async function loadCurrentPackage(obj) {
669
+ const localData = obj._data;
670
+ await obj.load();
671
+ const currentPkg = obj.package;
672
+ obj._data = localData;
673
+ return currentPkg;
674
+ }
675
+ /** Delete the object and reset its state so deploy recreates it in targetPkg. */
676
+ async function deleteAndReset(obj, targetPkg, options) {
677
+ const contract = obj.crudContract;
678
+ if (!contract?.delete) return false;
679
+ const lockHandle = await obj.lock(options.transport);
680
+ await contract.delete(obj.name, {
681
+ lockHandle: lockHandle.handle,
682
+ corrNr: options.transport
683
+ });
684
+ obj._data.packageRef = { name: targetPkg };
685
+ obj._lockHandle = void 0;
686
+ return true;
687
+ }
688
+ /** Log unexpected pre-deploy check failures (404 / not found is fine). */
689
+ function logReassignCheckError(obj, err, ctx) {
690
+ const msg = err instanceof Error ? err.message : String(err);
691
+ if (!msg.includes("404") && !msg.includes("not found")) ctx.logger.warn(` ⚠️ Pre-deploy check for ${obj.name}: ${msg}`);
692
+ }
693
+ /** Delete one object that sits in the wrong package; true when deleted. */
694
+ async function reassignObjectPackage(obj, options, ctx) {
695
+ const targetPkg = getTargetPackageName(obj);
696
+ if (!targetPkg) return false;
697
+ try {
698
+ const currentPkg = await loadCurrentPackage(obj);
699
+ if (!currentPkg || currentPkg === targetPkg) return false;
700
+ ctx.logger.info(` 📦 ${obj.name}: ${currentPkg} → ${targetPkg} (will delete + recreate)`);
701
+ return await deleteAndReset(obj, targetPkg, options);
702
+ } catch (err) {
703
+ logReassignCheckError(obj, err, ctx);
704
+ return false;
705
+ }
706
+ }
707
+ /**
708
+ * Pre-deploy: delete objects in the wrong package.
709
+ *
710
+ * SAP ignores packageRef on PUT (update), so if an object already exists in
711
+ * a different package we must delete it first and let the deploy recreate
712
+ * it in the correct one.
713
+ */
714
+ async function deleteObjectsInWrongPackage(objectSet, options, ctx) {
715
+ let deletedForReassign = 0;
716
+ for (const obj of objectSet) if (await reassignObjectPackage(obj, options, ctx)) deletedForReassign++;
717
+ if (deletedForReassign > 0) ctx.logger.info(`📦 ${deletedForReassign} object(s) deleted for package reassignment`);
718
+ }
719
+ /** Pre-deploy: recover persisted object locks (--unlock). */
720
+ async function recoverPersistedLocks(objectSet, context) {
721
+ const { adkContext, ctx } = context;
722
+ ctx.logger.info(`\n🔓 --unlock: Recovering persisted locks for ${objectSet.size} objects...`);
723
+ let unlocked = 0;
724
+ const lockSvc = adkContext.lockService;
725
+ if (!lockSvc) {
726
+ ctx.logger.warn("⚠️ lockService not available — skipping persisted-lock recovery");
727
+ return;
728
+ }
729
+ for (const obj of objectSet) try {
730
+ await lockSvc.forceUnlock(obj.objectUri);
731
+ unlocked++;
732
+ } catch {}
733
+ if (unlocked > 0) ctx.logger.info(` 🔓 ${unlocked} object(s) unlocked`);
734
+ }
735
+ /** Pre-deploy: validate the root package exists on SAP. */
736
+ async function ensureRootPackageExists(effectiveRootPackage, context) {
737
+ const { adkContext, ctx } = context;
738
+ if (await AdkPackage.exists(effectiveRootPackage, adkContext)) return;
739
+ ctx.logger.error(`❌ Root package ${effectiveRootPackage} does not exist on SAP.`);
740
+ ctx.logger.info(" Create it first in ADT/Eclipse, or use -p with an existing package.");
741
+ process.exit(1);
742
+ }
743
+ /** Run every pre-deploy step (root check, packages, cleanup, unlocks). */
744
+ async function runPreDeploySteps(runtime, effectiveRootPackage, options, ctx) {
745
+ const { objectSet } = runtime;
746
+ const context = {
747
+ client: runtime.client,
748
+ adkContext: runtime.adkContext,
749
+ ctx
750
+ };
751
+ if (effectiveRootPackage && !options.dryRun) {
752
+ await ensureRootPackageExists(effectiveRootPackage, context);
753
+ await ensureSubpackages(objectSet, effectiveRootPackage, context, options);
754
+ await skipObjectsInUnavailablePackages(objectSet, effectiveRootPackage, context);
755
+ await deleteObjectsInWrongPackage(objectSet, options, ctx);
756
+ }
757
+ if (options.unlock && !options.dryRun) await recoverPersistedLocks(objectSet, context);
758
+ }
759
+ // src/commands/export.ts
760
+ /**
761
+ * Export Command Plugin
762
+ *
763
+ * Exports local serialized files to SAP system.
764
+ *
765
+ * Usage in adt.config.ts:
766
+ * ```typescript
767
+ * export default {
768
+ * commands: [
769
+ * '@abapify/adt-export/commands/export',
770
+ * ],
771
+ * };
772
+ * ```
773
+ */
774
+ const exportCommand = {
775
+ name: "export",
776
+ alias: "deploy",
777
+ description: "Export local files to SAP (deploy serialized objects)",
778
+ arguments: [{
779
+ name: "[files...]",
780
+ description: "Specific files to deploy (e.g., zage_fixed_values.doma.xml). Omit to deploy all."
781
+ }],
782
+ options: [
783
+ {
784
+ flags: "-s, --source <path>",
785
+ description: "Source directory containing serialized files",
786
+ default: "."
787
+ },
788
+ {
789
+ flags: "-f, --format <format>",
790
+ description: "Format plugin: abapgit | @abapify/adt-plugin-abapgit",
791
+ default: "abapgit"
792
+ },
793
+ {
794
+ flags: "-t, --transport <request>",
795
+ description: "Transport request for changes"
796
+ },
797
+ {
798
+ flags: "-p, --package <package>",
799
+ description: "Target package for new objects"
800
+ },
801
+ {
802
+ flags: "--types <types>",
803
+ description: "Filter by object types (comma-separated, e.g., CLAS,INTF)"
804
+ },
805
+ {
806
+ flags: "--dry-run",
807
+ description: "Validate without saving to SAP",
808
+ default: false
809
+ },
810
+ {
811
+ flags: "--activate",
812
+ description: "Activate objects after deploy (use --no-activate to skip)",
813
+ default: true
814
+ },
815
+ {
816
+ flags: "--unlock",
817
+ description: "Release locks with handles persisted by this CLI before saving",
818
+ default: false
819
+ },
820
+ {
821
+ flags: "--verify",
822
+ description: "After deploy, verify each object ended up in the correct package on SAP",
823
+ default: false
824
+ },
825
+ {
826
+ flags: "--abap-language-version <version>",
827
+ description: "ABAP language version for new objects (2=keyUser, 5=cloud). Required for BTP systems."
828
+ }
829
+ ],
830
+ async execute(args, ctx) {
831
+ const options = args;
832
+ if (!ctx.getAdtClient) {
833
+ ctx.logger.error("❌ ADT client not available. This command requires authentication.");
834
+ ctx.logger.error(" Run: adt auth login");
835
+ process.exit(1);
836
+ }
837
+ const { fileTree } = await prepareExportFiles(options, ctx);
838
+ const result = {
839
+ discovered: 0,
840
+ saved: 0,
841
+ activated: 0,
842
+ skipped: 0,
843
+ failed: 0,
844
+ objects: []
845
+ };
846
+ try {
847
+ const runtime = await collectExportObjects(fileTree, options, result, ctx);
848
+ if (!runtime) {
849
+ displayExportResults(result, ctx.logger);
850
+ return;
851
+ }
852
+ const { objectSet } = runtime;
853
+ await runPreDeploySteps(runtime, resolveEffectiveRootPackage(objectSet, options, ctx), options, ctx);
854
+ await deployAndMapResults(objectSet, options, result, ctx);
855
+ if (options.verify && !options.dryRun) {
856
+ ctx.logger.info(`\n🔍 Verifying package assignments for ${objectSet.size} objects...`);
857
+ result.verification = await verifyPackageAssignments(objectSet, ctx.logger);
858
+ displayVerificationResults(result.verification, ctx.logger);
859
+ }
860
+ } catch (error) {
861
+ ctx.logger.error(`❌ Export failed: ${error instanceof Error ? error.message : String(error)}`);
862
+ process.exit(1);
863
+ }
864
+ displayExportResults(result, ctx.logger);
865
+ if (result.failed > 0 || (result.verification?.mismatched ?? 0) > 0) process.exit(1);
866
+ }
867
+ };
868
+ export { exportCommand as t };
869
+
870
+ //# sourceMappingURL=export-Bwc4ITze.mjs.map