@mohsinonxrm/pptb-dataverse-request-studio 1.4.0 → 1.5.0-beta.1

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 (50) hide show
  1. package/CHANGELOG.md +271 -0
  2. package/README.md +78 -9
  3. package/SECURITY.md +8 -1
  4. package/dist/assets/AssociateMode-mu2ai0TV.js +1 -0
  5. package/dist/assets/AssociateTargetsEditor-BoH9Qxe8.js +1 -0
  6. package/dist/assets/BatchMode-BVAfFgPy.js +11 -0
  7. package/dist/assets/BinaryColumnPickers-DYpKoRIO.js +1 -0
  8. package/dist/assets/BulkDeleteMode-Df-XirlR.js +1 -0
  9. package/dist/assets/BulkWriteMode-UXREEvbe.js +6 -0
  10. package/dist/assets/DisassociateMode-CKBL5nUo.js +2 -0
  11. package/dist/assets/ExecuteWorkflowMode-4EWco-ze.js +1 -0
  12. package/dist/assets/ManageFileMode-BFNwxuEY.js +1 -0
  13. package/dist/assets/ManageImageMode-DX0AdPN1.js +1 -0
  14. package/dist/assets/MergeMode-BzyXLu1b.js +1 -0
  15. package/dist/assets/PredefinedQueryMode-BT-HdZHF.js +1 -0
  16. package/dist/assets/RetrieveNextLinkMode-QBuIwdgS.js +1 -0
  17. package/dist/assets/{cssMode-B4BP9f3X.js → cssMode-DRNC4UuD.js} +1 -1
  18. package/dist/assets/{freemarker2-DFKOu_2v.js → freemarker2-BITb8GyO.js} +1 -1
  19. package/dist/assets/{handlebars-cWHtgvCj.js → handlebars-BbDVduNH.js} +1 -1
  20. package/dist/assets/{html-DSPQITYl.js → html-Ru2Cy2VS.js} +1 -1
  21. package/dist/assets/{htmlMode-Cr-uAXsT.js → htmlMode-DeMh8vPt.js} +1 -1
  22. package/dist/assets/index-XmEQbXiX.js +703 -0
  23. package/dist/assets/{javascript-B3oRul8j.js → javascript-DLj2yjBO.js} +1 -1
  24. package/dist/assets/{jsonMode-_zXsQ367.js → jsonMode-DOHFeg2H.js} +1 -1
  25. package/dist/assets/{liquid-Cib5dNaW.js → liquid-udbJGOUP.js} +1 -1
  26. package/dist/assets/{mdx-8A_8JwPK.js → mdx-B6ABiFDH.js} +1 -1
  27. package/dist/assets/{monacoSetup-DObeMDBe.js → monacoSetup-CEhMjQNN.js} +3 -3
  28. package/dist/assets/{python-DsudPCj1.js → python-DDgBOsRh.js} +1 -1
  29. package/dist/assets/{razor-CrmV2uj7.js → razor-DGf0KCTP.js} +1 -1
  30. package/dist/assets/{tsMode-BnycW89y.js → tsMode-D4ZDTisA.js} +1 -1
  31. package/dist/assets/{typescript-Bs6iTDav.js → typescript-CJFgy1iR.js} +1 -1
  32. package/dist/assets/{xml-DuKZPRNV.js → xml-BXhJpCm5.js} +1 -1
  33. package/dist/assets/{yaml-DDDa6myK.js → yaml-B7iGwJkY.js} +1 -1
  34. package/dist/icons/icon.svg +10 -13
  35. package/dist/index.html +1 -1
  36. package/package.json +10 -3
  37. package/dist/assets/AssociateMode-Bs_R9XbQ.js +0 -1
  38. package/dist/assets/AssociateTargetsEditor-CVWE3tbv.js +0 -1
  39. package/dist/assets/BatchMode-XGXMc2XF.js +0 -11
  40. package/dist/assets/BinaryColumnPickers-mrnLqk3Z.js +0 -1
  41. package/dist/assets/BulkDeleteMode-DowWcbnA.js +0 -1
  42. package/dist/assets/BulkWriteMode-Dt3M0dGV.js +0 -6
  43. package/dist/assets/DisassociateMode-qIc2CUpE.js +0 -2
  44. package/dist/assets/ExecuteWorkflowMode-Ce6sKYci.js +0 -1
  45. package/dist/assets/ManageFileMode-CcNSQkJf.js +0 -1
  46. package/dist/assets/ManageImageMode-Dn4P4D6H.js +0 -1
  47. package/dist/assets/MergeMode-DzPQq2Ao.js +0 -1
  48. package/dist/assets/PredefinedQueryMode-CaQqp2lm.js +0 -1
  49. package/dist/assets/RetrieveNextLinkMode-BNbknSwe.js +0 -1
  50. package/dist/assets/index-D0g0tm7R.js +0 -702
