@babamba2/abap-mcp-adt-powerup 4.14.0 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/dist/handlers/adobeform/high/handleDeleteAdobeForm.d.ts +50 -0
  3. package/dist/handlers/adobeform/high/handleDeleteAdobeForm.d.ts.map +1 -0
  4. package/dist/handlers/adobeform/high/handleDeleteAdobeForm.js +91 -0
  5. package/dist/handlers/adobeform/high/handleDeleteAdobeForm.js.map +1 -0
  6. package/dist/handlers/common/high/handleActivateObjects.d.ts.map +1 -1
  7. package/dist/handlers/common/high/handleActivateObjects.js +4 -1
  8. package/dist/handlers/common/high/handleActivateObjects.js.map +1 -1
  9. package/dist/handlers/include/high/handleUpdateInclude.d.ts +2 -0
  10. package/dist/handlers/include/high/handleUpdateInclude.d.ts.map +1 -1
  11. package/dist/handlers/include/high/handleUpdateInclude.js +7 -19
  12. package/dist/handlers/include/high/handleUpdateInclude.js.map +1 -1
  13. package/dist/handlers/program/high/handleCreateProgram.d.ts +9 -0
  14. package/dist/handlers/program/high/handleCreateProgram.d.ts.map +1 -1
  15. package/dist/handlers/program/high/handleCreateProgram.js +62 -1
  16. package/dist/handlers/program/high/handleCreateProgram.js.map +1 -1
  17. package/dist/handlers/screen/high/handleCreateScreen.d.ts.map +1 -1
  18. package/dist/handlers/screen/high/handleCreateScreen.js +1 -0
  19. package/dist/handlers/screen/high/handleCreateScreen.js.map +1 -1
  20. package/dist/handlers/screen/high/handleDeleteScreen.d.ts.map +1 -1
  21. package/dist/handlers/screen/high/handleDeleteScreen.js +1 -0
  22. package/dist/handlers/screen/high/handleDeleteScreen.js.map +1 -1
  23. package/dist/handlers/screen/high/handleUpdateScreen.d.ts.map +1 -1
  24. package/dist/handlers/screen/high/handleUpdateScreen.js +4 -10
  25. package/dist/handlers/screen/high/handleUpdateScreen.js.map +1 -1
  26. package/dist/handlers/screen/low/handleCreateScreen.d.ts +5 -0
  27. package/dist/handlers/screen/low/handleCreateScreen.d.ts.map +1 -1
  28. package/dist/handlers/screen/low/handleCreateScreen.js +6 -1
  29. package/dist/handlers/screen/low/handleCreateScreen.js.map +1 -1
  30. package/dist/handlers/screen/low/handleDeleteScreen.d.ts +5 -0
  31. package/dist/handlers/screen/low/handleDeleteScreen.d.ts.map +1 -1
  32. package/dist/handlers/screen/low/handleDeleteScreen.js +6 -1
  33. package/dist/handlers/screen/low/handleDeleteScreen.js.map +1 -1
  34. package/dist/handlers/screen/low/handleUpdateScreen.d.ts +5 -0
  35. package/dist/handlers/screen/low/handleUpdateScreen.d.ts.map +1 -1
  36. package/dist/handlers/screen/low/handleUpdateScreen.js +9 -11
  37. package/dist/handlers/screen/low/handleUpdateScreen.js.map +1 -1
  38. package/dist/handlers/system/high/handleRuntimeCallDispatch.d.ts +46 -0
  39. package/dist/handlers/system/high/handleRuntimeCallDispatch.d.ts.map +1 -0
  40. package/dist/handlers/system/readonly/handleGetJobUsage.d.ts +6 -3
  41. package/dist/handlers/system/readonly/handleGetJobUsage.d.ts.map +1 -1
  42. package/dist/handlers/system/readonly/handleGetJobUsage.js +12 -8
  43. package/dist/handlers/system/readonly/handleGetJobUsage.js.map +1 -1
  44. package/dist/handlers/system/readonly/handleGetObjectVersionSource.d.ts +48 -0
  45. package/dist/handlers/system/readonly/handleGetObjectVersionSource.d.ts.map +1 -0
  46. package/dist/handlers/system/readonly/handleGetObjectVersionSource.js +109 -0
  47. package/dist/handlers/system/readonly/handleGetObjectVersionSource.js.map +1 -0
  48. package/dist/handlers/system/readonly/handleGetObjectVersions.d.ts +45 -0
  49. package/dist/handlers/system/readonly/handleGetObjectVersions.d.ts.map +1 -0
  50. package/dist/handlers/system/readonly/handleGetObjectVersions.js +110 -0
  51. package/dist/handlers/system/readonly/handleGetObjectVersions.js.map +1 -0
  52. package/dist/handlers/system/readonly/handleGetSqlQuery.d.ts.map +1 -1
  53. package/dist/handlers/system/readonly/handleGetSqlQuery.js +7 -1
  54. package/dist/handlers/system/readonly/handleGetSqlQuery.js.map +1 -1
  55. package/dist/handlers/system/readonly/handleGetTcodeUsage.d.ts +6 -3
  56. package/dist/handlers/system/readonly/handleGetTcodeUsage.d.ts.map +1 -1
  57. package/dist/handlers/system/readonly/handleGetTcodeUsage.js +13 -12
  58. package/dist/handlers/system/readonly/handleGetTcodeUsage.js.map +1 -1
  59. package/dist/handlers/unit_test/high/handleRunUnitTest.d.ts +27 -0
  60. package/dist/handlers/unit_test/high/handleRunUnitTest.d.ts.map +1 -1
  61. package/dist/handlers/unit_test/high/handleRunUnitTest.js +81 -4
  62. package/dist/handlers/unit_test/high/handleRunUnitTest.js.map +1 -1
  63. package/dist/lib/handlers/base/BaseHandlerGroup.d.ts.map +1 -1
  64. package/dist/lib/handlers/base/BaseHandlerGroup.js +12 -7
  65. package/dist/lib/handlers/base/BaseHandlerGroup.js.map +1 -1
  66. package/dist/lib/handlers/groups/HighLevelHandlersGroup.d.ts.map +1 -1
  67. package/dist/lib/handlers/groups/HighLevelHandlersGroup.js +5 -0
  68. package/dist/lib/handlers/groups/HighLevelHandlersGroup.js.map +1 -1
  69. package/dist/lib/handlers/groups/ReadOnlyHandlersGroup.d.ts.map +1 -1
  70. package/dist/lib/handlers/groups/ReadOnlyHandlersGroup.js +10 -0
  71. package/dist/lib/handlers/groups/ReadOnlyHandlersGroup.js.map +1 -1
  72. package/dist/lib/legacyTableRead.d.ts.map +1 -1
  73. package/dist/lib/legacyTableRead.js +4 -2
  74. package/dist/lib/legacyTableRead.js.map +1 -1
  75. package/dist/lib/objectVersions.d.ts +78 -0
  76. package/dist/lib/objectVersions.d.ts.map +1 -0
  77. package/dist/lib/objectVersions.js +234 -0
  78. package/dist/lib/objectVersions.js.map +1 -0
  79. package/dist/lib/odataRfc.d.ts +9 -0
  80. package/dist/lib/odataRfc.d.ts.map +1 -1
  81. package/dist/lib/odataRfc.js +129 -7
  82. package/dist/lib/odataRfc.js.map +1 -1
  83. package/dist/lib/policy/blocklist.d.ts +73 -0
  84. package/dist/lib/policy/blocklist.d.ts.map +1 -0
  85. package/dist/lib/smartForm.d.ts +114 -0
  86. package/dist/lib/smartForm.d.ts.map +1 -0
  87. package/dist/lib/smartFormContent.d.ts +2 -0
  88. package/dist/lib/smartFormContent.d.ts.map +1 -1
  89. package/dist/lib/smartFormContent.js +27 -0
  90. package/dist/lib/smartFormContent.js.map +1 -1
  91. package/dist/lib/sourceFileInput.d.ts +15 -0
  92. package/dist/lib/sourceFileInput.d.ts.map +1 -0
  93. package/dist/lib/sourceFileInput.js +63 -0
  94. package/dist/lib/sourceFileInput.js.map +1 -0
  95. package/dist/lib/sourcePatchInput.d.ts +160 -0
  96. package/dist/lib/sourcePatchInput.d.ts.map +1 -0
  97. package/dist/lib/sourcePatchInput.js +701 -0
  98. package/dist/lib/sourcePatchInput.js.map +1 -0
  99. package/dist/lib/sqlLineWrap.d.ts +17 -0
  100. package/dist/lib/sqlLineWrap.d.ts.map +1 -0
  101. package/dist/lib/sqlLineWrap.js +72 -0
  102. package/dist/lib/sqlLineWrap.js.map +1 -0
  103. package/dist/lib/wlUsageS4.d.ts +47 -0
  104. package/dist/lib/wlUsageS4.d.ts.map +1 -0
  105. package/dist/lib/wlUsageS4.js +132 -0
  106. package/dist/lib/wlUsageS4.js.map +1 -0
  107. package/dist/server/BaseMcpServer.d.ts.map +1 -1
  108. package/dist/server/BaseMcpServer.js +30 -15
  109. package/dist/server/BaseMcpServer.js.map +1 -1
  110. package/docs/user-guide/AVAILABLE_TOOLS.md +54 -5
  111. package/docs/user-guide/AVAILABLE_TOOLS_COMPACT.md +1 -1
  112. package/docs/user-guide/AVAILABLE_TOOLS_HIGH.md +21 -3
  113. package/docs/user-guide/AVAILABLE_TOOLS_LEGACY.md +59 -5
  114. package/docs/user-guide/AVAILABLE_TOOLS_LOW.md +1 -1
  115. package/docs/user-guide/AVAILABLE_TOOLS_READONLY.md +33 -2
  116. package/package.json +1 -1
