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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +383 -0
  2. package/LICENSE +661 -661
  3. package/README.md +479 -390
  4. package/SECURITY.md +54 -51
  5. package/dist/assets/AssociateMode-BVHaHiUu.js +1 -0
  6. package/dist/assets/AssociateTargetsEditor-C-QKaWaJ.js +1 -0
  7. package/dist/assets/BatchMode-D1J8HcNO.js +11 -0
  8. package/dist/assets/BinaryColumnPickers-DLIbx4hp.js +1 -0
  9. package/dist/assets/BulkDeleteMode-CFcjcWta.js +1 -0
  10. package/dist/assets/BulkWriteMode-C3ZGwTjw.js +6 -0
  11. package/dist/assets/DisassociateMode-BwMK4UvP.js +2 -0
  12. package/dist/assets/ExecuteWorkflowMode-CkZdayJ4.js +1 -0
  13. package/dist/assets/ManageFileMode-DP3KXgFw.js +1 -0
  14. package/dist/assets/ManageImageMode-F0Dki5VQ.js +1 -0
  15. package/dist/assets/MergeMode-PeKTZ75X.js +1 -0
  16. package/dist/assets/PredefinedQueryMode-CDuc-WrN.js +1 -0
  17. package/dist/assets/RetrieveNextLinkMode-DenFlpEh.js +1 -0
  18. package/dist/assets/cssMode-DXyl4xBX.js +4 -0
  19. package/dist/assets/{freemarker2-CY0Qd_yj.js → freemarker2-CR_qGQP2.js} +2 -2
  20. package/dist/assets/handlebars-Buz2RscQ.js +1 -0
  21. package/dist/assets/html-B66Hfdqd.js +1 -0
  22. package/dist/assets/htmlMode-3ft3GC0g.js +4 -0
  23. package/dist/assets/index-C4fO68cu.js +704 -0
  24. package/dist/assets/javascript-Cy8u5Pbx.js +1 -0
  25. package/dist/assets/jsonMode-CvLp-1ik.js +10 -0
  26. package/dist/assets/liquid-BxIE_8lr.js +1 -0
  27. package/dist/assets/mdx-Bbo0ENZs.js +1 -0
  28. package/dist/assets/{monaco-editor-ErGqj9vD.js → monacoSetup-C4aSY1Tw.js} +193 -183
  29. package/dist/assets/monacoSetup-DvqauXKu.css +1 -0
  30. package/dist/assets/python-B6K3FYWG.js +1 -0
  31. package/dist/assets/razor-7sN2ZaJq.js +1 -0
  32. package/dist/assets/{tsMode-B1b3lx86.js → tsMode-CIH2Hja3.js} +2 -2
  33. package/dist/assets/typescript-rqW7IEk7.js +1 -0
  34. package/dist/assets/xml-Bm2nJGx3.js +1 -0
  35. package/dist/assets/yaml-Z6ahf7o7.js +1 -0
  36. package/{icons/icon-insider.svg → dist/icons/icon.svg} +22 -22
  37. package/dist/index.html +61 -4
  38. package/index.html +60 -1
  39. package/package.json +14 -8
  40. package/dist/assets/cssMode-DHcTSP5p.js +0 -4
  41. package/dist/assets/handlebars-BQEEw1Ke.js +0 -1
  42. package/dist/assets/html-BXibA6yW.js +0 -1
  43. package/dist/assets/htmlMode-BIOKXbRP.js +0 -4
  44. package/dist/assets/index-CCZE1KQi.js +0 -672
  45. package/dist/assets/javascript-BY4qn0pJ.js +0 -1
  46. package/dist/assets/jsonMode-BzZNqTrE.js +0 -10
  47. package/dist/assets/liquid-noPAIv1T.js +0 -1
  48. package/dist/assets/mdx-Ccyf8KqT.js +0 -1
  49. package/dist/assets/monaco-editor-I3pIE735.css +0 -1
  50. package/dist/assets/python-CTl0fa86.js +0 -1
  51. package/dist/assets/razor-DoNzFhT2.js +0 -1
  52. package/dist/assets/typescript-ONTfb8eq.js +0 -1
  53. package/dist/assets/xml-6DyixHd0.js +0 -1
  54. package/dist/assets/yaml-B9La2-TQ.js +0 -1
  55. package/icons/icon.svg +0 -25
  56. package/npm-shrinkwrap.json +0 -3832
