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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +179 -0
  2. package/README.md +12 -7
  3. package/dist/assets/AssociateMode-Bs_R9XbQ.js +1 -0
  4. package/dist/assets/AssociateTargetsEditor-CVWE3tbv.js +1 -0
  5. package/dist/assets/{BatchMode-D1J8HcNO.js → BatchMode-XGXMc2XF.js} +8 -8
  6. package/dist/assets/{BinaryColumnPickers-DLIbx4hp.js → BinaryColumnPickers-mrnLqk3Z.js} +1 -1
  7. package/dist/assets/BulkDeleteMode-DowWcbnA.js +1 -0
  8. package/dist/assets/BulkWriteMode-Dt3M0dGV.js +6 -0
  9. package/dist/assets/DisassociateMode-qIc2CUpE.js +2 -0
  10. package/dist/assets/ExecuteWorkflowMode-Ce6sKYci.js +1 -0
  11. package/dist/assets/{ManageFileMode-DP3KXgFw.js → ManageFileMode-CcNSQkJf.js} +1 -1
  12. package/dist/assets/{ManageImageMode-F0Dki5VQ.js → ManageImageMode-Dn4P4D6H.js} +1 -1
  13. package/dist/assets/{MergeMode-PeKTZ75X.js → MergeMode-DzPQq2Ao.js} +1 -1
  14. package/dist/assets/PredefinedQueryMode-CaQqp2lm.js +1 -0
  15. package/dist/assets/RetrieveNextLinkMode-BNbknSwe.js +1 -0
  16. package/dist/assets/{cssMode-DXyl4xBX.js → cssMode-B4BP9f3X.js} +1 -1
  17. package/dist/assets/{freemarker2-CR_qGQP2.js → freemarker2-DFKOu_2v.js} +1 -1
  18. package/dist/assets/{handlebars-Buz2RscQ.js → handlebars-cWHtgvCj.js} +1 -1
  19. package/dist/assets/{html-B66Hfdqd.js → html-DSPQITYl.js} +1 -1
  20. package/dist/assets/{htmlMode-3ft3GC0g.js → htmlMode-Cr-uAXsT.js} +1 -1
  21. package/dist/assets/index-D0g0tm7R.js +702 -0
  22. package/dist/assets/{javascript-Cy8u5Pbx.js → javascript-B3oRul8j.js} +1 -1
  23. package/dist/assets/{jsonMode-CvLp-1ik.js → jsonMode-_zXsQ367.js} +1 -1
  24. package/dist/assets/{liquid-BxIE_8lr.js → liquid-Cib5dNaW.js} +1 -1
  25. package/dist/assets/{mdx-Bbo0ENZs.js → mdx-8A_8JwPK.js} +1 -1
  26. package/dist/assets/{monacoSetup-C4aSY1Tw.js → monacoSetup-DObeMDBe.js} +176 -175
  27. package/dist/assets/{python-B6K3FYWG.js → python-DsudPCj1.js} +1 -1
  28. package/dist/assets/{razor-7sN2ZaJq.js → razor-CrmV2uj7.js} +1 -1
  29. package/dist/assets/{tsMode-CIH2Hja3.js → tsMode-BnycW89y.js} +1 -1
  30. package/dist/assets/{typescript-rqW7IEk7.js → typescript-Bs6iTDav.js} +1 -1
  31. package/dist/assets/{xml-Bm2nJGx3.js → xml-DuKZPRNV.js} +1 -1
  32. package/dist/assets/{yaml-Z6ahf7o7.js → yaml-DDDa6myK.js} +1 -1
  33. package/dist/index.html +1 -1
  34. package/package.json +6 -1
  35. package/dist/assets/AssociateMode-BVHaHiUu.js +0 -1
  36. package/dist/assets/AssociateTargetsEditor-C-QKaWaJ.js +0 -1
  37. package/dist/assets/BulkDeleteMode-CFcjcWta.js +0 -1
  38. package/dist/assets/BulkWriteMode-C3ZGwTjw.js +0 -6
  39. package/dist/assets/DisassociateMode-BwMK4UvP.js +0 -2
  40. package/dist/assets/ExecuteWorkflowMode-CkZdayJ4.js +0 -1
  41. package/dist/assets/PredefinedQueryMode-CDuc-WrN.js +0 -1
  42. package/dist/assets/RetrieveNextLinkMode-DenFlpEh.js +0 -1
  43. package/dist/assets/index-C4fO68cu.js +0 -704
