appium-mcp 1.97.2 → 1.99.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 (55) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +55 -2
  3. package/dist/locators/element-filter.d.ts +3 -1
  4. package/dist/locators/element-filter.d.ts.map +1 -1
  5. package/dist/locators/element-filter.js +44 -14
  6. package/dist/locators/element-filter.js.map +1 -1
  7. package/dist/locators/generate-all-locators.d.ts +6 -1
  8. package/dist/locators/generate-all-locators.d.ts.map +1 -1
  9. package/dist/locators/generate-all-locators.js +1 -1
  10. package/dist/locators/generate-all-locators.js.map +1 -1
  11. package/dist/locators/locator-generation.d.ts +4 -3
  12. package/dist/locators/locator-generation.d.ts.map +1 -1
  13. package/dist/locators/locator-generation.js +31 -10
  14. package/dist/locators/locator-generation.js.map +1 -1
  15. package/dist/locators/types.d.ts +3 -0
  16. package/dist/locators/types.d.ts.map +1 -0
  17. package/dist/locators/types.js +2 -0
  18. package/dist/locators/types.js.map +1 -0
  19. package/dist/telemetry/init.d.ts +2 -0
  20. package/dist/telemetry/init.d.ts.map +1 -1
  21. package/dist/telemetry/init.js +14 -1
  22. package/dist/telemetry/init.js.map +1 -1
  23. package/dist/tools/gestures/schema.d.ts.map +1 -1
  24. package/dist/tools/gestures/schema.js +7 -15
  25. package/dist/tools/gestures/schema.js.map +1 -1
  26. package/dist/tools/test-generation/locators.d.ts.map +1 -1
  27. package/dist/tools/test-generation/locators.js +19 -5
  28. package/dist/tools/test-generation/locators.js.map +1 -1
  29. package/dist/ui/inspector-screenshot-script.d.ts +3 -0
  30. package/dist/ui/inspector-screenshot-script.d.ts.map +1 -0
  31. package/dist/ui/inspector-screenshot-script.js +164 -0
  32. package/dist/ui/inspector-screenshot-script.js.map +1 -0
  33. package/dist/ui/mcp-ui-utils.d.ts.map +1 -1
  34. package/dist/ui/mcp-ui-utils.js +21 -44
  35. package/dist/ui/mcp-ui-utils.js.map +1 -1
  36. package/dist/ui/page-source-inspector-app.d.ts.map +1 -1
  37. package/dist/ui/page-source-inspector-app.js +198 -119
  38. package/dist/ui/page-source-inspector-app.js.map +1 -1
  39. package/dist/ui/xml-inspector-scripts.d.ts +4 -0
  40. package/dist/ui/xml-inspector-scripts.d.ts.map +1 -0
  41. package/dist/ui/xml-inspector-scripts.js +91 -0
  42. package/dist/ui/xml-inspector-scripts.js.map +1 -0
  43. package/package.json +2 -1
  44. package/server.json +2 -2
  45. package/src/locators/element-filter.ts +50 -16
  46. package/src/locators/generate-all-locators.ts +13 -7
  47. package/src/locators/locator-generation.ts +43 -10
  48. package/src/locators/types.ts +2 -0
  49. package/src/telemetry/init.ts +18 -1
  50. package/src/tools/gestures/schema.ts +7 -17
  51. package/src/tools/test-generation/locators.ts +31 -7
  52. package/src/ui/inspector-screenshot-script.ts +163 -0
  53. package/src/ui/mcp-ui-utils.ts +22 -44
  54. package/src/ui/page-source-inspector-app.ts +199 -119
  55. package/src/ui/xml-inspector-scripts.ts +91 -0