package/SECURITY.md CHANGED
@@ -1,51 +1,54 @@
1
- # Security Policy
2
-
3
- ## Reporting a Vulnerability
4
-
5
- Please do **not** open a public issue for security concerns. Use GitHub
6
- Security Advisories (private):
7
- <https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/security/advisories/new>
8
-
9
- I'll acknowledge receipt within a few business days and coordinate a fix +
10
- disclosure timeline with you.
11
-
12
- ## Scope
13
-
14
- The studio is a client-side composer + executor for Dataverse Web API
15
- requests, running either embedded in Power Platform ToolBox or standalone
16
- in a browser. Vulnerability reports of interest:
17
-
18
- - **Authentication / token handling** — any path that could leak a
19
- Dataverse access token, the PPTB session token, or a Connection's
20
- credentials from the host bridge.
21
- - **Cross-site / injection** — XSS, HTML / Markdown injection in
22
- user-supplied request fields, code-tab snippet output, or results-grid
23
- cell rendering.
24
- - **CSP / sandbox escape** — anything that lets DRS code execute outside
25
- the iframe / host's allowed origins, or fetch from a non-Dataverse host.
26
- - **Dataverse request integrity** — paths where the studio could emit a
27
- request that escalates privileges, bypasses documented `MSCRM.*` header
28
- rules, or alters another tool's state.
29
- - **Saved-request library** — paths where a crafted saved-request payload
30
- triggers code execution on load, exfiltrates localStorage from another
31
- org scope, or escapes the per-org scoping bucket.
32
- - **Dependency vulnerabilities** — known CVEs in production dependencies
33
- (`@fluentui/*`, `monaco-editor`, `@pptb/types`, etc.) that affect the
34
- shipped bundle.
35
-
36
- ## Out of scope
37
-
38
- - **Mistakes the user makes against their own environment** — DRS lets you
39
- Delete, Update, and Merge records. Destructive operations require typed
40
- confirmation; beyond that, the user is responsible for what they send.
41
- - **Standalone-mode network errors** — the standalone build (`npm run dev`)
42
- has no host bridge; Execute returns 501. This is by design, not a bug.
43
- - **Antipattern advisories** — the studio surfaces guidance per the
44
- Microsoft query-antipatterns doc, but it's advisory only; the request
45
- still goes through if the user proceeds.
46
-
47
- ## Supported versions
48
-
49
- Only the latest released minor version on `main` receives security fixes.
50
-
51
- Thanks for helping keep the tool safe.
1
+ # Security Policy
2
+
3
+ ## Reporting a Vulnerability
4
+
5
+ Please do **not** open a public issue for security concerns. Use GitHub
6
+ Security Advisories (private):
7
+ <https://github.com/mohsinonxrm/pptb-mxrm-dataverse-request-studio/security/advisories/new>
8
+
9
+ I'll acknowledge receipt within a few business days and coordinate a fix +
10
+ disclosure timeline with you.
11
+
12
+ ## Scope
13
+
14
+ The studio is a client-side composer + executor for Dataverse Web API
15
+ requests, running either embedded in Power Platform ToolBox or standalone
16
+ in a browser. Vulnerability reports of interest:
17
+
18
+ - **Authentication / token handling** — any path that could leak a
19
+ Dataverse access token, the PPTB session token, or a Connection's
20
+ credentials from the host bridge.
21
+ - **Cross-site / injection** — XSS, HTML / Markdown injection in
22
+ user-supplied request fields, code-tab snippet output, or results-grid
23
+ cell rendering.
24
+ - **CSP / sandbox escape** — anything that lets DRS code execute outside
25
+ the iframe / host's allowed origins, or fetch from a non-Dataverse host.
26
+ - **Dataverse request integrity** — paths where the studio could emit a
27
+ request that escalates privileges, bypasses documented `MSCRM.*` header
28
+ rules, or alters another tool's state.
29
+ - **Saved-request library** — paths where a crafted saved-request payload
30
+ triggers code execution on load, exfiltrates localStorage from another
31
+ org scope, or escapes the per-org scoping bucket.
32
+ - **Dependency vulnerabilities** — known CVEs in production dependencies
33
+ (`@fluentui/*`, `monaco-editor`, `@monaco-editor/react`, `@dnd-kit/*`,
34
+ `react`, etc.) that affect the shipped bundle. Dev-only tooling
35
+ (`@pptb/types`, Vite, TypeScript, Prettier) isn't shipped.
36
+
37
+ ## Out of scope
38
+
39
+ - **Mistakes the user makes against their own environment** — DRS lets you
40
+ Delete, Update, and Merge records. Delete and Bulk Delete Job require typed
41
+ confirmation; bulk and batch deletes and Merge don't. Beyond that, the user
42
+ is responsible for what they send.
43
+ - **Standalone-mode Execute errors** — the standalone build (`npm run dev`)
44
+ has no host bridge, so Execute returns `501 Not Implemented` ("Running
45
+ standalone: Execute needs the PPTB host"). This is by design, not a bug.
46
+ - **Antipattern advisories** — the studio surfaces guidance per the
47
+ Microsoft query-antipatterns doc, but it's advisory only; the request
48
+ still goes through if the user proceeds.
49
+
50
+ ## Supported versions
51
+
52
+ Only the latest released minor version on `main` receives security fixes.
53
+
54
+ Thanks for helping keep the tool safe.
@@ -0,0 +1 @@
1
+ import{c as ae,b5 as se,bK as U,r,u as re,e as oe,bL as ne,bM as ie,bN as le,f as de,bO as ce,bP as ue,b9 as ge,i as I,j as he,T as be,k as pe,bQ as me,bR as ye,bF as ve,bG as fe,bS as R,L as Se,p as xe,q as a,H as Pe,A as Te,B as Ne,I as je,v as ke,bT as we,x as Ce,y as Me,z as Ie,D as Re,R as Ae,bU as D,U as He,S as Fe,G as Le,bl as Be,aS as $e,bm as qe,b4 as Ee,a8 as Oe,X as T,bk as Ue,Y as De,a_ as ze}from"./index-C4fO68cu.js";import{A as Ve,N as We}from"./AssociateTargetsEditor-C-QKaWaJ.js";const Ge=()=>({table:"",sourceId:null,navProperty:null,targets:[],targetNames:{},headers:Le(),dirty:new Set});function Xe({themeMode:d}){const p=ae("associate"),n=se("associate",U,Ge),[e,c]=r.useState(n.state),{table:N}=re(e.table||null),{entities:A}=oe(),[H,F]=r.useState("source"),[m,j]=r.useState("builder"),[L,k]=r.useState(null),[V,B]=r.useState(!1),[W,G]=r.useState([]),[y,v]=r.useState(n.lastSavedId),[f,S]=r.useState(n.lastSavedHash),[$,w]=r.useState(""),b=r.useMemo(()=>ne(e),[e,N]),_=r.useMemo(()=>ie(e),[e,N]),i=r.useMemo(()=>le(e),[e,N]),x=de(e.table),o=e.navProperty?x?.navigationProperties.find(t=>t.name===e.navProperty):void 0,q=o?ce(o):!1,u=q?"PATCH":"POST",C=t=>c(s=>{const l=new Set(s.dirty);return l.add(t),{...s,dirty:l}}),P=(t,s,l)=>{c(M=>({...M,[t]:s})),l&&C(l)},J=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.",K=async()=>{B(!0);const t=await $e.associate(e);k(t),B(!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:D(t,i.length)??0},...s].slice(0,8)),c(s=>({...s,dirty:new Set}))},g=r.useMemo(()=>ue(e),[e]);ge("associate",g,y,f);const Q=r.useMemo(()=>I(g),[g]),E=f===null?!0:Q!==f,X=t=>{v(t.id),S(I(t.state))},O=t=>{if(t.modeId!=="associate")return;const s=t.state;if(A.length>0&&!A.some(l=>l.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(U(s)),v(t.id),S(I(s)),k(null),w(""),F("source")},Y=t=>{const s=qe(t,"associate");if(!s)return;const l=y,M=f;O(s),v(l),S(M)};he(r.useMemo(()=>e.table?{state:g,modeId:"associate",dirty:E,lastSavedId:y,onSaved:X,onLoadSaved:O}:null,[g,E,y,e.table]));const Z=[{id:"source",label:"Target",meta:x?.displayName??"Pick a table",items:[{id:"source",icon:pe,iconFilled:be,label:e.sourceId?$||`${x?.displayName??""} (selected)`:"Pick a record",badge:o?u:null,badgeAppearance:"tint",badgeColor:"brand",dirty:e.dirty.has("source")}]},{id:"relationship",label:"Relationship",meta:o?z(o.cardinality):"pick one",items:[{id:"nav",icon:ye,iconFilled:me,label:o?o.name:"Navigation property",code:!!o,badge:o?z(o.cardinality):null,badgeAppearance:"ghost",dirty:e.dirty.has("nav")}]},{id:"targets",label:"Related",meta:e.targets.length?`${e.targets.length} target${e.targets.length===1?"":"s"}`:"none",items:[{id:"targets",icon:fe,iconFilled:ve,label:q?"Target record":"Target records",badge:e.targets.length||null,badgeAppearance:"tint",badgeColor:e.targets.length>0?"success":"subtle",dirty:e.dirty.has("targets")},...i.length>0?[{id:"preview",icon:R,iconFilled:R,label:`${i.length} request${i.length===1?"":"s"}`,badge:i.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(H){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:o?u:null});break;case"preview":h=a.jsx(_e,{requests:i});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:_,entityLogical:b.entityLogical,multiRequests:i.length>1?i.map(t=>({method:t.method,relativeUrl:t.relativeUrl,body:t.body,description:`target ${t.targetId}`})):void 0};return a.jsx(Me,{sidebar:a.jsx(Fe,{type:p,urlPreview:b.relativeNoBase,sections:Z,activeNode:H,onSelect:t=>{F(t),j("builder")},recents:W,onRecentClick:Y}),urlBar:a.jsx(He,{method:u,url:b.relativeUrl,executeVerb:p.executeVerb,disabledReason:J,loading:V,onExecute:K}),children:a.jsxs(Ie,{tab:m,onTabChange:j,resultCount:D(L,i.length),children:[m==="builder"&&h,m==="code"&&a.jsx(Re,{themeMode:d,inputs:te}),m==="results"&&a.jsx(Ae,{result:L,mode:"single",table:e.table,writeContext:{operation:"associate",table:e.table,recordId:e.sourceId,recordName:$||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 _e({requests:d}){const p=Ee();return a.jsxs("div",{children:[a.jsx(Oe,{icon:R,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((n,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(Ue,{appearance:"filled",color:n.method==="POST"?"success":"warning",style:{fontWeight:700,justifySelf:"start"},children:n.method}),a.jsxs("div",{style:{minWidth:0},children:[a.jsx("div",{style:{wordBreak:"break-all"},children:n.relativeUrl}),a.jsx("div",{style:{marginTop:4,color:T.colorNeutralForeground3},children:JSON.stringify(n.body)})]})]},n.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{Xe as AssociateMode};
@@ -0,0 +1 @@
1
+ import{f as j,u as I,q as e,a8 as k,bQ as v,a4 as M,bi as L,b2 as U,X as r,bk as p,Y as b,r as S,b4 as G,A as P,B as O,aC as E,b$ as H,bJ as K,N as V,aO as _,a_ as J,b3 as Q,aA as X,I as Y}from"./index-C4fO68cu.js";function ne({table:t,value:s,onChange:n,group:o="relate",forOperation:u,footer:y}){const g=j(t)?.navigationProperties??[],d=g.find(i=>i.name===s);return I(d?.targetEntity??null),e.jsxs("div",{children:[e.jsx(k,{icon:v,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(L,{value:d?.name??"",selectedOptions:d?[d.name]:[],onOptionSelect:(i,x)=>n(x.optionValue??null),placeholder:"Pick a navigation property…",children:g.map(i=>e.jsx(U,{value:i.name,text:i.name,children:e.jsx(Z,{nav:i,forOperation:u})},i.name))})}),d&&e.jsx("div",{style:{marginTop:16},children:e.jsx(ee,{nav:d,forOperation:u})}),y&&e.jsx("div",{style:{marginTop:14},children:y})]})]})}function Z({nav:t,forOperation:s}){const n=j(t.targetEntity),o=C(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:r.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(b,{style:{color:r.colorNeutralForeground3},children:["→ ",n?.displayName??t.targetEntity," · ",te(t.cardinality)]})]})}function ee({nav:t,forOperation:s}){const n=j(t.targetEntity),o=C(t,s),u=t.cardinality==="ManyToOne"?"single-valued":"collection-valued",y=o==="POST"?r.colorPaletteGreenForeground1:o==="PATCH"?r.colorPaletteDarkOrangeForeground1:r.colorPaletteRedForeground1;return e.jsxs("div",{style:{border:`1px solid ${r.colorNeutralStroke2}`,borderRadius:r.borderRadiusMedium,padding:12,background:r.colorNeutralBackground1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(v,{style:{width:18,height:18,color:r.colorBrandForeground1}}),e.jsx("strong",{style:{fontFamily:r.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:r.colorNeutralForegroundOnBrand,fontWeight:700},children:o})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"120px 1fr",rowGap:4,fontSize:11},children:[e.jsx("span",{style:{color:r.colorNeutralForeground3},children:"Target entity"}),e.jsxs("span",{style:{fontFamily:r.fontFamilyMonospace},children:[n?.entitySetName??t.targetEntity," ",e.jsxs(b,{style:{color:r.colorNeutralForeground3},children:["· ",n?.displayName??t.targetEntity]})]}),e.jsx("span",{style:{color:r.colorNeutralForeground3},children:"Cardinality"}),e.jsxs("span",{children:[u," (",t.cardinality,")"]}),e.jsx("span",{style:{color:r.colorNeutralForeground3},children:"Relationship"}),e.jsx("span",{style:{fontFamily:r.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 te(t){return t==="ManyToOne"?"single-valued lookup":"collection-valued"}function C(t,s){return t.cardinality==="ManyToOne"?"PATCH":s==="disassociate"?"DELETE":"POST"}function ae({table:t,navProperty:s,targets:n,setTargets:o,targetNames:u,setTargetNames:y,group:N="relate",resolvedMethod:g}){const[d,i]=S.useState({}),x=u??d,F=y??i,R=G(),W=j(t),h=s?W?.navigationProperties.find(a=>a.name===s):void 0,m=h?j(h.targetEntity):void 0,l=h?.cardinality==="ManyToOne",A=l?1:1/0,[w,q]=S.useState(0);if(!h)return e.jsxs("div",{children:[e.jsx(k,{icon:v,title:"Target records",sub:"Pick a navigation property first.",group:N}),e.jsx(P,{layout:"multiline",intent:"info",style:{maxWidth:720},children:e.jsxs(O,{children:["Switch to the ",e.jsx("strong",{children:"Navigation property"})," pane and pick one — the target entity comes from there."]})})]});const T=n.length>=A,z=(a,c)=>{if(!a||n.includes(a)||T)return;const f=l?[a]:[...n,a];o(f),c&&F({...x,[a]:c}),q(D=>D+1)},$=a=>{if(o(n.filter(c=>c!==a)),x[a]!=null){const c={...x};delete c[a],F(c)}};return e.jsxs("div",{children:[e.jsxs(k,{icon:v,title:l?"Target record":"Target records",sub:e.jsx("span",{children:l?e.jsxs(e.Fragment,{children:["One target is allowed for ",e.jsx("code",{children:h.cardinality})," nav props — the server PUT 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:n.length>0?"brand":"subtle",children:[n.length," target",n.length===1?"":"s"]}),g&&e.jsx(p,{appearance:"filled",color:g==="POST"?"success":"informative",style:{fontWeight:700},children:g}),!l&&n.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(H,{style:{width:12,height:12}}),children:[n.length," requests queued"]})})]}),e.jsx("div",{className:J(R.inlineCard),style:{padding:12,marginBottom:14,maxWidth:880},children:n.length===0?e.jsxs(b,{style:{padding:"12px 4px",color:r.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:m?.displayName??h.targetEntity})," record",l?"":"s","."]}):e.jsx("div",{style:{display:"flex",flexDirection:"column"},children:n.map((a,c)=>{const f=x[a];return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 4px",borderBottom:c<n.length-1?`1px solid ${r.colorNeutralStroke3}`:"none"},children:[e.jsx(K,{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:r.colorNeutralForeground3},children:"(name not resolved)"})}),e.jsxs("div",{style:{fontFamily:r.fontFamilyMonospace,fontSize:10,color:r.colorNeutralForeground3},children:["/",m?.entitySetName??"?","(",a,")"]})]}),e.jsx(E,{content:"Remove target",relationship:"label",children:e.jsx(V,{size:"small",appearance:"subtle",icon:e.jsx(_,{}),onClick:()=>$(a),"aria-label":"Remove target"})})]},a)})})}),!T&&e.jsxs("div",{style:{maxWidth:560},children:[e.jsx(M,{label:l?"Pick target":"Add target",hint:l?`Pick a single ${m?.displayName??"record"} — the PUT sets this as the lookup value.`:`Each pick queues a separate POST. Currently ${n.length} target${n.length===1?"":"s"} queued.`,children:e.jsx(Q,{table:m?.logicalName??h.targetEntity,selectedId:null,onPick:a=>z(a?.id??null,a?.primary),placeholder:`Search ${m?.displayName??"record"}s…`},w)}),!l&&e.jsxs(b,{style:{display:"block",marginTop:6,color:r.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."]})]}),T&&l&&e.jsx(P,{layout:"multiline",intent:"info",style:{maxWidth:720,marginTop:12},children:e.jsxs(O,{children:[e.jsx(Y,{children:"Single-valued nav property — one target only."}),"To change the target, remove the current one first. The server PUT atomically replaces the previous lookup value."]})})]})}export{ae as A,ne as N};
@@ -0,0 +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(`
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(`
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=`{
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};
@@ -0,0 +1 @@
1
+ import{f,r as F,q as e,A as u,B as p,a8 as x,ct as h,a4 as N,bi as b,b2 as I,cd as j,X as n,bk as r,cg as g,Y as m,cv as z,cw as v}from"./index-C4fO68cu.js";function P({table:l,value:i,onChange:t,group:d="binary"}){const o=f(l),c=F.useMemo(()=>(o?.columns??[]).filter(a=>a.attributeType==="File"),[o]),s=c.find(a=>a.logicalName===i);return o?c.length===0?e.jsxs("div",{children:[e.jsx(x,{icon:j,title:"File column",group:d}),e.jsx(u,{layout:"multiline",intent:"warning",style:{maxWidth:720},children:e.jsxs(p,{children:[e.jsx("strong",{children:o.displayName})," has no File-typed columns. Add one via the maker portal or pick a different table."]})})]}):e.jsxs("div",{children:[e.jsx(x,{icon:j,title:"File column",sub:"Pick the File-typed column to operate on. Max size + target are sourced from the column metadata.",group:d}),e.jsxs("div",{style:{maxWidth:720},children:[e.jsx(N,{label:"Column",children:e.jsx(b,{value:s?.displayName??s?.logicalName??"",selectedOptions:i?[i]:[],onOptionSelect:(a,y)=>t(y.optionValue??null),placeholder:"Pick a file column…",children:c.map(a=>e.jsx(I,{value:a.logicalName,text:a.displayName,children:e.jsx(S,{col:a})},a.logicalName))})}),s&&e.jsx("div",{style:{marginTop:16},children:e.jsx(B,{col:s})})]})]}):e.jsx(u,{layout:"multiline",intent:"error",children:e.jsxs(p,{children:["Unknown table ",e.jsx("code",{children:l}),"."]})})}function S({col:l}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontFamily:n.fontFamilyMonospace,fontWeight:600},children:l.logicalName}),e.jsx(r,{appearance:"ghost",size:"extra-small",children:"File"}),e.jsxs(r,{appearance:"ghost",size:"extra-small",style:{marginLeft:"auto"},children:["max ",g((l.maxSizeInKB??32768)*1024)]})]}),e.jsxs(m,{style:{color:n.colorNeutralForeground3},children:[l.displayName,l.binaryTarget&&l.binaryTarget!=="file"&&e.jsxs(e.Fragment,{children:[" · ",l.binaryTarget," body"]})]})]})}function B({col:l}){const i=(l.maxSizeInKB??32768)*1024;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(j,{style:{color:n.colorBrandForeground1}}),e.jsx("strong",{style:{fontFamily:n.fontFamilyMonospace,fontSize:13},children:l.logicalName}),e.jsx(r,{appearance:"tint",color:"brand",children:"File"}),e.jsx("span",{style:{flexGrow:1}}),e.jsx(m,{style:{color:n.colorNeutralForeground3,fontFamily:n.fontFamilyMonospace},children:l.displayName})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"160px 1fr",rowGap:4,fontSize:11},children:[e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Max file size"}),e.jsxs("span",{children:[g(i)," ",e.jsxs(m,{style:{color:n.colorNeutralForeground3,marginLeft:4},children:["· ",(l.maxSizeInKB??32768).toLocaleString()," KB"]})]}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Companion column"}),e.jsxs("span",{style:{fontFamily:n.fontFamilyMonospace},children:[v(l.logicalName)," ",e.jsx(m,{style:{color:n.colorNeutralForeground3,marginLeft:4,fontFamily:n.fontFamilyBase},children:"· read-only string — $select to get the filename without downloading bytes"})]}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Retrieve returns"}),e.jsx("span",{children:"file id (Guid). Pass to DeleteFile or compose download URL."}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Binary target"}),e.jsx("span",{children:e.jsx(r,{appearance:"ghost",children:l.binaryTarget??"file"})})]})]})}function T({table:l,value:i,onChange:t,group:d="binary"}){const o=f(l),c=F.useMemo(()=>(o?.columns??[]).filter(a=>a.attributeType==="Image"),[o]),s=c.find(a=>a.logicalName===i);return o?c.length===0?e.jsxs("div",{children:[e.jsx(x,{icon:h,title:"Image column",group:d}),e.jsx(u,{layout:"multiline",intent:"warning",style:{maxWidth:720},children:e.jsxs(p,{children:[e.jsx("strong",{children:o.displayName})," has no Image-typed columns. Tables get one when their primary image is configured; custom image columns are created via solution explorer."]})})]}):e.jsxs("div",{children:[e.jsx(x,{icon:h,title:"Image column",sub:"Pick the Image-typed column. Primary image (entityimage) is thumbnail-only; custom image columns can store full size when configured.",group:d}),e.jsxs("div",{style:{maxWidth:720},children:[e.jsx(N,{label:"Column",children:e.jsx(b,{value:s?.displayName??s?.logicalName??"",selectedOptions:i?[i]:[],onOptionSelect:(a,y)=>t(y.optionValue??null),placeholder:"Pick an image column…",children:c.map(a=>e.jsx(I,{value:a.logicalName,text:a.displayName,children:e.jsx(C,{col:a})},a.logicalName))})}),s&&e.jsx("div",{style:{marginTop:16},children:e.jsx(k,{col:s})})]})]}):e.jsx(u,{layout:"multiline",intent:"error",children:e.jsxs(p,{children:["Unknown table ",e.jsx("code",{children:l}),"."]})})}function C({col:l}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontFamily:n.fontFamilyMonospace,fontWeight:600},children:l.logicalName}),e.jsx(r,{appearance:"ghost",size:"extra-small",children:"Image"}),l.isPrimaryImage&&e.jsx(r,{appearance:"tint",color:"brand",size:"extra-small",children:"primary"}),l.canStoreFullImage&&e.jsx(r,{appearance:"tint",color:"success",size:"extra-small",children:"full-size"}),e.jsx(r,{appearance:"ghost",size:"extra-small",style:{marginLeft:"auto"},children:l.isPrimaryImage?"144×144":`max ${g((l.maxSizeInKB??10240)*1024)}`})]}),e.jsx(m,{style:{color:n.colorNeutralForeground3},children:l.displayName})]})}function k({col:l}){const i=(l.maxSizeInKB??10240)*1024;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(h,{style:{color:n.colorBrandForeground1}}),e.jsx("strong",{style:{fontFamily:n.fontFamilyMonospace,fontSize:13},children:l.logicalName}),e.jsx(r,{appearance:"tint",color:"brand",children:"Image"}),l.isPrimaryImage&&e.jsx(r,{appearance:"tint",color:"brand",children:"primary"}),l.canStoreFullImage?e.jsx(r,{appearance:"tint",color:"success",children:"full-size enabled"}):e.jsx(r,{appearance:"tint",color:"subtle",children:"thumbnail only"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"180px 1fr",rowGap:4,fontSize:11},children:[e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Display name"}),e.jsx("span",{children:l.displayName}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Thumbnail size"}),e.jsx("span",{children:"144 × 144 (auto-cropped center)"}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Full-size"}),e.jsx("span",{children:l.canStoreFullImage?`Up to ${g(i)}`:e.jsx("em",{style:{color:n.colorNeutralForeground3},children:"not stored — thumbnail only"})}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Companion columns"}),e.jsx("span",{style:{fontFamily:n.fontFamilyMonospace,fontSize:10},children:(()=>{const t=z(l.logicalName);return`${t.id} · ${t.timestamp} · ${t.url}`})()}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Set on Create?"}),e.jsx("span",{children:l.isPrimaryImage?"Yes — primary image only":"No — Update or PATCH only"}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"File types"}),e.jsx("span",{children:"image/gif · image/jpeg · image/png · image/bmp · image/tiff"})]})]})}export{P as F,T as I};
@@ -0,0 +1 @@
1
+ import{f as B,E as H,g as Be,a as le,b as oe,s as Ue,d as L,m as ie,c as _e,r as u,u as Xe,e as Ye,h as We,i as W,j as Ve,T as He,k as Je,F as Qe,l as ze,C as je,n as Ge,M as Se,o as Ke,L as Ze,p as et,q as t,H as tt,t as at,v as st,w as ve,x as rt,y as nt,z as lt,A as E,B as R,D as ot,R as it,U as ct,S as ut,G as dt,I as J,J as ce,K as ke,N as $,O as pt,P as z,Q as mt,V as ht,W as yt,X as A,Y as F,Z as ft,_ as bt,$ as gt,a0 as xt,a1 as jt,a2 as St,a3 as vt,a4 as N,a5 as Q,a6 as kt,a7 as wt,a8 as we,a9 as Nt,aa as ue,ab as Dt,ac as de,ad as Tt}from"./index-C4fO68cu.js";const pe={eq:"Equal",ne:"NotEqual",gt:"GreaterThan",ge:"GreaterEqual",lt:"LessThan",le:"LessEqual"},Ct=new Set(["On","OnOrAfter","OnOrBefore","Today","Tomorrow","Yesterday","Last7Days","Next7Days","LastWeek","ThisWeek","NextWeek","LastMonth","ThisMonth","NextMonth","LastYear","ThisYear","NextYear","LastXHours","LastXDays","LastXWeeks","LastXMonths","LastXYears","NextXHours","NextXDays","NextXWeeks","NextXMonths","NextXYears","OlderThanXMinutes","OlderThanXHours","OlderThanXDays","OlderThanXWeeks","OlderThanXMonths","OlderThanXYears","ThisFiscalPeriod","ThisFiscalYear","LastFiscalPeriod","LastFiscalYear","NextFiscalPeriod","NextFiscalYear","LastXFiscalPeriods","LastXFiscalYears","NextXFiscalPeriods","NextXFiscalYears","InFiscalPeriod","InFiscalYear","InFiscalPeriodAndYear","InOrAfterFiscalPeriodAndYear","InOrBeforeFiscalPeriodAndYear","Between","NotBetween","In","NotIn","ContainValues","DoesNotContainValues","Above","AboveOrEqual","Under","UnderOrEqual","NotUnder","EqualUserId","NotEqualUserId","EqualBusinessId","NotEqualBusinessId","EqualRoleBusinessId","EqualUserLanguage","EqualUserTeams","EqualUserOrUserTeams","EqualUserOrUserHierarchy","EqualUserOrUserHierarchyAndTeams"]);function me(e){switch(e?.attributeType){case"Integer":case"Picklist":case"State":case"Status":case"MultiSelectPicklist":case"EntityName":return"System.Int32";case"BigInt":return"System.Int64";case"Decimal":case"Money":return"System.Decimal";case"Double":return"System.Double";case"Boolean":return"System.Boolean";case"DateTime":return"System.DateTime";case"Uniqueidentifier":case"Lookup":case"Customer":case"Owner":return"System.Guid";default:return"System.String"}}const Et=e=>e.replace(/[[%_]/g,s=>`[${s}]`);function Rt(e,s){const a=[],l=r=>{if(r.type==="rule"){if(r.col.includes("/"))return a.push(`"${r.col}" filters on a related table — not supported in a bulk delete query.`),null;if(r.valKind==="column")return a.push(`"${r.col}" compares two columns — not supported in a bulk delete query.`),null;const c=le(r.op),p=oe(e,r.col),h=r.val??"";if(c?.kind==="null-check")return{AttributeName:r.col,Operator:r.op==="is-null"?"Null":"NotNull",Values:[]};if(c?.kind==="comparison"&&pe[r.op])return{AttributeName:r.col,Operator:pe[r.op],Values:[{Type:me(p),Value:h}]};if(c?.kind==="odata-fn"){const{value:y}=Ue(h),f=Et(y),d=r.op==="contains"?`%${f}%`:r.op==="startswith"?`${f}%`:`%${f}`;return{AttributeName:r.col,Operator:r.negated?"NotLike":"Like",Values:[{Type:"System.String",Value:d}]}}return a.push(`Operator "${r.op}" on "${r.col}" has no QueryExpression mapping.`),null}if(r.type==="function"){const c=le(r.op);if(!c||!Ct.has(r.op))return a.push(`Query function "${r.op}" has no QueryExpression mapping.`),null;if(r.negated)return a.push(`"not ${r.op}" can't be expressed in a bulk delete query.`),null;if(r.col.includes("/"))return a.push(`"${r.col}" filters on a related table — not supported in a bulk delete query.`),null;const p=c.category==="hierarchy"?e.primaryKey:r.col,h=oe(e,r.col),y=c.kind==="dv-fn-array"?r.values??[]:c.kind==="dv-fn-2"?r.vals??["",""]:c.kind==="dv-fn-0"?[]:[r.val??""],f=c.kind==="dv-fn-1-int"||c.kind==="dv-fn-2"?"System.Int32":c.kind==="dv-fn-guid"?"System.Guid":me(h);return{AttributeName:p,Operator:r.op,Values:y.map(d=>({Type:f,Value:d}))}}return null},n=r=>{r.negated&&a.push('Negated groups ("not (…)") can’t be expressed in a bulk delete query.');const c={FilterOperator:r.combinator==="or"?"Or":"And",Conditions:[],Filters:[]};for(const p of r.rules)if(p.type==="group")c.Filters.push(n(p));else if(p.type==="lambda")a.push(`"${p.nav}/${p.lambda}(…)" filters on related records — not supported in a bulk delete query.`);else{const h=l(p);h&&c.Conditions.push(h)}return c},i=n(s);return{query:a.length?null:{EntityName:e.logicalName,Criteria:i},problems:a}}const $t=/^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i;function he(e){const s=e.split(/[\s,;]+/).map(n=>n.trim()).filter(Boolean),a=[],l=[];for(const n of s)$t.test(n)?a.push(n.replace(/^\{|\}$/g,"").toLowerCase()):l.push(n);return{ids:[...new Set(a)],invalid:l}}const ye=e=>({"@odata.type":"Microsoft.Dynamics.CRM.activityparty",activitypartyid:e});function Ne(e){return e&&e>0?`FREQ=DAILY;INTERVAL=${Math.floor(e)}`:""}function Ot(e,s){if(e.startMode==="at"&&e.startAt){const a=new Date(e.startAt);if(!Number.isNaN(a.getTime()))return a.toISOString()}return s.toISOString()}function At(e){const s=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${s(e.getMonth()+1)}-${s(e.getDate())} ${s(e.getHours())}:${s(e.getMinutes())}`}function De(e,s){return`DRS bulk delete · ${e||"table"} · ${At(s)}`}function Te(e,s){const a=B(e.table);if(!a)return{body:null,problems:["Pick a target table first."],deletesAll:!1};const{query:l,problems:n}=Rt(a,e.filter),i=he(e.toRecipients),r=he(e.ccRecipients),c=[...n];e.jobName.trim()||c.push("Give the job a name."),(i.invalid.length||r.invalid.length)&&c.push(`Not a systemuser id: ${[...i.invalid,...r.invalid].join(", ")}`),e.sendEmail&&i.ids.length===0&&c.push("Email notification needs at least one To recipient (systemuser id)."),e.startMode==="at"&&Number.isNaN(new Date(e.startAt).getTime())&&c.push("Pick a valid start date and time."),e.recurrenceDays!==null&&!(e.recurrenceDays>=1)&&c.push("Recurrence must be every 1 day or more.");const p=!!l&&Ce(l.Criteria);return{body:l?{QuerySet:[l],JobName:e.jobName.trim(),SendEmailNotification:e.sendEmail,ToRecipients:e.sendEmail?i.ids.map(ye):[],CCRecipients:e.sendEmail?r.ids.map(ye):[],RecurrencePattern:Ne(e.recurrenceDays),StartDateTime:Ot(e,s)}:null,problems:c,deletesAll:p}}function Ce(e){return e.Conditions.length===0&&e.Filters.every(Ce)}function Ft(e){const s=B(e.table),a="/BulkDelete",l=`${H.apiBase}${a}`;return{relativeUrl:l,relativeNoBase:a,bytes:l.length,queryParts:[],entitySet:s?.entitySetName??"",entityLogical:s?.logicalName??""}}function Lt(e){const s=B(e.table);if(!s)return null;const a=Be(e.filter,s),l=n=>encodeURIComponent(n).replace(/%2F/g,"/").replace(/%2C/g,",").replace(/%3D/g,"=").replace(/%24/g,"$").replace(/%28/g,"(").replace(/%29/g,")").replace(/%20/g," ").replace(/%27/g,"'").replace(/%3A/g,":");return`${s.entitySetName}?$select=${s.primaryKey}&$count=true&$top=1`+(a?`&$filter=${l(a)}`:"")}const Ee=5e3,Mt={0:"Ready",1:"Suspended",2:"Locked",3:"Completed"},fe={0:"Waiting for resources",10:"Waiting",20:"In progress",21:"Pausing",22:"Canceling",30:"Succeeded",31:"Failed",32:"Canceled"};function Pt(e){return`asyncoperations(${e})?$select=name,statecode,statuscode,message,friendlymessage,createdon,startedon,completedon,postponeuntil,recurrencepattern`}function It(e){return`bulkdeleteoperations?$select=successcount,failurecount,statecode,statuscode,isrecurring&$filter=_asyncoperationid_value eq ${e}`}function qt(e){const{dirty:s,...a}=e;return a}function Bt(e,s){return{...s,...e,dirty:new Set}}const Re=e=>{const s=typeof e=="object"&&e!==null?e:{};return s.message??s.innererror?.message??String(e)};async function Ut(e){const s=Lt(e);if(!s)return{ok:!1,error:"Table metadata not loaded."};try{const l=(await L.queryData(s))["@odata.count"];return typeof l!="number"?{ok:!1,error:"The response had no @odata.count."}:{ok:!0,count:l,capped:l>=Ee}}catch(a){return{ok:!1,error:Re(a)}}}async function _t(e){const{body:s,problems:a}=Te(e,new Date);if(!s||a.length)return ie({statusCode:400,message:a[0]??"Request incomplete."},0);const l=performance.now();try{const n=await L.execute({operationName:"BulkDelete",operationType:"action",parameters:s});return{status:200,statusText:"OK",ms:Math.round(performance.now()-l),bytes:JSON.stringify(n??{}).length,ok:!0,outcome:"ok",body:n??{},headers:{"OData-Version":"4.0"}}}catch(n){return ie(n,Math.round(performance.now()-l))}}function Xt(e){if(!e||typeof e!="object")return null;const s=e.JobId;return typeof s=="string"?s:null}async function Yt(){const s=(await L.execute({operationName:"WhoAmI",operationType:"function"})).UserId;if(typeof s!="string")throw new Error("WhoAmI returned no UserId.");return s.toLowerCase()}async function Wt(e){try{const s=await L.queryData(Pt(e)),a=Array.isArray(s?.value)?s.value[0]??null:s??null;let l=null;try{l=(await L.queryData(It(e)))?.value?.[0]??null}catch{}return{job:a,operation:l}}catch(s){return{job:null,operation:null,error:Re(s)}}}const q="bulk-delete",C="bulk",be=5e3,V=120,ge=()=>({table:"",filter:ve(),jobName:"",sendEmail:!1,toRecipients:"",ccRecipients:"",startMode:"now",startAt:"",recurrenceDays:null,headers:dt()});function Kt({themeMode:e}){const s=_e(q),[a,l]=u.useState(()=>({...ge(),dirty:new Set})),{table:n}=Xe(a.table||null),{entities:i}=Ye(),[r,c]=u.useState("target"),[p,h]=u.useState("builder"),[y,f]=u.useState(null),[d,x]=u.useState(null),[w,j]=u.useState(!1),[g,D]=u.useState(!1),[U,S]=u.useState([]),[v,G]=u.useState(null),[K,Z]=u.useState(void 0),[ee,te]=u.useState(null),[_,$e]=u.useState(()=>new Date);u.useEffect(()=>{const o=window.setInterval(()=>$e(new Date),6e4);return()=>window.clearInterval(o)},[]);const k=B(a.table),O=u.useMemo(()=>Ft(a),[a,n]),{body:Oe,problems:X,deletesAll:M}=u.useMemo(()=>Te(a,_),[a,n,_]),P=u.useMemo(()=>We(a.filter),[a.filter]),ae=(o,m,Y)=>l(re=>{const ne=new Set(re.dirty);return ne.add(Y),{...re,[o]:m,dirty:ne}}),Ae=a.table?k?X.length>0?X[0]:a.headers.some(o=>o.enabled&&!o.name)?"Fix empty header name.":null:"Loading table metadata…":"Pick a target table first.",Fe=async()=>{D(!1),j(!0);const o=await _t(a);f(o),x(o.ok?Xt(o.body):null),j(!1),h("results"),S(m=>[{id:`r-${Date.now()}`,modeId:q,url:O.relativeUrl,method:"POST",ts:Date.now(),status:o.status,ms:o.ms},...m].slice(0,8)),l(m=>({...m,dirty:new Set}))},I=u.useMemo(()=>qt(a),[a]),Le=u.useMemo(()=>W(I),[I]),se=ee===null?!0:Le!==ee,Me=o=>{Z(o.id),te(W(o.state))},Pe=o=>{if(o.modeId!==q)return;const m=o.state;if(i.length>0&&!i.some(Y=>Y.logicalName===m.table)){G(`Can't load "${o.name}": table '${m.table}' isn't available in this environment.`);return}G(null),l(Bt(m,ge())),Z(o.id),te(W(m)),f(null),x(null),c("filter")};Ve(u.useMemo(()=>a.table?{state:I,modeId:q,dirty:se,lastSavedId:K,onSaved:Me,onLoadSaved:Pe}:null,[I,se,K,a.table]));const Ie=[{id:"target",label:"Target",meta:k?`${k.displayName} · ${k.entitySetName}`:"Pick a table",items:[{id:"target",icon:Je,iconFilled:He,label:k?.displayName??"Pick a table",dirty:a.dirty.has("target")}]},{id:"query",label:"Query",meta:P?`${P} condition${P===1?"":"s"}`:"all rows",items:[{id:"filter",icon:ze,iconFilled:Qe,label:"Criteria",code:!0,badge:M?"ALL":P||null,badgeAppearance:"tint",badgeColor:M?"danger":"brand",dirty:a.dirty.has("filter")}]},{id:"job",label:"Job",meta:a.recurrenceDays?`every ${a.recurrenceDays} d`:"run once",items:[{id:"job",icon:Ge,iconFilled:je,label:"Name & schedule",badge:a.startMode==="at"?"scheduled":null,dirty:a.dirty.has("job")},{id:"notify",icon:Ke,iconFilled:Se,label:"Email notification",badge:a.sendEmail?"on":null,dirty:a.dirty.has("notify")}]},{id:"headers",label:"Headers",meta:`${a.headers.filter(o=>o.enabled).length} active`,items:[{id:"headers",icon:et,iconFilled:Ze,label:"HTTP headers",badge:a.headers.filter(o=>o.enabled).length||null,dirty:a.dirty.has("headers")}]}];let T=null;switch(r){case"target":T=t.jsx(st,{table:a.table,onTableChange:o=>{l(m=>({...m,table:o,filter:ve(),jobName:m.jobName&&!m.jobName.startsWith("DRS bulk delete")?m.jobName:o?De(o,new Date):"",dirty:new Set(["target","filter"])})),f(null),x(null)},group:C,sub:"Rows of this table that match the query are deleted by an asynchronous system job. Switching the target clears the query."});break;case"filter":T=t.jsxs("div",{children:[t.jsx(Vt,{deletesAll:M,problems:X,tbl:k}),t.jsx(at,{table:a.table,tree:a.filter,setTree:o=>ae("filter",o,"filter"),group:C})]});break;case"job":T=t.jsx(Ht,{state:a,now:_,onChange:o=>l(m=>({...m,...o,dirty:new Set([...m.dirty,"job"])}))});break;case"notify":T=t.jsx(Jt,{state:a,onChange:o=>l(m=>({...m,...o,dirty:new Set([...m.dirty,"notify"])}))});break;case"headers":T=t.jsx(tt,{items:a.headers,setItems:o=>ae("headers",o,"headers"),group:C});break}const qe={method:"POST",built:O,headers:rt(a.headers,null),body:Oe??{},entityLogical:O.entityLogical};return t.jsxs(nt,{sidebar:t.jsx(ut,{type:s,urlPreview:O.relativeNoBase,sections:Ie,activeNode:r,onSelect:o=>{c(o),h("builder")},recents:U}),urlBar:t.jsx(ct,{method:"POST",url:O.relativeUrl,executeVerb:s.executeVerb,disabledReason:Ae,loading:w,onExecute:async()=>D(!0)}),children:[t.jsxs(lt,{tab:p,onTabChange:h,resultCount:null,children:[p==="builder"&&t.jsxs(t.Fragment,{children:[v&&t.jsx(E,{intent:"error",style:{marginBottom:12},children:t.jsx(R,{children:v})}),T]}),p==="code"&&t.jsx(ot,{themeMode:e,inputs:qe,group:C}),p==="results"&&(y?.ok&&d?t.jsx(zt,{jobId:d,result:y}):t.jsx(it,{result:y,mode:"single",table:a.table}))]}),g&&k&&t.jsx(Qt,{state:a,tbl:k,deletesAll:M,onCancel:()=>D(!1),onConfirm:Fe})]})}function Vt({deletesAll:e,problems:s,tbl:a}){if(!a)return null;const l=s.filter(n=>/bulk delete query|mapping/.test(n));return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:12},children:[e&&t.jsx(E,{intent:"error",layout:"multiline",children:t.jsxs(R,{children:[t.jsxs(J,{children:["No conditions — every ",a.displayName," row matches"]}),"Add at least one condition unless you really mean to empty the table."]})}),l.length>0&&t.jsx(E,{intent:"error",layout:"multiline",children:t.jsxs(R,{children:[t.jsx(J,{children:"Can't convert to a QueryExpression"}),t.jsx("ul",{style:{margin:"4px 0 0",paddingLeft:18},children:l.map(n=>t.jsx("li",{children:n},n))})]})}),t.jsx(E,{intent:"info",layout:"multiline",children:t.jsxs(R,{children:["BulkDelete takes a ",t.jsx("code",{children:"QueryExpression"}),", so this $filter is converted: comparisons, null checks, contains / starts / ends with (as ",t.jsx("code",{children:"Like"}),"), and the Dataverse query functions map 1:1. Related-table paths, any/all, column-to-column comparisons and negated groups or functions aren't supported. The confirmation counts matches with the same $filter before anything is submitted."]})})]})}function Ht({state:e,now:s,onChange:a}){return t.jsxs("div",{style:{maxWidth:640,display:"flex",flexDirection:"column",gap:14},children:[t.jsx(we,{icon:je,title:"Job",sub:"The bulk delete runs as a system job; it only deletes rows created before it starts.",group:C}),t.jsx(N,{label:"Job name",required:!0,children:t.jsx(Q,{value:e.jobName,placeholder:De(e.table,s),onChange:(l,n)=>a({jobName:n.value})})}),t.jsx(N,{label:"Start",children:t.jsxs(Nt,{value:e.startMode,onChange:(l,n)=>a({startMode:n.value}),children:[t.jsx(ue,{value:"now",label:"Immediately (StartDateTime = when you send)"}),t.jsx(ue,{value:"at",label:"At a specific time"})]})}),e.startMode==="at"&&t.jsx(N,{label:"Start date and time (your local time)",children:t.jsx(Q,{type:"datetime-local",value:e.startAt,onChange:(l,n)=>a({startAt:n.value})})}),t.jsx(z,{checked:e.recurrenceDays!==null,onChange:(l,n)=>a({recurrenceDays:n.checked?7:null}),label:"Repeat the job"}),e.recurrenceDays!==null&&t.jsx(N,{label:"Every N days",hint:t.jsxs(t.Fragment,{children:["RecurrencePattern ",t.jsx("code",{children:Ne(e.recurrenceDays)||"—"}),". A recurring job keeps deleting new matching rows until you cancel it in System Jobs."]}),children:t.jsx(Dt,{min:1,max:365,value:e.recurrenceDays,onChange:(l,n)=>{const i=n.value??Number(n.displayValue);Number.isFinite(i)&&a({recurrenceDays:Math.max(1,Math.floor(i))})}})})]})}function Jt({state:e,onChange:s}){const[a,l]=u.useState(null),n=async()=>{try{const i=await Yt();e.toRecipients.toLowerCase().includes(i)||s({toRecipients:[e.toRecipients.trim(),i].filter(Boolean).join(", ")}),l(null)}catch(i){l(i instanceof Error?i.message:String(i))}};return t.jsxs("div",{style:{maxWidth:640,display:"flex",flexDirection:"column",gap:14},children:[t.jsx(we,{icon:Se,title:"Email notification",sub:"Email users when the job finishes. Recipients are systemuser ids with a valid email address.",group:C}),t.jsx(z,{checked:e.sendEmail,onChange:(i,r)=>s({sendEmail:r.checked}),label:"Send an email when the job completes"}),e.sendEmail&&t.jsxs(t.Fragment,{children:[t.jsx(N,{label:"To (systemuser ids)",required:!0,hint:"Comma, space or new-line separated.",children:t.jsx(de,{value:e.toRecipients,onChange:(i,r)=>s({toRecipients:r.value}),rows:2})}),t.jsxs("div",{children:[t.jsx($,{icon:t.jsx(Tt,{}),onClick:()=>{n()},children:"Add me"}),a&&t.jsx(F,{style:{color:A.colorPaletteRedForeground1,marginLeft:8},children:a})]}),t.jsx(N,{label:"Cc (systemuser ids)",children:t.jsx(de,{value:e.ccRecipients,onChange:(i,r)=>s({ccRecipients:r.value}),rows:2})})]})]})}function Qt({state:e,tbl:s,deletesAll:a,onCancel:l,onConfirm:n}){const[i,r]=u.useState(null),[c,p]=u.useState(""),[h,y]=u.useState(!1);u.useEffect(()=>{let j=!1;return Ut(e).then(g=>{j||r(g)}),()=>{j=!0}},[]);const f=c.trim()===s.logicalName,d=i?.ok&&i.count===0,x=f&&i!==null&&(!a||h)&&!(d&&!e.recurrenceDays),w=e.startMode==="at"&&e.startAt?new Date(e.startAt).toLocaleString():"as soon as the system job runs";return t.jsx(ft,{open:!0,modalType:"alert",onOpenChange:(j,g)=>!g.open&&l(),children:t.jsx(bt,{style:{maxWidth:560},children:t.jsxs(gt,{children:[t.jsxs(xt,{children:["Delete ",s.displayName," rows in bulk?"]}),t.jsxs(jt,{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsx(E,{intent:"error",layout:"multiline",children:t.jsxs(R,{children:[t.jsx(J,{children:"This permanently deletes data"}),"Deleted rows can't be restored, related rows follow the table's cascade rules, plug-ins and flows on Delete run for every row, and a failed job doesn't roll back what it already deleted."]})}),t.jsx("div",{children:i===null?t.jsx(St,{size:"tiny",label:"Counting matching rows…",labelPosition:"after"}):i.ok?t.jsxs(ke,{weight:"semibold",size:400,children:[i.capped?`${Ee.toLocaleString()} or more`:i.count.toLocaleString()," ",s.displayName," row",i.count===1?"":"s"," match right now."]}):t.jsxs(F,{style:{color:A.colorPaletteRedForeground1},children:["Couldn't count matching rows: ",i.error]})}),d&&!e.recurrenceDays&&t.jsx(F,{children:"Nothing matches, so there's nothing to delete."}),t.jsxs(F,{children:["Job ",t.jsx("strong",{children:e.jobName||"(unnamed)"})," starts ",w,e.recurrenceDays?` and repeats every ${e.recurrenceDays} day${e.recurrenceDays===1?"":"s"}, deleting rows that match at each run`:"","."]}),a&&t.jsx(vt,{checked:h,onChange:(j,g)=>y(!!g.checked),label:`The query has no conditions — delete every ${s.displayName} row.`}),t.jsx(N,{label:t.jsxs(t.Fragment,{children:["Type the table name ",t.jsx("code",{children:s.logicalName})," to confirm"]}),children:t.jsx(Q,{value:c,onChange:(j,g)=>p(g.value),autoComplete:"off","aria-label":"Table logical name"})})]}),t.jsxs(kt,{children:[t.jsx($,{appearance:"secondary",onClick:l,children:"Cancel"}),t.jsx($,{appearance:"primary",icon:t.jsx(wt,{}),disabled:!x,onClick:n,style:x?{backgroundColor:A.colorPaletteRedBackground3,color:A.colorNeutralForegroundOnBrand}:void 0,children:"Submit bulk delete job"})]})]})})})}function xe(e){return typeof e=="number"?e:void 0}function b(e,s,a){if(!e)return"—";const l=e[`${s}@OData.Community.Display.V1.FormattedValue`];if(typeof l=="string")return l;const n=e[s];return a&&typeof n=="number"?a[n]??String(n):n==null||n===""?"—":String(n)}function zt({jobId:e,result:s}){const[a,l]=u.useState(null),[n,i]=u.useState(0),[r,c]=u.useState(!0),[p,h]=u.useState(!1),y=xe(a?.job?.statecode)===3,f=async()=>{const S=await Wt(e);l(S),i(v=>v+1)};u.useEffect(()=>{f()},[e]),u.useEffect(()=>{if(!r||y||n>=V)return;const S=window.setTimeout(()=>{f()},be);return()=>window.clearTimeout(S)},[r,y,n]);const d=a?.job??null,x=a?.operation??null,w=xe(d?.statuscode),j=w===30?"success":w===31||w===32?"danger":"info",g=H.host?`https://${H.host}/main.aspx?pagetype=entityrecord&etn=asyncoperation&id=${e}`:"",D={padding:"4px 12px 4px 0",verticalAlign:"top"},U=[["Job id",t.jsx("code",{children:e},"id")],["Name",b(d,"name")],["State",b(d,"statecode",Mt)],["Status",b(d,"statuscode",fe)],["Deleted",x?b(x,"successcount"):"—"],["Failed",x?b(x,"failurecount"):"—"],["Created",b(d,"createdon")],["Started",b(d,"startedon")],["Completed",b(d,"completedon")],["Recurrence",b(d,"recurrencepattern")],["Message",b(d,"friendlymessage")!=="—"?b(d,"friendlymessage"):b(d,"message")]];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,maxWidth:760},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsx(ce,{status:"success",code:s.status,ms:s.ms}),t.jsx(ke,{weight:"semibold",children:"Bulk delete job submitted"}),a&&t.jsx(ce,{status:j,code:b(d,"statuscode",fe)})]}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[t.jsx($,{icon:t.jsx(pt,{}),onClick:()=>{f()},children:"Refresh"}),t.jsx(z,{checked:r&&!y&&n<V,disabled:y||n>=V,onChange:(S,v)=>c(v.checked),label:y?"Job completed":`Auto-refresh every ${be/1e3} s`}),t.jsx($,{icon:t.jsx(ht,{}),onClick:()=>{mt(e).then(()=>h(!0))},children:p?"Copied":"Copy job id"}),g&&t.jsx($,{as:"a",href:g,target:"_blank",rel:"noreferrer",icon:t.jsx(yt,{}),appearance:"subtle",children:"Open system job"})]}),a?.error&&t.jsx(E,{intent:"warning",children:t.jsxs(R,{children:["Couldn't read the job: ",a.error]})}),t.jsx("table",{style:{borderCollapse:"collapse",fontSize:13},children:t.jsx("tbody",{children:U.map(([S,v])=>t.jsxs("tr",{children:[t.jsx("td",{style:{...D,color:A.colorNeutralForeground3},children:S}),t.jsx("td",{style:D,children:v})]},S))})}),t.jsxs(F,{children:["Status comes from ",t.jsxs("code",{children:["asyncoperations(",e,")"]}),"; deleted / failed counts from the matching ",t.jsx("code",{children:"bulkdeleteoperations"})," row once the job has run."]})]})}export{Kt as BulkDeleteMode};
@@ -0,0 +1,6 @@
1
+ import{f as P,E as Je,ae as Ze,af as we,b as Qe,d as je,m as ge,ag as Ye,c as Xe,r as y,u as et,e as tt,ah as st,ai as at,aj as rt,ak as nt,al as it,i as X,j as ot,am as ke,an as lt,T as dt,k as ct,ao as ve,ap as ut,aq as Se,ar as pt,L as ht,p as mt,as as fe,at as yt,q as t,Y as M,au as gt,H as ft,v as bt,x as be,y as xt,z as wt,A as $,B as R,D as jt,R as kt,U as vt,S as St,a8 as ae,N as k,av as Ct,aw as Ce,ax as $e,V as re,ay as te,a4 as $t,a5 as Re,az as Rt,aA as Mt,aB as It,I as Me,X as E,aC as ee,aD as Dt,a9 as Ft,aa as Nt,a2 as Bt,J as At,K as Ut,Q as Lt,Z as Tt,_ as Ot,$ as Et,a0 as Pt,a1 as qt,ac as Vt,a3 as _t,a6 as Kt,aE as zt,G as Gt,aF as Wt}from"./index-C4fO68cu.js";const Ie=["CreateMultiple","UpdateMultiple","UpsertMultiple","DeleteMultiple"],Ht=1e3,Jt=100,Zt=/^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i,De=s=>Zt.test(s.trim()),Fe=s=>s.trim().replace(/^\{|\}$/g,"").toLowerCase();let Qt=1;function G(s){return{id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`row_${crypto.randomUUID()}`:`row_${Date.now().toString(36)}_${(Qt++).toString(36)}`,key:s?.key??"",fieldValues:s?.fieldValues??{},nullFields:s?.nullFields??[]}}function Yt(s){return G({key:"",fieldValues:Xt(s.fieldValues),nullFields:[...s.nullFields]})}function Xt(s){return JSON.parse(JSON.stringify(s))}const q={CreateMultiple:{label:"Create multiple",description:"Creates every row in one request and returns the new ids.",keyRequired:!1,allowsAlternateKey:!1,usesFields:!0,fieldPurpose:"create",successStatus:200},UpdateMultiple:{label:"Update multiple",description:"Updates rows addressed by their primary key (GUID). Send only changed columns.",keyRequired:!0,allowsAlternateKey:!1,usesFields:!0,fieldPurpose:"update",successStatus:204},UpsertMultiple:{label:"Upsert multiple",description:"Creates or updates each row, addressed by primary key or an alternate key. Needs a table that supports both CreateMultiple and UpdateMultiple.",keyRequired:!0,allowsAlternateKey:!0,usesFields:!0,fieldPurpose:"upsert",successStatus:204},DeleteMultiple:{label:"Delete multiple",description:"Deletes rows by primary key. Elastic tables only — for standard tables use Bulk Delete.",keyRequired:!0,allowsAlternateKey:!1,usesFields:!0,fieldPurpose:"update",successStatus:204}};function es(s,a){return Ze({table:s,fieldValues:a.fieldValues,nullFields:a.nullFields})}function ts(s,a,e){const r=q[s.operation],i={"@odata.type":`Microsoft.Dynamics.CRM.${a.logicalName}`},l=r.usesFields?es(s.table,e):{};Object.assign(i,l);const u=e.key.trim();let c;if(u?De(u)?i[a.primaryKey]=Fe(u):r.allowsAlternateKey?i["@odata.id"]=`${a.entitySetName}(${u})`:c=s.operation==="UpdateMultiple"?"Key must be a GUID — UpdateMultiple in the Web API does not accept alternate keys.":"Key must be a GUID.":r.keyRequired&&(c=s.operation==="UpsertMultiple"?"Missing key — a GUID or an alternate key such as name='value'.":"Missing primary key (GUID)."),!c&&s.operation!=="DeleteMultiple"&&Object.keys(l).length===0&&(c="No column values set."),!c&&s.operation==="CreateMultiple"){const o=ss(a,e);o.length>0&&(c=`Required column${o.length===1?"":"s"} unset: ${o.slice(0,3).join(", ")}${o.length>3?"…":""}`)}return{target:i,issue:c}}function ss(s,a){return s.columns.filter(e=>e.requiredLevel==="ApplicationRequired"&&e.isValidForCreate!==!1).filter(e=>{const r=a.fieldValues[e.logicalName];return r==null||r===""?!0:Array.isArray(r)?r.length===0:we(e)?!r?.id:!1}).map(e=>e.logicalName)}function Ne(s){const a=P(s.table);if(!a)return{body:{Targets:[]},issues:[]};const e=[],r=new Map;return{body:{Targets:s.rows.map((l,u)=>{const{target:c,issue:o}=ts(s,a,l);o&&e.push({rowIndex:u,rowId:l.id,message:o});const h=l.key.trim().toLowerCase();if(h){const p=r.get(h);p!==void 0?e.push({rowIndex:u,rowId:l.id,message:s.operation==="UpdateMultiple"?`Same key as row ${p+1} — UpdateMultiple applies only the first of them.`:`Same key as row ${p+1} — duplicate keys fail the request.`}):r.set(h,u)}return c})},issues:e}}function as(s){const a=P(s.table);if(!a)return{relativeUrl:"",relativeNoBase:"",bytes:0,queryParts:[],entitySet:"",entityLogical:""};const e=`/${a.entitySetName}/Microsoft.Dynamics.CRM.${s.operation}`,r=`${Je.apiBase}${e}`;return{relativeUrl:r,relativeNoBase:e,bytes:r.length,queryParts:[],entitySet:a.entitySetName,entityLogical:a.logicalName}}function rs(s){return s==="UpsertMultiple"?["CreateMultiple","UpdateMultiple"]:[s]}function ns(s,a){const e=r=>`'${r.replace(/'/g,"''")}'`;return`sdkmessagefilters?$select=sdkmessagefilterid&$filter=sdkmessageid/name eq ${e(s)} and primaryobjecttypecode eq ${e(a)}`}function is(s,a,e){const r=P(s.table);if(!s.table)return"Pick a target table first.";if(!r)return"Loading table metadata…";if(e.state==="unsupported")return e.message;if(s.rows.length===0)return"Add at least one row.";if(a.length>0){const i=a[0];return`Row ${i.rowIndex+1}: ${i.message}${a.length>1?` (+${a.length-1} more)`:""}`}return s.headers.some(i=>i.enabled&&!i.name)?"Fix empty header name.":null}function os(s,a,e){return s==="DeleteMultiple"?`DeleteMultiple isn't available for '${a}'. It's supported on elastic tables only — use the Bulk Delete mode (an asynchronous job) for standard tables.`:s==="UpsertMultiple"?`UpsertMultiple needs both CreateMultiple and UpdateMultiple, and '${a}' doesn't support ${e.join(" or ")}.`:`'${a}' doesn't support ${s} (no sdkmessagefilter for this table).`}const ls=new Set(["@key","key","id","@odata.id"]);function ds(s,a){const e=s.trim();if(!e)return{rows:[],skippedColumns:[],errors:[]};let r;if(e.startsWith("[")||e.startsWith("{")){let c;try{c=JSON.parse(e)}catch(h){return{rows:[],skippedColumns:[],errors:[`Invalid JSON: ${h instanceof Error?h.message:String(h)}`]}}const o=Array.isArray(c)?c:c&&typeof c=="object"?c.Targets??c.value:void 0;if(!Array.isArray(o))return{rows:[],skippedColumns:[],errors:['JSON must be an array of objects (or { "Targets": [ … ] }).']};r=o.filter(h=>!!h&&typeof h=="object")}else{const c=ys(e);if(c.length<2)return{rows:[],skippedColumns:[],errors:["CSV needs a header row and at least one data row."]};const[o,...h]=c;r=h.filter(p=>p.some(g=>g.trim()!=="")).map(p=>{const g={};return o.forEach((j,S)=>{const b=p[S];b!==void 0&&b!==""&&(g[j.trim()]=b)}),g})}const i=new Set,l=[];return{rows:r.map((c,o)=>{const h=G();for(const[p,g]of Object.entries(c)){const j=p.trim();if(j==="@odata.type"||j==="@odata.etag"||g===void 0)continue;if(ls.has(j.toLowerCase())||j.toLowerCase()===a.primaryKey){h.key=cs(String(g??""),a);continue}const S=/^(.+)@odata\.bind$/i.exec(j),b=us(a,S?S[1]:j);if(!b){i.add(j);continue}if(g===null){h.nullFields.push(b.logicalName);continue}const x=ps(b,g);"error"in x?l.push(`Row ${o+1}, ${j}: ${x.error}`):h.fieldValues[b.logicalName]=x.value}return h}),skippedColumns:[...i],errors:l}}function cs(s,a){const e=/^\/?([A-Za-z0-9_]+)\((.*)\)$/.exec(s.trim());return e&&e[1]===a.entitySetName?e[2]:s.trim()}function us(s,a){const e=a.toLowerCase(),r=Qe(s,e);if(r)return r;const i=s.columns.find(l=>we(l)&&e.startsWith(`${l.logicalName}_`));return i||s.columns.find(l=>l.displayName.toLowerCase()===e)}function xe(s,a){if(typeof a=="number")return a;const e=String(a).trim();return/^-?\d+$/.test(e)?Number(e):s.find(r=>r.label.toLowerCase()===e.toLowerCase())?.value}function ps(s,a){const e=typeof a=="string"?a.trim():a;switch(s.attributeType){case"Integer":case"BigInt":case"Decimal":case"Double":case"Money":{const r=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(r)?(s.attributeType==="Integer"||s.attributeType==="BigInt")&&!Number.isInteger(r)?{error:`"${String(a)}" is not a whole number`}:{value:r}:{error:`"${String(a)}" is not a number`}}case"Boolean":{if(typeof e=="boolean")return{value:e};const r=String(e).toLowerCase();return["true","1","yes","y"].includes(r)?{value:!0}:["false","0","no","n"].includes(r)?{value:!1}:r===s.trueOption.label.toLowerCase()?{value:!0}:r===s.falseOption.label.toLowerCase()?{value:!1}:{error:`"${String(a)}" is not a yes/no value`}}case"Picklist":case"State":case"Status":case"EntityName":{const r=xe(s.options,e);return r===void 0?{error:`unknown choice "${String(a)}"`}:{value:r}}case"MultiSelectPicklist":{const r=Array.isArray(e)?e:String(e).split(/[,;]/).map(l=>l.trim()).filter(Boolean),i=[];for(const l of r){const u=xe(s.options,l);if(u===void 0)return{error:`unknown choice "${String(l)}"`};i.push(u)}return{value:i}}case"Lookup":case"Customer":case"Owner":{const r=String(e),i=/^\/?([A-Za-z0-9_]+)\(\{?([0-9a-fA-F-]{36})\}?\)$/.exec(r);if(i){const o=s.targets.find(h=>P(h)?.entitySetName===i[1]);return o?{value:{id:i[2].toLowerCase(),targetEntity:o}}:{error:`"${i[1]}" is not a target of ${s.logicalName}`}}const l=/^([A-Za-z0-9_]+):\s*(.+)$/.exec(r),u=l?l[1].toLowerCase():s.targets[0],c=l?l[2]:r;return De(c)?s.targets.includes(u)?{value:{id:Fe(c),targetEntity:u}}:{error:`"${u}" is not a target of ${s.logicalName}`}:{error:`"${r}" is not a GUID`}}case"File":case"Image":return{error:"file and image columns can’t be set in a bulk write"};default:return{value:typeof e=="string"?e:String(e)}}}function hs(s){const{dirty:a,...e}=s;return e}function ms(s,a){return{...a,...s,operation:Ie.includes(s.operation)?s.operation:"CreateMultiple",rows:(s.rows??[]).map(e=>({id:e.id||G().id,key:e.key??"",fieldValues:e.fieldValues??{},nullFields:e.nullFields??[]})),dirty:new Set}}function ys(s){const a=s.split(/\r?\n/,1)[0],e=a.includes(" ")&&!a.includes(",")?" ":",",r=[];let i=[],l="",u=!1;for(let c=0;c<s.length;c++){const o=s[c];if(u){o==='"'?s[c+1]==='"'?(l+='"',c++):u=!1:l+=o;continue}o==='"'&&l===""?u=!0:o===e?(i.push(l),l=""):o===`
2
+ `||o==="\r"?(o==="\r"&&s[c+1]===`
3
+ `&&c++,i.push(l),r.push(i),i=[],l=""):l+=o}return i.push(l),r.push(i),r}async function gs(s,a){try{const e=[];for(const r of rs(a))(await je.queryData(ns(r,s)))?.value?.length||e.push(r);return e.length===0?{state:"supported"}:{state:"unsupported",message:os(a,s,e)}}catch(e){return{state:"unknown",message:`Couldn't check ${a} availability: ${e instanceof Error?e.message:String(e)}`}}}async function fs(s,a){const{body:e,issues:r}=Ne(s);if(r.length>0)return ge({statusCode:400,message:`Row ${r[0].rowIndex+1}: ${r[0].message}`},0);const i=Ye(a),l=performance.now();try{const u=await je.execute({operationName:s.operation,operationType:"action",entityName:s.table,parameters:e},i),c=Math.round(performance.now()-l),o=u&&Object.keys(u).length>0?u:null;return{status:o?200:204,statusText:o?"OK":"No Content",ms:c,bytes:o?JSON.stringify(o).length:0,ok:!0,outcome:"ok",body:o,headers:{"OData-Version":"4.0"}}}catch(u){return ge(u,Math.round(performance.now()-l),i)}}function se(s){if(!s||typeof s!="object")return[];const a=s.Ids;return Array.isArray(a)?a.filter(e=>typeof e=="string"):[]}const z="bulk-write",D="bulk",A=100,bs=25,Be=()=>({table:"",operation:"CreateMultiple",rows:[],headers:Gt(),bypass:zt()}),xs=()=>({...Be(),dirty:new Set}),O=s=>`row:${s}`;function Rs({themeMode:s}){const a=Xe(z),[e,r]=y.useState(xs),{table:i}=et(e.table||null),{entities:l}=tt(),[u,c]=y.useState("target"),[o,h]=y.useState("builder"),[p,g]=y.useState(null),[j,S]=y.useState("CreateMultiple"),[b,x]=y.useState(!1),[W,H]=y.useState([]),[w,v]=y.useState({state:"idle"}),[J,F]=y.useState(!1),[I,U]=y.useState(null),[Z,V]=y.useState(void 0),[ne,ie]=y.useState(null),C=P(e.table),L=y.useMemo(()=>as(e),[e,i]),{body:Ae,issues:T}=y.useMemo(()=>Ne(e),[e,i]),Ue=q[e.operation];y.useEffect(()=>{if(!e.table){v({state:"idle"});return}if(!st()){v({state:"unknown",message:"Not connected to Power Platform ToolBox — availability not checked."});return}let n=!1;return v({state:"checking"}),gs(e.table,e.operation).then(d=>{n||v(d)}),()=>{n=!0}},[e.table,e.operation]);const oe=(n,d)=>{const m=new Set(n.dirty);return m.add(d),m},Q=(n,d,m)=>r(f=>({...f,[n]:d,dirty:oe(f,m)})),B=n=>r(d=>({...d,rows:n(d.rows),dirty:oe(d,"rows")})),le=(n,d)=>B(m=>m.map(f=>f.id===n?{...f,...d}:f)),Le=()=>G({fieldValues:C&&e.operation==="CreateMultiple"?Wt(C):{}}),Te=n=>{const d=Le();B(m=>[...m,d])},de=n=>{const d=e.rows.find(f=>f.id===n);if(!d)return;const m=Yt(d);B(f=>{const We=f.findIndex(He=>He.id===n),ye=[...f];return ye.splice(We+1,0,m),ye})},ce=n=>{B(d=>d.filter(m=>m.id!==n)),u===O(n)&&c("rows")},_=y.useMemo(()=>at(e.headers,e.bypass),[e.headers,e.bypass]),ue=y.useMemo(()=>[...rt(e.bypass,"bypass"),...nt({op:"create",bypass:e.bypass})],[e.bypass]),Oe=it(ue),Ee=is(e,T,w)??(w.state==="checking"?`Checking ${e.operation} availability…`:null),Pe=async()=>{x(!0);const n=e.operation,d=await fs(e,be(_,null));g(d),S(n),x(!1),h("results");const m=se(d.body);H(f=>[{id:`r-${Date.now()}`,modeId:z,url:L.relativeUrl,method:"POST",ts:Date.now(),status:d.status,ms:d.ms,rowCount:d.ok?m.length||e.rows.length:0},...f].slice(0,8)),r(f=>({...f,dirty:new Set}))},K=y.useMemo(()=>hs(e),[e]),qe=y.useMemo(()=>X(K),[K]),pe=ne===null?!0:qe!==ne,Ve=n=>{V(n.id),ie(X(n.state))},_e=n=>{if(n.modeId!==z)return;const d=n.state;if(l.length>0&&!l.some(m=>m.logicalName===d.table)){U(`Can't load "${n.name}": table '${d.table}' isn't available in this environment.`);return}U(null),r(ms(d,Be())),V(n.id),ie(X(d)),g(null),c("rows")};ot(y.useMemo(()=>e.table?{state:K,modeId:z,dirty:pe,lastSavedId:Z,onSaved:Ve,onLoadSaved:_e}:null,[K,pe,Z,e.table]));const Y=y.useMemo(()=>{const n=new Map;for(const d of T)n.has(d.rowId)||n.set(d.rowId,d.message);return n},[T]),he=(n,d)=>{const m=C?n.fieldValues[C.primaryName]:void 0,f=n.key||typeof m=="string"&&m||"";return f?`#${d+1} · ${f}`:`#${d+1}`},Ke=e.rows.slice(0,bs).map((n,d)=>{const m=Y.get(n.id),f=Object.keys(n.fieldValues).length+n.nullFields.length;return{id:O(n.id),icon:lt,iconFilled:ke,label:he(n,d),badge:m?"!":f||null,badgeAppearance:"tint",badgeColor:m?"danger":"success"}}),me=w.state==="supported"?{badge:"supported",color:"success"}:w.state==="unsupported"?{badge:"unsupported",color:"danger"}:w.state==="checking"?{badge:"…",color:"subtle"}:w.state==="unknown"?{badge:"?",color:"warning"}:{badge:null,color:"subtle"},ze=[{id:"target",label:"Target",meta:C?`${C.displayName} · ${C.entitySetName}`:"Pick a table",items:[{id:"target",icon:ct,iconFilled:dt,label:C?.displayName??"Pick a table",dirty:e.dirty.has("target")}]},{id:"operation",label:"Operation",meta:e.operation,items:[{id:"operation",icon:ut,iconFilled:ve,label:Ue.label,badge:me.badge,badgeAppearance:"tint",badgeColor:me.color,dirty:e.dirty.has("operation")}]},{id:"rows",label:"Rows",meta:`${e.rows.length} row${e.rows.length===1?"":"s"}`,items:[{id:"rows",icon:pt,iconFilled:Se,label:"All rows",badge:T.length||null,badgeAppearance:"tint",badgeColor:"danger",dirty:e.dirty.has("rows"),children:Ke}]},{id:"headers",label:"Headers",meta:`${_.filter(n=>n.enabled).length} active`,items:[{id:"headers",icon:mt,iconFilled:ht,label:"HTTP headers",badge:_.filter(n=>n.enabled).length||null,dirty:e.dirty.has("headers")},{id:"bypass",icon:fe,iconFilled:fe,label:"Bypass logic",badge:yt(e.bypass),badgeAppearance:e.bypass.businessLogic!=="none"||e.bypass.suppressFlows?"tint":"ghost",badgeColor:e.bypass.businessLogic!=="none"||e.bypass.suppressFlows?"warning":"subtle",dirty:e.dirty.has("bypass")}]}];let N=null;if(u.startsWith("row:")){const n=e.rows.findIndex(m=>O(m.id)===u),d=e.rows[n];N=d?t.jsx(vs,{row:d,index:n,count:e.rows.length,table:e.table,tbl:C,operation:e.operation,issue:Y.get(d.id),themeMode:s,onPatch:m=>le(d.id,m),onNavigate:m=>c(O(e.rows[m].id)),onBack:()=>c("rows"),onDuplicate:()=>de(d.id),onRemove:()=>ce(d.id)},d.id):t.jsx(M,{children:"That row was removed."})}else switch(u){case"target":N=t.jsx(bt,{table:e.table,onTableChange:n=>{r(d=>({...d,table:n,rows:[],dirty:new Set(["target","rows"])})),g(null)},group:D,sub:"Every row in a bulk request targets the same table. Switching the target clears the rows."});break;case"operation":N=t.jsx(ws,{operation:e.operation,setOperation:n=>Q("operation",n,"operation"),support:w,table:e.table});break;case"rows":N=t.jsx(ks,{state:e,tbl:C,issueByRow:Y,issueCount:T.length,rowLabel:he,onAdd:()=>Te(),onImport:()=>F(!0),onClear:()=>B(()=>[]),onEdit:n=>c(O(n)),onDuplicate:de,onRemove:ce,onKeyChange:(n,d)=>le(n,{key:d})});break;case"headers":N=t.jsx(ft,{items:e.headers,setItems:n=>Q("headers",n,"headers"),group:D,sendsHeaders:!0});break;case"bypass":N=t.jsx(gt,{value:e.bypass,onChange:n=>Q("bypass",n,"bypass"),group:D});break}const Ge={method:"POST",built:L,headers:be(_,null),body:Ae,entityLogical:L.entityLogical};return t.jsxs(xt,{sidebar:t.jsx(St,{type:a,urlPreview:L.relativeNoBase,sections:ze,activeNode:u,onSelect:n=>{c(n),h("builder")},recents:W}),urlBar:t.jsx(vt,{method:"POST",url:L.relativeUrl,executeVerb:a.executeVerb,disabledReason:Ee??Oe,loading:b,onExecute:Pe,advisories:ue,onAdvisoryFocus:c}),children:[t.jsxs(wt,{tab:o,onTabChange:h,resultCount:p?.ok&&se(p.body).length||null,children:[o==="builder"&&t.jsxs(t.Fragment,{children:[I&&t.jsx($,{intent:"error",style:{marginBottom:12},children:t.jsx(R,{children:I})}),N]}),o==="code"&&t.jsx(jt,{themeMode:s,inputs:Ge,group:D}),o==="results"&&(p&&p.ok?t.jsx(Cs,{result:p,operation:j}):t.jsx(kt,{result:p,mode:"single",table:e.table}))]}),t.jsx(Ss,{open:J,tbl:C,onClose:()=>F(!1),onImport:(n,d)=>{B(m=>d?n:[...m,...n]),F(!1),c("rows")}})]})}function ws({operation:s,setOperation:a,support:e,table:r}){return t.jsxs("div",{style:{maxWidth:760},children:[t.jsx(ae,{icon:ve,title:"Operation",sub:"One request, many rows of the same table. On standard tables the whole request rolls back if any row fails.",group:D}),t.jsx(Ft,{value:s,onChange:(i,l)=>a(l.value),"aria-label":"Bulk operation",children:Ie.map(i=>t.jsx(Nt,{value:i,label:t.jsxs("span",{children:[t.jsx("code",{children:i}),t.jsx("br",{}),t.jsx(M,{children:q[i].description})]})},i))}),t.jsxs("div",{style:{marginTop:16,display:"flex",flexDirection:"column",gap:8},children:[r?e.state==="checking"?t.jsx(Bt,{size:"tiny",label:`Checking ${s} availability for ${r}…`}):e.state==="supported"?t.jsx($,{intent:"success",children:t.jsxs(R,{children:[t.jsx("code",{children:r})," supports ",s,"."]})}):e.state==="unsupported"?t.jsx($,{intent:"error",layout:"multiline",children:t.jsxs(R,{children:[t.jsx(Me,{children:"Not available"}),e.message]})}):e.state==="unknown"?t.jsx($,{intent:"warning",layout:"multiline",children:t.jsx(R,{children:e.message})}):null:t.jsx($,{intent:"info",children:t.jsxs(R,{children:["Pick a table to check whether it supports ",s,"."]})}),t.jsx($,{intent:"info",layout:"multiline",children:t.jsxs(R,{children:["Availability comes from the table's ",t.jsx("code",{children:"sdkmessagefilters"}),"."," ",t.jsx("code",{children:"UpsertMultiple"})," has no filter of its own — it's available where both"," ",t.jsx("code",{children:"CreateMultiple"})," and ",t.jsx("code",{children:"UpdateMultiple"})," are. Send 100–1,000 rows per request on standard tables (",Jt," on elastic tables); there's no fixed cap, but large payloads hit size and time limits."," ",t.jsx("a",{href:"https://learn.microsoft.com/en-us/power-apps/developer/data-platform/bulk-operations",target:"_blank",rel:"noreferrer",children:"Use bulk operation messages"})]})})]})]})}function js(s,a){const e=a?.primaryKey??"primary key";switch(s){case"CreateMultiple":return`optional ${e} GUID`;case"UpsertMultiple":return`${e} GUID or key='value'`;default:return`${e} GUID`}}function ks({state:s,tbl:a,issueByRow:e,issueCount:r,rowLabel:i,onAdd:l,onImport:u,onClear:c,onEdit:o,onDuplicate:h,onRemove:p,onKeyChange:g}){const[j,S]=y.useState(0),b=Math.max(1,Math.ceil(s.rows.length/A)),x=Math.min(j,b-1),W=s.rows.slice(x*A,(x+1)*A),H=q[s.operation],w={padding:"4px 8px",borderBottom:`1px solid ${E.colorNeutralStroke2}`};return t.jsxs("div",{children:[t.jsxs(ae,{icon:Se,title:"Rows",sub:`Each row becomes one item in Targets. ${H.keyRequired?"Every row needs a key.":"A key is optional."}`,group:D,children:[t.jsx(k,{icon:t.jsx(Mt,{}),onClick:l,disabled:!a,children:"Add row"}),t.jsx(k,{icon:t.jsx(It,{}),onClick:u,disabled:!a,children:"Import CSV / JSON…"}),t.jsx(k,{icon:t.jsx(te,{}),appearance:"subtle",onClick:c,disabled:s.rows.length===0,children:"Clear"})]}),!a&&t.jsx($,{intent:"info",children:t.jsx(R,{children:"Pick a target table first."})}),s.rows.length>Ht&&t.jsx($,{intent:"warning",layout:"multiline",style:{marginBottom:8},children:t.jsxs(R,{children:[t.jsxs(Me,{children:[s.rows.length.toLocaleString()," rows"]}),"Microsoft recommends 100–1,000 rows per request. Larger requests are more likely to hit message-size or time limits, and on standard tables a failure rolls back every row. Consider splitting the rows into several requests."]})}),r>0&&t.jsx($,{intent:"error",style:{marginBottom:8},children:t.jsxs(R,{children:[r," row issue",r===1?"":"s"," — fix them before sending."]})}),a&&s.rows.length===0&&t.jsx(M,{children:"No rows yet. Add rows one by one, or import them from CSV (header row of column names — Excel copy-paste works) or a JSON array of objects."}),s.rows.length>0&&t.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:13},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{textAlign:"left"},children:[t.jsx("th",{style:w,children:"#"}),t.jsx("th",{style:w,children:"Key"}),t.jsx("th",{style:w,children:"Columns"}),t.jsx("th",{style:w,children:"Status"}),t.jsx("th",{style:w,"aria-label":"Actions"})]})}),t.jsx("tbody",{children:W.map((v,J)=>{const F=x*A+J,I=[...Object.keys(v.fieldValues),...v.nullFields],U=e.get(v.id);return t.jsxs("tr",{children:[t.jsx("td",{style:w,children:F+1}),t.jsx("td",{style:{...w,minWidth:220},children:t.jsx(Re,{size:"small",value:v.key,placeholder:js(s.operation,a),onChange:(Z,V)=>g(v.id,V.value),"aria-label":`Row ${F+1} key`,style:{width:"100%"}})}),t.jsx("td",{style:w,children:t.jsx(M,{title:I.join(", "),children:I.length===0?"—":`${I.length}: ${I.slice(0,3).join(", ")}${I.length>3?"…":""}`})}),t.jsx("td",{style:w,children:U?t.jsx(M,{style:{color:E.colorPaletteRedForeground1},children:U}):t.jsx(M,{style:{color:E.colorPaletteGreenForeground1},children:"Ready"})}),t.jsxs("td",{style:{...w,whiteSpace:"nowrap"},children:[t.jsx(ee,{content:`Edit ${i(v,F)}`,relationship:"label",children:t.jsx(k,{size:"small",appearance:"subtle",icon:t.jsx(Dt,{}),onClick:()=>o(v.id)})}),t.jsx(ee,{content:"Duplicate row",relationship:"label",children:t.jsx(k,{size:"small",appearance:"subtle",icon:t.jsx(re,{}),onClick:()=>h(v.id)})}),t.jsx(ee,{content:"Remove row",relationship:"label",children:t.jsx(k,{size:"small",appearance:"subtle",icon:t.jsx(te,{}),onClick:()=>p(v.id)})})]})]},v.id)})})]}),b>1&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:8},children:[t.jsx(k,{size:"small",icon:t.jsx(Ce,{}),disabled:x===0,onClick:()=>S(x-1),"aria-label":"Previous page"}),t.jsxs(M,{children:["Rows ",x*A+1,"–",Math.min((x+1)*A,s.rows.length)," of"," ",s.rows.length]}),t.jsx(k,{size:"small",icon:t.jsx($e,{}),disabled:x>=b-1,onClick:()=>S(x+1),"aria-label":"Next page"})]})]})}function vs({row:s,index:a,count:e,table:r,tbl:i,operation:l,issue:u,themeMode:c,onPatch:o,onNavigate:h,onBack:p,onDuplicate:g,onRemove:j}){const S=q[l];return t.jsxs("div",{children:[t.jsxs(ae,{icon:ke,title:`Row ${a+1} of ${e}`,sub:l==="DeleteMultiple"?"Only the key (and partitionid on partitioned elastic tables) is needed.":void 0,group:D,children:[t.jsx(k,{icon:t.jsx(Ct,{}),appearance:"subtle",onClick:p,children:"All rows"}),t.jsx(k,{icon:t.jsx(Ce,{}),disabled:a===0,onClick:()=>h(a-1),"aria-label":"Previous row"}),t.jsx(k,{icon:t.jsx($e,{}),disabled:a>=e-1,onClick:()=>h(a+1),"aria-label":"Next row"}),t.jsx(k,{icon:t.jsx(re,{}),onClick:g,children:"Duplicate"}),t.jsx(k,{icon:t.jsx(te,{}),appearance:"subtle",onClick:j,children:"Remove"})]}),t.jsx($t,{label:S.keyRequired?"Key (required)":"Key (optional)",hint:l==="UpsertMultiple"?`A ${i?.primaryKey??"primary key"} GUID, or an alternate key segment such as name='Contoso' — sent as @odata.id.`:l==="CreateMultiple"?`Leave empty to let Dataverse assign the id, or set a ${i?.primaryKey??"primary key"} GUID.`:`The ${i?.primaryKey??"primary key"} GUID of the row.`,validationState:u?"error":"none",validationMessage:u,style:{maxWidth:520,marginBottom:12},children:t.jsx(Re,{value:s.key,onChange:(b,x)=>o({key:x.value})})}),S.usesFields&&t.jsx(Rt,{table:r,values:s.fieldValues,setValues:b=>o({fieldValues:b}),nullFields:s.nullFields,setNullFields:b=>o({nullFields:b}),group:D,themeMode:c,purpose:S.fieldPurpose})]})}function Ss({open:s,tbl:a,onClose:e,onImport:r}){const[i,l]=y.useState(""),[u,c]=y.useState(!1),o=y.useMemo(()=>a?ds(i,a):{rows:[],skippedColumns:[],errors:[]},[i,a]),h=async p=>{p&&l(await p.text())};return t.jsx(Tt,{open:s,onOpenChange:(p,g)=>!g.open&&e(),children:t.jsx(Ot,{style:{maxWidth:760},children:t.jsxs(Et,{children:[t.jsxs(Pt,{children:["Import rows",a?` into ${a.displayName}`:""]}),t.jsxs(qt,{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs(M,{children:["Paste CSV / tab-separated text with a header row of column logical (or display) names, or a JSON array of objects. A ",t.jsx("code",{children:a?.primaryKey??"primary key"}),","," ",t.jsx("code",{children:"id"})," or ",t.jsx("code",{children:"@key"})," column fills the row key. Lookups take a GUID (first target) or ",t.jsx("code",{children:"table:guid"}),"; choices take the value or the label."]}),t.jsx(Vt,{value:i,onChange:(p,g)=>l(g.value),rows:12,"aria-label":"Rows to import",placeholder:`name,numberofemployees
4
+ Contoso,10
5
+ Fabrikam,25`,textarea:{style:{fontFamily:E.fontFamilyMonospace,fontSize:12}}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsx("input",{type:"file",accept:".csv,.tsv,.txt,.json","aria-label":"Load rows from a file",onChange:p=>{h(p.target.files?.[0])}}),t.jsx(_t,{checked:u,onChange:(p,g)=>c(!!g.checked),label:"Replace existing rows"})]}),i.trim()&&t.jsx($,{intent:o.errors.length?"warning":o.rows.length?"success":"info",layout:"multiline",children:t.jsxs(R,{children:[o.rows.length," row",o.rows.length===1?"":"s"," parsed.",o.skippedColumns.length>0&&t.jsxs(t.Fragment,{children:[" Skipped columns (not on this table): ",o.skippedColumns.join(", "),"."]}),o.errors.length>0&&t.jsxs("ul",{style:{margin:"4px 0 0",paddingLeft:18},children:[o.errors.slice(0,6).map(p=>t.jsx("li",{children:p},p)),o.errors.length>6&&t.jsxs("li",{children:["…and ",o.errors.length-6," more"]})]})]})})]}),t.jsxs(Kt,{children:[t.jsx(k,{appearance:"secondary",onClick:e,children:"Cancel"}),t.jsxs(k,{appearance:"primary",disabled:o.rows.length===0,onClick:()=>{r(o.rows,u),l("")},children:["Import ",o.rows.length||""," row",o.rows.length===1?"":"s"]})]})]})})})}function Cs({result:s,operation:a}){const e=se(s.body),[r,i]=y.useState(!1);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,maxWidth:760},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx(At,{status:"success",code:s.status,ms:s.ms}),t.jsxs(Ut,{weight:"semibold",children:[a," ",e.length>0?`created ${e.length} row${e.length===1?"":"s"}`:"completed"]})]}),e.length>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{children:t.jsx(k,{icon:t.jsx(re,{}),onClick:()=>{Lt(e.join(`
6
+ `)).then(()=>i(!0))},children:r?"Copied":"Copy ids"})}),t.jsx("ol",{style:{margin:0,paddingLeft:32,fontFamily:E.fontFamilyMonospace,fontSize:12,maxHeight:480,overflow:"auto"},children:e.map(l=>t.jsx("li",{children:l},l))})]}):t.jsxs(M,{children:[a," returns 204 No Content — Dataverse doesn't report per-row results for it. Every row in the request succeeded (a failure would have rolled back the request on a standard table)."]})]})}export{Rs as BulkWriteMode};
@@ -0,0 +1,2 @@
1
+ import{c as ke,b5 as Ie,bV as ae,r as n,u as Pe,e as Ne,bW as Ce,bX as we,f as L,bY as Ee,bO as Y,bZ as Re,b9 as De,i as O,j as Fe,T as Me,k as Ae,bQ as $e,bR as Be,bF as z,bG as He,L as Le,p as ze,q as e,H as qe,v as Ue,bT as Ve,x as We,y as Oe,z as _e,D as Ge,R as Xe,bU as se,U as Ye,S as Ke,G as Qe,bl as Ze,a8 as _,A as G,B as X,I as re,as as Je,X as d,Y as C,a2 as et,b_ as tt,b4 as at,a_ as st,aS as rt,bm as nt,bk as ot}from"./index-C4fO68cu.js";import{N as lt,A as it}from"./AssociateTargetsEditor-C-QKaWaJ.js";const dt=()=>({table:"",sourceId:null,navProperty:null,targetIds:[],targetNames:{},headers:Qe(),dirty:new Set});function mt({themeMode:l}){const y=ke("disassociate"),g=Ie("disassociate",ae,dt),[t,o]=n.useState(g.state),{table:f}=Pe(t.table||null),{entities:j}=Ne(),[w,c]=n.useState("source"),[b,E]=n.useState("builder"),[R,q]=n.useState(null),[le,K]=n.useState(!1),[ie,de]=n.useState([]),[D,F]=n.useState(g.lastSavedId),[M,A]=n.useState(g.lastSavedHash),[Q,U]=n.useState(""),[m,v]=n.useState(null),[Z,S]=n.useState(!1),[V,$]=n.useState(null),T=n.useMemo(()=>Ce(t),[t,f]),k=n.useMemo(()=>we(t),[t,f]),p=L(t.table),r=t.navProperty?p?.navigationProperties.find(a=>a.name===t.navProperty):void 0,ce=r?Ee(r):!1,h=r?Y(r):!1,I=h?"PATCH":"DELETE";n.useEffect(()=>{let a=!1;if($(null),!h||!t.sourceId||!p||!r){v(null),S(!1);return}if(typeof window>"u"||!window.dataverseAPI?.queryData){v(null),S(!1),$("The PPTB host is not available, so the current value cannot be read.");return}v(null),S(!0);const s=`_${r.referencingAttribute||r.name}_value`,u=`/${p.entitySetName}(${t.sourceId})?$select=${s}`;return window.dataverseAPI.queryData(u).then(i=>{if(a)return;const N=i?.value,H=Array.isArray(N)?N[0]??null:N&&typeof N=="object"?N:i&&typeof i=="object"&&(s in i||p.primaryKey in i)?i:null;if(!H)$("Dataverse returned no row for the source record.");else{const te=String(H[s]??""),Se=String(H[`${s}@OData.Community.Display.V1.FormattedValue`]??""),Te=String(H[`${s}@Microsoft.Dynamics.CRM.lookuplogicalname`]??"");v(te?{id:te,name:Se||null,entity:Te||null}:null)}S(!1)}).catch(i=>{a||(v(null),S(!1),$(i instanceof Error?i.message:String(i)))}),()=>{a=!0}},[h,t.sourceId,t.navProperty,p,r]);const W=a=>o(s=>{const u=new Set(s.dirty);return u.add(a),{...s,dirty:u}}),B=(a,s,u)=>{o(i=>({...i,[a]:s})),u&&W(u)},ue=p?t.sourceId?t.navProperty?ce&&t.targetIds.length===0?"Pick at least one target record to disassociate.":h&&m===null&&!Z&&!V?"Source's lookup is already empty — nothing to disassociate.":t.headers.some(a=>a.enabled&&!a.name)?"Fix empty header name.":null:"Pick a navigation property.":"Pick a source record.":"Pick a source table first.",ge=async()=>{K(!0);const a=await rt.disassociate(t);q(a),K(!1),E("results"),de(s=>[{id:`r-${Date.now()}`,snapshot:x,modeId:"disassociate",url:T.relativeUrl,method:I,ts:Date.now(),status:a.status,ms:a.ms,rowCount:se(a,k.length)??0},...s].slice(0,8)),o(s=>({...s,dirty:new Set}))},x=n.useMemo(()=>Re(t),[t]);De("disassociate",x,D,M);const he=n.useMemo(()=>O(x),[x]),J=M===null?!0:he!==M,ye=a=>{F(a.id),A(O(a.state))},ee=a=>{if(a.modeId!=="disassociate")return;const s=a.state;if(j.length>0&&!j.some(u=>u.logicalName===s.table)){Ze(`Can't load "${a.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}o(ae(s)),F(a.id),A(O(s)),q(null),U(""),c("source")},me=a=>{const s=nt(a,"disassociate");if(!s)return;const u=D,i=M;ee(s),F(u),A(i)};Fe(n.useMemo(()=>t.table?{state:x,modeId:"disassociate",dirty:J,lastSavedId:D,onSaved:ye,onLoadSaved:ee}:null,[x,J,D,t.table]));const pe=[{id:"source",label:"Target",meta:p?.displayName??"Pick a table",items:[{id:"source",icon:Ae,iconFilled:Me,label:t.sourceId?Q||`${p?.displayName??""} (selected)`:"Pick a record",badge:r?I:null,badgeAppearance:"tint",badgeColor:"brand",dirty:t.dirty.has("source")}]},{id:"relationship",label:"Relationship",meta:r?oe(r.cardinality):"pick one",items:[{id:"nav",icon:Be,iconFilled:$e,label:r?r.name:"Navigation property",code:!!r,badge:r?oe(r.cardinality):null,badgeAppearance:"ghost",dirty:t.dirty.has("nav")}]},{id:"target",label:"Related",meta:h?m?`clear: ${m.name??m.id.slice(0,8)}…`:V?"value unknown":"lookup empty":t.targetIds.length?`${t.targetIds.length} target${t.targetIds.length===1?"":"s"}`:"none",items:[{id:"target",icon:He,iconFilled:z,label:h?"Target — implicit":t.targetIds.length>1?"Target records":"Target record",badge:h?"∅":t.targetIds.length||null,badgeAppearance:"tint",badgeColor:t.targetIds.length>0?"success":"subtle",dirty:t.dirty.has("target")}]},{id:"headers",label:"Headers",meta:`${t.headers.filter(a=>a.enabled).length} active`,items:[{id:"headers",icon:ze,iconFilled:Le,label:"HTTP headers",badge:t.headers.filter(a=>a.enabled).length||null,dirty:t.dirty.has("headers")}]}];let P;switch(w){case"source":P=e.jsx(Ue,{table:t.table,onTableChange:a=>{o(s=>({...s,table:a,sourceId:null,navProperty:null,targetIds:[],targetNames:{},dirty:new Set(["source","nav","target"])})),U(""),v(null),q(null),F(void 0),A(null)},recordId:t.sourceId,onRecordChange:(a,s)=>{B("sourceId",a,"source"),U(s??"")},group:"relate",sub:"Pick the source record holding the relationship link to remove."});break;case"nav":P=e.jsx("div",{children:e.jsx(lt,{table:t.table,value:t.navProperty,onChange:a=>{o(s=>({...s,navProperty:a,targetIds:[],targetNames:{}})),W("nav"),W("target")},group:"relate",forOperation:"disassociate",footer:r&&e.jsx(ut,{nav:r})})});break;case"target":P=e.jsx(ct,{state:t,setTargetIds:a=>B("targetIds",a,"target"),targetNames:t.targetNames,setTargetNames:a=>B("targetNames",a),currentLookup:m,currentLookupLoading:Z,currentLookupError:V});break;case"headers":P=e.jsx(qe,{items:t.headers,setItems:a=>B("headers",a,"headers"),group:"relate"});break}const be=Ve(I,We(t.headers,null)),ve=k[0],xe={method:I,built:T,headers:be,body:ve?.body,entityLogical:T.entityLogical,multiRequests:k.length>1?k.map(a=>({method:a.method,relativeUrl:a.relativeUrl,body:a.body,description:a.targetId?`target ${a.targetId}`:"clear lookup (null)"})):void 0},fe=h?m?.name?[m.name]:[]:t.targetIds.map(a=>t.targetNames[a]).filter(a=>!!a),je=h?m?1:0:t.targetIds.length;return e.jsx(Oe,{sidebar:e.jsx(Ke,{type:y,urlPreview:T.relativeNoBase,sections:pe,activeNode:w,onSelect:a=>{c(a),E("builder")},recents:ie,onRecentClick:me}),urlBar:e.jsx(Ye,{method:I,url:T.relativeUrl,executeVerb:y.executeVerb,disabledReason:ue,loading:le,onExecute:ge}),children:e.jsxs(_e,{tab:b,onTabChange:E,resultCount:se(R,k.length),children:[b==="builder"&&P,b==="code"&&e.jsx(Ge,{themeMode:l,inputs:xe}),b==="results"&&e.jsx(Xe,{result:R,mode:"single",table:t.table,writeContext:{operation:"disassociate",table:t.table,recordId:t.sourceId,recordName:Q||null,navProperty:t.navProperty??void 0,targetCount:je,targetNames:fe,targetNameById:t.targetNames}})]})})}function ct({state:l,setTargetIds:y,targetNames:g,setTargetNames:t,currentLookup:o,currentLookupLoading:f,currentLookupError:j}){const w=L(l.table),c=l.navProperty?w?.navigationProperties.find(R=>R.name===l.navProperty):void 0;if(!c)return e.jsxs("div",{children:[e.jsx(_,{icon:z,title:"Target record",sub:"Pick a navigation property first.",group:"relate"}),e.jsx(G,{layout:"multiline",intent:"info",style:{maxWidth:720},children:e.jsxs(X,{children:["Switch to the ",e.jsx("strong",{children:"Relationship"})," pane and pick a navigation property."]})})]});const b=L(c.targetEntity);return Y(c)?e.jsxs("div",{children:[e.jsx(_,{icon:z,title:"Target — implicit (single-valued)",sub:e.jsxs(e.Fragment,{children:["Single-valued nav props don't take a target id. The ",e.jsx("code",{children:"PATCH"})," body"," ",e.jsx("code",{children:`{ "${c.name}@odata.bind": null }`})," clears the lookup on the source row."]}),group:"relate"}),e.jsx(G,{layout:"multiline",intent:"warning",icon:e.jsx(Je,{}),style:{maxWidth:880,marginBottom:14},children:e.jsxs(X,{children:[e.jsx(re,{children:"This clears the lookup."}),e.jsx("code",{children:c.name})," on the source row becomes ",e.jsx("code",{children:"null"}),". The related row is"," ",e.jsx("strong",{children:"not"})," deleted — only the link is removed."]})}),e.jsxs("div",{style:{border:`1px solid ${d.colorNeutralStroke2}`,borderRadius:d.borderRadiusMedium,padding:12,maxWidth:560},children:[e.jsxs(C,{style:{color:d.colorNeutralForeground3,display:"block",marginBottom:8},children:["Current lookup value",f?" (loading…)":""]}),f?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx(et,{size:"tiny"}),e.jsx(C,{children:"Fetching the lookup's current value from Dataverse…"})]}):o?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx(tt,{size:28,name:o.name??void 0,color:"colorful"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600},children:o.name??"(name not available)"}),e.jsxs("div",{style:{fontFamily:d.fontFamilyMonospace,fontSize:10,color:d.colorNeutralForeground3},children:["/",(o.entity&&L(o.entity)?.entitySetName)??b?.entitySetName??c.targetEntity,"(",o.id,")"]})]})]}),o.entity&&o.entity!==c.targetEntity&&e.jsxs(C,{style:{display:"block",marginTop:8,color:d.colorNeutralForeground3},children:["The lookup currently references a ",e.jsx("code",{children:o.entity})," row, not"," ",e.jsx("code",{children:c.targetEntity}),"."]})]}):j?e.jsx(G,{layout:"multiline",intent:"warning",children:e.jsxs(X,{children:[e.jsx(re,{children:"Couldn't read the current value."}),"Execute still sends the ",e.jsx("code",{children:"PATCH"}),"; if the lookup is already empty it changes nothing. ",e.jsx("code",{children:j})]})}):e.jsx(C,{style:{color:d.colorNeutralForeground3,fontStyle:"italic"},children:"Source's lookup is already empty — the PATCH would be a no-op."})]})]}):e.jsxs("div",{children:[e.jsx(_,{icon:z,title:l.targetIds.length>1?"Target records":"Target record",sub:e.jsxs(e.Fragment,{children:["Pick one or more ",e.jsx("code",{children:b?.logicalName})," rows to remove from the collection. Each fires a separate DELETE request per docs — the target rows are"," ",e.jsx("strong",{children:"not"})," deleted, only the links."]}),group:"relate"}),e.jsx(it,{table:l.table,navProperty:l.navProperty,targets:l.targetIds,setTargets:y,targetNames:g,setTargetNames:t,group:"relate",resolvedMethod:null})]})}function ut({nav:l}){const y=at(),g=Y(l);return e.jsxs("div",{className:st(y.inlineCard),style:{padding:12},children:[e.jsx("strong",{style:{fontSize:12,display:"block",marginBottom:8},children:"URL shape per cardinality"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:10},children:[e.jsx(ne,{label:"Collection-valued (1:N / N:N)",syntax:"DELETE /<set>(<id>)/<nav>(<related-id>)/$ref",note:"One DELETE per target id.",active:!g}),e.jsx(ne,{label:"Single-valued (N:1)",syntax:`PATCH /<set>(<id>)
2
+ { "<nav>@odata.bind": null }`,note:"Clears the lookup — docs-preferred over DELETE/$ref (and the only path PPTB exposes).",active:g})]})]})}function ne({label:l,syntax:y,note:g,active:t}){return e.jsxs("div",{style:{padding:10,border:`1px solid ${t?d.colorBrandStroke1:d.colorNeutralStroke2}`,background:t?d.colorBrandBackground2:"transparent",borderRadius:d.borderRadiusMedium,opacity:t?1:.55},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[e.jsx("strong",{style:{fontSize:11},children:l}),t&&e.jsx(ot,{appearance:"tint",color:"brand",size:"extra-small",style:{marginLeft:"auto",fontWeight:700},children:"ACTIVE"})]}),e.jsx("code",{style:{fontFamily:d.fontFamilyMonospace,fontSize:11,wordBreak:"break-all",display:"block",whiteSpace:"pre-wrap"},children:y}),e.jsx(C,{style:{display:"block",marginTop:4,color:d.colorNeutralForeground3},children:g})]})}function oe(l){switch(l){case"OneToMany":return"1:N";case"ManyToOne":return"N:1";case"ManyToMany":return"N:N"}}export{mt as DisassociateMode};
@@ -0,0 +1 @@
1
+ import{b4 as Y,q as e,a_ as ye,X as p,r as l,Y as j,a2 as J,A as q,B as L,I as Q,bk as k,c as he,b5 as pe,c0 as G,c1 as ge,c2 as we,u as xe,f as ke,e as be,c3 as je,b9 as Se,i as H,j as ve,c4 as M,c5 as Ee,T as K,k as Ie,L as Te,p as Ne,H as Pe,a8 as Z,a4 as ee,b3 as Ce,x as qe,y as Le,z as Me,D as Ae,R as Re,U as We,S as $e,G as Be,bl as Fe,bi as De,b2 as X,aS as He,bm as Oe}from"./index-C4fO68cu.js";function ze({rows:i,keyWidth:s,className:d}){const t=Y(),a=s!=null?{gridTemplateColumns:`${typeof s=="number"?`${s}px`:s} 1fr`}:void 0;return e.jsx("div",{className:ye(t.kvGrid,d),style:a,children:i.map((n,m)=>e.jsx(Ve,{k:n.k,v:n.v,mono:n.mono},m))})}function Ve({k:i,v:s,mono:d}){const t=Y();return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:t.kvKey,children:i}),e.jsx("span",{className:d?t.kvValMono:t.kvVal,children:s==null||s===""?e.jsx("em",{style:{color:p.colorNeutralForeground4},children:"—"}):s})]})}const Ue="http://schemas.microsoft.com/winfx/2006/xaml",_e=new Set(["InputEntities","CreatedEntities"]);function Ge(i){if(!i||typeof DOMParser>"u")return[];let s;try{s=new DOMParser().parseFromString(i,"application/xml")}catch{return[]}if(s.getElementsByTagName("parsererror").length>0)return[];const d=[],t=s.getElementsByTagNameNS(Ue,"Property");for(const a of Array.from(t)){const n=a.getAttribute("Name"),m=/^(In|InOut)Argument\((.*)\)$/.exec((a.getAttribute("Type")??"").trim());if(!n||!m||_e.has(n))continue;let h=!1,g=null;for(const o of Array.from(a.getElementsByTagName("*"))){const y=o.getAttribute("Value");o.localName==="ArgumentRequiredAttribute"&&(h=y?.toLowerCase()==="true"),o.localName==="ArgumentDescriptionAttribute"&&y&&(g=y)}d.push({name:n,direction:m[1],type:m[2].trim(),required:h,description:g})}return d}function Ke(i){return i.replace(/\b[a-z]+:/g,"")}function Xe({workflowId:i}){const[s,d]=l.useState({status:"loading"});l.useEffect(()=>{if(typeof window>"u"||!window.dataverseAPI?.queryData){d({status:"ready",args:[]});return}let a=!1;return d({status:"loading"}),window.dataverseAPI.queryData(`workflows?$select=xaml&$filter=workflowid eq ${i}`).then(n=>{if(a)return;const m=n?.value?.[0],h=typeof m?.xaml=="string"?m.xaml:null;d({status:"ready",args:Ge(h)})}).catch(n=>{a||d({status:"error",message:n instanceof Error?n.message:String(n)})}),()=>{a=!0}},[i]);const t={color:p.colorNeutralForeground3,display:"block",marginTop:10};return s.status==="loading"?e.jsxs(j,{style:{...t,display:"flex",alignItems:"center",gap:6},children:[e.jsx(J,{size:"extra-tiny"})," Reading the workflow's input arguments…"]}):s.status==="error"?e.jsxs(j,{style:t,children:["Couldn't read the workflow definition to check for input arguments: ",s.message]}):s.args.length===0?e.jsxs(j,{style:t,children:["No input arguments declared — ",e.jsx("code",{children:"EntityId"})," is the whole request body."]}):e.jsx(q,{layout:"multiline",intent:"warning",style:{marginTop:12},children:e.jsxs(L,{children:[e.jsxs(Q,{children:["This workflow declares ",s.args.length," input argument",s.args.length===1?"":"s"]}),"The Web API ",e.jsx("code",{children:"ExecuteWorkflow"})," action only takes ",e.jsx("code",{children:"EntityId"}),", so these can't be set from here; the workflow runs with their default values.",e.jsx("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:s.args.map(a=>e.jsxs("li",{children:[e.jsx("code",{children:a.name})," ",e.jsx(k,{appearance:"outline",size:"small",children:Ke(a.type)}),a.direction==="InOut"&&e.jsx(k,{appearance:"tint",size:"small",style:{marginLeft:4},children:"in/out"}),a.required&&e.jsx(k,{appearance:"tint",color:"danger",size:"small",style:{marginLeft:4},children:"required"}),a.description&&e.jsxs("span",{style:{color:p.colorNeutralForeground3},children:[" — ",a.description]})]},a.name))})]})})}const Ye=()=>({workflowId:null,entityId:null,headers:Be(),dirty:new Set});function et({themeMode:i}){const s=he("exec-workflow"),d=pe("exec-workflow",G,Ye),[t,a]=l.useState(d.state),[n,m]=l.useState("pick"),[h,g]=l.useState("builder"),[o,y]=l.useState(null),[S,I]=l.useState(!1),[A,te]=l.useState([]),v=l.useMemo(()=>ge(t),[t]),re=l.useMemo(()=>we(t),[t]),[T,O]=l.useState([]),[se,R]=l.useState(!1),[ne,W]=l.useState(null);l.useEffect(()=>{let r=!1;if(typeof window>"u"||!window.dataverseAPI?.queryData){O([]),W("Workflows can only be loaded from a live Dataverse connection (PPTB).");return}return R(!0),W(null),window.dataverseAPI.queryData("workflows?$select=workflowid,name,uniquename,primaryentity,description&$filter=(statecode eq 1 and type eq 1 and ondemand eq true and category eq 0)&$orderby=name asc").then(f=>{if(r)return;const w=f?.value??[];O(w.map(x=>({id:String(x.workflowid??""),name:String(x.name??"(unnamed)"),uniqueName:x.uniquename!=null?String(x.uniquename):null,primaryEntity:String(x.primaryentity??""),description:x.description!=null?String(x.description):null}))),R(!1)}).catch(f=>{r||(W(f instanceof Error?f.message:String(f)),R(!1))}),()=>{r=!0}},[]);const c=t.workflowId?T.find(r=>r.id===t.workflowId):void 0;xe(c?.primaryEntity??null);const E=c?ke(c.primaryEntity):void 0,{entities:z}=be(),[N,$]=l.useState(d.lastSavedId),[P,B]=l.useState(d.lastSavedHash),[ae,F]=l.useState(""),D=r=>a(u=>{const f=new Set(u.dirty);return f.add(r),{...u,dirty:f}}),V=(r,u,f)=>{a(w=>({...w,[r]:u})),f&&D(f)},oe=c?t.entityId?t.headers.some(r=>r.enabled&&!r.name)?"Fix empty header name.":null:`Pick a ${c.primaryEntity} record to run the workflow on.`:"Pick a workflow.",ie=async()=>{I(!0);const r=await He.workflow(t);y(r),I(!1),g("results"),te(u=>[{id:`r-${Date.now()}`,snapshot:b,modeId:"exec-workflow",url:v.relativeUrl,method:"POST",ts:Date.now(),status:r.status,ms:r.ms,rowCount:r.ok?1:0},...u].slice(0,8)),a(u=>({...u,dirty:new Set}))},b=l.useMemo(()=>je(t),[t]);Se("exec-workflow",b,N,P);const le=l.useMemo(()=>H(b),[b]),U=P===null?!0:le!==P,de=r=>{$(r.id),B(H(r.state))},_=r=>{if(r.modeId!=="exec-workflow")return;const u=r.state,f=T.find(w=>w.id===u.workflowId);if(f&&z.length>0&&!z.some(w=>w.logicalName===f.primaryEntity)){Fe(`Can't load "${r.name}": workflow's primary entity \`${f.primaryEntity}\` isn't available in this environment.`);return}a(G(u)),$(r.id),B(H(u)),y(null),F(""),m("pick")},ce=r=>{const u=Oe(r,"exec-workflow");if(!u)return;const f=N,w=P;_(u),$(f),B(w)};ve(l.useMemo(()=>t.workflowId?{state:b,modeId:"exec-workflow",dirty:U,lastSavedId:N,onSaved:de,onLoadSaved:_}:null,[b,U,N,t.workflowId,T]));const ue=[{id:"workflow",label:"Target",meta:c?.name??"pick one",items:[{id:"pick",icon:Ee,iconFilled:M,label:c?.name??"Pick on-demand workflow",dirty:t.dirty.has("pick")}]},{id:"target",label:"Bound to",meta:c?`${E?.displayName??c.primaryEntity} record`:"—",items:[{id:"target",icon:Ie,iconFilled:K,label:t.entityId?`${E?.displayName??""} (selected)`:"Pick a record",badge:t.entityId?"✓":null,badgeAppearance:"ghost",dirty:t.dirty.has("target")}]},{id:"headers",label:"Headers",meta:`${t.headers.filter(r=>r.enabled).length} active`,items:[{id:"headers",icon:Ne,iconFilled:Te,label:"HTTP headers",badge:t.headers.filter(r=>r.enabled).length||null,dirty:t.dirty.has("headers")}]}];let C;switch(n){case"pick":C=e.jsx(Je,{workflows:T,loading:se,error:ne,workflowId:t.workflowId,setWorkflowId:r=>{a(u=>({...u,workflowId:r,entityId:null})),F(""),D("pick"),D("target")}});break;case"target":C=c?e.jsxs("div",{children:[e.jsx(Z,{icon:K,title:"Target record",sub:`The ${E?.displayName??c.primaryEntity} record the workflow operates on. Slots into the request body as "EntityId".`,group:"execute"}),e.jsxs("div",{style:{maxWidth:480},children:[e.jsx(ee,{label:`${E?.displayName??c.primaryEntity} record`,children:e.jsx(Ce,{table:c.primaryEntity,selectedId:t.entityId,onPick:r=>{V("entityId",r?.id??null,"target"),F(r?.primary??"")},placeholder:`Search ${E?.displayName??c.primaryEntity} records…`})}),e.jsx(Xe,{workflowId:c.id})]})]}):e.jsx(q,{layout:"multiline",intent:"info",children:e.jsx(L,{children:"Pick a workflow first."})});break;case"headers":C=e.jsx(Pe,{items:t.headers,setItems:r=>V("headers",r,"headers"),group:"execute"});break}const me=qe(t.headers,null),fe={method:"POST",built:v,headers:me,body:re,entityLogical:v.entityLogical};return e.jsx(Le,{sidebar:e.jsx($e,{type:s,urlPreview:v.relativeNoBase,sections:ue,activeNode:n,onSelect:r=>{m(r),g("builder")},recents:A,onRecentClick:ce}),urlBar:e.jsx(We,{method:"POST",url:v.relativeUrl,executeVerb:s.executeVerb,executeIcon:M,disabledReason:oe,loading:S,onExecute:ie}),children:e.jsxs(Me,{tab:h,onTabChange:g,resultCount:o?.ok?1:null,children:[h==="builder"&&C,h==="code"&&e.jsx(Ae,{themeMode:i,inputs:fe}),h==="results"&&e.jsx(Re,{result:o,mode:"single",table:c?.primaryEntity??"",writeContext:{operation:"workflow",table:c?.primaryEntity??"",recordId:t.entityId,recordName:ae||null,operationName:c?.name??void 0}})]})})}function Je({workflows:i,loading:s,error:d,workflowId:t,setWorkflowId:a}){const n=t?i.find(o=>o.id===t):void 0,[m,h]=l.useState("");l.useEffect(()=>{h(n?.name??"")},[n?.name]);const g=l.useMemo(()=>{const o=m.trim().toLowerCase();return!o||o===(n?.name??"").toLowerCase()?i:i.filter(y=>y.name.toLowerCase().includes(o)||(y.uniqueName?.toLowerCase().includes(o)??!1)||y.primaryEntity.toLowerCase().includes(o)||(y.description?.toLowerCase().includes(o)??!1))},[i,m,n]);return e.jsxs("div",{children:[e.jsx(Z,{icon:M,title:"On-demand workflow",sub:"Pick an activated workflow (type=Definition, category=Workflow). The workflow's primary entity drives the Target picker.",group:"execute",children:s?e.jsx(k,{appearance:"ghost",icon:e.jsx(J,{size:"extra-tiny"}),children:"loading…"}):e.jsxs(k,{appearance:"ghost",children:[i.length," workflow",i.length===1?"":"s"]})}),d&&e.jsx(q,{intent:"error",layout:"multiline",style:{marginBottom:12,maxWidth:760},children:e.jsxs(L,{children:["Couldn't load workflows: ",d]})}),e.jsxs("div",{style:{maxWidth:760},children:[e.jsx(ee,{label:"Workflow",children:e.jsxs(De,{freeform:!0,clearable:!0,value:m,selectedOptions:t?[t]:[],onChange:o=>{const y=o.target.value;h(y),y===""&&t&&a(null)},onOptionSelect:(o,y)=>{const S=y.optionValue??null;if(a(S),S){const I=i.find(A=>A.id===S);h(I?.name??"")}else h("")},placeholder:s?"Loading workflows…":i.length===0?"No activated workflows in this environment":"Search workflows…",disabled:s||i.length===0,listbox:{style:{maxHeight:420}},children:[g.length===0&&m.trim()&&e.jsx(X,{value:"__none",text:"",disabled:!0,children:e.jsxs(j,{style:{color:p.colorNeutralForeground3},children:['No workflows match "',m.trim(),'"']})}),g.map(o=>e.jsx(X,{value:o.id,text:o.name,children:e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{children:o.name}),e.jsxs(j,{style:{color:p.colorNeutralForeground3},children:["Primary entity:"," ",e.jsx("span",{style:{fontFamily:p.fontFamilyMonospace},children:o.primaryEntity}),o.description?` · ${o.description}`:""]})]})},o.id))]})}),n&&e.jsxs("div",{style:{marginTop:16,padding:12,border:`1px solid ${p.colorNeutralStroke2}`,borderRadius:p.borderRadiusMedium,background:p.colorNeutralBackground1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(M,{style:{color:p.colorBrandForeground1}}),e.jsx("strong",{style:{fontSize:13},children:n.name}),e.jsx(k,{appearance:"ghost",children:n.primaryEntity}),e.jsx("span",{style:{flexGrow:1}}),e.jsx(k,{appearance:"filled",color:"success",style:{fontWeight:700},children:"POST"})]}),e.jsx(j,{style:{color:p.colorNeutralForeground2,display:"block",marginBottom:8},children:n.description}),e.jsx(ze,{keyWidth:120,rows:[{k:"Workflow id",v:n.id,mono:!0},{k:"Primary entity",v:n.primaryEntity,mono:!0},{k:"URL shape",v:`POST /workflows(${n.id})/Microsoft.Dynamics.CRM.ExecuteWorkflow`,mono:!0},{k:"Body shape",v:'{ "EntityId": "<target-guid>" }',mono:!0},{k:"Response",v:"204 No Content — workflow runs async"}]}),e.jsx(q,{layout:"multiline",intent:"info",style:{marginTop:12},children:e.jsxs(L,{children:[e.jsx(Q,{children:"Workflow runs are asynchronous."}),"The 204 only confirms the request was accepted. Check the ",e.jsx("code",{children:"workflowlogs"})," ","/ ",e.jsx("code",{children:"asyncoperations"})," tables for completion + result."]})})]})]})]})}export{et as ExecuteWorkflowMode};