package/CHANGELOG.md CHANGED
@@ -5,6 +5,185 @@ All notable changes to Dataverse Request Studio will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [1.4.0-beta.3] - 2026-10-27
11
+
12
+ The third 1.4.0 beta fixes what a full regression pass on beta.2 turned up
13
+ ([#304]). The headline fix: Manage Image Data and Manage File Data can pick
14
+ columns again. The rest are smaller fixes to error handling, wording and
15
+ the saved-request library.
16
+
17
+ Still a **prerelease** on the npm `beta` tag, with the gold Insider icon.
18
+ Every fix was verified in Power Platform ToolBox 1.2.8 against a live
19
+ Dataverse environment.
20
+
21
+ ### 🐛 Fixed
22
+
23
+ - **Manage Image Data and Manage File Data list their columns again**
24
+ ([#305]). Image and File columns report the type `Virtual` and aren't
25
+ Advanced Find-eligible, so DRS dropped them, and both modes said the table
26
+ had no Image or File columns, even Account's `entityimage`.
27
+ - They're now loaded in the same metadata request, and `entityimage` can
28
+ also be used in `$select`.
29
+ - Each column's size limit and full-size image setting come from the
30
+ environment, so upload size checks use the column's real limit, and the
31
+ table's primary image is marked as thumbnail-only.
32
+ - **Order by** doesn't offer Image or File columns, which can't be sorted
33
+ on.
34
+ - A required Image or File column no longer blocks Create or Bulk Write.
35
+ Those columns are uploaded separately and aren't in the field set.
36
+ - **Execute Workflow can retry a failed workflow list** ([#306]). If loading
37
+ the on-demand workflows fails (for example a brief `HTTP 401` from the
38
+ host), the error has a **Retry** button, and the picker says the workflows
39
+ didn't load instead of "No activated workflows in this environment".
40
+ - **Associate and Disassociate name the right HTTP verb** ([#307]).
41
+ Disassociate's targets pane said each target fires a POST; it fires a
42
+ DELETE. Single-valued navigation properties said a PUT sets the lookup;
43
+ it's a PATCH with `<nav>@odata.bind`. Disassociate also showed the "Target
44
+ records" heading twice.
45
+ - **Saved-request library** ([#308]):
46
+ - With **All modes** off, an empty list says how many requests are saved
47
+ in other modes, instead of "No saved requests yet".
48
+ - Loading a saved request over a saved request you've edited asks before
49
+ discarding your changes.
50
+ - After you delete the saved entry a request came from, **Save** works
51
+ again without editing the request first.
52
+ - **Smaller wording fixes** ([#309]):
53
+ - Execute Action and Execute Function results point at the **JSON** tab.
54
+ - The response properties of an action or Custom API come from the
55
+ environment's `$metadata`, including inherited properties, instead of a
56
+ note about a "mock CSDL".
57
+ - Recent runs show a row count only for reads ("1 row", "6 rows"), not
58
+ "204 · 1 rows" for writes. Associate and Disassociate say how many
59
+ links were done ("3 of 5 linked"), and Bulk Write how many rows were
60
+ written.
61
+ - The **Learn more** link on an unknown-column error goes to *Select
62
+ columns*, or *Order rows* for `$orderby`.
63
+
64
+ [#304]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/304
65
+ [#305]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/305
66
+ [#306]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/306
67
+ [#307]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/307
68
+ [#308]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/308
69
+ [#309]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/309
70
+
71
+ ## [1.4.0-beta.2] - 2026-10-24
72
+
73
+ The second 1.4.0 beta fixes the issues found while testing beta.1 and
74
+ finishes the v1.4.0 milestone:
75
+ - paged reads now honour your page size;
76
+ - Retrieve all stays fast on very large tables;
77
+ - Execute Action and Execute Workflow send their headers (impersonation,
78
+ bypass);
79
+ - malformed ETags are caught before they're sent;
80
+ - a startup race that could leave DRS without a connection is fixed.
81
+
82
+ Still a **prerelease** on the npm `beta` tag, with the gold Insider icon.
83
+ Every fix was verified in Power Platform ToolBox 1.2.8 against a live
84
+ Dataverse environment.
85
+
86
+ ### 🛡️ Security
87
+
88
+ - **DOMPurify 3.4.17 in the Monaco editor.** Monaco bundles its own copy of
89
+ DOMPurify, and 1.4.0-beta.1 shipped 3.1.7, which open Dependabot alerts
90
+ (up to high severity) cover. The build now swaps in the npm package at
91
+ 3.4.17, and CI and the release workflow check the bundled version.
92
+ Command Bar Studio and FetchXML Studio use the same fix.
93
+
94
+ ### 🐛 Fixed
95
+
96
+ - **A page size no longer turns `$top` into "up to 5,000 rows"** ([#219]).
97
+ Retrieve Multiple used to drop `$top` whenever `Prefer: odata.maxpagesize`
98
+ was set, but Execute never sent that Prefer.
99
+ - On ToolBox 1.2.7+, Execute now sends the page size you set for
100
+ Retrieve Multiple, Predefined Query or Retrieve NextLink. In Retrieve
101
+ Multiple, scrolling and Retrieve all ask for the same size on every
102
+ page. ToolBox asks you to approve the `Prefer` header the first time.
103
+ Execute still asks for all annotations, so the grid renders as before.
104
+ Retrieve NextLink no longer starts with a page size of 50, so a pasted
105
+ link keeps the size it was made with unless you set one.
106
+ - On older ToolBox versions, Execute keeps `$top`, and the hints suggest
107
+ `$top` instead of a page size that can't be sent.
108
+ - `Prefer` now puts `odata.maxpagesize` last: in the Code tab, in
109
+ `$batch` parts and in exported collections. Dataverse rejects it before
110
+ `odata.include-annotations` with `0x80060888` "Invalid prefer header",
111
+ so requests with a page size and annotations used to fail.
112
+ - **Retrieve all stays responsive on large tables** ([#223]).
113
+ - Pages reach the grid in batches. The size is added up page by page,
114
+ instead of re-measuring everything loaded after every page, which slowed
115
+ down with every page.
116
+ - It pauses every 50,000 rows (or 1,000 pages) and says how many rows are
117
+ loaded. **Continue** loads the next batch. It used to stop silently after
118
+ 200 pages, so the grid and exports could look complete when they weren't.
119
+ - Response sizes are counted in UTF-8 bytes, so text in other scripts is
120
+ no longer undercounted.
121
+ - **Recent runs keeps up with paging** ([#211]): after scrolling or Retrieve
122
+ all, the entry shows the rows loaded, with "more available" or "all pages".
123
+ - **Execute Action and Execute Workflow send your request headers** ([#266]).
124
+ On ToolBox 1.2.7+, the enabled rows in their Headers pane (for example
125
+ `MSCRMCallerID` / `CallerObjectId` impersonation, or `MSCRM.*` bypass
126
+ headers) now go out with the request, after ToolBox asks you to approve
127
+ them. They used to be dropped, so an action or workflow ran as you without
128
+ saying so. Reads (apart from the page size, [#219]), relate, Execute
129
+ Function, Bulk Delete and the file / image / attachment modes still run
130
+ with ToolBox's own headers ([#109]).
131
+ - **A malformed ETag is caught before it's sent** ([#264]). Update,
132
+ Upsert and Delete send the **Specific ETag** trimmed. They block Execute,
133
+ with the reason, unless it is a quoted tag such as `W/"12345678"` (or
134
+ `*`). Before, a bare version number, curly quotes, JSON escaping
135
+ (`W/\"…\"`) or stray text went out and Dataverse answered with a 412 or
136
+ 400 that didn't point back at the value. **Fix** corrects those paste
137
+ mistakes in one click. `$batch` parts and exported collections send the
138
+ trimmed value too.
139
+ - **Error and result titles name the right source** ([#209]).
140
+ - When ToolBox reports no HTTP status, the error card says the message
141
+ comes from Dataverse only when it carries a Dataverse `0x8…` code. It
142
+ names ToolBox only for ToolBox's own messages, such as its
143
+ response-size limit, and claims neither source otherwise. The size hint
144
+ also mentions `$top` for requests without a page size.
145
+ - Create results name the record by the primary name the response
146
+ returns, so a new contact shows its full name instead of
147
+ "record <id>".
148
+ - **"N populated" counts only values that will be sent** ([#210]). The badge
149
+ and the red "missing" marker on required rows ignore the empty values a
150
+ table pre-fills for its required columns, the same way the required count
151
+ does. Before, a new contact could read "2 populated" with Last Name and
152
+ Owner still empty. The **Set** filter still lists those pre-filled rows, so
153
+ they stay visible to fill in.
154
+ - **No more "No active Dataverse connection" after the connection is
155
+ picked** ([#281]). When ToolBox bound the connection while DRS was still
156
+ starting up, DRS could miss it and stay on that error until it was
157
+ reopened. It now listens for the connection from the start, and Retry asks
158
+ ToolBox again.
159
+ - **Code → Editor no longer fakes a run** ([#240]). Its **Run (mock)**
160
+ button ignored the edited code and always showed the same two sample
161
+ account rows, which read like "your code works". The button is gone: the
162
+ editor is for editing and copying, and **Execute** sends the request the
163
+ builder shows.
164
+ - **The "…" menu has no dead items, and the counts are right** ([#265]).
165
+ **Duplicate request** and **Export OpenAPI** did nothing and are removed.
166
+ OpenAPI is one of the Code tab's formats, with **Save**. The mode picker and
167
+ the Code tab now count their modes (23) and formats (10) instead of saying
168
+ 18 and 8.
169
+ - **Docs caught up** ([#237]). CONTRIBUTING lists `npm test` and the CI
170
+ checks, and describes the tag-driven release (RELEASING.md) instead of a
171
+ manual publish. README describes the per-org metadata caches and the
172
+ Retrieve all pause.
173
+
174
+ [#109]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/109
175
+ [#209]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/209
176
+ [#210]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/210
177
+ [#211]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/211
178
+ [#219]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/219
179
+ [#223]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/223
180
+ [#237]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/237
181
+ [#240]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/240
182
+ [#264]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/264
183
+ [#265]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/265
184
+ [#266]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/266
185
+ [#281]: https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/issues/281
186
+
8
187
  ## [1.4.0-beta.1] - 2026-10-21
9
188
 
10
189
  The biggest release so far: four new modes (Bulk Write, Bulk Delete Job,
package/README.md CHANGED
@@ -33,8 +33,9 @@ modes have their own HTTP / fetch / C# / PPTB outputs.
33
33
  - **Retrieve Multiple** — full OData query composer with `$select`, `$filter`,
34
34
  `$orderby`, `$expand` (nested, with inner `$filter` / `$orderby` / `$top`),
35
35
  `$top`, `$count`, `$apply` (groupby / aggregate), and a virtualized results
36
- grid with infinite scroll via `@odata.nextLink`, **Retrieve all**, CSV / JSON
37
- export, per-column filters, row search, density and persisted column widths.
36
+ grid with infinite scroll via `@odata.nextLink`, **Retrieve all** (pauses
37
+ every 50,000 rows with **Continue**), CSV / JSON export, per-column filters,
38
+ row search, density and persisted column widths.
38
39
  Address shortcut chips in the `$filter` builder; paste any OData URL to load
39
40
  it into the builder.
40
41
  - **Retrieve Single** — one record by primary key (GUID), with `$select` /
@@ -149,9 +150,11 @@ modes have their own HTTP / fetch / C# / PPTB outputs.
149
150
  org with in-flight promise dedup. Switching the PPTB connection resets the
150
151
  prepared request and reloads metadata for the new environment.
151
152
  - **Request headers through PPTB 1.2.7+** — Create / Update / Upsert /
152
- Delete / Merge / Bulk Write headers (preconditions, `MSCRM.*` bypass, duplicate detection, impersonation) are
153
- sent as additional headers after you approve them once in ToolBox. On older
154
- hosts, requests that depend on a header are blocked with an explanation.
153
+ Delete / Merge / Bulk Write / Execute Action / Execute Workflow headers
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.
155
158
  `Authorization` / `Cookie` headers are never sent, saved or exported.
156
159
  - **Antipattern advisories** — Surfaces real-time guidance per the
157
160
  [Microsoft query-antipatterns doc](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/query-antipatterns):
@@ -218,7 +221,8 @@ modes have their own HTTP / fetch / C# / PPTB outputs.
218
221
 
219
222
  - [Power Platform ToolBox](https://www.powerplatformtoolbox.com/) **1.2.0 or
220
223
  later** (the tool declares `minAPI: 1.2.0`). **1.2.7 or later** is
221
- recommended: it sends the write modes' request headers and is required for
224
+ recommended: it sends the write and execute modes' request headers and the
225
+ page size, and is required for
222
226
  the `$batch` and ExecuteMultiple modes.
223
227
  - A connection to a Dataverse environment
224
228
  - For local development: **Node.js 22.22.2+, 24.15+ or 26+** and **npm** (see
@@ -359,7 +363,7 @@ src/
359
363
  pptbBridge.ts — typed wrapper over window.dataverseAPI
360
364
  metadataProvider.ts — entity / attribute / relationship loaders
361
365
  csdlProvider.ts — $metadata XML parsing + action / function index
362
- cache.ts — singleton TTL cache with in-flight dedup
366
+ cache.ts — per-org metadata caches (TTL + in-flight dedup)
363
367
  useLiveMetadata.ts, useColumnDetail.ts, useScopedEntities.ts, …
364
368
 
365
369
  primitives/ — small reusable UI bits
@@ -407,6 +411,7 @@ Dataverse API)
407
411
  | Retrieve Multiple (full OData) | ✅ |
408
412
  | Retrieve Single (by GUID) | ✅ |
409
413
  | `@odata.nextLink` paging, Retrieve all | ✅ |
414
+ | `Prefer: odata.maxpagesize` (page size) | ✅ 1.2.7+ (older ToolBox: Execute keeps `$top` instead) |
410
415
  | Predefined / user queries (incl. over related records) | ✅ |
411
416
  | `$apply` (groupby / aggregate) | ✅ |
412
417
  | Lambda filter (`any` / `all`) | ✅ |
@@ -0,0 +1 @@
1
+ import{c as ae,b7 as se,bM as D,r,u as re,e as oe,bN as ne,bO as le,bP as ie,f as de,bQ as ce,bR as ue,bb as ge,i as M,k as he,T as be,l as pe,bS as me,bT as ye,bH as ve,bI as fe,bU as A,L as Se,q as xe,t as a,H as Pe,B as Te,D as Ne,J as je,w as ke,bV as we,y as Ce,z as Ie,A as Me,G as Re,R as Ae,bW as R,U as He,S as Fe,I as $e,bn as Be,aU as Le,bo as qe,b6 as Ue,a9 as Ee,Y as T,bm as Oe,Z as De,b0 as ze}from"./index-D0g0tm7R.js";import{A as Ve,N as We}from"./AssociateTargetsEditor-CVWE3tbv.js";const Ge=()=>({table:"",sourceId:null,navProperty:null,targets:[],targetNames:{},headers:$e(),dirty:new Set});function _e({themeMode:d}){const p=ae("associate"),l=se("associate",D,Ge),[e,c]=r.useState(l.state),{table:N}=re(e.table||null),{entities:H}=oe(),[F,$]=r.useState("source"),[m,j]=r.useState("builder"),[B,k]=r.useState(null),[V,L]=r.useState(!1),[W,G]=r.useState([]),[y,v]=r.useState(l.lastSavedId),[f,S]=r.useState(l.lastSavedHash),[q,w]=r.useState(""),b=r.useMemo(()=>ne(e),[e,N]),J=r.useMemo(()=>le(e),[e,N]),o=r.useMemo(()=>ie(e),[e,N]),x=de(e.table),n=e.navProperty?x?.navigationProperties.find(t=>t.name===e.navProperty):void 0,U=n?ce(n):!1,u=U?"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)},Q=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.":null:"Pick a navigation property.":"Pick a source record.":"Pick a source table first.",Y=async()=>{L(!0);const t=await Le.associate(e);k(t),L(!1),j("results"),G(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,o.length)??0,summary:`${R(t,o.length)??0} of ${o.length} linked`},...s].slice(0,8)),c(s=>({...s,dirty:new Set}))},g=r.useMemo(()=>ue(e),[e]);ge("associate",g,y,f);const Z=r.useMemo(()=>M(g),[g]),E=f===null?!0:Z!==f,_=t=>{v(t.id),S(M(t.state))},O=t=>{if(t.modeId!=="associate")return;const s=t.state;if(H.length>0&&!H.some(i=>i.logicalName===s.table)){Be(`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(D(s)),v(t.id),S(M(s)),k(null),w(""),$("source")},K=t=>{const s=qe(t,"associate");if(!s)return;const i=y,I=f;O(s),v(i),S(I)};he(r.useMemo(()=>e.table?{state:g,modeId:"associate",dirty:E,lastSavedId:y,onSaved:_,onLoadSaved:O}:null,[g,E,y,e.table]));const X=[{id:"source",label:"Target",meta:x?.displayName??"Pick a table",items:[{id:"source",icon:pe,iconFilled:be,label:e.sourceId?q||`${x?.displayName??""} (selected)`:"Pick a record",badge:n?u:null,badgeAppearance:"tint",badgeColor:"brand",dirty:e.dirty.has("source")}]},{id:"relationship",label:"Relationship",meta:n?z(n.cardinality):"pick one",items:[{id:"nav",icon:ye,iconFilled:me,label:n?n.name:"Navigation property",code:!!n,badge:n?z(n.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:fe,iconFilled:ve,label:U?"Target record":"Target records",badge:e.targets.length||null,badgeAppearance:"tint",badgeColor:e.targets.length>0?"success":"subtle",dirty:e.dirty.has("targets")},...o.length>0?[{id:"preview",icon:A,iconFilled:A,label:`${o.length} request${o.length===1?"":"s"}`,badge:o.length,badgeAppearance:"ghost"}]:[]]},{id:"headers",label:"Headers",meta:`${e.headers.filter(t=>t.enabled).length} active`,items:[{id:"headers",icon:xe,iconFilled:Se,label:"HTTP headers",badge:e.headers.filter(t=>t.enabled).length||null,dirty:e.dirty.has("headers")}]}];let h;switch(F){case"source":h=a.jsx(ke,{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(We,{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(Te,{layout:"multiline",intent:"info",children:a.jsxs(Ne,{children:[a.jsx(je,{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(Ve,{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:n?u:null});break;case"preview":h=a.jsx(Je,{requests:o});break;case"headers":h=a.jsx(Pe,{items:e.headers,setItems:t=>P("headers",t,"headers"),group:"relate"});break}const ee=we(u,Ce(e.headers,null)),te={method:u,built:b,headers:ee,body:J,entityLogical:b.entityLogical,multiRequests:o.length>1?o.map(t=>({method:t.method,relativeUrl:t.relativeUrl,body:t.body,description:`target ${t.targetId}`})):void 0};return a.jsx(Ie,{sidebar:a.jsx(Fe,{type:p,urlPreview:b.relativeNoBase,sections:X,activeNode:F,onSelect:t=>{$(t),j("builder")},recents:W,onRecentClick:K}),urlBar:a.jsx(He,{method:u,url:b.relativeUrl,executeVerb:p.executeVerb,disabledReason:Q,loading:V,onExecute:Y}),children:a.jsxs(Me,{tab:m,onTabChange:j,resultCount:R(B,o.length),children:[m==="builder"&&h,m==="code"&&a.jsx(Re,{themeMode:d,inputs:te}),m==="results"&&a.jsx(Ae,{result:B,mode:"single",table:e.table,writeContext:{operation:"associate",table:e.table,recordId:e.sourceId,recordName:q||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 Je({requests:d}){const p=Ue();return a.jsxs("div",{children:[a.jsx(Ee,{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:ze(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(Oe,{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(De,{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 z(d){switch(d){case"OneToMany":return"1:N";case"ManyToOne":return"N:1";case"ManyToMany":return"N:N"}}export{_e as AssociateMode};
@@ -0,0 +1 @@
1
+ import{f as m,u as L,t as e,a9 as F,bS as b,a5 as M,bk as G,b4 as K,Y as n,bm as p,Z as v,r as P,b6 as V,B as O,D as C,aE as E,c1 as J,bL as Q,O as U,aQ as Y,b0 as Z,b5 as _,aC as X,J as ee}from"./index-D0g0tm7R.js";function le({table:t,value:s,onChange:r,group:o="relate",forOperation:u,footer:y}){const g=m(t)?.navigationProperties??[],d=g.find(i=>i.name===s);return L(d?.targetEntity??null),e.jsxs("div",{children:[e.jsx(F,{icon:b,title:"Navigation property",sub:"Cardinality is detected from metadata — the URL bar verb + shape adapt automatically.",group:o}),e.jsxs("div",{style:{maxWidth:720},children:[e.jsx(M,{label:"Navigation property",children:e.jsx(G,{value:d?.name??"",selectedOptions:d?[d.name]:[],onOptionSelect:(i,T)=>r(T.optionValue??null),placeholder:"Pick a navigation property…",children:g.map(i=>e.jsx(K,{value:i.name,text:i.name,children:e.jsx(te,{nav:i,forOperation:u})},i.name))})}),d&&e.jsx("div",{style:{marginTop:16},children:e.jsx(ne,{nav:d,forOperation:u})}),y&&e.jsx("div",{style:{marginTop:14},children:y})]})]})}function te({nav:t,forOperation:s}){const r=m(t.targetEntity),o=R(t,s);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:n.fontFamilyMonospace,fontWeight:600},children:t.name}),e.jsx(p,{appearance:"ghost",size:"extra-small",children:B(t.cardinality)}),e.jsx(p,{appearance:"tint",color:"brand",size:"extra-small",style:{marginLeft:"auto"},children:o})]}),e.jsxs(v,{style:{color:n.colorNeutralForeground3},children:["→ ",r?.displayName??t.targetEntity," · ",re(t.cardinality)]})]})}function ne({nav:t,forOperation:s}){const r=m(t.targetEntity),o=R(t,s),u=t.cardinality==="ManyToOne"?"single-valued":"collection-valued",y=o==="POST"?n.colorPaletteGreenForeground1:o==="PATCH"?n.colorPaletteDarkOrangeForeground1:n.colorPaletteRedForeground1;return e.jsxs("div",{style:{border:`1px solid ${n.colorNeutralStroke2}`,borderRadius:n.borderRadiusMedium,padding:12,background:n.colorNeutralBackground1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(b,{style:{width:18,height:18,color:n.colorBrandForeground1}}),e.jsx("strong",{style:{fontFamily:n.fontFamilyMonospace,fontSize:13},children:t.name}),e.jsx(p,{appearance:"tint",color:"brand",children:B(t.cardinality)}),e.jsx("span",{style:{flexGrow:1}}),e.jsx(p,{appearance:"filled",style:{background:y,color:n.colorNeutralForegroundOnBrand,fontWeight:700},children:o})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"120px 1fr",rowGap:4,fontSize:11},children:[e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Target entity"}),e.jsxs("span",{style:{fontFamily:n.fontFamilyMonospace},children:[r?.entitySetName??t.targetEntity," ",e.jsxs(v,{style:{color:n.colorNeutralForeground3},children:["· ",r?.displayName??t.targetEntity]})]}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Cardinality"}),e.jsxs("span",{children:[u," (",t.cardinality,")"]}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Relationship"}),e.jsx("span",{style:{fontFamily:n.fontFamilyMonospace,fontSize:10},children:t.relationshipName})]})]})}function B(t){switch(t){case"OneToMany":return"1:N";case"ManyToOne":return"N:1";case"ManyToMany":return"N:N"}}function re(t){return t==="ManyToOne"?"single-valued lookup":"collection-valued"}function R(t,s){return t.cardinality==="ManyToOne"?"PATCH":s==="disassociate"?"DELETE":"POST"}function se({table:t,navProperty:s,targets:r,setTargets:o,targetNames:u,setTargetNames:y,group:N="relate",resolvedMethod:g,sub:d,verb:i="POST"}){const[T,A]=P.useState({}),j=u??T,S=y??A,W=V(),w=m(t),h=s?w?.navigationProperties.find(a=>a.name===s):void 0,x=h?m(h.targetEntity):void 0,l=h?.cardinality==="ManyToOne",z=l?1:1/0,[$,q]=P.useState(0);if(!h)return e.jsxs("div",{children:[e.jsx(F,{icon:b,title:"Target records",sub:"Pick a navigation property first.",group:N}),e.jsx(O,{layout:"multiline",intent:"info",style:{maxWidth:720},children:e.jsxs(C,{children:["Switch to the ",e.jsx("strong",{children:"Navigation property"})," pane and pick one — the target entity comes from there."]})})]});const k=r.length>=z,D=(a,c)=>{if(!a||r.includes(a)||k)return;const f=l?[a]:[...r,a];o(f),c&&S({...j,[a]:c}),q(I=>I+1)},H=a=>{if(o(r.filter(c=>c!==a)),j[a]!=null){const c={...j};delete c[a],S(c)}};return e.jsxs("div",{children:[e.jsxs(F,{icon:b,title:l?"Target record":"Target records",sub:e.jsx("span",{children:d??(l?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(p,{appearance:"tint",color:r.length>0?"brand":"subtle",children:[r.length," target",r.length===1?"":"s"]}),g&&e.jsx(p,{appearance:"filled",color:g==="POST"?"success":"informative",style:{fontWeight:700},children:g}),!l&&r.length>1&&e.jsx(E,{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(p,{appearance:"ghost",icon:e.jsx(J,{style:{width:12,height:12}}),children:[r.length," requests queued"]})})]}),e.jsx("div",{className:Z(W.inlineCard),style:{padding:12,marginBottom:14,maxWidth:880},children:r.length===0?e.jsxs(v,{style:{padding:"12px 4px",color:n.colorNeutralForeground3,fontStyle:"italic",display:"block",textAlign:"center"},children:["No targets selected — use the picker below to choose"," ",l?"one":"one or more"," ",e.jsx("strong",{children:x?.displayName??h.targetEntity})," record",l?"":"s","."]}):e.jsx("div",{style:{display:"flex",flexDirection:"column"},children:r.map((a,c)=>{const f=j[a];return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 4px",borderBottom:c<r.length-1?`1px solid ${n.colorNeutralStroke3}`:"none"},children:[e.jsx(Q,{size:"small",name:f??"?",avatar:{color:"colorful"}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600},children:f??e.jsx("span",{style:{fontStyle:"italic",color:n.colorNeutralForeground3},children:"(name not resolved)"})}),e.jsxs("div",{style:{fontFamily:n.fontFamilyMonospace,fontSize:10,color:n.colorNeutralForeground3},children:["/",x?.entitySetName??"?","(",a,")"]})]}),e.jsx(E,{content:"Remove target",relationship:"label",children:e.jsx(U,{size:"small",appearance:"subtle",icon:e.jsx(Y,{}),onClick:()=>H(a),"aria-label":"Remove target"})})]},a)})})}),!k&&e.jsxs("div",{style:{maxWidth:560},children:[e.jsx(M,{label:l?"Pick target":"Add target",hint:l?`Pick a single ${x?.displayName??"record"} — the PATCH sets this as the lookup value.`:`Each pick queues a separate ${i}. Currently ${r.length} target${r.length===1?"":"s"} queued.`,children:e.jsx(_,{table:x?.logicalName??h.targetEntity,selectedId:null,onPick:a=>D(a?.id??null,a?.primary),placeholder:`Search ${x?.displayName??"record"}s…`},$)}),!l&&e.jsxs(v,{style:{display:"block",marginTop:6,color:n.colorNeutralForeground3},children:[e.jsx(X,{style:{width:12,height:12,verticalAlign:"middle"}})," picking a record adds it to the queue and resets the picker for the next pick."]})]}),k&&l&&e.jsx(O,{layout:"multiline",intent:"info",style:{maxWidth:720,marginTop:12},children:e.jsxs(C,{children:[e.jsx(ee,{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{se as A,le as N};
@@ -1,11 +1,11 @@
1
- import{ah as Mt,cx as Pt,d as Le,bB as ze,f as rt,c0 as At,c1 as Dt,c2 as Nt,cy as Ft,cz as _t,cA as Lt,cB as zt,cC as Ht,bV as Ut,bX as Wt,bT as He,bK as Gt,bN as Vt,bz as Jt,bC as Kt,bD as Qt,cD as Xt,cE as Yt,cF as Zt,cG as es,cH as ts,cI as ss,cJ as ns,cK as os,cL as rs,cM as as,ae as is,b6 as ls,b7 as cs,cN as ds,cO as us,cP as hs,cQ as ps,cR as ms,ai as fs,x as gs,aL as bs,cS as at,cT as xs,cU as ys,cV as ne,e as it,r as w,u as vs,bY as js,q as t,a8 as ce,ce as lt,aC as je,N as I,cW as ct,cX as dt,ay as $e,A as G,B as V,a4 as L,b1 as fe,b2 as ge,a5 as U,X as $,ac as ut,Y as M,P as we,aA as ie,cY as oe,cZ as Re,c_ as Ie,bg as $s,bh as Ue,c$ as Ce,ar as ws,I as te,d0 as Ss,d1 as ks,d2 as Ts,d3 as Es,d4 as Rs,d5 as Is,J as Se,aN as Cs,cf as Os,Q as qs,V as Bs,d6 as Ms,d7 as Ps,d8 as As,d9 as Ds,Z as Ns,_ as Fs,$ as _s,a0 as Ls,a1 as zs,br as Hs,a3 as Us,c as ke,a6 as Ws,b5 as Gs,da as Vs,db as Js,dc as We,E as Ge,dd as Ks,de as Qs,df as Xs,ca as be,al as Ys,dg as Zs,b9 as en,i as xe,j as tn,dh as sn,di as nn,dj as on,dk as rn,cd as an,dl as Ve,y as ln,z as cn,U as dn,S as un}from"./index-C4fO68cu.js";const ye=e=>e.status>=400;function hn(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 i=s.some(ye),a=e.transaction&&i,r=e.items.map(p=>{const x=o.get(p.contentId);return x?{itemId:p.item.id,contentId:p.contentId,outcome:a&&!ye(x)?"rolled-back":"done",status:x.status,statusText:x.statusText,headers:x.headers,body:x.body}:{itemId:p.item.id,contentId:p.contentId,outcome:a?"rolled-back":"not-run"}}),b=n.find(ye);return{items:r,segment:{transaction:e.transaction,contentIds:e.items.map(p=>p.contentId),ms:0,ok:!i&&r.every(p=>p.outcome==="done"),changesetError:b}}}function pn(e){const s=e.segments.some(x=>!x.skipped&&(!x.error||x.requestFailed)),o=e.items.length;let n=0,i=0,a=0,r=0,b=0;for(const x of e.items)x.outcome==="done"?(x.status??0)>=400?i++:n++:x.outcome==="rolled-back"?a++:x.outcome==="not-run"?r++:b++;const p=[`${o} request${o===1?"":"s"}`];return i&&p.push(`${i} failed`),a&&p.push(`${a} 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 mn=/additional headers were rejected|header consent/i,ht=/invalid content id correlation|missing operation results/i,fn=/invalid content id correlation/i;function gn(e){return e.replace(/^\s*Error invoking remote method '[^']*':\s*/i,"").replace(/^(?:\w*Error:\s*)+/,"").trim()}function bn(e,s){const o=gn(e);return mn.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&&fn.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&&ht.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 xn(e,s){const o=performance.now(),n=[],i=[];let a=!1;for(const r of e){const b=r.items.map(h=>h.contentId);if(a){i.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(pt),x=!r.transaction&&s.continueOnError?{Prefer:"odata.continue-on-error"}:void 0,f=performance.now();try{const h=r.transaction?await Le.executeTransaction(p,x):await Le.executeBatch(p,x),c=hn(r,h);c.segment.ms=Math.round(performance.now()-f),i.push(c.segment),n.push(...c.items),!c.segment.ok&&!s.continueOnError&&(a=!0)}catch(h){const c=h instanceof Error?h.message:String(h);x||p.some(g=>g.headers&&Object.keys(g.headers).length),i.push({transaction:r.transaction,contentIds:b,ms:Math.round(performance.now()-f),ok:!1,requestFailed:ht.test(c),error:bn(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||(a=!0)}}return{ms:Math.round(performance.now()-o),ok:i.every(r=>r.ok),items:n,segments:i}}function pt(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 yn(){return Mt()?Pt()?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 vn=new Set(["retrieve-multiple","retrieve-single","predefined-query","create","update","upsert","delete","merge","associate","disassociate","exec-action","exec-function","exec-workflow"]),jn=new Set(["authorization","accept","content-type","content-length","odata-version","odata-maxversion"]);function Je(e,s){return{id:`__batch__${e}`,name:e,value:s,enabled:!0,builtin:!0}}function F(e){let s=(e.headers??[]).map(i=>i.name==="MSCRM.SuppressDuplicateDetection"&&e.duplicateDetection!==void 0?{...i,enabled:e.duplicateDetection,value:"false"}:i);const o=e.concurrency?ms(e.concurrency):null;if(o&&s.push(Je(o.name,o.value)),e.suppressDuplicateDetection&&s.push(Je("MSCRM.SuppressDuplicateDetection","true")),e.bypass){const i=e.bypassCustomPlugins&&e.bypass.businessLogic==="none"?{...e.bypass,businessLogic:"sync",useLegacyHeader:!0}:e.bypass;s=fs(s,i)}const n=gs(s,e.prefer?bs(e.prefer):null);return Object.fromEntries(Object.entries(n).filter(([i])=>!jn.has(i.toLowerCase())))}function ve(e,s,o,n,i,a){return at("custom",{label:e,source:s,method:o,url:ys(n),body:a&&Object.keys(a).length>0?xs(a):a?"{}":"",headers:Object.entries(i).map(([r,b])=>({name:r,value:b,enabled:!0}))})}function $n(e){const{name:s}=e,o=(n,i,a,r)=>i?{ok:!0,items:[ve(s,s,n,i,a,r)]}:{ok:!1,reason:"its table isn’t available on this connection"};try{switch(e.modeId){case"retrieve-multiple":{const n=hs(e.state);return o("GET",ps(n).relativeUrl,F(n))}case"retrieve-single":{const n=ds(e.state);return o("GET",us(n).relativeUrl,F(n))}case"predefined-query":{const n=ls(e.state);return o("GET",cs(n).relativeUrl,F(n))}case"create":{const n=rs(e.state);return o("POST",as(n).relativeUrl,F(n),is(n))}case"update":{const n=ss(e.state);return o(n.method,ns(n).relativeUrl,F(n),os(n))}case"upsert":{const n=Zt(e.state);return o("PATCH",es(n).relativeUrl,F(n),ts(n))}case"delete":{const n=Xt(e.state);return o("DELETE",Yt(n).relativeUrl,F(n))}case"merge":{const n=Jt(e.state);return o("POST",Kt(n).relativeUrl,F(n),Qt(n))}case"associate":{const n=Gt(e.state),i=F(n),a=Vt(n);return a.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:a.map(r=>ve(`${s} → ${r.targetId}`,s,r.method,r.relativeUrl,He(r.method,i),r.body))}}case"disassociate":{const n=Ut(e.state),i=F(n),a=Wt(n);return a.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:a.map(r=>ve(r.targetId?`${s} × ${r.targetId}`:s,s,r.method,r.relativeUrl,He(r.method,i),r.body))}}case"exec-action":{const n=Lt(e.state);return o("POST",zt(n).relativeUrl,F(n),Ht(n))}case"exec-function":{const n=Ft(e.state);return o("GET",_t(n).relativeUrl,F(n))}case"exec-workflow":{const n=At(e.state);return o("POST",Dt(n).relativeUrl,F(n),Nt(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 wn(e){if(e&&typeof e=="object"&&"table"in e){const s=e.table;if(typeof s=="string")return s}return""}async function Sn(e){const s=wn(e.state);s&&await ze.getTable(s).catch(()=>{});const o=e.state?.navProperty;if(s&&typeof o=="string"&&o){const n=rt(s)?.navigationProperties.find(i=>i.name===o)?.targetEntity;n&&await ze.getTable(n).catch(()=>{})}return $n(e)}const z=`\r
2
- `;function kn(e){return/^\$\d+/.test(e)?e:`${ne}/${e}`}function Tn(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} ${kn(s.path)} HTTP/1.1`];for(const[n,i]of Object.entries(s.headers))o.push(`${n}: ${i}`);return s.body!==void 0&&!Tn(s.headers,"Content-Type")&&o.push("Content-Type: application/json; type=entry"),o.push("",s.body??""),o.join(z)}let Ke=0;function le(e){Ke+=1;const s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(16)}-${Ke.toString(16)}-${Math.random().toString(16).slice(2)}`;return`${e}_${s}`}function mt(e,s={}){const o=s.batch??le("batch");let n=0,i="";for(const a of e)if(a.parts.length!==0)if(a.atomic){const r=s.changeset?.(n)??le("changeset");n+=1,i+=`--${o}${z}Content-Type: multipart/mixed; boundary=${r}${z}${z}`;for(const b of a.parts)i+=`--${r}${z}${Te(b)}${z}`;i+=`--${r}--${z}`}else for(const r of a.parts)i+=`--${o}${z}${Te(r)}${z}`;return i+=`--${o}--${z}`,{boundary:o,contentType:`multipart/mixed; boundary=${o}`,body:i}}const ft=/boundary=(?:"([^"]+)"|([^;\s]+))/i;function En(e,s){const o=ft.exec(e);if(o)return o[1]||o[2];const n=/^\s*--([^\r\n]+)/.exec(s);return n?n[1].trim():null}function Qe(e){const s={};for(const o of e.split(/\r?\n/)){const n=o.indexOf(":");if(n<=0)continue;const i=o.slice(0,n).trim().toLowerCase(),a=o.slice(n+1).trim();s[i]=s[i]?`${s[i]}, ${a}`:a}return s}function Rn(e,s){const o=`--${s}`,n=[];let i=e.indexOf(o);if(i<0)throw new Error(`Response boundary "${s}" not found.`);for(;i>=0;){if(i+=o.length,e.startsWith("--",i))return n;const a=e.indexOf(o,i);if(a<0)throw new Error("Response is missing its closing boundary.");n.push(e.slice(i,a).replace(/^\r?\n/,"").replace(/\r?\n$/,"")),i=a}return n}function Xe(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 In(e,s=""){const o=En(s,e);if(!o)throw new Error("No multipart boundary in the Content-Type or the body.");let n=0;const i=(a,r,b)=>Rn(a,r).flatMap(p=>{const[x,f]=Xe(p),h=Qe(x),c=ft.exec(h["content-type"]??"");if(c){const j=n++;return i(f,c[1]||c[2],j)}const g=f.search(/HTTP\/1\.[01]\s+\d{3}/i);if(g<0)throw new Error("A response part has no HTTP status line.");const[S,C]=Xe(f.slice(g)),[_,...A]=S.split(/\r?\n/),W=/^HTTP\/1\.[01]\s+(\d{3})(?:\s+(.*))?$/i.exec(_.trim());if(!W)throw new Error(`Malformed status line: ${_}`);const E=C.trim();let O;if(E)try{O=JSON.parse(E)}catch{O=E}const m={status:Number(W[1]),statusText:W[2]?.trim()||void 0,headers:Qe(A.join(`
1
+ import{aj as Mt,cA as Pt,d as Le,bD as He,f as rt,c2 as Dt,c3 as At,c4 as Nt,cB as Ft,cC as _t,cD as Lt,cE as Ht,cF as zt,bX as Ut,bZ as Wt,bV as ze,bM as Gt,bP as Vt,bB as Jt,bE as Kt,bF as Qt,cG as Xt,cH as Yt,cI as Zt,cJ as es,cK as ts,cL as ss,cM as ns,cN as os,cO as rs,cP as as,af as is,b8 as ls,b9 as cs,cQ as ds,cR as us,cS as hs,cT as ps,cU as ms,ak as fs,y as gs,aN as bs,cV as at,cW as xs,cX as ys,cY as ne,e as it,r as w,u as vs,b_ as js,t,a9 as ce,ch as lt,aE as je,O as I,cZ as ct,c_ as dt,aA as $e,B as G,D as V,a5 as L,b3 as fe,b4 as ge,a6 as U,Y as $,ad as ut,Z as M,Q as we,aC as ie,c$ as oe,d0 as Re,d1 as Ie,bi as $s,bj as Ue,d2 as Ce,at as ws,J as te,d3 as Ss,d4 as ks,d5 as Es,d6 as Ts,d7 as Rs,d8 as Is,K as Se,aP as Cs,ci as Os,V as qs,W as Bs,d9 as Ms,da as Ps,db as Ds,dc as As,_ as Ns,$ as Fs,a0 as _s,a1 as Ls,a2 as Hs,bt as zs,a4 as Us,c as ke,a7 as Ws,b7 as Gs,dd as Vs,de as Js,df as We,E as Ge,dg as Ks,dh as Qs,di as Xs,cd as be,an as Ys,dj as Zs,bb as en,i as xe,k as tn,dk as sn,dl as nn,dm as on,dn as rn,cg as an,dp as Ve,z as ln,A as cn,U as dn,S as un}from"./index-D0g0tm7R.js";const ye=e=>e.status>=400;function hn(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 i=s.some(ye),a=e.transaction&&i,r=e.items.map(p=>{const x=o.get(p.contentId);return x?{itemId:p.item.id,contentId:p.contentId,outcome:a&&!ye(x)?"rolled-back":"done",status:x.status,statusText:x.statusText,headers:x.headers,body:x.body}:{itemId:p.item.id,contentId:p.contentId,outcome:a?"rolled-back":"not-run"}}),b=n.find(ye);return{items:r,segment:{transaction:e.transaction,contentIds:e.items.map(p=>p.contentId),ms:0,ok:!i&&r.every(p=>p.outcome==="done"),changesetError:b}}}function pn(e){const s=e.segments.some(x=>!x.skipped&&(!x.error||x.requestFailed)),o=e.items.length;let n=0,i=0,a=0,r=0,b=0;for(const x of e.items)x.outcome==="done"?(x.status??0)>=400?i++:n++:x.outcome==="rolled-back"?a++:x.outcome==="not-run"?r++:b++;const p=[`${o} request${o===1?"":"s"}`];return i&&p.push(`${i} failed`),a&&p.push(`${a} 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 mn=/additional headers were rejected|header consent/i,ht=/invalid content id correlation|missing operation results/i,fn=/invalid content id correlation/i;function gn(e){return e.replace(/^\s*Error invoking remote method '[^']*':\s*/i,"").replace(/^(?:\w*Error:\s*)+/,"").trim()}function bn(e,s){const o=gn(e);return mn.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&&fn.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&&ht.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 xn(e,s){const o=performance.now(),n=[],i=[];let a=!1;for(const r of e){const b=r.items.map(h=>h.contentId);if(a){i.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(pt),x=!r.transaction&&s.continueOnError?{Prefer:"odata.continue-on-error"}:void 0,f=performance.now();try{const h=r.transaction?await Le.executeTransaction(p,x):await Le.executeBatch(p,x),c=hn(r,h);c.segment.ms=Math.round(performance.now()-f),i.push(c.segment),n.push(...c.items),!c.segment.ok&&!s.continueOnError&&(a=!0)}catch(h){const c=h instanceof Error?h.message:String(h);x||p.some(g=>g.headers&&Object.keys(g.headers).length),i.push({transaction:r.transaction,contentIds:b,ms:Math.round(performance.now()-f),ok:!1,requestFailed:ht.test(c),error:bn(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||(a=!0)}}return{ms:Math.round(performance.now()-o),ok:i.every(r=>r.ok),items:n,segments:i}}function pt(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 yn(){return Mt()?Pt()?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 vn=new Set(["retrieve-multiple","retrieve-single","predefined-query","create","update","upsert","delete","merge","associate","disassociate","exec-action","exec-function","exec-workflow"]),jn=new Set(["authorization","accept","content-type","content-length","odata-version","odata-maxversion"]);function Je(e,s){return{id:`__batch__${e}`,name:e,value:s,enabled:!0,builtin:!0}}function F(e){let s=(e.headers??[]).map(i=>i.name==="MSCRM.SuppressDuplicateDetection"&&e.duplicateDetection!==void 0?{...i,enabled:e.duplicateDetection,value:"false"}:i);const o=e.concurrency?ms(e.concurrency):null;if(o&&s.push(Je(o.name,o.value)),e.suppressDuplicateDetection&&s.push(Je("MSCRM.SuppressDuplicateDetection","true")),e.bypass){const i=e.bypassCustomPlugins&&e.bypass.businessLogic==="none"?{...e.bypass,businessLogic:"sync",useLegacyHeader:!0}:e.bypass;s=fs(s,i)}const n=gs(s,e.prefer?bs(e.prefer):null);return Object.fromEntries(Object.entries(n).filter(([i])=>!jn.has(i.toLowerCase())))}function ve(e,s,o,n,i,a){return at("custom",{label:e,source:s,method:o,url:ys(n),body:a&&Object.keys(a).length>0?xs(a):a?"{}":"",headers:Object.entries(i).map(([r,b])=>({name:r,value:b,enabled:!0}))})}function $n(e){const{name:s}=e,o=(n,i,a,r)=>i?{ok:!0,items:[ve(s,s,n,i,a,r)]}:{ok:!1,reason:"its table isn’t available on this connection"};try{switch(e.modeId){case"retrieve-multiple":{const n=hs(e.state);return o("GET",ps(n).relativeUrl,F(n))}case"retrieve-single":{const n=ds(e.state);return o("GET",us(n).relativeUrl,F(n))}case"predefined-query":{const n=ls(e.state);return o("GET",cs(n).relativeUrl,F(n))}case"create":{const n=rs(e.state);return o("POST",as(n).relativeUrl,F(n),is(n))}case"update":{const n=ss(e.state);return o(n.method,ns(n).relativeUrl,F(n),os(n))}case"upsert":{const n=Zt(e.state);return o("PATCH",es(n).relativeUrl,F(n),ts(n))}case"delete":{const n=Xt(e.state);return o("DELETE",Yt(n).relativeUrl,F(n))}case"merge":{const n=Jt(e.state);return o("POST",Kt(n).relativeUrl,F(n),Qt(n))}case"associate":{const n=Gt(e.state),i=F(n),a=Vt(n);return a.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:a.map(r=>ve(`${s} → ${r.targetId}`,s,r.method,r.relativeUrl,ze(r.method,i),r.body))}}case"disassociate":{const n=Ut(e.state),i=F(n),a=Wt(n);return a.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:a.map(r=>ve(r.targetId?`${s} × ${r.targetId}`:s,s,r.method,r.relativeUrl,ze(r.method,i),r.body))}}case"exec-action":{const n=Lt(e.state);return o("POST",Ht(n).relativeUrl,F(n),zt(n))}case"exec-function":{const n=Ft(e.state);return o("GET",_t(n).relativeUrl,F(n))}case"exec-workflow":{const n=Dt(e.state);return o("POST",At(n).relativeUrl,F(n),Nt(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 wn(e){if(e&&typeof e=="object"&&"table"in e){const s=e.table;if(typeof s=="string")return s}return""}async function Sn(e){const s=wn(e.state);s&&await He.getTable(s).catch(()=>{});const o=e.state?.navProperty;if(s&&typeof o=="string"&&o){const n=rt(s)?.navigationProperties.find(i=>i.name===o)?.targetEntity;n&&await He.getTable(n).catch(()=>{})}return $n(e)}const H=`\r
2
+ `;function kn(e){return/^\$\d+/.test(e)?e:`${ne}/${e}`}function En(e,s){const o=s.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===o)}function Ee({contentId:e,wire:s}){const o=["Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${e}`,"",`${s.method} ${kn(s.path)} HTTP/1.1`];for(const[n,i]of Object.entries(s.headers))o.push(`${n}: ${i}`);return s.body!==void 0&&!En(s.headers,"Content-Type")&&o.push("Content-Type: application/json; type=entry"),o.push("",s.body??""),o.join(H)}let Ke=0;function le(e){Ke+=1;const s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(16)}-${Ke.toString(16)}-${Math.random().toString(16).slice(2)}`;return`${e}_${s}`}function mt(e,s={}){const o=s.batch??le("batch");let n=0,i="";for(const a of e)if(a.parts.length!==0)if(a.atomic){const r=s.changeset?.(n)??le("changeset");n+=1,i+=`--${o}${H}Content-Type: multipart/mixed; boundary=${r}${H}${H}`;for(const b of a.parts)i+=`--${r}${H}${Ee(b)}${H}`;i+=`--${r}--${H}`}else for(const r of a.parts)i+=`--${o}${H}${Ee(r)}${H}`;return i+=`--${o}--${H}`,{boundary:o,contentType:`multipart/mixed; boundary=${o}`,body:i}}const ft=/boundary=(?:"([^"]+)"|([^;\s]+))/i;function Tn(e,s){const o=ft.exec(e);if(o)return o[1]||o[2];const n=/^\s*--([^\r\n]+)/.exec(s);return n?n[1].trim():null}function Qe(e){const s={};for(const o of e.split(/\r?\n/)){const n=o.indexOf(":");if(n<=0)continue;const i=o.slice(0,n).trim().toLowerCase(),a=o.slice(n+1).trim();s[i]=s[i]?`${s[i]}, ${a}`:a}return s}function Rn(e,s){const o=`--${s}`,n=[];let i=e.indexOf(o);if(i<0)throw new Error(`Response boundary "${s}" not found.`);for(;i>=0;){if(i+=o.length,e.startsWith("--",i))return n;const a=e.indexOf(o,i);if(a<0)throw new Error("Response is missing its closing boundary.");n.push(e.slice(i,a).replace(/^\r?\n/,"").replace(/\r?\n$/,"")),i=a}return n}function Xe(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 In(e,s=""){const o=Tn(s,e);if(!o)throw new Error("No multipart boundary in the Content-Type or the body.");let n=0;const i=(a,r,b)=>Rn(a,r).flatMap(p=>{const[x,f]=Xe(p),h=Qe(x),c=ft.exec(h["content-type"]??"");if(c){const j=n++;return i(f,c[1]||c[2],j)}const g=f.search(/HTTP\/1\.[01]\s+\d{3}/i);if(g<0)throw new Error("A response part has no HTTP status line.");const[S,C]=Xe(f.slice(g)),[_,...D]=S.split(/\r?\n/),W=/^HTTP\/1\.[01]\s+(\d{3})(?:\s+(.*))?$/i.exec(_.trim());if(!W)throw new Error(`Malformed status line: ${_}`);const T=C.trim();let O;if(T)try{O=JSON.parse(T)}catch{O=T}const m={status:Number(W[1]),statusText:W[2]?.trim()||void 0,headers:Qe(D.join(`
3
3
  `))};return h["content-id"]&&(m.contentId=h["content-id"]),O!==void 0&&(m.body=O),b!==void 0&&(m.changeset=b),[m]});return i(e,o)}const gt={http:"HTTP ($batch)",fetch:"fetch (JavaScript)",pptb:"PPTB dataverseAPI"};function bt(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 Ye(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 Cn=e=>e.replace(/\r\n/g,`
4
- `);function On(e,s){const o=s.orgUrl||"[Organization URI]",n=mt(bt(s.items),s.boundaries);switch(e){case"http":return Cn([`POST ${o}${ne}/$batch HTTP/1.1`,...Ye(n.contentType,s.continueOnError),"",n.body].join(z));case"fetch":{const i=n.body.split(z);i[i.length-1]===""&&i.pop();const a=Ye(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 = [",...i.map(r=>` ${JSON.stringify(r)},`),"].join('\\r\\n') + '\\r\\n';","",`const res = await fetch(${JSON.stringify(`${o}${ne}/$batch`)}, {`," method: 'POST',"," headers: {"," Authorization: `Bearer ${accessToken}`,",...a," },"," 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(`
4
+ `);function On(e,s){const o=s.orgUrl||"[Organization URI]",n=mt(bt(s.items),s.boundaries);switch(e){case"http":return Cn([`POST ${o}${ne}/$batch HTTP/1.1`,...Ye(n.contentType,s.continueOnError),"",n.body].join(H));case"fetch":{const i=n.body.split(H);i[i.length-1]===""&&i.pop();const a=Ye(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 = [",...i.map(r=>` ${JSON.stringify(r)},`),"].join('\\r\\n') + '\\r\\n';","",`const res = await fetch(${JSON.stringify(`${o}${ne}/$batch`)}, {`," method: 'POST',"," headers: {"," Authorization: `Bearer ${accessToken}`,",...a," },"," 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
5
  `)}case"pptb":{if(s.plan.length===0)return"// Add a request to see the host calls.";const i=["// 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&&i.push(`// ${s.plan.length} calls, in order.${s.continueOnError?"":" A failed call stops the rest."}`),s.plan.forEach((a,r)=>{const b=a.items.filter(f=>f.wire).map(pt),p=a.transaction?"executeTransaction":"executeBatch",x=!a.transaction&&s.continueOnError?", undefined, { Prefer: 'odata.continue-on-error' }":"";i.push("",`const results${r+1} = await dataverseAPI.${p}(${JSON.stringify(b,null,2)}${x});`)}),i.push("","// Each result: { contentId, status, statusText, headers, body }"),i.join(`
6
- `).replace(/\\r\\n/g,"\\n")}}}const qn=/^\{?[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),Q=e=>`new Guid(${B(e.replace(/[{}]/g,""))})`;function X(e,s){return s.logicalOf(e)??e.replace(/s$/,"")}function Bn(e){const s=/^([A-Za-z_][\w]*)\(([^)]+)\)$/.exec(e.trim());return s?{set:s[1],id:s[2]}:null}function Mn(e,s,o,n,i){if(o===null)return"null";const a=n.attrType(e,s);switch(a){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 Q(String(o))}return typeof o=="string"?B(o):typeof o=="boolean"?String(o):typeof o=="number"?(a||i.push(`${s}: confirm the type (int / OptionSetValue / Money / decimal)`),String(o)):(i.push(`${s}: nested value not converted`),null)}function Pn(e,s,o,n){const i=[];for(const[a,r]of Object.entries(s)){if(a.endsWith("@odata.bind")){let p=a.slice(0,-11);if(!o.attrType(e,p)&&p.includes("_")){const f=p.slice(0,p.lastIndexOf("_"));o.attrType(e,f)&&(p=f)}const x=typeof r=="string"?Bn(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?i.push(`[${B(p)}] = new EntityReference(${B(X(x.set,o))}, ${Q(x.id)}),`):n.push(`${p}: couldn't convert the @odata.bind value`);continue}if(a.includes("@"))continue;const b=Mn(e,a,r,o,n);b!==null&&i.push(`[${B(a)}] = ${b},`)}return i}function Ze(e){if(!e)return{};try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}}const An=(e,s)=>e.map(o=>" ".repeat(s)+o);function et(e){return e?`new ColumnSet(${e.split(",").map(s=>B(s.trim().replace(/^_(.+)_value$/,"$1"))).join(", ")})`:"new ColumnSet(true)"}function Dn(e,s){const o=e.wire;if(!o)return[`// $${e.contentId}: has errors — fix it in the Builder.`];const n=[],i=[],a=e.item,r=`// $${e.contentId} ${o.method} ${o.path}`,b=f=>(i.push(r,...n.map(h=>`// TODO ${h}`),...f),i),p=qn.test(a.recordId.trim());if(a.op==="create"||a.op==="update"){const f=X(a.entitySet,s);a.op==="update"&&!p&&n.push(`record id ${a.recordId} isn't a GUID — use new Entity(logicalName, keyAttributes) for an alternate key`);const h=a.op==="update"&&p?`new Entity(${B(f)}, ${Q(a.recordId.trim())})`:`new Entity(${B(f)})`,c=Pn(f,Ze(o.body),s,n);return b([`requests.Add(new ${a.op==="create"?"CreateRequest":"UpdateRequest"}`,"{",` Target = ${h}`," {",...An(c,8)," },","});"])}if(a.op==="delete"){const f=X(a.entitySet,s);return p||n.push(`record id ${a.recordId} isn't a GUID`),b([`requests.Add(new DeleteRequest { Target = new EntityReference(${B(f)}, ${Q(a.recordId.trim())}) });`])}if(a.op==="retrieve"){const f=X(a.entitySet,s),h=new URLSearchParams(a.query.trim().replace(/^\?/,"")),c=h.get("$select");if(a.recordId.trim())return b(["requests.Add(new RetrieveRequest","{",` Target = new EntityReference(${B(f)}, ${Q(a.recordId.trim())}),`,` ColumnSet = ${et(c)},`,"});"]);const g=h.get("$top");for(const S of["$filter","$orderby","$expand","$apply","fetchXml"])h.get(S)&&n.push(`translate ${S} into the QueryExpression (or use FetchExpression)`);return b(["requests.Add(new RetrieveMultipleRequest","{",` Query = new QueryExpression(${B(f)})`," {",` ColumnSet = ${et(c)},`,...g?[` TopCount = ${Number(g)},`]:[]," },","});"])}if(a.op==="associate"){const f=X(a.entitySet,s),h=X(a.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(f)}, ${Q(a.recordId.trim())}),`,` Relationship = new Relationship(${B(a.navProperty.trim())}),`,` RelatedEntities = new EntityReferenceCollection { new EntityReference(${B(h)}, ${Q(a.targetId.trim())}) },`,"});"])}const x=/^(?:Microsoft\.Dynamics\.CRM\.)?([A-Za-z_][\w]*)$/.exec(o.path);if(o.method==="POST"&&x&&!s.logicalOf(x[1])){const f=Object.entries(Ze(o.body)).filter(([h])=>!h.includes("@"));return b([`requests.Add(new OrganizationRequest(${B(x[1])})`,"{"," Parameters ="," {",...f.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 Nn(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(i=>[...Dn(i,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 tt=[{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"}],Fn=["GET","POST","PATCH","PUT","DELETE"],_n=[{name:"Prefer",value:"return=representation"},{name:"If-Match",value:"*"},{name:"MSCRM.SuppressDuplicateDetection",value:"false"}],H={fontFamily:$.fontFamilyMonospace,fontSize:12};function Ln({item:e,contentId:s,group:o,groups:n,wire:i,issues:a,onChange:r,onRemove:b,onMove:p,onMoveToGroup:x}){const{entities:f}=it(),h=w.useMemo(()=>f.find(m=>m.entitySetName===e.entitySet.trim())?.logicalName??null,[f,e.entitySet]),{table:c}=vs(e.op==="associate"?h:null),g=w.useMemo(()=>(c?.navigationProperties??[]).filter(js),[c]),S=`drs-batch-sets-${e.id}`,C=`drs-batch-navs-${e.id}`,_=e.op!=="custom",A=e.op==="update"||e.op==="delete"||e.op==="associate",W=e.op==="create"||e.op==="update"||e.op==="custom",E=n.indexOf(o),O=(m,j)=>r({headers:e.headers.map((D,P)=>P===m?{...D,...j}:D)});return t.jsxs("div",{style:{maxWidth:860},children:[t.jsxs(ce,{icon:lt,title:`Request $${s}`,sub:o.atomic?`In change set ${E+1} — rolls back with the rest of the change set if any request fails.`:`In group ${E+1} — independent; runs on its own.`,group:"batch",children:[t.jsx(je,{content:"Move up",relationship:"label",children:t.jsx(I,{icon:t.jsx(ct,{}),appearance:"subtle",onClick:()=>p(-1)})}),t.jsx(je,{content:"Move down",relationship:"label",children:t.jsx(I,{icon:t.jsx(dt,{}),appearance:"subtle",onClick:()=>p(1)})}),t.jsx(I,{icon:t.jsx($e,{}),appearance:"subtle",onClick:b,children:"Remove"})]}),a.length>0&&t.jsx(G,{intent:a.some(m=>m.severity==="error")?"error":"warning",layout:"multiline",style:{marginBottom:12},children:t.jsx(V,{children:a.map((m,j)=>t.jsx("div",{children:m.message},j))})}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:12},children:[t.jsx(L,{label:"Operation",children:t.jsx(fe,{value:tt.find(m=>m.id===e.op)?.label??"",selectedOptions:[e.op],onOptionSelect:(m,j)=>{const D=j.optionValue,P={op:D};(D==="create"||D==="update")&&!e.body.trim()&&(P.body=`{
6
+ `).replace(/\\r\\n/g,"\\n")}}}const qn=/^\{?[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),Q=e=>`new Guid(${B(e.replace(/[{}]/g,""))})`;function X(e,s){return s.logicalOf(e)??e.replace(/s$/,"")}function Bn(e){const s=/^([A-Za-z_][\w]*)\(([^)]+)\)$/.exec(e.trim());return s?{set:s[1],id:s[2]}:null}function Mn(e,s,o,n,i){if(o===null)return"null";const a=n.attrType(e,s);switch(a){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 Q(String(o))}return typeof o=="string"?B(o):typeof o=="boolean"?String(o):typeof o=="number"?(a||i.push(`${s}: confirm the type (int / OptionSetValue / Money / decimal)`),String(o)):(i.push(`${s}: nested value not converted`),null)}function Pn(e,s,o,n){const i=[];for(const[a,r]of Object.entries(s)){if(a.endsWith("@odata.bind")){let p=a.slice(0,-11);if(!o.attrType(e,p)&&p.includes("_")){const f=p.slice(0,p.lastIndexOf("_"));o.attrType(e,f)&&(p=f)}const x=typeof r=="string"?Bn(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?i.push(`[${B(p)}] = new EntityReference(${B(X(x.set,o))}, ${Q(x.id)}),`):n.push(`${p}: couldn't convert the @odata.bind value`);continue}if(a.includes("@"))continue;const b=Mn(e,a,r,o,n);b!==null&&i.push(`[${B(a)}] = ${b},`)}return i}function Ze(e){if(!e)return{};try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}}const Dn=(e,s)=>e.map(o=>" ".repeat(s)+o);function et(e){return e?`new ColumnSet(${e.split(",").map(s=>B(s.trim().replace(/^_(.+)_value$/,"$1"))).join(", ")})`:"new ColumnSet(true)"}function An(e,s){const o=e.wire;if(!o)return[`// $${e.contentId}: has errors — fix it in the Builder.`];const n=[],i=[],a=e.item,r=`// $${e.contentId} ${o.method} ${o.path}`,b=f=>(i.push(r,...n.map(h=>`// TODO ${h}`),...f),i),p=qn.test(a.recordId.trim());if(a.op==="create"||a.op==="update"){const f=X(a.entitySet,s);a.op==="update"&&!p&&n.push(`record id ${a.recordId} isn't a GUID — use new Entity(logicalName, keyAttributes) for an alternate key`);const h=a.op==="update"&&p?`new Entity(${B(f)}, ${Q(a.recordId.trim())})`:`new Entity(${B(f)})`,c=Pn(f,Ze(o.body),s,n);return b([`requests.Add(new ${a.op==="create"?"CreateRequest":"UpdateRequest"}`,"{",` Target = ${h}`," {",...Dn(c,8)," },","});"])}if(a.op==="delete"){const f=X(a.entitySet,s);return p||n.push(`record id ${a.recordId} isn't a GUID`),b([`requests.Add(new DeleteRequest { Target = new EntityReference(${B(f)}, ${Q(a.recordId.trim())}) });`])}if(a.op==="retrieve"){const f=X(a.entitySet,s),h=new URLSearchParams(a.query.trim().replace(/^\?/,"")),c=h.get("$select");if(a.recordId.trim())return b(["requests.Add(new RetrieveRequest","{",` Target = new EntityReference(${B(f)}, ${Q(a.recordId.trim())}),`,` ColumnSet = ${et(c)},`,"});"]);const g=h.get("$top");for(const S of["$filter","$orderby","$expand","$apply","fetchXml"])h.get(S)&&n.push(`translate ${S} into the QueryExpression (or use FetchExpression)`);return b(["requests.Add(new RetrieveMultipleRequest","{",` Query = new QueryExpression(${B(f)})`," {",` ColumnSet = ${et(c)},`,...g?[` TopCount = ${Number(g)},`]:[]," },","});"])}if(a.op==="associate"){const f=X(a.entitySet,s),h=X(a.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(f)}, ${Q(a.recordId.trim())}),`,` Relationship = new Relationship(${B(a.navProperty.trim())}),`,` RelatedEntities = new EntityReferenceCollection { new EntityReference(${B(h)}, ${Q(a.targetId.trim())}) },`,"});"])}const x=/^(?:Microsoft\.Dynamics\.CRM\.)?([A-Za-z_][\w]*)$/.exec(o.path);if(o.method==="POST"&&x&&!s.logicalOf(x[1])){const f=Object.entries(Ze(o.body)).filter(([h])=>!h.includes("@"));return b([`requests.Add(new OrganizationRequest(${B(x[1])})`,"{"," Parameters ="," {",...f.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 Nn(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(i=>[...An(i,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 tt=[{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"}],Fn=["GET","POST","PATCH","PUT","DELETE"],_n=[{name:"Prefer",value:"return=representation"},{name:"If-Match",value:"*"},{name:"MSCRM.SuppressDuplicateDetection",value:"false"}],z={fontFamily:$.fontFamilyMonospace,fontSize:12};function Ln({item:e,contentId:s,group:o,groups:n,wire:i,issues:a,onChange:r,onRemove:b,onMove:p,onMoveToGroup:x}){const{entities:f}=it(),h=w.useMemo(()=>f.find(m=>m.entitySetName===e.entitySet.trim())?.logicalName??null,[f,e.entitySet]),{table:c}=vs(e.op==="associate"?h:null),g=w.useMemo(()=>(c?.navigationProperties??[]).filter(js),[c]),S=`drs-batch-sets-${e.id}`,C=`drs-batch-navs-${e.id}`,_=e.op!=="custom",D=e.op==="update"||e.op==="delete"||e.op==="associate",W=e.op==="create"||e.op==="update"||e.op==="custom",T=n.indexOf(o),O=(m,j)=>r({headers:e.headers.map((A,P)=>P===m?{...A,...j}:A)});return t.jsxs("div",{style:{maxWidth:860},children:[t.jsxs(ce,{icon:lt,title:`Request $${s}`,sub:o.atomic?`In change set ${T+1} — rolls back with the rest of the change set if any request fails.`:`In group ${T+1} — independent; runs on its own.`,group:"batch",children:[t.jsx(je,{content:"Move up",relationship:"label",children:t.jsx(I,{icon:t.jsx(ct,{}),appearance:"subtle",onClick:()=>p(-1)})}),t.jsx(je,{content:"Move down",relationship:"label",children:t.jsx(I,{icon:t.jsx(dt,{}),appearance:"subtle",onClick:()=>p(1)})}),t.jsx(I,{icon:t.jsx($e,{}),appearance:"subtle",onClick:b,children:"Remove"})]}),a.length>0&&t.jsx(G,{intent:a.some(m=>m.severity==="error")?"error":"warning",layout:"multiline",style:{marginBottom:12},children:t.jsx(V,{children:a.map((m,j)=>t.jsx("div",{children:m.message},j))})}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:12},children:[t.jsx(L,{label:"Operation",children:t.jsx(fe,{value:tt.find(m=>m.id===e.op)?.label??"",selectedOptions:[e.op],onOptionSelect:(m,j)=>{const A=j.optionValue,P={op:A};(A==="create"||A==="update")&&!e.body.trim()&&(P.body=`{
8
8
 
9
- }`),r(P)},children:tt.map(m=>t.jsx(ge,{value:m.id,children:m.label},m.id))})}),n.length>1&&t.jsx(L,{label:"Group",children:t.jsx(fe,{value:`${o.atomic?"Change set":"Independent"} ${E+1}`,selectedOptions:[o.id],onOptionSelect:(m,j)=>j.optionValue&&x(j.optionValue),children:n.map((m,j)=>t.jsx(ge,{value:m.id,children:`${m.atomic?"Change set":"Independent"} ${j+1}`},m.id))})}),t.jsx(L,{label:"Label (optional)",children:t.jsx(U,{value:e.label,onChange:(m,j)=>r({label:j.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(L,{label:"Method",children:t.jsx(fe,{value:e.method,selectedOptions:[e.method],onOptionSelect:(m,j)=>r({method:j.optionValue}),children:Fn.map(m=>t.jsx(ge,{value:m,children:m},m))})}),t.jsx(L,{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(U,{value:e.url,onChange:(m,j)=>r({url:j.value}),input:{style:H}})})]}),_&&t.jsx(L,{label:e.op==="associate"?"Source table (entity set)":"Table (entity set)",children:t.jsx(U,{value:e.entitySet,onChange:(m,j)=>r({entitySet:j.value}),placeholder:"accounts",input:{list:S,style:H}})}),(A||e.op==="retrieve")&&t.jsx(L,{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(U,{value:e.recordId,onChange:(m,j)=>r({recordId:j.value}),placeholder:"00000000-0000-0000-0000-000000000000",input:{style:H}})}),e.op==="retrieve"&&t.jsx(L,{label:"Query options",hint:"Without the leading ?",children:t.jsx(U,{value:e.query,onChange:(m,j)=>r({query:j.value}),placeholder:"$select=name&$top=10",input:{style:H}})}),e.op==="associate"&&t.jsxs(t.Fragment,{children:[t.jsx(L,{label:"Navigation property (collection-valued)",children:t.jsx(U,{value:e.navProperty,onChange:(m,j)=>r({navProperty:j.value}),placeholder:"contact_customer_accounts",input:{list:C,style:H}})}),t.jsx(L,{label:"Target table (entity set)",children:t.jsx(U,{value:e.targetSet,onChange:(m,j)=>r({targetSet:j.value}),placeholder:"contacts",input:{list:S,style:H}})}),t.jsx(L,{label:"Target record id",hint:"GUID or $n",children:t.jsx(U,{value:e.targetId,onChange:(m,j)=>r({targetId:j.value}),input:{style:H}})})]})]}),t.jsx("datalist",{id:S,children:f.map(m=>t.jsx("option",{value:m.entitySetName,children:m.displayName},m.logicalName))}),t.jsx("datalist",{id:C,children:g.map(m=>t.jsx("option",{value:m.name,children:m.targetEntity},m.name))}),W&&t.jsx(L,{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(ut,{value:e.body,onChange:(m,j)=>r({body:j.value}),resize:"vertical",rows:8,textarea:{style:H,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:$.colorNeutralForeground3},children:"Sent inside this part. Power Platform ToolBox asks you to approve them the first time."})]}),e.headers.map((m,j)=>t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:6,alignItems:"center"},children:[t.jsx(we,{checked:m.enabled,onChange:(D,P)=>O(j,{enabled:P.checked}),"aria-label":`Send ${m.name||"header"}`}),t.jsx(U,{value:m.name,onChange:(D,P)=>O(j,{name:P.value}),placeholder:"Name","aria-label":"Header name",input:{style:H},style:{flex:"1 1 0",minWidth:0}}),t.jsx(U,{value:m.value,onChange:(D,P)=>O(j,{value:P.value}),placeholder:"Value","aria-label":"Header value",input:{style:H},style:{flex:"2 1 0",minWidth:0}}),t.jsx(I,{icon:t.jsx($e,{}),appearance:"subtle","aria-label":"Remove header",onClick:()=>r({headers:e.headers.filter((D,P)=>P!==j)})})]},j)),t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[t.jsx(I,{size:"small",icon:t.jsx(ie,{}),onClick:()=>r({headers:[...e.headers,{name:"",value:"",enabled:!0}]}),children:"Header"}),_n.filter(m=>!e.headers.some(j=>j.name.toLowerCase()===m.name.toLowerCase())).map(m=>t.jsxs(I,{size:"small",appearance:"subtle",onClick:()=>r({headers:[...e.headers,{...m,enabled:!0}]}),children:["+ ",m.name,": ",m.value]},m.name))]})]}),i&&t.jsxs("div",{style:{marginTop:16},children:[t.jsx("strong",{style:{fontSize:13},children:"Part preview"}),t.jsx("pre",{style:{...H,background:$.colorNeutralBackground1,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:4,padding:10,marginTop:6,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:Te({contentId:s,wire:i}).replace(/\r\n/g,`
10
- `)})]}),e.source&&t.jsxs(M,{style:{color:$.colorNeutralForeground3},children:["From: ",e.source]})]})}const zn=[{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 Hn({onAdd:e,label:s="Add request",disabledGet:o}){return t.jsxs(ks,{children:[t.jsx(Ts,{disableButtonEnhancement:!0,children:t.jsx(I,{icon:t.jsx(ie,{}),children:s})}),t.jsx(Es,{children:t.jsx(Rs,{children:zn.filter(n=>!(o&&n.id==="retrieve")).map(n=>t.jsx(Is,{onClick:()=>e(n.id),children:n.label},n.id))})})]})}function Un({groups:e,continueOnError:s,setContinueOnError:o,plan:n,unavailable:i,needsConsent:a,orgUrl:r,onAddGroup:b,onOpenSaved:p,onAddLast:x,lastLabel:f,onSelect:h,notice:c,variant:g="batch",returnResponses:S=!0,setReturnResponses:C}){const _=e.reduce((E,O)=>E+O.items.length,0),A=g==="execute-multiple";let W=0;return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ce,{icon:ws,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(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsx(te,{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)."]})}),i&&t.jsx(G,{intent:"warning",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsx(te,{children:"Can’t send from here"}),i," You can still compose the batch and copy it from the Code tab."]})}),c&&t.jsx(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsx(V,{children:c})}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:16},children:[A?e[0]&&t.jsx(I,{icon:t.jsx(ie,{}),onClick:()=>h(`group:${e[0].id}`),children:"Add request"}):t.jsxs(t.Fragment,{children:[t.jsx(I,{icon:t.jsx(Re,{}),onClick:()=>b(!0),children:"Add change set"}),t.jsx(I,{icon:t.jsx(Ie,{}),onClick:()=>b(!1),children:"Add independent group"})]}),t.jsx(I,{icon:t.jsx(ie,{}),onClick:p,children:"Add from Saved…"}),t.jsx(I,{icon:t.jsx(Ss,{}),onClick:x,disabled:!f,children:f?`Add last request (${f})`:"Add last request"})]}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,background:$.colorNeutralBackground1,marginBottom:16},children:[t.jsx(we,{checked:s,onChange:(E,O)=>o(O.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:$.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&&C&&t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,background:$.colorNeutralBackground1,marginBottom:16},children:[t.jsx(we,{checked:S,onChange:(E,O)=>C(O.checked),"aria-label":"ReturnResponses"}),t.jsxs("div",{children:[t.jsx("strong",{children:"ReturnResponses"}),t.jsx(M,{block:!0,style:{color:$.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#."})]})]}),a&&t.jsx(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsx(te,{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(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsxs(te,{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(E=>E.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:[_," request",_===1?"":"s"]})," ","in ",e.length," group",e.length===1?"":"s"]}),e.map((E,O)=>t.jsxs("div",{style:{border:`1px solid ${$.colorNeutralStroke2}`,borderLeft:`3px solid ${E.atomic?"var(--color-request-batch)":$.colorNeutralStroke1}`,borderRadius:6,padding:"8px 12px",marginBottom:8,background:$.colorNeutralBackground1},children:[t.jsx(I,{appearance:"transparent",onClick:()=>h(`group:${E.id}`),style:{padding:0},children:t.jsx("strong",{children:A?"Requests":E.atomic?`Change set ${O+1}`:`Independent group ${O+1}`})}),E.items.length===0&&t.jsx(M,{block:!0,style:{color:$.colorNeutralForeground3},children:"Empty — skipped when sent."}),E.items.map(m=>{W+=1;const j=oe(m,r);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>h(`item:${m.id}`),onKeyDown:D=>(D.key==="Enter"||D.key===" ")&&h(`item:${m.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"3px 0",cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:$.colorNeutralForeground3},children:["$",W]}),t.jsx(Ce,{method:j.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.path||"—"}),m.label&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:m.label})]},m.id)})]},E.id))]})}function Wn({group:e,index:s,count:o,contentIdOf:n,orgUrl:i,onSetAtomic:a,onAdd:r,onRemoveGroup:b,onMoveGroup:p,onSelect:x,variant:f="batch"}){const h=e.items.some(g=>oe(g,i).method==="GET"),c=f==="execute-multiple";return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ce,{icon:e.atomic?Re:Ie,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(I,{icon:t.jsx(ct,{}),appearance:"subtle","aria-label":"Move group up",disabled:s===0,onClick:()=>p(-1)}),t.jsx(I,{icon:t.jsx(dt,{}),appearance:"subtle","aria-label":"Move group down",disabled:s===o-1,onClick:()=>p(1)}),t.jsx(I,{icon:t.jsx($e,{}),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($s,{ariaLabel:"Group kind",children:[t.jsx(Ue,{checked:e.atomic,onClick:()=>a(!0),children:"Change set (atomic)"}),t.jsx(Ue,{checked:!e.atomic,onClick:()=>a(!1),children:"Independent"})]}),t.jsx(Hn,{onAdd:r,disabledGet:e.atomic})]}),e.atomic&&h&&t.jsx(G,{intent:"error",style:{marginBottom:12},children:t.jsx(V,{children:"This change set holds a GET request. Move it to an independent group."})}),e.items.length===0&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:"No requests yet."}),e.items.map(g=>{const S=oe(g,i);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>x(`item:${g.id}`),onKeyDown:C=>(C.key==="Enter"||C.key===" ")&&x(`item:${g.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"6px 8px",borderBottom:`1px solid ${$.colorNeutralStroke3}`,cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:$.colorNeutralForeground3},children:["$",n(g.id)]}),t.jsx(Ce,{method:S.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.path||"—"}),g.label&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:g.label})]},g.id)})]})}const se={fontFamily:$.fontFamilyMonospace,fontSize:12};function st(e){return e.outcome!=="done"?e.outcome==="rolled-back"?"warning":"info":e.status===void 0?"info":e.status>=400?"danger":"success"}function Ee(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 nt({r:e}){const s=Ee(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 ${$.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:$.colorNeutralForeground3},children:["$",e.contentId]}),e.method&&t.jsx(Ce,{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(Se,{status:st(e),code:n}):t.jsx(Se,{status:st(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(G,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsx(V,{children:s})}),o&&t.jsxs("div",{style:{...se,marginBottom:6},children:["OData-EntityId: ",t.jsx("code",{children:o})]}),e.headers&&Object.keys(e.headers).length>0&&t.jsx("pre",{style:{...se,margin:"0 0 8px",whiteSpace:"pre-wrap"},children:Object.entries(e.headers).map(([i,a])=>`${i}: ${a}`).join(`
11
- `)}),e.body!==void 0&&t.jsx("pre",{style:{...se,margin:0,whiteSpace:"pre-wrap",wordBreak:"break-all",background:$.colorNeutralBackground1,border:`1px solid ${$.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:$.colorNeutralForeground3},children:"No response body."}),e.outcome==="rolled-back"&&t.jsx(M,{block:!0,style:{color:$.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:$.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:$.colorNeutralForeground3},children:"An earlier failure stopped the batch before this request ran."})]})]})}function Gn({run:e,rows:s,extraTitle:o}){const[n,i]=w.useState(""),[a,r]=w.useState(null),[b,p]=w.useState(null),x=()=>{try{r(In(n)),p(null)}catch(c){r(null),p(c instanceof Error?c.message:String(c))}},f=(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(S=>S.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(C=>{const _=c.get(C);return _?.outcome==="done"&&(_.status??0)>=400})&&f.other>0&&(f.failed+=1,f.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(Se,{status:e.ok?"success":"danger",code:e.ok?200:"Failed",ms:e.ms}),t.jsxs("span",{style:{fontSize:13},children:[f.ok," succeeded · ",f.failed," failed",f.other?` · ${f.other} rolled back or not run`:"",f.noResult?` · ${f.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(G,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsxs(V,{children:[t.jsxs(te,{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??""} — ${Ee(c.changesetError.body)??"see the response body below"}`,c.changesetError?.body!==void 0&&!Ee(c.changesetError.body)&&t.jsx("pre",{style:{...se,whiteSpace:"pre-wrap"},children:JSON.stringify(c.changesetError.body,null,2)})]})},g):null),t.jsx("div",{style:{background:$.colorNeutralBackground1,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,padding:"0 8px"},children:s.map(c=>t.jsx(nt,{r:c},c.key))})]}):t.jsx(M,{block:!0,style:{color:$.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(Cs,{style:{verticalAlign:"middle",marginRight:6}}),"Inspect a raw $batch response from another client"]}),t.jsxs("div",{style:{marginTop:8},children:[t.jsx(ut,{value:n,onChange:(c,g)=>i(g.value),placeholder:"--batchresponse_…",rows:8,resize:"vertical",textarea:{style:se,spellCheck:!1},style:{width:"100%"},"aria-label":"Raw $batch response"}),t.jsx(I,{style:{marginTop:8},onClick:x,disabled:!n.trim(),children:"Parse response"}),b&&t.jsx(G,{intent:"error",style:{marginTop:8},children:t.jsx(V,{children:b})}),a&&t.jsx("div",{style:{marginTop:8},children:a.map((c,g)=>t.jsx(nt,{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 ot({formats:e,labels:s,generate:o,note:n,crlfFormats:i=["http"]}){const[a,r]=w.useState(e[0]),[b,p]=w.useState(!1),x=o(a);return t.jsxs("div",{children:[t.jsx(ce,{icon:Os,title:"Code",sub:n,group:"batch",children:t.jsx(je,{content:"Copy",relationship:"label",children:t.jsx(I,{icon:t.jsx(Bs,{}),appearance:"subtle",onClick:()=>{qs(x).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},children:b?"Copied":"Copy"})})}),t.jsx(Ms,{selectedValue:a,onTabSelect:(f,h)=>r(h.value),size:"small",children:e.map(f=>t.jsx(Ps,{value:f,children:s[f]},f))}),t.jsx("pre",{style:{fontFamily:$.fontFamilyMonospace,fontSize:12,lineHeight:1.5,background:$.colorNeutralBackground1,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,padding:12,marginTop:8,whiteSpace:"pre",overflow:"auto",maxHeight:"calc(100vh - 260px)"},children:x}),i.includes(a)&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:"Line breaks in a $batch body are CRLF on the wire."})]})}function Vn({open:e,onClose:s,onAdd:o}){const{saved:n}=As(),[i,a]=w.useState(new Set),[r,b]=w.useState(""),p=Ds(),x=w.useMemo(()=>n.filter(h=>vn.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]),f=()=>{a(new Set),b(""),s()};return t.jsx(Ns,{open:e,onOpenChange:(h,c)=>!c.open&&f(),children:t.jsx(Fs,{style:{maxWidth:640},children:t.jsxs(_s,{children:[t.jsx(Ls,{children:"Add saved requests to the batch"}),t.jsxs(zs,{children:[t.jsx(U,{value:r,onChange:(h,c)=>b(c.value),placeholder:"Filter by name",contentBefore:t.jsx(Hs,{}),style:{width:"100%",marginBottom:8},"aria-label":"Filter saved requests"}),x.length===0&&t.jsx(M,{block:!0,style:{color:$.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(Us,{checked:i.has(h.id),onChange:(c,g)=>a(S=>{const C=new Set(S);return g.checked?C.add(h.id):C.delete(h.id),C}),label:t.jsxs("span",{children:[h.name," ",t.jsx(M,{style:{color:$.colorNeutralForeground3},children:ke(h.modeId).name})]})})},h.id))})]}),t.jsxs(Ws,{children:[t.jsx(I,{appearance:"secondary",onClick:f,children:"Cancel"}),t.jsxs(I,{appearance:"primary",disabled:i.size===0,onClick:()=>{o(x.filter(h=>i.has(h.id))),f()},children:["Add ",i.size||""]})]})]})})})}const Jn=["http","fetch","pptb"],Kn=["csharp","http","pptb"],Qn={...gt,csharp:"ExecuteMultipleRequest (C#)",http:"Web API equivalent ($batch)"},Xn=new Set(["bulk-delete","bulk-write","batch","execute-multiple"]);function Zn({themeMode:e,variant:s="batch"}){const o=s==="execute-multiple",n=o?"execute-multiple":"batch",i=ke(n),a=Gs(n,We,o?Vs:Js),[r,b]=w.useState(a.state),p=r.returnResponses??!0,{entities:x}=it(),[f,h]=w.useState("overview"),[c,g]=w.useState("builder"),[S,C]=w.useState(null),[_,A]=w.useState(!1),[W,E]=w.useState([]),[O,m]=w.useState(!1),[j,D]=w.useState(null),[P,Oe]=w.useState(a.lastSavedId),[de,qe]=w.useState(a.lastSavedHash),K=Ge.host?`https://${Ge.host}`:"",q=w.useMemo(()=>Ks(r.groups,K),[r.groups,K]),re=w.useMemo(()=>Qs(q.items),[q]),Be=yn(),ue=(l,d)=>{const u=new Set(l.dirty);return u.add(d),{...l,dirty:u}},J=w.useCallback((l,d="batch")=>b(u=>ue({...u,groups:l(u.groups)},d)),[]),xt=(l,d)=>J(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&&(J(y=>{let v=y.find(R=>R.id===l);const k=d.some(R=>oe(R,K).method==="GET");if((!v||v.atomic&&k)&&(v=[...y].reverse().find(R=>k?!R.atomic:!0)),!v){const R=Ve(!k,d);return[...y,R]}const T=v.id;return y.map(R=>R.id===T?{...R,items:[...R.items,...d]}:R)}),u&&(h(`item:${d[0].id}`),g("builder")))},yt=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},vt=(l,d)=>J(u=>{const y=u.findIndex(N=>N.items.some(Bt=>Bt.id===l));if(y<0)return u;const v=u[y].items,k=v.findIndex(N=>N.id===l),T=u.map(N=>({...N,items:[...N.items]})),R=k+d;if(R>=0&&R<v.length)[T[y].items[k],T[y].items[R]]=[T[y].items[R],T[y].items[k]];else if(u[y+d]){const[N]=T[y].items.splice(k,1);d<0?T[y-1].items.push(N):T[y+1].items.unshift(N)}return T}),jt=(l,d)=>J(u=>{const y=u.flatMap(v=>v.items).find(v=>v.id===l);return y?u.map(v=>{const k=v.items.filter(T=>T.id!==l);return v.id===d?{...v,items:[...k,y]}:{...v,items:k}}):u}),he=Xs(),Y=he&&!Xn.has(he.modeId)?he:null,Pe=Y?ke(Y.modeId).name:null,Ae=async l=>{const d=[],u=[];for(const v of l){const k=await Sn(v);k.ok?d.push(...k.items):u.push(`“${v.name}” (${k.reason})`)}const y=f.startsWith("group:")?f.slice(6):null;Me(y,d,!1),D([d.length?`Added ${d.length} request${d.length===1?"":"s"}.`:"",u.length?`Skipped ${u.join(", ")}.`:""].filter(Boolean).join(" ")||null)},De=w.useMemo(()=>{const l=q.issues.map((u,y)=>{const v=u.target?u.target.startsWith("g")?`group:${u.target}`:`item:${u.target}`:"overview",k=q.items.find(R=>R.item.id===u.target),T=k?`$${k.contentId}: ${u.message}`:u.message;return u.severity==="error"?be.err(`batch-${y}`,"validation",T,void 0,v):be.warn(`batch-${y}`,"validation",T,void 0,v)}),d=q.items.filter(u=>u.wire?.method==="DELETE").length;return d>0&&l.push(be.warn("batch-deletes","validation",`This batch deletes ${d} record${d===1?"":"s"}`,"Deletes in a batch run without the Delete mode’s confirmation. Check the ids first.","overview")),l},[q]),$t=Be??Ys(De),wt=q.items.some(l=>l.wire&&Object.keys(l.wire.headers).length>0)||r.continueOnError&&re.some(l=>!l.transaction),St=async()=>{A(!0);try{const l=await xn(re,{continueOnError:r.continueOnError});C(l);const{status:d,summary:u,succeeded:y}=pn(l);E(v=>[{id:`r-${Date.now()}`,modeId:n,url:`${ne}/$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")}},kt=w.useMemo(()=>S?(o&&!p?S.items.filter(d=>d.outcome!=="done"||(d.status??0)>=400):S.items).map(d=>{const u=q.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}}):[],[S,q,o,p]),Ne=w.useRef({batch:le("batch"),cs:[]}),pe=w.useMemo(()=>({batch:Ne.current.batch,changeset:l=>{var d;return(d=Ne.current.cs)[l]??(d[l]=le("changeset"))}}),[]),Tt=w.useMemo(()=>new TextEncoder().encode(mt(bt(q.items),pe).body).length,[q,pe]),Fe=l=>On(l,{items:q.items,plan:re,continueOnError:r.continueOnError,orgUrl:K,boundaries:pe}),Et=l=>l==="csharp"?Nn(q.items,{continueOnError:r.continueOnError,returnResponses:p},{logicalOf:d=>x.find(u=>u.entitySetName===d)?.logicalName??null,attrType:(d,u)=>rt(d)?.columns.find(y=>y.logicalName===u)?.attributeType??null}):Fe(l),Z=w.useMemo(()=>Zs(r),[r]);en(n,Z,P,de);const Rt=w.useMemo(()=>xe(Z),[Z]),_e=de===null?!0:Rt!==de,ae=q.items.length,It=l=>{Oe(l.id),qe(xe(l.state))},Ct=l=>{if(l.modeId!==n)return;const d=l.state;b(We(d)),Oe(l.id),qe(xe(d)),C(null),h("overview")};tn(w.useMemo(()=>({state:Z,modeId:n,dirty:_e,lastSavedId:P,onSaved:It,onLoadSaved:Ct}),[Z,_e,P]));const me=l=>q.issues.filter(d=>d.target===l),Ot=l=>S?.items.find(d=>d.itemId===l),qt=[{id:"batch",label:o?"ExecuteMultiple":"Batch",meta:`${ae} request${ae===1?"":"s"}`,items:[{id:"overview",icon:nn,iconFilled:sn,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?Re:Ie,iconFilled:l.atomic?on:rn,label:o?"Add request":l.atomic?"Atomic group":"Independent requests",badge:me(l.id).length||null,badgeColor:"danger"},...l.items.map(u=>{const y=q.items.find(N=>N.item.id===u.id),v=oe(u,K),k=me(u.id).filter(N=>N.severity==="error").length,T=Ot(u.id),R=k?`${k} issue${k===1?"":"s"}`:T?T.status!==void 0?T.status:T.outcome==="rolled-back"?"rolled back":T.outcome==="unknown"?"no result":"not run":null;return{id:`item:${u.id}`,icon:lt,iconFilled:an,label:`$${y?.contentId??"?"} ${v.method} ${u.label||v.path||"…"}`,code:!0,badge:R,badgeAppearance:"tint",badgeColor:k||T&&(T.outcome!=="done"||(T.status??0)>=400)?"danger":"success",dirty:r.dirty.has(`item:${u.id}`)}})]}))];let ee=null;if(f.startsWith("item:")){const l=yt(f.slice(5)),d=l&&q.items.find(u=>u.item.id===l.item.id);l&&d&&(ee=t.jsx(Ln,{item:l.item,contentId:d.contentId,group:l.group,groups:r.groups,wire:d.wire,issues:me(l.item.id),onChange:u=>xt(l.item.id,u),onRemove:()=>{J(u=>u.map(y=>({...y,items:y.items.filter(v=>v.id!==l.item.id)}))),h(`group:${l.group.id}`)},onMove:u=>vt(l.item.id,u),onMoveToGroup:u=>jt(l.item.id,u)},l.item.id))}else if(f.startsWith("group:")){const l=r.groups.findIndex(u=>u.id===f.slice(6)),d=r.groups[l];d&&(ee=t.jsx(Wn,{group:d,index:l,count:r.groups.length,variant:s,orgUrl:K,contentIdOf:u=>q.items.find(y=>y.item.id===u)?.contentId??"?",onSetAtomic:u=>J(y=>y.map(v=>v.id===d.id?{...v,atomic:u}:v)),onAdd:u=>Me(d.id,[at(u)]),onRemoveGroup:()=>{J(u=>u.filter(y=>y.id!==d.id)),h("overview")},onMoveGroup:u=>J(y=>{const v=[...y],k=l+u;return k<0||k>=v.length?y:([v[l],v[k]]=[v[k],v[l]],v)}),onSelect:h}))}return ee||(ee=t.jsx(Un,{variant:s,returnResponses:p,setReturnResponses:l=>b(d=>ue({...d,returnResponses:l},"overview")),groups:r.groups,continueOnError:r.continueOnError,setContinueOnError:l=>b(d=>ue({...d,continueOnError:l},"overview")),plan:re,unavailable:Be,needsConsent:wt,orgUrl:K,onAddGroup:l=>{const d=Ve(l);J(u=>[...u,d]),h(`group:${d.id}`)},onOpenSaved:()=>m(!0),onAddLast:()=>{Y&&Ae([{...Y,name:Pe??Y.modeId}])},lastLabel:Pe,onSelect:h,notice:j})),t.jsxs(ln,{sidebar:t.jsx(un,{type:i,urlPreview:`/$batch · ${ae} request${ae===1?"":"s"}${o?" · ExecuteMultiple":""}`,sections:qt,activeNode:f,onSelect:l=>{h(l),g("builder")},recents:W}),urlBar:t.jsx(dn,{method:"BATCH",url:`${ne}/$batch`,bytes:Tt,executeVerb:i.executeVerb,disabledReason:$t,loading:_,onExecute:St,advisories:De,onAdvisoryFocus:l=>{h(l),g("builder")}}),children:[t.jsxs(cn,{tab:c,onTabChange:g,resultCount:S?S.items.length:null,children:[c==="builder"&&ee,c==="code"&&o&&t.jsx(ot,{formats:Kn,labels:Qn,generate:Et,note:"DRS sends these requests as a Web API $batch; the C# is the SDK form."}),c==="code"&&!o&&t.jsx(ot,{formats:Jn,labels:gt,generate:Fe,note:q.issues.some(l=>l.severity==="error")?"Requests with errors are left out until they’re fixed.":void 0}),c==="results"&&t.jsx(Gn,{run:S,rows:kt,extraTitle:o&&!p&&S?"ReturnResponses = false: only faults are listed.":void 0})]}),t.jsx(Vn,{open:O,onClose:()=>m(!1),onAdd:l=>{Ae(l.map(d=>({modeId:d.modeId,state:d.state,name:d.name})))}})]})}export{Zn as BatchMode};
9
+ }`),r(P)},children:tt.map(m=>t.jsx(ge,{value:m.id,children:m.label},m.id))})}),n.length>1&&t.jsx(L,{label:"Group",children:t.jsx(fe,{value:`${o.atomic?"Change set":"Independent"} ${T+1}`,selectedOptions:[o.id],onOptionSelect:(m,j)=>j.optionValue&&x(j.optionValue),children:n.map((m,j)=>t.jsx(ge,{value:m.id,children:`${m.atomic?"Change set":"Independent"} ${j+1}`},m.id))})}),t.jsx(L,{label:"Label (optional)",children:t.jsx(U,{value:e.label,onChange:(m,j)=>r({label:j.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(L,{label:"Method",children:t.jsx(fe,{value:e.method,selectedOptions:[e.method],onOptionSelect:(m,j)=>r({method:j.optionValue}),children:Fn.map(m=>t.jsx(ge,{value:m,children:m},m))})}),t.jsx(L,{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(U,{value:e.url,onChange:(m,j)=>r({url:j.value}),input:{style:z}})})]}),_&&t.jsx(L,{label:e.op==="associate"?"Source table (entity set)":"Table (entity set)",children:t.jsx(U,{value:e.entitySet,onChange:(m,j)=>r({entitySet:j.value}),placeholder:"accounts",input:{list:S,style:z}})}),(D||e.op==="retrieve")&&t.jsx(L,{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(U,{value:e.recordId,onChange:(m,j)=>r({recordId:j.value}),placeholder:"00000000-0000-0000-0000-000000000000",input:{style:z}})}),e.op==="retrieve"&&t.jsx(L,{label:"Query options",hint:"Without the leading ?",children:t.jsx(U,{value:e.query,onChange:(m,j)=>r({query:j.value}),placeholder:"$select=name&$top=10",input:{style:z}})}),e.op==="associate"&&t.jsxs(t.Fragment,{children:[t.jsx(L,{label:"Navigation property (collection-valued)",children:t.jsx(U,{value:e.navProperty,onChange:(m,j)=>r({navProperty:j.value}),placeholder:"contact_customer_accounts",input:{list:C,style:z}})}),t.jsx(L,{label:"Target table (entity set)",children:t.jsx(U,{value:e.targetSet,onChange:(m,j)=>r({targetSet:j.value}),placeholder:"contacts",input:{list:S,style:z}})}),t.jsx(L,{label:"Target record id",hint:"GUID or $n",children:t.jsx(U,{value:e.targetId,onChange:(m,j)=>r({targetId:j.value}),input:{style:z}})})]})]}),t.jsx("datalist",{id:S,children:f.map(m=>t.jsx("option",{value:m.entitySetName,children:m.displayName},m.logicalName))}),t.jsx("datalist",{id:C,children:g.map(m=>t.jsx("option",{value:m.name,children:m.targetEntity},m.name))}),W&&t.jsx(L,{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(ut,{value:e.body,onChange:(m,j)=>r({body:j.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:$.colorNeutralForeground3},children:"Sent inside this part. Power Platform ToolBox asks you to approve them the first time."})]}),e.headers.map((m,j)=>t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:6,alignItems:"center"},children:[t.jsx(we,{checked:m.enabled,onChange:(A,P)=>O(j,{enabled:P.checked}),"aria-label":`Send ${m.name||"header"}`}),t.jsx(U,{value:m.name,onChange:(A,P)=>O(j,{name:P.value}),placeholder:"Name","aria-label":"Header name",input:{style:z},style:{flex:"1 1 0",minWidth:0}}),t.jsx(U,{value:m.value,onChange:(A,P)=>O(j,{value:P.value}),placeholder:"Value","aria-label":"Header value",input:{style:z},style:{flex:"2 1 0",minWidth:0}}),t.jsx(I,{icon:t.jsx($e,{}),appearance:"subtle","aria-label":"Remove header",onClick:()=>r({headers:e.headers.filter((A,P)=>P!==j)})})]},j)),t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[t.jsx(I,{size:"small",icon:t.jsx(ie,{}),onClick:()=>r({headers:[...e.headers,{name:"",value:"",enabled:!0}]}),children:"Header"}),_n.filter(m=>!e.headers.some(j=>j.name.toLowerCase()===m.name.toLowerCase())).map(m=>t.jsxs(I,{size:"small",appearance:"subtle",onClick:()=>r({headers:[...e.headers,{...m,enabled:!0}]}),children:["+ ",m.name,": ",m.value]},m.name))]})]}),i&&t.jsxs("div",{style:{marginTop:16},children:[t.jsx("strong",{style:{fontSize:13},children:"Part preview"}),t.jsx("pre",{style:{...z,background:$.colorNeutralBackground1,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:4,padding:10,marginTop:6,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:Ee({contentId:s,wire:i}).replace(/\r\n/g,`
10
+ `)})]}),e.source&&t.jsxs(M,{style:{color:$.colorNeutralForeground3},children:["From: ",e.source]})]})}const Hn=[{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 zn({onAdd:e,label:s="Add request",disabledGet:o}){return t.jsxs(ks,{children:[t.jsx(Es,{disableButtonEnhancement:!0,children:t.jsx(I,{icon:t.jsx(ie,{}),children:s})}),t.jsx(Ts,{children:t.jsx(Rs,{children:Hn.filter(n=>!(o&&n.id==="retrieve")).map(n=>t.jsx(Is,{onClick:()=>e(n.id),children:n.label},n.id))})})]})}function Un({groups:e,continueOnError:s,setContinueOnError:o,plan:n,unavailable:i,needsConsent:a,orgUrl:r,onAddGroup:b,onOpenSaved:p,onAddLast:x,lastLabel:f,onSelect:h,notice:c,variant:g="batch",returnResponses:S=!0,setReturnResponses:C}){const _=e.reduce((T,O)=>T+O.items.length,0),D=g==="execute-multiple";let W=0;return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ce,{icon:ws,title:D?"ExecuteMultiple":"$batch request",sub:D?"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"}),D&&t.jsx(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsx(te,{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)."]})}),i&&t.jsx(G,{intent:"warning",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsx(te,{children:"Can’t send from here"}),i," You can still compose the batch and copy it from the Code tab."]})}),c&&t.jsx(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsx(V,{children:c})}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:16},children:[D?e[0]&&t.jsx(I,{icon:t.jsx(ie,{}),onClick:()=>h(`group:${e[0].id}`),children:"Add request"}):t.jsxs(t.Fragment,{children:[t.jsx(I,{icon:t.jsx(Re,{}),onClick:()=>b(!0),children:"Add change set"}),t.jsx(I,{icon:t.jsx(Ie,{}),onClick:()=>b(!1),children:"Add independent group"})]}),t.jsx(I,{icon:t.jsx(ie,{}),onClick:p,children:"Add from Saved…"}),t.jsx(I,{icon:t.jsx(Ss,{}),onClick:x,disabled:!f,children:f?`Add last request (${f})`:"Add last request"})]}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,background:$.colorNeutralBackground1,marginBottom:16},children:[t.jsx(we,{checked:s,onChange:(T,O)=>o(O.checked),"aria-label":"Continue on error"}),t.jsxs("div",{children:[t.jsx("strong",{children:D?"ContinueOnError":"Continue on error"})," ",t.jsx("code",{style:{fontSize:12},children:"Prefer: odata.continue-on-error"}),t.jsx(M,{block:!0,style:{color:$.colorNeutralForeground3},children:D?"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."})]})]}),D&&C&&t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,background:$.colorNeutralBackground1,marginBottom:16},children:[t.jsx(we,{checked:S,onChange:(T,O)=>C(O.checked),"aria-label":"ReturnResponses"}),t.jsxs("div",{children:[t.jsx("strong",{children:"ReturnResponses"}),t.jsx(M,{block:!0,style:{color:$.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#."})]})]}),a&&t.jsx(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsx(te,{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(G,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(V,{children:[t.jsxs(te,{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(T=>T.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:[_," request",_===1?"":"s"]})," ","in ",e.length," group",e.length===1?"":"s"]}),e.map((T,O)=>t.jsxs("div",{style:{border:`1px solid ${$.colorNeutralStroke2}`,borderLeft:`3px solid ${T.atomic?"var(--color-request-batch)":$.colorNeutralStroke1}`,borderRadius:6,padding:"8px 12px",marginBottom:8,background:$.colorNeutralBackground1},children:[t.jsx(I,{appearance:"transparent",onClick:()=>h(`group:${T.id}`),style:{padding:0},children:t.jsx("strong",{children:D?"Requests":T.atomic?`Change set ${O+1}`:`Independent group ${O+1}`})}),T.items.length===0&&t.jsx(M,{block:!0,style:{color:$.colorNeutralForeground3},children:"Empty — skipped when sent."}),T.items.map(m=>{W+=1;const j=oe(m,r);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>h(`item:${m.id}`),onKeyDown:A=>(A.key==="Enter"||A.key===" ")&&h(`item:${m.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"3px 0",cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:$.colorNeutralForeground3},children:["$",W]}),t.jsx(Ce,{method:j.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.path||"—"}),m.label&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:m.label})]},m.id)})]},T.id))]})}function Wn({group:e,index:s,count:o,contentIdOf:n,orgUrl:i,onSetAtomic:a,onAdd:r,onRemoveGroup:b,onMoveGroup:p,onSelect:x,variant:f="batch"}){const h=e.items.some(g=>oe(g,i).method==="GET"),c=f==="execute-multiple";return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ce,{icon:e.atomic?Re:Ie,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(I,{icon:t.jsx(ct,{}),appearance:"subtle","aria-label":"Move group up",disabled:s===0,onClick:()=>p(-1)}),t.jsx(I,{icon:t.jsx(dt,{}),appearance:"subtle","aria-label":"Move group down",disabled:s===o-1,onClick:()=>p(1)}),t.jsx(I,{icon:t.jsx($e,{}),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($s,{ariaLabel:"Group kind",children:[t.jsx(Ue,{checked:e.atomic,onClick:()=>a(!0),children:"Change set (atomic)"}),t.jsx(Ue,{checked:!e.atomic,onClick:()=>a(!1),children:"Independent"})]}),t.jsx(zn,{onAdd:r,disabledGet:e.atomic})]}),e.atomic&&h&&t.jsx(G,{intent:"error",style:{marginBottom:12},children:t.jsx(V,{children:"This change set holds a GET request. Move it to an independent group."})}),e.items.length===0&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:"No requests yet."}),e.items.map(g=>{const S=oe(g,i);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>x(`item:${g.id}`),onKeyDown:C=>(C.key==="Enter"||C.key===" ")&&x(`item:${g.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"6px 8px",borderBottom:`1px solid ${$.colorNeutralStroke3}`,cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:$.colorNeutralForeground3},children:["$",n(g.id)]}),t.jsx(Ce,{method:S.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.path||"—"}),g.label&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:g.label})]},g.id)})]})}const se={fontFamily:$.fontFamilyMonospace,fontSize:12};function st(e){return e.outcome!=="done"?e.outcome==="rolled-back"?"warning":"info":e.status===void 0?"info":e.status>=400?"danger":"success"}function Te(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 nt({r:e}){const s=Te(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 ${$.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:$.colorNeutralForeground3},children:["$",e.contentId]}),e.method&&t.jsx(Ce,{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(Se,{status:st(e),code:n}):t.jsx(Se,{status:st(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(G,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsx(V,{children:s})}),o&&t.jsxs("div",{style:{...se,marginBottom:6},children:["OData-EntityId: ",t.jsx("code",{children:o})]}),e.headers&&Object.keys(e.headers).length>0&&t.jsx("pre",{style:{...se,margin:"0 0 8px",whiteSpace:"pre-wrap"},children:Object.entries(e.headers).map(([i,a])=>`${i}: ${a}`).join(`
11
+ `)}),e.body!==void 0&&t.jsx("pre",{style:{...se,margin:0,whiteSpace:"pre-wrap",wordBreak:"break-all",background:$.colorNeutralBackground1,border:`1px solid ${$.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:$.colorNeutralForeground3},children:"No response body."}),e.outcome==="rolled-back"&&t.jsx(M,{block:!0,style:{color:$.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:$.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:$.colorNeutralForeground3},children:"An earlier failure stopped the batch before this request ran."})]})]})}function Gn({run:e,rows:s,extraTitle:o}){const[n,i]=w.useState(""),[a,r]=w.useState(null),[b,p]=w.useState(null),x=()=>{try{r(In(n)),p(null)}catch(c){r(null),p(c instanceof Error?c.message:String(c))}},f=(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(S=>S.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(C=>{const _=c.get(C);return _?.outcome==="done"&&(_.status??0)>=400})&&f.other>0&&(f.failed+=1,f.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(Se,{status:e.ok?"success":"danger",code:e.ok?200:"Failed",ms:e.ms}),t.jsxs("span",{style:{fontSize:13},children:[f.ok," succeeded · ",f.failed," failed",f.other?` · ${f.other} rolled back or not run`:"",f.noResult?` · ${f.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(G,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsxs(V,{children:[t.jsxs(te,{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??""} — ${Te(c.changesetError.body)??"see the response body below"}`,c.changesetError?.body!==void 0&&!Te(c.changesetError.body)&&t.jsx("pre",{style:{...se,whiteSpace:"pre-wrap"},children:JSON.stringify(c.changesetError.body,null,2)})]})},g):null),t.jsx("div",{style:{background:$.colorNeutralBackground1,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,padding:"0 8px"},children:s.map(c=>t.jsx(nt,{r:c},c.key))})]}):t.jsx(M,{block:!0,style:{color:$.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(Cs,{style:{verticalAlign:"middle",marginRight:6}}),"Inspect a raw $batch response from another client"]}),t.jsxs("div",{style:{marginTop:8},children:[t.jsx(ut,{value:n,onChange:(c,g)=>i(g.value),placeholder:"--batchresponse_…",rows:8,resize:"vertical",textarea:{style:se,spellCheck:!1},style:{width:"100%"},"aria-label":"Raw $batch response"}),t.jsx(I,{style:{marginTop:8},onClick:x,disabled:!n.trim(),children:"Parse response"}),b&&t.jsx(G,{intent:"error",style:{marginTop:8},children:t.jsx(V,{children:b})}),a&&t.jsx("div",{style:{marginTop:8},children:a.map((c,g)=>t.jsx(nt,{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 ot({formats:e,labels:s,generate:o,note:n,crlfFormats:i=["http"]}){const[a,r]=w.useState(e[0]),[b,p]=w.useState(!1),x=o(a);return t.jsxs("div",{children:[t.jsx(ce,{icon:Os,title:"Code",sub:n,group:"batch",children:t.jsx(je,{content:"Copy",relationship:"label",children:t.jsx(I,{icon:t.jsx(Bs,{}),appearance:"subtle",onClick:()=>{qs(x).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},children:b?"Copied":"Copy"})})}),t.jsx(Ms,{selectedValue:a,onTabSelect:(f,h)=>r(h.value),size:"small",children:e.map(f=>t.jsx(Ps,{value:f,children:s[f]},f))}),t.jsx("pre",{style:{fontFamily:$.fontFamilyMonospace,fontSize:12,lineHeight:1.5,background:$.colorNeutralBackground1,border:`1px solid ${$.colorNeutralStroke2}`,borderRadius:6,padding:12,marginTop:8,whiteSpace:"pre",overflow:"auto",maxHeight:"calc(100vh - 260px)"},children:x}),i.includes(a)&&t.jsx(M,{style:{color:$.colorNeutralForeground3},children:"Line breaks in a $batch body are CRLF on the wire."})]})}function Vn({open:e,onClose:s,onAdd:o}){const{saved:n}=Ds(),[i,a]=w.useState(new Set),[r,b]=w.useState(""),p=As(),x=w.useMemo(()=>n.filter(h=>vn.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]),f=()=>{a(new Set),b(""),s()};return t.jsx(Ns,{open:e,onOpenChange:(h,c)=>!c.open&&f(),children:t.jsx(Fs,{style:{maxWidth:640},children:t.jsxs(_s,{children:[t.jsx(Ls,{children:"Add saved requests to the batch"}),t.jsxs(Hs,{children:[t.jsx(U,{value:r,onChange:(h,c)=>b(c.value),placeholder:"Filter by name",contentBefore:t.jsx(zs,{}),style:{width:"100%",marginBottom:8},"aria-label":"Filter saved requests"}),x.length===0&&t.jsx(M,{block:!0,style:{color:$.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(Us,{checked:i.has(h.id),onChange:(c,g)=>a(S=>{const C=new Set(S);return g.checked?C.add(h.id):C.delete(h.id),C}),label:t.jsxs("span",{children:[h.name," ",t.jsx(M,{style:{color:$.colorNeutralForeground3},children:ke(h.modeId).name})]})})},h.id))})]}),t.jsxs(Ws,{children:[t.jsx(I,{appearance:"secondary",onClick:f,children:"Cancel"}),t.jsxs(I,{appearance:"primary",disabled:i.size===0,onClick:()=>{o(x.filter(h=>i.has(h.id))),f()},children:["Add ",i.size||""]})]})]})})})}const Jn=["http","fetch","pptb"],Kn=["csharp","http","pptb"],Qn={...gt,csharp:"ExecuteMultipleRequest (C#)",http:"Web API equivalent ($batch)"},Xn=new Set(["bulk-delete","bulk-write","batch","execute-multiple"]);function Zn({themeMode:e,variant:s="batch"}){const o=s==="execute-multiple",n=o?"execute-multiple":"batch",i=ke(n),a=Gs(n,We,o?Vs:Js),[r,b]=w.useState(a.state),p=r.returnResponses??!0,{entities:x}=it(),[f,h]=w.useState("overview"),[c,g]=w.useState("builder"),[S,C]=w.useState(null),[_,D]=w.useState(!1),[W,T]=w.useState([]),[O,m]=w.useState(!1),[j,A]=w.useState(null),[P,Oe]=w.useState(a.lastSavedId),[de,qe]=w.useState(a.lastSavedHash),K=Ge.host?`https://${Ge.host}`:"",q=w.useMemo(()=>Ks(r.groups,K),[r.groups,K]),re=w.useMemo(()=>Qs(q.items),[q]),Be=yn(),ue=(l,d)=>{const u=new Set(l.dirty);return u.add(d),{...l,dirty:u}},J=w.useCallback((l,d="batch")=>b(u=>ue({...u,groups:l(u.groups)},d)),[]),xt=(l,d)=>J(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&&(J(y=>{let v=y.find(R=>R.id===l);const k=d.some(R=>oe(R,K).method==="GET");if((!v||v.atomic&&k)&&(v=[...y].reverse().find(R=>k?!R.atomic:!0)),!v){const R=Ve(!k,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")))},yt=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},vt=(l,d)=>J(u=>{const y=u.findIndex(N=>N.items.some(Bt=>Bt.id===l));if(y<0)return u;const v=u[y].items,k=v.findIndex(N=>N.id===l),E=u.map(N=>({...N,items:[...N.items]})),R=k+d;if(R>=0&&R<v.length)[E[y].items[k],E[y].items[R]]=[E[y].items[R],E[y].items[k]];else if(u[y+d]){const[N]=E[y].items.splice(k,1);d<0?E[y-1].items.push(N):E[y+1].items.unshift(N)}return E}),jt=(l,d)=>J(u=>{const y=u.flatMap(v=>v.items).find(v=>v.id===l);return y?u.map(v=>{const k=v.items.filter(E=>E.id!==l);return v.id===d?{...v,items:[...k,y]}:{...v,items:k}}):u}),he=Xs(),Y=he&&!Xn.has(he.modeId)?he:null,Pe=Y?ke(Y.modeId).name:null,De=async l=>{const d=[],u=[];for(const v of l){const k=await Sn(v);k.ok?d.push(...k.items):u.push(`“${v.name}” (${k.reason})`)}const y=f.startsWith("group:")?f.slice(6):null;Me(y,d,!1),A([d.length?`Added ${d.length} request${d.length===1?"":"s"}.`:"",u.length?`Skipped ${u.join(", ")}.`:""].filter(Boolean).join(" ")||null)},Ae=w.useMemo(()=>{const l=q.issues.map((u,y)=>{const v=u.target?u.target.startsWith("g")?`group:${u.target}`:`item:${u.target}`:"overview",k=q.items.find(R=>R.item.id===u.target),E=k?`$${k.contentId}: ${u.message}`:u.message;return u.severity==="error"?be.err(`batch-${y}`,"validation",E,void 0,v):be.warn(`batch-${y}`,"validation",E,void 0,v)}),d=q.items.filter(u=>u.wire?.method==="DELETE").length;return d>0&&l.push(be.warn("batch-deletes","validation",`This batch deletes ${d} record${d===1?"":"s"}`,"Deletes in a batch run without the Delete mode’s confirmation. Check the ids first.","overview")),l},[q]),$t=Be??Ys(Ae),wt=q.items.some(l=>l.wire&&Object.keys(l.wire.headers).length>0)||r.continueOnError&&re.some(l=>!l.transaction),St=async()=>{D(!0);try{const l=await xn(re,{continueOnError:r.continueOnError});C(l);const{status:d,summary:u,succeeded:y}=pn(l);T(v=>[{id:`r-${Date.now()}`,modeId:n,url:`${ne}/$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{D(!1),g("results")}},kt=w.useMemo(()=>S?(o&&!p?S.items.filter(d=>d.outcome!=="done"||(d.status??0)>=400):S.items).map(d=>{const u=q.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}}):[],[S,q,o,p]),Ne=w.useRef({batch:le("batch"),cs:[]}),pe=w.useMemo(()=>({batch:Ne.current.batch,changeset:l=>{var d;return(d=Ne.current.cs)[l]??(d[l]=le("changeset"))}}),[]),Et=w.useMemo(()=>new TextEncoder().encode(mt(bt(q.items),pe).body).length,[q,pe]),Fe=l=>On(l,{items:q.items,plan:re,continueOnError:r.continueOnError,orgUrl:K,boundaries:pe}),Tt=l=>l==="csharp"?Nn(q.items,{continueOnError:r.continueOnError,returnResponses:p},{logicalOf:d=>x.find(u=>u.entitySetName===d)?.logicalName??null,attrType:(d,u)=>rt(d)?.columns.find(y=>y.logicalName===u)?.attributeType??null}):Fe(l),Z=w.useMemo(()=>Zs(r),[r]);en(n,Z,P,de);const Rt=w.useMemo(()=>xe(Z),[Z]),_e=de===null?!0:Rt!==de,ae=q.items.length,It=l=>{Oe(l.id),qe(xe(l.state))},Ct=l=>{if(l.modeId!==n)return;const d=l.state;b(We(d)),Oe(l.id),qe(xe(d)),C(null),h("overview")};tn(w.useMemo(()=>({state:Z,modeId:n,dirty:_e,lastSavedId:P,onSaved:It,onLoadSaved:Ct}),[Z,_e,P]));const me=l=>q.issues.filter(d=>d.target===l),Ot=l=>S?.items.find(d=>d.itemId===l),qt=[{id:"batch",label:o?"ExecuteMultiple":"Batch",meta:`${ae} request${ae===1?"":"s"}`,items:[{id:"overview",icon:nn,iconFilled:sn,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?Re:Ie,iconFilled:l.atomic?on:rn,label:o?"Add request":l.atomic?"Atomic group":"Independent requests",badge:me(l.id).length||null,badgeColor:"danger"},...l.items.map(u=>{const y=q.items.find(N=>N.item.id===u.id),v=oe(u,K),k=me(u.id).filter(N=>N.severity==="error").length,E=Ot(u.id),R=k?`${k} issue${k===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:lt,iconFilled:an,label:`$${y?.contentId??"?"} ${v.method} ${u.label||v.path||"…"}`,code:!0,badge:R,badgeAppearance:"tint",badgeColor:k||E&&(E.outcome!=="done"||(E.status??0)>=400)?"danger":"success",dirty:r.dirty.has(`item:${u.id}`)}})]}))];let ee=null;if(f.startsWith("item:")){const l=yt(f.slice(5)),d=l&&q.items.find(u=>u.item.id===l.item.id);l&&d&&(ee=t.jsx(Ln,{item:l.item,contentId:d.contentId,group:l.group,groups:r.groups,wire:d.wire,issues:me(l.item.id),onChange:u=>xt(l.item.id,u),onRemove:()=>{J(u=>u.map(y=>({...y,items:y.items.filter(v=>v.id!==l.item.id)}))),h(`group:${l.group.id}`)},onMove:u=>vt(l.item.id,u),onMoveToGroup:u=>jt(l.item.id,u)},l.item.id))}else if(f.startsWith("group:")){const l=r.groups.findIndex(u=>u.id===f.slice(6)),d=r.groups[l];d&&(ee=t.jsx(Wn,{group:d,index:l,count:r.groups.length,variant:s,orgUrl:K,contentIdOf:u=>q.items.find(y=>y.item.id===u)?.contentId??"?",onSetAtomic:u=>J(y=>y.map(v=>v.id===d.id?{...v,atomic:u}:v)),onAdd:u=>Me(d.id,[at(u)]),onRemoveGroup:()=>{J(u=>u.filter(y=>y.id!==d.id)),h("overview")},onMoveGroup:u=>J(y=>{const v=[...y],k=l+u;return k<0||k>=v.length?y:([v[l],v[k]]=[v[k],v[l]],v)}),onSelect:h}))}return ee||(ee=t.jsx(Un,{variant:s,returnResponses:p,setReturnResponses:l=>b(d=>ue({...d,returnResponses:l},"overview")),groups:r.groups,continueOnError:r.continueOnError,setContinueOnError:l=>b(d=>ue({...d,continueOnError:l},"overview")),plan:re,unavailable:Be,needsConsent:wt,orgUrl:K,onAddGroup:l=>{const d=Ve(l);J(u=>[...u,d]),h(`group:${d.id}`)},onOpenSaved:()=>m(!0),onAddLast:()=>{Y&&De([{...Y,name:Pe??Y.modeId}])},lastLabel:Pe,onSelect:h,notice:j})),t.jsxs(ln,{sidebar:t.jsx(un,{type:i,urlPreview:`/$batch · ${ae} request${ae===1?"":"s"}${o?" · ExecuteMultiple":""}`,sections:qt,activeNode:f,onSelect:l=>{h(l),g("builder")},recents:W}),urlBar:t.jsx(dn,{method:"BATCH",url:`${ne}/$batch`,bytes:Et,executeVerb:i.executeVerb,disabledReason:$t,loading:_,onExecute:St,advisories:Ae,onAdvisoryFocus:l=>{h(l),g("builder")}}),children:[t.jsxs(cn,{tab:c,onTabChange:g,resultCount:S?S.items.length:null,children:[c==="builder"&&ee,c==="code"&&o&&t.jsx(ot,{formats:Kn,labels:Qn,generate:Tt,note:"DRS sends these requests as a Web API $batch; the C# is the SDK form."}),c==="code"&&!o&&t.jsx(ot,{formats:Jn,labels:gt,generate:Fe,note:q.issues.some(l=>l.severity==="error")?"Requests with errors are left out until they’re fixed.":void 0}),c==="results"&&t.jsx(Gn,{run:S,rows:kt,extraTitle:o&&!p&&S?"ReturnResponses = false: only faults are listed.":void 0})]}),t.jsx(Vn,{open:O,onClose:()=>m(!1),onAdd:l=>{De(l.map(d=>({modeId:d.modeId,state:d.state,name:d.name})))}})]})}export{Zn as BatchMode};