@abapify/adt-diff 0.4.0 → 0.4.3

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,6 @@
1
+ import { CliCommandPlugin } from "@abapify/adt-plugin";
2
+ //#region src/commands/diff.d.ts
3
+ declare const diffCommand: CliCommandPlugin;
4
+ //#endregion
5
+ export { diffCommand as default, diffCommand };
6
+ //# sourceMappingURL=diff.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff.d.mts","names":[],"sources":["../../src/commands/diff.ts"],"mappings":";;cA6wBa,aAAa"}
@@ -0,0 +1,2 @@
1
+ import { t as diffCommand } from "../diff-rq6zDvAI.mjs";
2
+ export { diffCommand as default, diffCommand };
@@ -0,0 +1,884 @@
1
+ import { getFormatPlugin, requireFormatPlugin } from "@abapify/adt-plugin";
2
+ import { AdkObject, createAdk } from "@abapify/adk";
3
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
4
+ import { glob } from "node:fs/promises";
5
+ import { basename, dirname, join, relative, resolve } from "node:path";
6
+ import { createTwoFilesPatch } from "diff";
7
+ import chalk from "chalk";
8
+ import { XMLParser } from "fast-xml-parser";
9
+ import { adtContract } from "@abapify/adt-contracts";
10
+ //#region src/lib/abapgit-to-cds.ts
11
+ /** DDIC DATATYPE → CDS abap.<type> name */
12
+ const DATATYPE_TO_CDS = {
13
+ CHAR: "char",
14
+ CLNT: "clnt",
15
+ NUMC: "numc",
16
+ DATS: "dats",
17
+ DATN: "datn",
18
+ TIMS: "tims",
19
+ TIMN: "timn",
20
+ DEC: "dec",
21
+ CURR: "curr",
22
+ QUAN: "quan",
23
+ RAW: "raw",
24
+ INT1: "int1",
25
+ INT2: "int2",
26
+ INT4: "int4",
27
+ INT8: "int8",
28
+ FLTP: "fltp",
29
+ STRG: "string",
30
+ RSTR: "rawstring",
31
+ CUKY: "cuky",
32
+ UNIT: "unit",
33
+ LANG: "lang",
34
+ ACCP: "accp",
35
+ PREC: "prec",
36
+ D16N: "d16n",
37
+ D34N: "d34n",
38
+ D16R: "d16r",
39
+ D34R: "d34r",
40
+ D16D: "d16d",
41
+ D34D: "d34d",
42
+ UTCL: "utclong",
43
+ SSTR: "sstring",
44
+ LCHR: "lchr",
45
+ LRAW: "lraw"
46
+ };
47
+ /** Types that never take a length parameter in CDS */
48
+ const NO_LENGTH_TYPES = /* @__PURE__ */ new Set([
49
+ "clnt",
50
+ "cuky",
51
+ "dats",
52
+ "datn",
53
+ "tims",
54
+ "timn",
55
+ "int1",
56
+ "int2",
57
+ "int4",
58
+ "int8",
59
+ "fltp",
60
+ "lang",
61
+ "accp",
62
+ "prec",
63
+ "d16n",
64
+ "d34n",
65
+ "d16r",
66
+ "d34r",
67
+ "utclong"
68
+ ]);
69
+ /** Types that take decimals in CDS: abap.dec(len,dec) */
70
+ const DECIMAL_TYPES = /* @__PURE__ */ new Set([
71
+ "dec",
72
+ "curr",
73
+ "quan",
74
+ "fltp",
75
+ "d16d",
76
+ "d34d"
77
+ ]);
78
+ /** Types that are variable-length (string, rawstring) — length 0 is omitted */
79
+ const VARIABLE_LENGTH_TYPES = /* @__PURE__ */ new Set(["string", "rawstring"]);
80
+ /** DD02V EXCLASS → CDS @AbapCatalog.enhancement.category */
81
+ const ENHANCEMENT_CATEGORY_REVERSE = {
82
+ "0": "#NOT_CLASSIFIED",
83
+ "1": "#NOT_EXTENSIBLE",
84
+ "2": "#EXTENSIBLE_CHARACTER_NUMERIC",
85
+ "3": "#EXTENSIBLE_CHARACTER",
86
+ "4": "#EXTENSIBLE_ANY"
87
+ };
88
+ /** DD02V CONTFLAG → CDS @AbapCatalog.deliveryClass */
89
+ const DELIVERY_CLASS_REVERSE = {
90
+ A: "#A",
91
+ C: "#C",
92
+ L: "#L",
93
+ G: "#G",
94
+ E: "#E",
95
+ S: "#S",
96
+ W: "#W"
97
+ };
98
+ /** DD02V TABCLASS → CDS @AbapCatalog.tableCategory */
99
+ const TABLE_CATEGORY_REVERSE = {
100
+ TRANSP: "#TRANSPARENT",
101
+ CLUSTER: "#CLUSTER",
102
+ POOL: "#POOL",
103
+ APPEND: "#APPEND"
104
+ };
105
+ /** DD02V MATEFLAG → CDS @AbapCatalog.dataMaintenance */
106
+ const DATA_MAINTENANCE_REVERSE = {
107
+ X: "#RESTRICTED",
108
+ N: "#NOT_ALLOWED",
109
+ "": "#ALLOWED"
110
+ };
111
+ /**
112
+ * Build CDS DDL source from DD02V header and DD03P field entries.
113
+ *
114
+ * @param dd02v - Table/structure header data
115
+ * @param dd03pEntries - Field entries (sorted by POSITION if present)
116
+ * @returns CDS DDL source string
117
+ */
118
+ function buildCdsDdl(dd02v, dd03pEntries) {
119
+ const lines = [];
120
+ const tableName = dd02v.TABNAME ?? "";
121
+ const isStructure = dd02v.TABCLASS === "INTTAB";
122
+ if (dd02v.DDTEXT) lines.push(`@EndUserText.label : '${escapeAnnotationString(dd02v.DDTEXT)}'`);
123
+ if (dd02v.EXCLASS) {
124
+ const cat = ENHANCEMENT_CATEGORY_REVERSE[dd02v.EXCLASS];
125
+ if (cat) lines.push(`@AbapCatalog.enhancement.category : ${cat}`);
126
+ }
127
+ if (!isStructure) {
128
+ if (dd02v.TABCLASS) {
129
+ const cat = TABLE_CATEGORY_REVERSE[dd02v.TABCLASS];
130
+ if (cat) lines.push(`@AbapCatalog.tableCategory : ${cat}`);
131
+ }
132
+ if (dd02v.CONTFLAG) {
133
+ const dc = DELIVERY_CLASS_REVERSE[dd02v.CONTFLAG];
134
+ if (dc) lines.push(`@AbapCatalog.deliveryClass : ${dc}`);
135
+ }
136
+ if (dd02v.MATEFLAG !== void 0) {
137
+ const dm = DATA_MAINTENANCE_REVERSE[dd02v.MATEFLAG ?? ""];
138
+ if (dm) lines.push(`@AbapCatalog.dataMaintenance : ${dm}`);
139
+ }
140
+ }
141
+ const keyword = isStructure ? "define structure" : "define table";
142
+ lines.push(`${keyword} ${tableName.toLowerCase()} {`, "");
143
+ const fieldInfos = buildFieldInfos([...dd03pEntries].sort((a, b) => {
144
+ return Number.parseInt(a.POSITION ?? "0", 10) - Number.parseInt(b.POSITION ?? "0", 10);
145
+ }), tableName);
146
+ const maxNameWidth = Math.max(...fieldInfos.filter((f) => f.kind === "field").map((f) => f.prefix.length), 0);
147
+ for (const info of fieldInfos) if (info.kind === "include") {
148
+ if (info.suffix) lines.push(` include ${info.name} with suffix ${info.suffix};`);
149
+ else lines.push(` include ${info.name};`);
150
+ } else {
151
+ for (const ann of info.annotations) lines.push(` ${ann}`);
152
+ const paddedPrefix = info.prefix.padEnd(maxNameWidth);
153
+ lines.push(` ${paddedPrefix} : ${info.typeStr};`);
154
+ }
155
+ lines.push("", "}");
156
+ return lines.join("\n") + "\n";
157
+ }
158
+ /**
159
+ * Pre-process DD03P entries into structured field info for emission.
160
+ */
161
+ function buildFieldInfos(entries, tableName) {
162
+ const result = [];
163
+ for (let i = 0; i < entries.length; i++) {
164
+ const entry = entries[i];
165
+ const fieldName = entry.FIELDNAME ?? "";
166
+ if (fieldName.startsWith(".INCLU-")) {
167
+ const includeName = entry.PRECFIELD ?? "";
168
+ if (includeName) {
169
+ const suffix = fieldName.slice(7).toLowerCase();
170
+ result.push({
171
+ kind: "include",
172
+ name: includeName.toLowerCase(),
173
+ suffix
174
+ });
175
+ }
176
+ continue;
177
+ }
178
+ if (fieldName === ".INCLUDE") {
179
+ const includeName = entry.PRECFIELD ?? "";
180
+ if (includeName) result.push({
181
+ kind: "include",
182
+ name: includeName.toLowerCase()
183
+ });
184
+ continue;
185
+ }
186
+ if (entry.COMPTYPE === "S" && entry.DATATYPE === "STRU") {
187
+ const isKey = entry.KEYFLAG === "X";
188
+ const notNull = entry.NOTNULL === "X" || isKey;
189
+ const rollname = entry.ROLLNAME ?? fieldName;
190
+ const prefix = isKey ? `key ${fieldName.toLowerCase()}` : fieldName.toLowerCase();
191
+ const typeStr = notNull ? `${rollname.toLowerCase()} not null` : rollname.toLowerCase();
192
+ result.push({
193
+ kind: "field",
194
+ prefix,
195
+ typeStr,
196
+ annotations: []
197
+ });
198
+ continue;
199
+ }
200
+ if (entry.COMPTYPE === "E" && entry.ROLLNAME) {
201
+ const isKey = entry.KEYFLAG === "X";
202
+ const notNull = entry.NOTNULL === "X" || isKey;
203
+ const prefix = isKey ? `key ${fieldName.toLowerCase()}` : fieldName.toLowerCase();
204
+ const typeStr = notNull ? `${entry.ROLLNAME.toLowerCase()} not null` : entry.ROLLNAME.toLowerCase();
205
+ result.push({
206
+ kind: "field",
207
+ prefix,
208
+ typeStr,
209
+ annotations: []
210
+ });
211
+ continue;
212
+ }
213
+ const cdsType = buildCdsTypeString(entry);
214
+ if (!cdsType) continue;
215
+ const isKey = entry.KEYFLAG === "X";
216
+ const notNull = entry.NOTNULL === "X" || isKey;
217
+ const annotations = [];
218
+ if (entry.DATATYPE === "CURR" && entry.REFTABLE && entry.REFFIELD) {
219
+ const refTable = entry.REFTABLE.toUpperCase() === tableName.toUpperCase() ? tableName.toLowerCase() : entry.REFTABLE.toLowerCase();
220
+ annotations.push(`@Semantics.amount.currencyCode : '${refTable}.${entry.REFFIELD.toLowerCase()}'`);
221
+ } else if (entry.DATATYPE === "QUAN" && entry.REFTABLE && entry.REFFIELD) {
222
+ const refTable = entry.REFTABLE.toUpperCase() === tableName.toUpperCase() ? tableName.toLowerCase() : entry.REFTABLE.toLowerCase();
223
+ annotations.push(`@Semantics.quantity.unitOfMeasure : '${refTable}.${entry.REFFIELD.toLowerCase()}'`);
224
+ }
225
+ const prefix = isKey ? `key ${fieldName.toLowerCase()}` : fieldName.toLowerCase();
226
+ const typeStr = notNull ? `${cdsType} not null` : cdsType;
227
+ result.push({
228
+ kind: "field",
229
+ prefix,
230
+ typeStr,
231
+ annotations
232
+ });
233
+ }
234
+ return result;
235
+ }
236
+ /**
237
+ * Build the CDS type string from a DD03P entry.
238
+ * E.g., "abap.char(10)", "abap.dec(15,2)", "abap.int4"
239
+ */
240
+ function buildCdsTypeString(entry) {
241
+ const datatype = entry.DATATYPE;
242
+ if (!datatype) return null;
243
+ const cdsName = DATATYPE_TO_CDS[datatype];
244
+ if (!cdsName) return null;
245
+ if (NO_LENGTH_TYPES.has(cdsName)) return `abap.${cdsName}`;
246
+ const leng = entry.LENG ? Number.parseInt(entry.LENG, 10) : void 0;
247
+ const decimals = entry.DECIMALS ? Number.parseInt(entry.DECIMALS, 10) : void 0;
248
+ if (VARIABLE_LENGTH_TYPES.has(cdsName)) {
249
+ if (leng && leng > 0) return `abap.${cdsName}(${leng})`;
250
+ return `abap.${cdsName}(0)`;
251
+ }
252
+ if (DECIMAL_TYPES.has(cdsName) && leng !== void 0) return `abap.${cdsName}(${leng},${decimals ?? 0})`;
253
+ if (leng !== void 0) return `abap.${cdsName}(${leng})`;
254
+ return `abap.${cdsName}`;
255
+ }
256
+ /**
257
+ * Escape single quotes in annotation string values
258
+ */
259
+ function escapeAnnotationString(value) {
260
+ return value.replaceAll("'", "''");
261
+ }
262
+ const xmlParser = new XMLParser({
263
+ ignoreAttributes: false,
264
+ attributeNamePrefix: "@_",
265
+ trimValues: true,
266
+ parseTagValue: false,
267
+ parseAttributeValue: false,
268
+ removeNSPrefix: true,
269
+ isArray: (name) => name === "DD03P"
270
+ });
271
+ /**
272
+ * Parse abapGit TABL XML content and extract DD02V/DD03P data.
273
+ */
274
+ function parseTablXml(xmlContent) {
275
+ const values = xmlParser.parse(xmlContent)?.abapGit?.abap?.values ?? {};
276
+ const dd02v = values.DD02V ?? {};
277
+ let dd03pRaw = values.DD03P_TABLE?.DD03P ?? [];
278
+ if (!Array.isArray(dd03pRaw)) dd03pRaw = [dd03pRaw];
279
+ return {
280
+ dd02v,
281
+ dd03p: dd03pRaw
282
+ };
283
+ }
284
+ /**
285
+ * Parse abapGit TABL XML and build CDS DDL source.
286
+ *
287
+ * @param xmlContent - Raw XML content of a .tabl.xml file
288
+ * @returns CDS DDL source string
289
+ */
290
+ function tablXmlToCdsDdl(xmlContent) {
291
+ const { dd02v, dd03p } = parseTablXml(xmlContent);
292
+ return buildCdsDdl(dd02v, dd03p);
293
+ }
294
+ //#endregion
295
+ //#region src/commands/diff.ts
296
+ /**
297
+ * Diff Command Plugin — Type-Agnostic
298
+ *
299
+ * Compares local abapGit files against what SAP has.
300
+ *
301
+ * The local file (from abapGit) is the source of truth — it defines which
302
+ * fields matter. The remote side is fetched from SAP via ADT, serialized
303
+ * through the same handler, then **projected** onto the local's field set.
304
+ * Any extra fields the serializer adds (LANGDEP, POSITION, etc.) are
305
+ * stripped so the diff only shows real value changes.
306
+ *
307
+ * For XML metadata: parse both → project remote onto local's keys → rebuild
308
+ * For .abap source: compare text directly
309
+ *
310
+ * Works for ALL object types supported by adt-plugin-abapgit:
311
+ * CLAS, INTF, PROG, FUGR, TABL, DOMA, DTEL, TTYP, DEVC
312
+ *
313
+ * Usage:
314
+ * adt diff zage_structure.tabl.xml
315
+ * adt diff *.tabl.xml
316
+ * adt diff zcl_myclass.clas.xml --no-color
317
+ */
318
+ const abapgit = () => requireFormatPlugin("abapgit");
319
+ const getHandler = (type) => abapgit().getHandler(type);
320
+ const getSupportedTypes = () => [...getFormatPlugin("abapgit")?.supportedTypes ?? []];
321
+ const parseAbapGitFilename = (filename) => abapgit().parseFilename?.(filename) ?? null;
322
+ /**
323
+ * ADT schema lookup for --raw mode.
324
+ *
325
+ * Maps abapGit type codes to raw CRUD contract schemas (NOT speci-proxied).
326
+ * Each entry has:
327
+ * - schema: the TypedSchema with .build() for XML serialization
328
+ * - wrapperKey: the root element key expected by build()
329
+ */
330
+ const adtSchemaMap = {
331
+ TTYP: {
332
+ schema: adtContract.ddic.tabletypes.bodySchema,
333
+ wrapperKey: "tableType"
334
+ },
335
+ DOMA: {
336
+ schema: adtContract.ddic.domains.bodySchema,
337
+ wrapperKey: "domain"
338
+ },
339
+ DTEL: {
340
+ schema: adtContract.ddic.dataelements.bodySchema,
341
+ wrapperKey: "wbobj"
342
+ },
343
+ CLAS: {
344
+ schema: adtContract.oo.classes.bodySchema,
345
+ wrapperKey: "abapClass"
346
+ },
347
+ INTF: {
348
+ schema: adtContract.oo.interfaces.bodySchema,
349
+ wrapperKey: "abapInterface"
350
+ },
351
+ PROG: {
352
+ schema: adtContract.programs.programs.bodySchema,
353
+ wrapperKey: "abapProgram"
354
+ },
355
+ FUGR: {
356
+ schema: adtContract.functions.groups.bodySchema,
357
+ wrapperKey: "abapFunctionGroup"
358
+ },
359
+ DEVC: {
360
+ schema: adtContract.packages.bodySchema,
361
+ wrapperKey: "package"
362
+ }
363
+ };
364
+ /**
365
+ * Expand glob patterns to matching file paths.
366
+ * Passes through literal filenames unchanged.
367
+ */
368
+ async function expandGlobs(patterns, cwd) {
369
+ const results = [];
370
+ for (const pattern of patterns) if (/[*?[\]{}]/.test(pattern)) for await (const match of glob(pattern, { cwd })) results.push(match);
371
+ else results.push(pattern);
372
+ return results;
373
+ }
374
+ /**
375
+ * Walk up from a directory to find the nearest ancestor containing .abapgit.xml.
376
+ * Returns the resolved absolute path to the repo root, or undefined if not found.
377
+ */
378
+ function findAbapGitRoot(startDir) {
379
+ let dir = resolve(startDir);
380
+ const root = resolve("/");
381
+ while (dir !== root) {
382
+ if (existsSync(join(dir, ".abapgit.xml"))) return dir;
383
+ const parent = dirname(dir);
384
+ if (parent === dir) break;
385
+ dir = parent;
386
+ }
387
+ }
388
+ /**
389
+ * Scan an abapGit repository directory for all supported XML metadata files.
390
+ * Returns relative paths to each .xml file (excluding .abapgit.xml and package.devc.xml).
391
+ */
392
+ async function scanAbapGitFiles(repoRoot) {
393
+ const supportedTypes = new Set(getSupportedTypes().map((t) => t.toLowerCase()));
394
+ const files = [];
395
+ for await (const match of glob("**/*.xml", { cwd: repoRoot })) {
396
+ if (match.endsWith(".abapgit.xml")) continue;
397
+ if (match.endsWith("package.devc.xml")) continue;
398
+ const filename = basename(match);
399
+ const parsed = parseAbapGitFilename(filename);
400
+ if (!parsed) continue;
401
+ if (parsed.extension !== "xml") continue;
402
+ if (!supportedTypes.has(parsed.type.toLowerCase())) continue;
403
+ files.push(match);
404
+ }
405
+ return [...files].sort((a, b) => a.localeCompare(b));
406
+ }
407
+ /**
408
+ * Collect all local files belonging to one abapGit object.
409
+ *
410
+ * Given the XML metadata file, scans the same directory for companion
411
+ * .abap files that share the same name.type prefix.
412
+ *
413
+ * @returns Map of relative filename → content
414
+ */
415
+ function collectLocalFiles(xmlPath, objectName, fileExtension) {
416
+ const dir = dirname(xmlPath);
417
+ const prefix = `${objectName}.${fileExtension}`;
418
+ const files = /* @__PURE__ */ new Map();
419
+ for (const entry of readdirSync(dir)) if (entry.toLowerCase().startsWith(prefix)) {
420
+ const fullPath = join(dir, entry);
421
+ files.set(entry.toLowerCase(), readFileSync(fullPath, "utf-8"));
422
+ }
423
+ return files;
424
+ }
425
+ /**
426
+ * Project `source` onto `reference`'s key structure.
427
+ *
428
+ * Recursively keeps only the keys from `source` that also exist in
429
+ * `reference`. For arrays, builds a **union** of all keys across all
430
+ * reference elements as the template — because different elements may
431
+ * have different optional fields (e.g. DD03P entries where some have
432
+ * DECIMALS and others don't).
433
+ *
434
+ * This ensures the remote object only contains fields the local cares
435
+ * about, so serializer-added extras (LANGDEP, POSITION, etc.) vanish.
436
+ */
437
+ function projectOnto(source, reference) {
438
+ if (reference === null || reference === void 0) return source;
439
+ if (source === null || source === void 0) return source;
440
+ if (Array.isArray(reference) && Array.isArray(source)) {
441
+ if (reference.length === 0) return source;
442
+ const unionShape = mergeObjectKeys(reference);
443
+ if (unionShape === void 0) return source;
444
+ return source.map((item) => projectOnto(item, unionShape));
445
+ }
446
+ if (typeof reference === "object" && typeof source === "object" && !Array.isArray(reference) && !Array.isArray(source)) {
447
+ const ref = reference;
448
+ const src = source;
449
+ const result = {};
450
+ for (const key of Object.keys(ref)) if (key in src) result[key] = projectOnto(src[key], ref[key]);
451
+ return result;
452
+ }
453
+ return source;
454
+ }
455
+ /**
456
+ * Merge all keys from an array of objects into a single union object.
457
+ * Each key gets the first non-undefined value found across elements.
458
+ * Used to build the "widest" template for array element projection.
459
+ */
460
+ function mergeObjectKeys(items) {
461
+ const objects = items.filter((item) => item !== null && typeof item === "object" && !Array.isArray(item));
462
+ if (objects.length === 0) return void 0;
463
+ const union = {};
464
+ for (const obj of objects) for (const [key, value] of Object.entries(obj)) if (!(key in union) || union[key] === void 0) union[key] = value;
465
+ return union;
466
+ }
467
+ /**
468
+ * Normalize an XML pair for comparison.
469
+ *
470
+ * 1. Parse both local and remote through the schema (strips formatting)
471
+ * 2. Project remote values onto local's field structure (strips extras)
472
+ * 3. Rebuild both through the same builder (identical formatting)
473
+ *
474
+ * Returns [normalizedLocal, normalizedRemote].
475
+ */
476
+ function normalizeXmlPair(localXml, remoteXml, handler) {
477
+ try {
478
+ const localParsed = handler.schema.parse(localXml);
479
+ const remoteProjected = projectOnto(handler.schema.parse(remoteXml), localParsed);
480
+ return [handler.schema.build(localParsed, { pretty: true }), handler.schema.build(remoteProjected, { pretty: true })];
481
+ } catch {
482
+ return [localXml, remoteXml];
483
+ }
484
+ }
485
+ /**
486
+ * Print a unified diff with optional color.
487
+ * Returns true if differences were found.
488
+ * When silent=true, skips printing but still detects differences.
489
+ */
490
+ function printDiff(localLabel, remoteLabel, localContent, remoteContent, contextLines, useColor, silent = false) {
491
+ const local = localContent.endsWith("\n") ? localContent : localContent + "\n";
492
+ const remote = remoteContent.endsWith("\n") ? remoteContent : remoteContent + "\n";
493
+ if (local === remote) return false;
494
+ if (silent) return true;
495
+ const patch = createTwoFilesPatch(`a/${localLabel}`, `b/${remoteLabel}`, local, remote, "local", "remote (SAP)", { context: contextLines });
496
+ for (const line of patch.split("\n")) {
497
+ if (!useColor) {
498
+ console.log(line);
499
+ continue;
500
+ }
501
+ if (line.startsWith("+++") || line.startsWith("---")) console.log(chalk.bold(line));
502
+ else if (line.startsWith("+")) console.log(chalk.green(line));
503
+ else if (line.startsWith("-")) console.log(chalk.red(line));
504
+ else if (line.startsWith("@@")) console.log(chalk.cyan(line));
505
+ else console.log(line);
506
+ }
507
+ return true;
508
+ }
509
+ /**
510
+ * Diff a single abapGit XML file against SAP remote.
511
+ * Returns a result object indicating whether differences were found.
512
+ */
513
+ async function diffSingleFile(filePath, ctx, adk, options) {
514
+ const { contextLines, useColor, source, raw, summary } = options;
515
+ const fullPath = resolve(ctx.cwd, filePath);
516
+ if (!existsSync(fullPath)) return {
517
+ objectName: filePath,
518
+ objectType: "?",
519
+ hasDifferences: false,
520
+ fileCount: 0,
521
+ identicalCount: 0,
522
+ error: `File not found: ${fullPath}`
523
+ };
524
+ const filename = basename(fullPath);
525
+ const parsed = parseAbapGitFilename(filename);
526
+ if (!parsed) return {
527
+ objectName: filename,
528
+ objectType: "?",
529
+ hasDifferences: false,
530
+ fileCount: 0,
531
+ identicalCount: 0,
532
+ error: `Cannot parse filename: ${filename}. Expected abapGit format: name.type.xml`
533
+ };
534
+ if (parsed.extension !== "xml") return {
535
+ objectName: parsed.name,
536
+ objectType: parsed.type,
537
+ hasDifferences: false,
538
+ fileCount: 0,
539
+ identicalCount: 0,
540
+ error: `Expected .xml metadata file, got .${parsed.extension}. Pass the .xml file, not .abap.`
541
+ };
542
+ if (source && parsed.type !== "TABL") return {
543
+ objectName: parsed.name,
544
+ objectType: parsed.type,
545
+ hasDifferences: false,
546
+ fileCount: 0,
547
+ identicalCount: 0,
548
+ error: `Source format is only supported for TABL objects. Got: ${parsed.type}`
549
+ };
550
+ if (source && raw) return {
551
+ objectName: parsed.name,
552
+ objectType: parsed.type,
553
+ hasDifferences: false,
554
+ fileCount: 0,
555
+ identicalCount: 0,
556
+ error: "--source and --raw are mutually exclusive"
557
+ };
558
+ const handler = getHandler(parsed.type);
559
+ if (!handler) return {
560
+ objectName: parsed.name,
561
+ objectType: parsed.type,
562
+ hasDifferences: false,
563
+ fileCount: 0,
564
+ identicalCount: 0,
565
+ error: `Unsupported object type: ${parsed.type}. Supported: ${getSupportedTypes().join(", ")}`
566
+ };
567
+ const objectName = parsed.name.toLowerCase();
568
+ const localFiles = collectLocalFiles(fullPath, objectName, handler.fileExtension);
569
+ if (!summary) console.log(`\n${useColor ? chalk.bold("Diff:") : "Diff:"} ${parsed.name} (${parsed.type}) — ${localFiles.size} file(s)`);
570
+ const localXml = readFileSync(fullPath, "utf-8");
571
+ let adkType = parsed.type;
572
+ if (handler.fromAbapGit) try {
573
+ const values = handler.schema.parse(localXml)?.abapGit?.abap?.values ?? {};
574
+ const payload = handler.fromAbapGit(values);
575
+ if (typeof payload.type === "string") adkType = payload.type;
576
+ } catch {}
577
+ if (!summary) console.log(`${useColor ? chalk.dim("Fetching") : "Fetching"} ${parsed.name} (${adkType}) from SAP...`);
578
+ const remoteObjRaw = adk.get(parsed.name, adkType);
579
+ if (!(remoteObjRaw instanceof AdkObject)) return {
580
+ objectName: parsed.name,
581
+ objectType: parsed.type,
582
+ hasDifferences: false,
583
+ fileCount: localFiles.size,
584
+ identicalCount: 0,
585
+ error: `Unsupported ADK type: ${adkType} (no registered handler)`
586
+ };
587
+ const remoteObj = remoteObjRaw;
588
+ try {
589
+ await remoteObj.load();
590
+ } catch (error) {
591
+ return {
592
+ objectName: parsed.name,
593
+ objectType: parsed.type,
594
+ hasDifferences: false,
595
+ fileCount: localFiles.size,
596
+ identicalCount: 0,
597
+ error: `Failed to load remote object: ${error instanceof Error ? error.message : String(error)}`
598
+ };
599
+ }
600
+ if (source) {
601
+ const localSource = tablXmlToCdsDdl(localXml);
602
+ let remoteSource;
603
+ try {
604
+ remoteSource = await remoteObj.getSource();
605
+ } catch (error) {
606
+ return {
607
+ objectName: parsed.name,
608
+ objectType: parsed.type,
609
+ hasDifferences: false,
610
+ fileCount: 1,
611
+ identicalCount: 0,
612
+ error: `Failed to fetch remote source: ${error instanceof Error ? error.message : String(error)}`
613
+ };
614
+ }
615
+ const localAnnotations = new Set(localSource.split("\n").filter((l) => l.startsWith("@")).map((l) => l.split(":")[0].trim()));
616
+ remoteSource = remoteSource.split("\n").filter((l) => {
617
+ if (!l.startsWith("@")) return true;
618
+ const name = l.split(":")[0].trim();
619
+ return localAnnotations.has(name);
620
+ }).join("\n");
621
+ const sourceFile = `${objectName}.tabl.acds`;
622
+ const diffFound = printDiff(sourceFile, sourceFile, localSource, remoteSource, contextLines, useColor, summary);
623
+ return {
624
+ objectName: parsed.name,
625
+ objectType: parsed.type,
626
+ hasDifferences: diffFound,
627
+ fileCount: 1,
628
+ identicalCount: diffFound ? 0 : 1
629
+ };
630
+ }
631
+ if (raw) {
632
+ const adtSchema = adtSchemaMap[parsed.type];
633
+ if (!adtSchema) return {
634
+ objectName: parsed.name,
635
+ objectType: parsed.type,
636
+ hasDifferences: false,
637
+ fileCount: 1,
638
+ identicalCount: 0,
639
+ error: `Raw mode not supported for ${parsed.type}: no ADT schema mapping. Supported: ${Object.keys(adtSchemaMap).join(", ")}`
640
+ };
641
+ const { schema: rawSchema, wrapperKey } = adtSchema;
642
+ let remoteAdtXml;
643
+ try {
644
+ const remoteData = await remoteObj.data();
645
+ remoteAdtXml = rawSchema.build({ [wrapperKey]: remoteData }, { pretty: true });
646
+ } catch (e) {
647
+ return {
648
+ objectName: parsed.name,
649
+ objectType: parsed.type,
650
+ hasDifferences: false,
651
+ fileCount: 1,
652
+ identicalCount: 0,
653
+ error: `Failed to build remote ADT XML: ${e instanceof Error ? e.message : String(e)}`
654
+ };
655
+ }
656
+ let localAdtXml;
657
+ if (handler.fromAbapGit) try {
658
+ const values = handler.schema.parse(localXml)?.abapGit?.abap?.values ?? {};
659
+ const localPayload = handler.fromAbapGit(values);
660
+ const merged = {
661
+ ...await remoteObj.data(),
662
+ ...localPayload
663
+ };
664
+ localAdtXml = rawSchema.build({ [wrapperKey]: merged }, { pretty: true });
665
+ } catch (e) {
666
+ return {
667
+ objectName: parsed.name,
668
+ objectType: parsed.type,
669
+ hasDifferences: false,
670
+ fileCount: 1,
671
+ identicalCount: 0,
672
+ error: `Failed to build local ADT XML: ${e instanceof Error ? e.message : String(e)}`
673
+ };
674
+ }
675
+ if (!localAdtXml) return {
676
+ objectName: parsed.name,
677
+ objectType: parsed.type,
678
+ hasDifferences: false,
679
+ fileCount: 1,
680
+ identicalCount: 0,
681
+ error: `Raw mode not supported for ${parsed.type}: no fromAbapGit() mapping`
682
+ };
683
+ const xmlFile = `${objectName}.${parsed.type.toLowerCase()}.adt.xml`;
684
+ const diffFound = printDiff(xmlFile, xmlFile, localAdtXml, remoteAdtXml, contextLines, useColor, summary);
685
+ return {
686
+ objectName: parsed.name,
687
+ objectType: parsed.type,
688
+ hasDifferences: diffFound,
689
+ fileCount: 1,
690
+ identicalCount: diffFound ? 0 : 1
691
+ };
692
+ }
693
+ let remoteFiles;
694
+ try {
695
+ remoteFiles = await handler.serialize(remoteObj);
696
+ } catch (error) {
697
+ return {
698
+ objectName: parsed.name,
699
+ objectType: parsed.type,
700
+ hasDifferences: false,
701
+ fileCount: localFiles.size,
702
+ identicalCount: 0,
703
+ error: `Failed to serialize remote object: ${error instanceof Error ? error.message : String(error)}`
704
+ };
705
+ }
706
+ const remoteMap = /* @__PURE__ */ new Map();
707
+ for (const f of remoteFiles) remoteMap.set(f.path.toLowerCase(), f.content);
708
+ let hasDifferences = false;
709
+ let identicalCount = 0;
710
+ for (const [localPath, localContent] of localFiles) {
711
+ const remoteContent = remoteMap.get(localPath);
712
+ if (remoteContent === void 0) {
713
+ if (!summary) console.log(useColor ? chalk.yellow(`\n + Only in local: ${localPath}`) : `\n + Only in local: ${localPath}`);
714
+ hasDifferences = true;
715
+ continue;
716
+ }
717
+ const isXml = localPath.endsWith(".xml");
718
+ let diffLocal = localContent;
719
+ let diffRemote = remoteContent;
720
+ if (isXml) [diffLocal, diffRemote] = normalizeXmlPair(localContent, remoteContent, handler);
721
+ if (printDiff(localPath, localPath, diffLocal, diffRemote, contextLines, useColor, summary)) hasDifferences = true;
722
+ else identicalCount++;
723
+ }
724
+ for (const [remotePath] of remoteMap) if (!localFiles.has(remotePath)) {
725
+ if (!summary) console.log(useColor ? chalk.yellow(`\n - Only in remote: ${remotePath}`) : `\n - Only in remote: ${remotePath}`);
726
+ hasDifferences = true;
727
+ }
728
+ return {
729
+ objectName: parsed.name,
730
+ objectType: parsed.type,
731
+ hasDifferences,
732
+ fileCount: localFiles.size,
733
+ identicalCount
734
+ };
735
+ }
736
+ const diffCommand = {
737
+ name: "diff",
738
+ description: "Compare local abapGit files against SAP remote (any supported object type)",
739
+ arguments: [{
740
+ name: "[files...]",
741
+ description: `Local .xml files or glob patterns to compare (e.g., zcl_myclass.clas.xml, *.tabl.xml). When omitted, scans the abapGit repo in the current directory. Supported types: ${getSupportedTypes().join(", ")}`
742
+ }],
743
+ options: [
744
+ {
745
+ flags: "--no-color",
746
+ description: "Disable colored output"
747
+ },
748
+ {
749
+ flags: "-c, --context <lines>",
750
+ description: "Number of context lines in diff",
751
+ default: "3"
752
+ },
753
+ {
754
+ flags: "-s, --source",
755
+ description: "Compare ADK source instead of XML (TABL only)"
756
+ },
757
+ {
758
+ flags: "-r, --raw",
759
+ description: "Compare ADT-level XML payloads (what GET returns vs what PUT would send)"
760
+ },
761
+ {
762
+ flags: "-p, --package <name>",
763
+ description: "Scan all abapGit files in the current directory (package name is informational)"
764
+ },
765
+ {
766
+ flags: "-f, --full",
767
+ description: "Show full unified diffs (default in single-file mode; in package/multi-file mode only summary is shown unless --full is given)"
768
+ }
769
+ ],
770
+ async execute(args, ctx) {
771
+ const filePatterns = args.files ?? [];
772
+ const contextLines = Number.parseInt(String(args.context ?? "3"), 10);
773
+ const useColor = args.color !== false;
774
+ const source = args.source === true;
775
+ const raw = args.raw === true;
776
+ const packageName = args.package;
777
+ const fullDiffs = args.full === true;
778
+ let files;
779
+ let scanMode = false;
780
+ let repoRoot;
781
+ if (filePatterns.length > 0) {
782
+ files = await expandGlobs(filePatterns, ctx.cwd);
783
+ if (files.length === 0) {
784
+ ctx.logger.error("No files matched the given pattern(s).");
785
+ process.exit(1);
786
+ }
787
+ } else {
788
+ repoRoot = findAbapGitRoot(ctx.cwd);
789
+ if (!repoRoot) {
790
+ ctx.logger.error(packageName ? "No .abapgit.xml found in current directory or parents." : "No files specified and no .abapgit.xml found. Usage: adt diff <file...> or run from an abapGit repo directory.");
791
+ process.exit(1);
792
+ }
793
+ scanMode = true;
794
+ const scannedFiles = await scanAbapGitFiles(repoRoot);
795
+ if (scannedFiles.length === 0) {
796
+ ctx.logger.error("No supported abapGit objects found in repository.");
797
+ process.exit(1);
798
+ }
799
+ files = scannedFiles.map((f) => relative(ctx.cwd, join(repoRoot, f)));
800
+ const pkgSuffix = packageName ? ` (package: ${packageName})` : "";
801
+ ctx.logger.info(`📦 Scanning ${scannedFiles.length} object(s) in ${repoRoot}${pkgSuffix}...`);
802
+ }
803
+ const summaryMode = scanMode && !fullDiffs;
804
+ if (!ctx.getAdtClient) {
805
+ ctx.logger.error("ADT client not available. Run: adt auth login");
806
+ process.exit(1);
807
+ }
808
+ const client = await ctx.getAdtClient();
809
+ const adk = createAdk(client);
810
+ const results = [];
811
+ for (const file of files) {
812
+ const result = await diffSingleFile(file, ctx, adk, {
813
+ contextLines,
814
+ useColor,
815
+ source,
816
+ raw,
817
+ summary: summaryMode
818
+ });
819
+ if (result.error && !summaryMode) ctx.logger.error(result.error);
820
+ results.push(result);
821
+ }
822
+ const totalFiles = results.length;
823
+ const withDiffs = results.filter((r) => r.hasDifferences).length;
824
+ const withErrors = results.filter((r) => r.error).length;
825
+ const identical = totalFiles - withDiffs - withErrors;
826
+ console.log("");
827
+ if (scanMode) {
828
+ for (const r of results) {
829
+ let icon;
830
+ let line;
831
+ if (r.error) {
832
+ icon = "⚠️";
833
+ line = `${r.objectType} ${r.objectName}: ${r.error}`;
834
+ } else if (r.hasDifferences) {
835
+ icon = "❌";
836
+ line = `${r.objectType} ${r.objectName}`;
837
+ } else {
838
+ icon = "✅";
839
+ line = `${r.objectType} ${r.objectName}`;
840
+ }
841
+ if (useColor) {
842
+ if (r.error) console.log(chalk.yellow(` ${icon} ${line}`));
843
+ else if (r.hasDifferences) console.log(chalk.red(` ${icon} ${line}`));
844
+ else console.log(chalk.green(` ${icon} ${line}`));
845
+ } else console.log(` ${icon} ${line}`);
846
+ }
847
+ console.log("");
848
+ const summaryParts = [`${totalFiles} object(s)`, `${identical} identical`];
849
+ if (withDiffs > 0) summaryParts.push(`${withDiffs} changed`);
850
+ if (withErrors > 0) summaryParts.push(`${withErrors} errors`);
851
+ const summaryLine = summaryParts.join(", ");
852
+ if (withDiffs > 0 || withErrors > 0) {
853
+ console.log(useColor ? chalk.red(`📋 ${summaryLine}`) : `📋 ${summaryLine}`);
854
+ process.exit(1);
855
+ }
856
+ console.log(useColor ? chalk.green(`📋 ${summaryLine}`) : `📋 ${summaryLine}`);
857
+ return;
858
+ }
859
+ if (totalFiles === 1) {
860
+ const r = results[0];
861
+ if (r.error) process.exit(1);
862
+ if (r.hasDifferences) {
863
+ const identicalSuffix = r.identicalCount > 0 ? ` (${r.identicalCount} file(s) identical)` : "";
864
+ console.log(useColor ? chalk.red("Differences found.") + (r.identicalCount > 0 ? chalk.dim(identicalSuffix) : "") : `Differences found.${identicalSuffix}`);
865
+ process.exit(1);
866
+ }
867
+ console.log(useColor ? chalk.green(`No differences found. (${r.identicalCount} file(s) identical)`) : `No differences found. (${r.identicalCount} file(s) identical)`);
868
+ return;
869
+ }
870
+ const parts = [`${totalFiles} object(s) checked`, `${identical} identical`];
871
+ if (withDiffs > 0) parts.push(`${withDiffs} with differences`);
872
+ if (withErrors > 0) parts.push(`${withErrors} with errors`);
873
+ const summaryText = parts.join(", ");
874
+ if (withDiffs > 0 || withErrors > 0) {
875
+ console.log(useColor ? chalk.red(`Diff summary: ${summaryText}`) : `Diff summary: ${summaryText}`);
876
+ process.exit(1);
877
+ }
878
+ console.log(useColor ? chalk.green(`Diff summary: ${summaryText}`) : `Diff summary: ${summaryText}`);
879
+ }
880
+ };
881
+ //#endregion
882
+ export { tablXmlToCdsDdl as i, buildCdsDdl as n, parseTablXml as r, diffCommand as t };
883
+
884
+ //# sourceMappingURL=diff-rq6zDvAI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff-rq6zDvAI.mjs","names":["nativeGlob"],"sources":["../src/lib/abapgit-to-cds.ts","../src/commands/diff.ts"],"sourcesContent":["/**\n * abapGit DD02V/DD03P → CDS DDL Source Builder\n *\n * Reverse mapping of cds-to-abapgit.ts — reconstructs CDS DDL source code\n * from parsed abapGit XML data (DD02V header + DD03P field entries).\n *\n * Used by `adt diff` to compare local abapGit serialized files against\n * SAP remote CDS source fetched via ADT /source/main endpoint.\n */\n\n// ============================================\n// DD02V / DD03P input types\n// (mirror of cds-to-abapgit.ts output types)\n// ============================================\n\nexport interface DD02VData {\n TABNAME?: string;\n DDLANGUAGE?: string;\n TABCLASS?: string;\n LANGDEP?: string;\n DDTEXT?: string;\n MASTERLANG?: string;\n CONTFLAG?: string;\n EXCLASS?: string;\n AUTHCLASS?: string;\n CLIDEP?: string;\n BUFFERED?: string;\n MATEFLAG?: string;\n SHLPEXI?: string;\n}\n\nexport interface DD03PData {\n FIELDNAME?: string;\n POSITION?: string;\n KEYFLAG?: string;\n ROLLNAME?: string;\n ADMINFIELD?: string;\n INTTYPE?: string;\n INTLEN?: string;\n NOTNULL?: string;\n DATATYPE?: string;\n LENG?: string;\n DECIMALS?: string;\n SHLPORIGIN?: string;\n MASK?: string;\n COMPTYPE?: string;\n REFTABLE?: string;\n REFFIELD?: string;\n PRECFIELD?: string;\n DDTEXT?: string;\n DOMNAME?: string;\n}\n\n// ============================================\n// Reverse mapping tables\n// ============================================\n\n/** DDIC DATATYPE → CDS abap.<type> name */\nconst DATATYPE_TO_CDS: Record<string, string> = {\n CHAR: 'char',\n CLNT: 'clnt',\n NUMC: 'numc',\n DATS: 'dats',\n DATN: 'datn',\n TIMS: 'tims',\n TIMN: 'timn',\n DEC: 'dec',\n CURR: 'curr',\n QUAN: 'quan',\n RAW: 'raw',\n INT1: 'int1',\n INT2: 'int2',\n INT4: 'int4',\n INT8: 'int8',\n FLTP: 'fltp',\n STRG: 'string',\n RSTR: 'rawstring',\n CUKY: 'cuky',\n UNIT: 'unit',\n LANG: 'lang',\n ACCP: 'accp',\n PREC: 'prec',\n D16N: 'd16n',\n D34N: 'd34n',\n D16R: 'd16r',\n D34R: 'd34r',\n D16D: 'd16d',\n D34D: 'd34d',\n UTCL: 'utclong',\n SSTR: 'sstring',\n LCHR: 'lchr',\n LRAW: 'lraw',\n};\n\n/** Types that never take a length parameter in CDS */\nconst NO_LENGTH_TYPES = new Set([\n 'clnt',\n 'cuky',\n 'dats',\n 'datn',\n 'tims',\n 'timn',\n 'int1',\n 'int2',\n 'int4',\n 'int8',\n 'fltp',\n 'lang',\n 'accp',\n 'prec',\n 'd16n',\n 'd34n',\n 'd16r',\n 'd34r',\n 'utclong',\n]);\n\n/** Types that take decimals in CDS: abap.dec(len,dec) */\nconst DECIMAL_TYPES = new Set(['dec', 'curr', 'quan', 'fltp', 'd16d', 'd34d']);\n\n/** Types that are variable-length (string, rawstring) — length 0 is omitted */\nconst VARIABLE_LENGTH_TYPES = new Set(['string', 'rawstring']);\n\n/** DD02V EXCLASS → CDS @AbapCatalog.enhancement.category */\nconst ENHANCEMENT_CATEGORY_REVERSE: Record<string, string> = {\n '0': '#NOT_CLASSIFIED',\n '1': '#NOT_EXTENSIBLE',\n '2': '#EXTENSIBLE_CHARACTER_NUMERIC',\n '3': '#EXTENSIBLE_CHARACTER',\n '4': '#EXTENSIBLE_ANY',\n};\n\n/** DD02V CONTFLAG → CDS @AbapCatalog.deliveryClass */\nconst DELIVERY_CLASS_REVERSE: Record<string, string> = {\n A: '#A',\n C: '#C',\n L: '#L',\n G: '#G',\n E: '#E',\n S: '#S',\n W: '#W',\n};\n\n/** DD02V TABCLASS → CDS @AbapCatalog.tableCategory */\nconst TABLE_CATEGORY_REVERSE: Record<string, string> = {\n TRANSP: '#TRANSPARENT',\n CLUSTER: '#CLUSTER',\n POOL: '#POOL',\n APPEND: '#APPEND',\n};\n\n/** DD02V MATEFLAG → CDS @AbapCatalog.dataMaintenance */\nconst DATA_MAINTENANCE_REVERSE: Record<string, string> = {\n X: '#RESTRICTED',\n N: '#NOT_ALLOWED',\n '': '#ALLOWED',\n};\n\n// ============================================\n// Builder\n// ============================================\n\n/**\n * Build CDS DDL source from DD02V header and DD03P field entries.\n *\n * @param dd02v - Table/structure header data\n * @param dd03pEntries - Field entries (sorted by POSITION if present)\n * @returns CDS DDL source string\n */\nexport function buildCdsDdl(\n dd02v: DD02VData,\n dd03pEntries: DD03PData[],\n): string {\n const lines: string[] = [];\n const tableName = dd02v.TABNAME ?? '';\n const isStructure = dd02v.TABCLASS === 'INTTAB';\n\n // --- Annotations ---\n if (dd02v.DDTEXT) {\n lines.push(\n `@EndUserText.label : '${escapeAnnotationString(dd02v.DDTEXT)}'`,\n );\n }\n\n if (dd02v.EXCLASS) {\n const cat = ENHANCEMENT_CATEGORY_REVERSE[dd02v.EXCLASS];\n if (cat) {\n lines.push(`@AbapCatalog.enhancement.category : ${cat}`);\n }\n }\n\n if (!isStructure) {\n // Table-specific annotations\n if (dd02v.TABCLASS) {\n const cat = TABLE_CATEGORY_REVERSE[dd02v.TABCLASS];\n if (cat) {\n lines.push(`@AbapCatalog.tableCategory : ${cat}`);\n }\n }\n\n if (dd02v.CONTFLAG) {\n const dc = DELIVERY_CLASS_REVERSE[dd02v.CONTFLAG];\n if (dc) {\n lines.push(`@AbapCatalog.deliveryClass : ${dc}`);\n }\n }\n\n if (dd02v.MATEFLAG !== undefined) {\n const dm = DATA_MAINTENANCE_REVERSE[dd02v.MATEFLAG ?? ''];\n if (dm) {\n lines.push(`@AbapCatalog.dataMaintenance : ${dm}`);\n }\n }\n }\n\n // --- Definition header ---\n const keyword = isStructure ? 'define structure' : 'define table';\n lines.push(`${keyword} ${tableName.toLowerCase()} {`, ''); // Blank line after opening brace (SAP format)\n\n // --- Sort fields by POSITION ---\n const sorted = [...dd03pEntries].sort((a, b) => {\n const posA = Number.parseInt(a.POSITION ?? '0', 10);\n const posB = Number.parseInt(b.POSITION ?? '0', 10);\n return posA - posB;\n });\n\n // --- Compute alignment ---\n // Find max field name width for alignment (only field entries, not includes)\n const fieldInfos = buildFieldInfos(sorted, tableName);\n const maxNameWidth = Math.max(\n ...fieldInfos\n .filter((f): f is FieldInfo => f.kind === 'field')\n .map((f) => f.prefix.length),\n 0,\n );\n\n // --- Emit fields ---\n for (const info of fieldInfos) {\n if (info.kind === 'include') {\n if (info.suffix) {\n lines.push(` include ${info.name} with suffix ${info.suffix};`);\n } else {\n lines.push(` include ${info.name};`);\n }\n } else {\n // Field annotations (e.g., @Semantics.amount.currencyCode)\n for (const ann of info.annotations) {\n lines.push(` ${ann}`);\n }\n\n const paddedPrefix = info.prefix.padEnd(maxNameWidth);\n lines.push(` ${paddedPrefix} : ${info.typeStr};`);\n }\n }\n\n lines.push('', '}'); // Blank line before closing brace (SAP format)\n\n return lines.join('\\n') + '\\n'; // Trailing newline (SAP format)\n}\n\n// ============================================\n// Internal helpers\n// ============================================\n\ninterface FieldInfo {\n kind: 'field';\n /** \"key fieldname\" or \"fieldname\" — used for alignment */\n prefix: string;\n /** CDS type string (e.g., \"abap.char(10) not null\") */\n typeStr: string;\n /** Field-level annotations */\n annotations: string[];\n}\n\ninterface IncludeInfo {\n kind: 'include';\n name: string;\n /** Optional suffix for `include ... with suffix <suffix>` */\n suffix?: string;\n}\n\ntype MemberInfo = FieldInfo | IncludeInfo;\n\n/**\n * Pre-process DD03P entries into structured field info for emission.\n */\nfunction buildFieldInfos(\n entries: DD03PData[],\n tableName: string,\n): MemberInfo[] {\n const result: MemberInfo[] = [];\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n const fieldName = entry.FIELDNAME ?? '';\n\n // .INCLU-<SUFFIX> entries → include with suffix\n if (fieldName.startsWith('.INCLU-')) {\n const includeName = entry.PRECFIELD ?? '';\n if (includeName) {\n // Extract suffix from .INCLU-<SUFFIX> (e.g., \".INCLU-_XX\" → \"_xx\")\n const suffix = fieldName.slice('.INCLU-'.length).toLowerCase();\n result.push({\n kind: 'include',\n name: includeName.toLowerCase(),\n suffix,\n });\n }\n continue;\n }\n\n // Include directive → plain include\n if (fieldName === '.INCLUDE') {\n const includeName = entry.PRECFIELD ?? '';\n if (includeName) {\n result.push({\n kind: 'include',\n name: includeName.toLowerCase(),\n });\n }\n continue;\n }\n\n // Structure-typed field (COMPTYPE = 'S', not an include)\n if (entry.COMPTYPE === 'S' && entry.DATATYPE === 'STRU') {\n const isKey = entry.KEYFLAG === 'X';\n const notNull = entry.NOTNULL === 'X' || isKey;\n const rollname = entry.ROLLNAME ?? fieldName;\n\n const prefix = isKey\n ? `key ${fieldName.toLowerCase()}`\n : fieldName.toLowerCase();\n\n const typeStr = notNull\n ? `${rollname.toLowerCase()} not null`\n : rollname.toLowerCase();\n\n result.push({\n kind: 'field',\n prefix,\n typeStr,\n annotations: [],\n });\n continue;\n }\n\n // Data element reference (COMPTYPE = 'E')\n if (entry.COMPTYPE === 'E' && entry.ROLLNAME) {\n const isKey = entry.KEYFLAG === 'X';\n const notNull = entry.NOTNULL === 'X' || isKey;\n\n const prefix = isKey\n ? `key ${fieldName.toLowerCase()}`\n : fieldName.toLowerCase();\n\n const typeStr = notNull\n ? `${entry.ROLLNAME.toLowerCase()} not null`\n : entry.ROLLNAME.toLowerCase();\n\n result.push({\n kind: 'field',\n prefix,\n typeStr,\n annotations: [],\n });\n continue;\n }\n\n // Built-in type field\n const cdsType = buildCdsTypeString(entry);\n if (!cdsType) continue;\n\n const isKey = entry.KEYFLAG === 'X';\n const notNull = entry.NOTNULL === 'X' || isKey;\n const annotations: string[] = [];\n\n // @Semantics annotations for CURR/QUAN fields\n if (entry.DATATYPE === 'CURR' && entry.REFTABLE && entry.REFFIELD) {\n const refTable =\n entry.REFTABLE.toUpperCase() === tableName.toUpperCase()\n ? tableName.toLowerCase()\n : entry.REFTABLE.toLowerCase();\n annotations.push(\n `@Semantics.amount.currencyCode : '${refTable}.${entry.REFFIELD.toLowerCase()}'`,\n );\n } else if (entry.DATATYPE === 'QUAN' && entry.REFTABLE && entry.REFFIELD) {\n const refTable =\n entry.REFTABLE.toUpperCase() === tableName.toUpperCase()\n ? tableName.toLowerCase()\n : entry.REFTABLE.toLowerCase();\n annotations.push(\n `@Semantics.quantity.unitOfMeasure : '${refTable}.${entry.REFFIELD.toLowerCase()}'`,\n );\n }\n\n const prefix = isKey\n ? `key ${fieldName.toLowerCase()}`\n : fieldName.toLowerCase();\n\n const typeStr = notNull ? `${cdsType} not null` : cdsType;\n\n result.push({\n kind: 'field',\n prefix,\n typeStr,\n annotations,\n });\n }\n\n return result;\n}\n\n/**\n * Build the CDS type string from a DD03P entry.\n * E.g., \"abap.char(10)\", \"abap.dec(15,2)\", \"abap.int4\"\n */\nfunction buildCdsTypeString(entry: DD03PData): string | null {\n const datatype = entry.DATATYPE;\n if (!datatype) return null;\n\n const cdsName = DATATYPE_TO_CDS[datatype];\n if (!cdsName) return null;\n\n // Fixed-length types without parameters\n if (NO_LENGTH_TYPES.has(cdsName)) {\n return `abap.${cdsName}`;\n }\n\n // Parse LENG and DECIMALS (strip leading zeros)\n const leng = entry.LENG ? Number.parseInt(entry.LENG, 10) : undefined;\n const decimals = entry.DECIMALS\n ? Number.parseInt(entry.DECIMALS, 10)\n : undefined;\n\n // Variable-length types (string, rawstring)\n if (VARIABLE_LENGTH_TYPES.has(cdsName)) {\n if (leng && leng > 0) {\n return `abap.${cdsName}(${leng})`;\n }\n return `abap.${cdsName}(0)`;\n }\n\n // Types with decimals\n if (DECIMAL_TYPES.has(cdsName) && leng !== undefined) {\n const dec = decimals ?? 0;\n return `abap.${cdsName}(${leng},${dec})`;\n }\n\n // Types with length only\n if (leng !== undefined) {\n return `abap.${cdsName}(${leng})`;\n }\n\n // Fallback: no parameters\n return `abap.${cdsName}`;\n}\n\n/**\n * Escape single quotes in annotation string values\n */\nfunction escapeAnnotationString(value: string): string {\n return value.replaceAll(\"'\", \"''\");\n}\n\n// ============================================\n// XML parsing\n// ============================================\n\nimport { XMLParser } from 'fast-xml-parser';\n\nconst xmlParser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n trimValues: true,\n parseTagValue: false,\n parseAttributeValue: false,\n removeNSPrefix: true,\n isArray: (name) => name === 'DD03P',\n});\n\n/**\n * Parse abapGit TABL XML content and extract DD02V/DD03P data.\n */\nexport function parseTablXml(xmlContent: string): {\n dd02v: DD02VData;\n dd03p: DD03PData[];\n} {\n const parsed = xmlParser.parse(xmlContent);\n const values = parsed?.abapGit?.abap?.values ?? {};\n\n const dd02v: DD02VData = values.DD02V ?? {};\n\n // DD03P can be inside DD03P_TABLE or directly as array\n let dd03pRaw = values.DD03P_TABLE?.DD03P ?? [];\n if (!Array.isArray(dd03pRaw)) {\n dd03pRaw = [dd03pRaw];\n }\n\n return { dd02v, dd03p: dd03pRaw };\n}\n\n// ============================================\n// Convenience: parse XML and build DDL\n// ============================================\n\n/**\n * Parse abapGit TABL XML and build CDS DDL source.\n *\n * @param xmlContent - Raw XML content of a .tabl.xml file\n * @returns CDS DDL source string\n */\nexport function tablXmlToCdsDdl(xmlContent: string): string {\n const { dd02v, dd03p } = parseTablXml(xmlContent);\n return buildCdsDdl(dd02v, dd03p);\n}\n","/**\n * Diff Command Plugin — Type-Agnostic\n *\n * Compares local abapGit files against what SAP has.\n *\n * The local file (from abapGit) is the source of truth — it defines which\n * fields matter. The remote side is fetched from SAP via ADT, serialized\n * through the same handler, then **projected** onto the local's field set.\n * Any extra fields the serializer adds (LANGDEP, POSITION, etc.) are\n * stripped so the diff only shows real value changes.\n *\n * For XML metadata: parse both → project remote onto local's keys → rebuild\n * For .abap source: compare text directly\n *\n * Works for ALL object types supported by adt-plugin-abapgit:\n * CLAS, INTF, PROG, FUGR, TABL, DOMA, DTEL, TTYP, DEVC\n *\n * Usage:\n * adt diff zage_structure.tabl.xml\n * adt diff *.tabl.xml\n * adt diff zcl_myclass.clas.xml --no-color\n */\n\nimport {\n requireFormatPlugin,\n getFormatPlugin,\n type CliCommandPlugin,\n type CliContext,\n type FormatHandler,\n type ParsedFormatFilename,\n} from '@abapify/adt-plugin';\nimport {\n createAdk,\n AdkObject,\n type AdtClient,\n type AdkFactory,\n} from '@abapify/adk';\nimport { readFileSync, existsSync, readdirSync } from 'node:fs';\nimport { glob as nativeGlob } from 'node:fs/promises';\nimport { resolve, basename, dirname, join, relative } from 'node:path';\nimport { createTwoFilesPatch } from 'diff';\nimport chalk from 'chalk';\n\n// abapGit is the only diff format today. The plugin registers itself on\n// import (see adt-cli/src/lib/cli.ts bootstrap).\nconst abapgit = () => requireFormatPlugin('abapgit');\nconst getHandler = (type: string): FormatHandler | undefined =>\n abapgit().getHandler(type);\n// Used in command `description` at module-load time — must be safe to call\n// before the bootstrap has registered the plugin (returns `[]` in that case;\n// the actual `execute` body always runs post-bootstrap).\nconst getSupportedTypes = (): string[] => [\n ...(getFormatPlugin('abapgit')?.supportedTypes ?? []),\n];\nconst parseAbapGitFilename = (filename: string): ParsedFormatFilename | null =>\n abapgit().parseFilename?.(filename) ?? null;\ntype ObjectHandler = FormatHandler;\nimport { tablXmlToCdsDdl } from '../lib/abapgit-to-cds';\nimport { adtContract } from '@abapify/adt-contracts';\n\n/**\n * ADT schema lookup for --raw mode.\n *\n * Maps abapGit type codes to raw CRUD contract schemas (NOT speci-proxied).\n * Each entry has:\n * - schema: the TypedSchema with .build() for XML serialization\n * - wrapperKey: the root element key expected by build()\n */\nconst adtSchemaMap: Record<\n string,\n {\n // The actual schemas are TypedSchema<T> from adt-schemas. Each has a\n // narrowly-typed build(data: T, ...) that is contravariantly incompatible\n // with a unified (data: unknown, ...) signature. We widen to `any` here\n // so the callers in this file (which know the wrapperKey) can pass the\n // correct shape. See FormatHandler<T, TSchema> in adt-plugin for the\n // same pattern.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: { build: (data: any, options?: { pretty?: boolean }) => string };\n wrapperKey: string;\n }\n> = {\n TTYP: {\n schema: adtContract.ddic.tabletypes.bodySchema,\n wrapperKey: 'tableType',\n },\n DOMA: { schema: adtContract.ddic.domains.bodySchema, wrapperKey: 'domain' },\n DTEL: {\n schema: adtContract.ddic.dataelements.bodySchema,\n wrapperKey: 'wbobj',\n },\n CLAS: { schema: adtContract.oo.classes.bodySchema, wrapperKey: 'abapClass' },\n INTF: {\n schema: adtContract.oo.interfaces.bodySchema,\n wrapperKey: 'abapInterface',\n },\n PROG: {\n schema: adtContract.programs.programs.bodySchema,\n wrapperKey: 'abapProgram',\n },\n FUGR: {\n schema: adtContract.functions.groups.bodySchema,\n wrapperKey: 'abapFunctionGroup',\n },\n DEVC: {\n schema: adtContract.packages.bodySchema,\n wrapperKey: 'package',\n },\n};\n\n/**\n * Expand glob patterns to matching file paths.\n * Passes through literal filenames unchanged.\n */\nasync function expandGlobs(patterns: string[], cwd: string): Promise<string[]> {\n const results: string[] = [];\n for (const pattern of patterns) {\n if (/[*?[\\]{}]/.test(pattern)) {\n for await (const match of nativeGlob(pattern, { cwd })) {\n results.push(match);\n }\n } else {\n results.push(pattern);\n }\n }\n return results;\n}\n\n/**\n * Walk up from a directory to find the nearest ancestor containing .abapgit.xml.\n * Returns the resolved absolute path to the repo root, or undefined if not found.\n */\nfunction findAbapGitRoot(startDir: string): string | undefined {\n let dir = resolve(startDir);\n const root = resolve('/');\n\n while (dir !== root) {\n if (existsSync(join(dir, '.abapgit.xml'))) {\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return undefined;\n}\n\n/**\n * Scan an abapGit repository directory for all supported XML metadata files.\n * Returns relative paths to each .xml file (excluding .abapgit.xml and package.devc.xml).\n */\nasync function scanAbapGitFiles(repoRoot: string): Promise<string[]> {\n const supportedTypes = new Set(\n getSupportedTypes().map((t) => t.toLowerCase()),\n );\n const files: string[] = [];\n\n for await (const match of nativeGlob('**/*.xml', { cwd: repoRoot })) {\n if (match.endsWith('.abapgit.xml')) continue;\n if (match.endsWith('package.devc.xml')) continue;\n\n const filename = basename(match);\n const parsed = parseAbapGitFilename(filename);\n if (!parsed) continue;\n if (parsed.extension !== 'xml') continue;\n if (!supportedTypes.has(parsed.type.toLowerCase())) continue;\n\n files.push(match);\n }\n\n return [...files].sort((a: string, b: string) => a.localeCompare(b));\n}\n\n/**\n * Collect all local files belonging to one abapGit object.\n *\n * Given the XML metadata file, scans the same directory for companion\n * .abap files that share the same name.type prefix.\n *\n * @returns Map of relative filename → content\n */\nfunction collectLocalFiles(\n xmlPath: string,\n objectName: string,\n fileExtension: string,\n): Map<string, string> {\n const dir = dirname(xmlPath);\n const prefix = `${objectName}.${fileExtension}`;\n const files = new Map<string, string>();\n\n for (const entry of readdirSync(dir)) {\n if (entry.toLowerCase().startsWith(prefix)) {\n const fullPath = join(dir, entry);\n files.set(entry.toLowerCase(), readFileSync(fullPath, 'utf-8'));\n }\n }\n\n return files;\n}\n\n/**\n * Project `source` onto `reference`'s key structure.\n *\n * Recursively keeps only the keys from `source` that also exist in\n * `reference`. For arrays, builds a **union** of all keys across all\n * reference elements as the template — because different elements may\n * have different optional fields (e.g. DD03P entries where some have\n * DECIMALS and others don't).\n *\n * This ensures the remote object only contains fields the local cares\n * about, so serializer-added extras (LANGDEP, POSITION, etc.) vanish.\n */\nfunction projectOnto(source: unknown, reference: unknown): unknown {\n if (reference === null || reference === undefined) return source;\n if (source === null || source === undefined) return source;\n\n // Both arrays — build union template from ALL reference elements\n if (Array.isArray(reference) && Array.isArray(source)) {\n if (reference.length === 0) return source;\n\n // Merge all reference elements into a union shape\n const unionShape = mergeObjectKeys(reference);\n if (unionShape === undefined) return source;\n\n return source.map((item) => projectOnto(item, unionShape));\n }\n\n // Both objects — keep only keys present in reference\n if (\n typeof reference === 'object' &&\n typeof source === 'object' &&\n !Array.isArray(reference) &&\n !Array.isArray(source)\n ) {\n const ref = reference as Record<string, unknown>;\n const src = source as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(ref)) {\n if (key in src) {\n result[key] = projectOnto(src[key], ref[key]);\n }\n }\n return result;\n }\n\n // Primitives — return source as-is\n return source;\n}\n\n/**\n * Merge all keys from an array of objects into a single union object.\n * Each key gets the first non-undefined value found across elements.\n * Used to build the \"widest\" template for array element projection.\n */\nfunction mergeObjectKeys(\n items: unknown[],\n): Record<string, unknown> | undefined {\n const objects = items.filter(\n (item): item is Record<string, unknown> =>\n item !== null && typeof item === 'object' && !Array.isArray(item),\n );\n if (objects.length === 0) return undefined;\n\n const union: Record<string, unknown> = {};\n for (const obj of objects) {\n for (const [key, value] of Object.entries(obj)) {\n if (!(key in union) || union[key] === undefined) {\n union[key] = value;\n }\n }\n }\n return union;\n}\n\n/**\n * Normalize an XML pair for comparison.\n *\n * 1. Parse both local and remote through the schema (strips formatting)\n * 2. Project remote values onto local's field structure (strips extras)\n * 3. Rebuild both through the same builder (identical formatting)\n *\n * Returns [normalizedLocal, normalizedRemote].\n */\nfunction normalizeXmlPair(\n localXml: string,\n remoteXml: string,\n handler: ObjectHandler,\n): [string, string] {\n try {\n const localParsed = handler.schema.parse(localXml);\n const remoteParsed = handler.schema.parse(remoteXml);\n\n // Project remote onto local's shape — drop fields local doesn't have\n const remoteProjected = projectOnto(remoteParsed, localParsed);\n\n const normalizedLocal = handler.schema.build(localParsed, { pretty: true });\n const normalizedRemote = handler.schema.build(\n remoteProjected as typeof localParsed,\n { pretty: true },\n );\n\n return [normalizedLocal, normalizedRemote];\n } catch {\n // If parsing fails, return as-is\n return [localXml, remoteXml];\n }\n}\n\n/**\n * Print a unified diff with optional color.\n * Returns true if differences were found.\n * When silent=true, skips printing but still detects differences.\n */\nfunction printDiff(\n localLabel: string,\n remoteLabel: string,\n localContent: string,\n remoteContent: string,\n contextLines: number,\n useColor: boolean,\n silent = false,\n): boolean {\n const local = localContent.endsWith('\\n')\n ? localContent\n : localContent + '\\n';\n const remote = remoteContent.endsWith('\\n')\n ? remoteContent\n : remoteContent + '\\n';\n\n if (local === remote) return false;\n\n if (silent) return true;\n\n const patch = createTwoFilesPatch(\n `a/${localLabel}`,\n `b/${remoteLabel}`,\n local,\n remote,\n 'local',\n 'remote (SAP)',\n { context: contextLines },\n );\n\n for (const line of patch.split('\\n')) {\n if (!useColor) {\n console.log(line);\n continue;\n }\n if (line.startsWith('+++') || line.startsWith('---')) {\n console.log(chalk.bold(line));\n } else if (line.startsWith('+')) {\n console.log(chalk.green(line));\n } else if (line.startsWith('-')) {\n console.log(chalk.red(line));\n } else if (line.startsWith('@@')) {\n console.log(chalk.cyan(line));\n } else {\n console.log(line);\n }\n }\n\n return true;\n}\n\n/** Result of diffing a single file */\ninterface DiffResult {\n objectName: string;\n objectType: string;\n hasDifferences: boolean;\n fileCount: number;\n identicalCount: number;\n error?: string;\n}\n\n/**\n * Diff a single abapGit XML file against SAP remote.\n * Returns a result object indicating whether differences were found.\n */\nasync function diffSingleFile(\n filePath: string,\n ctx: CliContext,\n adk: AdkFactory,\n options: {\n contextLines: number;\n useColor: boolean;\n source: boolean;\n raw: boolean;\n summary?: boolean;\n },\n): Promise<DiffResult> {\n const { contextLines, useColor, source, raw, summary } = options;\n const fullPath = resolve(ctx.cwd, filePath);\n\n if (!existsSync(fullPath)) {\n return {\n objectName: filePath,\n objectType: '?',\n hasDifferences: false,\n fileCount: 0,\n identicalCount: 0,\n error: `File not found: ${fullPath}`,\n };\n }\n\n // Parse filename to detect type\n const filename = basename(fullPath);\n const parsed = parseAbapGitFilename(filename);\n if (!parsed) {\n return {\n objectName: filename,\n objectType: '?',\n hasDifferences: false,\n fileCount: 0,\n identicalCount: 0,\n error: `Cannot parse filename: ${filename}. Expected abapGit format: name.type.xml`,\n };\n }\n\n if (parsed.extension !== 'xml') {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 0,\n identicalCount: 0,\n error: `Expected .xml metadata file, got .${parsed.extension}. Pass the .xml file, not .abap.`,\n };\n }\n\n // Validate --source option\n if (source && parsed.type !== 'TABL') {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 0,\n identicalCount: 0,\n error: `Source format is only supported for TABL objects. Got: ${parsed.type}`,\n };\n }\n\n // Validate mutual exclusion of --source and --raw\n if (source && raw) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 0,\n identicalCount: 0,\n error: '--source and --raw are mutually exclusive',\n };\n }\n\n // Look up handler from abapGit registry\n const handler = getHandler(parsed.type);\n if (!handler) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 0,\n identicalCount: 0,\n error: `Unsupported object type: ${parsed.type}. Supported: ${getSupportedTypes().join(', ')}`,\n };\n }\n\n // Collect local files for this object\n const objectName = parsed.name.toLowerCase();\n const localFiles = collectLocalFiles(\n fullPath,\n objectName,\n handler.fileExtension,\n );\n\n if (!summary) {\n console.log(\n `\\n${useColor ? chalk.bold('Diff:') : 'Diff:'} ${parsed.name} (${parsed.type}) — ${localFiles.size} file(s)`,\n );\n }\n\n // Parse local XML to extract ADK type info via fromAbapGit\n const localXml = readFileSync(fullPath, 'utf-8');\n let adkType = parsed.type;\n\n if (handler.fromAbapGit) {\n try {\n const parsedXml = handler.schema.parse(localXml);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const values = (parsedXml as any)?.abapGit?.abap?.values ?? {};\n const payload = handler.fromAbapGit(values);\n if (typeof payload.type === 'string') {\n adkType = payload.type;\n }\n } catch {\n // Fall through — use filename-derived type\n }\n }\n\n // Fetch remote ADK object\n if (!summary) {\n console.log(\n `${useColor ? chalk.dim('Fetching') : 'Fetching'} ${parsed.name} (${adkType}) from SAP...`,\n );\n }\n\n const remoteObjRaw = adk.get(parsed.name, adkType);\n\n // Narrow to AdkObject (excludes AdkGenericObject for unregistered types)\n if (!(remoteObjRaw instanceof AdkObject)) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: localFiles.size,\n identicalCount: 0,\n error: `Unsupported ADK type: ${adkType} (no registered handler)`,\n };\n }\n const remoteObj = remoteObjRaw;\n\n try {\n await remoteObj.load();\n } catch (error) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: localFiles.size,\n identicalCount: 0,\n error: `Failed to load remote object: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n // ========================================\n // Source format: compare ADK source (e.g. CDS DDL)\n // ========================================\n if (source) {\n const localSource = tablXmlToCdsDdl(localXml);\n\n let remoteSource: string;\n try {\n remoteSource = await (\n remoteObj as unknown as { getSource(): Promise<string> }\n ).getSource();\n } catch (error) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 1,\n identicalCount: 0,\n error: `Failed to fetch remote source: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n // Project remote onto local's annotation set — same principle as XML path.\n // If local XML doesn't have a field (e.g. MATEFLAG), strip the\n // corresponding annotation from remote so it doesn't appear as a diff.\n const localAnnotations = new Set(\n localSource\n .split('\\n')\n .filter((l) => l.startsWith('@'))\n .map((l) => l.split(':')[0].trim()),\n );\n remoteSource = remoteSource\n .split('\\n')\n .filter((l) => {\n if (!l.startsWith('@')) return true;\n const name = l.split(':')[0].trim();\n return localAnnotations.has(name);\n })\n .join('\\n');\n\n const sourceFile = `${objectName}.tabl.acds`;\n const diffFound = printDiff(\n sourceFile,\n sourceFile,\n localSource,\n remoteSource,\n contextLines,\n useColor,\n summary,\n );\n\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: diffFound,\n fileCount: 1,\n identicalCount: diffFound ? 0 : 1,\n };\n }\n\n // ========================================\n // Raw mode: compare ADT-level XML payloads\n // ========================================\n if (raw) {\n const adtSchema = adtSchemaMap[parsed.type];\n if (!adtSchema) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 1,\n identicalCount: 0,\n error: `Raw mode not supported for ${parsed.type}: no ADT schema mapping. Supported: ${Object.keys(adtSchemaMap).join(', ')}`,\n };\n }\n\n const { schema: rawSchema, wrapperKey } = adtSchema;\n\n // Build remote ADT XML from loaded data\n let remoteAdtXml: string;\n try {\n const remoteData = await remoteObj.data();\n remoteAdtXml = rawSchema.build(\n { [wrapperKey]: remoteData },\n { pretty: true },\n );\n } catch (e) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 1,\n identicalCount: 0,\n error: `Failed to build remote ADT XML: ${e instanceof Error ? e.message : String(e)}`,\n };\n }\n\n // Parse local abapGit XML → fromAbapGit() → local ADK data\n let localAdtXml: string | undefined;\n if (handler.fromAbapGit) {\n try {\n const parsedXml = handler.schema.parse(localXml);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const values = (parsedXml as any)?.abapGit?.abap?.values ?? {};\n const localPayload = handler.fromAbapGit(values);\n\n // Merge local overrides onto remote's full data (remote is template)\n const remoteData = await remoteObj.data();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const merged = { ...(remoteData as any), ...localPayload };\n localAdtXml = rawSchema.build(\n { [wrapperKey]: merged },\n { pretty: true },\n );\n } catch (e) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 1,\n identicalCount: 0,\n error: `Failed to build local ADT XML: ${e instanceof Error ? e.message : String(e)}`,\n };\n }\n }\n\n if (!localAdtXml) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: 1,\n identicalCount: 0,\n error: `Raw mode not supported for ${parsed.type}: no fromAbapGit() mapping`,\n };\n }\n\n const xmlFile = `${objectName}.${parsed.type.toLowerCase()}.adt.xml`;\n const diffFound = printDiff(\n xmlFile,\n xmlFile,\n localAdtXml,\n remoteAdtXml,\n contextLines,\n useColor,\n summary,\n );\n\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: diffFound,\n fileCount: 1,\n identicalCount: diffFound ? 0 : 1,\n };\n }\n\n // Serialize remote using the same handler → produces SerializedFile[]\n let remoteFiles;\n try {\n remoteFiles = await handler.serialize(remoteObj);\n } catch (error) {\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences: false,\n fileCount: localFiles.size,\n identicalCount: 0,\n error: `Failed to serialize remote object: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n // Build remote file map (lowercase path → content)\n const remoteMap = new Map<string, string>();\n for (const f of remoteFiles) {\n remoteMap.set(f.path.toLowerCase(), f.content);\n }\n\n // Diff each file\n let hasDifferences = false;\n let identicalCount = 0;\n\n for (const [localPath, localContent] of localFiles) {\n const remoteContent = remoteMap.get(localPath);\n if (remoteContent === undefined) {\n if (!summary) {\n console.log(\n useColor\n ? chalk.yellow(`\\n + Only in local: ${localPath}`)\n : `\\n + Only in local: ${localPath}`,\n );\n }\n hasDifferences = true;\n continue;\n }\n\n // For XML files: normalize both through schema, projecting remote\n // onto local's field set to strip serializer-added extras\n const isXml = localPath.endsWith('.xml');\n let diffLocal = localContent;\n let diffRemote = remoteContent;\n if (isXml) {\n [diffLocal, diffRemote] = normalizeXmlPair(\n localContent,\n remoteContent,\n handler,\n );\n }\n\n const diffFound = printDiff(\n localPath,\n localPath,\n diffLocal,\n diffRemote,\n contextLines,\n useColor,\n summary,\n );\n if (diffFound) {\n hasDifferences = true;\n } else {\n identicalCount++;\n }\n }\n\n // Files present in remote but not locally\n for (const [remotePath] of remoteMap) {\n if (!localFiles.has(remotePath)) {\n if (!summary) {\n console.log(\n useColor\n ? chalk.yellow(`\\n - Only in remote: ${remotePath}`)\n : `\\n - Only in remote: ${remotePath}`,\n );\n }\n hasDifferences = true;\n }\n }\n\n return {\n objectName: parsed.name,\n objectType: parsed.type,\n hasDifferences,\n fileCount: localFiles.size,\n identicalCount,\n };\n}\n\nexport const diffCommand: CliCommandPlugin = {\n name: 'diff',\n description:\n 'Compare local abapGit files against SAP remote (any supported object type)',\n\n arguments: [\n {\n name: '[files...]',\n description: `Local .xml files or glob patterns to compare (e.g., zcl_myclass.clas.xml, *.tabl.xml). When omitted, scans the abapGit repo in the current directory. Supported types: ${getSupportedTypes().join(', ')}`,\n },\n ],\n\n options: [\n {\n flags: '--no-color',\n description: 'Disable colored output',\n },\n {\n flags: '-c, --context <lines>',\n description: 'Number of context lines in diff',\n default: '3',\n },\n {\n flags: '-s, --source',\n description: 'Compare ADK source instead of XML (TABL only)',\n },\n {\n flags: '-r, --raw',\n description:\n 'Compare ADT-level XML payloads (what GET returns vs what PUT would send)',\n },\n {\n flags: '-p, --package <name>',\n description:\n 'Scan all abapGit files in the current directory (package name is informational)',\n },\n {\n flags: '-f, --full',\n description:\n 'Show full unified diffs (default in single-file mode; in package/multi-file mode only summary is shown unless --full is given)',\n },\n ],\n\n async execute(args: Record<string, unknown>, ctx: CliContext) {\n const filePatterns = (args.files as string[]) ?? [];\n const contextLines = Number.parseInt(\n String((args.context as string | number | undefined) ?? '3'),\n 10,\n );\n const useColor = args.color !== false;\n const source = args.source === true;\n const raw = args.raw === true;\n const packageName = args.package as string | undefined;\n const fullDiffs = args.full === true;\n\n let files: string[];\n let scanMode = false;\n let repoRoot: string | undefined;\n\n if (filePatterns.length > 0) {\n // Explicit files/globs — expand as before\n files = await expandGlobs(filePatterns, ctx.cwd);\n if (files.length === 0) {\n ctx.logger.error('No files matched the given pattern(s).');\n process.exit(1);\n }\n } else {\n // No files given — scan mode.\n // If --package given, or auto-detect abapGit repo root from cwd.\n repoRoot = findAbapGitRoot(ctx.cwd);\n if (!repoRoot) {\n ctx.logger.error(\n packageName\n ? 'No .abapgit.xml found in current directory or parents.'\n : 'No files specified and no .abapgit.xml found. Usage: adt diff <file...> or run from an abapGit repo directory.',\n );\n process.exit(1);\n }\n\n scanMode = true;\n const scannedFiles = await scanAbapGitFiles(repoRoot);\n if (scannedFiles.length === 0) {\n ctx.logger.error('No supported abapGit objects found in repository.');\n process.exit(1);\n }\n\n // Convert to paths relative to cwd\n files = scannedFiles.map((f) => relative(ctx.cwd, join(repoRoot!, f)));\n\n const pkgSuffix = packageName ? ` (package: ${packageName})` : '';\n ctx.logger.info(\n `📦 Scanning ${scannedFiles.length} object(s) in ${repoRoot}${pkgSuffix}...`,\n );\n }\n\n // In scan mode default to summary (suppress diffs), unless --full\n const summaryMode = scanMode && !fullDiffs;\n\n // Need ADT client for remote comparison\n if (!ctx.getAdtClient) {\n ctx.logger.error('ADT client not available. Run: adt auth login');\n process.exit(1);\n }\n\n // Create ADT client and ADK once, shared across all files\n const client = await ctx.getAdtClient!();\n const adk = createAdk(client as AdtClient);\n\n // Diff each file\n const results: DiffResult[] = [];\n for (const file of files) {\n const result = await diffSingleFile(file, ctx, adk, {\n contextLines,\n useColor,\n source,\n raw,\n summary: summaryMode,\n });\n\n if (result.error && !summaryMode) {\n ctx.logger.error(result.error);\n }\n\n results.push(result);\n }\n\n // Summary\n const totalFiles = results.length;\n const withDiffs = results.filter((r) => r.hasDifferences).length;\n const withErrors = results.filter((r) => r.error).length;\n const identical = totalFiles - withDiffs - withErrors;\n\n console.log('');\n\n if (scanMode) {\n // Package/scan mode: always show per-object status table\n for (const r of results) {\n let icon: string;\n let line: string;\n if (r.error) {\n icon = '⚠️';\n line = `${r.objectType} ${r.objectName}: ${r.error}`;\n } else if (r.hasDifferences) {\n icon = '❌';\n line = `${r.objectType} ${r.objectName}`;\n } else {\n icon = '✅';\n line = `${r.objectType} ${r.objectName}`;\n }\n\n if (useColor) {\n if (r.error) {\n console.log(chalk.yellow(` ${icon} ${line}`));\n } else if (r.hasDifferences) {\n console.log(chalk.red(` ${icon} ${line}`));\n } else {\n console.log(chalk.green(` ${icon} ${line}`));\n }\n } else {\n console.log(` ${icon} ${line}`);\n }\n }\n\n console.log('');\n const summaryParts: string[] = [\n `${totalFiles} object(s)`,\n `${identical} identical`,\n ];\n if (withDiffs > 0) summaryParts.push(`${withDiffs} changed`);\n if (withErrors > 0) summaryParts.push(`${withErrors} errors`);\n const summaryLine = summaryParts.join(', ');\n\n if (withDiffs > 0 || withErrors > 0) {\n console.log(\n useColor ? chalk.red(`📋 ${summaryLine}`) : `📋 ${summaryLine}`,\n );\n process.exit(1);\n }\n console.log(\n useColor ? chalk.green(`📋 ${summaryLine}`) : `📋 ${summaryLine}`,\n );\n return;\n }\n\n if (totalFiles === 1) {\n // Single-file mode: keep original concise output\n const r = results[0];\n if (r.error) {\n // Error already printed above\n process.exit(1);\n }\n if (r.hasDifferences) {\n const identicalSuffix =\n r.identicalCount > 0\n ? ` (${r.identicalCount} file(s) identical)`\n : '';\n console.log(\n useColor\n ? chalk.red('Differences found.') +\n (r.identicalCount > 0 ? chalk.dim(identicalSuffix) : '')\n : `Differences found.${identicalSuffix}`,\n );\n process.exit(1);\n }\n console.log(\n useColor\n ? chalk.green(\n `No differences found. (${r.identicalCount} file(s) identical)`,\n )\n : `No differences found. (${r.identicalCount} file(s) identical)`,\n );\n return;\n }\n\n // Multi-file summary (explicit glob, not scan mode)\n const parts: string[] = [\n `${totalFiles} object(s) checked`,\n `${identical} identical`,\n ];\n if (withDiffs > 0) parts.push(`${withDiffs} with differences`);\n if (withErrors > 0) parts.push(`${withErrors} with errors`);\n const summaryText = parts.join(', ');\n\n if (withDiffs > 0 || withErrors > 0) {\n console.log(\n useColor\n ? chalk.red(`Diff summary: ${summaryText}`)\n : `Diff summary: ${summaryText}`,\n );\n process.exit(1);\n }\n console.log(\n useColor\n ? chalk.green(`Diff summary: ${summaryText}`)\n : `Diff summary: ${summaryText}`,\n );\n },\n};\n\nexport default diffCommand;\n"],"mappings":";;;;;;;;;;;AA0DA,MAAM,kBAA0C;CAC9C,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;AACR;;AAGA,M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;EACF;EAEA,IAAI,eAAe,GAAG;GAEpB,MAAM,IAAI,QAAQ;GAClB,IAAI,EAAE,OAEJ,QAAQ,KAAK,CAAC;GAEhB,IAAI,EAAE,gBAAgB;IACpB,MAAM,kBACJ,EAAE,iBAAiB,IACf,KAAK,EAAE,eAAe,uBACtB;IACN,QAAQ,IACN,WACI,MAAM,IAAI,oBAAoB,KAC3B,EAAE,iBAAiB,IAAI,MAAM,IAAI,eAAe,IAAI,MACvD,qBAAqB,iBAC3B;IACA,QAAQ,KAAK,CAAC;GAChB;GACA,QAAQ,IACN,WACI,MAAM,MACJ,0BAA0B,EAAE,eAAe,oBAC7C,IACA,0BAA0B,EAAE,eAAe,oBACjD;GACA;EACF;EAGA,MAAM,QAAkB,CACtB,GAAG,WAAW,qBACd,GAAG,UAAU,WACf;EACA,IAAI,YAAY,GAAG,MAAM,KAAK,GAAG,UAAU,kBAAkB;EAC7D,IAAI,aAAa,GAAG,MAAM,KAAK,GAAG,WAAW,aAAa;EAC1D,MAAM,cAAc,MAAM,KAAK,IAAI;EAEnC,IAAI,YAAY,KAAK,aAAa,GAAG;GACnC,QAAQ,IACN,WACI,MAAM,IAAI,iBAAiB,aAAa,IACxC,iBAAiB,aACvB;GACA,QAAQ,KAAK,CAAC;EAChB;EACA,QAAQ,IACN,WACI,MAAM,MAAM,iBAAiB,aAAa,IAC1C,iBAAiB,aACvB;CACF;AACF"}
@@ -0,0 +1,72 @@
1
+ import diffCommand from "./commands/diff.mjs";
2
+ //#region src/lib/abapgit-to-cds.d.ts
3
+ /**
4
+ * abapGit DD02V/DD03P → CDS DDL Source Builder
5
+ *
6
+ * Reverse mapping of cds-to-abapgit.ts — reconstructs CDS DDL source code
7
+ * from parsed abapGit XML data (DD02V header + DD03P field entries).
8
+ *
9
+ * Used by `adt diff` to compare local abapGit serialized files against
10
+ * SAP remote CDS source fetched via ADT /source/main endpoint.
11
+ */
12
+ interface DD02VData {
13
+ TABNAME?: string;
14
+ DDLANGUAGE?: string;
15
+ TABCLASS?: string;
16
+ LANGDEP?: string;
17
+ DDTEXT?: string;
18
+ MASTERLANG?: string;
19
+ CONTFLAG?: string;
20
+ EXCLASS?: string;
21
+ AUTHCLASS?: string;
22
+ CLIDEP?: string;
23
+ BUFFERED?: string;
24
+ MATEFLAG?: string;
25
+ SHLPEXI?: string;
26
+ }
27
+ interface DD03PData {
28
+ FIELDNAME?: string;
29
+ POSITION?: string;
30
+ KEYFLAG?: string;
31
+ ROLLNAME?: string;
32
+ ADMINFIELD?: string;
33
+ INTTYPE?: string;
34
+ INTLEN?: string;
35
+ NOTNULL?: string;
36
+ DATATYPE?: string;
37
+ LENG?: string;
38
+ DECIMALS?: string;
39
+ SHLPORIGIN?: string;
40
+ MASK?: string;
41
+ COMPTYPE?: string;
42
+ REFTABLE?: string;
43
+ REFFIELD?: string;
44
+ PRECFIELD?: string;
45
+ DDTEXT?: string;
46
+ DOMNAME?: string;
47
+ }
48
+ /**
49
+ * Build CDS DDL source from DD02V header and DD03P field entries.
50
+ *
51
+ * @param dd02v - Table/structure header data
52
+ * @param dd03pEntries - Field entries (sorted by POSITION if present)
53
+ * @returns CDS DDL source string
54
+ */
55
+ declare function buildCdsDdl(dd02v: DD02VData, dd03pEntries: DD03PData[]): string;
56
+ /**
57
+ * Parse abapGit TABL XML content and extract DD02V/DD03P data.
58
+ */
59
+ declare function parseTablXml(xmlContent: string): {
60
+ dd02v: DD02VData;
61
+ dd03p: DD03PData[];
62
+ };
63
+ /**
64
+ * Parse abapGit TABL XML and build CDS DDL source.
65
+ *
66
+ * @param xmlContent - Raw XML content of a .tabl.xml file
67
+ * @returns CDS DDL source string
68
+ */
69
+ declare function tablXmlToCdsDdl(xmlContent: string): string;
70
+ //#endregion
71
+ export { type DD02VData, type DD03PData, buildCdsDdl, diffCommand, parseTablXml, tablXmlToCdsDdl };
72
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/lib/abapgit-to-cds.ts"],"mappings":";;;;;;;;;;;UAeiB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;iBAuHc,YACd,OAAO,WACP,cAAc;;;;iBAwTA,aAAa;EAC3B,OAAO;EACP,OAAO;;;;;;;;iBA0BO,gBAAgB"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { i as tablXmlToCdsDdl, n as buildCdsDdl, r as parseTablXml, t as diffCommand } from "./diff-rq6zDvAI.mjs";
2
+ export { buildCdsDdl, diffCommand, parseTablXml, tablXmlToCdsDdl };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abapify/adt-diff",
3
- "version": "0.4.0",
3
+ "version": "0.4.3",
4
4
  "description": "Diff CLI plugin for adt-cli - compare local serialized files against SAP remote source",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -27,17 +27,17 @@
27
27
  "abapgit"
28
28
  ],
29
29
  "dependencies": {
30
- "@abapify/adk": "0.4.0",
31
- "@abapify/adt-contracts": "0.4.0",
32
- "@abapify/adt-plugin": "0.4.0",
33
- "@abapify/adt-plugin-abapgit": "0.4.0",
30
+ "@abapify/adk": "0.4.3",
31
+ "@abapify/adt-contracts": "0.4.3",
32
+ "@abapify/adt-plugin": "0.4.3",
33
+ "@abapify/adt-plugin-abapgit": "0.4.3",
34
34
  "chalk": "^5.6.2",
35
35
  "diff": "^8.0.3",
36
36
  "fast-xml-parser": "^5.5.5"
37
37
  },
38
38
  "module": "./dist/index.mjs",
39
39
  "devDependencies": {
40
- "@abapify/adt-fixtures": "0.4.0"
40
+ "@abapify/adt-fixtures": "0.4.3"
41
41
  },
42
42
  "repository": {
43
43
  "type": "git",