@@ -0,0 +1,701 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEST_CODE_REFUSAL = exports.SOURCE_PATCH_TOOLS = exports.MAX_SOURCE_PATCHES = void 0;
4
+ exports.includeSourceUrl = includeSourceUrl;
5
+ exports.patchTargetOf = patchTargetOf;
6
+ exports.withSourcePatchesSchema = withSourcePatchesSchema;
7
+ exports.parseSourcePatches = parseSourcePatches;
8
+ exports.applySourcePatches = applySourcePatches;
9
+ exports.stripAbapComments = stripAbapComments;
10
+ exports.hasOrphanClassImplementation = hasOrphanClassImplementation;
11
+ exports.isReadChannel = isReadChannel;
12
+ exports.assertNotTestCode = assertNotTestCode;
13
+ exports.readNewestSource = readNewestSource;
14
+ exports.readCurrentSource = readCurrentSource;
15
+ exports.resolveSourcePatchesArg = resolveSourcePatchesArg;
16
+ exports.sameSource = sameSource;
17
+ exports.restoreAfterFailedPatch = restoreAfterFailedPatch;
18
+ exports.withUndoNote = withUndoNote;
19
+ exports.runWithPatchRestore = runWithPatchRestore;
20
+ exports.attachPatchedInfo = attachPatchedInfo;
21
+ /**
22
+ * `source_patches` — server-side patch input for the source-writing Update* tools.
23
+ *
24
+ * The caller sends only the changed fragments as exact replacements
25
+ * (`{ old_string, new_string, replace_all? }`, 1–50). Before the handler runs,
26
+ * the server reads the object's current source itself — the newest saved
27
+ * version (inactive when one exists, else active), because that is what the
28
+ * Update overwrites — applies the replacements in order and passes the result
29
+ * on as the tool's source argument. One call, no fetch, no local file.
30
+ *
31
+ * Rules:
32
+ * - source_patches is exclusive with the tool's source argument and with
33
+ * source_file — any presence of those keys, even "", refuses the call.
34
+ * - Matching runs on text with line endings normalised to \n (the patches
35
+ * too); a source with mixed line endings is patched as written instead.
36
+ * Each old_string must be non-empty and occur exactly once (overlapping
37
+ * occurrences count), unless replace_all (then at least once). Any
38
+ * failure refuses the WHOLE call — nothing is uploaded.
39
+ * - The uploaded text keeps the source's original line-ending style.
40
+ * - Test code is never patched: UpdateLocalTestClass, or FOR TESTING in the
41
+ * current or the patched source (comments and literals ignored) refuses
42
+ * the call — send the full source_code, which the plugin's blocklist hook
43
+ * scans. Business code passes, as a full upload of it does (the hook does
44
+ * not scan business code). No blocklist profile is read here.
45
+ * - The result gets `patched: { count, replacements, bytes, source_sha256 }`
46
+ * (sha of the uploaded text). The source is never echoed.
47
+ */
48
+ const node_crypto_1 = require("node:crypto");
49
+ const handleUpdateInclude_1 = require("../handlers/include/high/handleUpdateInclude");
50
+ const clients_1 = require("./clients");
51
+ const utils_1 = require("./utils");
52
+ exports.MAX_SOURCE_PATCHES = 50;
53
+ const up = (v) => String(v ?? '')
54
+ .trim()
55
+ .toUpperCase();
56
+ /** readResult.data → text, like the Get* handlers do. */
57
+ function dataText(readResult) {
58
+ if (!readResult || !readResult.readResult)
59
+ return undefined;
60
+ const d = readResult.readResult.data;
61
+ if (d === undefined || d === null)
62
+ return undefined;
63
+ return typeof d === 'string' ? d : JSON.stringify(d);
64
+ }
65
+ const clientRead = (pick, config) => async (ctx, args, version) => {
66
+ const client = (0, clients_1.createAdtClient)(ctx.connection, ctx.logger);
67
+ return dataText(await pick(client).read(config(args), version));
68
+ };
69
+ /**
70
+ * Include: the same source URL UpdateInclude writes — under the function
71
+ * group for a function-group include (function_group, or main_program
72
+ * SAPL<group>), else /programs/includes — with an explicit version.
73
+ */
74
+ function includeSourceUrl(args, version) {
75
+ const name = (0, utils_1.encodeSapObjectName)(up(args.include_name));
76
+ const fg = (0, handleUpdateInclude_1.functionGroupOf)(args);
77
+ const base = fg
78
+ ? `/sap/bc/adt/functions/groups/${(0, utils_1.encodeSapObjectName)(fg).toLowerCase()}/includes/${name.toLowerCase()}`
79
+ : `/sap/bc/adt/programs/includes/${name}`;
80
+ return `${base}/source/main?version=${version}`;
81
+ }
82
+ const readInclude = async (ctx, args, version) => {
83
+ const url = includeSourceUrl(args, version);
84
+ try {
85
+ const resp = await (0, utils_1.makeAdtRequestWithTimeout)(ctx.connection, url, 'GET', 'default');
86
+ const d = resp?.data;
87
+ return d === undefined || d === null ? undefined : String(d);
88
+ }
89
+ catch (e) {
90
+ if (e?.response?.status === 404)
91
+ return undefined;
92
+ throw e;
93
+ }
94
+ };
95
+ const TARGETS = {
96
+ UpdateProgram: {
97
+ codeField: 'source_code',
98
+ nameFields: ['program_name'],
99
+ singlePart: true,
100
+ read: clientRead((c) => c.getProgram(), (a) => ({ programName: up(a.program_name) })),
101
+ },
102
+ UpdateInclude: {
103
+ codeField: 'source_code',
104
+ nameFields: ['include_name'],
105
+ singlePart: true,
106
+ read: readInclude,
107
+ },
108
+ UpdateClass: {
109
+ codeField: 'source_code',
110
+ nameFields: ['class_name'],
111
+ read: clientRead((c) => c.getClass(), (a) => ({ className: up(a.class_name) })),
112
+ },
113
+ UpdateInterface: {
114
+ codeField: 'source_code',
115
+ nameFields: ['interface_name'],
116
+ singlePart: true,
117
+ read: clientRead((c) => c.getInterface(), (a) => ({ interfaceName: up(a.interface_name) })),
118
+ },
119
+ UpdateFunctionModule: {
120
+ codeField: 'source_code',
121
+ nameFields: ['function_group_name', 'function_module_name'],
122
+ singlePart: true,
123
+ read: clientRead((c) => c.getFunctionModule(), (a) => ({
124
+ functionModuleName: up(a.function_module_name),
125
+ functionGroupName: up(a.function_group_name),
126
+ })),
127
+ },
128
+ UpdateLocalTypes: {
129
+ codeField: 'local_types_code',
130
+ nameFields: ['class_name'],
131
+ activateField: 'activate_on_update',
132
+ read: clientRead((c) => c.getLocalTypes(), (a) => ({ className: up(a.class_name) })),
133
+ },
134
+ UpdateLocalDefinitions: {
135
+ codeField: 'definitions_code',
136
+ nameFields: ['class_name'],
137
+ activateField: 'activate_on_update',
138
+ read: clientRead((c) => c.getLocalDefinitions(), (a) => ({ className: up(a.class_name) })),
139
+ },
140
+ UpdateLocalMacros: {
141
+ codeField: 'macros_code',
142
+ nameFields: ['class_name'],
143
+ activateField: 'activate_on_update',
144
+ read: clientRead((c) => c.getLocalMacros(), (a) => ({ className: up(a.class_name) })),
145
+ },
146
+ UpdateLocalTestClass: {
147
+ codeField: 'test_class_code',
148
+ nameFields: ['class_name'],
149
+ activateField: 'activate_on_update',
150
+ read: clientRead((c) => c.getLocalTestClass(), (a) => ({ className: up(a.class_name) })),
151
+ },
152
+ };
153
+ /** Tools that accept source_patches. */
154
+ exports.SOURCE_PATCH_TOOLS = Object.keys(TARGETS);
155
+ /** Supported only when the tool's schema really carries the source field. */
156
+ function patchTargetOf(toolName, inputSchema) {
157
+ const t = TARGETS[toolName];
158
+ if (!t)
159
+ return undefined;
160
+ if (inputSchema && !inputSchema?.properties?.[t.codeField])
161
+ return undefined;
162
+ return t;
163
+ }
164
+ const PATCHES_DESCRIPTION = "Server-side patch: exact replacements applied to the object's current source (newest saved version — inactive if one exists, else active), then uploaded. Use instead of the full source when you know the exact current text of the lines you change. Each old_string must occur exactly once (or set replace_all); otherwise nothing is uploaded. Line endings are normalised for matching. Not together with the full source or source_file. Business code only: a source with test classes (FOR TESTING) or a local test class part is refused — send the full source.";
165
+ /**
166
+ * Schema with `source_patches` added and the source field no longer required
167
+ * (one of the inputs is checked at call time). Other tools pass unchanged.
168
+ */
169
+ function withSourcePatchesSchema(toolName, inputSchema) {
170
+ const t = patchTargetOf(toolName, inputSchema);
171
+ if (!t || !inputSchema?.properties)
172
+ return inputSchema;
173
+ return {
174
+ ...inputSchema,
175
+ properties: {
176
+ ...inputSchema.properties,
177
+ source_patches: {
178
+ type: 'array',
179
+ description: PATCHES_DESCRIPTION,
180
+ minItems: 1,
181
+ maxItems: exports.MAX_SOURCE_PATCHES,
182
+ items: {
183
+ type: 'object',
184
+ properties: {
185
+ old_string: {
186
+ type: 'string',
187
+ description: 'Exact current text (non-empty).',
188
+ },
189
+ new_string: {
190
+ type: 'string',
191
+ description: 'Replacement text (may be empty).',
192
+ },
193
+ replace_all: {
194
+ type: 'boolean',
195
+ description: 'Replace every occurrence. Default false.',
196
+ },
197
+ },
198
+ required: ['old_string', 'new_string'],
199
+ },
200
+ },
201
+ },
202
+ required: (inputSchema.required || []).filter((k) => k !== t.codeField),
203
+ };
204
+ }
205
+ const nl = (s) => s.replace(/\r\n?/g, '\n');
206
+ const snippet = (s) => {
207
+ const one = s.replace(/\s+/g, ' ').trim();
208
+ return one.length > 60 ? `${one.slice(0, 57)}...` : one;
209
+ };
210
+ /** Count occurrences, overlapping ones too ("aa" in "aaa" = 2). */
211
+ function occurrences(text, needle) {
212
+ let n = 0;
213
+ let i = text.indexOf(needle);
214
+ while (i !== -1) {
215
+ n++;
216
+ i = text.indexOf(needle, i + 1);
217
+ }
218
+ return n;
219
+ }
220
+ /** Line-ending style: 'crlf' / 'lf' when uniform (or none), 'mixed' otherwise (lone CR counts as mixed). */
221
+ function eolStyle(text) {
222
+ const crlf = /\r\n/.test(text);
223
+ const lf = /(^|[^\r])\n/.test(text);
224
+ const cr = /\r(?!\n)/.test(text);
225
+ if (cr || (crlf && lf))
226
+ return 'mixed';
227
+ return crlf ? 'crlf' : 'lf';
228
+ }
229
+ /** Validate the raw argument; throws a short error naming the bad patch. */
230
+ function parseSourcePatches(raw) {
231
+ if (!Array.isArray(raw))
232
+ throw new Error('source_patches must be an array');
233
+ if (raw.length < 1 || raw.length > exports.MAX_SOURCE_PATCHES)
234
+ throw new Error(`source_patches must hold 1–${exports.MAX_SOURCE_PATCHES} patches (got ${raw.length})`);
235
+ return raw.map((p, i) => {
236
+ if (!p || typeof p !== 'object' || Array.isArray(p))
237
+ throw new Error(`source_patches[${i}] must be an object`);
238
+ if (typeof p.old_string !== 'string' || p.old_string.length === 0)
239
+ throw new Error(`source_patches[${i}].old_string must be a non-empty string`);
240
+ if (typeof p.new_string !== 'string')
241
+ throw new Error(`source_patches[${i}].new_string must be a string`);
242
+ if (p.replace_all !== undefined && typeof p.replace_all !== 'boolean')
243
+ throw new Error(`source_patches[${i}].replace_all must be a boolean`);
244
+ if (nl(p.old_string) === nl(p.new_string))
245
+ throw new Error(`source_patches[${i}]: old_string and new_string are the same`);
246
+ return {
247
+ old_string: p.old_string,
248
+ new_string: p.new_string,
249
+ replace_all: p.replace_all === true,
250
+ };
251
+ });
252
+ }
253
+ /**
254
+ * Apply patches in order. Returns the new text in the source's line-ending
255
+ * style. Throws (nothing applied) when a patch does not match as required.
256
+ *
257
+ * Uniform line endings: matching on text normalised to \n, the result is
258
+ * written back in the source's style. Mixed line endings: the patches are
259
+ * applied to the raw text as given (no line is rewritten); an old_string
260
+ * that does not match the raw text refuses the call.
261
+ */
262
+ function applySourcePatches(source, patches) {
263
+ const style = eolStyle(source);
264
+ const mixed = style === 'mixed';
265
+ let text = mixed ? source : nl(source);
266
+ let replacements = 0;
267
+ patches.forEach((p, i) => {
268
+ const oldS = mixed ? p.old_string : nl(p.old_string);
269
+ const newS = mixed ? p.new_string : nl(p.new_string);
270
+ const n = occurrences(text, oldS);
271
+ if (n === 0 && mixed)
272
+ throw new Error(`source_patches[${i}]: old_string found 0 times in the current source as written ("${snippet(oldS)}"); the source has mixed line endings — nothing uploaded, send source_code.`);
273
+ if (n === 0)
274
+ throw new Error(`source_patches[${i}]: old_string found 0 times in the current source ("${snippet(oldS)}") — nothing uploaded. Copy old_string from the current source.`);
275
+ if (n > 1 && !p.replace_all)
276
+ throw new Error(`source_patches[${i}]: old_string found ${n} times ("${snippet(oldS)}") — nothing uploaded. Add surrounding lines to make it unique, or set replace_all.`);
277
+ // split/join replaces non-overlapping occurrences — count those, not n
278
+ const parts = text.split(oldS);
279
+ text = parts.join(newS);
280
+ replacements += parts.length - 1;
281
+ });
282
+ return {
283
+ text: style === 'crlf' ? text.replace(/\n/g, '\r\n') : text,
284
+ replacements,
285
+ };
286
+ }
287
+ /**
288
+ * ABAP source without comments and literal text — a character scanner, the
289
+ * same as the plugin hook's stripAbapNoise (ABAP mode): `*` in column 1 and
290
+ * `"` comment to the line end; '…' / `…` become '' / `` (doubled quote =
291
+ * escaped); a string template |…| keeps its delimiters and the CODE of its
292
+ * embedded expressions { … } (which may hold literals and templates of their
293
+ * own) and drops its text (\ escapes). '…', `…` and template text end at the
294
+ * line end. A quote inside one literal never opens another and never
295
+ * swallows the code after it.
296
+ */
297
+ function stripAbapComments(source) {
298
+ const s = nl(source);
299
+ const n = s.length;
300
+ const stack = [];
301
+ let out = '';
302
+ let lineStart = true;
303
+ let i = 0;
304
+ const toEol = () => {
305
+ while (i < n && s[i] !== '\n')
306
+ i++;
307
+ };
308
+ while (i < n) {
309
+ const c = s[i];
310
+ if (c === '\n') {
311
+ if (stack[stack.length - 1] === 'tpl') {
312
+ stack.pop();
313
+ out += '|';
314
+ }
315
+ out += '\n';
316
+ lineStart = true;
317
+ i++;
318
+ continue;
319
+ }
320
+ const atStart = lineStart;
321
+ lineStart = false;
322
+ if (stack[stack.length - 1] === 'tpl') {
323
+ if (c === '\\') {
324
+ i += s[i + 1] === '\n' ? 1 : 2;
325
+ continue;
326
+ }
327
+ if (c === '|') {
328
+ stack.pop();
329
+ out += '|';
330
+ i++;
331
+ continue;
332
+ }
333
+ if (c === '{') {
334
+ stack.push('emb');
335
+ out += '{';
336
+ i++;
337
+ continue;
338
+ }
339
+ i++;
340
+ continue;
341
+ }
342
+ if ((atStart && c === '*') || c === '"') {
343
+ toEol();
344
+ continue;
345
+ }
346
+ if (c === "'" || c === '`') {
347
+ let j = i + 1;
348
+ while (j < n && s[j] !== '\n') {
349
+ if (s[j] === c) {
350
+ if (s[j + 1] === c) {
351
+ j += 2;
352
+ continue;
353
+ }
354
+ break;
355
+ }
356
+ j++;
357
+ }
358
+ out += c + c;
359
+ i = j < n && s[j] === c ? j + 1 : j;
360
+ continue;
361
+ }
362
+ if (c === '|') {
363
+ stack.push('tpl');
364
+ out += '|';
365
+ i++;
366
+ continue;
367
+ }
368
+ if (c === '}' && stack[stack.length - 1] === 'emb') {
369
+ stack.pop();
370
+ out += '}';
371
+ i++;
372
+ continue;
373
+ }
374
+ out += c;
375
+ i++;
376
+ }
377
+ return out;
378
+ }
379
+ /** Tools whose whole source is ABAP Unit test code. */
380
+ const TEST_CODE_TOOLS = new Set(['UpdateLocalTestClass']);
381
+ /**
382
+ * A CLASS … IMPLEMENTATION without a CLASS … DEFINITION (not DEFERRED /
383
+ * LOAD) of that class in the same text — e.g. a test class split over two
384
+ * includes: its implementation alone carries no FOR TESTING but still runs
385
+ * under RunUnitTest. Expects comment- and literal-free text.
386
+ */
387
+ function hasOrphanClassImplementation(clean) {
388
+ const t = clean.replace(/:/g, ' ');
389
+ const defined = new Set();
390
+ for (const m of t.matchAll(/\bCLASS\s+([\w/]+)\s+DEFINITION\b(?!\s+(?:DEFERRED|LOAD|LOCAL\s+FRIENDS)\b)/gi))
391
+ defined.add(m[1].toUpperCase());
392
+ for (const m of t.matchAll(/\bCLASS\s+([\w/]+)\s+IMPLEMENTATION\b/gi))
393
+ if (!defined.has(m[1].toUpperCase()))
394
+ return true;
395
+ return false;
396
+ }
397
+ /**
398
+ * True when the patched source is a read channel — the same rule the plugin
399
+ * hook applies to a full upload (block-forbidden-tables.mjs
400
+ * sourceIsReadChannel): a test-code tool, `FOR TESTING` in the source, or a
401
+ * class implementation whose definition is elsewhere (comments and literals
402
+ * ignored). Its test classes' messages come back to the agent through
403
+ * RunUnitTest, so a read there extracts rows.
404
+ */
405
+ function isReadChannel(toolName, source) {
406
+ if (TEST_CODE_TOOLS.has(toolName))
407
+ return true;
408
+ // Colon chaining (`FOR: TESTING`) splits keywords: the colon is a separator here.
409
+ const clean = stripAbapComments(source).replace(/:/g, ' ');
410
+ return (/\bFOR\s+TESTING\b/i.test(clean) || hasOrphanClassImplementation(clean));
411
+ }
412
+ exports.TEST_CODE_REFUSAL = 'source_patches refused — this source contains test classes (FOR TESTING, or a class implementation whose definition is in another include); nothing uploaded. Send the full source_code so the blocklist hook can check it.';
413
+ /**
414
+ * Exactly "same as a full upload", with no blocklist profile on the server:
415
+ * the hook scans a full upload only when it is a read channel (test code),
416
+ * so a patch to test code is refused outright — before (the current text)
417
+ * or after (the patched text), so removing FOR TESTING by a patch is caught
418
+ * too. Business code passes, as a full upload of it does.
419
+ */
420
+ function assertNotTestCode(before, after, toolName = '') {
421
+ if (isReadChannel(toolName, before) || isReadChannel(toolName, after))
422
+ throw new Error(exports.TEST_CODE_REFUSAL);
423
+ }
424
+ /**
425
+ * Newest saved version and whether it is an inactive one. `unsure` is set
426
+ * when an inactive read came back but it could not be proven that no real
427
+ * inactive version exists — hadInactive is then true (never activate).
428
+ */
429
+ async function readNewestSource(t, ctx, args) {
430
+ let inactive;
431
+ try {
432
+ inactive = await t.read(ctx, args, 'inactive');
433
+ }
434
+ catch (e) {
435
+ // 404 = no inactive version. Anything else: refuse rather than patch a
436
+ // possibly stale active text over someone's inactive changes.
437
+ if (e?.response?.status !== 404)
438
+ throw e;
439
+ }
440
+ if (typeof inactive === 'string') {
441
+ // ECC ADT answers ?version=inactive with the ACTIVE text (200, not 404)
442
+ // when no inactive version exists. Same text as active = nothing inactive
443
+ // worth keeping: re-activating it changes nothing, even if someone's
444
+ // inactive entry with identical text exists — but only for single-part
445
+ // objects (a class activation also activates its other parts). An
446
+ // inactive version that reads as "" (and differs from active) is a real
447
+ // (empty) version. Active never activated (404) → a real inactive
448
+ // version; active read failed → cannot tell, keep it inactive.
449
+ let activeText;
450
+ try {
451
+ activeText = await t.read(ctx, args, 'active');
452
+ }
453
+ catch (e) {
454
+ if (e?.response?.status !== 404)
455
+ return {
456
+ text: inactive,
457
+ hadInactive: true,
458
+ unsure: `the active version could not be read (${e?.message || String(e)}), so it is unknown whether an inactive version existed before`,
459
+ };
460
+ }
461
+ if (typeof activeText !== 'string' || !sameSource(inactive, activeText))
462
+ return { text: inactive, hadInactive: true };
463
+ if (!t.singlePart)
464
+ return {
465
+ text: inactive,
466
+ hadInactive: true,
467
+ unsure: "activating it would also activate the other parts of the object, which may hold someone else's inactive changes",
468
+ };
469
+ return { text: inactive, hadInactive: false };
470
+ }
471
+ const active = await t.read(ctx, args, 'active');
472
+ if (typeof active !== 'string')
473
+ throw new Error('current source not found');
474
+ return { text: active, hadInactive: false };
475
+ }
476
+ /** Newest saved version: inactive when it exists, else active. */
477
+ async function readCurrentSource(t, ctx, args) {
478
+ return (await readNewestSource(t, ctx, args)).text;
479
+ }
480
+ /**
481
+ * Replace `source_patches` by the tool's source argument. Calls without
482
+ * `source_patches` pass through unchanged. Throws a short error when the
483
+ * tool is unsupported, inputs are combined, a patch is malformed, the read
484
+ * fails or a patch does not match — the handler never runs then.
485
+ */
486
+ async function resolveSourcePatchesArg(toolName, inputSchema, args, ctx) {
487
+ if (!args || typeof args !== 'object' || args.source_patches === undefined)
488
+ return { args };
489
+ const t = patchTargetOf(toolName, inputSchema);
490
+ if (!t)
491
+ throw new Error(`${toolName} does not take source_patches (supported: ${exports.SOURCE_PATCH_TOOLS.join(', ')})`);
492
+ // Any presence of the source field or source_file (even "" or null) is a
493
+ // mix: the hooks would scan that field, not the patches.
494
+ const has = (k) => Object.hasOwn(args, k);
495
+ if (has(t.codeField) || has('source_file'))
496
+ throw new Error(`give source_patches alone — not together with ${t.codeField} or source_file`);
497
+ const patches = parseSourcePatches(args.source_patches);
498
+ // A test-code tool is refused before any read.
499
+ if (TEST_CODE_TOOLS.has(toolName))
500
+ throw new Error(exports.TEST_CODE_REFUSAL);
501
+ for (const f of t.nameFields)
502
+ if (typeof args[f] !== 'string' || !args[f].trim())
503
+ throw new Error(`source_patches needs ${f}`);
504
+ const context = typeof ctx === 'function' ? await ctx() : ctx;
505
+ let current;
506
+ let hadInactive;
507
+ let unsure;
508
+ try {
509
+ ({
510
+ text: current,
511
+ hadInactive,
512
+ unsure,
513
+ } = await readNewestSource(t, context, args));
514
+ }
515
+ catch (e) {
516
+ throw new Error(`source_patches: cannot read the current source of ${t.nameFields.map((f) => up(args[f])).join('/')} — nothing uploaded (${e?.message || String(e)})`);
517
+ }
518
+ const { text, replacements } = applySourcePatches(current, patches);
519
+ assertNotTestCode(current, text, toolName);
520
+ const { source_patches: _p, source_file: _f, ...rest } = args;
521
+ return {
522
+ args: { ...rest, [t.codeField]: text },
523
+ patched: {
524
+ count: patches.length,
525
+ replacements,
526
+ bytes: Buffer.byteLength(text, 'utf8'),
527
+ source_sha256: (0, node_crypto_1.createHash)('sha256').update(text, 'utf8').digest('hex'),
528
+ },
529
+ restore: {
530
+ target: t,
531
+ codeField: t.codeField,
532
+ before: current,
533
+ after: text,
534
+ hadInactive,
535
+ ...(unsure ? { unsure } : {}),
536
+ },
537
+ };
538
+ }
539
+ /**
540
+ * Same source as SAP stores it: line endings, trailing blanks per line and
541
+ * trailing empty lines do not count (SAP's line storage drops them).
542
+ */
543
+ function sameSource(a, b) {
544
+ const norm = (s) => nl(s)
545
+ .split('\n')
546
+ .map((l) => l.trimEnd())
547
+ .join('\n')
548
+ .replace(/\n+$/, '');
549
+ return norm(a) === norm(b);
550
+ }
551
+ const resultText = (r) => (Array.isArray(r?.content) ? r.content : [])
552
+ .map((c) => typeof c?.text === 'string'
553
+ ? c.text
554
+ : c?.json !== undefined
555
+ ? JSON.stringify(c.json)
556
+ : '')
557
+ .join('\n');
558
+ /**
559
+ * A failed patched call must not leave the patched source behind (e.g. an
560
+ * include fails at activation after its upload: SAP keeps the broken text as
561
+ * the inactive version). When the newest saved source now equals the patched
562
+ * text, the pre-patch source is uploaded again with the same tool: activated
563
+ * when there was no inactive version before (active and inactive back to the
564
+ * old state), else saved as the previous inactive version. Returns the line
565
+ * to add to the error.
566
+ */
567
+ async function restoreAfterFailedPatch(r, args, ctx, invoke) {
568
+ let now;
569
+ try {
570
+ now = (await readNewestSource(r.target, ctx, args)).text;
571
+ }
572
+ catch (e) {
573
+ return `source_patches: could not read the object after the failure (${e?.message || String(e)}) — check its inactive version.`;
574
+ }
575
+ if (sameSource(now, r.before))
576
+ return 'source_patches: the patched source was not saved — nothing to undo.';
577
+ if (!sameSource(now, r.after))
578
+ return 'source_patches: NOT UNDONE — the saved source is neither the patched nor the pre-patch text (SAP may have changed it on save); check the object.';
579
+ const activateField = r.target.activateField || 'activate';
580
+ try {
581
+ const res = await invoke({
582
+ ...args,
583
+ [r.codeField]: r.before,
584
+ [activateField]: !r.hadInactive,
585
+ });
586
+ if (res?.isError)
587
+ throw new Error(resultText(res) || 'error result');
588
+ }
589
+ catch (e) {
590
+ // Say what is saved now, not what probably is.
591
+ let saved = 'unknown — read the object';
592
+ try {
593
+ const after = (await readNewestSource(r.target, ctx, args)).text;
594
+ saved = sameSource(after, r.after)
595
+ ? 'the PATCHED source is still saved as the inactive version; replace it before anything else'
596
+ : sameSource(after, r.before)
597
+ ? 'the pre-patch source is saved again but its activation did not finish; activate or check it'
598
+ : 'a different source is saved now; check the object';
599
+ }
600
+ catch {
601
+ /* keep "unknown" */
602
+ }
603
+ return `source_patches: UNDO FAILED (${e?.message || String(e)}) — ${saved}.`;
604
+ }
605
+ // Read back: report only what is saved now.
606
+ try {
607
+ const back = (await readNewestSource(r.target, ctx, args)).text;
608
+ if (!sameSource(back, r.before))
609
+ return 'source_patches: UNDO UNCONFIRMED — the undo call succeeded but a different source is saved now; check the object.';
610
+ }
611
+ catch (e) {
612
+ return `source_patches: UNDO UNCONFIRMED — the undo call succeeded but the read-back failed (${e?.message || String(e)}); check the object.`;
613
+ }
614
+ if (!r.hadInactive)
615
+ // Read-back checks the text only (ECC serves the active text as "inactive"), so no claim about the worklist.
616
+ return `${UNDONE_NOTE} — the previous source is active again.`;
617
+ if (r.unsure)
618
+ return `${UNDONE_NOTE} — the pre-patch source is saved as the inactive version, not activated: ${r.unsure}. Activate it if no one else has open changes.`;
619
+ return `${UNDONE_NOTE} — the previous inactive version is back (not activated).`;
620
+ }
621
+ const UNDONE_NOTE = 'source_patches: the failed patch was undone';
622
+ /**
623
+ * INCLUDE_STAGED_ADVICE (UpdateInclude, failed activation) is only true while
624
+ * the broken source is still saved: after a successful undo it contradicts
625
+ * the undo note, so it is dropped. The handler builds its message from the
626
+ * same constant, so the two cannot drift apart.
627
+ */
628
+ const dropStagedAdvice = (s) => s
629
+ .split(` ${handleUpdateInclude_1.INCLUDE_STAGED_ADVICE}`)
630
+ .join('')
631
+ .split(handleUpdateInclude_1.INCLUDE_STAGED_ADVICE)
632
+ .join('');
633
+ /** Failure text plus the undo note; stale staged-source advice removed when the undo succeeded. */
634
+ function withUndoNote(message, note) {
635
+ const base = note.startsWith(UNDONE_NOTE)
636
+ ? dropStagedAdvice(message)
637
+ : message;
638
+ return `${base}\n${note}`;
639
+ }
640
+ /**
641
+ * Run a resolved call; when it was a patch and it fails (throws or returns
642
+ * isError), undo a saved patched source before reporting the failure.
643
+ */
644
+ async function runWithPatchRestore(resolved, ctx, invoke) {
645
+ if (!resolved.restore)
646
+ return invoke(resolved.args);
647
+ let result;
648
+ try {
649
+ result = await invoke(resolved.args);
650
+ }
651
+ catch (e) {
652
+ const note = await restoreAfterFailedPatch(resolved.restore, resolved.args, ctx, invoke);
653
+ if (e instanceof Error) {
654
+ e.message = withUndoNote(e.message, note);
655
+ throw e;
656
+ }
657
+ throw new Error(withUndoNote(String(e), note));
658
+ }
659
+ if (!result?.isError)
660
+ return result;
661
+ const note = await restoreAfterFailedPatch(resolved.restore, resolved.args, ctx, invoke);
662
+ const undone = note.startsWith(UNDONE_NOTE);
663
+ const content = (Array.isArray(result.content) ? result.content : []).map((c) => undone && c?.type === 'text' && typeof c.text === 'string'
664
+ ? { ...c, text: dropStagedAdvice(c.text) }
665
+ : c);
666
+ return { ...result, content: [...content, { type: 'text', text: note }] };
667
+ }
668
+ /**
669
+ * Add `patched` to a successful handler result: into the JSON of the first
670
+ * text item when it is a JSON object, else as an extra text item.
671
+ */
672
+ function attachPatchedInfo(result, patched) {
673
+ const r = result;
674
+ if (!patched || !r || typeof r !== 'object' || r.isError)
675
+ return result;
676
+ const content = Array.isArray(r.content) ? [...r.content] : [];
677
+ const idx = content.findIndex((c) => c?.type === 'text' && typeof c.text === 'string');
678
+ if (idx >= 0) {
679
+ try {
680
+ const obj = JSON.parse(content[idx].text);
681
+ if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
682
+ content[idx] = {
683
+ ...content[idx],
684
+ text: JSON.stringify({ ...obj, patched }, null, 2),
685
+ };
686
+ return { ...r, content };
687
+ }
688
+ }
689
+ catch {
690
+ /* not JSON — append below */
691
+ }
692
+ }
693
+ const jdx = content.findIndex((c) => c?.type === 'json' && c.json && typeof c.json === 'object');
694
+ if (jdx >= 0 && !Array.isArray(content[jdx].json)) {
695
+ content[jdx] = { ...content[jdx], json: { ...content[jdx].json, patched } };
696
+ return { ...r, content };
697
+ }
698
+ content.push({ type: 'text', text: JSON.stringify({ patched }) });
699
+ return { ...r, content };
700
+ }
701
+ //# sourceMappingURL=sourcePatchInput.js.map