@@ -1,3 +1,6 @@
1
+ import {INSPECTOR_SCREENSHOT_SCRIPT} from './inspector-screenshot-script.js';
2
+ import {XML_FORMAT_SCRIPT, XML_SEARCH_SCRIPT} from './xml-inspector-scripts.js';
3
+
1
4
  /**
2
5
  * Static MCP App used by appium_get_page_source.
3
6
  *
@@ -13,114 +16,122 @@ export function createPageSourceInspectorAppUI(): string {
13
16
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
14
17
  <title>Page Source Inspector</title>
15
18
  <style>
19
+ :root { color-scheme: dark; --bg: #17191d; --panel: #202329; --line: #343941; --text: #e5e8ee; --muted: #a3acba; --accent: #91baff; }
16
20
  * { box-sizing: border-box; }
17
- body {
18
- margin: 0;
19
- overflow: hidden;
20
- background: #1e1e1e;
21
- color: #d4d4d4;
22
- font-family: Monaco, Menlo, "Courier New", monospace;
23
- }
24
- summary {
25
- padding: 12px 16px;
26
- background: #2d2d2d;
27
- cursor: pointer;
28
- font-size: 14px;
29
- }
30
- summary .info { margin-left: 8px; }
31
- .toolbar {
32
- display: flex;
33
- flex-wrap: wrap;
34
- align-items: center;
35
- justify-content: space-between;
36
- gap: 12px;
37
- padding: 12px 16px;
38
- border-bottom: 1px solid #3e3e3e;
39
- background: #2d2d2d;
40
- }
41
- .toolbar-right {
42
- flex-wrap: wrap;
43
- display: flex;
44
- align-items: center;
45
- gap: 8px;
46
- }
47
- .title { font-size: 14px; font-weight: 500; }
48
- .info { color: #999; font-size: 12px; }
49
- .btn {
50
- padding: 6px 12px;
51
- border: 0;
52
- border-radius: 4px;
53
- background: #007aff;
54
- color: #fff;
55
- cursor: pointer;
56
- font: 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
57
- }
58
- .btn:hover { background: #0056b3; }
59
- .btn-secondary { background: #444; }
60
- .btn-secondary:hover { background: #555; }
61
- .search-box {
62
- width: 200px;
63
- padding: 6px 12px;
64
- border: 1px solid #555;
65
- border-radius: 4px;
66
- outline: none;
67
- background: #3e3e3e;
68
- color: #d4d4d4;
69
- font-size: 13px;
70
- }
71
- .search-box:focus { border-color: #007aff; }
72
- .viewer {
73
- max-height: 320px;
74
- overflow: auto;
75
- padding: 16px;
76
- }
77
- .xml-content {
78
- margin: 0;
79
- white-space: pre;
80
- color: #d4d4d4;
81
- font-size: 13px;
82
- line-height: 1.6;
83
- }
84
- mark {
85
- border-radius: 2px;
86
- background: #ffd54f;
87
- color: #1e1e1e;
88
- }
89
- .empty {
90
- color: #999;
91
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
92
- }
21
+ [hidden] { display: none !important; }
22
+ body { margin: 0; overflow: auto; background: var(--bg); color: var(--text); font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
23
+ summary { cursor: pointer; padding: 16px 20px; }
24
+ summary::marker { color: var(--muted); }
25
+ .title { font-size: 15px; font-weight: 600; letter-spacing: -.2px; }
26
+ .info { color: var(--muted); font-size: 12px; margin-left: 10px; }
27
+ .toolbar, .section-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; }
28
+ .toolbar { padding: 12px 20px; border-block: 1px solid var(--line); background: var(--panel); }
29
+ .toolbar-right { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
30
+ .btn { padding: 8px 12px; border: 1px solid transparent; border-radius: 7px; background: #a7c7ff; color: #14243d; cursor: pointer; font: inherit; font-weight: 600; }
31
+ .btn:hover { background: #c2d8ff; }
32
+ .btn:disabled { opacity: .55; cursor: wait; }
33
+ .btn-secondary { background: transparent; border-color: #48505d; color: var(--text); }
34
+ .btn-secondary:hover { background: #303641; }
35
+ .btn:focus-visible, summary:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
36
+ .search-box { width: min(240px, 100%); min-width: 0; padding: 8px 12px; border: 1px solid #48505d; border-radius: 7px; background: var(--bg); color: var(--text); font: inherit; }
37
+ .search-box::placeholder { color: var(--muted); }
38
+ .viewer { height: 320px; min-height: 160px; resize: vertical; overflow: auto; padding: 20px; }
39
+ .xml-content, .selector { margin: 0; font: 12px/1.75 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
40
+ .xml-content { white-space: pre; color: #c5d3e7; }
41
+ mark[data-active] { outline: 2px solid #91baff; background: #ff963c; }
42
+ .search-status { padding: 6px 20px; color: var(--muted); font-size: 12px; }
43
+ .search-status:empty { display: none; }
44
+ mark { border-radius: 3px; background: #eac77a; color: #252019; }
45
+ .empty, .hint { color: var(--muted); }
46
+ .empty { font-family: inherit; }
47
+ .hint { margin: 6px 0 0; font-size: 12px; }
48
+ .screenshot-panel { border-top: 1px solid var(--line); padding: 20px; }
49
+ .screenshot-frame { position: relative; width: fit-content; max-width: 100%; margin: 12px auto; }
50
+ .screenshot-frame img { display: block; max-width: 100%; max-height: 480px; }
51
+ .element-overlay { position: absolute; border: 2px solid #ff963c; background: #ff963c33; pointer-events: none; }
52
+ #screenshotElement { width: 100%; margin: 10px 0; padding: 8px; background: var(--panel); color: var(--text); border: 1px solid var(--line); }
53
+ #selectedXmlElement { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
54
+ .locators { border-top: 1px solid var(--line); padding: 20px; }
55
+ h2 { margin: 0; font-size: 14px; font-weight: 600; }
56
+ #locatorStatus { margin: 16px 0 10px; color: var(--accent); font-size: 12px; }
57
+ .locator-results { max-height: 480px; overflow: auto; }
58
+ .locator-card { margin: 8px 0; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); overflow: hidden; }
59
+ .locator-card summary { padding: 12px 14px; overflow-wrap: anywhere; }
60
+ .element-type { margin-left: 8px; color: var(--muted); font-size: 11px; }
61
+ .locator-row { margin: 0 14px 14px; }
62
+ .strategy { display: block; margin-bottom: 5px; color: var(--muted); font-size: 11px; font-weight: 600; }
63
+ .selector { padding: 10px 12px; background: var(--bg); border-radius: 5px; white-space: pre-wrap; overflow-wrap: anywhere; user-select: all; }
64
+ @media (max-width: 420px) { .toolbar, .locators { padding: 12px; } .toolbar-right { width: 100%; } .search-box { width: 100%; } .info { display: block; margin: 4px 0 0 18px; } }
93
65
  </style>
94
66
  </head>
95
67
  <body>
96
- <details>
68
+ <details open>
97
69
  <summary>
98
- <span class="title">📄 Page Source Inspector</span>
70
+ <span class="title">Page Source Inspector</span>
99
71
  <span class="info" id="sourceInfo">Waiting for page source…</span>
100
72
  </summary>
101
73
  <div class="toolbar">
74
+ <input type="search" class="search-box" id="searchBox" placeholder="Search elements…" aria-label="Search elements" title="Highlight XML text and find locator candidates by element tag or attribute value">
102
75
  <div class="toolbar-right">
103
- <input type="text" class="search-box" id="searchBox" placeholder="Search…">
104
- <button class="btn btn-secondary" id="copyButton">Copy</button>
105
- <button class="btn btn-secondary" id="formatButton">Format</button>
106
- <button class="btn" id="generateButton">Generate Locators</button>
76
+ <button class="btn btn-secondary" id="takeScreenshotButton">Take screenshot</button>
77
+ <button class="btn btn-secondary" id="formatButton">Format XML</button>
78
+ <button class="btn btn-secondary" id="copyButton">Copy XML</button>
107
79
  </div>
108
80
  </div>
109
- <div class="viewer">
81
+ <div id="searchStatus" class="search-status" role="status" aria-live="polite"></div>
82
+ <div class="viewer" title="Drag the bottom-right corner to resize vertically">
110
83
  <pre class="xml-content empty" id="xmlContent">Waiting for page source…</pre>
111
84
  </div>
85
+ <section id="screenshotPanel" class="screenshot-panel" hidden aria-label="Screenshot preview">
86
+ <h2>Screenshot &amp; XML elements</h2>
87
+ <p class="hint">Capture refreshes XML too. Select an element to overlay its bounds. Images and XML are captured sequentially; keep the screen still. Supports x/y/width/height and Android bounds.</p>
88
+ <p id="screenshotStatus" role="status" aria-live="polite"></p>
89
+ <div class="screenshot-frame">
90
+ <img id="inspectorScreenshot" alt="Device screenshot" hidden>
91
+ <div id="elementOverlay" class="element-overlay" hidden></div>
92
+ </div>
93
+ <label for="screenshotElement">XML element (filtered by Search)</label>
94
+ <select id="screenshotElement"><option value="">Select an XML element to highlight</option></select>
95
+ <pre id="selectedXmlElement"></pre>
96
+ </section>
97
+ <section class="locators" aria-labelledby="locatorsHeading">
98
+ <div class="section-header">
99
+ <h2 id="locatorsHeading">Locator candidates</h2>
100
+ <button class="btn" id="generateButton">Find locators</button>
101
+ </div>
102
+ <p class="hint">Find locators for elements matching the search text in their type or attributes (name, label, text, ID, etc.). Matches ignore case and may include hidden elements. Fetches fresh XML; leave search blank for the default candidate list.</p>
103
+ <label class="hint" for="xpathAttributes">Preferred XPath attributes (optional)</label>
104
+ <input type="text" class="search-box" id="xpathAttributes" placeholder="AutomationId, data-testid" aria-describedby="xpathAttributesHelp" style="display:block;width:100%;margin-top:6px">
105
+ <p class="hint" id="xpathAttributesHelp">Comma-separated attribute names, in priority order. Existing attributes remain as fallback.</p>
106
+ <div id="locatorResults" hidden>
107
+ <p id="locatorStatus" role="status" aria-live="polite"></p>
108
+ <div class="locator-results" id="locatorOutput"></div>
109
+ </div>
110
+ </section>
112
111
  </details>
113
112
  <script>
114
113
  (() => {
114
+ ${XML_FORMAT_SCRIPT}
115
+ ${XML_SEARCH_SCRIPT}
116
+ ${INSPECTOR_SCREENSHOT_SCRIPT}
115
117
  const PAGE_SOURCE_PREFIX = 'Page source retrieved successfully: \\n\\\`\\\`\\\`xml ';
116
118
  const xmlContent = document.getElementById('xmlContent');
117
119
  const sourceInfo = document.getElementById('sourceInfo');
118
120
  const searchBox = document.getElementById('searchBox');
121
+ const generateButton = document.getElementById('generateButton');
122
+ const locatorResults = document.getElementById('locatorResults');
123
+ const locatorStatus = document.getElementById('locatorStatus');
124
+ const locatorOutput = document.getElementById('locatorOutput');
125
+ const xmlSearch = createXmlSearch(xmlContent, document.getElementById('searchStatus'));
119
126
  let source = '';
120
127
  let savedFile;
121
128
  let nextRequestId = 1;
122
129
  const pendingRequests = new Map();
123
130
 
131
+ const screenshotInspector = createScreenshotInspector(
132
+ (name, args) => sendRequest('tools/call', {name, arguments: args}), setSource, sourceFromToolResult,
133
+ );
134
+
124
135
  function sendRequest(method, params) {
125
136
  const id = nextRequestId++;
126
137
  window.parent.postMessage({jsonrpc: '2.0', id, method, params}, '*');
@@ -154,30 +165,9 @@ export function createPageSourceInspectorAppUI(): string {
154
165
  return text;
155
166
  }
156
167
 
157
- function appendHighlightedText(container, text, query) {
158
- const lowerText = text.toLowerCase();
159
- const lowerQuery = query.toLowerCase();
160
- let position = 0;
161
-
162
- while (position < text.length) {
163
- const matchIndex = lowerText.indexOf(lowerQuery, position);
164
- if (matchIndex === -1) {
165
- container.appendChild(document.createTextNode(text.slice(position)));
166
- return;
167
- }
168
- if (matchIndex > position) {
169
- container.appendChild(document.createTextNode(text.slice(position, matchIndex)));
170
- }
171
- const mark = document.createElement('mark');
172
- mark.textContent = text.slice(matchIndex, matchIndex + query.length);
173
- container.appendChild(mark);
174
- position = matchIndex + query.length;
175
- }
176
- }
177
-
178
168
  function renderSource() {
179
169
  const query = searchBox.value.trim();
180
- xmlContent.textContent = '';
170
+ xmlSearch.render('', '');
181
171
  xmlContent.classList.toggle('empty', source.length === 0);
182
172
  if (savedFile) {
183
173
  sourceInfo.textContent = savedFile.bytes + ' bytes saved';
@@ -186,28 +176,22 @@ export function createPageSourceInspectorAppUI(): string {
186
176
  }
187
177
  if (!source) {
188
178
  xmlContent.textContent = 'No page source was returned.';
189
- } else if (!query) {
190
- xmlContent.textContent = source;
191
179
  } else {
192
- appendHighlightedText(xmlContent, source, query);
180
+ xmlSearch.render(source, query);
193
181
  }
194
182
  sourceInfo.textContent = source.length + ' characters';
195
183
  }
196
184
 
197
185
  function setSource(nextSource) {
198
186
  source = nextSource;
187
+ screenshotInspector.updateSource(source);
199
188
  renderSource();
200
189
  }
201
190
 
202
191
  function formatXML() {
203
192
  if (!source) return;
204
193
  try {
205
- const parser = new DOMParser();
206
- const documentNode = parser.parseFromString(source, 'text/xml');
207
- if (documentNode.querySelector('parsererror')) {
208
- throw new Error('Invalid XML');
209
- }
210
- source = new XMLSerializer().serializeToString(documentNode);
194
+ source = formatXml(source);
211
195
  renderSource();
212
196
  } catch {
213
197
  window.alert('Failed to format XML');
@@ -223,11 +207,89 @@ export function createPageSourceInspectorAppUI(): string {
223
207
  }
224
208
  }
225
209
 
210
+ function renderLocators(elements) {
211
+ locatorOutput.textContent = '';
212
+ elements.forEach((element, index) => {
213
+ const card = document.createElement('details');
214
+ card.className = 'locator-card';
215
+ card.open = index === 0;
216
+ const heading = document.createElement('summary');
217
+ const label = element.text || element.contentDesc || element.resourceId;
218
+ heading.textContent = (index + 1) + '. ' + (label || element.tagName || 'Element');
219
+ if (label && element.tagName) {
220
+ const type = document.createElement('span');
221
+ type.className = 'element-type';
222
+ type.textContent = element.tagName;
223
+ heading.appendChild(type);
224
+ }
225
+ card.appendChild(heading);
226
+ const entries = Object.entries(element.locators || {}).filter(([, value]) => typeof value === 'string');
227
+ entries.forEach(([strategy, selector]) => {
228
+ const row = document.createElement('div');
229
+ row.className = 'locator-row';
230
+ const name = document.createElement('span');
231
+ name.className = 'strategy';
232
+ name.textContent = strategy;
233
+ const code = document.createElement('pre');
234
+ code.className = 'selector';
235
+ code.textContent = selector;
236
+ row.appendChild(name);
237
+ row.appendChild(code);
238
+ card.appendChild(row);
239
+ });
240
+ if (!entries.length) {
241
+ const empty = document.createElement('p');
242
+ empty.className = 'locator-row hint';
243
+ empty.textContent = 'No candidate selectors for this element.';
244
+ card.appendChild(empty);
245
+ }
246
+ locatorOutput.appendChild(card);
247
+ });
248
+ }
249
+
250
+ function parseLocatorResult(result) {
251
+ const text = (result?.content || [])
252
+ .filter(item => item.type === 'text')
253
+ .map(item => item.text)
254
+ .join('\\n');
255
+ if (result?.isError) throw new Error(text || 'Tool returned an error');
256
+ const data = JSON.parse(text);
257
+ if (!Array.isArray(data.interactableElements)) throw new Error('No locator data returned');
258
+ return data.interactableElements;
259
+ }
260
+
261
+ function describeLocatorResults(count, query) {
262
+ if (query) {
263
+ const matches = count ? count + ' matching elements' : 'No matching elements';
264
+ return matches + ' for “' + query + '” in freshly fetched XML.';
265
+ }
266
+ if (!count) return 'No supported elements found in the fetched XML.';
267
+ return 'Candidates generated for ' + count + ' elements from freshly fetched XML.';
268
+ }
269
+
226
270
  async function generateLocators() {
271
+ if (generateButton.disabled) return;
272
+ const query = searchBox.value.trim();
273
+ generateButton.disabled = true;
274
+ locatorResults.hidden = false;
275
+ locatorStatus.textContent = 'Fetching XML and generating candidates…';
276
+ locatorOutput.textContent = '';
227
277
  try {
228
- await sendRequest('tools/call', {name: 'generate_locators', arguments: {}});
229
- } catch {
230
- window.alert('Failed to generate locators');
278
+ const xpathAttributes = [...new Set((document.getElementById('xpathAttributes').value || '')
279
+ .split(',').map(name => name.trim()).filter(Boolean))];
280
+ if (xpathAttributes.length > 20 || xpathAttributes.some(name => !/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name))) {
281
+ throw new Error('Enter up to 20 attribute names, separated by commas (no XPath expressions or namespace prefixes).');
282
+ }
283
+ const args = query ? {query} : {};
284
+ if (xpathAttributes.length) args.xpathAttributes = xpathAttributes;
285
+ const result = await sendRequest('tools/call', {name: 'generate_locators', arguments: args});
286
+ const elements = parseLocatorResult(result);
287
+ locatorStatus.textContent = describeLocatorResults(elements.length, query);
288
+ renderLocators(elements);
289
+ } catch (error) {
290
+ locatorStatus.textContent = 'Failed to generate locators: ' + error.message;
291
+ } finally {
292
+ generateButton.disabled = false;
231
293
  }
232
294
  }
233
295
 
@@ -252,7 +314,11 @@ export function createPageSourceInspectorAppUI(): string {
252
314
  }
253
315
  });
254
316
 
255
- searchBox.addEventListener('input', renderSource);
317
+ searchBox.addEventListener('input', () => {
318
+ renderSource();
319
+ screenshotInspector.filter(searchBox.value);
320
+ });
321
+ searchBox.addEventListener('keydown', xmlSearch.handleKeyDown);
256
322
  document.getElementById('copyButton').addEventListener('click', copyToClipboard);
257
323
  document.getElementById('formatButton').addEventListener('click', formatXML);
258
324
  document.getElementById('generateButton').addEventListener('click', generateLocators);
@@ -262,7 +328,21 @@ export function createPageSourceInspectorAppUI(): string {
262
328
  appInfo: {name: 'Appium Page Source Inspector', version: '1.0.0'},
263
329
  appCapabilities: {availableDisplayModes: ['inline', 'fullscreen']},
264
330
  })
265
- .then(() => sendNotification('ui/notifications/initialized', {}))
331
+ .then(() => {
332
+ sendNotification('ui/notifications/initialized', {});
333
+ // Let flexible MCP App hosts follow resizing and details expansion.
334
+ if (typeof ResizeObserver !== 'undefined') {
335
+ let previousHeight;
336
+ const observer = new ResizeObserver(() => {
337
+ const height = Math.ceil(document.body.getBoundingClientRect().height);
338
+ if (height !== previousHeight) {
339
+ previousHeight = height;
340
+ sendNotification('ui/notifications/size-changed', {height});
341
+ }
342
+ });
343
+ observer.observe(document.body);
344
+ }
345
+ })
266
346
  .catch(() => {
267
347
  sourceInfo.textContent = 'Unable to initialize inspector';
268
348
  });
@@ -0,0 +1,91 @@
1
+ /** Shared browser helpers embedded by both inspector transports. Keep these scripts data-free. */
2
+ export const XML_FORMAT_SCRIPT = String.raw`
3
+ function formatXml(source) {
4
+ const documentNode = new DOMParser().parseFromString(source, 'text/xml');
5
+ if (!documentNode.documentElement || documentNode.getElementsByTagName('parsererror').length) {
6
+ throw new Error('Invalid XML');
7
+ }
8
+
9
+ function indentElement(element, depth) {
10
+ // Whitespace can be meaningful in mixed content, CDATA and preserved subtrees.
11
+ if (element.getAttribute('xml:space') === 'preserve') return;
12
+ const children = Array.from(element.childNodes);
13
+ const hasText = children.some(child =>
14
+ child.nodeType === 4 || (child.nodeType === 3 && (child.nodeValue || '').trim())
15
+ );
16
+ if (hasText || !children.some(child => child.nodeType === 1)) return;
17
+ for (const child of children) {
18
+ if (child.nodeType === 3) {
19
+ element.removeChild(child);
20
+ continue;
21
+ }
22
+ if (child.nodeType === 1) indentElement(child, depth + 1);
23
+ element.insertBefore(documentNode.createTextNode('\n' + ' '.repeat(depth + 1)), child);
24
+ }
25
+ element.appendChild(documentNode.createTextNode('\n' + ' '.repeat(depth)));
26
+ }
27
+
28
+ indentElement(documentNode.documentElement, 0);
29
+ const serializer = new XMLSerializer();
30
+ let formatted = Array.from(documentNode.childNodes)
31
+ .filter(node => node.nodeType !== 3)
32
+ .map(node => serializer.serializeToString(node))
33
+ .join('\n');
34
+ const declaration = source.match(/^\s*(<\?xml\s[^?]*\?>)/);
35
+ if (declaration && !formatted.startsWith('<?xml ')) {
36
+ formatted = declaration[1] + '\n' + formatted;
37
+ }
38
+ return formatted;
39
+ }
40
+ `;
41
+
42
+ export const XML_SEARCH_SCRIPT = String.raw`
43
+ function createXmlSearch(container, status) {
44
+ let matches = [];
45
+ let activeIndex = -1;
46
+
47
+ function render(text, query) {
48
+ container.textContent = '';
49
+ matches = [];
50
+ activeIndex = -1;
51
+ query = query.trim();
52
+ status.textContent = '';
53
+ if (!query) {
54
+ container.textContent = text;
55
+ return;
56
+ }
57
+ const lowerText = text.toLowerCase();
58
+ const lowerQuery = query.toLowerCase();
59
+ let position = 0;
60
+ while (position < text.length) {
61
+ const index = lowerText.indexOf(lowerQuery, position);
62
+ if (index === -1) break;
63
+ container.appendChild(document.createTextNode(text.slice(position, index)));
64
+ const mark = document.createElement('mark');
65
+ mark.textContent = text.slice(index, index + query.length);
66
+ container.appendChild(mark);
67
+ matches.push(mark);
68
+ position = index + query.length;
69
+ }
70
+ container.appendChild(document.createTextNode(text.slice(position)));
71
+ status.textContent = matches.length ? matches.length + ' matches · Enter / Shift+Enter to navigate' : 'No matches';
72
+ }
73
+
74
+ function handleKeyDown(event) {
75
+ if (event.key !== 'Enter' || event.isComposing) return;
76
+ event.preventDefault();
77
+ if (!matches.length) return;
78
+ if (activeIndex >= 0) matches[activeIndex].removeAttribute('data-active');
79
+ const step = event.shiftKey ? -1 : 1;
80
+ activeIndex = activeIndex < 0
81
+ ? (event.shiftKey ? matches.length - 1 : 0)
82
+ : (activeIndex + step + matches.length) % matches.length;
83
+ const match = matches[activeIndex];
84
+ match.setAttribute('data-active', 'true');
85
+ match.scrollIntoView({block: 'nearest', inline: 'nearest'});
86
+ status.textContent = (activeIndex + 1) + ' / ' + matches.length + ' · Enter / Shift+Enter to navigate';
87
+ }
88
+
89
+ return {render, handleKeyDown};
90
+ }
91
+ `;