@mohsinonxrm/pptb-fetchxml-studio 1.4.0 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,362 +1,432 @@
1
- # FetchXML Studio for Power Platform ToolBox
2
-
3
- A powerful, modern FetchXML query builder and data explorer for [Power Platform ToolBox](https://github.com/PowerPlatformToolBox/desktop-app). Inspired by the XrmToolBox FetchXML Builder, reimagined with React 18, Fluent UI v9, and seamless Dataverse integration.
4
-
5
- ![Version](https://img.shields.io/badge/version-1.4.0-blue)
6
- ![React](https://img.shields.io/badge/React-18-61DAFB?logo=react)
7
- ![TypeScript](https://img.shields.io/badge/TypeScript-5.9-3178C6?logo=typescript)
8
- ![Fluent UI](https://img.shields.io/badge/Fluent%20UI-v9-0078D4?logo=microsoft)
9
- ![PPTB Types](https://img.shields.io/badge/%40pptb%2Ftypes-1.2.3-blue)
10
-
11
- ## ✨ Features
12
-
13
- ### 🔧 Visual Query Builder
14
- - **Tree-based hierarchy** — Build FetchXML queries visually with entities, attributes, filters, orders, and link-entities
15
- - **Smart property editors** — Context-aware panels for each node type (fetch options, conditions, relationships)
16
- - **Full FetchXML support** — Aggregate queries, grouping, distinct, top/count, paging, and advanced hints
17
- - **Nested filters** — Create complex AND/OR filter groups with unlimited nesting
18
- - **Link-entity relationships** — Browse and add 1:N, N:1, and N:N relationships with inner/outer joins
19
-
20
- ### 📊 Results Grid
21
- - **Virtualized DataGrid** — Handle large result sets with smooth scrolling (powered by react-window)
22
- - **Rich cell rendering** — Power Apps-style display for lookups, option sets, dates, currency, and more
23
- - **Multi-column sorting** — Click headers to sort; Shift+click for multi-column sort
24
- - **Row selection** — Select single or multiple records for bulk operations
25
- - **Resizable & reorderable columns** — Customize your view with drag-and-drop columns
26
- - **Formatted values** — Display OData formatted values or raw values (configurable)
27
-
28
- ### 📝 FetchXML Editor
29
- - **Monaco editor** — Full-featured XML editor with XML syntax highlighting and line numbers
30
- - **Bi-directional editing** — Edit XML directly and parse back to the visual builder
31
- - **Copy to clipboard** — One-click copy of generated FetchXML, available in both read-only and editor modes
32
- - **Alias validation** — Invalid alias characters are sanitized in real time in the property editors; the parser auto-corrects aliases on Parse to Tree with a clear description of each correction
33
- - **LayoutXML preview** — See the column layout configuration
34
-
35
- ### 📥 Load & Save Views
36
- - **Load system/personal views** — Browse and load existing Dataverse views
37
- - **Optimized view execution** — Uses SavedQuery/UserQuery APIs for better performance
38
- - **Save to Dataverse** — Save your queries as new personal views or update existing ones
39
- - **Solution-aware** — Add views to solutions during save
40
-
41
- ### 📤 Export & Data Operations
42
- - **Local Excel export** — Native `.xlsx` generation via ExcelJS with proper data types (numbers, dates, currencies, booleans)
43
- - **Dataverse Excel export** — Server-side export via the `ExportToExcel` action (requires a saved view)
44
- - **Native save dialog** — When running inside PPTB, both export paths use `fileSystem.saveFile` for a native OS save-file dialog; falls back to browser blob download in standalone/dev mode
45
- - **Formatted value options** — Export formatted values, raw values, or both side-by-side columns
46
- - **Record deletion** — Delete selected records with confirmation dialog
47
- - **Bulk delete jobs** — Submit async `BulkDelete` jobs to Dataverse with job-tracking URL
48
- - **Batch delete** — Parallel per-record delete for small sets (up to 100 records) with progress and ETA
49
- - **Run workflows** — Execute on-demand workflows on selected records with batch execution and progress tracking
50
-
51
- ### 📋 Bulk Attribute Selection
52
- - **Select Attributes dialog** — Multi-select attributes from a searchable DataGrid; accessible from entity and link-entity context menus
53
- - **Smart updates** — Adds new selections and removes deselected attributes while preserving existing order and properties
54
- - **Search & filter** — Real-time filtering across logical name, display name, and data type columns
55
-
56
- ### 🔀 Code Generation
57
- - **Code tab** — New tab in the right pane that generates ready-to-use code from the current query in seven formats
58
- - **C# QueryExpression** — Full SDK object graph (`QueryExpression`, `ColumnSet`, `FilterExpression`, `ConditionExpression`, `LinkEntity`, `OrderExpression`) via the Dataverse `FetchXmlToQueryExpression` API; supports aggregate queries with `XrmAggregateType` and `XrmDateTimeGrouping`
59
- - **C# FetchExpression** — Simple `new FetchExpression(@"...")` wrapper using a verbatim string literal
60
- - **JavaScript** — `Xrm.WebApi.retrieveMultipleRecords` call for model-driven apps and PCF components
61
- - **pac CLI** — `pac org fetch --xml "..."` command for the Power Platform CLI
62
- - **Power Automate** — Field-by-field form mirroring the Dataverse "List rows" connector UI; table name resolved from `EntityDefinitions` metadata (not a heuristic), each field individually copyable
63
- - **Web API** — Full OData URL with request headers, cURL snippet, and PowerShell `Invoke-RestMethod` example; entity set name resolved from metadata
64
- - **SQL** — Dataverse-generated T-SQL via `FetchXMLToSQL` (undocumented API, labelled Preview)
65
-
66
- ### 🎨 User Experience
67
- - **Dark/Light themes** — Follows Power Platform ToolBox theme with Fluent UI tokens
68
- - **Lazy metadata loading** — Loads only what's needed, when it's needed
69
- - **Intelligent caching** — In-memory cache prevents duplicate API calls per session
70
- - **Resizable panes** — Adjust split-pane layout to your preference
71
- - **Keyboard shortcuts** — `Ctrl+Enter` to execute query, copy XML to clipboard
72
- - **Display settings** — Toggle logical names vs display names in column headers; choose formatted, raw, or both value modes in the grid and exports
73
- - **Query scope settings** — Control which entities appear in the entity picker: *Publisher + Solution* (full filter), *Solution Only*, or *All Entities* (no filter). Persisted across sessions.
74
- - **Advanced Find Only toggle** — When on (default), limits entities and attributes to those marked `IsValidForAdvancedFind = true`. Disable to access all entities including system and developer tables. Filter is applied locally — toggling is instant with no additional API call.
75
-
76
- ### 🔗 Tool-to-Tool (T2T) Integration
77
- - **Send to Tool button** — Launch another PPTB tool directly from FetchXML Studio, pre-loading it with the current FetchXML query and active Dataverse connection (one-way handoff).
78
- - **Automatic tool discovery** — Targets are discovered via the PPTB capability registry — installed tools that declare the `fetchxml` capability. The Send to Tool control always renders as a dropdown listing the discovered tools (even a single match). No configuration needed.
79
- - **Active connection forwarding** — The active Dataverse connection is forwarded automatically so the target tool opens against the same environment.
80
- - **Inbound prefill** — FetchXML Studio also accepts incoming T2T invocations from other tools (see [Callee Contract](#-callee-contract-pptbconfigjson) below).
81
-
82
- ### 🔒 Privilege-Aware
83
- - **Export privilege check** — Only shows Dataverse export option if user has access
84
- - **Delete privilege check** — Validates entity-specific delete permissions before enabling delete actions
85
- - **Bulk delete privilege check** — Validates `prvBulkDelete` before surfacing bulk delete
86
- - **Workflow privilege check** — Validates `prvReadWorkflow` + `prvWorkflowExecution` before showing workflow picker
87
- - **View save privilege check** — Validates `prvWriteQuery` / `prvWriteCustomization` / `prvPublishCustomization` / `prvWriteUserQuery` before save operations
88
-
89
- ## 🖼️ Interface Overview
90
-
91
- ```
92
- ┌─────────────────────────────────────────────────────────────────────────┐
93
- │ [Entity Selector ▼] [Load View ▼] [Save View] [Send to Tool ▼] [⚙] │
94
- ├──────────────────────┬──────────────────────────────────────────────────┤
95
- │ │ [FetchXML] [LayoutXML] [Results] [Code] [▶ Execute]│
96
- │ Query Tree ├──────────────────────────────────────────────────┤
97
- │ │ │
98
- │ 📁 fetch │ Results Grid / Monaco Editor │
99
- │ └─📁 entity │ │
100
- │ ├─📋 attribute │ ┌────────────┬────────────┬──────────────┐ │
101
- │ ├─📋 attribute │ │ Column 1 │ Column 2 │ Column 3 │ │
102
- │ ├─🔽 order │ ├────────────┼────────────┼──────────────┤ │
103
- │ ├─🔍 filter │ │ Value │ Value │ Value │ │
104
- │ │ └─ condition │ │ Value │ Value │ Value │ │
105
- │ └─🔗 link-entity│ └────────────┴────────────┴──────────────┘ │
106
- │ │ │
107
- ├──────────────────────┤ [◀ Prev] Page 1 of 10 [Next ▶] 100 records │
108
- │ │ │
109
- │ Properties Panel │ [+ Add Columns] [✎ Edit Columns] [⬇ Export] │
110
- │ (context-aware) │ [🗑 Delete] [Bulk Delete] [⚡ Run Workflow] │
111
- │ │ │
112
- └──────────────────────┴──────────────────────────────────────────────────┘
113
- ```
114
-
115
- ## 🚀 Getting Started
116
-
117
- ### Prerequisites
118
- - [Power Platform ToolBox](https://github.com/PowerPlatformToolBox/desktop-app) desktop application
119
- - Connection to a Dataverse environment
120
-
121
- ### Installation
122
- FetchXML Studio is available as a tool in Power Platform ToolBox. Install it from the tool gallery or load as a custom tool.
123
-
124
- ## 🛠️ Development
125
-
126
- ### Setup
127
-
128
- ```bash
129
- # Clone the repository
130
- git clone https://github.com/mohsinonxrm/pptb-fetchxml-studio.git
131
- cd pptb-fetchxml-studio
132
-
133
- # Install dependencies
134
- npm install
135
-
136
- # Start development server
137
- npm run dev
138
- ```
139
-
140
- ### Building
141
-
142
- ```bash
143
- # Production build
144
- npm run build
145
-
146
- # Preview production build
147
- npm run preview
148
-
149
- # Validate package manifest against PPTB registry rules
150
- npm run validate
151
-
152
- # Finalize for publishing (build + shrinkwrap)
153
- npm run finalize-package
154
- ```
155
-
156
- ### Debug Logging
157
-
158
- Enable debug logging in the browser console:
159
-
160
- ```javascript
161
- // Enable specific category
162
- enableDebug("metadataAPI"); // API calls and responses
163
- enableDebug("treeExpansion"); // Tree node operations
164
- enableDebug("relationshipPicker"); // Relationship loading
165
- enableDebug("linkEntityEditor"); // Link-entity configuration
166
- enableDebug("propertiesPanel"); // Property editor routing
167
-
168
- // Enable all
169
- enableAllDebug();
170
-
171
- // Disable
172
- disableDebug("metadataAPI");
173
- disableAllDebug();
174
- ```
175
-
176
- ## 📦 Tech Stack
177
-
178
- | Technology | Version | Purpose |
179
- |------------|---------|--------|
180
- | **React** | 18.3 | UI framework |
181
- | **TypeScript** | 5.9 | Type-safe development |
182
- | **Vite** | 7 | Build tooling and HMR |
183
- | **Fluent UI v9** | 9.72 | Microsoft design system (Tree, DataGrid, Tabs, Drawer, etc.) |
184
- | **Monaco Editor** | 0.54 | VS Code XML editor for FetchXML authoring |
185
- | **react-window** | 2 | Virtualized list rendering for large datasets |
186
- | **ExcelJS** | 4.4 | Native `.xlsx` generation with typed cells |
187
- | **@pptb/types** | 1.2.3 | Power Platform ToolBox host API types (`window.dataverseAPI`, `window.toolboxAPI`) |
188
-
189
- ## 📁 Project Structure
190
-
191
- ```
192
- src/
193
- ├── app/
194
- │ └── AppShell.tsx # Main layout with resizable split panes
195
- ├── features/fetchxml/
196
- │ ├── api/
197
- │ │ ├── pptbClient.ts # window.dataverseAPI wrapper (all Dataverse ops)
198
- │ │ ├── dataverseMetadata.ts # Lazy metadata loading with cache + dedup
199
- │ │ ├── excelExport.ts # Local ExcelJS export with native types
200
- │ │ ├── formattedValues.ts # OData @FormattedValue annotation helpers
201
- │ │ └── invocation.ts # T2T caller API (isT2TSupported, sendFetchXmlToTool)
202
- │ ├── model/
203
- │ │ ├── nodes.ts # FetchXML node TypeScript definitions
204
- │ │ ├── fetchxml.ts # FetchXML XML generation
205
- │ │ ├── fetchxmlParser.ts # FetchXML XML → node tree parser
206
- │ │ ├── fetchxmlIntellisense.ts # Intellisense / autocomplete helpers
207
- │ │ ├── layoutxml.ts # LayoutXML generation
208
- │ │ ├── operators.ts # Operator definitions by attribute type
209
- │ │ ├── displaySettings.ts # Display settings types and defaults
210
- │ │ └── treeUtils.ts # Tree traversal utilities
211
- │ ├── engine/
212
- │ │ ├── queryExpressionTypes.ts # QE JSON schema interfaces (number | string enums)
213
- │ │ ├── queryExpressionCodegen.ts # C# SDK code emitter (resolveEnum, unwrapODataValue)
214
- │ │ └── fetchxmlCodeGenerators.ts # Sync generators: FetchExpr, JS, pac, PA, WebAPI
215
- │ ├── state/
216
- │ │ ├── builderStore.tsx # React context + reducer state management
217
- │ │ └── cache.ts # Per-session in-memory metadata cache
218
- │ └── ui/
219
- │ ├── LeftPane/ # Tree view + context-aware properties panel
220
- │ │ └── PropertiesPanel/
221
- │ │ └── editors/ # Node-specific property editors
222
- │ ├── RightPane/ # Monaco editor, LayoutXML viewer, results grid,
223
- │ │ # code generation panel, Power Automate pane
224
- │ ├── Toolbar/ # Entity selector, load view picker, save button,
225
- │ │ # send-to-tool button
226
-
227
- │ ├── Dialogs/ # Save view, select attributes, delete, bulk
228
- │ │ # delete, workflow picker, solution picker
229
- │ └── Settings/ # Settings drawer (display preferences)
230
- └── shared/
231
- ├── components/ # Reusable value pickers (option set, boolean,
232
- │ # date, numeric, multi-value, relationship, etc.)
233
- ├── contexts/ # ThemeContext
234
- ├── hooks/ # usePptbContext, useLazyMetadata, useAccessMode,
235
- │ # usePublisherFilter, useSolutionFilter
236
- └── utils/ # Debug logging utilities
237
- ```
238
-
239
- ## 🔧 FetchXML Features Support
240
-
241
- | Feature | Status |
242
- |---------|--------|
243
- | Basic queries | ✅ |
244
- | Attributes (select columns) | ✅ |
245
- | All-attributes | ✅ |
246
- | Filters (and/or) | ✅ |
247
- | Nested filters | ✅ |
248
- | All condition operators | ✅ |
249
- | Link-entity (joins) | ✅ |
250
- | Inner/outer joins | ✅ |
251
- | N:N relationships | ✅ |
252
- | Orders (sorting) | ✅ |
253
- | Multi-column sort | ✅ |
254
- | Aggregate queries | ✅ |
255
- | Groupby | ✅ |
256
- | Distinct | ✅ |
257
- | Top/Count | ✅ |
258
- | Paging with cookies | ✅ |
259
- | Value-of conditions | ✅ |
260
- | Entity name on conditions | ✅ |
261
- | Filter link-entity (any/all) | ✅ |
262
- | Query hints | ✅ |
263
-
264
- ## 🔗 Callee Contract (`pptb.config.json`)
265
-
266
- FetchXML Studio declares a PPTB [Inter-Tool Invocation](https://github.com/PowerPlatformToolBox/desktop-app) callee contract in `pptb.config.json` at the repository root, and declares the `fetchxml` capability so callers can discover it. Any other PPTB tool can launch FetchXML Studio and pre-populate it by passing a prefill payload that matches the following schema:
267
-
268
- ```json
269
- {
270
- "fetchXml": "<fetch><entity name=\"account\">...</entity></fetch>"
271
- }
272
- ```
273
-
274
- | Field | Type | Required | Description |
275
- |---|---|---|---|
276
- | `fetchXml` | `string` | One of these three | Full serialized FetchXML query string. The root entity is parsed from this. |
277
- | `viewRef` | `object` | One of these three | EntityReference to an existing view. The FetchXML is retrieved from the view record. |
278
- | `entityLogicalName` | `string` | One of these three | Root entity logical name (e.g. `"account"`). Starts a fresh query on that entity. **Ignored when `fetchXml` is present** — the root entity is then derived from the FetchXML, since a mismatched value would break this metadata-driven tool's lookups. |
279
- | `viewRef.id` | `string` (uuid) | Required if viewRef | GUID of the view record |
280
- | `viewRef.entityLogicalName` | `"savedquery"` \| `"userquery"` | Required if viewRef | Dataverse entity logical name — `savedquery` = system/public view, `userquery` = personal view |
281
-
282
- Resolution priority at runtime: **`fetchXml` → `viewRef` → `entityLogicalName`**. With no prefill (a standalone launch) the tool opens empty.
283
-
284
- ### Returning a query to the caller
285
-
286
- When FetchXML Studio is launched by another tool, a **Return FetchXML** button appears in the FetchXML toolbar. Clicking it returns the current query to the caller:
287
-
288
- ```json
289
- { "fetchXml": "<fetch>...</fetch>" }
290
- ```
291
-
292
- The caller receives this as the resolved value of `launchTool(...)`. This is distinct from the host-injected "Return to [Caller]" banner, which simply navigates back and resolves the caller's promise with `null` (no data).
293
-
294
- ### Sending a query from another PPTB tool
295
-
296
- To launch FetchXML Studio from your own PPTB tool with a pre-loaded query:
297
-
298
- ```typescript
299
- const result = await window.toolboxAPI.invocation.launchTool(
300
- "@mohsinonxrm/pptb-fetchxml-studio",
301
- { fetchXml: "<fetch><entity name=\"account\"><attribute name=\"name\"/></entity></fetch>" },
302
- { primaryConnectionId: connection?.id ?? null },
303
- );
304
-
305
- // If the user clicks "Return FetchXML", result is { fetchXml }.
306
- // If they close the window or click the host's back banner, result is null.
307
- const editedFetchXml = (result as { fetchXml?: string } | null)?.fetchXml;
308
- ```
309
-
310
- ### Sending a query to another tool (Send to Tool)
311
-
312
- FetchXML Studio discovers send targets automatically — no configuration needed. It calls the host capability registry (`toolboxAPI.invocation.findToolsByCapability("fetchxml")`) to find installed tools that declare the `fetchxml` capability in their own `pptb.config.json`, and lists them in a **Send to Tool** button (a single button for one match, a dropdown picker for several). The button is hidden when no other `fetchxml`-capable tools are installed, or on hosts that don't support capability discovery.
313
-
314
- The launch is one-way (`noReturn: true`) — FetchXML Studio hands the current query off and does not wait for data back. Any tool that wants to appear here only needs to declare:
315
-
316
- ```json
317
- { "invocation": { "version": "1.0.0", "capabilities": ["fetchxml"], "prefill": { "properties": { "fetchXml": { "type": "string" } } } } }
318
- ```
319
-
320
- ---
321
-
322
- ## 🤝 Contributing
323
-
324
- Contributions are welcome! Please feel free to submit a Pull Request.
325
-
326
- 1. Fork the repository
327
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
328
- 3. Commit your changes (`git commit -m 'feat: add amazing feature'`)
329
- 4. Push to the branch (`git push origin feature/amazing-feature`)
330
- 5. Open a Pull Request
331
-
332
- ### Commit Convention
333
- This project follows [Conventional Commits](https://www.conventionalcommits.org/):
334
- - `feat:` New feature
335
- - `fix:` Bug fix
336
- - `refactor:` Code refactoring
337
- - `docs:` Documentation
338
- - `chore:` Maintenance
339
-
340
- ## 📋 Roadmap
341
-
342
- - [ ] Import/export query definitions (JSON)
343
- - [ ] Quick query templates
344
- - [ ] Query history
345
- - [ ] Web API code generation
346
- - [ ] Query performance insights
347
- - [ ] Syntax validation in Monaco
348
-
349
- ## 📄 License
350
-
351
- Licensed under the GNU Affero General Public License v3.0 (AGPL-3.0-only). See [LICENSE](LICENSE) for details.
352
-
353
- ## 🙏 Acknowledgments
354
-
355
- - [XrmToolBox FetchXML Builder](https://github.com/rappen/FetchXMLBuilder) - Original inspiration
356
- - [Power Platform ToolBox](https://github.com/PowerPlatformToolBox/desktop-app) - Host platform
357
- - [Fluent UI](https://react.fluentui.dev/) - UI component library
358
- - [Monaco Editor](https://microsoft.github.io/monaco-editor/) - Code editor
359
-
360
- ---
361
-
362
- Built with ❤️ for the Power Platform community
1
+ # FetchXML Studio for Power Platform ToolBox
2
+
3
+ A powerful, modern FetchXML query builder and data explorer for [Power Platform ToolBox](https://github.com/PowerPlatformToolBox/desktop-app). Inspired by the XrmToolBox FetchXML Builder, reimagined with React 18, Fluent UI v9, and seamless Dataverse integration.
4
+
5
+ ![Version](https://img.shields.io/badge/version-1.4.2-blue)
6
+ [![npm](https://img.shields.io/npm/v/@mohsinonxrm/pptb-fetchxml-studio?label=npm)](https://www.npmjs.com/package/@mohsinonxrm/pptb-fetchxml-studio)
7
+ ![React](https://img.shields.io/badge/React-18-61DAFB?logo=react)
8
+ ![TypeScript](https://img.shields.io/badge/TypeScript-5.9-3178C6?logo=typescript)
9
+ ![Fluent UI](https://img.shields.io/badge/Fluent%20UI-v9-0078D4?logo=microsoft)
10
+ ![PPTB Types](https://img.shields.io/badge/%40pptb%2Ftypes-1.2.3-blue)
11
+
12
+ ## ✨ Features
13
+
14
+ ### 🔧 Visual Query Builder
15
+ - **Tree-based hierarchy** — Build FetchXML queries visually with entities, attributes, filters, orders, and link-entities
16
+ - **Property panel for every node** — Fetch options, entity, attributes, all-attributes, sorts, filters, conditions and link-entities each have an editor covering the full FetchXML reference. Every field explains itself in an info popover with a link to Microsoft Learn.
17
+ - **Metadata-driven** — Attribute pickers, operators, value pickers, aggregate functions, date grouping, sortable attributes and compare-to-attribute choices follow each attribute's metadata, so the panel only offers what Dataverse accepts.
18
+ - **Shows problems where they are** — Rule errors appear on the field they're about and as an **Error** badge in the tree; settings Dataverse ignores are listed with a **Remove** button.
19
+ - **Tree badges** — Aggregate, Distinct, Retained and Hints on the query; Group by, date grouping and aggregate functions on attributes; Union and Quick find on filters.
20
+ - **Safe mode changes** — Turning off aggregate, or switching a link-entity to a type that returns no attributes, lists what has to change and asks first.
21
+ - **Full FetchXML support** — Aggregate queries, grouping, distinct, top/count, paging, and advanced hints
22
+ - **Nested filters** — Create complex AND/OR filter groups with unlimited nesting
23
+ - **Link-entity relationships** — Browse and add 1:N, N:1, and N:N relationships with inner/outer joins; N:N relationships join through their intersect entity, as documented; intersect entities (such as `systemuserroles` or `teammembership`) can be joined to each side of their N:N relationship
24
+
25
+ ### 📊 Results Grid
26
+ - **Virtualized DataGrid** — Handle large result sets with smooth scrolling (powered by react-window)
27
+ - **Copy results** — Right-click a cell to copy its value, its raw value (GUID, number, ISO date or option value), the row, the selected rows or the column. **Ctrl+C** copies the selected rows, or the focused cell. The command bar's **Copy** menu copies the selected or all loaded rows, as shown or as raw values. Rows copy as tab-separated values with a header row, so they paste into Excel as cells
28
+ - **Paging and Retrieve All** — Scrolling to the end loads the next page; **Retrieve All** loads every page, with **Stop** to keep what's loaded so far. Pages use the documented paging cookie and the query's own `count` and starting `page`. Queries Dataverse returns no cookie for (sorted by a link-entity attribute, or distinct) page by page number, with a note. Views follow `@odata.nextLink`. A failed page shows how many rows loaded, with **Retry**
29
+ - **Rich cell rendering** — Power Apps-style display for lookups, option sets, dates, currency, and more
30
+ - **Column header menu** — Click a header for **Sort** (A to Z, smallest to largest or oldest to newest, by type), **Filter by…** and **Clear filter**. Shift+click a header still adds it to a multi-column sort.
31
+ - **Column filters** — **Filter by…** adds a `<condition>` to the query and runs it again, so the filter covers every record, not just the loaded ones. Operators and value pickers follow the attribute's metadata, as in the property panel. Column filters are kept in their own `<filter type="and">` inside the root filter, apart from the conditions you built. An `or` root filter is wrapped so the column filters narrow the results; it's unwrapped again when the last column filter goes. Link-entity columns use `entityname`, which filters after the join. Active filters show as removable tags above the grid, and filtered columns show a filter icon
32
+ - **Quick search** — The search box above the grid filters the loaded rows as you type: any column, values as shown, with matches highlighted. The info bar shows how many loaded rows match. Rows it hides are deselected, and scrolling doesn't load more pages while searching
33
+ - **Multi-column sorting** — Shift+click headers for multi-column sort. Each click writes a valid `<order>`: by alias in aggregate queries, with `entityname` for link-entity columns, and not at all for attribute types Dataverse can't sort (multi-select option sets)
34
+ - **Edit / Add columns** — Remove, reorder and add columns from the root entity or related entities (N:1 and 1:N); the tree and FetchXML change to match. Removing a column removes its attribute (aliased or not, root or link-entity), any sort on its alias, and an outer link-entity left empty. At least one column must remain (a query without attributes returns every attribute). Add columns isn't available in aggregate queries
35
+ - **Link-entities without an alias** — Their columns show in the grid: Dataverse names them `{name}{N}.attribute`, and the grid uses the same names
36
+ - **Row selection** — Select single or multiple records for bulk operations. Record actions use the table's primary key, which Dataverse returns automatically for regular queries; for aggregate and distinct queries (which return no record IDs) record actions are disabled with an explanation
37
+ - **Resizable & reorderable columns** — Customize your view with drag-and-drop columns
38
+ - **Formatted values** — Display OData formatted values or raw values (configurable)
39
+ - **Works with every entity** — Queries run against the entity set name from Dataverse metadata, so entities with irregular names (for example `feedback`, `msdyn_conversationdata`) run correctly. The Power Platform ToolBox host's own name guess is wrong for about 4% of entities.
40
+
41
+ ### 📝 FetchXML Editor
42
+ - **Monaco editor** — Full-featured XML editor with XML syntax highlighting and line numbers
43
+ - **Bi-directional editing** — Edit XML directly and parse back to the visual builder
44
+ - **Intellisense from the reference** — Element, attribute and value suggestions follow the FetchXML reference (every documented attribute, including `aggregatelimit`, `datasource`, `options`, `rowaggregate`, order `entityname` and the quick find overrides). Undocumented attributes are suggested only where Dataverse was verified to accept them, and say so. Value suggestions work for hyphenated attributes such as `link-type`
45
+ - **Power Automate–safe values** — Apostrophes stay literal in the generated FetchXML (attribute values use double quotes), so expressions such as `@{body('x')}` paste into Power Automate unchanged; `"`, `&`, `<` and `>` are escaped everywhere, including names, aliases and `from` / `to`
46
+ - **Editor mode actions run what you see** — In editor mode, **Execute**, **Save** and **Send to Tool** first load your FetchXML into the tree, so results, saved views and sent queries always match the editor. Execute is available as soon as the editor has content, even before an entity is chosen. If the tree would change anything, a confirmation lists the changes first, and the editor then shows the cleaned FetchXML that ran. Invalid FetchXML is reported and nothing runs.
47
+ - **What you build is what runs** — The generated FetchXML contains exactly what is in the tree; nothing is injected, so what you copy, save as a view, or send to another tool matches what executes
48
+ - **Copy to clipboard** — One-click copy of generated FetchXML, available in both read-only and editor modes
49
+ - **Alias validation** — Invalid alias characters are sanitized in real time in the property editors; Parse to Tree corrects invalid aliases, lists each correction, and updates every reference to a corrected alias (condition and order `entityname`, `valueof`, aggregate order aliases) so the query keeps working
50
+ - **Accurate validation** — Everything in the FetchXML reference is supported, plus undocumented behaviour verified to work (e.g. `link-type="natural"`). Every rule is checked against a live Dataverse environment:
51
+ - **errors** block execution — only for FetchXML Dataverse is known to reject;
52
+ - **warnings** offer **Execute anyway** — only where it can't be determined in the client (e.g. a link-entity without `from`/`to`, which is valid only for system many-to-many relationships);
53
+ - **notes** never block (e.g. `xmlns:*` from other tools, which Dataverse ignores).
54
+ - **Query-level checks** — Validate and Execute catch the mistakes Dataverse rejects, each verified on a live environment:
55
+ - aggregate queries where an attribute has no Group by / aggregate or no alias;
56
+ - an aggregate order using an alias from another entity;
57
+ - `aggregatelimit` combined with an order;
58
+ - duplicate aliases;
59
+ - an invalid union hint;
60
+ - misuse of `rowaggregate`;
61
+ - `top` together with `count`, `page` or `returntotalrecordcount`, and `page` below 1;
62
+ - comparing to another attribute (`valueof`) with an operator other than eq, ne, gt, ge, lt or le, or through a link-entity without an alias;
63
+ - a link-entity inside a filter whose type isn't any / not any / all / not all;
64
+ - attributes, all-attributes or orders in an exists, in, any, not any, all or not all link-entity.
65
+
66
+ Settings Dataverse accepts but ignores (such as `aggregatelimit` on a non-aggregate query, `aggregate` on a condition, which FetchXML can't use to filter on aggregate values, or `visible` on a link-entity) are shown as notes only.
67
+ - **Boolean spellings** — `"1"`/`"0"` and other spellings Dataverse accepts are read correctly (e.g. `usertimezone="1"`, `descending="1"`, `enableprefiltering="1"`), so Parse to Tree never flips or drops them.
68
+ - **Lossless Parse to Tree** — Every attribute in the FetchXML reference is kept, including `datasource`, `aggregatelimit`, `useraworderby`, query hints (`options`), `latematerialize`, `<order alias>`, `distinct` counts, `rowaggregate` and quick find flags. So are unknown, namespaced and legacy attributes (e.g. `xmlns:generator` from SQL 4 CDS, `version`/`mapping` from Advanced Find, `uiname`/`uitype` from saved views). Every FetchXML example in the Microsoft Learn FetchXML articles round-trips without loss.
69
+ - **No silent changes** — If Parse to Tree must correct something Dataverse would reject (for example an invalid alias), a confirmation dialog lists every change first
70
+ - **LayoutXML preview** — See the column layout configuration
71
+
72
+ ### 📥 Load & Save Views
73
+ - **Load system/personal views** — Browse and load existing Dataverse views
74
+ - **Optimized view execution** — Uses SavedQuery/UserQuery APIs for better performance
75
+ - **Save to Dataverse** — Save your queries as new personal views or update existing ones
76
+ - **Solution-aware** — Add views to solutions during save
77
+
78
+ ### 📤 Export & Data Operations
79
+ - **Local Excel export** — Native `.xlsx` generation via ExcelJS with proper data types (numbers, dates, currencies, booleans)
80
+ - **Dataverse Excel export** — Server-side export via the `ExportToExcel` action (requires a saved view)
81
+ - **Native save dialog** — When running inside PPTB, both export paths use `fileSystem.saveFile` for a native OS save-file dialog; falls back to browser blob download in standalone/dev mode
82
+ - **Formatted value options** — Export formatted values, raw values, or both side-by-side columns
83
+ - **Record deletion** — Delete selected records with confirmation dialog
84
+ - **Bulk delete jobs** — Submit async `BulkDelete` jobs to Dataverse with job-tracking URL
85
+ - **Batch delete** — Parallel per-record delete for small sets (up to 100 records) with progress and ETA
86
+ - **Run workflows** — Execute on-demand workflows on selected records with batch execution and progress tracking
87
+
88
+ ### 📋 Bulk Attribute Selection
89
+ - **Select Attributes dialog** — Multi-select attributes from a sortable, resizable grid (display name, logical name, type). Long names end with an ellipsis and show in full on hover. Search by display or logical name, filter by type, show selected only, and see how many are selected. Opens from the entity and link-entity Add menus
90
+ - **Smart updates** — Adds new selections and removes deselected attributes while preserving existing order and properties
91
+ - **Search & filter** — Real-time filtering across logical name, display name, and data type columns
92
+
93
+ ### 🔀 Code Generation
94
+ - **Code tab** — New tab in the right pane that generates ready-to-use code from the current query in seven formats
95
+ - **C# QueryExpression** — Full SDK object graph (`QueryExpression`, `ColumnSet`, `FilterExpression`, `ConditionExpression`, `LinkEntity`, `OrderExpression`) via the Dataverse `FetchXmlToQueryExpression` API; supports aggregate queries with `XrmAggregateType` and `XrmDateTimeGrouping`
96
+ - **C# FetchExpression** — Simple `new FetchExpression(@"...")` wrapper using a verbatim string literal
97
+ - **JavaScript** — `Xrm.WebApi.retrieveMultipleRecords` call for model-driven apps and PCF components
98
+ - **pac CLI** — `pac org fetch --xml "..."` command for the Power Platform CLI
99
+ - **Power Automate** — Field-by-field form mirroring the Dataverse "List rows" connector UI; table name resolved from `EntityDefinitions` metadata (not a heuristic), each field individually copyable; Top Count is taken only from `top` (`count` is a page size)
100
+ - **Web API** — Full OData URL with request headers (including `Prefer: odata.include-annotations="*"` for formatted values and paging cookies), the documented paging-cookie steps, a cURL snippet and a PowerShell `Invoke-RestMethod` example; entity set name resolved from metadata
101
+ - **SQL** — Dataverse-generated T-SQL via `FetchXMLToSQL` (undocumented API, labelled Preview)
102
+
103
+ ### 🎨 User Experience
104
+ - **Dark/Light themes** — Every surface (tree, properties, editors, results grid, panels and dialogs) uses the Fluent UI v9 light or dark theme and follows the Power Platform ToolBox theme live: changing it in ToolBox settings, including **System**, and changing the OS theme while ToolBox is on System, update the tool without a reload
105
+ - **Lazy metadata loading** — Loads only what's needed, when it's needed
106
+ - **Intelligent caching** — In-memory cache prevents duplicate API calls per session
107
+ - **Resizable panes** — Adjust split-pane layout to your preference
108
+ - **Keyboard shortcuts** — `Ctrl+Enter` to execute query, copy XML to clipboard
109
+ - **Display settings** — Toggle logical names vs display names in column headers; choose formatted, raw, or both value modes in the grid and exports
110
+ - **Query scope settings** — Control which entities appear in the entity picker: *Publisher + Solution* (full filter), *Solution Only*, or *All Entities* (no filter). Persisted across sessions.
111
+ - **Advanced Find Only toggle** — When on (default), entities, attributes and relationships are limited to the ones Advanced Find shows (`IsValidForAdvancedFind`), in every entity scope. Turn it off to build queries Advanced Find can't: system and customization entities (saved views, forms, plug-in steps, solution components), intersect entities (team membership, user roles), and hidden attributes and relationships. Attributes that can't be read (`IsValidForRead = false`) are never listed. Hidden label attributes (such as `statuscodename`) can be filtered and sorted. Toggling is instant: metadata is fetched once and filtered locally. Attributes already in a query keep their operators and value inputs either way.
112
+
113
+ ### 🔗 Tool-to-Tool (T2T) Integration
114
+ - **Send to Tool button** — Launch another PPTB tool directly from FetchXML Studio, pre-loading it with the current FetchXML query and active Dataverse connection (one-way handoff).
115
+ - **Automatic tool discovery** — Targets are discovered via the PPTB capability registry — installed tools that declare the `fetchxml` capability. The Send to Tool control always renders as a dropdown listing the discovered tools (even a single match). No configuration needed.
116
+ - **Active connection forwarding** — The active Dataverse connection is forwarded automatically so the target tool opens against the same environment.
117
+ - **Inbound prefill** — FetchXML Studio also accepts incoming T2T invocations from other tools (see [Callee Contract](#-callee-contract-pptbconfigjson) below).
118
+
119
+ ### 🔒 Privilege-Aware
120
+ - **Export privilege check** — Only shows Dataverse export option if user has access
121
+ - **Delete privilege check** — Validates entity-specific delete permissions before enabling delete actions
122
+ - **Bulk delete privilege check** — Validates `prvBulkDelete` before surfacing bulk delete
123
+ - **Workflow privilege check** — Validates `prvReadWorkflow` + `prvWorkflowExecution` before showing workflow picker
124
+ - **View save privilege check** — Validates `prvWriteQuery` / `prvWriteCustomization` / `prvPublishCustomization` / `prvWriteUserQuery` before save operations
125
+
126
+ ## 🖼️ Interface Overview
127
+
128
+ ```
129
+ ┌─────────────────────────────────────────────────────────────────────────┐
130
+ │ [Entity Selector ▼] [Load View ▼] [Save View] [Send to Tool ▼] [⚙] │
131
+ ├──────────────────────┬──────────────────────────────────────────────────┤
132
+ │ │ [FetchXML] [LayoutXML] [Results] [Code] [▶ Execute]│
133
+ │ Query Tree ├──────────────────────────────────────────────────┤
134
+ │ │ │
135
+ │ 📁 fetch │ Results Grid / Monaco Editor │
136
+ │ └─📁 entity │ │
137
+ │ ├─📋 attribute │ ┌────────────┬────────────┬──────────────┐ │
138
+ │ ├─📋 attribute │ │ Column 1 │ Column 2 │ Column 3 │ │
139
+ │ ├─🔽 order │ ├────────────┼────────────┼──────────────┤ │
140
+ │ ├─🔍 filter │ │ Value │ Value │ Value │ │
141
+ │ │ └─ condition │ │ Value │ Value │ Value │ │
142
+ │ └─🔗 link-entity│ └────────────┴────────────┴──────────────┘ │
143
+ │ │ │
144
+ ├──────────────────────┤ [◀ Prev] Page 1 of 10 [Next ▶] 100 records │
145
+ │ │ │
146
+ │ Properties Panel │ [+ Add Columns] [✎ Edit Columns] [⬇ Export] │
147
+ │ (context-aware) │ [🗑 Delete] [Bulk Delete] [⚡ Run Workflow] │
148
+ │ │ │
149
+ └──────────────────────┴──────────────────────────────────────────────────┘
150
+ ```
151
+
152
+ ## 🚀 Getting Started
153
+
154
+ ### Prerequisites
155
+ - [Power Platform ToolBox](https://github.com/PowerPlatformToolBox/desktop-app) desktop application
156
+ - Connection to a Dataverse environment
157
+
158
+ ### Installation
159
+ FetchXML Studio is available as a tool in Power Platform ToolBox. Install it from the tool gallery or load as a custom tool. The package is published on npm as [`@mohsinonxrm/pptb-fetchxml-studio`](https://www.npmjs.com/package/@mohsinonxrm/pptb-fetchxml-studio).
160
+
161
+ ## 🛠️ Development
162
+
163
+ ### Setup
164
+
165
+ ```bash
166
+ # Clone the repository
167
+ git clone https://github.com/mohsinonxrm/pptb-mxrm-fetchxml-studio.git
168
+ cd pptb-mxrm-fetchxml-studio
169
+
170
+ # Install the exact dependency versions from package-lock.json
171
+ npm ci
172
+
173
+ # Start development server
174
+ npm run dev
175
+ ```
176
+
177
+ ### Building
178
+
179
+ ```bash
180
+ # Production build
181
+ npm run build
182
+
183
+ # Preview production build
184
+ npm run preview
185
+
186
+ # Validate package manifest against PPTB registry rules
187
+ npm run validate
188
+ ```
189
+
190
+ **Releases.** CI (`.github/workflows/ci.yml`) runs typecheck, lint, tests, PPTB validation, the build and a package-contents check on every pull request. Pushing a `vX.Y.Z` tag on `main` publishes to npm with provenance and creates the GitHub Release; see [RELEASING.md](RELEASING.md).
191
+
192
+ **Tool icon.** `package.json` points `icon` at `icons/icon.svg` under `dist/`, where Power Platform ToolBox looks for it. The build bundles `icons/icon-insider.svg` (gold stamp) for prerelease versions such as `1.4.2-beta.7`, and `icons/icon.svg` for releases.
193
+
194
+ **Dependencies.** `package-lock.json` is committed and pins every dependency with an integrity hash. Use `npm ci` for a clean install. After changing dependencies, run `npm install` and commit the updated lockfile.
195
+
196
+ ### Testing
197
+
198
+ ```bash
199
+ # Unit tests (Vitest + jsdom): parser, serializer, rules, round-trip over the Microsoft Learn examples
200
+ npm test
201
+
202
+ # Watch mode
203
+ npm run test:watch
204
+
205
+ # Type check and lint
206
+ npm run typecheck
207
+ npm run lint
208
+
209
+ # Formatting (Prettier)
210
+ npm run format:check
211
+ ```
212
+
213
+ ### Debug Logging
214
+
215
+ Enable debug logging in the browser console:
216
+
217
+ ```javascript
218
+ // Enable specific category
219
+ enableDebug("metadataAPI"); // API calls and responses
220
+ enableDebug("treeExpansion"); // Tree node operations
221
+ enableDebug("relationshipPicker"); // Relationship loading
222
+ enableDebug("linkEntityEditor"); // Link-entity configuration
223
+ enableDebug("propertiesPanel"); // Property editor routing
224
+
225
+ // Enable all
226
+ enableAllDebug();
227
+
228
+ // Disable
229
+ disableDebug("metadataAPI");
230
+ disableAllDebug();
231
+ ```
232
+
233
+ ## 📦 Tech Stack
234
+
235
+ | Technology | Version | Purpose |
236
+ |------------|---------|--------|
237
+ | **React** | 18.3 | UI framework |
238
+ | **TypeScript** | 5.9 | Type-safe development |
239
+ | **Vite** | 7 | Build tooling and HMR |
240
+ | **Fluent UI v9** | 9.74 | Microsoft design system (Tree, DataGrid, Tabs, Drawer, etc.) |
241
+ | **Monaco Editor** | 0.54 | VS Code XML editor for FetchXML authoring |
242
+ | **react-window** | 2 | Virtualized list rendering for large datasets |
243
+ | **ExcelJS** | 4.4 | Native `.xlsx` generation with typed cells |
244
+ | **@pptb/types** | 1.2.3 | Power Platform ToolBox host API types (`window.dataverseAPI`, `window.toolboxAPI`) |
245
+ | **Vitest** | 5 | Unit tests (jsdom) |
246
+
247
+ ## 📁 Project Structure
248
+
249
+ ```
250
+ src/
251
+ ├── app/
252
+ │ └── AppShell.tsx # Main layout with resizable split panes
253
+ ├── features/fetchxml/
254
+ │ ├── api/
255
+ │ │ ├── pptbClient.ts # window.dataverseAPI wrapper (all Dataverse ops)
256
+ │ │ ├── dataverseMetadata.ts # Lazy metadata loading with cache + dedup
257
+ │ │ ├── excelExport.ts # Local ExcelJS export with native types
258
+ │ │ ├── formattedValues.ts # OData @FormattedValue annotation helpers
259
+ │ │ └── invocation.ts # T2T caller API (isT2TSupported, sendFetchXmlToTool)
260
+ │ ├── model/
261
+ │ │ ├── nodes.ts # FetchXML node TypeScript definitions
262
+ │ │ ├── fetchxml.ts # FetchXML XML generation
263
+ │ │ ├── fetchxmlParser.ts # FetchXML XML → node tree parser (severity-classified findings)
264
+ │ │ ├── fetchxmlRules.ts # Query-level rules shared by the parser and editors
265
+ │ │ ├── attributeCapabilities.ts # What each attribute type supports (sort, group by, aggregates, valueof)
266
+ │ │ ├── aggregateToggle.ts # What turning off an aggregate query changes
267
+ │ │ ├── fetchxmlIntellisense.ts # Intellisense / autocomplete helpers
268
+ │ │ ├── layoutxml.ts # LayoutXML generation
269
+ │ │ ├── operators.ts # Operator definitions by attribute type
270
+ │ │ ├── displaySettings.ts # Display settings types and defaults
271
+ │ │ ├── treeUtils.ts # Tree traversal utilities
272
+ │ │ └── __fixtures__/ # FetchXML examples from Microsoft Learn (MIT) for round-trip tests
273
+ │ ├── engine/
274
+ │ │ ├── queryExpressionTypes.ts # QE JSON schema interfaces (number | string enums)
275
+ │ │ ├── queryExpressionCodegen.ts # C# SDK code emitter (resolveEnum, unwrapODataValue)
276
+ │ │ └── fetchxmlCodeGenerators.ts # Sync generators: FetchExpr, JS, pac, PA, WebAPI
277
+ │ ├── state/
278
+ │ │ ├── builderStore.tsx # React context + reducer state management
279
+ │ │ └── cache.ts # Per-session in-memory metadata cache
280
+ │ └── ui/
281
+ │ ├── LeftPane/ # Tree view + context-aware properties panel
282
+ │ │ └── PropertiesPanel/
283
+ │ │ ├── editors/ # One editor per node type
284
+ │ │ ├── fields.tsx # InfoField, InfoCheckbox, NumberField, LeftoverSetting
285
+ │ │ ├── docLinks.ts # Microsoft Learn links used by the info popovers
286
+ │ │ ├── ruleFindings.ts # Rule findings → field validation
287
+ │ │ └── useEditorMetadata.ts # Attribute / entity metadata hooks
288
+ │ ├── RightPane/ # Monaco editor, LayoutXML viewer, results grid,
289
+ │ │ # code generation panel, Power Automate pane
290
+ │ ├── Toolbar/ # Entity selector, load view picker, save button,
291
+ │ │ # send-to-tool button
292
+
293
+ │ ├── Dialogs/ # Save view, select attributes, delete, bulk
294
+ │ │ # delete, workflow picker, solution picker
295
+ │ └── Settings/ # Settings drawer (display preferences)
296
+ └── shared/
297
+ ├── components/ # Reusable value pickers (option set, boolean,
298
+ │ # date, numeric, multi-value, relationship, etc.)
299
+ ├── contexts/ # ThemeContext
300
+ ├── hooks/ # usePptbContext, useLazyMetadata, useAccessMode,
301
+ │ # usePublisherFilter, useSolutionFilter
302
+ └── utils/ # Debug logging utilities
303
+ ```
304
+
305
+ ## 🔧 FetchXML Features Support
306
+
307
+ | Feature | Status |
308
+ |---------|--------|
309
+ | Basic queries | ✅ |
310
+ | Attributes (select columns) | ✅ |
311
+ | All-attributes | ✅ |
312
+ | Filters (and/or) | ✅ |
313
+ | Nested filters | ✅ |
314
+ | All condition operators (offered per attribute from the documented data types and a live operator × attribute-type matrix; value inputs match each operator: whole numbers for "x" operators, period + year for fiscal period operators) | ✅ |
315
+ | Link-entity (joins) | ✅ |
316
+ | Inner/outer joins | ✅ |
317
+ | N:N relationships (through the intersect entity) | ✅ |
318
+ | Orders (sorting) | ✅ |
319
+ | Multi-column sort | ✅ |
320
+ | Aggregate queries | ✅ |
321
+ | Groupby | ✅ |
322
+ | Distinct | ✅ |
323
+ | Top/Count | ✅ |
324
+ | Paging with cookies (`fetchxmlpagingcookie`), page-number paging when Dataverse returns no cookie, views via `@odata.nextLink` | ✅ |
325
+ | Value-of conditions | ✅ |
326
+ | Entity name on conditions | ✅ |
327
+ | Filter link-entity (any/all) | ✅ |
328
+ | Query hints | ✅ |
329
+ | Order by alias (aggregate) | ✅ |
330
+ | Quick find, union hint | ✅ |
331
+ | Row aggregate (hierarchy child count) | ✅ |
332
+ | Long-term retention (`datasource`) | ✅ |
333
+ | Validation against Dataverse rules | ✅ |
334
+
335
+ ## 🔗 Callee Contract (`pptb.config.json`)
336
+
337
+ FetchXML Studio declares a PPTB [Inter-Tool Invocation](https://github.com/PowerPlatformToolBox/desktop-app) callee contract in `pptb.config.json` at the repository root, and declares the `fetchxml` capability so callers can discover it. Any other PPTB tool can launch FetchXML Studio and pre-populate it by passing a prefill payload that matches the following schema:
338
+
339
+ ```json
340
+ {
341
+ "fetchXml": "<fetch><entity name=\"account\">...</entity></fetch>"
342
+ }
343
+ ```
344
+
345
+ | Field | Type | Required | Description |
346
+ |---|---|---|---|
347
+ | `fetchXml` | `string` | One of these three | Full serialized FetchXML query string. The root entity is parsed from this. |
348
+ | `viewRef` | `object` | One of these three | EntityReference to an existing view. The FetchXML is retrieved from the view record. |
349
+ | `entityLogicalName` | `string` | One of these three | Root entity logical name (e.g. `"account"`). Starts a fresh query on that entity. **Ignored when `fetchXml` is present** — the root entity is then derived from the FetchXML, since a mismatched value would break this metadata-driven tool's lookups. |
350
+ | `viewRef.id` | `string` (uuid) | Required if viewRef | GUID of the view record |
351
+ | `viewRef.entityLogicalName` | `"savedquery"` \| `"userquery"` | Required if viewRef | Dataverse entity logical name — `savedquery` = system/public view, `userquery` = personal view |
352
+
353
+ Resolution priority at runtime: **`fetchXml` → `viewRef` → `entityLogicalName`**. With no prefill (a standalone launch) the tool opens empty.
354
+
355
+ ### Returning a query to the caller
356
+
357
+ When FetchXML Studio is launched by another tool, a **Return FetchXML** button appears in the FetchXML toolbar. Clicking it returns the current query to the caller:
358
+
359
+ ```json
360
+ { "fetchXml": "<fetch>...</fetch>" }
361
+ ```
362
+
363
+ The caller receives this as the resolved value of `launchTool(...)`. This is distinct from the host-injected "Return to [Caller]" banner, which simply navigates back and resolves the caller's promise with `null` (no data).
364
+
365
+ ### Sending a query from another PPTB tool
366
+
367
+ To launch FetchXML Studio from your own PPTB tool with a pre-loaded query:
368
+
369
+ ```typescript
370
+ const result = await window.toolboxAPI.invocation.launchTool(
371
+ "@mohsinonxrm/pptb-fetchxml-studio",
372
+ { fetchXml: "<fetch><entity name=\"account\"><attribute name=\"name\"/></entity></fetch>" },
373
+ { primaryConnectionId: connection?.id ?? null },
374
+ );
375
+
376
+ // If the user clicks "Return FetchXML", result is { fetchXml }.
377
+ // If they close the window or click the host's back banner, result is null.
378
+ const editedFetchXml = (result as { fetchXml?: string } | null)?.fetchXml;
379
+ ```
380
+
381
+ ### Sending a query to another tool (Send to Tool)
382
+
383
+ FetchXML Studio discovers send targets automatically — no configuration needed. It calls the host capability registry (`toolboxAPI.invocation.findToolsByCapability("fetchxml")`) to find installed tools that declare the `fetchxml` capability in their own `pptb.config.json`, and lists them in a **Send to Tool** button (a single button for one match, a dropdown picker for several). The button is hidden when no other `fetchxml`-capable tools are installed, or on hosts that don't support capability discovery.
384
+
385
+ The launch is one-way (`noReturn: true`) — FetchXML Studio hands the current query off and does not wait for data back. Any tool that wants to appear here only needs to declare:
386
+
387
+ ```json
388
+ { "invocation": { "version": "1.0.0", "capabilities": ["fetchxml"], "prefill": { "properties": { "fetchXml": { "type": "string" } } } } }
389
+ ```
390
+
391
+ ---
392
+
393
+ ## 🤝 Contributing
394
+
395
+ Contributions are welcome! Please feel free to submit a Pull Request.
396
+
397
+ 1. Fork the repository
398
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
399
+ 3. Commit your changes (`git commit -m 'feat: add amazing feature'`)
400
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
401
+ 5. Open a Pull Request
402
+
403
+ ### Commit Convention
404
+ This project follows [Conventional Commits](https://www.conventionalcommits.org/):
405
+ - `feat:` New feature
406
+ - `fix:` Bug fix
407
+ - `refactor:` Code refactoring
408
+ - `docs:` Documentation
409
+ - `chore:` Maintenance
410
+
411
+ ## 📋 Roadmap
412
+
413
+ - [ ] Import/export query definitions (JSON)
414
+ - [ ] Quick query templates
415
+ - [ ] Query history
416
+ - [ ] Query performance insights
417
+ - [ ] Syntax validation in Monaco
418
+
419
+ ## 📄 License
420
+
421
+ Licensed under the GNU Affero General Public License v3.0 (AGPL-3.0-only). See [LICENSE](LICENSE) for details.
422
+
423
+ ## 🙏 Acknowledgments
424
+
425
+ - [XrmToolBox FetchXML Builder](https://github.com/rappen/FetchXMLBuilder) - Original inspiration
426
+ - [Power Platform ToolBox](https://github.com/PowerPlatformToolBox/desktop-app) - Host platform
427
+ - [Fluent UI](https://react.fluentui.dev/) - UI component library
428
+ - [Monaco Editor](https://microsoft.github.io/monaco-editor/) - Code editor
429
+
430
+ ---
431
+
432
+ Built with ❤️ for the Power Platform community