package/CHANGELOG.md CHANGED
@@ -7,6 +7,277 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.5.0-beta.1] - 2026-10-30
11
+
12
+ The first 1.5.0 beta. Writes now ask before they're sent, naming the
13
+ environment, and Production gets a safe mode that's on by default ([#241]).
14
+ Read and execute requests send their headers, and impersonation is never
15
+ dropped silently ([#109]). The entity scope moves from Settings to a button in
16
+ the header ([#42]). Ids, names and filter values are checked and typed before
17
+ they go into a URL ([#221]). There are also accessibility, metadata-cache and
18
+ copy fixes, and 272 new tests for the write path.
19
+
20
+ Still a **prerelease** on the npm `beta` tag, with the gold Insider icon.
21
+ Power Platform ToolBox **1.2.7 or later** is recommended: older hosts can't
22
+ send request headers, so a request with an impersonation header isn't sent
23
+ on them.
24
+
25
+ ### ✨ Added
26
+
27
+ - **The entity scope is a button in the header** ([#42]), after the request
28
+ type, instead of Settings → Query Scope. It reads **Choose scope** until you
29
+ pick one, then the scope itself (`Contoso › Sales Core v1.2.0`, `+1` for
30
+ more, or **All entities**), with the full list as a tooltip when it's cut
31
+ off. Its popover holds the entity source, publishers, solutions and
32
+ Advanced Find only, and changes apply right away, per environment as
33
+ before:
34
+ - removing a publisher also removes its solutions;
35
+ - solutions are grouped Unmanaged / Managed, show `Name vX.Y.Z`, and search
36
+ matches the name, unique name or version;
37
+ - on first run a tip points at the button, once per environment;
38
+ - without a scope, the entity picker is disabled and reads "Choose a scope
39
+ to list entities", and the pane's **Choose scope** opens the popover. With
40
+ one, it counts the entities in scope.
41
+
42
+ The same design as FetchXML Studio's and Command Bar Studio's. Settings
43
+ keeps a pointer to the button.
44
+ - **Writes ask before they're sent** ([#241]). The confirmation names the
45
+ target: the environment (connection name, URL and type, with Production
46
+ highlighted), the operation, the table and the scope. Execute and Ctrl+Enter
47
+ both go through it.
48
+ - Merge, Execute Action / Custom API / Custom Action, Execute Workflow, Bulk
49
+ Write, `$batch` and ExecuteMultiple with writes, and multi-target
50
+ Associate / Disassociate always ask.
51
+ - Create, Update, Upsert, Delete and single-target Associate / Disassociate
52
+ ask on a Production connection.
53
+ - On Production, and for more than 100 records (or batch writes) anywhere,
54
+ you type the table (or operation) name before the button enables.
55
+ - If the connection changes while the confirmation is open, nothing is sent.
56
+ - The Bulk Delete Job confirmation names the environment too.
57
+ - **The header shows the connection and its environment type** inside
58
+ ToolBox too, with Production in red ([#241]).
59
+ - **Production safe mode** in Settings → Safety, on by default ([#241]).
60
+ - **README: "What this tool changes"** lists every request that changes data,
61
+ when it asks, and what DRS stores locally ([#241]).
62
+ - **Read, Execute Function, Associate / Disassociate and Bulk Delete Job
63
+ requests send their headers** ([#109]). The Headers pane says which rows
64
+ Execute sends and marks the rest as Code tab only. Later pages of a
65
+ Retrieve Multiple send the first page's headers, so they run as the same
66
+ user. It's an allow-list, so a plain read still sends none and never asks
67
+ for consent:
68
+ - impersonation (`MSCRMCallerID`, and a new `CallerObjectId` preset for
69
+ the Microsoft Entra object id) in all of them;
70
+ - `If-None-Match` and `Consistency` on reads. A matching etag shows as
71
+ **304 Not Modified**, not as an error;
72
+ - the bypass headers on Associate / Disassociate.
73
+ The page size's `Prefer` still keeps ToolBox's
74
+ `odata.include-annotations="*"`; other preferences stay in the Code tab.
75
+ - **Impersonation is never dropped silently** ([#109]).
76
+ - On a ToolBox older than 1.2.7, which can't send headers, a request with
77
+ an impersonation header isn't sent, instead of running as you. The same
78
+ goes for Associate / Disassociate with a bypass header.
79
+ - Both impersonation headers at once, or the presets' all-zero
80
+ placeholder, aren't sent either.
81
+ - A declined header prompt on Associate / Disassociate asks once and sends
82
+ nothing, rather than falling back to a request without your headers.
83
+ - **Execute Custom API and Custom Action list your own operations first**
84
+ ([#248]). A Dynamics org has well over a thousand of them, nearly all
85
+ Microsoft's. The Operation list now groups them:
86
+ - **Your org & ISVs** first, **Microsoft** below. Nothing is hidden, and
87
+ search covers both groups (publisher names too).
88
+ - Each one shows its solution's publisher, and so does the summary card.
89
+ - The Scope list counts your own operations per scope ("12 ops, 2 yours").
90
+ - Execute Action (WinOpportunity, QualifyLead, …) is unchanged.
91
+
92
+ ### 🐛 Fixed
93
+
94
+ - **The sidebar works with a screen reader and the keyboard** ([#243]). It
95
+ announced itself as a tree, but arrow keys did nothing, nested clauses
96
+ were read as top-level ones, and every parent said "expanded" although
97
+ nothing collapses. It's now a "Request structure" navigation landmark:
98
+ - each section has a heading and is a list named by it, and nested
99
+ clauses (an `$expand` relationship's clauses, required parameters, Bulk
100
+ Write rows) are nested lists, so their level is read;
101
+ - Tab moves between clauses, Enter or Space opens one, and the open one
102
+ is marked as current;
103
+ - the chevrons, which looked collapsible but weren't, are gone;
104
+ - the "modified" marker and the ✓ badge are read out;
105
+ - keyboard focus shows a ring inside the sidebar;
106
+ - the table name after an expanded relationship (`primarycontactid →
107
+ Contact`) has enough contrast to read.
108
+ - **Small labels are readable again** ([#330]). Badges such as "req",
109
+ "null", "File", "max 32 MB", "soon", "lookup" and the Results count used
110
+ Fluent's extra-small size, a 10px dot, so their text spilled out or was
111
+ cut off. They now use the small size, as the sidebar badges do since
112
+ [#200].
113
+ - **Expired metadata is refetched, not served as fresh** ([#334]). The table
114
+ list, and the columns of a table not yet loaded this session, are cached
115
+ for an hour. When that hour is up and they're fetched again, other pickers
116
+ now wait for the fetch instead of getting the old data, and a failed fetch
117
+ is retried on the next use instead of the old data counting as fresh for
118
+ another hour.
119
+ - **Retrieve Multiple's checks run once the table's columns arrive**
120
+ ([#347]). A saved request loaded before its table's metadata showed no
121
+ advisories, and Execute wasn't blocked for a query Dataverse rejects, until
122
+ you changed something.
123
+ - **Save and the Saved library use the current request and environment**
124
+ ([#347]). The header kept calling the handlers from when the mode last
125
+ published them, so they could read old data. Loading a saved Retrieve
126
+ Multiple request whose table this environment doesn't have now says so,
127
+ even when the table list arrived after the mode opened.
128
+ - **Text follow-ups** ([#317]):
129
+ - Associate and Disassociate say "Target record" when one target is
130
+ picked or the relationship takes only one, in the pane and the sidebar,
131
+ and "Target records" otherwise.
132
+ - An action or function that returns `Collection(<type>)` lists one item's
133
+ properties when the type is known, and a Custom API response with a
134
+ publisher prefix (`msdyn_ActivateProcessesResponse`) lists its
135
+ properties and is labelled complex, instead of being described as an
136
+ entity. On a Dynamics org that's several hundred operations.
137
+ - **Copy buttons go through ToolBox and say whether they worked** ([#242]).
138
+ Inside ToolBox, the webview can refuse the browser clipboard, and a
139
+ refused copy did nothing at all: you then pasted whatever was on the
140
+ clipboard before. Every Copy button (URL bar, Code tab, results, write
141
+ result, previews, Power Automate, …) now uses ToolBox's own clipboard
142
+ inside ToolBox (the browser's outside it), and confirms the copy with a
143
+ short "Copied" note or on the button itself. When it fails, it says
144
+ "Couldn't copy" and what to do instead. Retrieve NextLink's Paste says
145
+ when the clipboard can't be read.
146
+ - **Choosing a file no longer reads it into memory** ([#222]). Manage File,
147
+ Image and Attachment Data keep the file's name, size and type only: Execute
148
+ can't send binary content from inside ToolBox, and the Code tab uses a
149
+ placeholder for the bytes, so a large file used to freeze the tool for
150
+ nothing. Manage Image previews the chosen image through an object URL (up
151
+ to 5 MB). A pasted base64 body is capped at 10 MB, with a message.
152
+ - **Non-ASCII file names work in generated upload code** ([#222]). The
153
+ `x-ms-file-name` header only takes ASCII (and `fetch` / XHR throw on such
154
+ a header), so a name like `报告.pdf` or `Résumé.docx` travels as the
155
+ `x-ms-file-name` query parameter instead, as Microsoft documents, in both
156
+ the single-request and chunked uploads.
157
+ - **Invalidating one table's metadata now refetches it** ([#335]). The next
158
+ read used to return the old table from the in-memory registry. Nothing
159
+ invalidates a single table yet, so this changes nothing you can see today.
160
+ - **"Advanced Find only" works, and is off by default** ([#44]), matching
161
+ FetchXML Studio:
162
+ - Off: the table, column and relationship pickers offer everything.
163
+ - On: they offer only what Advanced Find shows (`IsValidForAdvancedFind`).
164
+ Image and File columns are always offered.
165
+ - Metadata now loads unfiltered, and only the pickers are scoped, so a
166
+ column already in a request keeps working either way. Before, the switch
167
+ did nothing, and columns and relationships that Advanced Find hides were
168
+ never offered.
169
+ - The read pickers still never offer columns that can't be read, and new
170
+ sorts, filter rules and functions start on a column the picker offers.
171
+ - The Create form doesn't treat columns Advanced Find hides (such as
172
+ `owneridtype`) as required, as before.
173
+ - A setting saved by an earlier version is reset to off once.
174
+ - Loading a saved request, pasting a URL and a batch item's entity set
175
+ check the table against every table, so a saved request for a table
176
+ outside the Query Scope loads instead of being reported missing.
177
+ - **Ids and names are checked before they go into a URL** ([#221]). A record
178
+ id must be a GUID, and a navigation property or column name a plain name,
179
+ before Execute enables. This applies in Associate, Disassociate, Execute
180
+ Action / Function / Workflow, Predefined Query and the file, image and
181
+ attachment modes. The other modes already checked. The executor refuses
182
+ them too, so a value like `x)/other_nav` can't send a different request.
183
+ - **A query function on a related table's column is caught inside `any` /
184
+ `all` too** ([#336]). Dataverse rejects a function such as `EqualUserId`
185
+ whose column runs through a relationship
186
+ (`PropertyName='parentcustomerid_account/ownerid'`). Outside a lambda
187
+ this already blocked Execute with an explanation; inside one it wasn't
188
+ checked, so the request was sent and failed.
189
+ - **Filter values are typed** ([#221]). A number, GUID or date column's
190
+ value goes into `$filter` unquoted only when it is one. Anything else is
191
+ quoted and escaped, and Execute is blocked with a message naming the value,
192
+ instead of a Dataverse 400. The DateTime fallback now escapes quotes. The
193
+ same applies to the Dataverse query functions (`LastXDays`, `Under`, …),
194
+ `$expand` inner filters and Bulk Delete Job. Filter column, lambda and
195
+ `$expand` names must be names too. EntityName columns (`objecttypecode`)
196
+ are now compared as strings, as the Web API expects.
197
+ - **Execute Function parameters are typed the same way** ([#221]). GUID and
198
+ date values go into the URL unquoted only when they are one, and record
199
+ references are escaped.
200
+ - **Imported saved requests are checked deeply** ([#221]). Entries whose
201
+ ids, names or query trees would change the URL are skipped, and the import
202
+ status says which and why. Copying or moving from another connection's
203
+ library applies the same check.
204
+ - **Retrieve Single no longer turns on `If-None-Match: null`** by default
205
+ ([#109]). Execute sends that header now, and `null` never matches an etag;
206
+ saved requests that have it still run without it.
207
+ - **Time zone independent times in a DST gap keep their digits** ([#337]).
208
+ Such a time is stored as typed, with no conversion. When it fell in the
209
+ hour your clocks skip (02:30 on a spring-forward day), the results grid and
210
+ the Update / Merge comparison showed it an hour later, and changing only
211
+ its date, or just clicking into the time picker and out, sent the later
212
+ time. The time picker itself still shows it an hour on, because it can
213
+ only hold a local time.
214
+ - **Exported URLs encode spaces** ([#221]). Postman, Insomnia and Bruno
215
+ collections, cURL / fetch / XHR / C# / PowerShell code and the HTTP-action
216
+ URIs write `%20`. The URL bar still shows spaces.
217
+
218
+ ### 🔧 Internal
219
+
220
+ - **Release model leftovers** ([#197]):
221
+ - `.github/dependabot.yml` sends grouped weekly updates into `dev` with a 14-day
222
+ cooldown, the same policy as FetchXML Studio and Command Bar Studio.
223
+ `RELEASING.md` describes it.
224
+ - `SECURITY.md` has the shared supported-versions table.
225
+ - **Alternate-key column types go through the shared type lookup**
226
+ ([#318]). Key columns typed separately (#64) now resolve the way every
227
+ other column does, Image and File included. No visible change: a key
228
+ column can't be an Image or File column.
229
+ - **Saved-request tests no longer re-import the store per test** ([#319]).
230
+ The store's startup (credential scrub, then read) is one function,
231
+ `startSavedStore()`, that the module runs at load and the tests call
232
+ directly. Those tests went from about 415 ms to about 20 ms each, so
233
+ they no longer time out when several test runs share the machine. One
234
+ test still loads the module afresh to check the startup wiring.
235
+ - **ESLint and a package check in CI** ([#273]), as in FetchXML Studio and
236
+ Command Bar Studio:
237
+ - `npm run lint` runs ESLint (recommended JS / TypeScript rules, React
238
+ hooks, jsx-a11y) with no warnings allowed, in CI. It also stops direct
239
+ `navigator.clipboard` use (#242). Fixing its findings removed dead code
240
+ and caught a crash: the `$apply` editor called two hooks after an early
241
+ return, so React threw when a table's metadata arrived after the
242
+ editor first rendered.
243
+ - CI and the release workflow check what `npm pack` would publish: the
244
+ files ToolBox needs, no sources or source maps, and a size budget.
245
+ - `npm run finalize-package` is gone; CI and the release workflow cover
246
+ it. `minAPI` stays at 1.2.0: DRS detects what the host can do at
247
+ runtime.
248
+ - **Tests for the write path** ([#235]): 272 new tests, 804 in all.
249
+ - A parity test checks, mode by mode, that Execute sends exactly what the
250
+ Code tab shows: method, URL, body and headers, apart from the documented
251
+ differences (headers the host builds, the reads' allow-list and page
252
+ size).
253
+ - The write executors' refusals: PUT of one column, alternate-key Upsert,
254
+ single-property Delete, unsafe ids, and impersonation on an older
255
+ ToolBox.
256
+ - Modules that had no tests: date and time values, the bypass headers,
257
+ workflow arguments, request validation, the query advisories, mode
258
+ drafts, the metadata cache and provider, and the ToolBox bridge's events.
259
+
260
+ [#197]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/197
261
+ [#42]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/42
262
+ [#347]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/347
263
+ [#330]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/330
264
+ [#242]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/242
265
+ [#317]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/317
266
+ [#334]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/334
267
+ [#235]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/235
268
+ [#273]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/273
269
+ [#319]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/319
270
+ [#318]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/318
271
+ [#248]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/248
272
+ [#335]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/335
273
+ [#222]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/222
274
+ [#44]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/44
275
+ [#336]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/336
276
+ [#109]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/109
277
+ [#221]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/221
278
+ [#337]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/337
279
+ [#241]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/241
280
+
10
281
  ## [1.4.0] - 2026-10-30
11
282
 
12
283
  The first stable release since 1.1.4, and the biggest so far. The work planned
package/README.md CHANGED
@@ -152,10 +152,15 @@ modes have their own HTTP / fetch / C# / PPTB outputs.
152
152
  - **Request headers through PPTB 1.2.7+** — Create / Update / Upsert /
153
153
  Delete / Merge / Bulk Write / Execute Action / Execute Workflow headers
154
154
  (preconditions, `MSCRM.*` bypass, duplicate detection, impersonation) are
155
- sent as additional headers after you approve them once in ToolBox, and so is
156
- the page size of paged reads. On older hosts, write requests that depend on
157
- a precondition or bypass header are blocked with an explanation.
158
- `Authorization` / `Cookie` headers are never sent, saved or exported.
155
+ sent as additional headers after you approve them once in ToolBox. The
156
+ read modes, Execute Function, Associate / Disassociate and Bulk Delete Job send an
157
+ allow-list: impersonation (`MSCRMCallerID`, `CallerObjectId`) everywhere,
158
+ plus `If-None-Match`, `Consistency` and the page size on reads, and the
159
+ bypass headers on Associate / Disassociate; the Headers pane marks the
160
+ rest as Code tab only. On older hosts, requests that depend on a
161
+ precondition, bypass or impersonation header are blocked with an
162
+ explanation. `Authorization` / `Cookie` headers are never sent, saved or
163
+ exported.
159
164
  - **Antipattern advisories** — Surfaces real-time guidance per the
160
165
  [Microsoft query-antipatterns doc](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/query-antipatterns):
161
166
  `FilteringOnCalculatedColumns`, `LargeAmountOfLogicalAttributes`, large-text
@@ -221,9 +226,11 @@ modes have their own HTTP / fetch / C# / PPTB outputs.
221
226
 
222
227
  - [Power Platform ToolBox](https://www.powerplatformtoolbox.com/) **1.2.0 or
223
228
  later** (the tool declares `minAPI: 1.2.0`). **1.2.7 or later** is
224
- recommended: it sends the write and execute modes' request headers and the
225
- page size, and is required for
226
- the `$batch` and ExecuteMultiple modes.
229
+ recommended: it sends request headers (impersonation, preconditions,
230
+ bypass) and the page size, and is required for
231
+ the `$batch` and ExecuteMultiple modes. DRS detects what the host can do
232
+ at runtime, so `minAPI` stays at 1.2.0 rather than locking out older
233
+ hosts (#273).
227
234
  - A connection to a Dataverse environment
228
235
  - For local development: **Node.js 22.22.2+, 24.15+ or 26+** and **npm** (see
229
236
  `engines` in `package.json`)
@@ -236,6 +243,67 @@ are published to npm under the `latest` tag. Prereleases of the next version
236
243
  are published under the `beta` tag (for example `1.5.0-beta.1`) and use the
237
244
  gold Insider icon.
238
245
 
246
+ ### Choose the entity scope
247
+
248
+ The entity pickers list the entities in the scope shown on the **scope button**
249
+ in the header, after the request type. On first run it reads **Choose scope**
250
+ and a tip points at it. Open it to pick where entities come from:
251
+
252
+ - **Publisher → solution** (default): one or more publishers, then their
253
+ solutions;
254
+ - **Solution only**: one or more solutions;
255
+ - **All entities**: everything in the environment.
256
+
257
+ **Advanced Find only** is there too. Changes apply right away, and the scope is
258
+ remembered per environment.
259
+
260
+ ---
261
+
262
+ ## ✏️ What this tool changes
263
+
264
+ Dataverse Request Studio only reads from Dataverse until you send a request
265
+ from one of the write, relate, execute, bulk or batch modes. Every request runs
266
+ as the connected user (or the user an impersonation header names), so Dataverse
267
+ applies that user's security roles.
268
+
269
+ **Before a write is sent, it asks.** The confirmation names the target: the
270
+ environment (connection name, URL and type, with Production highlighted), the
271
+ operation, the table and the scope. The header shows the connection and its
272
+ type at all times.
273
+
274
+ | Request | When it asks |
275
+ |---|---|
276
+ | **Merge**, **Execute Action / Custom API / Custom Action**, **Execute Workflow**, **Bulk Write**, `$batch` / **ExecuteMultiple** with any write, **Associate / Disassociate** with more than one target | Always |
277
+ | **Create**, **Update**, **Upsert**, single-target **Associate / Disassociate** | On a Production connection, with **Production safe mode** on (the default; Settings → Safety) |
278
+ | **Delete** | Always for a whole row: type the record's name and acknowledge, in the mode itself. On a Production connection with safe mode on, the confirmation above as well |
279
+ | **Bulk Delete Job** | Always: the confirmation names the environment, counts the matching rows, and you type the table name |
280
+ | Reads (Retrieve, Predefined Query, Execute Function, downloads) | Never |
281
+
282
+ On a Production connection with safe mode on, and for more than 100 records (or
283
+ more than 100 writes in a batch) on any connection, you type the table name (or
284
+ the action name, or `batch` / `ExecuteMultiple`) before the confirm button
285
+ enables. Execute and Ctrl+Enter go through the same confirmation. If the
286
+ connection changes while the confirmation is open, nothing is sent.
287
+
288
+ What each request does in Dataverse is exactly what the URL bar and the Code
289
+ tab show: one Web API request (or one per target for Associate / Disassociate,
290
+ or one `$batch` per group). The binary modes (file, image, attachment) don't
291
+ send anything from inside ToolBox: Execute returns 501, and you copy the request
292
+ from the Code tab.
293
+
294
+ **Stored on your machine, not in Dataverse:**
295
+
296
+ - **Saved requests** — in the browser storage of the ToolBox tool window, one
297
+ library per environment (`drs:saved-requests:v1:<host>`). If a library can't
298
+ be read, it's copied to a backup key instead of being overwritten. Export and
299
+ Import write and read JSON files you pick.
300
+ - **Settings** (logical names, value display, entity scope, Advanced Find,
301
+ density, column widths, Production safe mode) — in ToolBox's settings store
302
+ for this tool.
303
+ - **Exports** (CSV, JSON, Postman, Insomnia, Bruno, OpenAPI) — only to files you
304
+ choose. Credential headers (`Authorization`, cookies) are never saved or
305
+ exported.
306
+
239
307
  ---
240
308
 
241
309
  ## 🛠️ Development
@@ -272,8 +340,8 @@ npm run preview
272
340
  # Validate manifest against PPTB registry rules
273
341
  npm run validate
274
342
 
275
- # Pre-publish: validate → build
276
- npm run finalize-package
343
+ # Lint (ESLint, no warnings allowed)
344
+ npm run lint
277
345
  ```
278
346
 
279
347
  ### Standalone vs PPTB-embedded
@@ -422,6 +490,7 @@ Dataverse API)
422
490
  | `Prefer: return=representation` | ✅ (ToolBox always sends it on writes) |
423
491
  | Optimistic concurrency (`If-Match` / `If-None-Match`) | ✅ 1.2.7+ |
424
492
  | `MSCRM.*` bypass family (custom plug-ins, flows, async) | ✅ 1.2.7+ |
493
+ | Impersonation (`MSCRMCallerID` / `CallerObjectId`) on every mode | ✅ 1.2.7+ |
425
494
  | Single-property PUT / DELETE | 📝 |
426
495
  | Alternate-key upsert | 📝 |
427
496
  | Associate / Disassociate (collection + single-valued) | ✅ |
package/SECURITY.md CHANGED
@@ -49,6 +49,13 @@ in a browser. Vulnerability reports of interest:
49
49
 
50
50
  ## Supported versions
51
51
 
52
- Only the latest released minor version on `main` receives security fixes.
52
+ | Version | Supported |
53
+ |---|---|
54
+ | The current stable release (npm `latest`) | ✅ Fixes and security fixes |
55
+ | The previous minor release | ✅ Critical and security fixes for 30 days after the next minor ships (npm `support-X.Y`) |
56
+ | Betas (npm `beta`) | Fixed in the next beta |
57
+ | Anything older | ❌ |
58
+
59
+ See [RELEASING.md](RELEASING.md) → *Supported versions*.
53
60
 
54
61
  Thanks for helping keep the tool safe.
@@ -0,0 +1 @@
1
+ import{k as le,b9 as ie,bQ as z,l as r,u as de,n as ce,bR as ue,bS as ge,bT as he,f as be,bU as pe,bc as me,bV as ye,be as ve,p as M,q as W,t as fe,T as Se,v as xe,bW as Pe,bX as Te,bL as Ne,bM as je,bY as A,L as ke,z as we,A as a,H as Ce,N as Ie,O as Me,V as Re,D as Ae,bZ as Le,I as J,J as He,K as $e,P as Fe,R as qe,b_ as R,U as Be,S as Ee,Q as Ue,b0 as Oe,b1 as De,bs as Ve,b8 as ze,ah as We,a2 as T,bq as Je,a3 as Qe,br as _e}from"./index-XmEQbXiX.js";import{t as Ge,A as Ke,N as Xe}from"./AssociateTargetsEditor-BoH9Qxe8.js";const Ye=()=>({table:"",sourceId:null,navProperty:null,targets:[],targetNames:{},headers:Ue(),dirty:new Set});function st({themeMode:d}){const p=le("associate"),l=ie("associate",z,Ye),[e,c]=r.useState(l.state),{table:N}=de(e.table||null),{allEntities:L}=ce(),[H,$]=r.useState("source"),[m,j]=r.useState("builder"),[F,k]=r.useState(null),[_,q]=r.useState(!1),[G,K]=r.useState([]),[y,v]=r.useState(l.lastSavedId),[f,S]=r.useState(l.lastSavedHash),[B,w]=r.useState(""),b=r.useMemo(()=>ue(e),[e,N]),X=r.useMemo(()=>ge(e),[e,N]),n=r.useMemo(()=>he(e),[e,N]),x=be(e.table),o=e.navProperty?x?.navigationProperties.find(t=>t.name===e.navProperty):void 0,E=o?pe(o):!1,u=E?"PATCH":"POST",C=t=>c(s=>{const i=new Set(s.dirty);return i.add(t),{...s,dirty:i}}),P=(t,s,i)=>{c(I=>({...I,[t]:s})),i&&C(i)},Y=me([["Source record id",e.sourceId],...e.targets.map(t=>["Target record id",t])],[["Navigation property",e.navProperty]]),Z=x?e.sourceId?e.navProperty?e.targets.length===0?"Pick at least one target record.":e.headers.some(t=>t.enabled&&!t.name)?"Fix empty header name.":Y:"Pick a navigation property.":"Pick a source record.":"Pick a source table first.",ee=async()=>{q(!0);const t=await De.associate(e,J(e.headers,null));k(t),q(!1),j("results"),K(s=>[{id:`r-${Date.now()}`,snapshot:g,modeId:"associate",url:b.relativeUrl,method:u,ts:Date.now(),status:t.status,ms:t.ms,rowCount:R(t,n.length)??0,summary:`${R(t,n.length)??0} of ${n.length} linked`},...s].slice(0,8)),c(s=>({...s,dirty:new Set}))},g=r.useMemo(()=>ye(e),[e]);ve("associate",g,y,f);const te=r.useMemo(()=>M(g),[g]),U=f===null?!0:te!==f,ae=t=>{v(t.id),S(M(t.state))},O=t=>{if(t.modeId!=="associate")return;const s=t.state;if(L.length>0&&!L.some(i=>i.logicalName===s.table)){Oe(`Can't load "${t.name}": entity \`${s.table}\` isn't available in this environment. The solution may have been removed or you may be connected to a different org.`);return}c(z(s)),v(t.id),S(M(s)),k(null),w(""),$("source")},se=t=>{const s=Ve(t,"associate");if(!s)return;const i=y,I=f;O(s),v(i),S(I)},D=W(ae),V=W(O);fe(r.useMemo(()=>e.table?{state:g,modeId:"associate",dirty:U,lastSavedId:y,onSaved:D,onLoadSaved:V}:null,[g,U,y,e.table,D,V]));const re=[{id:"source",label:"Target",meta:x?.displayName??"Pick a table",items:[{id:"source",icon:xe,iconFilled:Se,label:e.sourceId?B||`${x?.displayName??""} (selected)`:"Pick a record",badge:o?u:null,badgeAppearance:"tint",badgeColor:"brand",dirty:e.dirty.has("source")}]},{id:"relationship",label:"Relationship",meta:o?Q(o.cardinality):"pick one",items:[{id:"nav",icon:Te,iconFilled:Pe,label:o?o.name:"Navigation property",code:!!o,badge:o?Q(o.cardinality):null,badgeAppearance:"ghost",dirty:e.dirty.has("nav")}]},{id:"targets",label:"Related",meta:e.targets.length?`${e.targets.length} target${e.targets.length===1?"":"s"}`:"none",items:[{id:"targets",icon:je,iconFilled:Ne,label:Ge(E,e.targets.length),badge:e.targets.length||null,badgeAppearance:"tint",badgeColor:e.targets.length>0?"success":"subtle",dirty:e.dirty.has("targets")},...n.length>0?[{id:"preview",icon:A,iconFilled:A,label:`${n.length} request${n.length===1?"":"s"}`,badge:n.length,badgeAppearance:"ghost"}]:[]]},{id:"headers",label:"Headers",meta:`${e.headers.filter(t=>t.enabled).length} active`,items:[{id:"headers",icon:we,iconFilled:ke,label:"HTTP headers",badge:e.headers.filter(t=>t.enabled).length||null,dirty:e.dirty.has("headers")}]}];let h;switch(H){case"source":h=a.jsx(Ae,{table:e.table,onTableChange:t=>{c(s=>({...s,table:t,sourceId:null,navProperty:null,targets:[],targetNames:{},dirty:new Set(["source","nav","targets"])})),w(""),k(null),v(void 0),S(null)},recordId:e.sourceId,onRecordChange:(t,s)=>{P("sourceId",t,"source"),w(s??"")},group:"relate",sub:"Pick the source entity and the record that the relationship anchors on."});break;case"nav":h=a.jsx(Xe,{table:e.table,value:e.navProperty,onChange:t=>{c(s=>({...s,navProperty:t,targets:[],targetNames:{}})),C("nav"),C("targets")},group:"relate",forOperation:"associate",footer:a.jsx(Ie,{layout:"multiline",intent:"info",children:a.jsxs(Me,{children:[a.jsx(Re,{children:"How cardinality drives the request"}),a.jsx("strong",{children:"Collection-valued"})," (1:N / N:N) → ",a.jsx("code",{children:"POST /…/$ref"})," with one request per target. ",a.jsx("strong",{children:"Single-valued"})," (N:1) →"," ",a.jsx("code",{children:"PATCH /source(id)"})," with body"," ",a.jsx("code",{children:'{ "<nav>@odata.bind": "<target-set>(<id>)" }'})," (one target). This is the docs-preferred shape — the URL bar verb updates automatically. The PATCH is sent with ",a.jsx("code",{children:"If-Match: *"}),", so a wrong source id fails with 404 instead of creating a record; Power Platform ToolBox asks you to approve that header once."," ",a.jsx("a",{href:"https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/associate-disassociate-entities-using-web-api",target:"_blank",rel:"noopener noreferrer",style:{color:"inherit"},children:"MS Learn ↗"})]})})});break;case"targets":h=a.jsx(Ke,{table:e.table,navProperty:e.navProperty,targets:e.targets,setTargets:t=>P("targets",t,"targets"),targetNames:e.targetNames,setTargetNames:t=>P("targetNames",t),group:"relate",resolvedMethod:o?u:null});break;case"preview":h=a.jsx(Ze,{requests:n});break;case"headers":h=a.jsx(Ce,{policy:"relate",items:e.headers,setItems:t=>P("headers",t,"headers"),group:"relate"});break}const oe=Le(u,J(e.headers,null)),ne={method:u,built:b,headers:oe,body:X,entityLogical:b.entityLogical,multiRequests:n.length>1?n.map(t=>({method:t.method,relativeUrl:t.relativeUrl,body:t.body,description:`target ${t.targetId}`})):void 0};return a.jsx(He,{sidebar:a.jsx(Ee,{type:p,urlPreview:b.relativeNoBase,sections:re,activeNode:H,onSelect:t=>{$(t),j("builder")},recents:G,onRecentClick:se}),urlBar:a.jsx(Be,{method:u,url:b.relativeUrl,executeVerb:p.executeVerb,writeConfirm:{operation:o?`Associate (${o.name})`:"Associate",table:e.table,scope:{kind:"records",count:Math.max(1,e.targets.length)},highImpact:e.targets.length>1},disabledReason:Z,loading:_,onExecute:ee}),children:a.jsxs($e,{tab:m,onTabChange:j,resultCount:R(F,n.length),children:[m==="builder"&&h,m==="code"&&a.jsx(Fe,{themeMode:d,inputs:ne}),m==="results"&&a.jsx(qe,{result:F,mode:"single",table:e.table,writeContext:{operation:"associate",table:e.table,recordId:e.sourceId,recordName:B||null,navProperty:e.navProperty??void 0,targetCount:e.targets.length,targetNames:e.targets.map(t=>e.targetNames[t]).filter(t=>!!t),targetNameById:e.targetNames}})]})})}function Ze({requests:d}){const p=ze();return a.jsxs("div",{children:[a.jsx(We,{icon:A,title:`Generated requests (${d.length})`,sub:"Each target queues a separate HTTP request. For large counts, prefer a $batch request.",group:"relate"}),a.jsxs("div",{className:_e(p.inlineCard),style:{padding:12,maxWidth:980,fontFamily:T.fontFamilyMonospace,fontSize:11},children:[d.map((l,e)=>a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"60px 1fr",gap:8,padding:"8px 0",borderBottom:e<d.length-1?`1px solid ${T.colorNeutralStroke3}`:"none"},children:[a.jsx(Je,{appearance:"filled",color:l.method==="POST"?"success":"warning",style:{fontWeight:700,justifySelf:"start"},children:l.method}),a.jsxs("div",{style:{minWidth:0},children:[a.jsx("div",{style:{wordBreak:"break-all"},children:l.relativeUrl}),a.jsx("div",{style:{marginTop:4,color:T.colorNeutralForeground3},children:JSON.stringify(l.body)})]})]},l.targetId)),d.length===0&&a.jsx(Qe,{style:{color:T.colorNeutralForeground3,fontStyle:"italic",padding:"12px 4px",textAlign:"center",display:"block"},children:"No requests queued — pick at least one target on the Related pane."})]})]})}function Q(d){switch(d){case"OneToMany":return"1:N";case"ManyToOne":return"N:1";case"ManyToMany":return"N:N"}}export{st as AssociateMode};
@@ -0,0 +1 @@
1
+ import{f,b3 as G,b7 as K,u as V,A as e,ah as S,bW as b,ad as B,bn as J,b5 as U,a2 as a,bq as u,a3 as v,l as O,b8 as X,N as C,O as E,aL as M,c5 as Y,bP as _,Y as Q,aX as Z,br as ee,b6 as te,aJ as ne,V as ae}from"./index-XmEQbXiX.js";function ie({table:t,value:l,onChange:n,group:i="relate",forOperation:p,footer:y}){const g=f(t)?.navigationProperties??[],d=g.find(s=>s.name===l),T=G(),F=g.filter(s=>K(s,T)||s.name===l);return V(d?.targetEntity??null),e.jsxs("div",{children:[e.jsx(S,{icon:b,title:"Navigation property",sub:"Cardinality is detected from metadata — the URL bar verb + shape adapt automatically.",group:i}),e.jsxs("div",{style:{maxWidth:720},children:[e.jsx(B,{label:"Navigation property",children:e.jsx(J,{value:d?.name??"",selectedOptions:d?[d.name]:[],onOptionSelect:(s,m)=>n(m.optionValue??null),placeholder:"Pick a navigation property…",children:F.map(s=>e.jsx(U,{value:s.name,text:s.name,children:e.jsx(re,{nav:s,forOperation:p})},s.name))})}),d&&e.jsx("div",{style:{marginTop:16},children:e.jsx(le,{nav:d,forOperation:p})}),y&&e.jsx("div",{style:{marginTop:14},children:y})]})]})}function re({nav:t,forOperation:l}){const n=f(t.targetEntity),i=W(t,l);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontFamily:a.fontFamilyMonospace,fontWeight:600},children:t.name}),e.jsx(u,{appearance:"ghost",size:"small",children:R(t.cardinality)}),e.jsx(u,{appearance:"tint",color:"brand",size:"small",style:{marginLeft:"auto"},children:i})]}),e.jsxs(v,{style:{color:a.colorNeutralForeground3},children:["→ ",n?.displayName??t.targetEntity," · ",se(t.cardinality)]})]})}function le({nav:t,forOperation:l}){const n=f(t.targetEntity),i=W(t,l),p=t.cardinality==="ManyToOne"?"single-valued":"collection-valued",y=i==="POST"?a.colorPaletteGreenForeground1:i==="PATCH"?a.colorPaletteDarkOrangeForeground1:a.colorPaletteRedForeground1;return e.jsxs("div",{style:{border:`1px solid ${a.colorNeutralStroke2}`,borderRadius:a.borderRadiusMedium,padding:12,background:a.colorNeutralBackground1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(b,{style:{width:18,height:18,color:a.colorBrandForeground1}}),e.jsx("strong",{style:{fontFamily:a.fontFamilyMonospace,fontSize:13},children:t.name}),e.jsx(u,{appearance:"tint",color:"brand",children:R(t.cardinality)}),e.jsx("span",{style:{flexGrow:1}}),e.jsx(u,{appearance:"filled",style:{background:y,color:a.colorNeutralForegroundOnBrand,fontWeight:700},children:i})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"120px 1fr",rowGap:4,fontSize:11},children:[e.jsx("span",{style:{color:a.colorNeutralForeground3},children:"Target entity"}),e.jsxs("span",{style:{fontFamily:a.fontFamilyMonospace},children:[n?.entitySetName??t.targetEntity," ",e.jsxs(v,{style:{color:a.colorNeutralForeground3},children:["· ",n?.displayName??t.targetEntity]})]}),e.jsx("span",{style:{color:a.colorNeutralForeground3},children:"Cardinality"}),e.jsxs("span",{children:[p," (",t.cardinality,")"]}),e.jsx("span",{style:{color:a.colorNeutralForeground3},children:"Relationship"}),e.jsx("span",{style:{fontFamily:a.fontFamilyMonospace,fontSize:10},children:t.relationshipName})]})]})}function R(t){switch(t){case"OneToMany":return"1:N";case"ManyToOne":return"N:1";case"ManyToMany":return"N:N"}}function se(t){return t==="ManyToOne"?"single-valued lookup":"collection-valued"}function W(t,l){return t.cardinality==="ManyToOne"?"PATCH":l==="disassociate"?"DELETE":"POST"}function A(t,l){return t||l===1?"Target record":"Target records"}function ce({table:t,navProperty:l,targets:n,setTargets:i,targetNames:p,setTargetNames:y,group:N="relate",resolvedMethod:g,sub:d,verb:T="POST"}){const[F,s]=O.useState({}),m=p??F,P=y??s,w=X(),q=f(t),h=l?q?.navigationProperties.find(r=>r.name===l):void 0,x=h?f(h.targetEntity):void 0,o=h?.cardinality==="ManyToOne",z=o?1:1/0,[$,D]=O.useState(0);if(!h)return e.jsxs("div",{children:[e.jsx(S,{icon:b,title:A(!1,n.length),sub:"Pick a navigation property first.",group:N}),e.jsx(C,{layout:"multiline",intent:"info",style:{maxWidth:720},children:e.jsxs(E,{children:["Switch to the ",e.jsx("strong",{children:"Navigation property"})," pane and pick one — the target entity comes from there."]})})]});const k=n.length>=z,I=(r,c)=>{if(!r||n.includes(r)||k)return;const j=o?[r]:[...n,r];i(j),c&&P({...m,[r]:c}),D(L=>L+1)},H=r=>{if(i(n.filter(c=>c!==r)),m[r]!=null){const c={...m};delete c[r],P(c)}};return e.jsxs("div",{children:[e.jsxs(S,{icon:b,title:A(o,n.length),sub:e.jsx("span",{children:d??(o?e.jsxs(e.Fragment,{children:["One target is allowed for ",e.jsx("code",{children:h.cardinality})," nav props — a PATCH with"," ",e.jsxs("code",{children:[h.name,"@odata.bind"]})," sets the lookup."]}):e.jsxs(e.Fragment,{children:["One or more targets — each fires a separate POST request. For many targets, Dataverse recommends a ",e.jsx("code",{children:"$batch"})," request."]}))}),group:N,children:[e.jsxs(u,{appearance:"tint",color:n.length>0?"brand":"subtle",children:[n.length," target",n.length===1?"":"s"]}),g&&e.jsx(u,{appearance:"filled",color:g==="POST"?"success":"informative",style:{fontWeight:700},children:g}),!o&&n.length>1&&e.jsx(M,{content:"Will fire one request per target — Dataverse recommends $batch for large counts. Batch transport lands in a later pass.",relationship:"description",children:e.jsxs(u,{appearance:"ghost",icon:e.jsx(Y,{style:{width:12,height:12}}),children:[n.length," requests queued"]})})]}),e.jsx("div",{className:ee(w.inlineCard),style:{padding:12,marginBottom:14,maxWidth:880},children:n.length===0?e.jsxs(v,{style:{padding:"12px 4px",color:a.colorNeutralForeground3,fontStyle:"italic",display:"block",textAlign:"center"},children:["No targets selected — use the picker below to choose"," ",o?"one":"one or more"," ",e.jsx("strong",{children:x?.displayName??h.targetEntity})," record",o?"":"s","."]}):e.jsx("div",{style:{display:"flex",flexDirection:"column"},children:n.map((r,c)=>{const j=m[r];return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 4px",borderBottom:c<n.length-1?`1px solid ${a.colorNeutralStroke3}`:"none"},children:[e.jsx(_,{size:"small",name:j??"?",avatar:{color:"colorful"}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600},children:j??e.jsx("span",{style:{fontStyle:"italic",color:a.colorNeutralForeground3},children:"(name not resolved)"})}),e.jsxs("div",{style:{fontFamily:a.fontFamilyMonospace,fontSize:10,color:a.colorNeutralForeground3},children:["/",x?.entitySetName??"?","(",r,")"]})]}),e.jsx(M,{content:"Remove target",relationship:"label",children:e.jsx(Q,{size:"small",appearance:"subtle",icon:e.jsx(Z,{}),onClick:()=>H(r),"aria-label":"Remove target"})})]},r)})})}),!k&&e.jsxs("div",{style:{maxWidth:560},children:[e.jsx(B,{label:o?"Pick target":"Add target",hint:o?`Pick a single ${x?.displayName??"record"} — the PATCH sets this as the lookup value.`:`Each pick queues a separate ${T}. Currently ${n.length} target${n.length===1?"":"s"} queued.`,children:e.jsx(te,{table:x?.logicalName??h.targetEntity,selectedId:null,onPick:r=>I(r?.id??null,r?.primary),placeholder:`Search ${x?.displayName??"record"}s…`},$)}),!o&&e.jsxs(v,{style:{display:"block",marginTop:6,color:a.colorNeutralForeground3},children:[e.jsx(ne,{style:{width:12,height:12,verticalAlign:"middle"}})," picking a record adds it to the queue and resets the picker for the next pick."]})]}),k&&o&&e.jsx(C,{layout:"multiline",intent:"info",style:{maxWidth:720,marginTop:12},children:e.jsxs(E,{children:[e.jsx(ae,{children:"Single-valued nav property — one target only."}),"To change the target, remove the current one first. The PATCH replaces the previous lookup value."]})})]})}export{ce as A,ie as N,A as t};
@@ -0,0 +1,11 @@
1
+ import{aq as Dt,cE as Ft,e as Ue,bH as ze,f as lt,c6 as _t,c7 as Lt,c8 as Ht,cF as Ut,cG as zt,cH as Wt,cI as Gt,cJ as Vt,b$ as Jt,c1 as Kt,bZ as We,bQ as Qt,bT as Xt,bF as Yt,bI as Zt,bJ as es,cK as ts,cL as ss,cM as ns,cN as os,cO as rs,cP as as,cQ as is,cR as ls,cS as cs,cT as ds,an as us,ba as hs,bb as ps,cU as ms,cV as fs,cW as gs,cX as bs,cY as xs,ar as ys,I as vs,aU as $s,cZ as ct,c_ as js,c$ as ws,d0 as re,n as dt,l as w,u as Ss,b3 as ks,d1 as Es,c2 as Ts,A as t,ah as ue,cl as ut,aL as je,Y as C,d2 as ht,d3 as pt,aH as we,N as J,O as K,ad as H,b4 as ge,b5 as be,ae as W,a2 as j,al as mt,a3 as M,_ as Se,aJ as ce,d4 as ae,d5 as Ie,d6 as Ce,bl as Rs,bm as Ge,d7 as Oe,aA as Is,V as ne,d8 as Cs,d9 as Os,da as qs,db as Bs,dc as Ms,dd as Ps,W as ke,aW as As,cm as Ns,$ as Ds,a0 as Fs,de as _s,df as Ls,dg as Hs,dh as Us,a5 as zs,a6 as Ws,a7 as Gs,a8 as Vs,a9 as Js,bx as Ks,ac as Qs,k as Ee,af as Xs,b9 as Ys,di as Zs,dj as en,dk as Ve,E as Je,dl as tn,dm as sn,dn as nn,ch as xe,au as on,dp as rn,be as an,p as ye,q as Ke,t as ln,dq as cn,dr as dn,ds as un,dt as hn,ck as pn,du as Qe,J as mn,K as fn,U as gn,S as bn}from"./index-XmEQbXiX.js";const ve=e=>e.status>=400;function xn(e,s){const o=new Map,n=[];for(const p of s)p.contentId&&!o.has(p.contentId)?o.set(p.contentId,p):n.push(p);o.size===0&&n.length===e.items.length&&(e.items.forEach((p,x)=>o.set(p.contentId,n[x])),n.length=0);const a=s.some(ve),i=e.transaction&&a,r=e.items.map(p=>{const x=o.get(p.contentId);return x?{itemId:p.item.id,contentId:p.contentId,outcome:i&&!ve(x)?"rolled-back":"done",status:x.status,statusText:x.statusText,headers:x.headers,body:x.body}:{itemId:p.item.id,contentId:p.contentId,outcome:i?"rolled-back":"not-run"}}),b=n.find(ve);return{items:r,segment:{transaction:e.transaction,contentIds:e.items.map(p=>p.contentId),ms:0,ok:!a&&r.every(p=>p.outcome==="done"),changesetError:b}}}function yn(e){const s=e.segments.some(x=>!x.skipped&&(!x.error||x.requestFailed)),o=e.items.length;let n=0,a=0,i=0,r=0,b=0;for(const x of e.items)x.outcome==="done"?(x.status??0)>=400?a++:n++:x.outcome==="rolled-back"?i++:x.outcome==="not-run"?r++:b++;const p=[`${o} request${o===1?"":"s"}`];return a&&p.push(`${a} failed`),i&&p.push(`${i} rolled back`),r&&p.push(`${r} not run`),b&&p.push(`${b} no result`),o>0&&n===o&&p.push("all succeeded"),{status:s?200:0,summary:p.join(" · "),succeeded:n}}const vn=/additional headers were rejected|header consent/i,ft=/invalid content id correlation|missing operation results/i,$n=/invalid content id correlation/i;function jn(e){return e.replace(/^\s*Error invoking remote method '[^']*':\s*/i,"").replace(/^(?:\w*Error:\s*)+/,"").trim()}function wn(e,s){const o=jn(e);return vn.test(o)?`Power Platform ToolBox didn’t send this batch because its request headers weren’t approved, so nothing reached Dataverse. Send again and allow the headers when ToolBox asks, or remove them. Host message: ${o}`:!s.transaction&&s.continueOnError&&$n.test(o)?`A request in this batch failed, and Power Platform ToolBox couldn’t read the continue-on-error response because more requests followed the failed one (a known ToolBox batch-parser bug). Dataverse still ran every request: the ones that succeeded were applied. To see each result, put requests that might fail last in the batch, or send them on their own. Host message: ${o}`:!s.transaction&&!s.continueOnError&&ft.test(o)?`A request failed and Dataverse stopped the batch there. Requests before it were applied; the rest didn’t run. This version of Power Platform ToolBox can’t return partial results without continue-on-error — turn on Continue on error to see each request’s result. Host message: ${o}`:o}async function Sn(e,s){const o=performance.now(),n=[],a=[];let i=!1;for(const r of e){const b=r.items.map(h=>h.contentId);if(i){a.push({transaction:r.transaction,contentIds:b,ms:0,ok:!1,skipped:!0});for(const h of r.items)n.push({itemId:h.item.id,contentId:h.contentId,outcome:"not-run"});continue}const p=r.items.map(gt),x=!r.transaction&&s.continueOnError?{Prefer:"odata.continue-on-error"}:void 0,m=performance.now();try{const h=r.transaction?await Ue.executeTransaction(p,x):await Ue.executeBatch(p,x),c=xn(r,h);c.segment.ms=Math.round(performance.now()-m),a.push(c.segment),n.push(...c.items),!c.segment.ok&&!s.continueOnError&&(i=!0)}catch(h){const c=h instanceof Error?h.message:String(h);x||p.some(g=>g.headers&&Object.keys(g.headers).length),a.push({transaction:r.transaction,contentIds:b,ms:Math.round(performance.now()-m),ok:!1,requestFailed:ft.test(c),error:wn(c,{transaction:r.transaction,continueOnError:s.continueOnError})});for(const g of r.items)n.push({itemId:g.item.id,contentId:g.contentId,outcome:r.transaction?"rolled-back":"unknown"});s.continueOnError||(i=!0)}}return{ms:Math.round(performance.now()-o),ok:a.every(r=>r.ok),items:n,segments:a}}function gt(e){const s=e.wire,o={method:s.method,url:s.path,contentId:e.contentId};return Object.keys(s.headers).length>0&&(o.headers={...s.headers}),s.body!==void 0&&(o.body=s.body),o}function kn(){return Dt()?Ft()?null:"Sending a $batch requires Power Platform ToolBox 1.2.7 or later.":"Run Dataverse Request Studio inside Power Platform ToolBox to send a batch."}const En=new Set(["retrieve-multiple","retrieve-single","predefined-query","create","update","upsert","delete","merge","associate","disassociate","exec-action","exec-function","exec-workflow"]),Tn=new Set(["authorization","accept","content-type","content-length","odata-version","odata-maxversion"]);function Xe(e,s){return{id:`__batch__${e}`,name:e,value:s,enabled:!0,builtin:!0}}function L(e){let s=(e.headers??[]).map(a=>a.name==="MSCRM.SuppressDuplicateDetection"&&e.duplicateDetection!==void 0?{...a,enabled:e.duplicateDetection,value:"false"}:a);const o=e.concurrency?xs(e.concurrency):null;if(o&&s.push(Xe(o.name,o.value)),e.suppressDuplicateDetection&&s.push(Xe("MSCRM.SuppressDuplicateDetection","true")),e.bypass){const a=e.bypassCustomPlugins&&e.bypass.businessLogic==="none"?{...e.bypass,businessLogic:"sync",useLegacyHeader:!0}:e.bypass;s=ys(s,a)}const n=vs(s,e.prefer?$s(e.prefer):null);return Object.fromEntries(Object.entries(n).filter(([a])=>!Tn.has(a.toLowerCase())))}function $e(e,s,o,n,a,i){return ct("custom",{label:e,source:s,method:o,url:ws(n),body:i&&Object.keys(i).length>0?js(i):i?"{}":"",headers:Object.entries(a).map(([r,b])=>({name:r,value:b,enabled:!0}))})}function Rn(e){const{name:s}=e,o=(n,a,i,r)=>a?{ok:!0,items:[$e(s,s,n,a,i,r)]}:{ok:!1,reason:"its table isn’t available on this connection"};try{switch(e.modeId){case"retrieve-multiple":{const n=gs(e.state);return o("GET",bs(n).relativeUrl,L(n))}case"retrieve-single":{const n=ms(e.state);return o("GET",fs(n).relativeUrl,L(n))}case"predefined-query":{const n=hs(e.state);return o("GET",ps(n).relativeUrl,L(n))}case"create":{const n=cs(e.state);return o("POST",ds(n).relativeUrl,L(n),us(n))}case"update":{const n=as(e.state);return o(n.method,is(n).relativeUrl,L(n),ls(n))}case"upsert":{const n=ns(e.state);return o("PATCH",os(n).relativeUrl,L(n),rs(n))}case"delete":{const n=ts(e.state);return o("DELETE",ss(n).relativeUrl,L(n))}case"merge":{const n=Yt(e.state);return o("POST",Zt(n).relativeUrl,L(n),es(n))}case"associate":{const n=Qt(e.state),a=L(n),i=Xt(n);return i.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:i.map(r=>$e(`${s} → ${r.targetId}`,s,r.method,r.relativeUrl,We(r.method,a),r.body))}}case"disassociate":{const n=Jt(e.state),a=L(n),i=Kt(n);return i.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:i.map(r=>$e(r.targetId?`${s} × ${r.targetId}`:s,s,r.method,r.relativeUrl,We(r.method,a),r.body))}}case"exec-action":{const n=Wt(e.state);return o("POST",Gt(n).relativeUrl,L(n),Vt(n))}case"exec-function":{const n=Ut(e.state);return o("GET",zt(n).relativeUrl,L(n))}case"exec-workflow":{const n=_t(e.state);return o("POST",Lt(n).relativeUrl,L(n),Ht(n))}default:return{ok:!1,reason:"file, image and attachment requests can’t be sent in a batch"}}}catch(n){return{ok:!1,reason:n instanceof Error?n.message:String(n)}}}function In(e){if(e&&typeof e=="object"&&"table"in e){const s=e.table;if(typeof s=="string")return s}return""}async function Cn(e){const s=In(e.state);s&&await ze.getTable(s).catch(()=>{});const o=e.state?.navProperty;if(s&&typeof o=="string"&&o){const n=lt(s)?.navigationProperties.find(a=>a.name===o)?.targetEntity;n&&await ze.getTable(n).catch(()=>{})}return Rn(e)}const U=`\r
2
+ `;function On(e){return/^\$\d+/.test(e)?e:`${re}/${e}`}function qn(e,s){const o=s.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===o)}function Te({contentId:e,wire:s}){const o=["Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${e}`,"",`${s.method} ${On(s.path)} HTTP/1.1`];for(const[n,a]of Object.entries(s.headers))o.push(`${n}: ${a}`);return s.body!==void 0&&!qn(s.headers,"Content-Type")&&o.push("Content-Type: application/json; type=entry"),o.push("",s.body??""),o.join(U)}let Ye=0;function de(e){Ye+=1;const s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(16)}-${Ye.toString(16)}-${Math.random().toString(16).slice(2)}`;return`${e}_${s}`}function bt(e,s={}){const o=s.batch??de("batch");let n=0,a="";for(const i of e)if(i.parts.length!==0)if(i.atomic){const r=s.changeset?.(n)??de("changeset");n+=1,a+=`--${o}${U}Content-Type: multipart/mixed; boundary=${r}${U}${U}`;for(const b of i.parts)a+=`--${r}${U}${Te(b)}${U}`;a+=`--${r}--${U}`}else for(const r of i.parts)a+=`--${o}${U}${Te(r)}${U}`;return a+=`--${o}--${U}`,{boundary:o,contentType:`multipart/mixed; boundary=${o}`,body:a}}const xt=/boundary=(?:"([^"]+)"|([^;\s]+))/i;function Bn(e,s){const o=xt.exec(e);if(o)return o[1]||o[2];const n=/^\s*--([^\r\n]+)/.exec(s);return n?n[1].trim():null}function Ze(e){const s={};for(const o of e.split(/\r?\n/)){const n=o.indexOf(":");if(n<=0)continue;const a=o.slice(0,n).trim().toLowerCase(),i=o.slice(n+1).trim();s[a]=s[a]?`${s[a]}, ${i}`:i}return s}function Mn(e,s){const o=`--${s}`,n=[];let a=e.indexOf(o);if(a<0)throw new Error(`Response boundary "${s}" not found.`);for(;a>=0;){if(a+=o.length,e.startsWith("--",a))return n;const i=e.indexOf(o,a);if(i<0)throw new Error("Response is missing its closing boundary.");n.push(e.slice(a,i).replace(/^\r?\n/,"").replace(/\r?\n$/,"")),a=i}return n}function et(e){const s=/\r?\n\r?\n/.exec(e);return s?[e.slice(0,s.index),e.slice(s.index+s[0].length)]:[e,""]}function Pn(e,s=""){const o=Bn(s,e);if(!o)throw new Error("No multipart boundary in the Content-Type or the body.");let n=0;const a=(i,r,b)=>Mn(i,r).flatMap(p=>{const[x,m]=et(p),h=Ze(x),c=xt.exec(h["content-type"]??"");if(c){const V=n++;return a(m,c[1]||c[2],V)}const g=m.search(/HTTP\/1\.[01]\s+\d{3}/i);if(g<0)throw new Error("A response part has no HTTP status line.");const[k,O]=et(m.slice(g)),[D,...A]=k.split(/\r?\n/),G=/^HTTP\/1\.[01]\s+(\d{3})(?:\s+(.*))?$/i.exec(D.trim());if(!G)throw new Error(`Malformed status line: ${D}`);const I=O.trim();let P;if(I)try{P=JSON.parse(I)}catch{P=I}const q={status:Number(G[1]),statusText:G[2]?.trim()||void 0,headers:Ze(A.join(`
3
+ `))};return h["content-id"]&&(q.contentId=h["content-id"]),P!==void 0&&(q.body=P),b!==void 0&&(q.changeset=b),[q]});return a(e,o)}const yt={http:"HTTP ($batch)",fetch:"fetch (JavaScript)",pptb:"PPTB dataverseAPI"};function vt(e){const s=[];let o=null;for(const n of e)n.wire&&(n.group!==o&&s.push({atomic:n.group.atomic,parts:[]}),s[s.length-1].parts.push({contentId:n.contentId,wire:n.wire}),o=n.group);return s}function tt(e,s){return["OData-MaxVersion: 4.0","OData-Version: 4.0","If-None-Match: null","Accept: application/json",`Content-Type: ${e}`,...s?["Prefer: odata.continue-on-error"]:[]]}const An=e=>e.replace(/\r\n/g,`
4
+ `);function Nn(e,s){const o=s.orgUrl||"[Organization URI]",n=bt(vt(s.items),s.boundaries);switch(e){case"http":return An([`POST ${o}${re}/$batch HTTP/1.1`,...tt(n.contentType,s.continueOnError),"",n.body].join(U));case"fetch":{const a=n.body.split(U);a[a.length-1]===""&&a.pop();const i=tt(n.contentType,s.continueOnError).filter(r=>!r.startsWith("If-None-Match")).map(r=>{const b=r.indexOf(":");return` ${JSON.stringify(r.slice(0,b))}: ${JSON.stringify(r.slice(b+1).trim())},`});return["// Dataverse $batch — every line of the body must end in CRLF.","const body = [",...a.map(r=>` ${JSON.stringify(r)},`),"].join('\\r\\n') + '\\r\\n';","",`const res = await fetch(${JSON.stringify(`${o}${re}/$batch`)}, {`," method: 'POST',"," headers: {"," Authorization: `Bearer ${accessToken}`,",...i," },"," body,","});","","// The response is multipart/mixed too: one part per request, change sets nested.","console.log(res.status, res.headers.get('Content-Type'));","console.log(await res.text());"].join(`
5
+ `)}case"pptb":{if(s.plan.length===0)return"// Add a request to see the host calls.";const a=["// What Dataverse Request Studio sends through Power Platform ToolBox (1.2.7+).","// The host writes the multipart body; each change set is its own call."];return s.plan.length>1&&a.push(`// ${s.plan.length} calls, in order.${s.continueOnError?"":" A failed call stops the rest."}`),s.plan.forEach((i,r)=>{const b=i.items.filter(m=>m.wire).map(gt),p=i.transaction?"executeTransaction":"executeBatch",x=!i.transaction&&s.continueOnError?", undefined, { Prefer: 'odata.continue-on-error' }":"";a.push("",`const results${r+1} = await dataverseAPI.${p}(${JSON.stringify(b,null,2)}${x});`)}),a.push("","// Each result: { contentId, status, statusText, headers, body }"),a.join(`
6
+ `).replace(/\\r\\n/g,"\\n")}}}const Dn=/^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i,B=e=>JSON.stringify(e),Y=e=>`new Guid(${B(e.replace(/[{}]/g,""))})`;function Z(e,s){return s.logicalOf(e)??e.replace(/s$/,"")}function Fn(e){const s=/^([A-Za-z_][\w]*)\(([^)]+)\)$/.exec(e.trim());return s?{set:s[1],id:s[2]}:null}function _n(e,s,o,n,a){if(o===null)return"null";const i=n.attrType(e,s);switch(i){case"Picklist":case"State":case"Status":return`new OptionSetValue(${Number(o)})`;case"MultiSelectPicklist":return`new OptionSetValueCollection { ${String(o).split(",").filter(Boolean).map(r=>`new OptionSetValue(${Number(r)})`).join(", ")} }`;case"Money":return`new Money(${Number(o)}m)`;case"Decimal":return`${Number(o)}m`;case"BigInt":return`${Number(o)}L`;case"DateTime":return`DateTime.Parse(${B(String(o))})`;case"Uniqueidentifier":return Y(String(o))}return typeof o=="string"?B(o):typeof o=="boolean"?String(o):typeof o=="number"?(i||a.push(`${s}: confirm the type (int / OptionSetValue / Money / decimal)`),String(o)):(a.push(`${s}: nested value not converted`),null)}function Ln(e,s,o,n){const a=[];for(const[i,r]of Object.entries(s)){if(i.endsWith("@odata.bind")){let p=i.slice(0,-11);if(!o.attrType(e,p)&&p.includes("_")){const m=p.slice(0,p.lastIndexOf("_"));o.attrType(e,m)&&(p=m)}const x=typeof r=="string"?Fn(r.replace(/^.*\/api\/data\/v[\d.]+\//,"")):null;typeof r=="string"&&/^\$\d+$/.test(r)?n.push(`${p}: ${r} referenced an earlier request — ExecuteMultiple has no Content-ID references; set the id returned by that request`):x?a.push(`[${B(p)}] = new EntityReference(${B(Z(x.set,o))}, ${Y(x.id)}),`):n.push(`${p}: couldn't convert the @odata.bind value`);continue}if(i.includes("@"))continue;const b=_n(e,i,r,o,n);b!==null&&a.push(`[${B(i)}] = ${b},`)}return a}function st(e){if(!e)return{};try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}}const Hn=(e,s)=>e.map(o=>" ".repeat(s)+o);function nt(e){return e?`new ColumnSet(${e.split(",").map(s=>B(s.trim().replace(/^_(.+)_value$/,"$1"))).join(", ")})`:"new ColumnSet(true)"}function Un(e,s){const o=e.wire;if(!o)return[`// $${e.contentId}: has errors — fix it in the Builder.`];const n=[],a=[],i=e.item,r=`// $${e.contentId} ${o.method} ${o.path}`,b=m=>(a.push(r,...n.map(h=>`// TODO ${h}`),...m),a),p=Dn.test(i.recordId.trim());if(i.op==="create"||i.op==="update"){const m=Z(i.entitySet,s);i.op==="update"&&!p&&n.push(`record id ${i.recordId} isn't a GUID — use new Entity(logicalName, keyAttributes) for an alternate key`);const h=i.op==="update"&&p?`new Entity(${B(m)}, ${Y(i.recordId.trim())})`:`new Entity(${B(m)})`,c=Ln(m,st(o.body),s,n);return b([`requests.Add(new ${i.op==="create"?"CreateRequest":"UpdateRequest"}`,"{",` Target = ${h}`," {",...Hn(c,8)," },","});"])}if(i.op==="delete"){const m=Z(i.entitySet,s);return p||n.push(`record id ${i.recordId} isn't a GUID`),b([`requests.Add(new DeleteRequest { Target = new EntityReference(${B(m)}, ${Y(i.recordId.trim())}) });`])}if(i.op==="retrieve"){const m=Z(i.entitySet,s),h=new URLSearchParams(i.query.trim().replace(/^\?/,"")),c=h.get("$select");if(i.recordId.trim())return b(["requests.Add(new RetrieveRequest","{",` Target = new EntityReference(${B(m)}, ${Y(i.recordId.trim())}),`,` ColumnSet = ${nt(c)},`,"});"]);const g=h.get("$top");for(const k of["$filter","$orderby","$expand","$apply","fetchXml"])h.get(k)&&n.push(`translate ${k} into the QueryExpression (or use FetchExpression)`);return b(["requests.Add(new RetrieveMultipleRequest","{",` Query = new QueryExpression(${B(m)})`," {",` ColumnSet = ${nt(c)},`,...g?[` TopCount = ${Number(g)},`]:[]," },","});"])}if(i.op==="associate"){const m=Z(i.entitySet,s),h=Z(i.targetSet,s);return n.push("Relationship takes the relationship schema name — usually the navigation property name"),b(["requests.Add(new AssociateRequest","{",` Target = new EntityReference(${B(m)}, ${Y(i.recordId.trim())}),`,` Relationship = new Relationship(${B(i.navProperty.trim())}),`,` RelatedEntities = new EntityReferenceCollection { new EntityReference(${B(h)}, ${Y(i.targetId.trim())}) },`,"});"])}const x=/^(?:Microsoft\.Dynamics\.CRM\.)?([A-Za-z_][\w]*)$/.exec(o.path);if(o.method==="POST"&&x&&!s.logicalOf(x[1])){const m=Object.entries(st(o.body)).filter(([h])=>!h.includes("@"));return b([`requests.Add(new OrganizationRequest(${B(x[1])})`,"{"," Parameters ="," {",...m.map(([h,c])=>typeof c=="object"&&c!==null?` // TODO ${h}: convert ${JSON.stringify(c)}`:` [${B(h)}] = ${typeof c=="string"?B(c):String(c)},`)," },","});"])}return[r,"// No SDK request generated for this Web API call — add the matching OrganizationRequest."]}function zn(e,s,o){return["// ExecuteMultiple (SDK for .NET). Microsoft.Xrm.Sdk + Microsoft.Xrm.Sdk.Messages + Microsoft.Xrm.Sdk.Query.","// Max 1000 requests per call; ExecuteMultiple is not transactional — use ExecuteTransactionRequest for all-or-nothing.","var requests = new OrganizationRequestCollection();","",...e.flatMap(a=>[...Un(a,o),""]),"var executeMultiple = new ExecuteMultipleRequest","{"," Settings = new ExecuteMultipleSettings"," {",` ContinueOnError = ${s.continueOnError},`,` ReturnResponses = ${s.returnResponses},`," },"," Requests = requests,","};","","var response = (ExecuteMultipleResponse)service.Execute(executeMultiple);","","// With ReturnResponses = false only faults come back. RequestIndex is 0-based.","foreach (var item in response.Responses)","{"," if (item.Fault != null)",' Console.WriteLine($"Request {item.RequestIndex} failed: {item.Fault.Message}");'," else if (item.Response != null)",' Console.WriteLine($"Request {item.RequestIndex}: {item.Response.ResponseName}");',"}",'Console.WriteLine($"IsFaulted: {response.IsFaulted}");'].join(`
7
+ `)}const ot=[{id:"create",label:"Create (POST)"},{id:"update",label:"Update (PATCH)"},{id:"delete",label:"Delete (DELETE)"},{id:"retrieve",label:"Retrieve (GET)"},{id:"associate",label:"Associate (POST $ref)"},{id:"custom",label:"Custom request"}],Wn=["GET","POST","PATCH","PUT","DELETE"],Gn=[{name:"Prefer",value:"return=representation"},{name:"If-Match",value:"*"},{name:"MSCRM.SuppressDuplicateDetection",value:"false"}],z={fontFamily:j.fontFamilyMonospace,fontSize:12};function Vn({item:e,contentId:s,group:o,groups:n,wire:a,issues:i,onChange:r,onRemove:b,onMove:p,onMoveToGroup:x}){const{entities:m,allEntities:h}=dt(),c=w.useMemo(()=>h.find(f=>f.entitySetName===e.entitySet.trim())?.logicalName??null,[h,e.entitySet]),{table:g}=Ss(e.op==="associate"?c:null),k=ks(),O=w.useMemo(()=>Es(g?.navigationProperties??[],k).filter(Ts),[g,k]),D=`drs-batch-sets-${e.id}`,A=`drs-batch-navs-${e.id}`,G=e.op!=="custom",I=e.op==="update"||e.op==="delete"||e.op==="associate",P=e.op==="create"||e.op==="update"||e.op==="custom",q=n.indexOf(o),V=(f,$)=>r({headers:e.headers.map((F,N)=>N===f?{...F,...$}:F)});return t.jsxs("div",{style:{maxWidth:860},children:[t.jsxs(ue,{icon:ut,title:`Request $${s}`,sub:o.atomic?`In change set ${q+1} — rolls back with the rest of the change set if any request fails.`:`In group ${q+1} — independent; runs on its own.`,group:"batch",children:[t.jsx(je,{content:"Move up",relationship:"label",children:t.jsx(C,{icon:t.jsx(ht,{}),appearance:"subtle",onClick:()=>p(-1)})}),t.jsx(je,{content:"Move down",relationship:"label",children:t.jsx(C,{icon:t.jsx(pt,{}),appearance:"subtle",onClick:()=>p(1)})}),t.jsx(C,{icon:t.jsx(we,{}),appearance:"subtle",onClick:b,children:"Remove"})]}),i.length>0&&t.jsx(J,{intent:i.some(f=>f.severity==="error")?"error":"warning",layout:"multiline",style:{marginBottom:12},children:t.jsx(K,{children:i.map((f,$)=>t.jsx("div",{children:f.message},$))})}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:12},children:[t.jsx(H,{label:"Operation",children:t.jsx(ge,{value:ot.find(f=>f.id===e.op)?.label??"",selectedOptions:[e.op],onOptionSelect:(f,$)=>{const F=$.optionValue,N={op:F};(F==="create"||F==="update")&&!e.body.trim()&&(N.body=`{
8
+
9
+ }`),r(N)},children:ot.map(f=>t.jsx(be,{value:f.id,children:f.label},f.id))})}),n.length>1&&t.jsx(H,{label:"Group",children:t.jsx(ge,{value:`${o.atomic?"Change set":"Independent"} ${q+1}`,selectedOptions:[o.id],onOptionSelect:(f,$)=>$.optionValue&&x($.optionValue),children:n.map((f,$)=>t.jsx(be,{value:f.id,children:`${f.atomic?"Change set":"Independent"} ${$+1}`},f.id))})}),t.jsx(H,{label:"Label (optional)",children:t.jsx(W,{value:e.label,onChange:(f,$)=>r({label:$.value})})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:12,marginTop:12},children:[e.op==="custom"&&t.jsxs(t.Fragment,{children:[t.jsx(H,{label:"Method",children:t.jsx(ge,{value:e.method,selectedOptions:[e.method],onOptionSelect:(f,$)=>r({method:$.optionValue}),children:Wn.map(f=>t.jsx(be,{value:f,children:f},f))})}),t.jsx(H,{label:"URL (relative to /api/data/v9.2/)",hint:"e.g. WhoAmI, accounts?$top=5, $1/primarycontactid/$ref",style:{gridColumn:"span 2"},children:t.jsx(W,{value:e.url,onChange:(f,$)=>r({url:$.value}),input:{style:z}})})]}),G&&t.jsx(H,{label:e.op==="associate"?"Source table (entity set)":"Table (entity set)",children:t.jsx(W,{value:e.entitySet,onChange:(f,$)=>r({entitySet:$.value}),placeholder:"accounts",input:{list:D,style:z}})}),(I||e.op==="retrieve")&&t.jsx(H,{label:e.op==="retrieve"?"Record id (optional)":"Record id",hint:e.op==="retrieve"?void 0:"GUID, alternate key, or $n for a record created earlier in this change set",children:t.jsx(W,{value:e.recordId,onChange:(f,$)=>r({recordId:$.value}),placeholder:"00000000-0000-0000-0000-000000000000",input:{style:z}})}),e.op==="retrieve"&&t.jsx(H,{label:"Query options",hint:"Without the leading ?",children:t.jsx(W,{value:e.query,onChange:(f,$)=>r({query:$.value}),placeholder:"$select=name&$top=10",input:{style:z}})}),e.op==="associate"&&t.jsxs(t.Fragment,{children:[t.jsx(H,{label:"Navigation property (collection-valued)",children:t.jsx(W,{value:e.navProperty,onChange:(f,$)=>r({navProperty:$.value}),placeholder:"contact_customer_accounts",input:{list:A,style:z}})}),t.jsx(H,{label:"Target table (entity set)",children:t.jsx(W,{value:e.targetSet,onChange:(f,$)=>r({targetSet:$.value}),placeholder:"contacts",input:{list:D,style:z}})}),t.jsx(H,{label:"Target record id",hint:"GUID or $n",children:t.jsx(W,{value:e.targetId,onChange:(f,$)=>r({targetId:$.value}),input:{style:z}})})]})]}),t.jsx("datalist",{id:D,children:m.map(f=>t.jsx("option",{value:f.entitySetName,children:f.displayName},f.logicalName))}),t.jsx("datalist",{id:A,children:O.map(f=>t.jsx("option",{value:f.name,children:f.targetEntity},f.name))}),P&&t.jsx(H,{label:"Body (JSON)",hint:o.atomic?'Reference a record created earlier in this change set with "$n", e.g. "primarycontactid@odata.bind": "$1".':void 0,style:{marginTop:12},children:t.jsx(mt,{value:e.body,onChange:(f,$)=>r({body:$.value}),resize:"vertical",rows:8,textarea:{style:z,spellCheck:!1}})}),t.jsxs("div",{style:{marginTop:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6,flexWrap:"wrap"},children:[t.jsx("strong",{style:{fontSize:13},children:"Request headers"}),t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"Sent inside this part. Power Platform ToolBox asks you to approve them the first time."})]}),e.headers.map((f,$)=>t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:6,alignItems:"center"},children:[t.jsx(Se,{checked:f.enabled,onChange:(F,N)=>V($,{enabled:N.checked}),"aria-label":`Send ${f.name||"header"}`}),t.jsx(W,{value:f.name,onChange:(F,N)=>V($,{name:N.value}),placeholder:"Name","aria-label":"Header name",input:{style:z},style:{flex:"1 1 0",minWidth:0}}),t.jsx(W,{value:f.value,onChange:(F,N)=>V($,{value:N.value}),placeholder:"Value","aria-label":"Header value",input:{style:z},style:{flex:"2 1 0",minWidth:0}}),t.jsx(C,{icon:t.jsx(we,{}),appearance:"subtle","aria-label":"Remove header",onClick:()=>r({headers:e.headers.filter((F,N)=>N!==$)})})]},$)),t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[t.jsx(C,{size:"small",icon:t.jsx(ce,{}),onClick:()=>r({headers:[...e.headers,{name:"",value:"",enabled:!0}]}),children:"Header"}),Gn.filter(f=>!e.headers.some($=>$.name.toLowerCase()===f.name.toLowerCase())).map(f=>t.jsxs(C,{size:"small",appearance:"subtle",onClick:()=>r({headers:[...e.headers,{...f,enabled:!0}]}),children:["+ ",f.name,": ",f.value]},f.name))]})]}),a&&t.jsxs("div",{style:{marginTop:16},children:[t.jsx("strong",{style:{fontSize:13},children:"Part preview"}),t.jsx("pre",{style:{...z,background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:4,padding:10,marginTop:6,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:Te({contentId:s,wire:a}).replace(/\r\n/g,`
10
+ `)})]}),e.source&&t.jsxs(M,{style:{color:j.colorNeutralForeground3},children:["From: ",e.source]})]})}const Jn=[{id:"create",label:"Create"},{id:"update",label:"Update"},{id:"delete",label:"Delete"},{id:"retrieve",label:"Retrieve"},{id:"associate",label:"Associate"},{id:"custom",label:"Custom request"}];function Kn({onAdd:e,label:s="Add request",disabledGet:o}){return t.jsxs(Os,{children:[t.jsx(qs,{disableButtonEnhancement:!0,children:t.jsx(C,{icon:t.jsx(ce,{}),children:s})}),t.jsx(Bs,{children:t.jsx(Ms,{children:Jn.filter(n=>!(o&&n.id==="retrieve")).map(n=>t.jsx(Ps,{onClick:()=>e(n.id),children:n.label},n.id))})})]})}function Qn({groups:e,continueOnError:s,setContinueOnError:o,plan:n,unavailable:a,needsConsent:i,orgUrl:r,onAddGroup:b,onOpenSaved:p,onAddLast:x,lastLabel:m,onSelect:h,notice:c,variant:g="batch",returnResponses:k=!0,setReturnResponses:O}){const D=e.reduce((I,P)=>I+P.items.length,0),A=g==="execute-multiple";let G=0;return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ue,{icon:Is,title:A?"ExecuteMultiple":"$batch request",sub:A?"Up to 1,000 independent requests in one call, with the SDK’s ContinueOnError and ReturnResponses settings.":"Up to 1,000 requests in one POST to /$batch. Requests in a change set succeed or roll back together.",group:"batch"}),A&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsx(ne,{children:"Sent as a Web API $batch"}),"ExecuteMultiple is an SDK for .NET (Organization service) message; the Web API has no ExecuteMultiple action. Its Web API equivalent is a ",t.jsx("code",{children:"$batch"})," of independent requests, which is what DRS sends. ContinueOnError maps to"," ",t.jsx("code",{children:"Prefer: odata.continue-on-error"}),"; ReturnResponses = false shows only the faults, as ExecuteMultipleResponse does. The Code tab has the ExecuteMultipleRequest (C#). For all-or-nothing, use the $batch Request mode’s change sets (ExecuteTransaction)."]})}),a&&t.jsx(J,{intent:"warning",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsx(ne,{children:"Can’t send from here"}),a," You can still compose the batch and copy it from the Code tab."]})}),c&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsx(K,{children:c})}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:16},children:[A?e[0]&&t.jsx(C,{icon:t.jsx(ce,{}),onClick:()=>h(`group:${e[0].id}`),children:"Add request"}):t.jsxs(t.Fragment,{children:[t.jsx(C,{icon:t.jsx(Ie,{}),onClick:()=>b(!0),children:"Add change set"}),t.jsx(C,{icon:t.jsx(Ce,{}),onClick:()=>b(!1),children:"Add independent group"})]}),t.jsx(C,{icon:t.jsx(ce,{}),onClick:p,children:"Add from Saved…"}),t.jsx(C,{icon:t.jsx(Cs,{}),onClick:x,disabled:!m,children:m?`Add last request (${m})`:"Add last request"})]}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,background:j.colorNeutralBackground1,marginBottom:16},children:[t.jsx(Se,{checked:s,onChange:(I,P)=>o(P.checked),"aria-label":"Continue on error"}),t.jsxs("div",{children:[t.jsx("strong",{children:A?"ContinueOnError":"Continue on error"})," ",t.jsx("code",{style:{fontSize:12},children:"Prefer: odata.continue-on-error"}),t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:A?"False: processing stops at the first fault; the rest don’t run. True: every request runs and each fault is reported. Requests that already ran aren’t undone either way.":"Off: Dataverse stops at the first failed request or change set. On: it runs the rest and returns every result. A change set is all-or-nothing either way."})]})]}),A&&O&&t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,background:j.colorNeutralBackground1,marginBottom:16},children:[t.jsx(Se,{checked:k,onChange:(I,P)=>O(P.checked),"aria-label":"ReturnResponses"}),t.jsxs("div",{children:[t.jsx("strong",{children:"ReturnResponses"}),t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"True: a response for every request. False: only the faults, which is what you want for bulk loads. A $batch always returns every response; DRS filters the Results the same way and sets it in the C#."})]})]}),i&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsx(ne,{children:"Headers need your approval in Power Platform ToolBox"}),"This batch sends request headers (per-request headers or continue-on-error). If you haven’t approved additional request headers for this tool yet, ToolBox asks first; if you reject, nothing is sent."]})}),n.length>1&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsxs(ne,{children:["Sent as ",n.length," host calls"]}),"Power Platform ToolBox sends one change set or one run of independent requests per call, so this batch goes out as ",n.length," $batch requests in order (",n.map(I=>I.transaction?"change set":"independent").join(" → "),"). Each change set is still atomic.",s?"":" A failed call stops the ones after it."," The Code tab shows the single-envelope form for other clients."]})}),t.jsxs("div",{style:{fontSize:13,marginBottom:8},children:[t.jsxs("strong",{children:[D," request",D===1?"":"s"]})," ","in ",e.length," group",e.length===1?"":"s"]}),e.map((I,P)=>t.jsxs("div",{style:{border:`1px solid ${j.colorNeutralStroke2}`,borderLeft:`3px solid ${I.atomic?"var(--color-request-batch)":j.colorNeutralStroke1}`,borderRadius:6,padding:"8px 12px",marginBottom:8,background:j.colorNeutralBackground1},children:[t.jsx(C,{appearance:"transparent",onClick:()=>h(`group:${I.id}`),style:{padding:0},children:t.jsx("strong",{children:A?"Requests":I.atomic?`Change set ${P+1}`:`Independent group ${P+1}`})}),I.items.length===0&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"Empty — skipped when sent."}),I.items.map(q=>{G+=1;const V=ae(q,r);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>h(`item:${q.id}`),onKeyDown:f=>(f.key==="Enter"||f.key===" ")&&h(`item:${q.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"3px 0",cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:j.colorNeutralForeground3},children:["$",G]}),t.jsx(Oe,{method:V.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:V.path||"—"}),q.label&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:q.label})]},q.id)})]},I.id))]})}function Xn({group:e,index:s,count:o,contentIdOf:n,orgUrl:a,onSetAtomic:i,onAdd:r,onRemoveGroup:b,onMoveGroup:p,onSelect:x,variant:m="batch"}){const h=e.items.some(g=>ae(g,a).method==="GET"),c=m==="execute-multiple";return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ue,{icon:e.atomic?Ie:Ce,title:c?"Requests":e.atomic?`Change set ${s+1}`:`Independent group ${s+1}`,sub:c?"ExecuteMultiple runs each request on its own, in order. It isn’t transactional.":e.atomic?"Atomic: if any request fails, Dataverse rolls back the whole change set. GET isn’t allowed here.":"Each request runs on its own; a failure doesn’t undo the others.",group:"batch",children:!c&&t.jsxs(t.Fragment,{children:[t.jsx(C,{icon:t.jsx(ht,{}),appearance:"subtle","aria-label":"Move group up",disabled:s===0,onClick:()=>p(-1)}),t.jsx(C,{icon:t.jsx(pt,{}),appearance:"subtle","aria-label":"Move group down",disabled:s===o-1,onClick:()=>p(1)}),t.jsx(C,{icon:t.jsx(we,{}),appearance:"subtle",onClick:b,children:"Remove group"})]})}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[!c&&t.jsxs(Rs,{ariaLabel:"Group kind",children:[t.jsx(Ge,{checked:e.atomic,onClick:()=>i(!0),children:"Change set (atomic)"}),t.jsx(Ge,{checked:!e.atomic,onClick:()=>i(!1),children:"Independent"})]}),t.jsx(Kn,{onAdd:r,disabledGet:e.atomic})]}),e.atomic&&h&&t.jsx(J,{intent:"error",style:{marginBottom:12},children:t.jsx(K,{children:"This change set holds a GET request. Move it to an independent group."})}),e.items.length===0&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"No requests yet."}),e.items.map(g=>{const k=ae(g,a);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>x(`item:${g.id}`),onKeyDown:O=>(O.key==="Enter"||O.key===" ")&&x(`item:${g.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"6px 8px",borderBottom:`1px solid ${j.colorNeutralStroke3}`,cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:j.colorNeutralForeground3},children:["$",n(g.id)]}),t.jsx(Oe,{method:k.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.path||"—"}),g.label&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:g.label})]},g.id)})]})}const oe={fontFamily:j.fontFamilyMonospace,fontSize:12};function rt(e){return e.outcome!=="done"?e.outcome==="rolled-back"?"warning":"info":e.status===void 0?"info":e.status>=400?"danger":"success"}function Re(e){if(e&&typeof e=="object"&&"error"in e){const s=e.error;if(s?.message)return s.code?`${s.code}: ${s.message}`:s.message}return null}function at({r:e}){const s=Re(e.body),o=e.headers?.["odata-entityid"]??e.headers?.["OData-EntityId"],n=e.outcome==="rolled-back"?"Rolled back":e.outcome==="not-run"?"Not run":e.outcome==="unknown"?"No result":null;return t.jsxs("details",{style:{borderBottom:`1px solid ${j.colorNeutralStroke3}`,padding:"6px 4px"},children:[t.jsxs("summary",{style:{display:"flex",gap:8,alignItems:"center",cursor:"pointer",listStyle:"none"},children:[t.jsxs("code",{style:{width:40,color:j.colorNeutralForeground3},children:["$",e.contentId]}),e.method&&t.jsx(Oe,{method:e.method,size:"sm"}),t.jsxs("code",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.label?`${e.label} — `:"",e.path??""]}),n&&e.status===void 0?t.jsx(ke,{status:rt(e),code:n}):t.jsx(ke,{status:rt(e),code:e.status!==void 0&&e.status<300?e.status:`${e.status??"—"}${e.statusText&&(e.status??0)>=300?` ${e.statusText}`:""}`}),n&&e.status!==void 0&&t.jsx(M,{children:n})]}),t.jsxs("div",{style:{padding:"8px 0 4px 48px"},children:[s&&t.jsx(J,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsx(K,{children:s})}),o&&t.jsxs("div",{style:{...oe,marginBottom:6},children:["OData-EntityId: ",t.jsx("code",{children:o})]}),e.headers&&Object.keys(e.headers).length>0&&t.jsx("pre",{style:{...oe,margin:"0 0 8px",whiteSpace:"pre-wrap"},children:Object.entries(e.headers).map(([a,i])=>`${a}: ${i}`).join(`
11
+ `)}),e.body!==void 0&&t.jsx("pre",{style:{...oe,margin:0,whiteSpace:"pre-wrap",wordBreak:"break-all",background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:4,padding:8,maxHeight:360,overflow:"auto"},children:typeof e.body=="string"?e.body:JSON.stringify(e.body,null,2)}),e.body===void 0&&e.outcome==="done"&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"No response body."}),e.outcome==="rolled-back"&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"The change set failed, so Dataverse undid this request with the rest of it."}),e.outcome==="unknown"&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"The host call failed as a whole (see the message above), so there’s no result for this request."}),e.outcome==="not-run"&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"An earlier failure stopped the batch before this request ran."})]})]})}function Yn({run:e,rows:s,extraTitle:o}){const[n,a]=w.useState(""),[i,r]=w.useState(null),[b,p]=w.useState(null),x=()=>{try{r(Pn(n)),p(null)}catch(c){r(null),p(c instanceof Error?c.message:String(c))}},m=(e?.items??[]).reduce((c,g)=>(g.outcome==="done"&&g.status!==void 0&&g.status<400?c.ok+=1:g.outcome==="done"?c.failed+=1:g.outcome==="unknown"?c.noResult+=1:c.other+=1,c),{ok:0,failed:0,other:0,noResult:0}),h=c=>!!c.requestFailed&&c.contentIds.every(g=>s.find(k=>k.contentId===g)?.outcome==="unknown");if(e){const c=new Map(s.map(g=>[g.contentId,g]));for(const g of e.segments){if(!g.changesetError&&!g.requestFailed)continue;!g.contentIds.some(O=>{const D=c.get(O);return D?.outcome==="done"&&(D.status??0)>=400})&&m.other>0&&(m.failed+=1,m.other-=1)}}return t.jsxs("div",{style:{maxWidth:1e3},children:[e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",marginBottom:12,flexWrap:"wrap"},children:[t.jsx(ke,{status:e.ok?"success":"danger",code:e.ok?200:"Failed",ms:e.ms}),t.jsxs("span",{style:{fontSize:13},children:[m.ok," succeeded · ",m.failed," failed",m.other?` · ${m.other} rolled back or not run`:"",m.noResult?` · ${m.noResult} no result`:"",e.segments.length>1?` · ${e.segments.length} host calls`:""]}),o&&t.jsx(M,{children:o})]}),e.segments.map((c,g)=>c.error||c.changesetError?t.jsx(J,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsxs(K,{children:[t.jsxs(ne,{children:[h(c)?"No results for ":"",c.transaction?"Change set":"Requests"," $",c.contentIds[0],c.contentIds.length>1?`–$${c.contentIds[c.contentIds.length-1]}`:"",h(c)?"":" failed"]}),c.error??`${c.changesetError.status} ${c.changesetError.statusText??""} — ${Re(c.changesetError.body)??"see the response body below"}`,c.changesetError?.body!==void 0&&!Re(c.changesetError.body)&&t.jsx("pre",{style:{...oe,whiteSpace:"pre-wrap"},children:JSON.stringify(c.changesetError.body,null,2)})]})},g):null),t.jsx("div",{style:{background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,padding:"0 8px"},children:s.map(c=>t.jsx(at,{r:c},c.key))})]}):t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3,marginBottom:16},children:"Send the batch to see each request’s status, headers and body here."}),t.jsxs("details",{style:{marginTop:24},children:[t.jsxs("summary",{style:{cursor:"pointer",fontSize:13},children:[t.jsx(As,{style:{verticalAlign:"middle",marginRight:6}}),"Inspect a raw $batch response from another client"]}),t.jsxs("div",{style:{marginTop:8},children:[t.jsx(mt,{value:n,onChange:(c,g)=>a(g.value),placeholder:"--batchresponse_…",rows:8,resize:"vertical",textarea:{style:oe,spellCheck:!1},style:{width:"100%"},"aria-label":"Raw $batch response"}),t.jsx(C,{style:{marginTop:8},onClick:x,disabled:!n.trim(),children:"Parse response"}),b&&t.jsx(J,{intent:"error",style:{marginTop:8},children:t.jsx(K,{children:b})}),i&&t.jsx("div",{style:{marginTop:8},children:i.map((c,g)=>t.jsx(at,{r:{key:String(g),contentId:c.contentId??String(g+1),label:c.changeset!==void 0?`change set ${c.changeset+1}`:void 0,outcome:"done",status:c.status,statusText:c.statusText,headers:c.headers,body:c.body}},g))})]})]})]})}function it({formats:e,labels:s,generate:o,note:n,crlfFormats:a=["http"]}){const[i,r]=w.useState(e[0]),[b,p]=w.useState(!1),x=o(i);return t.jsxs("div",{children:[t.jsx(ue,{icon:Ns,title:"Code",sub:n,group:"batch",children:t.jsx(je,{content:"Copy",relationship:"label",children:t.jsx(C,{icon:t.jsx(Fs,{}),appearance:"subtle",onClick:()=>{Ds(x,"the code",{toastOnSuccess:!1}).then(m=>{m&&(p(!0),setTimeout(()=>p(!1),1500))})},children:b?"Copied":"Copy"})})}),t.jsx(_s,{selectedValue:i,onTabSelect:(m,h)=>r(h.value),size:"small",children:e.map(m=>t.jsx(Ls,{value:m,children:s[m]},m))}),t.jsx("pre",{style:{fontFamily:j.fontFamilyMonospace,fontSize:12,lineHeight:1.5,background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,padding:12,marginTop:8,whiteSpace:"pre",overflow:"auto",maxHeight:"calc(100vh - 260px)"},children:x}),a.includes(i)&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"Line breaks in a $batch body are CRLF on the wire."})]})}function Zn({open:e,onClose:s,onAdd:o}){const{saved:n}=Hs(),[a,i]=w.useState(new Set),[r,b]=w.useState(""),p=Us(),x=w.useMemo(()=>n.filter(h=>En.has(h.modeId)&&(!h.orgScope||h.orgScope===p)).filter(h=>!r.trim()||h.name.toLowerCase().includes(r.trim().toLowerCase())).sort((h,c)=>c.savedAt-h.savedAt),[n,p,r]),m=()=>{i(new Set),b(""),s()};return t.jsx(zs,{open:e,onOpenChange:(h,c)=>!c.open&&m(),children:t.jsx(Ws,{style:{maxWidth:640},children:t.jsxs(Gs,{children:[t.jsx(Vs,{children:"Add saved requests to the batch"}),t.jsxs(Js,{children:[t.jsx(W,{value:r,onChange:(h,c)=>b(c.value),placeholder:"Filter by name",contentBefore:t.jsx(Ks,{}),style:{width:"100%",marginBottom:8},"aria-label":"Filter saved requests"}),x.length===0&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3,padding:"12px 0"},children:"No saved requests on this connection that can go in a batch. Save a request from a Read, Write, Relate or Execute mode first."}),t.jsx("div",{style:{maxHeight:360,overflowY:"auto"},children:x.map(h=>t.jsx("div",{style:{display:"flex",alignItems:"center",gap:4},children:t.jsx(Qs,{checked:a.has(h.id),onChange:(c,g)=>i(k=>{const O=new Set(k);return g.checked?O.add(h.id):O.delete(h.id),O}),label:t.jsxs("span",{children:[h.name," ",t.jsx(M,{style:{color:j.colorNeutralForeground3},children:Ee(h.modeId).name})]})})},h.id))})]}),t.jsxs(Xs,{children:[t.jsx(C,{appearance:"secondary",onClick:m,children:"Cancel"}),t.jsxs(C,{appearance:"primary",disabled:a.size===0,onClick:()=>{o(x.filter(h=>a.has(h.id))),m()},children:["Add ",a.size||""]})]})]})})})}const eo=["http","fetch","pptb"],to=["csharp","http","pptb"],so={...yt,csharp:"ExecuteMultipleRequest (C#)",http:"Web API equivalent ($batch)"},no=new Set(["bulk-delete","bulk-write","batch","execute-multiple"]);function ro({themeMode:e,variant:s="batch"}){const o=s==="execute-multiple",n=o?"execute-multiple":"batch",a=Ee(n),i=Ys(n,Ve,o?Zs:en),[r,b]=w.useState(i.state),p=r.returnResponses??!0,{allEntities:x}=dt(),[m,h]=w.useState("overview"),[c,g]=w.useState("builder"),[k,O]=w.useState(null),[D,A]=w.useState(!1),[G,I]=w.useState([]),[P,q]=w.useState(!1),[V,f]=w.useState(null),[$,F]=w.useState(i.lastSavedId),[N,qe]=w.useState(i.lastSavedHash),X=Je.host?`https://${Je.host}`:"",T=w.useMemo(()=>tn(r.groups,X),[r.groups,X]),ie=w.useMemo(()=>sn(T.items),[T]),Be=kn(),$t=w.useMemo(()=>{const l=T.items.length,d=T.items.filter(u=>u.wire&&u.wire.method!=="GET").length;return d===0?null:{operation:a.name,scope:{kind:"text",text:`${l} request${l===1?"":"s"}, ${d} of them change${d===1?"s":""} data`,count:d},highImpact:!0,confirmWord:a.id==="execute-multiple"?"ExecuteMultiple":"batch"}},[T,a.id,a.name]),he=(l,d)=>{const u=new Set(l.dirty);return u.add(d),{...l,dirty:u}},Q=w.useCallback((l,d="batch")=>b(u=>he({...u,groups:l(u.groups)},d)),[]),jt=(l,d)=>Q(u=>u.map(y=>({...y,items:y.items.map(v=>v.id===l?{...v,...d}:v)})),`item:${l}`),Me=(l,d,u=!0)=>{d.length!==0&&(Q(y=>{let v=y.find(R=>R.id===l);const S=d.some(R=>ae(R,X).method==="GET");if((!v||v.atomic&&S)&&(v=[...y].reverse().find(R=>S?!R.atomic:!0)),!v){const R=Qe(!S,d);return[...y,R]}const E=v.id;return y.map(R=>R.id===E?{...R,items:[...R.items,...d]}:R)}),u&&(h(`item:${d[0].id}`),g("builder")))},wt=l=>{for(const d of r.groups){const u=d.items.find(y=>y.id===l);if(u)return{group:d,item:u}}return null},St=(l,d)=>Q(u=>{const y=u.findIndex(_=>_.items.some(Nt=>Nt.id===l));if(y<0)return u;const v=u[y].items,S=v.findIndex(_=>_.id===l),E=u.map(_=>({..._,items:[..._.items]})),R=S+d;if(R>=0&&R<v.length)[E[y].items[S],E[y].items[R]]=[E[y].items[R],E[y].items[S]];else if(u[y+d]){const[_]=E[y].items.splice(S,1);d<0?E[y-1].items.push(_):E[y+1].items.unshift(_)}return E}),kt=(l,d)=>Q(u=>{const y=u.flatMap(v=>v.items).find(v=>v.id===l);return y?u.map(v=>{const S=v.items.filter(E=>E.id!==l);return v.id===d?{...v,items:[...S,y]}:{...v,items:S}}):u}),pe=nn(),ee=pe&&!no.has(pe.modeId)?pe:null,Pe=ee?Ee(ee.modeId).name:null,Ae=async l=>{const d=[],u=[];for(const v of l){const S=await Cn(v);S.ok?d.push(...S.items):u.push(`“${v.name}” (${S.reason})`)}const y=m.startsWith("group:")?m.slice(6):null;Me(y,d,!1),f([d.length?`Added ${d.length} request${d.length===1?"":"s"}.`:"",u.length?`Skipped ${u.join(", ")}.`:""].filter(Boolean).join(" ")||null)},Ne=w.useMemo(()=>{const l=T.issues.map((u,y)=>{const v=u.target?u.target.startsWith("g")?`group:${u.target}`:`item:${u.target}`:"overview",S=T.items.find(R=>R.item.id===u.target),E=S?`$${S.contentId}: ${u.message}`:u.message;return u.severity==="error"?xe.err(`batch-${y}`,"validation",E,void 0,v):xe.warn(`batch-${y}`,"validation",E,void 0,v)}),d=T.items.filter(u=>u.wire?.method==="DELETE").length;return d>0&&l.push(xe.warn("batch-deletes","validation",`This batch deletes ${d} record${d===1?"":"s"}`,"The batch’s confirmation counts writes, not the records each delete removes, and there’s no typed record name as in the Delete mode. Check the ids first.","overview")),l},[T]),Et=Be??on(Ne),Tt=T.items.some(l=>l.wire&&Object.keys(l.wire.headers).length>0)||r.continueOnError&&ie.some(l=>!l.transaction),Rt=async()=>{A(!0);try{const l=await Sn(ie,{continueOnError:r.continueOnError});O(l);const{status:d,summary:u,succeeded:y}=yn(l);I(v=>[{id:`r-${Date.now()}`,modeId:n,url:`${re}/$batch`,method:"BATCH",ts:Date.now(),status:d,ms:l.ms,rowCount:y,summary:u},...v].slice(0,8)),b(v=>({...v,dirty:new Set}))}finally{A(!1),g("results")}},It=w.useMemo(()=>k?(o&&!p?k.items.filter(d=>d.outcome!=="done"||(d.status??0)>=400):k.items).map(d=>{const u=T.items.find(y=>y.item.id===d.itemId);return{key:d.itemId,contentId:d.contentId,method:u?.wire?.method,path:u?.wire?.path,label:u?.item.label,outcome:d.outcome,status:d.status,statusText:d.statusText,headers:d.headers,body:d.body}}):[],[k,T,o,p]),De=w.useRef({batch:de("batch"),cs:[]}),me=w.useMemo(()=>({batch:De.current.batch,changeset:l=>{var d;return(d=De.current.cs)[l]??(d[l]=de("changeset"))}}),[]),Ct=w.useMemo(()=>new TextEncoder().encode(bt(vt(T.items),me).body).length,[T,me]),Fe=l=>Nn(l,{items:T.items,plan:ie,continueOnError:r.continueOnError,orgUrl:X,boundaries:me}),Ot=l=>l==="csharp"?zn(T.items,{continueOnError:r.continueOnError,returnResponses:p},{logicalOf:d=>x.find(u=>u.entitySetName===d)?.logicalName??null,attrType:(d,u)=>lt(d)?.columns.find(y=>y.logicalName===u)?.attributeType??null}):Fe(l),te=w.useMemo(()=>rn(r),[r]);an(n,te,$,N);const qt=w.useMemo(()=>ye(te),[te]),_e=N===null?!0:qt!==N,le=T.items.length,Bt=l=>{F(l.id),qe(ye(l.state))},Mt=l=>{if(l.modeId!==n)return;const d=l.state;b(Ve(d)),F(l.id),qe(ye(d)),O(null),h("overview")},Le=Ke(Bt),He=Ke(Mt);ln(w.useMemo(()=>({state:te,modeId:n,dirty:_e,lastSavedId:$,onSaved:Le,onLoadSaved:He}),[te,n,_e,$,Le,He]));const fe=l=>T.issues.filter(d=>d.target===l),Pt=l=>k?.items.find(d=>d.itemId===l),At=[{id:"batch",label:o?"ExecuteMultiple":"Batch",meta:`${le} request${le===1?"":"s"}`,items:[{id:"overview",icon:dn,iconFilled:cn,label:o?"Settings & add":"Options & add",badge:r.continueOnError?"continue":null,badgeAppearance:"tint",dirty:r.dirty.has("overview")}]},...r.groups.map((l,d)=>({id:l.id,label:o?"Requests":l.atomic?`Change set ${d+1}`:`Independent ${d+1}`,meta:`${l.items.length}`,items:[{id:`group:${l.id}`,icon:l.atomic?Ie:Ce,iconFilled:l.atomic?un:hn,label:o?"Add request":l.atomic?"Atomic group":"Independent requests",badge:fe(l.id).length||null,badgeColor:"danger"},...l.items.map(u=>{const y=T.items.find(_=>_.item.id===u.id),v=ae(u,X),S=fe(u.id).filter(_=>_.severity==="error").length,E=Pt(u.id),R=S?`${S} issue${S===1?"":"s"}`:E?E.status!==void 0?E.status:E.outcome==="rolled-back"?"rolled back":E.outcome==="unknown"?"no result":"not run":null;return{id:`item:${u.id}`,icon:ut,iconFilled:pn,label:`$${y?.contentId??"?"} ${v.method} ${u.label||v.path||"…"}`,code:!0,badge:R,badgeAppearance:"tint",badgeColor:S||E&&(E.outcome!=="done"||(E.status??0)>=400)?"danger":"success",dirty:r.dirty.has(`item:${u.id}`)}})]}))];let se=null;if(m.startsWith("item:")){const l=wt(m.slice(5)),d=l&&T.items.find(u=>u.item.id===l.item.id);l&&d&&(se=t.jsx(Vn,{item:l.item,contentId:d.contentId,group:l.group,groups:r.groups,wire:d.wire,issues:fe(l.item.id),onChange:u=>jt(l.item.id,u),onRemove:()=>{Q(u=>u.map(y=>({...y,items:y.items.filter(v=>v.id!==l.item.id)}))),h(`group:${l.group.id}`)},onMove:u=>St(l.item.id,u),onMoveToGroup:u=>kt(l.item.id,u)},l.item.id))}else if(m.startsWith("group:")){const l=r.groups.findIndex(u=>u.id===m.slice(6)),d=r.groups[l];d&&(se=t.jsx(Xn,{group:d,index:l,count:r.groups.length,variant:s,orgUrl:X,contentIdOf:u=>T.items.find(y=>y.item.id===u)?.contentId??"?",onSetAtomic:u=>Q(y=>y.map(v=>v.id===d.id?{...v,atomic:u}:v)),onAdd:u=>Me(d.id,[ct(u)]),onRemoveGroup:()=>{Q(u=>u.filter(y=>y.id!==d.id)),h("overview")},onMoveGroup:u=>Q(y=>{const v=[...y],S=l+u;return S<0||S>=v.length?y:([v[l],v[S]]=[v[S],v[l]],v)}),onSelect:h}))}return se||(se=t.jsx(Qn,{variant:s,returnResponses:p,setReturnResponses:l=>b(d=>he({...d,returnResponses:l},"overview")),groups:r.groups,continueOnError:r.continueOnError,setContinueOnError:l=>b(d=>he({...d,continueOnError:l},"overview")),plan:ie,unavailable:Be,needsConsent:Tt,orgUrl:X,onAddGroup:l=>{const d=Qe(l);Q(u=>[...u,d]),h(`group:${d.id}`)},onOpenSaved:()=>q(!0),onAddLast:()=>{ee&&Ae([{...ee,name:Pe??ee.modeId}])},lastLabel:Pe,onSelect:h,notice:V})),t.jsxs(mn,{sidebar:t.jsx(bn,{type:a,urlPreview:`/$batch · ${le} request${le===1?"":"s"}${o?" · ExecuteMultiple":""}`,sections:At,activeNode:m,onSelect:l=>{h(l),g("builder")},recents:G}),urlBar:t.jsx(gn,{method:"BATCH",url:`${re}/$batch`,bytes:Ct,executeVerb:a.executeVerb,writeConfirm:$t,disabledReason:Et,loading:D,onExecute:Rt,advisories:Ne,onAdvisoryFocus:l=>{h(l),g("builder")}}),children:[t.jsxs(fn,{tab:c,onTabChange:g,resultCount:k?k.items.length:null,children:[c==="builder"&&se,c==="code"&&o&&t.jsx(it,{formats:to,labels:so,generate:Ot,note:"DRS sends these requests as a Web API $batch; the C# is the SDK form."}),c==="code"&&!o&&t.jsx(it,{formats:eo,labels:yt,generate:Fe,note:T.issues.some(l=>l.severity==="error")?"Requests with errors are left out until they’re fixed.":void 0}),c==="results"&&t.jsx(Yn,{run:k,rows:It,extraTitle:o&&!p&&k?"ReturnResponses = false: only faults are listed.":void 0})]}),t.jsx(Zn,{open:P,onClose:()=>q(!1),onAdd:l=>{Ae(l.map(d=>({modeId:d.modeId,state:d.state,name:d.name})))}})]})}export{ro as BatchMode};