@ppdostudio/ppdo-cli 1.0.0-beta.1 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +22 -3
  3. package/THIRD-PARTY-NOTICES +1 -0
  4. package/dist/bin.js +2 -2
  5. package/dist/chunks/{ado-XAHQWYNQ.js → ado-OTSVKTOE.js} +6 -6
  6. package/dist/chunks/{api-KN24TLH6.js → api-IRGGH5DJ.js} +1 -1
  7. package/dist/chunks/{api-7RAWLIQV.js → api-TZJXGWWQ.js} +1 -1
  8. package/dist/chunks/{auth-VZSJMSMF.js → auth-7CDWOYJE.js} +1 -1
  9. package/dist/chunks/{azCli-AEZK2RBQ.js → azCli-UEDQHRLP.js} +1 -1
  10. package/dist/chunks/batch-LKWCBKAB.js +2 -0
  11. package/dist/chunks/{build-LSQEAEFK.js → build-PBPXO3GJ.js} +1 -1
  12. package/dist/chunks/bulk-NY5XX752.js +2 -0
  13. package/dist/chunks/chunk-2IUXH534.js +2 -0
  14. package/dist/chunks/{chunk-STWQDANK.js → chunk-3L7657R3.js} +1 -1
  15. package/dist/chunks/{chunk-MGZDEW3X.js → chunk-46KBBWEH.js} +1 -1
  16. package/dist/chunks/{chunk-B4FPKDMH.js → chunk-6NBCHK6X.js} +1 -1
  17. package/dist/chunks/chunk-6VLFO5FJ.js +7 -0
  18. package/dist/chunks/{chunk-BCAXUZIO.js → chunk-B3TJ3RJN.js} +1 -1
  19. package/dist/chunks/chunk-BG2OIOSN.js +2 -0
  20. package/dist/chunks/{chunk-MZEUD7ET.js → chunk-BWOEIEFY.js} +1 -1
  21. package/dist/chunks/chunk-ELSYHAYC.js +2 -0
  22. package/dist/chunks/chunk-FOEBNCSD.js +3 -0
  23. package/dist/chunks/{chunk-TM3M633T.js → chunk-GLU4X7PT.js} +2 -2
  24. package/dist/chunks/{chunk-HIW2K6OP.js → chunk-GQLXEQVQ.js} +1 -1
  25. package/dist/chunks/{chunk-4KP27OCL.js → chunk-GY6BUIDP.js} +1 -1
  26. package/dist/chunks/chunk-HJQJ77F2.js +3 -0
  27. package/dist/chunks/chunk-I7MHI5CU.js +151 -0
  28. package/dist/chunks/chunk-ITP35SAY.js +2 -0
  29. package/dist/chunks/{chunk-LL4XQ3L7.js → chunk-J67P6QFC.js} +2 -2
  30. package/dist/chunks/{chunk-WNQERCOO.js → chunk-KBZI5UDL.js} +1 -1
  31. package/dist/chunks/chunk-MNGA7IHQ.js +4 -0
  32. package/dist/chunks/{chunk-MK6QZ4ES.js → chunk-P4IFCLVF.js} +1 -1
  33. package/dist/chunks/chunk-Q2RD4TRK.js +2 -0
  34. package/dist/chunks/chunk-S6NK6GX2.js +5 -0
  35. package/dist/chunks/chunk-SWXCK5C2.js +2 -0
  36. package/dist/chunks/chunk-T4IH34D7.js +2 -0
  37. package/dist/chunks/{chunk-WMDKJRDC.js → chunk-TCLZ4XM6.js} +1 -1
  38. package/dist/chunks/chunk-VC7ADQ6E.js +2 -0
  39. package/dist/chunks/{chunk-I3TMFYRJ.js → chunk-XUHLW6B2.js} +1 -1
  40. package/dist/chunks/{commands-GRWX32IX.js → commands-EOUU353W.js} +1 -1
  41. package/dist/chunks/component-JCIJQELN.js +2 -0
  42. package/dist/chunks/{config-UKI5TBH5.js → config-WV3NZGTI.js} +1 -1
  43. package/dist/chunks/connection-L6CUFUPJ.js +2 -0
  44. package/dist/chunks/connref-IT6K56UT.js +2 -0
  45. package/dist/chunks/convert-ILMJ2HHN.js +5 -0
  46. package/dist/chunks/customizations-AX7ZSXCK.js +2 -0
  47. package/dist/chunks/data-UWOV3LBO.js +5 -0
  48. package/dist/chunks/dependency-V4ZJIWQL.js +3 -0
  49. package/dist/chunks/{discovery-IWAWXXWF.js → discovery-PSGWFMJH.js} +1 -1
  50. package/dist/chunks/{dv-C45WDXRG.js → dv-SD5LTNZJ.js} +109 -48
  51. package/dist/chunks/{env-GL5ZPAZI.js → env-6RZCHQUC.js} +2 -2
  52. package/dist/chunks/environment-IBLJHUAL.js +2 -0
  53. package/dist/chunks/{environments-VZWNFJYE.js → environments-3P2I4QUC.js} +1 -1
  54. package/dist/chunks/envvar-KJ2TUZGJ.js +2 -0
  55. package/dist/chunks/fanout-2WQYFUWL.js +2 -0
  56. package/dist/chunks/{fetchxml-FWUQZP4M.js → fetchxml-M6EOF7N6.js} +1 -1
  57. package/dist/chunks/functions-NILMLS4R.js +2 -0
  58. package/dist/chunks/{graph-OK24IOUV.js → graph-NO2OT2TL.js} +1 -1
  59. package/dist/chunks/{group-TLGLTTUG.js → group-ISSJ4H2A.js} +2 -2
  60. package/dist/chunks/history-JPMLQDJI.js +2 -0
  61. package/dist/chunks/{identity-SRTOEQVC.js → identity-SBQNHSBF.js} +1 -1
  62. package/dist/chunks/init-X2VEK4T2.js +2 -0
  63. package/dist/chunks/jobs-XC7EYPBP.js +2 -0
  64. package/dist/chunks/lifecycle-2F7MF6EP.js +2 -0
  65. package/dist/chunks/{main-HOYSLMHZ.js → main-J3O5YMIY.js} +2 -2
  66. package/dist/chunks/metadata-NZFQIAAG.js +2 -0
  67. package/dist/chunks/metadataCreate-XSHK32TR.js +2 -0
  68. package/dist/chunks/{msalUser-3PBGT655.js → msalUser-KC75VDVV.js} +1 -1
  69. package/dist/chunks/names-N5JRXO33.js +2 -0
  70. package/dist/chunks/{pat-KGOBISLG.js → pat-PCMOZYM5.js} +1 -1
  71. package/dist/chunks/{pipelines-62CVDRXV.js → pipelines-OCHSIQ2E.js} +1 -1
  72. package/dist/chunks/pluginRegister-LEVZNDZN.js +4 -0
  73. package/dist/chunks/{plugins-SBMDFXVA.js → plugins-TEME2R77.js} +1 -1
  74. package/dist/chunks/{policies-BZR5437X.js → policies-EWCANNBE.js} +1 -1
  75. package/dist/chunks/{pools-I4NVR67Z.js → pools-54KMEL5D.js} +1 -1
  76. package/dist/chunks/process-KR7LIXZB.js +2 -0
  77. package/dist/chunks/{projects-GXIQO7HV.js → projects-LPVDFLPC.js} +1 -1
  78. package/dist/chunks/{provider-FN7TXWRE.js → provider-D7DMMAS6.js} +1 -1
  79. package/dist/chunks/{prs-F2EVQJRV.js → prs-C4EKGJWA.js} +1 -1
  80. package/dist/chunks/records-C4RLQXFK.js +2 -0
  81. package/dist/chunks/{run-LNEOCXZA.js → run-27MYTWHY.js} +1 -1
  82. package/dist/chunks/{run-SB4QN5Q4.js → run-46PEJS3S.js} +1 -1
  83. package/dist/chunks/{run-ICS4FNZA.js → run-7L6W2YWJ.js} +1 -1
  84. package/dist/chunks/run-CD3ZOB5V.js +4 -0
  85. package/dist/chunks/{run-APD3TRCW.js → run-EUNN6OZO.js} +1 -1
  86. package/dist/chunks/{run-H2OLE76P.js → run-JDNEQMJC.js} +1 -1
  87. package/dist/chunks/{run-G2MVOV3C.js → run-T3IIJ7SK.js} +1 -1
  88. package/dist/chunks/{run-XRPU3YZF.js → run-ZHIDOKQH.js} +1 -1
  89. package/dist/chunks/{runtime-MIU5CS5B.js → runtime-FJJPTBEE.js} +1 -1
  90. package/dist/chunks/security-SBIAK6QD.js +2 -0
  91. package/dist/chunks/{service-4VHAPTA6.js → service-4N3YP4Z7.js} +1 -1
  92. package/dist/chunks/{service-RFKOKM72.js → service-HASXLUGE.js} +1 -1
  93. package/dist/chunks/{services-4BORTJPM.js → services-C6G4XRXR.js} +1 -1
  94. package/dist/chunks/{skills-6O2GSTU4.js → skills-FW4F3EIW.js} +1 -1
  95. package/dist/chunks/solution-CNBNIS7Z.js +2 -0
  96. package/dist/chunks/solutionExport-Y524HMGN.js +2 -0
  97. package/dist/chunks/{solutionfiles-VWZHFZZ6.js → solutionfiles-2TP3Y2RW.js} +1 -1
  98. package/dist/chunks/{spn-2RZJLCML.js → spn-YSYMDTOI.js} +1 -1
  99. package/dist/chunks/{users-JIBQKPYA.js → users-Q7BJKBPP.js} +1 -1
  100. package/dist/chunks/{vargroups-Q2KG7LHR.js → vargroups-GNZBODVJ.js} +1 -1
  101. package/dist/chunks/{whoami-V54TCLT5.js → whoami-6G6UFTNS.js} +1 -1
  102. package/dist/chunks/{workitems-UG5O3EGB.js → workitems-2IOGD3EL.js} +1 -1
  103. package/package.json +7 -3
  104. package/schema/reference-data.schema.json +192 -0
  105. package/skills/ppdo-cli/SKILL.md +1 -0
  106. package/skills/ppdo-cli-data/SKILL.md +669 -0
  107. package/skills/ppdo-cli-dataverse/SKILL.md +6 -0
  108. package/skills/ppdo-cli-plugins/PluginRegistration.cs +229 -0
  109. package/skills/ppdo-cli-plugins/SKILL.md +95 -0
  110. package/skills/ppdo-cli-plugins/reference.md +72 -0
  111. package/dist/chunks/batch-EZPKLWEI.js +0 -4
  112. package/dist/chunks/bulk-7FZCDH5U.js +0 -2
  113. package/dist/chunks/chunk-5SBBTR3Y.js +0 -2
  114. package/dist/chunks/chunk-BODUSF3V.js +0 -2
  115. package/dist/chunks/chunk-DVQ7OYIJ.js +0 -2
  116. package/dist/chunks/chunk-KBQYSAJX.js +0 -2
  117. package/dist/chunks/chunk-OXZG44O5.js +0 -2
  118. package/dist/chunks/chunk-PYTSDUPY.js +0 -2
  119. package/dist/chunks/chunk-RC5VPVGC.js +0 -2
  120. package/dist/chunks/chunk-TXVNEV3M.js +0 -3
  121. package/dist/chunks/component-TCL43QXZ.js +0 -2
  122. package/dist/chunks/connection-QNXMJGHZ.js +0 -2
  123. package/dist/chunks/connref-U3CMQ64O.js +0 -2
  124. package/dist/chunks/customizations-VNEASPWI.js +0 -7
  125. package/dist/chunks/dependency-U6OQA5PS.js +0 -3
  126. package/dist/chunks/environment-FPS4AFM5.js +0 -2
  127. package/dist/chunks/envvar-52V6K6LF.js +0 -2
  128. package/dist/chunks/fanout-Q3656CCP.js +0 -2
  129. package/dist/chunks/functions-SNCK2IYV.js +0 -2
  130. package/dist/chunks/history-67SQS54S.js +0 -2
  131. package/dist/chunks/jobs-2ZPBDDHT.js +0 -2
  132. package/dist/chunks/lifecycle-OJRM7K2I.js +0 -2
  133. package/dist/chunks/metadata-WYVJ7NP7.js +0 -2
  134. package/dist/chunks/metadataCreate-PBA3KH3A.js +0 -2
  135. package/dist/chunks/names-ZRM6SAYU.js +0 -2
  136. package/dist/chunks/process-WS76WV3T.js +0 -2
  137. package/dist/chunks/records-7IQET422.js +0 -2
  138. package/dist/chunks/run-KP2SNX2A.js +0 -3
  139. package/dist/chunks/security-RC3EI7CZ.js +0 -2
  140. package/dist/chunks/solution-3WUUDYF3.js +0 -2
  141. package/dist/chunks/solutionExport-GTBTHG2D.js +0 -2
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
- import{j as f,r as a}from"./chunk-STWQDANK.js";import{b as i}from"./chunk-TQLZ3TRU.js";function d(r=i()){let s=new Set([f]);try{let n=a(r)?.identities;if(n&&typeof n=="object"){for(let e of Object.values(n))if(!(!e||typeof e!="object"))for(let t of["secret_env","pat_env"]){let o=e[t];typeof o=="string"&&o&&s.add(o)}}}catch{}return s}function g(r={},s=d()){let c=t=>process.platform==="win32"?t.toUpperCase():t,n=new Set([...s].map(c)),e={};for(let[t,o]of Object.entries(process.env))n.has(c(t))||(e[t]=o);return{...e,...r}}export{g as a};
2
+ import{j as f,r as a}from"./chunk-3L7657R3.js";import{b as i}from"./chunk-TQLZ3TRU.js";function d(r=i()){let s=new Set([f]);try{let n=a(r)?.identities;if(n&&typeof n=="object"){for(let e of Object.values(n))if(!(!e||typeof e!="object"))for(let t of["secret_env","pat_env"]){let o=e[t];typeof o=="string"&&o&&s.add(o)}}}catch{}return s}function g(r={},s=d()){let c=t=>process.platform==="win32"?t.toUpperCase():t,n=new Set([...s].map(c)),e={};for(let[t,o]of Object.entries(process.env))n.has(c(t))||(e[t]=o);return{...e,...r}}export{g as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{c as tt,i as J,j as et}from"./chunk-ITP35SAY.js";import{F as vt,G as D,b as X,c as I,d as C,e as T,f as i,g as O,h as R,i as gt,j as wt,k as ht,l as yt,n as N,s as Q,t as P,u as y,v as b,w as A,x as G,y as bt,z as B}from"./chunk-BG2OIOSN.js";import{a as ut}from"./chunk-UCTMKA2J.js";import{a as dt,b as pt,c as mt,d as ft,e as q,f as Z,h as Y}from"./chunk-FOEBNCSD.js";import{x as ct,y as lt}from"./chunk-BALEFXOL.js";import{b as z}from"./chunk-2IUXH534.js";import{e as k}from"./chunk-S4KF5Z3S.js";import{a as F,b as j,d as M,f as at}from"./chunk-WXOTXJNG.js";import{randomUUID as Bt}from"node:crypto";import{mkdtempSync as Lt,readdirSync as Et,readFileSync as xt,rmSync as Ut,statSync as Rt,mkdirSync as Ft,writeFileSync as Mt}from"node:fs";import{tmpdir as zt}from"node:os";import{basename as Xt,dirname as jt,extname as Gt,join as L,normalize as Jt}from"node:path";var kt="uniquename,friendlyname,version,ismanaged,installedon,modifiedon,solutionid",Wt={import:0,uninstall:1,export:2,publish:3,"publish-all":4},Ct="publisherid($select=uniquename,customizationprefix)";function w(t){return t==null?"None":t===!0?"True":t===!1?"False":String(t)}function Pt(t){let e=O(i(t,"publisherid"));return{uniquename:i(t,"uniquename"),name:i(t,"friendlyname"),version:i(t,"version"),managed:i(t,"ismanaged"),publisher:i(e,"uniquename"),prefix:i(e,"customizationprefix"),installed:i(t,"installedon"),modified:i(t,"modifiedon"),id:i(t,"solutionid")}}async function V(t,e,n){let s=await y(t,e,"GET","solutions",{params:[["$select",kt],["$expand",Ct],["$filter",`uniquename eq ${q(n)}`]]}),o=R(b(s).value);if(!o.length)throw new M(`no solution named '${n}'`,{service:"dataverse",hint:"run: ppdo-cli dv solution list"});return o[0]}function Se(t){return t.split(",").map(e=>Z(e)).filter(e=>e)}async function Ee(t,e,n){let s=await y(t,e,"GET",`EntityDefinitions(LogicalName=${q(n)})`,{params:[["$select","ObjectTypeCode"]]});return _t(b(s),"ObjectTypeCode")}function _t(t,e){if(!(e in t))throw new Error(`KeyError: '${e}'`);return t[e]}async function xe(t,e,n,s){let o=[];for(let c of n)o.push((await V(t,e,c)).solutionid);let r=o.map(c=>`_solutionid_value eq ${c}`).join(" or "),l=[["$select","objectid"],["$filter",`(${r}) and componenttype eq ${s}`]],[a]=await B(t,e,"solutioncomponents",l,null,null);return yt(a.map(c=>c.objectid))}async function je(t){let e=t.args,n=await P(t),s=["isvisible eq true"];e.unmanaged&&s.push("ismanaged eq false"),e.managed&&s.push("ismanaged eq true"),e.publisher&&s.push(`publisherid/customizationprefix eq ${q(String(e.publisher))}`);let o=[["$select",kt],["$expand",Ct],["$filter",s.join(" and ")],["$orderby","uniquename"]];z(t,n,"GET","solutions",null);let[r]=await B(t,n,"solutions",o,null,N(e),"solutions");await t.emit(r.map(Pt))}async function ke(t){let e=await P(t);await t.emit(Pt(await V(t,e,String(t.args.uniquename))))}async function Ce(t){let e=t.args,n=await P(t),s=await V(t,n,String(e.uniquename)),o=`_solutionid_value eq ${w(s.solutionid)}`;typeof e.type=="number"&&(o+=` and componenttype eq ${e.type}`);let r=[["$select","componenttype,objectid,rootcomponentbehavior,ismetadata"],["$filter",o]],l=G(`odata.include-annotations="${X}"`),[a]=await B(t,n,"solutioncomponents",r,l,N(e),"components");await t.emit(a.map(c=>({type:i(c,"componenttype"),type_name:i(c,`componenttype${I}`),object_id:i(c,"objectid"),behavior:T(i(c,`rootcomponentbehavior${I}`),i(c,"rootcomponentbehavior"))})))}var Vt=["dependencytype","requiredcomponenttype","requiredcomponentobjectid","requiredcomponentparentid","dependentcomponenttype","dependentcomponentobjectid","dependentcomponentparentid"];async function Pe(t){let e=t.args,n=await P(t),s=e.forUninstall?"RetrieveDependenciesForUninstall":"RetrieveMissingDependencies",[o,r]=Y(s,[["SolutionUniqueName",String(e.uniquename)]],new Set(["SolutionUniqueName"])),l=G(`odata.include-annotations="${X}"`),a=b(await y(t,n,"GET",o,{params:r,headers:l})),c=R(T(i(a,"value"),T(i(O(i(a,"EntityCollection")),"Entities"),[]))),u=[];for(let d of c){let p={};for(let m of Vt)i(d,m)!==null&&(p[m]=d[m]),C(i(d,`${m}${I}`))&&(p[`${m}_name`]=d[`${m}${I}`]);u.push(C(p)?p:d)}await t.emit(u)}async function _e(t){let e=t.args,n=D(e.save),s=D(e.unpack),o=String(e.uniquename);if(!(n||s))throw new j("pass --save <file.zip>, --unpack <folder>, or both");if(e.both&&e.managed)throw new j("--both already exports managed");if(e.allowDelete&&!s)throw new j("--allow-delete is for --unpack");let r=await P(t);await V(t,r,o);let l=Lt(L(zt(),"ppdevops-export-"));try{let a=n?Jt(n):L(l,`${o}.zip`),c=Xt(a,Gt(a)),u=L(jt(a),`${c}_managed.zip`),d=e.both?[[!1,a],[!0,u]]:[[!!e.managed,a]],p=[];for(let[v,f]of d)p.push(await Ht(t,r,o,v,f));if(!n)for(let v of p)delete v.saved;if(!s){await t.emit(p.length===1?p[0]:{solution:o,exports:p});return}let m=e.both?"Both":e.managed?"Managed":"Unmanaged",g=await Kt(a,s,m,!!e.allowDelete),x={};for(let[v,f]of Object.entries(g))x[v]=Array.isArray(f)?f.length:f;await t.emit({solution:o,exports:p,unpacked:s,package_type:m,deleted_allowed:!!e.allowDelete,files:x})}finally{Ut(l,{recursive:!0,force:!0})}}async function Ht(t,e,n,s,o){let r=b(await y(t,e,"POST","ExportSolutionAsync",{body:A({SolutionName:n,Managed:s})})),l=i(r,"AsyncOperationId"),a=i(r,"ExportJobId");k(`exporting ${n} (${s?"managed":"unmanaged"}), job ${w(l)}`);let c=await J(t,e,l);et(c);let u=b(await y(t,e,"POST","DownloadSolutionExportData",{body:A({ExportJobId:a})})),d=Buffer.from(String(_t(u,"ExportSolutionFile")),"base64");return Ft(jt(o),{recursive:!0}),Mt(o,d),{solution:n,managed:s,saved:o,bytes:d.length,job_id:l}}async function Kt(t,e,n,s){let{PackError:o}=await import("./components-LRHXR5HR.js"),r=await import("./plan-ALLKT2QZ.js"),l=await import("./unpack-HUH7OJMP.js");k(`unpacking into ${e} (${n})`);let a=new r.Snapshot(e),c;try{[c]=l.buildPlan(t,n)}catch(u){throw u instanceof o||u instanceof Error&&!u.code&&!(u instanceof F)?new j(`can't unpack the export: ${u.message}`):u}return await r.apply(c,e,{delete:s,snapshot:a})}function Zt(t,e){let n=new Set;for(let l of e){let a=O(i(l,"Attributes")),c=R(i(a,"Keys")),u=R(i(a,"Values")),d=new Map;c.slice(0,u.length).forEach((p,m)=>d.set(p,u[m]));for(let p of["schemaname","connectionreferencelogicalname"])C(d.get(p))&&n.add(w(d.get(p)).toLowerCase())}let s=[],o=[],r=e.length>0;for(let l of R(i(t,"EnvironmentVariables"))){let a=i(l,"SchemaName");if(r&&C(a)&&!n.has(String(a).toLowerCase())){o.push(`environment variable ${a}`);continue}s.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:a,value:i(l,"Value")})}for(let l of R(i(t,"ConnectionReferences"))){let a=i(l,"LogicalName");if(r&&C(a)&&!n.has(String(a).toLowerCase())){o.push(`connection reference ${a}`);continue}s.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:a,connectionid:i(l,"ConnectionId"),connectorid:i(l,"ConnectorId")})}return[s,o]}function qt(t,e){let n;try{n=Et(t,{withFileTypes:!0})}catch{return}let s=[];for(let o of n)o.isDirectory()?s.push(o.name):e.push(L(t,o.name));for(let o of s)qt(L(t,o),e)}function Yt(t){let e=0;try{e=Et(t).filter(l=>l.toLowerCase().endsWith(".cdsproj")).length}catch{e=0}if(e!==1)throw new j("name the solution .zip to import",{hint:"without a file, the folder must hold one .cdsproj"});let n=[];qt(t,n);let s=n.filter(l=>l.toLowerCase().endsWith(".zip"));if(!s.length)throw new j(`no .zip under ${t}`,{hint:"build the project first: ppdo-cli dv solution pack"});let o=s[0],r=Rt(o).mtimeMs;for(let l of s.slice(1)){let a=Rt(l).mtimeMs;a>r&&([o,r]=[l,a])}return o}function Tt(t){let e=null;for(let n of t)if(typeof n=="string")e=(e??"")+n;else if(n&&typeof n=="object"&&"value"in n&&!("kids"in n))e=(e??"")+String(n.value);else break;return e}async function $t(t){let{unzipSync:e}=await import("./esm-Z4QMBGAD.js"),n=await import("./xmldoc-B2HUNTVK.js"),s=()=>new j(`${t} is not a solution .zip`),o;try{o=e(new Uint8Array(xt(t)),{filter:u=>u.name.toLowerCase()==="solution.xml"})}catch(u){throw u.code?u:s()}let r=Object.keys(o)[0];if(r===void 0)throw s();let l;try{l=n.parseElement(o[r])}catch{throw s()}let a=l.element("SolutionManifest");if(!a)throw s();let c=u=>{let d=a.element(u);return d?Tt(d.kids)??"":null};return[c("UniqueName"),c("Version")]}function Qt(t,e){let n=r=>r.split(".").map(l=>{if(!/^\s*[+-]?\d+\s*$/.test(l))throw new Error(`ValueError: invalid literal for int() with base 10: '${l}'`);return parseInt(l,10)}),s=n(t),o=n(e);for(let r=0;r<Math.min(s.length,o.length);r++)if(s[r]!==o[r])return s[r]>o[r];return s.length>=o.length}var te="workflow,dialog,business-rule,action,bpf";async function ee(t,e,n){let s={};for(let o of R(i(O(n),"Workflows"))){let r=i(o,"UserEmail"),l=i(o,"WorkflowId"),a=R(i(b(await y(t,e,"GET","systemusers",{params:[["$select","systemuserid"],["$filter",`internalemailaddress eq ${q(w(r))}`]]})),"value"));if(!a.length)throw new M(`no user with the email ${w(r)}, named for flow ${w(T(i(o,"Name"),l))}`,{service:"dataverse"});s[mt(w(l),"{}").toLowerCase()]=a[0].systemuserid}return s}async function ne(t,e,n,s,o){let r=await import("./process-KR7LIXZB.js"),l=await import("./plugins-TEME2R77.js"),a=[[te,s.activateWorkflows],["flow",s.activateFlows]].filter(([,f])=>f).map(([f])=>f),c={solution:n,category:a.join(",")},[u,d]=await e.lookups(async()=>[a.length?await r.rows(t,e,c):[],s.activatePlugins?await l.stepRows(t,e,c):[]]),p=new Set(u.map(f=>String(f.workflowid).toLowerCase()));for(let f of ht(Object.keys(o).filter($=>!p.has($)),$=>$))k(`warning: flow ${f} is in the settings but not in the solution; skipped`);let[m,g]=await r.applyState(t,e,u,!0,o),[x,v]=await l.applyState(t,e,d,!0);return[[...m,...x],{...g,...v}]}var oe={ENOENT:"No such file or directory",EACCES:"Permission denied",EPERM:"Operation not permitted",EISDIR:"Is a directory"};async function qe(t){let e=t.args;Q(e,{holding:"--holding",upgrade:"--upgrade"},!1,"dv solution import");let n=D(e.file),s=D(e.path);if(n&&s)throw new j("give the file once, as an argument or with --path");if(!e.async&&(e.activatePlugins||e.activateWorkflows||e.activateFlows||e.publishChanges))throw new j("the --activate options and --publish-changes run after the import, so they need --async");let o=n||s;o||(o=Yt(process.cwd()),k(`importing ${o}`));let r;try{r=xt(o).toString("base64")}catch(h){let S=h;throw new j(`cannot read ${o}: ${oe[S.code??""]??S.message}`)}let l=D(e.settings),a=null;if(l)try{a=ut(vt(lt(l).toString("utf8")))}catch(h){throw h instanceof SyntaxError&&(h.name="JSONDecodeError"),h}let c=await P(t),u=e.upgrade?"StageAndUpgradeAsync":"ImportSolutionAsync";if(z(t,c,"POST",u,null),e.skipLowerVersion){let[h,S]=await $t(o),K=await c.lookups(async()=>R(i(b(await y(t,c,"GET","solutions",{params:[["$select","version"],["$filter",`uniquename eq ${q(w(h))}`]]})),"value")));if(K.length&&Qt(K[0].version,w(S))){let rt=K[0].version;k(`${w(h)} ${rt} is installed, so ${w(S)} was not imported`),await t.emit({solution:h,version:S,installed_version:rt,status:"skipped"});return}}let[d,p]=await c.lookups(async()=>{let h=e.activateFlows?await ee(t,c,a):{},S=b(await y(t,c,"POST","StageSolution",{body:A({CustomizationFile:r})}));return[h,S]},["StageSolution"]),m=O(i(p,"StageSolutionResults")),g=R(i(m,"MissingDependencies"));if(g.length&&e.skipDependencyCheck)k(`warning: staging found ${g.length} missing dependencies; importing anyway`);else if(g.length)throw await t.emit({stage:"failed",missing_dependencies:g}),new at(`${g.length} missing dependencies; nothing was imported`,{service:"dataverse",hint:"install the required solutions first, or check the export"});let x=[];if(C(a)){let h;[x,h]=Zt(a,R(i(m,"SolutionComponentsDetails")));for(let S of h)k(`warning: ${S} is in the settings but not in the solution; skipped`)}let v=Bt(),f={OverwriteUnmanagedCustomizations:!!e.overwriteUnmanaged,PublishWorkflows:!!e.activatePlugins,ImportJobId:v};g.length?f.CustomizationFile=r:f.SolutionParameters={StageSolutionUploadId:i(m,"StageSolutionUploadId")},e.holding&&(f.HoldingSolution=!0),e.skipDependencyCheck&&(f.SkipProductUpdateDependencies=!0),x.length&&(f.ComponentParameters=x);let $=b(await y(t,c,"POST",u,{body:A(f)})),_=i($,"AsyncOperationId"),nt=O(i(m,"SolutionDetails")),H=i(nt,"SolutionUniqueName"),ot=i(nt,"SolutionVersion");C(H)||([H,ot]=await $t(o));let E={solution:H,version:ot,mode:e.upgrade?"upgrade":e.holding?"holding":"update",job_id:_,import_job_id:v,settings_applied:x.length};if(!e.async){await t.emit({...E,status:"started",hint:`ppdo-cli dv job wait ${w(_)}`});return}k(`importing ${w(E.solution)} ${w(E.version)}, job ${w(_)}`);let U=await J(t,c,_);if(E.status=i(U,"status"),E.message=i(U,"message"),i(U,"statuscode")!==tt&&(await t.emit(E),et(U,`run: ppdo-cli dv solution import-results ${v}`)),e.publishChanges){let h=b(await y(t,c,"POST","PublishAllXmlAsync",{body:Buffer.from("{}")}));k(`publishing customizations, job ${w(i(h,"AsyncOperationId"))}`);let S=await J(t,c,i(h,"AsyncOperationId"));if(E.published=i(S,"statuscode")===tt,!E.published)throw await t.emit(E),new F(`the import succeeded, but publishing failed: ${w(i(S,"message"))}`,{service:"dataverse"})}let Nt=w(E.solution)+(e.holding?"_Upgrade":""),[st,it]=await ne(t,c,Nt,e,d);if(st.length&&(E.activated=st),await t.emit(E),C(it))throw new F(`the import succeeded, but ${Object.keys(it).length} components could not be turned on`,{service:"dataverse",hint:"each one's error is under activated"})}var It="urn:schemas-microsoft-com:office:spreadsheet",St={"Date/Time":"time",ItemType:"type",Name:"name","Localized Name":"display_name",Status:"status",ErrorCode:"error_code",ErrorText:"error"};function Ot(t,e){for(let n=t;n;n=n.parent){let s=n.scope?.get(e);if(s!==void 0)return s;let o=n.attrs.find(([r])=>r===(e?`xmlns:${e}`:"xmlns"));if(o)return o[1]}}function W(t,e){if(t.local!==e)return!1;let n=t.name.indexOf(":");return(t.ns||Ot(t,n<0?"":t.name.slice(0,n)))===It}function At(t,e){for(let[n,s]of t.attrs){let o=n.indexOf(":");if(!(o<0||n.slice(o+1)!==e)&&Ot(t,n.slice(0,o))===It)return s}return null}function*Dt(t,e){W(t,e)&&(yield t);for(let n of t.descendants())W(n,e)&&(yield n)}function se(t){let e=[];for(let n of Dt(t,"Row")){let s=[];for(let o of n.elements().filter(r=>W(r,"Cell"))){let r=At(o,"Index");if(r)for(let a=parseInt(r,10)-1-s.length;a>0;a--)s.push("");let l=o.elements().find(a=>W(a,"Data"));s.push(l?Z(Tt(l.kids)??""):"")}e.push(s)}return e}async function ie(t){let e=await import("./xmldoc-B2HUNTVK.js"),n;try{n=e.parseElement(t)}catch(u){throw new Error(`ParseError: ${u.message}`)}let s=new Map;for(let u of Dt(n,"Worksheet"))s.set(At(u,"Name"),se(u));let o={},r="solution";for(let u of s.get("Solution")??[])if(u.length===1&&u[0])r=u[0].toLowerCase();else if(u.length>=2&&u[0]){let d=u[0].toLowerCase().split(" ").join("_");r==="solution"&&["name","display_name","version","package_type"].includes(d)?o[d]=u[1]:r==="publisher"&&d==="name"&&(o.publisher=u[1])}let l=s.get("Components")??[],a=l[0]??[],c=[];for(let u of l.slice(1)){let d={};a.slice(0,u.length).forEach((p,m)=>{let g=u[m];p in St&&g&&(d[St[p]]=g)}),(d.type||d.name||d.error)&&c.push(d)}return[o,c]}async function re(t,e,n){let s=R(b(await y(t,e,"GET","importjobs",{params:[["$select","importjobid"],["$filter",`solutionname eq ${q(n)}`],["$orderby","createdon desc"],["$top","1"]]})).value);if(!s.length)throw new M(`no import job for solution '${n}'`,{service:"dataverse",hint:"run: ppdo-cli dv solution history --operation import"});return s[0].importjobid}function ae(t){let e=t*10,n=Math.round(e);return(Math.abs(e%1)===.5?n%2===0?n:n-1:n)/10}async function Te(t){let e=t.args,n=String(e.target),s=await P(t),o=pt(n)?ft(n):await re(t,s,n),r=b(await y(t,s,"GET",`importjobs(${o})`,{params:[["$select","solutionname,progress,createdon,startedon,completedon"]]})),[l,a]=Y("RetrieveFormattedImportJobResults",[["ImportJobId",o]]),c=b(await y(t,s,"GET",l,{params:a})),[u,d]=await ie(String(T(i(c,"FormattedResults"),""))),p=d.filter($=>$.status==="Failure"||C($.error)),m={};for(let $ of d){let _=$.status??"";m[_]=(m[_]??0)+1}let g=i(r,"progress"),x=p.length?"failed":g!==null&&typeof g=="number"&&g>=100?"succeeded":"incomplete",v={};for(let[$,_]of Object.entries(m))$&&(v[$]=_);let f={import_job_id:o,solution:T(i(u,"name"),i(r,"solutionname")),version:i(u,"version"),package:i(u,"package_type"),publisher:i(u,"publisher"),result:x,progress:typeof g=="number"?ae(g):null,started:i(r,"startedon"),completed:i(r,"completedon"),counts:v,failed:p};e.components&&(f.components=d),await t.emit(gt(f))}async function ce(t,e,n,s,o){let r=[],l={...n,Prefer:[n.Prefer,"odata.maxpagesize=500"].filter(a=>a).join(", ")};for await(let a of bt(t,"msdyn_solutionhistories",e,l))for(let c of R(b(a).value)){if(String(T(i(c,"msdyn_starttime"),""))<s)return r;if(o!==null&&r.length>=o)return k(`showing the first ${o} operations; pass --limit n or --all for more`),r;r.push(c)}return r}async function Ie(t){let e=t.args,n=await P(t),s=[];e.uniquename&&s.push(`msdyn_name eq ${q(String(e.uniquename))}`),e.state&&s.push(`msdyn_result eq ${e.state==="failed"?"false":"true"}`),e.operation&&s.push(`msdyn_operation eq ${Wt[String(e.operation)]}`);let o=[["$orderby","msdyn_starttime desc"]];s.length&&o.push(["$filter",s.join(" and ")]),z(t,n,"GET","msdyn_solutionhistories",null);let r=G(`odata.include-annotations="${X}"`),l;e.since?l=await ce(n,o,r,ct(String(e.since)),N(e)):[l]=await B(t,n,"msdyn_solutionhistories",o,r,N(e),"operations");let a=[];for(let c of l){let u={solution:i(c,"msdyn_name"),version:i(c,"msdyn_solutionversion"),operation:i(c,`msdyn_operation${I}`),suboperation:i(c,`msdyn_suboperation${I}`),result:i(c,"msdyn_result")===!0?"succeeded":"failed",started:i(c,"msdyn_starttime"),ended:i(c,"msdyn_endtime"),seconds:i(c,"msdyn_totaltime"),managed:i(c,"msdyn_ismanaged"),publisher:i(c,"msdyn_publishername"),id:i(c,"msdyn_solutionhistoryid")};i(c,"msdyn_result")!==!0&&(u.error_code=i(c,"msdyn_errorcode"),u.error=i(c,"msdyn_exceptionmessage")),u.suboperation==="None"&&delete u.suboperation,a.push(wt(u))}await t.emit(a)}function le(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}async function Oe(t){let e=t.args;Q(e,{all:"--all",entity:"--entity"},!0,"dv solution publish");let n=await P(t);if(e.all){await y(t,n,"POST","PublishAllXml",{body:Buffer.from("{}")}),await t.emit({published:"all"});return}let s=e.entity.map(r=>dt(r,"table logical name").toLowerCase()),o="<importexportxml><entities>"+s.map(r=>`<entity>${le(r)}</entity>`).join("")+"</entities></importexportxml>";await y(t,n,"POST","PublishXml",{body:A({ParameterXml:o})}),await t.emit({published:s})}export{Wt as a,Pt as b,V as c,Se as d,Ee as e,xe as f,je as g,ke as h,Ce as i,Pe as j,_e as k,Zt as l,Yt as m,$t as n,Qt as o,qe as p,ie as q,Te as r,Ie as s,Oe as t};
@@ -0,0 +1,5 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{$ as tt,A as Fe,B as We,C as Xe,D as be,F as Pe,H as Re,I as Je,J as De,N as Qe,S as U,T as fe,U as ve,V as et,X as Q,a as z,aa as nt,ca as rt,e as Ue,f as Ge,g as ze,i as R,j as X,k as ce,l as q,m as _,o as J,p as he,q as we,r as B,s as H,t as Ce,u as ae,v as $e,w as qe,y as He,z as Ze}from"./chunk-I7MHI5CU.js";var ue=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,at=/^(\d{4})-(\d{2})-(\d{2})/,ot=`
3
+ `,it=`\r
4
+ `;function v(e){return typeof e=="object"&&e!==null&&e.lookup===!0}function ke(e){return typeof e=="object"&&e!==null&&e.file===!0}function xe(e){return typeof e=="object"&&e!==null&&e.image===!0}function lt(e){switch(e.kind){case"lookup":return[`_${e.name}_value`];case"file":return[e.name,`${e.name}_name`];case"image":return[`${e.name}id`];default:return[e.name]}}function Oe(e){let t=e.trim();/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(t)&&(t+="Z"),/^\d{4}-\d{2}-\d{2}$/.test(t)&&(t+="T00:00:00Z"),t=t.replace(/(\.\d{3})\d+/,"$1");let r=Date.parse(t);return Number.isNaN(r)?null:new Date(r).toISOString().slice(0,19)+"Z"}function Se(e,t){switch(t.kind){case"lookup":{let r=e[`_${t.name}_value`];if(typeof r!="string"||!r)return null;let n=String(e[`_${t.name}_value${et}`]??t.targets[0]??""),o=e[`_${t.name}_value${ve}`];return{lookup:!0,table:n,id:r.toLowerCase(),name:typeof o=="string"?o:null}}case"file":{let r=e[t.name];if(typeof r!="string"||!r)return null;let n=e[`${t.name}_name`];return{file:!0,id:r.toLowerCase(),name:typeof n=="string"?n:null}}case"image":{let r=e[`${t.name}id`];return typeof r=="string"&&r?{image:!0,id:r.toLowerCase()}:null}default:return Pt(e[t.name]??null,t)}}function Pt(e,t){if(e==null)return null;switch(t.kind){case"text":return e===""?null:String(e);case"int":case"decimal":case"choice":return e instanceof R?e:new R(String(e));case"bool":return!!e;case"choices":{let r=String(e).split(",").map(n=>n.trim()).filter(n=>n).map(Number);return r.length?[...new Set(r)].sort((n,o)=>n-o):null}case"date":{let r=at.exec(String(e));return r?r[0]:null}case"datetime":return Oe(String(e));case"guid":return String(e).toLowerCase();default:return null}}var F=class extends Error{};function Ie(e,t,r){let n=null;if(e instanceof R)n=e;else if(typeof e=="string")try{n=new R(e)}catch{n=null}if(!n||r&&!/^-?\d+$/.test(n.text))throw new F(`'${t.name}' must be ${r?"a whole number":"a number"}`);return n}function on(e,t){if(e===null)return null;switch(t.kind){case"text":if(typeof e=="string")return e===""?null:e;if(e instanceof R)return e.text;if(typeof e=="boolean")return e?"true":"false";throw new F(`'${t.name}' must be text`);case"int":case"choice":return Ie(e,t,!0);case"decimal":return Ie(e,t,!1);case"bool":if(typeof e!="boolean")throw new F(`'${t.name}' must be true or false`);return e;case"choices":{let n=(Array.isArray(e)?e:[e]).map(o=>Number(Ie(o,t,!0).text));return n.length?[...new Set(n)].sort((o,i)=>o-i):null}case"date":{let r=typeof e=="string"?at.exec(e):null;if(!r||Oe(r[0])===null)throw new F(`'${t.name}' must be a date (YYYY-MM-DD)`);return r[0]}case"datetime":{let r=typeof e=="string"?Oe(e):null;if(!r)throw new F(`'${t.name}' must be a date and time (YYYY-MM-DDTHH:MM:SSZ)`);return r}case"guid":if(typeof e!="string"||!ue.test(e))throw new F(`'${t.name}' must be a GUID`);return e.toLowerCase();default:throw new F(`'${t.name}' is a ${t.attributeType} column`)}}function sn(e,t){return e===""&&(e=null),t===""&&(t=null),e===null||t===null?e===t:typeof e=="string"&&typeof t=="string"?e.split(it).join(ot)===t.split(it).join(ot):e instanceof R&&t instanceof R?e.text===t.text:Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((r,n)=>r===t[n]):v(e)&&v(t)?e.id===t.id:typeof e=="boolean"&&typeof t=="boolean"?e===t:!1}function ct(e,t){if(e===null)return null;if(t.kind==="choice"&&e instanceof R){let r=t.options.get(Number(e.text));return r===void 0?e:new q(e,r)}if(t.kind==="choices"&&Array.isArray(e)){let r=e.map(o=>new R(String(o))),n=e.map(o=>t.options.get(o)??String(o));return new q(new ce(r),n.join(", "))}if(typeof e=="string"||typeof e=="boolean"||e instanceof R)return e;throw new Error(`no file form for ${t.name}`)}function an(e,t){return e===null?null:t.kind==="choices"&&Array.isArray(e)?e.join(","):(t.kind==="choice"||t.kind==="int"||t.kind==="decimal",e)}function ln(e){return e===null?null:e instanceof R?e:v(e)?e.name?`${e.id} (${e.name})`:e.id:ke(e)?e.name:xe(e)?"image":typeof e=="string"&&e.length>st?`${e.slice(0,st)}... (${e.length} characters)`:e}var st=200;import{existsSync as Ut}from"node:fs";import{join as Gt}from"node:path";var me=25;function Le(e){return"g:"+e.toLowerCase()}var Me=class{constructor(t,r){this.model=t;this.dv=r}known=new Map;async identity(t){let r=this.model.schema.byName.get(t)??null,n=r?this.model.meta(t):await this.model.other(t);if(!n)throw new F(`the environment has no table '${t}'`);return{table:t,meta:n,schema:r}}cache(t){let r=this.known.get(t);return r||(r=new Map,this.known.set(t,r)),r}get(t,r){return this.known.get(t)?.get(r.toLowerCase())}async selectFor(t){let r=await this.identity(t),n=new Set([r.meta.primaryId]);return r.meta.primaryName&&n.add(r.meta.primaryName),[...n]}async seed(t,r){let n=await this.identity(t),o=this.cache(t);for(let i of r){let c=String(i[n.meta.primaryId]).toLowerCase(),f=n.meta.primaryName?i[n.meta.primaryName]??null:null;o.set(c,{id:c,key:Le(c),form:[[n.meta.primaryId,c]],name:typeof f=="string"?f:null})}}async ensure(t,r){let n=this.cache(t),o=[...new Set(r.map(p=>p.toLowerCase()))].filter(p=>!n.has(p));if(!o.length)return;let i=await this.identity(t),c=await this.selectFor(t),f=[];for(let p=0;p<o.length;p+=me)f.push(o.slice(p,p+me));let l=(await Q(f,4,p=>this.dv.rows(i.meta.entitySet,[["$select",c.join(",")],["$filter",p.map(g=>`${i.meta.primaryId} eq ${g}`).join(" or ")]]))).flat();await this.seed(t,l);for(let p of o)n.has(p)||n.set(p,null)}lookupForm(t,r){let n=this.get(t.table,t.id),o=t.name??n?.name??null;if(r.targets.length>1){let i=this.model.tables.get(t.table)?.primaryId??`${t.table}id`;return new q(new X([["$table",t.table],[i,t.id]]),o)}return new q(t.id,o)}async findByKeys(t,r,n=[]){let o=await this.identity(t),i=new Map;if(!r.length)return i;let c=[...new Set([...await this.selectFor(t),...n])],f=[...new Set(r.map(g=>g.key.slice(2)))],l=[];for(let g=0;g<f.length;g+=me)l.push(f.slice(g,g+me));let p=(await Q(l,4,g=>this.dv.rows(o.meta.entitySet,[["$select",c.join(",")],["$filter",g.map(u=>`${o.meta.primaryId} eq ${u}`).join(" or ")]]))).flat();await this.seed(t,p);for(let g of p)i.set(Le(String(g[o.meta.primaryId])),g);return i}};function ft(e,t){if(typeof e!="string"||!ue.test(e))throw new F(`${t} must be a GUID`);return e.toLowerCase()}var Ee=class{constructor(t){this.keys=t}async recordKey(t,r){let o=(await this.keys.identity(t)).meta.primaryId;if(r[o]===void 0||r[o]===null||r[o]==="")throw new F(`the record has no '${o}' (its GUID)`);let i=ft(r[o],`'${o}'`);return{table:t,key:Le(i),parts:[{col:o,value:i}]}}async lookupKey(t,r){let n=B(r),o,i;if(n&&"$table"in n){let u=n.$table;if(typeof u!="string"||!t.targets.includes(u))throw new F(`'${t.name}': $table must be one of ${t.targets.join(", ")}`);o=u;let $={};for(let[S,b]of Object.entries(n))S!=="$table"&&($[S]=b);i=$}else{if(t.targets.length>1)throw new F(`'${t.name}' can point to more than one table (${t.targets.join(", ")}): the value must be a map with $table`);o=t.targets[0],i=r}let f=(await this.keys.identity(o)).meta.primaryId,l=B(i),p=i;if(l){let u=Object.keys(l).filter($=>$!==f);if(u.length)throw new F(`'${t.name}': a lookup is the GUID of its target; ${o} has no key '${u[0]}' (use ${f})`);p=l[f]}let g=ft(p,`'${t.name}' points to ${o}: the value`);return{table:o,key:Le(g),parts:[{col:f,value:g}]}}};import{createHash as Rt}from"node:crypto";var Dt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/,It=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function ut(e){return e.map(t=>/^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$/.test(t)?t.toLowerCase():t).join("--")}function mt(e){return`${e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,80)}~${Rt("sha256").update(e,"utf8").digest("hex").slice(0,8)}`}function Ot(e){return Dt.test(e)&&!e.endsWith(".")&&!It.test(e)?e:mt(e)}function dt(e){let t=e.map(Ot),r=new Map;for(let n of t)r.set(n.toLowerCase(),(r.get(n.toLowerCase())??0)+1);return t.map((n,o)=>(r.get(n.toLowerCase())??0)>1?mt(e[o]):n)}import{existsSync as gt,readdirSync as yt,readFileSync as Vt,statSync as Ve}from"node:fs";import{join as de}from"node:path";var pt=/^[a-z0-9][a-z0-9-]*$/;function Ye(e){let t=de(e,$e);return!gt(t)||!Ve(t).isDirectory()?[]:yt(t).filter(r=>Ve(de(t,r)).isDirectory()).sort()}function ht(e,t,r,n){let o=`${$e}/${t}`;pt.test(t)||n.push(`${o}: an overlay name must match ${pt.source}`);let i=de(e,o,"tables"),c=[];if(!gt(i))return c;for(let f of yt(i).sort()){let l=`${o}/tables/${f}`;if(Ve(de(i,f)).isDirectory()||!f.endsWith(".yaml")){n.push(`${l}: an overlay has one YAML file for each table, in tables/`);continue}let p=f.slice(0,-5);if(!r.byName.get(p)){n.push(`${l}: the schema has no table '${p}'`);continue}let u;try{u=B(we(Vt(de(i,f),"utf8"),l))}catch(b){if(b instanceof he){n.push(...b.problems.map(x=>`${l}: ${x}`));continue}throw b}if(!u){n.push(`${l}: the file must be a map with table, overlay and records`);continue}for(let b of Object.keys(u))["table","overlay","records"].includes(b)||n.push(`${l}: unknown property '${b}'`);u.table!==p&&n.push(`${l}: table must be '${p}', the file name`),u.overlay!==t&&n.push(`${l}: overlay must be '${t}', the folder name`);let $=[],S=u.records??[];Array.isArray(S)?S.forEach((b,x)=>{let E=B(b);if(!E){n.push(`${l}: record ${x+1} must be a map`);return}"$deleted"in E&&n.push(`${l}: record ${x+1}: an overlay cannot have $deleted; deletes are only in the deletion log (data/.deleted)`),$.push({file:l,index:x,values:E})}):n.push(`${l}: records must be a list`),c.push({table:p,file:l,records:$})}return c}function xn(e,t,r){let n=Ye(e);if(t!==null){if(!n.includes(t))throw z("overlay_not_found",`the overlay '${t}' does not exist in ${$e}`,[],n.length?`the overlays are: ${n.join(", ")}`:"the folder has no overlays");return t}if(!r&&n.length)throw z("overlay_required",`the folder has overlays (${n.join(", ")}): give --overlay <name> or --no-overlay`);return null}async function Yt(e,t,r){let n=new Set(await e.selectFor(t.table));for(let o of t.columns){let i=r.columns.get(o.name);for(let c of lt(i))n.add(c)}return r.columns.has("statecode")&&n.add("statecode"),[...n]}function Kt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;")}function _t(e,t,r,n){let o=new Set([t.primaryId]);t.primaryName&&o.add(t.primaryName);for(let c of e.columns){let f=t.columns.get(c.name);f.kind==="file"?(o.add(f.name),o.add(`${f.name}_name`)):f.kind==="image"?o.add(`${f.name}id`):o.add(f.name)}return t.columns.has("statecode")&&o.add("statecode"),`<fetch version="1.0" mapping="logical" ${`count="5000" page="${r}"`+(n?` paging-cookie="${Kt(n)}"`:"")}><entity name="${e.table}">`+[...o].map(c=>`<attribute name="${c}"/>`).join("")+`<order attribute="${t.primaryId}"/>`+(e.fetchXmlFilter?nt(e.fetchXmlFilter,e.table):"")+"</entity></fetch>"}async function bt(e,t,r,n){let o=t.meta(n.table);if(n.fetchXmlFilter)return e.fetchRows(o.entitySet,(p,g)=>_t(n,o,p,g));let i=(await Yt(r,n,o)).join(","),c=[["$select",i]];if(n.filter&&c.push(["$filter",n.filter]),!await Nt(e,o,n.filter))return e.rows(o.entitySet,c);let f=jt(o.primaryId),l=await Q(f,$t,p=>e.rows(o.entitySet,[["$select",i],["$filter",n.filter?`(${n.filter}) and (${p})`:p]]));return e.progress.log(`read ${n.table} in ${f.length} ranges of the primary key, ${$t} at the same time`),l.flat()}var wt=16,$t=8;function jt(e){let t=n=>`00000000-0000-0000-0000-${n.toString(16)}00000000000`,r=[];for(let n=0;n<wt;n++){let o=n===0?null:`${e} ge ${t(n)}`,i=n===wt-1?null:`${e} lt ${t(n+1)}`;r.push([o,i].filter(c=>c).join(" and "))}return r}async function Nt(e,t,r){let n=[["$select",t.primaryId],["$count","true"],["$top","1"]];r&&n.push(["$filter",r]);let o=await e.getJson(t.entitySet,n);return Number(o["@odata.count"]??0)>=5e3||o["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"]===!0}import{existsSync as kt,readFileSync as Bt}from"node:fs";import{join as je}from"node:path";var xt="data/.deleted",Te=`${xt}/tables`,Ae=`${xt}/relationships`,Ke="the deletion log has the form before issue 12 (match keys and restored); an entry is now id, name and deleted";function St(e,t,r){try{let n=B(we(Bt(je(e,t),"utf8"),t));return n||r.push(`${t}: the file must be a map`),n}catch(n){if(n instanceof he)return r.push(...n.problems.map(o=>`${t}: ${o}`)),null;throw n}}var Lt=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:null,_e=e=>typeof e=="string"&&ue.test(e)?e.toLowerCase():null;function Mt(e,t,r){let n=`${Te}/${t}.yaml`;if(!kt(je(e,n)))return null;let o=St(e,n,r);if(!o)return null;for(let l of Object.keys(o))l==="match"?r.push(`${n}: ${Ke}`):["table","records"].includes(l)||r.push(`${n}: unknown property '${l}'`);o.table!==t&&r.push(`${n}: table must be '${t}'`);let i=[],c=new Set,f=o.records??[];return Array.isArray(f)?f.forEach((l,p)=>{let g=B(l),u=`${n} record ${p+1}`;if(!g){r.push(`${u}: must be a map with id, name and deleted`);return}for(let x of Object.keys(g))x==="restored"?r.push(`${u}: ${Ke}`):["id","name","deleted"].includes(x)||r.push(`${u}: unknown property '${x}'`);let $=_e(g.id);$?c.has($)?r.push(`${u}: the GUID ${$} is in the log two times`):c.add($):r.push(`${u}: id must be the GUID of the record`);let S=g.name;S!=null&&typeof S!="string"&&r.push(`${u}: name must be text`);let b=Lt(g.deleted);b||r.push(`${u}: deleted must be a date (YYYY-MM-DD)`),$&&b&&i.push({id:$,name:typeof S=="string"?S:null,deleted:b,index:p})}):r.push(`${n}: records must be a list`),{table:t,file:n,entries:i}}function Et(e,t,r){let n=`${Ae}/${t.toLowerCase()}.yaml`;if(!kt(je(e,n)))return null;let o=St(e,n,r);if(!o)return null;for(let g of Object.keys(o))["relationship","from","to","links"].includes(g)||r.push(`${n}: unknown property '${g}'`);let i=o.from,c=o.to;if((typeof o.relationship!="string"||o.relationship.toLowerCase()!==t.toLowerCase())&&r.push(`${n}: relationship must be '${t}'`),typeof i!="string"||typeof c!="string")return r.push(`${n}: the header must have from and to`),null;let f=[],l=new Set,p=o.links??[];return Array.isArray(p)?p.forEach((g,u)=>{let $=B(g),S=`${n} link ${u+1}`;if(!$){r.push(`${S}: must be a map with from, to and removed`);return}for(let T of Object.keys($))T==="restored"?r.push(`${S}: ${Ke}`):["from","to","removed"].includes(T)||r.push(`${S}: unknown property '${T}'`);let b=_e($.from),x=_e($.to);(!b||!x)&&r.push(`${S}: from and to must be the GUIDs of the two records`);let E=Lt($.removed);if(E||r.push(`${S}: removed must be a date (YYYY-MM-DD)`),!(!b||!x||!E)){if(l.has(`${b}|${x}`)){r.push(`${S}: the link is in the log two times`);return}l.add(`${b}|${x}`),f.push({from:b,to:x,removed:E})}}):r.push(`${n}: links must be a list`),{name:t,file:n,from:i,to:c,entries:f}}var pe=(e,t)=>e<t?-1:e>t?1:0;function Tt(e,t){let r=[...t].sort((n,o)=>pe(n.deleted,o.deleted)||pe(n.id,o.id));return J(new _([["table",e],["records",r.map(n=>{let o=[["id",n.id]];return n.name!==null&&o.push(["name",n.name]),o.push(["deleted",n.deleted]),new _(o)})]]))}function At(e,t,r,n){let o=[...n].sort((i,c)=>pe(i.removed,c.removed)||pe(i.from,c.from)||pe(i.to,c.to));return J(new _([["relationship",e],["from",t],["to",r],["links",o.map(i=>new _([["from",i.from],["to",i.to],["removed",i.removed]]))]]))}function Ct(e,t){return{name:e,kind:"lookup",attributeType:"Lookup",typeName:"LookupType",validForCreate:!0,validForUpdate:!0,validForRead:!0,custom:!1,attributeOf:null,targets:[t],navigation:new Map,options:new Map,stateOf:new Map,primaryImage:!1,fullImage:!1,dateOnly:!1}}function ge(e,t){if(e instanceof q)return ge(e.value,t);if(e instanceof R){t.push(Number(e.text));return}if(e instanceof X){for(let[r,n]of e.entries)r!=="$table"&&ge(n,t);return}if(e instanceof ce||Array.isArray(e)||e instanceof _){t.push(JSON.stringify(e));return}if(typeof e=="object"&&e!==null){for(let[r,n]of Object.entries(e))r!=="$table"&&ge(n,t);return}t.push(e==null?"":String(e))}function zt(e,t){let r=[...e],n=[...t];for(let o=0;o<Math.min(r.length,n.length);o++){let i=r[o].codePointAt(0)-n[o].codePointAt(0);if(i)return i}return r.length-n.length}function Ne(e,t){for(let r=0;r<Math.min(e.length,t.length);r++){let n=e[r],o=t[r];if(typeof n=="number"&&typeof o=="number"){if(n!==o)return n<o?-1:1;continue}let i=zt(String(n),String(o));if(i)return i}return e.length-t.length}function Be(e){let t=[];for(let[,r]of e)ge(r,t);return t}function qt(e){let t=[];for(let[,r]of e)ge(r,t);return ut(t.map(String))}function ie(e){return e instanceof q?ie(e.value):e instanceof R?"n"+e.text:e instanceof X||e instanceof _?"{"+e.entries.map(([t,r])=>`${t}=${ie(r)}`).join(",")+"}":e instanceof ce?"["+e.items.map(ie).join(",")+"]":Array.isArray(e)?"["+e.map(ie).join(",")+"]":typeof e=="object"&&e!==null?"{"+Object.entries(e).map(([t,r])=>`${t}=${ie(r)}`).join(",")+"}":typeof e=="string"?"s"+e.replace(/\r\n/g,`
5
+ `):String(e)}function Ft(){return new Date().toISOString().slice(0,10)}async function Qn(e,t,r){let n=e.progress,o=rt(t);n.log(`export ${t}: ${o.tables.length} schema files`);let i=new tt(e,o);await fe(n,"read the metadata",()=>i.load(),()=>`${U(i.tables.size)} tables`);let c=new Me(i,e),f=new Ee(c),l=[],p=i.dataTables(),g=o.relationships.map(a=>a.name),u=r.only?new Set(r.only.map(a=>a.toLowerCase())):null;if(u){let a=new Set([...p.map(A=>A.table),...g.map(A=>A.toLowerCase())]),h=[...u].filter(A=>!a.has(A));if(h.length)throw z("usage",`--only: the schema has no table or relationship '${h[0]}'`)}let $=p.filter(a=>!u||u.has(a.table)),S=o.relationships.filter(a=>!u||u.has(a.name.toLowerCase())),b=new Map;for(let a of $)b.set(a.table,a);for(let a of S){let h=i.relationship(a.name);for(let A of[h.entity1,h.entity2])b.set(A,o.byName.get(A))}let x=new Map;await Q([...b.values()],4,async a=>{x.set(a.table,await fe(n,`read ${a.table}`,()=>bt(e,i,c,a),h=>`${U(h.length)} records`))});for(let[a,h]of x)await c.seed(a,h);let E=new Map;for(let a of $){let h=i.meta(a.table);for(let A of x.get(a.table)??[])for(let te of a.columns){let O=h.columns.get(te.name);if(O.kind!=="lookup")continue;let V=Se(A,O);if(v(V)){let y=E.get(V.table);y||E.set(V.table,y=new Set),y.add(V.id)}}}for(let[a,h]of E)await fe(n,`read the keys of the lookup targets in ${a}`,()=>c.ensure(a,[...h]),()=>`${U(h.size)} records`);let T=new We,D=[],ee=await Ht(t,o,f,l);for(let a of $){let h=i.meta(a.table);D.push(await Zt(e,t,i,c,f,a,h,x.get(a.table)??[],T,r,l,ee))}let Z=[];for(let a of S)Z.push(await fe(n,`read the links of ${a.name}`,()=>vt(e,t,i,c,f,a.name,a.delete.mode!=="off",x,T,l,r),h=>`${U(h.links)} links`));u||(T.own(H),T.own(Ce),T.own(ae));let M=Xe(t,T,!r.check);n.log(`${r.check?"would write":"wrote"} ${U(M.written.length)} files, ${r.check?"would remove":"removed"} ${U(M.removed.length)} files`);for(let a of l)n.log(`warning: ${a}`);let j=a=>M.written.concat(M.removed).filter(h=>h===a||h.startsWith(a+"/")||h.startsWith(a+"."));for(let a of D){let h=`${H}/${a.table}`;a.written=j(h).length>0,a.files!==void 0&&(a.files_changed=j(`${ae}/${a.table}`).length),a.files_changed&&(a.written=!0)}for(let a of D)M.written.includes(`${Te}/${a.table}.yaml`)&&(a.written=!0);for(let a of Z)a.written=M.written.includes(a.file)||M.removed.includes(a.file)||M.written.includes(`${Ae}/${a.name.toLowerCase()}.yaml`);let se=new Set([...D.map(a=>a.table)]);for(let a of M.removed){let h=/^data\/(tables|files)\/([^/.]+)/.exec(a);(!h||!se.has(h[2]))&&l.push(`${r.check?"would remove":"removed"} ${a}: the schema does not name it`)}return{folder:t,checked_only:r.check,tables:D,relationships:Z,warnings:l}}async function Ht(e,t,r,n){let o=new Map;for(let i of Ye(e)){let c=[];for(let f of ht(e,i,t,c))for(let l of f.records)try{let p=await r.recordKey(f.table,l.values),g=o.get(f.table);g||o.set(f.table,g=[]),g.push({file:f.file,key:p.key})}catch{}c.length&&n.push(`the overlay '${i}' has problems; the import will refuse it: ${c[0]}`)}return o}async function Zt(e,t,r,n,o,i,c,f,l,p,g,u){let $=qe(i,c.primaryId),S=i.columns.map(s=>c.columns.get(s.name)).filter(s=>s.kind==="file"||s.kind==="image"),b=i.columns.filter(s=>De(i.table,s.name)).map(s=>s.name),x=new Map,E=new Map;for(let s of f){let m=String(s[c.primaryId]).toLowerCase(),d=n.get(i.table,m);x.set(d.key,Jt(n,i,c,s,d)),E.set(d.key,s)}let T=[],D=null;try{D=He(t,i.table,T)}catch{D=null}T.length&&g.push(`${H}/${i.table}.yaml: the file in the folder is not valid; the export writes it again (${T[0]})`);let ee=i.delete.mode!=="off",Z=p.today??Ft(),M=ee?Qt(t,i):null,j=0,se=0,a=0,h=0,A=new Set,te=new Map;if(D&&!T.length&&D.header.match.join(",")===$.match.join(",")){let s=[];for(let w of D.records){let k;try{k=await o.recordKey(i.table,w.values)}catch(C){if(C instanceof F){g.push(`${w.file}: a record is not valid and is not kept: ${C.message}`);continue}throw C}if(A.add(k.key),x.has(k.key)){te.set(k.key,ie(w.values));continue}s.push({fk:k,values:w.values})}let m=s.length?await n.findByKeys(i.table,s.map(w=>w.fk)):new Map,d=u.get(i.table)??[];for(let w of s){a++;let k=w.fk.key.slice(2),C=d.filter(K=>K.key===w.fk.key).map(K=>K.file);for(let K of C)g.push(`${K}: names ${i.table} ${k}, which the export removed; remove the entry from the overlay`);if(m.has(w.fk.key)){g.push(`${i.table} ${k}: the record is no longer in the scope (it is in the environment); the export removes it from the file and does not log it as deleted`);continue}if(!M||M.byId.has(k))continue;let I=c.primaryName?w.values[c.primaryName]:void 0,G={id:k,name:typeof I=="string"?I:I instanceof R?I.text:null,deleted:Z,index:-1};M.entries.push(G),M.byId.set(k,G),h++}}if(M){for(let s of M.byId.keys())x.has("g:"+s)&&g.push(`${i.table} ${s}: the record is in the deletion log and in the source environment again; the log keeps the entry, and the import uses the data file and does not delete it`);M.entries.length&&l.put(`${Te}/${i.table}.yaml`,Tt(i.table,M.entries))}for(let s of x.keys())A.has(s)||j++;let O=[...x.values()].sort((s,m)=>Ne(s.sort,m.sort)),V=dt(O.map(s=>qt(s.form))),y=[],L=(s,m,d,w,k)=>{let I=i.columns.find(re=>re.name===d)?.file??i.files.name??Wt,G=E.get(s.key);return ze(I,{id:m,column:d,filename:w,ext:k,value:(re,ye)=>{if(re===c.primaryId)return m;let oe=Se(G,c.columns.get(re));return ye&&v(oe)&&oe.name===null?n.get(oe.table,oe.id)?.name??"":Xt(oe,ye)}})};if(S.length){let s=[];O.forEach((d,w)=>{if(d.id)for(let k of S){let C=d.entries.findIndex(([I])=>I===k.name);C>=0&&d.entries[C][1]!==null&&s.push({rec:d,idf:V[w],c:k,at:C})}}),e.progress.log(`${i.table}: download ${U(s.length)} files and images, ${p.parallel} at the same time`);let m=0;await Q(s,p.parallel,async d=>{m++,m%50===0&&e.progress.log(`${i.table}: ${U(m)} of ${U(s.length)} files`);let w=await Qe(e,c,d.rec.id,d.c);if(w===null){d.rec.entries[d.at]=[d.c.name,null];return}w.length>Pe&&g.push(`${i.table} ${d.idf} ${d.c.name}: the file is ${w.length} bytes; source control keeps each version of a binary file`);let k=d.rec.entries[d.at][1],C=d.c.kind==="file"?k.entries.find(([K])=>K==="name")?.[1]:null,I=d.c.kind==="file"?Re(C):Je(w),G=L(d.rec,d.idf,d.c.name,C,I);y.push({rec:d.rec,idf:d.idf,at:d.at,column:d.c.name,rel:G,bytes:w,ext:I,name:C,isFile:d.c.kind==="file"})})}b.length&&O.forEach((s,m)=>{for(let d of b){let w=s.entries.findIndex(([oe])=>oe===d),k=w>=0?s.entries[w][1]:null;if(typeof k!="string")continue;let I=E.get(s.key)[De(i.table,d)],G=typeof I=="string"&&I?I:null,K=Buffer.from(k,"base64"),re=Re(G),ye=L(s,V[m],d,G,re);K.length>Pe&&g.push(`${i.table} ${V[m]} ${d}: the file is ${K.length} bytes; source control keeps each version of a binary file`),y.push({rec:s,idf:V[m],at:w,column:d,rel:ye,bytes:K,ext:re,name:null,isFile:!1})}});let P=new Map;for(let s of y){let m=s.rel.split("/");for(let d=1;d<m.length;d++){let w=m.slice(0,d).join("/").toLowerCase(),k=m[d-1],C=P.get(w);(C===void 0||k<C)&&P.set(w,k)}}let N=s=>s.map((m,d)=>P.get(s.slice(0,d+1).join("/").toLowerCase())).join("/"),Y=new Map,ne=[];y.sort((s,m)=>s.idf<m.idf?-1:s.idf>m.idf?1:s.column<m.column?-1:1);for(let s of y){let m=s.rel.split("/"),d=m.length>1?N(m.slice(0,-1))+"/":"";s.rel=d+m[m.length-1];let w=`${s.idf} ${s.column}`,k=Y.get(s.rel.toLowerCase());k!==void 0?ne.push(`${ae}/${i.table}/${s.rel}: ${k} and ${w}`):Y.set(s.rel.toLowerCase(),w)}if(ne.length)throw z("file_name_conflict",`${i.file}: the file name pattern gives one path to two files; add {$id} to the pattern, or use columns whose values are unique`,ne.sort());for(let s of y){let m=[["$file",s.rel]];s.isFile&&m.push(["name",s.name]),s.rec.entries[s.at]=[s.column,new X(m)],s.rec.binaries.push({column:s.column,bytes:s.bytes,ext:s.ext}),l.put(`${ae}/${i.table}/${s.rel}`,s.bytes)}for(let s of O){let m=te.get(s.key);m!==void 0&&m!==ie(new _(s.entries))&&se++}let W=`${H}/${i.table}.yaml`;i.layout==="table"?(l.put(W,J(be([...Fe($),["records",O.map(s=>new _(s.entries))]]))),l.ownFile(W),l.own(`${H}/${i.table}`)):(l.put(W,J(be(Fe($)))),l.ownFile(W),O.forEach((s,m)=>l.put(`${H}/${i.table}/${V[m]}.yaml`,J(new _(s.entries)))),l.own(`${H}/${i.table}`)),(S.length||b.length)&&l.own(`${ae}/${i.table}`);let le={table:i.table,file:W,...i.layout==="record"?{layout:"record",folder:`${H}/${i.table}`}:{},records:O.length,added:j,changed:se,removed:a,logged:h,written:!1};return(S.length||b.length)&&(le.files=O.reduce((s,m)=>s+m.binaries.length,0),le.files_changed=0),le}var Wt=Ge(Ue).pattern;function Xt(e,t){return e===null?"":v(e)?t?e.name??"":e.id:ke(e)?e.name??"":xe(e)?"":e instanceof R?e.text:Array.isArray(e)?e.join(","):String(e)}function Jt(e,t,r,n,o){let i=o.form.map(([c,f])=>[c,f]);for(let c of t.columns){let f=r.columns.get(c.name),l=Se(n,f);l===null?i.push([f.name,null]):v(l)?i.push([f.name,e.lookupForm(l,f)]):ke(l)?i.push([f.name,new X([["$file",""],["name",l.name]])]):xe(l)?i.push([f.name,new X([["$file",""]])]):i.push([f.name,ct(l,f)])}return{key:o.key,id:o.id,sort:Be(o.form),form:o.form.map(([c,f])=>[c,f]),entries:i,binaries:[]}}function Qt(e,t){let r=[],n=Mt(e,t.table,r);if(r.length)throw z("data_invalid","a file of the deletion log is not valid; correct it, the export never removes an entry",r);let o=n?.entries??[];return{entries:o,byId:new Map(o.map(i=>[i.id,i]))}}async function vt(e,t,r,n,o,i,c,f,l,p,g){let u=r.relationship(i),$=await r.other(u.intersect);if(!$)throw z("not_found",`the environment has no intersect table '${u.intersect}'`);let S=await e.rows($.entitySet,[["$select",`${u.attr1},${u.attr2}`]],!1),b=r.meta(u.entity1),x=new Set((f.get(u.entity1)??[]).map(y=>String(y[b.primaryId]).toLowerCase())),E=new Map;for(let y of S){let L=String(y[u.attr1]).toLowerCase();if(!x.has(L))continue;let P=E.get(L);P||E.set(L,P=new Set),P.add(String(y[u.attr2]).toLowerCase())}await n.ensure(u.entity2,[...new Set([...E.values()].flatMap(y=>[...y]))]);let T=Ct("from",u.entity1),D=Ct("to",u.entity2),ee=(y,L,P)=>{let N=n.get(y,L);return n.lookupForm({lookup:!0,table:y,id:L,name:N?.name??null},P)},Z=(y,L)=>n.get(y,L)?.key??"g:"+L,M=[...E].map(([y,L])=>{let P=ee(u.entity1,y,T),N=[...L].map(Y=>({form:ee(u.entity2,Y,D),sort:Be([["to",ee(u.entity2,Y,D)]]),key:Z(u.entity2,Y)}));return N.sort((Y,ne)=>Ne(Y.sort,ne.sort)),{from:P,fromKey:Z(u.entity1,y),sort:Be([["from",P]]),to:N}});M.sort((y,L)=>Ne(y.sort,L.sort));let j=`${Ce}/${i.toLowerCase()}.yaml`,se=J(be([["relationship",i],["from",u.entity1],["to",u.entity2],["links",M.map(y=>new _([["from",y.from],["to",y.to.map(L=>L.form)]]))]]));l.put(j,se),l.ownFile(j);let a=new Set(M.flatMap(y=>y.to.map(L=>`${y.fromKey}|${L.key}`))),h=new Map,A=[],te=Ut(Gt(t,j))?Ze(t,i,A):null;if(te&&!A.length)for(let y of te.links)try{let L=await o.lookupKey(T,y.from);for(let P of y.to)h.set(`${L.key}|${(await o.lookupKey(D,P)).key}`,{from:y.from,to:P})}catch{}else A.length&&p.push(`${j}: the file in the folder is not valid; the export writes it again (${A[0]})`);let O=[...h.keys()].filter(y=>!a.has(y)),V=0;if(c){let y=`${Ae}/${i.toLowerCase()}.yaml`,L=[],P=Et(t,i,L);if(L.length)throw z("data_invalid","a file of the deletion log is not valid; correct it, the export never removes an entry",L);let N=P?.entries??[],Y=new Map(N.map(m=>[`g:${m.from}|g:${m.to}`,m])),ne=g.today??Ft(),W=m=>new Set((f.get(m)??[]).map(d=>"g:"+String(d[r.meta(m).primaryId]).toLowerCase())),le=W(u.entity1),s=W(u.entity2);for(let m of O){let[d,w]=m.split("|");if(!le.has(d)||!s.has(w)||Y.has(m))continue;let k={from:d.slice(2),to:w.slice(2),removed:ne};N.push(k),Y.set(m,k),V++}for(let m of Y.keys())a.has(m)&&p.push(`${y}: the link ${m.replace(/g:/g,"")} is in the deletion log and in the source environment again; the log keeps the entry, and the import uses the relationship file and does not remove the link`);N.length&&l.put(y,At(i,u.entity1,u.entity2,N))}return{name:i,file:j,links:a.size,added:[...a].filter(y=>!h.has(y)).length,removed:O.length,logged:V,written:!1}}export{v as a,ke as b,xe as c,Oe as d,Se as e,F as f,on as g,sn as h,an as i,ln as j,Mt as k,Et as l,Me as m,Ee as n,ht as o,xn as p,Yt as q,bt as r,Ct as s,Ne as t,Be as u,Qn as v};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{B as P,D as E,E as k,F as N,H as D,b as $,d as c,f as l,g as b,n as v,t as h,u as S,x,z as I}from"./chunk-BG2OIOSN.js";import{a as q}from"./chunk-UCTMKA2J.js";import{a as T,g as R}from"./chunk-FOEBNCSD.js";import{b as C}from"./chunk-KBZI5UDL.js";import{y as B}from"./chunk-BALEFXOL.js";import{b as M}from"./chunk-2IUXH534.js";import{e as H}from"./chunk-S4KF5Z3S.js";import{a as j,b as w}from"./chunk-WXOTXJNG.js";var J=t=>typeof t=="string"?t:null,L=new RegExp("\\r\\n|[\\n\\r\\x0b\\x0c\\x1c\\x1d\\x1e\\x85\u2028\u2029]");function U(t){let e=t.split(L);return e.length&&e[e.length-1]===""&&e.pop(),e}async function tt(t){let e=t.args,a=T(J(e.entityset),"entity set name"),r=await h(t),o=x(e.formatted?`odata.include-annotations="${$}"`:null),s=v(e);if(e.fetchxml){if(["select","filter","expand","orderby","top","apply","count"].some(u=>c(e[u])))throw new w("--fetchxml can't be combined with OData options");let{run:d}=await import("./fetchxml-M6EOF7N6.js"),y=await d(t,r,a,String(e.fetchxml),!!e.formatted,s);await t.emitStream(y);return}let i=[];for(let[d,y]of[["select","$select"],["filter","$filter"],["expand","$expand"],["orderby","$orderby"],["apply","$apply"]]){let u=e[d];c(u)&&i.push([y,String(u)])}c(e.top)&&i.push(["$top",String(e.top)]),e.count&&i.push(["$count","true"]),M(t,r,"GET",a,null);let[n,m]=await I(t,r,a,i,o,s);if(e.count){let d=l(m,"@odata.count");if(await t.format()==="json"){await t.emit({count:d,value:n});return}H(`count: ${d===null?"None":String(d)}`)}await t.emit(n)}async function et(t){let e=t.args,a=await h(t),r=[];c(e.select)&&r.push(["$select",String(e.select)]),c(e.expand)&&r.push(["$expand",String(e.expand)]);let o=x(e.formatted?`odata.include-annotations="${$}"`:null),s=await S(t,a,"GET",R(String(e.entityset),String(e.key)),{params:r,headers:o});await t.emit(s.json())}async function nt(t){let e=t.args,a=T(J(e.entityset),"entity set name"),r=await k(e.body,!0),o=await h(t),s=e.return&&c(e.select)?[["$select",String(e.select)]]:null,i={...x(e.return?"return=representation":null),...E(t,o)},n=await S(t,o,"POST",a,{params:s,headers:i,body:r});e.return&&n.body.length?await t.emit(n.json()):await t.emit({id:P(n),entity_id:n.header("odata-entityid")})}async function st(t){let e=t.args,a=R(String(e.entityset),String(e.key)),r=await k(e.body,!0),o=await h(t),s={...x(e.return?"return=representation":null),...E(t,o)};c(e.ifMatch)?s["If-Match"]=String(e.ifMatch):e.upsert||(s["If-Match"]="*");let i=await S(t,o,"PATCH",a,{headers:s,body:r});e.return&&i.body.length?await t.emit(i.json()):await t.emit({id:P(i),status:i.status})}async function at(t){let e=t.args,a=R(String(e.entityset),String(e.key)),r=await h(t),o={...c(e.ifMatch)?{"If-Match":String(e.ifMatch)}:{},...E(t,r)},s=await S(t,r,"DELETE",a,{headers:Object.keys(o).length?o:null});await t.emit({deleted:a,status:s.status})}function _(t){return t==null?"None":t===!0?"True":t===!1?"False":typeof t=="string"?t:JSON.stringify(t)}function G(t){let e=N(B(t==="-"?t:"@"+t).toString("utf8")),a=[];if(U(e).forEach((r,o)=>{let s=o+1;if(!r.trim())return;let i;try{i=q(r)}catch(d){throw new w(`line ${s}: not JSON (${d.message})`)}let n=b(i),m=_(n.method??"").toUpperCase();if(!["GET","POST","PATCH","PUT","DELETE"].includes(m)||!c(n.path))throw new w(`line ${s}: needs a method (GET/POST/PATCH/PUT/DELETE) and a path`);if(String(n.path).includes("://"))throw new w(`line ${s}: use a path relative to the Web API, not a full URL`);a.push({method:m,path:n.path,body:l(n,"body"),headers:l(n,"headers")})}),!a.length)throw new w("no requests in the input");return a}async function rt(t){let e=t.args,a=G(String(e.file)),r=await h(t),o=E(t,r);Object.keys(o).length&&(a=a.map(n=>({...n,headers:{...b(n.headers),...o}})));let s=[];for await(let[n,m,d]of D(t,r,a,!!e.changeset,!!e.continueOnError))m.forEach((y,u)=>{let g=d[u],p={index:n+u,method:y.method,path:y.path,status:l(g,"status")},A=b(g.headers);c(A["odata-entityid"])&&(p.entity_id=A["odata-entityid"]);let f=l(g,"body");if(c(g.rolled_back)&&(p.rolled_back=!0),typeof f=="object"&&f!==null&&!Array.isArray(f)&&"error"in f){let O=b(f.error);p.error=C(l(O,"message"))??null,p.code=l(O,"code")}else f!==null&&(p.body=f);c(g.error)&&(p.error=g.error),s.push(p)});await t.emit(s);let i=s.filter(n=>!c(n.status)||n.status>=400);if(i.length)throw new j(`${i.length} of ${s.length} batch requests failed`,{service:"dataverse",hint:"see each result's status and error"})}export{U as a,tt as b,et as c,nt as d,st as e,at as f,G as g,rt as h};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{d as $,e as v,f as s,g as I,h as _,i as D,k as L,l as O,n as z,s as W,t as R,u as f,v as b,w as U,z as M}from"./chunk-BG2OIOSN.js";import{d as G,h as x}from"./chunk-FOEBNCSD.js";import{b as k}from"./chunk-2IUXH534.js";import{e as T}from"./chunk-S4KF5Z3S.js";import{b as N}from"./chunk-WXOTXJNG.js";var Y=new Map([[1,"Entity"],[2,"Attribute"],[9,"OptionSet"],[10,"EntityRelationship"]]),F=new Map([[1,"entity"],[2,"attribute"],[9,"optionset"],[10,"entityrelationship"]]),V=new Map([[20,"role"],[26,"savedquery"],[29,"workflow"],[36,"template"],[60,"systemform"],[61,"webresource"],[62,"sitemap"],[63,"connectionrole"],[66,"customcontrol"],[70,"fieldsecurityprofile"],[80,"appmodule"],[91,"pluginassembly"],[92,"sdkmessageprocessingstep"],[95,"serviceendpoint"],[300,"canvasapp"],[380,"environmentvariabledefinition"],[381,"environmentvariablevalue"]]),Q=new Map([[1,"table"],[2,"column"],[3,"relationship"],[9,"choice"],[10,"relationship"],[20,"role"],[26,"view"],[29,"process"],[31,"report"],[36,"email-template"],[50,"ribbon"],[59,"chart"],[60,"form"],[61,"webresource"],[62,"sitemap"],[66,"custom-control"],[80,"app"],[91,"assembly"],[92,"step"],[300,"canvas-app"],[380,"envvar"],[381,"envvar-value"]]),J=new Map([[0,"none"],[1,"solution-internal"],[2,"published"],[4,"unpublished"]]),X=new Map([[61,["webresourceset","webresourceid",["name","displayname","content","description"]]],[60,["systemforms","formid",["name","formxml","description"]]],[26,["savedqueries","savedqueryid",["name","fetchxml","layoutxml","description"]]],[80,["appmodules","appmoduleid",["name","descriptor","description"]]]]),P=new Map,q=new Map;async function E(e,n){let{componentId:t,componentType:a}=await import("./lifecycle-2F7MF6EP.js"),o=e.args,c=await a(e,n,String(o.type));return[c,await t(e,n,c,String(o.component),String(o.type))]}async function Z(e,n,t){let a=Y.get(t);if(a)return a;let o=await A(e,n,t);if(!o)throw new N(`component type ${t} has no layers ppdo-cli can read`);let c=b(await f(e,n,"GET",`EntityDefinitions(LogicalName='${o}')`,{params:[["$select","SchemaName"]]}));return v(s(c,"SchemaName"),o)}async function A(e,n,t){let a=V.get(t);if(a)return a;if(t<1e4)return null;if(!q.has(t)){let o=_(b(await f(e,n,"GET","EntityDefinitions",{params:[["$select","LogicalName"],["$filter",`ObjectTypeCode eq ${t}`]]})).value);q.set(t,o.length?o[0].LogicalName:null)}return q.get(t)??null}async function ee(e,n,t){if(!t)return null;if(!P.has(t)){let a=b(await f(e,n,"GET",`EntityDefinitions(LogicalName='${t}')`,{params:[["$select","EntitySetName,PrimaryNameAttribute"]]})),o=s(a,"EntitySetName"),c=s(a,"PrimaryNameAttribute");P.set(t,$(o)&&$(c)?[o,c]:null)}return P.get(t)??null}async function C(e,n,t){return Q.get(t)||await A(e,n,t)||String(t)}var ne=new Set(["componentstate","overwritetime","solutionid","supportingsolutionid","versionnumber","ismanaged","componentidunique","modifiedon","modifiedby","createdon","createdby","organizationid"]);function te(e,n){let t;try{t=_(s(I(JSON.parse(e||"{}")),"Attributes"))}catch{return null}let a={};for(let o of t){let c=s(o,"Key");if(!$(c))continue;let l=String(c).toLowerCase();ne.has(l)||l.endsWith("idunique")||(a[c]=s(o,"Value"))}return n?a:L(Object.keys(a),o=>o)}async function re(e){let n=await R(e);k(e,n,"GET","msdyn_componentlayers",null);let[t,a]=await E(e,n),o=await Z(e,n,t),[c]=await M(e,n,"msdyn_componentlayers",[["$select","msdyn_order,msdyn_solutionname,msdyn_publishername,msdyn_overwritetime,msdyn_changes"],["$filter",`msdyn_componentid eq '${a}' and msdyn_solutioncomponentname eq '${o}'`]],null,null);c.length||T(`no layers for ${await C(e,n,t)} ${a}: check the type and id`);let l=!!e.args.values,p=[];L(c,i=>v(s(i,"msdyn_order"),0)).forEach((i,r)=>{let u=s(i,"msdyn_overwritetime"),m=te(s(i,"msdyn_changes"),l),g={order:s(i,"msdyn_order"),solution:s(i,"msdyn_solutionname"),publisher:s(i,"msdyn_publishername"),updated:String(u||"").startsWith("1900-")?null:u};r===0&&!l?g.base=`${(Array.isArray(m)?m:[]).length} properties`:g.changes=m,p.push(D(g))}),await e.emit(p)}async function oe(e,n,t){let{find:a}=await import("./solution-CNBNIS7Z.js"),o=new Map,c=(await a(e,n,"Default")).solutionid,l=O(t.map(([,i])=>i));for(let i=0;i<l.length;i+=25){let r=l.slice(i,i+25).map(m=>`msdyn_objectid eq '${m}'`).join(" or "),[u]=await M(e,n,"msdyn_solutioncomponentsummaries",[["$select","msdyn_objectid,msdyn_name,msdyn_displayname"],["$filter",`msdyn_solutionid eq ${c} and (${r})`]],null,null);for(let m of u)o.set(String(m.msdyn_objectid).toLowerCase(),v(s(m,"msdyn_name"),s(m,"msdyn_displayname")))}let p=async(i,r)=>b(await f(e,n,"GET",i,{params:[["$select",r]]}));for(let[i,r,u]of t){if(r===null)continue;let m=r.toLowerCase();if(!o.has(m))try{if(i===1)o.set(m,s(await p(`EntityDefinitions(${r})`,"LogicalName"),"LogicalName"));else if(i===3||i===10)o.set(m,s(await p(`RelationshipDefinitions(${r})`,"SchemaName"),"SchemaName"));else if(i===2&&u&&!u.startsWith("00000000")){let g=s(await p(`EntityDefinitions(${u})`,"LogicalName"),"LogicalName"),y=s(await p(`EntityDefinitions(${u})/Attributes(${r})`,"LogicalName"),"LogicalName");o.set(m,`${g??"None"}.${y??"None"}`)}else if(i!==null){let g=await ee(e,n,await A(e,n,i));if(g){let[y,w]=g;o.set(m,s(await p(`${y}(${G(r)})`,w),w))}}}catch{continue}}return o}async function le(e){let n=e.args;W(n,{dependents:"--dependents",blockingDelete:"--blocking-delete"},!1,"dv component dependencies");let t=await R(e),[a,o]=await E(e,t),c=n.dependents?"RetrieveDependentComponents":n.blockingDelete?"RetrieveDependenciesForDelete":"RetrieveRequiredComponents",[l,p]=x(c,[["ObjectId",o],["ComponentType",String(a)]]),i=_(b(await f(e,t,"GET",l,{params:p})).value),r=c==="RetrieveRequiredComponents"?"required":"dependent",u=z(n);u!==null&&(i=i.slice(0,u)),u!==null&&i.length===u&&T(`showing the first ${u} dependencies; pass --limit n or --all for more`);let m=i.map(d=>[s(d,`${r}componenttype`),s(d,`${r}componentobjectid`),s(d,`${r}componentparentid`)]),g=i.length?await oe(e,t,m):new Map,y=new Map;if(i.length){let[d]=await M(e,t,"solutions",[["$select","solutionid,uniquename"]],null,null);for(let h of d)y.set(String(h.solutionid).toLowerCase(),h.uniquename)}let w=[];for(let d=0;d<i.length;d++){let h=i[d],[j,B]=m[d],H=String(v(s(h,`${r}componentbasesolutionid`),"")).toLowerCase(),S=s(h,"dependencytype"),K={type:j===null?"None":await C(e,t,j),name:g.get(String(B||"").toLowerCase())??null,id:B,dependency:typeof S=="number"&&J.has(S)?J.get(S):S,solution:y.get(H)??null};w.push(D(K))}w=L(w,d=>[String(d.type),String(v(s(d,"name"),"")).toLowerCase()]),await e.emit(w)}async function ue(e){let n=await R(e),[t,a]=await E(e,n),[o,c]=x("IsComponentCustomizable",[["ComponentId",a],["ComponentType",String(t)]]),l=b(await f(e,n,"GET",o,{params:c}));await e.emit({type:await C(e,n,t),id:a,customizable:s(l,"IsComponentCustomizable")})}async function de(e){let n=await R(e),[t,a]=await E(e,n),o=X.get(t);if(!o)throw new N("unpublished works for forms, views, web resources and apps",{hint:"Dataverse's RetrieveUnpublished doesn't support other types (site maps included)"});let[c,,l]=o,p=l.join(","),i=b(await f(e,n,"GET",`${c}(${a})`,{params:[["$select",p]]})),r=b(await f(e,n,"GET",`${c}(${a})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`,{params:[["$select",p]]})),u=(y,w)=>{let d=v(y,null),h=v(w,null);return typeof d=="object"||typeof h=="object"?JSON.stringify(d)===JSON.stringify(h):d===h},m=l.filter(y=>!u(s(i,y),s(r,y))),g={type:await C(e,n,t),id:a,name:v(s(r,"name"),s(i,"name")),pending:m.length>0,changed:m};if(e.args.show&&m.length){let y={};for(let w of m)y[w]=s(r,w);g.unpublished=y}await e.emit(g)}async function pe(e){let n=await R(e);k(e,n,"POST","RemoveActiveCustomization",Buffer.from("{}"));let[t,a,o]=await n.lookups(async()=>{let[l,p]=await E(e,n);return[l,p,F.get(l)||await A(e,n,l)]});if(!o)throw new N(`component type ${t} isn't supported here`);let c=b(await f(e,n,"POST","RemoveActiveCustomization",{body:U({LogicalName:o,Id:a})}));await e.emit({type:await C(e,n,t),id:a,removed:$(s(c,"Success"))})}export{Y as a,F as b,V as c,Q as d,J as e,X as f,Z as g,A as h,ee as i,C as j,te as k,re as l,le as m,ue as n,de as o,pe as p};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
- var _="1.0.0-beta.1";export{_ as a};
2
+ var _="1.0.0-beta.2";export{_ as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{d as z}from"./chunk-T4IH34D7.js";import{C as ne,G as C,H as oe,d as q,e as K,f as r,g as D,h as R,k as B,l as G,t as Q,u as X,v as ee,z as te}from"./chunk-BG2OIOSN.js";import{a as V}from"./chunk-UCTMKA2J.js";import{b as W,d as Z}from"./chunk-FOEBNCSD.js";import{b as Y}from"./chunk-2IUXH534.js";import{e as T}from"./chunk-S4KF5Z3S.js";import{b as A}from"./chunk-WXOTXJNG.js";import{readFileSync as U}from"node:fs";import{gunzipSync as le}from"node:zlib";var ue=["resolved","not-found","type-unsupported"],ce=new Map([[3,"relationship-internal"],[4,"choice-value"],[5,"lookup-value"],[6,"view-column"],[7,"label"],[8,"relationship-condition"],[11,"relationship-role"],[12,"relationship-role-link"],[14,"key"],[46,"table-map"],[47,"column-map"],[48,"ribbon-command"],[49,"ribbon-context-group"],[50,"ribbon-customization"],[52,"ribbon-rule"],[53,"ribbon-tab-command-map"],[55,"ribbon-diff"],[68,"custom-control-default"],[88,"app-role"],[90,"plugin-type"],[93,"step-image"]]),ae=500,pe=new Map([[20,["role","name",null]],[26,["savedquery","name","returnedtypecode"]],[29,["workflow","uniquename|name","primaryentity"]],[36,["template","title","templatetypecode"]],[48,["ribboncommand","command","entity"]],[49,["ribboncontextgroup","contextgroupid","entity"]],[50,["ribboncustomization","entity","entity"]],[52,["ribbonrule","ruleid","entity"]],[53,["ribbontabtocommandmap","controlid","entity"]],[55,["ribbondiff","diffid","entity"]],[59,["savedqueryvisualization","name","primaryentitytypecode"]],[60,["systemform","name","objecttypecode"]],[61,["webresource","name",null]],[62,["sitemap","sitemapnameunique|sitemapname",null]],[63,["connectionrole","name",null]],[66,["customcontrol","name",null]],[70,["fieldsecurityprofile","name",null]],[80,["appmodule","uniquename|name",null]],[90,["plugintype","typename",null]],[91,["pluginassembly","name",null]],[92,["sdkmessageprocessingstep","name",null]],[93,["sdkmessageprocessingstepimage","name",null]],[95,["serviceendpoint","name",null]],[300,["canvasapp","name",null]],[380,["environmentvariabledefinition","schemaname",null]],[381,["environmentvariablevalue","schemaname",null]]]),se=["PicklistAttributeMetadata","MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata","BooleanAttributeMetadata"],fe="00000000-0000-0000-0000-000000000000";function ie(t){if(typeof t!="string"||!W(t))return null;let o=Z(t);return o===fe?null:o}function I(t){if(t==null)return"None";if(t===!0)return"True";if(t===!1)return"False";if(typeof t=="number")return String(t);if(typeof t=="string"){let o=t.includes("'")&&!t.includes('"')?'"':"'",s=t.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");return o==="'"&&(s=s.replace(/'/g,"\\'")),o+s+o}return Array.isArray(t)?"["+t.map(I).join(", ")+"]":"{"+Object.entries(t).map(([o,s])=>`${I(o)}: ${I(s)}`).join(", ")+"}"}var L=(t,o)=>`${t}|${o}`;function de(t){let o=new Map,s=(u,i,p=null)=>{let f=ie(i);if(typeof u!="number"||!Number.isInteger(u)||f===null)throw new A(`not a component (type, id): ${I(u)}, ${I(i)}`);let b=L(u,f),y=o.get(b);o.set(b,{key:[u,f],parent:y?.parent||ie(p)})},c=0;for(let u of t){if(c++,!u.trim())continue;let i;try{i=V(u)}catch(p){throw new A(`line ${c} is not JSON: ${p.message}`)}if("requiredcomponentobjectid"in i||"dependentcomponentobjectid"in i)for(let p of["required","dependent"])s(r(i,p+"componenttype"),r(i,p+"componentobjectid"),r(i,p+"componentparentid"));else"componenttype"in i?s(r(i,"componenttype"),r(i,"objectid")):s(r(i,"type"),r(i,"id"),r(i,"parent_id"))}return o}function re(t){return ne(t)}function ge(t,o){for(let s of o.split("|"))if(q(r(t,s)))return t[s];return null}var ye=["type","id","type_name","name_status","name","logical_name","schema_name","parent_type","parent_id","parent_logical_name","parent_schema_name","source"];function w(t,o,s,c={}){let u={};for(let i of ye)u[i]=null;Object.assign(u,{type:t,id:o,type_name:z.get(t)??ce.get(t)??null,name_status:s});for(let[i,p]of Object.entries(c))i in u&&(u[i]=p===void 0?null:p);return u}var F=class{constructor(o,s){this.rt=o;this.client=s}tablesCache=null;async get(o,s){return ee(await X(this.rt,this.client,"GET",o,{params:s}))}async all(o,s){return(await te(this.rt,this.client,o,s,null,null))[0]}async tables(){if(this.tablesCache===null){let o=await this.get("EntityDefinitions",[["$select","MetadataId,LogicalName,SchemaName,DisplayName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute,ObjectTypeCode"]]);this.tablesCache=new Map(R(o.value).map(s=>[String(s.MetadataId).toLowerCase(),s]))}return this.tablesCache}async tableByName(o){if(!q(o))return null;for(let s of(await this.tables()).values())if(s.LogicalName===o)return s;return null}async batch(o){let s=[],c=o.map(u=>({method:"GET",path:u}));for await(let[,,u]of oe(this.rt,this.client,c,!1,!0))s.push(...u);return s}};async function we(t,o,s){let c=new F(t,o),u=new Map,i=(e,n,a)=>{u.set(L(e,n),{key:[e,n],row:a})},p=new Map;for(let{key:e}of s.values()){let[n,a]=e;p.has(n)||p.set(n,[]),p.get(n).push(a)}let f=e=>p.get(e)??[],b=(e,n)=>s.get(L(e,n))?.parent??null,y=await c.tables(),S=async e=>{let n=await c.tableByName(e);return{parent_type:1,parent_id:n?n.MetadataId:null,parent_logical_name:e,parent_schema_name:n?n.SchemaName:null}};for(let e of f(1)){let n=y.get(e);i(1,e,n?w(1,e,"resolved",{name:re(r(n,"DisplayName")),logical_name:n.LogicalName,schema_name:n.SchemaName,source:"EntityDefinitions"}):w(1,e,"not-found",{source:"EntityDefinitions"}))}let h=new Map,$=B(G(f(2).map(e=>b(2,e)).filter(e=>e!==null&&y.has(e))),e=>e),x=await c.batch($.map(e=>`EntityDefinitions(${e})/Attributes?$select=MetadataId,LogicalName,SchemaName,DisplayName`));if($.forEach((e,n)=>{let a=x[n];if(a)for(let m of R(r(D(r(a,"body")),"value")))h.set(String(m.MetadataId).toLowerCase(),[m,y.get(e)])}),f(2).some(e=>!h.has(e))){let e=await c.get("EntityDefinitions",[["$select","MetadataId"],["$expand","Attributes($select=MetadataId,LogicalName,SchemaName,DisplayName)"]]);for(let n of R(e.value))for(let a of R(r(n,"Attributes"))){let m=String(a.MetadataId).toLowerCase();h.has(m)||h.set(m,[a,y.get(String(n.MetadataId).toLowerCase())??{}])}}for(let e of f(2)){let n=h.get(e);if(n){let[a,m]=n;i(2,e,w(2,e,"resolved",{name:re(r(a,"DisplayName")),logical_name:a.LogicalName,schema_name:a.SchemaName,parent_type:1,parent_id:r(m,"MetadataId"),parent_logical_name:r(m,"LogicalName"),parent_schema_name:r(m,"SchemaName"),source:"Attributes"}))}else i(2,e,w(2,e,"not-found",{source:"Attributes"}))}let me=[...f(10),...f(3)],H=new Map;if(me.length){let e=await c.get("RelationshipDefinitions",[["$select","MetadataId,SchemaName"]]);for(let n of R(e.value))H.set(String(n.MetadataId).toLowerCase(),n)}for(let e of[10,3])for(let n of f(e)){let a=H.get(n);i(e,n,a?w(e,n,"resolved",{name:a.SchemaName,schema_name:a.SchemaName,source:"RelationshipDefinitions"}):w(e,n,e===10?"not-found":"type-unsupported",{source:"RelationshipDefinitions"}))}if(f(14).length){let e=new Map,n=await c.get("EntityDefinitions",[["$select","MetadataId"],["$expand","Keys($select=MetadataId,LogicalName,SchemaName)"]]);for(let a of R(n.value))for(let m of R(r(a,"Keys")))e.set(String(m.MetadataId).toLowerCase(),[m,y.get(String(a.MetadataId).toLowerCase())??{}]);for(let a of f(14)){let m=e.get(a);if(m){let[_,N]=m;i(14,a,w(14,a,"resolved",{name:_.SchemaName,logical_name:_.LogicalName,schema_name:_.SchemaName,parent_type:1,parent_id:r(N,"MetadataId"),parent_logical_name:r(N,"LogicalName"),parent_schema_name:r(N,"SchemaName"),source:"Keys"}))}else i(14,a,w(14,a,"not-found",{source:"Keys"}))}}if(f(9).length){let e=new Map,n=await c.get("GlobalOptionSetDefinitions",[["$select","MetadataId,Name"]]);for(let l of R(n.value))e.set(String(l.MetadataId).toLowerCase(),l);let a=new Set;for(let l of f(9)){let g=e.get(l);g?i(9,l,w(9,l,"resolved",{name:g.Name,schema_name:g.Name,source:"GlobalOptionSetDefinitions"})):a.add(l)}let m=new Set;for(let{key:l,parent:g}of s.values())l[0]===2&&g&&m.add(g);for(let l of f(1))m.add(l);let _=[...y.keys()],N=[_.filter(l=>m.has(l)),_.filter(l=>!m.has(l))];for(let l=0;l<N.length;l++){let g=N[l];if(!a.size||!g.length)continue;l===1&&T(`looking for ${a.size} local choice(s) in the choice columns of every other table`);let j=g.flatMap(d=>se.map(k=>`EntityDefinitions(${d})/Attributes/Microsoft.Dynamics.CRM.${k}?$select=MetadataId,LogicalName,SchemaName&$expand=OptionSet($select=MetadataId,Name,IsGlobal)`));(await c.batch(j)).forEach((d,k)=>{let M=y.get(g[Math.floor(k/se.length)]);for(let v of R(r(D(r(d,"body")),"value"))){let P=D(r(v,"OptionSet")),E=String(K(r(P,"MetadataId"),"")).toLowerCase();a.has(E)&&(a.delete(E),i(9,E,w(9,E,"resolved",{name:r(P,"Name"),schema_name:r(P,"Name"),parent_type:2,parent_id:v.MetadataId,parent_logical_name:`${M.LogicalName}.${v.LogicalName}`,parent_schema_name:`${M.SchemaName}.${v.SchemaName}`,source:"Attributes/OptionSet"})))}})}for(let l of a)i(9,l,w(9,l,"not-found",{source:"GlobalOptionSetDefinitions"}))}let J=new Map;for(let e of y.values())J.set(r(e,"ObjectTypeCode"),e);for(let[e,n]of p){if([1,2,3,9,10,14].includes(e))continue;let a=pe.get(e),m=a?await c.tableByName(a[0]):e>=1e4?J.get(e)??null:null;if(!m){for(let d of n)i(e,d,w(e,d,"type-unsupported"));continue}let _=m.EntitySetName,N=m.PrimaryIdAttribute,l=a?a[1]:K(r(m,"PrimaryNameAttribute"),N),g=a?a[2]:null,j=G([N,...l.split("|"),...g?[g]:[]]).join(","),O=new Map;for(let d=0;d<n.length;d+=ae){let k=n.slice(d,d+ae).map(M=>`'${M}'`).join(",");for(let M of await c.all(_,[["$select",j],["$filter",`Microsoft.Dynamics.CRM.In(PropertyName='${N}',PropertyValues=[${k}])`]]))O.set(String(M[N]).toLowerCase(),M)}for(let d of n){let k=O.get(d);if(!k){i(e,d,w(e,d,"not-found",{source:_}));continue}let M=g?r(k,g):null,v=g&&M!==null&&M!=="none"?await S(M):{};i(e,d,w(e,d,"resolved",{name:ge(k,l),source:_,type_name:z.get(e)||ce.get(e)||m.LogicalName,...v}))}}return B([...u.values()],e=>[e.key[0],e.key[1]]).map(e=>e.row)}function be(t){let o;t==="-"?o=U(0,"utf8"):t.toLowerCase().endsWith(".gz")?o=le(U(t)).toString("utf8"):o=U(t,"utf8");let s="\\n\\r\\x0b\\x0c\\x1c\\x1d\\x1e\\x85\u2028\u2029",c=o.split(new RegExp(`\\r\\n|[${s}]`));return c.length&&c[c.length-1]===""&&c.pop(),c}async function xe(t){let o=t.args,s=C(o.file),c=C(o.type),u=C(o.component);if(!s&&!(c&&u))throw new A("give <type> <component>, or --file with components to name");let i=await Q(t);Y(t,i,"GET","EntityDefinitions",null);let p=new Map;if(s)for(let[S,h]of de(be(s)))p.set(S,h);if(c&&u){let{componentId:S,componentType:h}=await import("./lifecycle-2F7MF6EP.js"),$=await h(t,i,c),x=await S(t,i,$,u,c);p.has(L($,x))||p.set(L($,x),{key:[$,x],parent:null})}let f=await we(t,i,p),b={};for(let S of ue)b[S]=f.filter(h=>h.name_status===S).length;let y=C(o.save);if(y){let{save:S}=await import("./dependency-V4ZJIWQL.js");await S(y,f),await t.emit({saved:y,components:f.length,...b})}else await t.emit(f);(b["not-found"]||b["type-unsupported"])&&T(`${b["not-found"]} not found, ${b["type-unsupported"]} of a type ppdo-cli can't name`)}export{ue as a,ce as b,ae as c,pe as d,I as e,de as f,re as g,ge as h,w as i,we as j,be as k,xe as l};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
- import{a as G}from"./chunk-MK6QZ4ES.js";import{a as L,c as H,d as U,h as E}from"./chunk-MBNUMAAZ.js";import{a as O}from"./chunk-4KP27OCL.js";import{f as D,g as M}from"./chunk-H4OY4EFC.js";import{e as b}from"./chunk-S4KF5Z3S.js";import{a as y,b as v,c as g}from"./chunk-WXOTXJNG.js";import{spawn as fe}from"node:child_process";import{randomBytes as P}from"node:crypto";import xe from"node:http";var w=class extends Error{},k=null;function q(){let e=k;return k=null,e}function j(e){return k=new w(e)}var I=class{constructor(t=60){this.timeout=t}async send(t,n,r,i){let s={...r?.headers??{}},a=null;t==="POST"&&(a=Buffer.from(r?.body??"","utf8"),Object.keys(s).some(p=>p.toLowerCase()==="content-type")||(s["Content-Type"]="application/x-www-form-urlencoded")),k=null;let o;try{o=await O().request(t,n,s,a,{timeout:i?i/1e3:this.timeout})}catch(p){throw j(p.message)}let d;try{d=o.body.length?JSON.parse(o.text):{}}catch{throw j(`HTTP ${o.status}: ${o.text.slice(0,200)}`)}return{headers:{...o.headers},body:d,status:o.status}}sendGetRequestAsync(t,n,r){return this.send("GET",t,n,r)}sendPostRequestAsync(t,n){return this.send("POST",t,n)}};var Y=["#1F8FFF","#4EBFF4","#33C173","#F8AE30","#8B9BB4","#E1E7EF"];function W(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return Y[(t>>>0)%Y.length]}function ce(e){if(!e)return"data:,";let t=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="7" fill="${W(e)}"/></svg>`;return`data:image/svg+xml,${encodeURIComponent(t)}`}function F(e){return{"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":`default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'${e?`; script-src 'nonce-${e}'`:""}`,"x-content-type-options":"nosniff","x-frame-options":"DENY","referrer-policy":"no-referrer"}}var J=F();function c(e){return e.replace(/[&<>"']/g,t=>`&#${t.charCodeAt(0)};`)}var de=`<svg class="mark" viewBox="0 0 96 96" aria-hidden="true">
2
+ import{a as G}from"./chunk-P4IFCLVF.js";import{a as L,c as H,d as U,h as E}from"./chunk-MBNUMAAZ.js";import{a as O}from"./chunk-GY6BUIDP.js";import{f as D,g as M}from"./chunk-H4OY4EFC.js";import{e as b}from"./chunk-S4KF5Z3S.js";import{a as y,b as v,c as g}from"./chunk-WXOTXJNG.js";import{spawn as fe}from"node:child_process";import{randomBytes as P}from"node:crypto";import xe from"node:http";var w=class extends Error{},k=null;function q(){let e=k;return k=null,e}function j(e){return k=new w(e)}var I=class{constructor(t=60){this.timeout=t}async send(t,n,r,i){let s={...r?.headers??{}},a=null;t==="POST"&&(a=Buffer.from(r?.body??"","utf8"),Object.keys(s).some(p=>p.toLowerCase()==="content-type")||(s["Content-Type"]="application/x-www-form-urlencoded")),k=null;let o;try{o=await O().request(t,n,s,a,{timeout:i?i/1e3:this.timeout})}catch(p){throw j(p.message)}let d;try{d=o.body.length?JSON.parse(o.text):{}}catch{throw j(`HTTP ${o.status}: ${o.text.slice(0,200)}`)}return{headers:{...o.headers},body:d,status:o.status}}sendGetRequestAsync(t,n,r){return this.send("GET",t,n,r)}sendPostRequestAsync(t,n){return this.send("POST",t,n)}};var Y=["#1F8FFF","#4EBFF4","#33C173","#F8AE30","#8B9BB4","#E1E7EF"];function W(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return Y[(t>>>0)%Y.length]}function ce(e){if(!e)return"data:,";let t=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="7" fill="${W(e)}"/></svg>`;return`data:image/svg+xml,${encodeURIComponent(t)}`}function F(e){return{"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":`default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'${e?`; script-src 'nonce-${e}'`:""}`,"x-content-type-options":"nosniff","x-frame-options":"DENY","referrer-policy":"no-referrer"}}var J=F();function c(e){return e.replace(/[&<>"']/g,t=>`&#${t.charCodeAt(0)};`)}var de=`<svg class="mark" viewBox="0 0 96 96" aria-hidden="true">
3
3
  <defs>
4
4
  <linearGradient id="mf" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#1F8FFF" stop-opacity="0.34"/><stop offset="1" stop-color="#1F8FFF" stop-opacity="0.12"/></linearGradient>
5
5
  <linearGradient id="ms" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#4EBFF4" stop-opacity="0.85"/><stop offset="1" stop-color="#1F8FFF" stop-opacity="0.25"/></linearGradient>
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
- import{r as o}from"./chunk-BALEFXOL.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";function r(m){o(m,"commands","L","list every command with its class (R/W/D/M/L)").argument("[group]","only this command group, e.g. dv or ado").argKey("group","only").option("--json","same as -o json (the default)").handler(async a=>(await import("./run-H2OLE76P.js")).commands(a))}export{r as register};
2
+ import{r as o}from"./chunk-BALEFXOL.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";function r(m){o(m,"commands","L","list every command with its class (R/W/D/M/L)").argument("[group]","only this command group, e.g. dv or ado").argKey("group","only").option("--json","same as -o json (the default)").handler(async a=>(await import("./run-JDNEQMJC.js")).commands(a))}export{r as register};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-T4IH34D7.js";import"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import"./chunk-FOEBNCSD.js";import"./chunk-BALEFXOL.js";import"./chunk-J4R6QXW7.js";import"./chunk-2IUXH534.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";export{e as DEPENDENCY_TYPES,d as LABELS,b as METADATA_LOGICAL,a as METADATA_NAMES,c as TABLES,f as UNPUBLISHED,k as changes,n as customizable,m as dependencies,j as label,g as layerName,l as layers,p as removeActive,i as tableMeta,h as tableName,o as unpublished};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
- import{A,B,C,D,E,F,G,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-STWQDANK.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";export{s as Config,k as DEFAULT_CLIENT_ID,m as ENV_NAME_RE,h as ENV_VARS,q as Environment,p as Group,o as Identity,g as LABELS,b as METHODS,c as MODES,a as NAME_RE,l as ORG_RE,i as PIN_FILE,d as RANK,x as Resolved,j as SECRET_ENV,e as SERVICES,f as SERVICE_ALIASES,B as appIdentity,A as appRequested,n as checkName,C as devopsUrlScope,v as findPin,w as gitRoot,t as grants,y as isUrl,G as normaliseDataverseUrl,r as readJsonFile,E as resolveApp,z as resolveEnv,F as resolveIdentity,D as urlEnvironment,u as widening};
2
+ import{A,B,C,D,E,F,G,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-3L7657R3.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";export{s as Config,k as DEFAULT_CLIENT_ID,m as ENV_NAME_RE,h as ENV_VARS,q as Environment,p as Group,o as Identity,g as LABELS,b as METHODS,c as MODES,a as NAME_RE,l as ORG_RE,i as PIN_FILE,d as RANK,x as Resolved,j as SECRET_ENV,e as SERVICES,f as SERVICE_ALIASES,B as appIdentity,A as appRequested,n as checkName,C as devopsUrlScope,v as findPin,w as gitRoot,t as grants,y as isUrl,G as normaliseDataverseUrl,r as readJsonFile,E as resolveApp,z as resolveEnv,F as resolveIdentity,D as urlEnvironment,u as widening};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{G as L,d as j,e as h,f as s,g as u,h as v,i as N,k as P,n as O,t as _,u as M,v as D,z as G}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import"./chunk-FOEBNCSD.js";import"./chunk-BALEFXOL.js";import{b as T,c as $,d as b}from"./chunk-GY6BUIDP.js";import{c as I,g as q}from"./chunk-J4R6QXW7.js";import{b as E}from"./chunk-2IUXH534.js";import"./chunk-TCLZ4XM6.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import{e as A}from"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var z="api.powerapps.com",J="2016-11-01";function B(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var R=class extends T{name="powerapps";scope(){return"https://service.powerapps.com//.default"}url(e,t){let r=e.includes("://")?e:`https://${z}/${e.replace(/^\/+/,"")}`,a=[...t??[]];return!r.includes("api-version=")&&!a.some(([c])=>c==="api-version")&&a.push(["api-version",J]),a.length&&(r+=(r.includes("?")?"&":"?")+I(a,"$'(),/:@*")),r}allowed(e){let t=q(e);return t.scheme==="https"&&t.host===z}requestId(e){return e.header("x-ms-request-id")||e.header("x-ms-correlation-request-id")}error(e){let t=null,r=null;try{let a=e.json(),c=B(a)&&B(a.error)?a.error:{};t=typeof c.code=="string"?c.code:null,r=typeof c.message=="string"?c.message:null}catch{r=e.text.trim().slice(0,300)||null}return $(this.name,e,t,r,this.requestId(e))}};async function F(n,e){let t=new R,r=e.identity;if(!r)throw new Error("the Dataverse client has no identity");let{getToken:a}=await import("./provider-D7DMMAS6.js"),c=new b(t,n,d=>a(r,t.scope(),{forceRefresh:d,log:p=>n.log(p)}));return c.target=e.target,c.identity=r,c}function K(n){let e=n.trim(),t=e.slice(e.lastIndexOf("/")+1);return t.startsWith("shared_")?t:"shared_"+t}async function re(n){let e=n.args,t=await _(n),r=D(await M(n,t,"GET","RetrieveCurrentOrganization(AccessType=Microsoft.Dynamics.CRM.EndpointAccessType'Default')")),c=u(r.Detail).EnvironmentId,[d]=await G(n,t,"connectionreferences",[["$select","connectionreferencelogicalname,connectionid"],["$filter","connectionid ne null"]],null,null),p=new Map;for(let o of d){let i=String(o.connectionid).toLowerCase();p.has(i)||p.set(i,[]),p.get(i).push(o.connectionreferencelogicalname)}let f=await F(n,t),C=L(e.connector),x=C?`providers/Microsoft.PowerApps/apis/${K(C)}/connections`:"providers/Microsoft.PowerApps/connections";E(n,f,"GET",x,null);let H=[["$filter",`environment eq '${c}'`]],g=[],S=await f.request("GET",x,{params:H});for(;;){let o=u(S.json());g=g.concat(v(o.value));let i=o.nextLink;if(!i)break;S=await f.request("GET",String(i))}let l=[];for(let o of g){let i=u(s(o,"properties")),V=v(i.statuses).map(w=>s(w,"status")).filter(w=>j(w)),y=u(i.createdBy),k=s(i,"apiId")||"",W={id:s(o,"name"),connector:k.slice(k.lastIndexOf("/")+1)||null,display_name:s(i,"displayName"),status:V.join(", ")||null,account:s(i,"accountName"),created_by:h(h(s(y,"userPrincipalName"),s(y,"email")),s(y,"displayName")),created:s(i,"createdTime"),references:p.get(String(s(o,"name")||"").toLowerCase())??[]};l.push(N(W))}e.unused&&(l=l.filter(o=>!o.references.length)),l=P(l,o=>[String(s(o,"connector")||""),String(s(o,"display_name")||"").toLowerCase()]);let m=O(e);m!==null&&l.length>m&&(A(`showing the first ${m} connections; pass --limit n or --all for more`),l=l.slice(0,m)),await n.emit(l)}export{K as connectorName,re as list};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{d as P,e as T,f as k}from"./chunk-Q2RD4TRK.js";import"./chunk-ITP35SAY.js";import"./chunk-ZUXLC5VX.js";import{A as L,G as w,f as s,h as x,n as _,t as l,u as g,v as j,w as E}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import{b as v,d as R,e as $,f as C,i as b}from"./chunk-FOEBNCSD.js";import"./chunk-BALEFXOL.js";import"./chunk-J4R6QXW7.js";import{b as p}from"./chunk-2IUXH534.js";import"./chunk-S4KF5Z3S.js";import{a as y,b as u,d as m}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var I="connectionreferencelogicalname,connectionreferencedisplayname,connectorid,connectionid,_customconnectorid_value,ismanaged,statecode,description,modifiedon";function q(n){return n.slice(n.lastIndexOf("/")+1)}function d(n,o=!1){let e=s(n,"connectorid")||"",t={name:s(n,"connectionreferencelogicalname"),display_name:s(n,"connectionreferencedisplayname"),connector:q(e)||null,connection:s(n,"connectionid"),managed:s(n,"ismanaged"),id:s(n,"connectionreferenceid")};if(o){Object.assign(t,{connector_id:e||null,custom_connector_id:s(n,"_customconnectorid_value"),description:s(n,"description"),active:s(n,"statecode")===0,modified:s(n,"modifiedon")});let i={};for(let[c,r]of Object.entries(t))(r!==null||c==="connection")&&(i[c]=r);t=i}return t}async function h(n,o,e){let t=v(e),i=t?"connectionreferenceid":"connectionreferencelogicalname",c=t?R(e):$(e),r=await g(n,o,"GET","connectionreferences",{params:[["$select",I],["$filter",`${i} eq ${c}`]]}),a=x(j(r).value);if(!a.length)throw new m(`no connection reference '${e}'`,{service:"dataverse",hint:"run: ppdo-cli dv connref list --name '*<part of the name>*'"});return a[0]}async function U(n){let o=n.args,e=await l(n);p(n,e,"GET","connectionreferences",null);let t=null,i=w(o.solution);i&&(t=await k(n,e,P(i),await T(n,e,"connectionreference")));let c=[],r=w(o.name);r&&c.push(b("connectionreferencelogicalname",r)),o.unbound&&c.push("connectionid eq null");let a=[["$select",I],["$orderby","connectionreferencelogicalname"]];c.length&&a.push(["$filter",c.join(" and ")]);let S=await L(n,e,"connectionreferences","connectionreferenceid",t,a,null,_(o),"connection references",f=>String(s(f,"connectionreferencelogicalname")||"").toLowerCase());await n.emit(S.map(f=>d(f)))}async function M(n){let o=await l(n);await n.emit(d(await h(n,o,String(n.args.name)),!0))}function A(n,o){let e=(C(n).split("?",1)[0]??"").split("/").filter(c=>c),t=e[e.length-1];if(t!==void 0&&["details","edit"].includes(t.toLowerCase())&&e.pop(),!e.length)throw new u("--connection is empty");let i=e.length>=2?e[e.length-2]:"";if(i.startsWith("shared_")&&o&&i.toLowerCase()!==o.toLowerCase())throw new u(`'${n}' is a ${i} connection; this reference needs ${o}`);return e[e.length-1]}async function W(n){let o=n.args,e=await l(n);p(n,e,"PATCH","connectionreferences",Buffer.from("{}"));let t=await e.lookups(()=>h(n,e,String(o.name))),i=d(t).connector,c=A(String(o.connection),i);try{await g(n,e,"PATCH",`connectionreferences(${t.connectionreferenceid})`,{body:E({connectionid:c}),headers:{"If-Match":"*"}})}catch(r){throw!(r instanceof y)||r.exitCode===0||!r.message.includes("ConnectionNotFound")&&!r.message.includes("RouteNotFound")?r:new m(`no connection '${c}' for ${i??"None"} that you can use`,{service:"dataverse",hint:"the connection must exist in this environment, be for the same connector, and be yours or shared with you; its id is the last part of its URL in Power Automate > Connections"})}await n.emit(d(await h(n,e,t.connectionreferenceid),!0))}export{A as connectionId,h as find,M as get,U as list,W as set,d as shape};
@@ -0,0 +1,5 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{a as Ce}from"./chunk-HJQJ77F2.js";import{d as he,t as G,u as J}from"./chunk-S6NK6GX2.js";import{A as oe,B as me,C as le,D as W,J as ce,K as fe,X as ue,Z as pe,_ as de,a as F,aa as we,c as ne,d as se,i as O,j as q,k as ae,l as z,m as A,n as re,o as K,s as j,t as U,u as ie}from"./chunk-I7MHI5CU.js";import{a as ge,b as ye}from"./chunk-6VLFO5FJ.js";import{S as te}from"./chunk-QMTPHZLQ.js";import"./chunk-FOEBNCSD.js";import"./chunk-KBZI5UDL.js";import"./chunk-GY6BUIDP.js";import"./chunk-J4R6QXW7.js";import"./chunk-2IUXH534.js";import"./chunk-TCLZ4XM6.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{existsSync as R,readdirSync as Le,readFileSync as $e,statSync as Q}from"node:fs";import{basename as Y,dirname as v,join as y}from"node:path";var be=new RegExp("^\uFEFF"),Ne={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function V(t){return t.replace(/&(#x[0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);/g,(m,s)=>s.startsWith("#x")?String.fromCodePoint(parseInt(s.slice(2),16)):s.startsWith("#")?String.fromCodePoint(parseInt(s.slice(1),10)):Ne[s]??m)}function E(t){let s=$e(t).toString("utf8");return s.charCodeAt(0)===65279?s.slice(1):s}function Me(t,m){let s=[];if(!R(t))throw F("usage",`${t} does not exist`);let f,i,n=[];if(Q(t).isDirectory()){let d=y(t,"data.xml"),S=y(t,"Extracted","data.xml");if(f=R(d)?d:S,!R(f))throw F("usage",`${t} has no data.xml and no Extracted/data.xml`);i=E(f),n.push([y(v(f),"data_schema.xml"),()=>E(y(v(f),"data_schema.xml"))]),n.push([y(t,"schema.xml"),()=>E(y(t,"schema.xml"))])}else if(t.toLowerCase().endsWith(".zip")){let d=te($e(t)),S=Object.keys(d).find(P=>Y(P).toLowerCase()==="data.xml");if(!S)throw F("usage",`${t} has no data.xml`);f=`${t}/${S}`,i=Buffer.from(d[S]).toString("utf8").replace(be,"");let _=Object.keys(d).find(P=>Y(P).toLowerCase()==="data_schema.xml");_&&n.push([`${t}/${_}`,()=>Buffer.from(d[_]).toString("utf8").replace(be,"")]),n.push([y(v(t),"schema.xml"),()=>E(y(v(t),"schema.xml"))])}else f=t,i=E(t),n.push([y(v(t),"data_schema.xml"),()=>E(y(v(t),"data_schema.xml"))]),n.push([y(v(t),"schema.xml"),()=>E(y(v(t),"schema.xml"))]);if(m){if(!R(m))throw F("cmt_schema_missing",`${m} does not exist`);return{data:f,dataText:i,schemaPath:m,schemaText:E(m),warnings:s}}let r=n.filter(([d])=>d.includes(".zip/")||R(d));if(!r.length)throw F("cmt_schema_missing","no CMT schema: give --cmt-schema, or put data_schema.xml next to data.xml or schema.xml in the source folder");let[h,o]=r[0],l=o(),L=r.find(([d])=>d!==h&&Y(d).toLowerCase()==="schema.xml");return L&&Y(h).toLowerCase()==="data_schema.xml"&&L[1]().replace(/\r\n/g,`
3
+ `)!==l.replace(/\r\n/g,`
4
+ `)&&s.push(`${L[0]} is different from ${h}; the conversion uses ${Y(h)}`),{data:f,dataText:i,schemaPath:h,schemaText:l,warnings:s}}function Se(t,m){try{return ye(t)}catch(s){throw s instanceof ge?F("data_invalid",`${m} is not valid XML: ${s.message}`):s}}function Fe(t,m){let s=Se(t,m),f=[];for(let i of s.iter("entity")){let n=[];for(let o of i.findall("fields/field"))n.push({name:o.get("name")??"",type:(o.get("type")??"").toLowerCase(),primaryKey:(o.get("primaryKey")??"").toLowerCase()==="true",lookupType:(o.get("lookupType")??"").split("|").map(l=>l.trim()).filter(l=>l)});let r=n.find(o=>o.primaryKey)?.name??i.get("primaryidfield")??`${i.get("name")}id`,h=i.find("filter");f.push({name:i.get("name")??"",primaryId:r,primaryName:i.get("primarynamefield"),fields:n,disablePlugins:(i.get("disableplugins")??"").toLowerCase()==="true",filter:Ie(h?.text?.trim()||null,i.get("name")??""),relationships:i.findall("relationships/relationship").filter(o=>(o.get("manyToMany")??"").toLowerCase()==="true").map(o=>({name:o.get("name")??"",target:o.get("m2mTargetEntity")??""}))})}return f}var _e=["number","decimal","float","money","bigint","int","integer","double"],Pe=["optionsetvalue","state","status","picklist"],xe=["imagedata","image","file","filedata"];function ke(t,m,s,f,i){let n=m.get("value");if(n===null)return;let r=t.type;if(r==="entityreference"||r==="owner"||r==="customer"||r==="lookup"){let h=n.toLowerCase(),o=m.get("lookupentityname"),l=m.get("lookupentity")??t.lookupType[0]??"";return t.lookupType.length>1||i.length>1||r==="owner"||r==="customer"?new z(new q([["$table",l],[`${l}id`,h]]),o?V(o):null):new z(h,o?V(o):null)}if(_e.includes(r)||Pe.includes(r)){let h=re(n);if(h===null){s.push(`${f}.${t.name}: '${n}' is not a number; the value is left out`);return}return new O(h)}if(r==="bool"||r==="boolean")return/^(true|1)$/i.test(n.trim());if(r==="datetime")return he(n)??V(n);if(r==="guid"||r==="uniqueidentifier")return n.toLowerCase();if(r==="optionsetvaluecollection"||r==="multiselectpicklist"){let h=(n.match(/-?\d+/g)??[]).map(Number).filter(l=>l>=0),o=[...new Set(h)].sort((l,L)=>l-L);return o.length?new ae(o.map(l=>new O(String(l)))):null}return V(n)}async function We(t,m,s,f){let i=Me(m,f.cmtSchema),n=[...i.warnings];for(let e of["schema","data"]){let u=y(s,e);if(!f.force&&R(u)&&Q(u).isDirectory()&&Te(u))throw se("folder_not_empty",`${u} has files`,"give --force to replace them, or use a new folder")}let r=Fe(i.schemaText,i.schemaPath),h=Se(i.dataText,i.data),o=new Map,l=[];await ue(r,4,async e=>{let u=await de(t,e.name,new Set(e.fields.map(x=>x.name)));u?o.set(e.name,u):l.push(`the environment has no table '${e.name}'`)});let L=new Set(r.map(e=>e.name)),d=new Map,S=new Map,_=new Set;for(let e of r){let u=o.get(e.name);if(!u)continue;let x=[];for(let b of e.fields.filter(c=>!c.primaryKey&&c.name!==e.primaryId)){let c=u.columns.get(b.name);if(!c){l.push(`'${e.name}' has no column '${b.name}'`);continue}let N=pe(c);N?n.push(`${e.name}.${b.name}: left out of the schema, because it ${N}`):x.push(b)}d.set(e.name,x);let k=[];for(let b of e.relationships){let c=[...u.manyToMany.values()].find(X=>X.intersect.toLowerCase()===b.name.toLowerCase());if(!c){l.push(`'${e.name}' has no many-to-many relationship with the intersect table '${b.name}'`);continue}if(_.has(c.schemaName.toLowerCase()))continue;_.add(c.schemaName.toLowerCase());let N=c.entity1===e.name?c.entity2:c.entity1;if(!L.has(N)){n.push(`${e.name}: the many-to-many relationship ${c.schemaName} is left out, because its other table '${N}' is not in the CMT schema`);continue}k.push({cmtName:b.name,schemaName:c.schemaName,entity1:c.entity1,entity2:c.entity2,owner:e.name})}S.set(e.name,k)}if(l.length)throw ne("not_found","the environment does not have each table, column and relationship of the CMT schema",l.sort());let P=new Map;for(let e of h.iter("entity"))P.set(e.get("name")??"",e);let T=new me,D={source:m,data:i.data,cmt_schema:i.schemaPath,folder:s,tables:[],relationships:[],warnings:n};for(let e of r){let u=d.get(e.name);for(let a of u)xe.includes(a.type)&&n.push(`${e.name}.${a.name}: a file or image column is not converted; the first export saves the files`);let x=[["version",new O("1")],["table",e.name],["columns",u.map(a=>a.name)]];e.filter&&(x.push(["fetchXmlFilter",e.filter]),n.push(`${e.name}: the filter is FetchXML; its <filter> is in fetchXmlFilter`)),x.push(["nullValues","ignore"]),e.disablePlugins&&(x.push(["bypass",new A([["plugins","all"]])]),n.push(`${e.name}: disableplugins is true; the schema has bypass plugins all, which needs mode full`));let k=S.get(e.name);k.length&&x.push(["relationships",k.map(a=>new A([["name",a.schemaName]]))]),T.put(`schema/${e.name}.yaml`,Ce+`
5
+ `+K(new A(x)));let b=P.get(e.name),c=[],N=new Map(e.fields.map(a=>[a.name,a]));for(let a of b?.findall("records/record")??[]){let M=(a.get("id")??"").toLowerCase(),I=[[e.primaryId,M]],$=new Map;for(let g of a.findall("field")){let w=N.get(g.get("name")??"");if(!w||w.primaryKey||w.name===e.primaryId||xe.includes(w.type))continue;let p=ke(w,g,n,e.name,o.get(e.name)?.columns.get(w.name)?.targets??[]);p!==void 0&&$.set(w.name,p)}for(let g of u){let w=ce(e.name,g.name),p=$.get(g.name);if(!w||typeof p!="string"||!p)continue;let C=fe(M,g.name,p,$.get(w));T.put(`${ie}/${e.name}/${C.fname}`,C.bytes),$.set(g.name,new q([["$file",C.fname]]))}for(let g of u)$.has(g.name)&&I.push([g.name,$.get(g.name)]);c.push({sort:J([[e.primaryId,M]]),node:new A(I)})}c.sort((a,M)=>G(a.sort,M.sort));let X={table:e.name,layout:"table",match:[e.primaryId],columns:u.map(a=>a.name),filter:null,fetchXmlFilter:e.filter},Z=`${j}/${e.name}.yaml`;T.put(Z,K(W([...oe(X),["records",c.map(a=>a.node)]]))),D.tables.push({table:e.name,schema:`schema/${e.name}.yaml`,file:Z,records:c.length,columns:u.length});for(let a of k){let M=a.owner!==a.entity1,I=new Map;for(let p of b?.findall("m2mrelationships/m2mrelationship")??[]){if((p.get("m2mrelationshipname")??"").toLowerCase()!==a.cmtName.toLowerCase())continue;let C=(p.get("sourceid")??"").toLowerCase();for(let ve of p.findall("targetids/targetid")){let B=(ve.text??"").trim().toLowerCase();if(!C||!B)continue;let[ee,Ee]=M?[B,C]:[C,B],H=I.get(ee);H||I.set(ee,H=new Set),H.add(Ee)}}let $=0,g=[...I].map(([p,C])=>($+=C.size,{sort:J([["from",p]]),node:new A([["from",p],["to",[...C].sort()]])}));g.sort((p,C)=>G(p.sort,C.sort));let w=`${U}/${a.schemaName.toLowerCase()}.yaml`;T.put(w,K(W([["relationship",a.schemaName],["from",a.entity1],["to",a.entity2],["links",g.map(p=>p.node)]]))),D.relationships.push({name:a.schemaName,file:w,links:$})}}return f.force&&(T.own("schema"),T.own(j),T.own(U)),le(s,T,!0),D}function Te(t){for(let m of Le(t)){let s=y(t,m);if(!Q(s).isDirectory()||Te(s))return!0}return!1}function Ie(t,m){if(!t)return null;try{return we(t,m,!0)||null}catch{return t}}export{V as decodeAgain,Me as findSources,Fe as readCmtSchema,We as runConvert};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{a as B,b as k,c as me}from"./chunk-6VLFO5FJ.js";import{A as de,B as F,F as ue,G as u,d as Q,e as A,f as c,g as le,h as C,i as h,k as N,n as _,t as x,u as g,v as q,w as P,z as Z}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import{a as ce,b as Y,d as z,e as j,f as J,i as K}from"./chunk-FOEBNCSD.js";import{y as se}from"./chunk-BALEFXOL.js";import{a as re}from"./chunk-J4R6QXW7.js";import{b as E}from"./chunk-2IUXH534.js";import"./chunk-S4KF5Z3S.js";import{a as ae,b as y,d as W}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{randomUUID as Te}from"node:crypto";import{readFileSync as je,writeFileSync as we}from"node:fs";import{extname as ke}from"node:path";var ye=new Map([[0,"public"],[1,"advanced-find"],[2,"associated"],[4,"quick-find"],[8,"reporting"],[16,"offline-filters"],[64,"lookup"],[128,"appointment-book"],[256,"outlook-filters"],[512,"address-book-filters"],[1024,"main-without-subject"],[2048,"other"],[4096,"interactive-workflow"],[8192,"offline-template"],[16384,"custom-defined"]]),ge=new Map([[0,"dashboard"],[2,"main"],[5,"mobile"],[6,"quick-view"],[7,"quick-create"],[11,"card"],[12,"main-interactive"]]),fe={main:2,"quick-create":7,"quick-view":6,card:11},ne=new Map([[1,"html"],[2,"css"],[3,"js"],[4,"xml"],[5,"png"],[6,"jpg"],[7,"gif"],[8,"xap"],[9,"xsl"],[10,"ico"],[11,"svg"],[12,"resx"]]),Ce={".htm":1,".html":1,".css":2,".js":3,".xml":4,".png":5,".jpg":6,".jpeg":6,".gif":7,".xap":8,".xsl":9,".xslt":9,".ico":10,".svg":11,".resx":12},Ne=new Set([1,2,3,4,9,11,12]),Be="{4273EDBD-AC1D-40d3-9FB2-095C621B552D}",be="name,returnedtypecode,querytype,isdefault,statecode,ismanaged,description,savedqueryid",he="name,objecttypecode,type,formactivationstate,isdefault,ismanaged,description,formid",xe="name,displayname,webresourcetype,ismanaged,description,modifiedon,webresourceid",I=Buffer.from("{}");function D(e,t){for(let[o,n]of e)if(n===t)return o;throw new Error(`unknown type ${t}`)}function oe(e,t){return typeof t=="number"&&e.has(t)?e.get(t):t}function R(e){return e.publish===!1}function L(e){return typeof e!="string"||!e?null:ue(se(e).toString("utf8"))}function ee(e,t,o){let n;try{n=k(J(e))}catch(i){throw i instanceof B?new y(`the ${o} is not well-formed XML: ${i.message}`):i}if(n.tag!==t)throw new y(`the ${o} must have a <${t}> root, not <${n.tag}>`);return n}async function S(e,t,o,n,i){let a=await g(e,t,"GET",`${o}(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`,{params:[["$select",i]]});return q(a)}async function H(e,t,o){ce(o,"table logical name");let n=q(await g(e,t,"GET",`EntityDefinitions(LogicalName='${o}')`,{params:[["$select","LogicalName,EntitySetName,ObjectTypeCode,PrimaryIdAttribute,PrimaryNameAttribute"]]})),i=q(await g(e,t,"GET",`EntityDefinitions(LogicalName='${o}')/Attributes`,{params:[["$select","LogicalName"]]}));return n.attributes=new Set(C(i.value).map(a=>a.LogicalName)),n}async function M(e,t,o){let n=[];o.table&&n.push(`<entities><entity>${o.table}</entity></entities>`),o.webresource&&n.push(`<webresources><webresource>{${o.webresource}}</webresource></webresources>`);let i={ParameterXml:"<importexportxml>"+n.join("")+"</importexportxml>"};await g(e,t,"POST","PublishXml",{body:P(i)})}async function ve(e,t,o,n,i,a,s,r,d){let l=Y(s)?`${n} eq ${z(s)}`:`name eq ${j(s)}`;r&&(l+=` and ${i} eq ${j(r)}`);let f=C(q(await g(e,t,"GET",o,{params:[["$select",a],["$filter",l]]})).value);if(!f.length)throw new W(`no ${d} '${s}'`+(r?` on ${r}`:""),{service:"dataverse",hint:`run: ppdo-cli dv ${d} list <table>`});if(f.length>1)throw new y(`${f.length} ${d}s are named '${s}'`,{hint:"pass --table, or use an id: "+f.slice(0,5).map(m=>m[n]).join(", ")});return f[0]}async function ie(e,t,o){if(!o)return{};let{find:n}=await import("./solution-CNBNIS7Z.js");return await n(e,t,o),{"MSCRM.SolutionUniqueName":o}}function Le(e){let t=e.get("attribute"),o=e.get("operator"),n=e.findall("value").map(s=>s.text),i=e.get("value")!==null?e.get("value"):n.length?n.map(s=>s??"None").join(","):null;return`${e.get("entityname")?`${e.get("entityname")}.`:""}${t??"None"} ${o??"None"}`+(i!==null?` ${i}`:"")}function $e(e){if(e===null)return null;let t=` ${e.get("type","and")} `;return e.children.filter(n=>n.tag==="condition"||n.tag==="filter").map(n=>n.tag==="condition"?Le(n):`(${$e(n)??"None"})`).filter(n=>n).join(t)||null}function Re(e,t){let o={};try{let a=k(e||"").find("entity");a!==null&&(o.sort=a.findall("order").map(s=>(s.get("descending")==="true"?"-":"")+(s.get("attribute")||s.get("alias")||"")),o.filter=$e(a.find("filter")),o.links=[...a.iter("link-entity")].map(s=>({table:s.get("name"),alias:s.get("alias"),from:s.get("from"),to:s.get("to"),type:s.get("link-type","inner")})))}catch(i){if(!(i instanceof B))throw i;o.fetch_error="not well-formed"}try{let i=k(t||"");o.columns=[...i.iter("cell")].map(a=>{let s=a.get("width");return{name:a.get("name"),width:/^[0-9]+$/.test(s||"")?parseInt(s,10):s}})}catch(i){if(!(i instanceof B))throw i;o.layout_error="not well-formed"}let n={};for(let[i,a]of Object.entries(o))a!==null&&!(Array.isArray(a)&&!a.length)&&(n[i]=a);return n}async function Ee(e,t,o,n,i){let s=ee(n,"fetch","FetchXML").find("entity");if(s===null||s.get("name")!==o)throw new y(`the FetchXML's <entity name> must be ${o}`);let r=ee(i,"grid","layout XML"),d=new Set(s.findall("attribute").map(p=>p.get("name"))),l=s.find("all-attributes")!==null,f=new Set([...s.iter("link-entity")].map(p=>p.get("alias")).filter(p=>p)),m=[];for(let p of r.iter("cell")){let T=p.get("name")||"";T.includes(".")?f.has(T.slice(0,T.indexOf(".")))||m.push(T):!l&&!d.has(T)&&m.push(T)}if(m.length)throw new y("layout columns not in the query: "+m.join(", "),{hint:"add <attribute name=...> (or the link-entity alias) to the FetchXML"});let w=e,v=t,$=await H(w,v,o),b=k(J(n));for(let p of["page","paging-cookie","top"])b.attrib.delete(p);b.set("count","1");try{await v.request("GET",`${$.EntitySetName}?fetchXml=`+re(me(b),""))}catch(p){throw p instanceof ae?new y(`the FetchXML doesn't run: ${p.message}`):p}}function U(e){return h({name:c(e,"name"),table:c(e,"returnedtypecode"),type:oe(ye,c(e,"querytype")),default:A(c(e,"isdefault"),null),state:c(e,"statecode")===1?"inactive":"active",managed:c(e,"ismanaged"),id:c(e,"savedqueryid")})}async function Je(e){let t=e.args,o=await x(e);E(e,o,"GET","savedqueries",null);let n=[`returnedtypecode eq ${j(String(t.table))}`];u(t.type)&&n.push(`querytype eq ${D(ye,u(t.type))}`),u(t.name)&&n.push(K("name",u(t.name)));let[i]=await Z(e,o,"savedqueries",[["$select",be],["$filter",n.join(" and ")],["$orderby","name"]],null,_(t),"views");await e.emit(i.map(U))}function G(e,t,o,n){return ve(e,t,"savedqueries","savedqueryid","returnedtypecode",be,o,n,"view")}function Se(e,t){we(e,t,"utf8")}async function Ke(e){let t=e.args,o=await x(e),n=await G(e,o,String(t.view),u(t.table)),i=await S(e,o,"savedqueries",n.savedqueryid,"fetchxml,layoutxml,name,description"),a={...U(n),description:c(i,"description"),...Re(c(i,"fetchxml"),c(i,"layoutxml"))};for(let[s,r]of[[u(t.saveFetchxml),"fetchxml"],[u(t.saveLayoutxml),"layoutxml"]])s&&(Se(s,c(i,r)||""),(a.saved??=[]).push(s));await e.emit(h(a))}function Oe(e){let t=e.PrimaryNameAttribute,o=e.PrimaryIdAttribute,n=e.ObjectTypeCode,i='<filter type="and"><condition attribute="statecode" operator="eq" value="0" /></filter>',a=`<fetch version="1.0" mapping="logical"><entity name="${e.LogicalName}"><attribute name="${t}" /><attribute name="${o}" /><order attribute="${t}" descending="false" />${i}</entity></fetch>`;e.attributes.has("statecode")||(a=a.split(i).join(""));let s=`<grid name="resultset" object="${n}" jump="${t}" select="1" icon="1" preview="1"><row name="result" id="${o}"><cell name="${t}" width="300" /></row></grid>`;return[a,s]}async function Qe(e){let t=e.args,o=String(t.table),n=await x(e);E(e,n,"POST","savedqueries",I);let i=L(t.fetchxml),a=L(t.layoutxml),s=await n.lookups(async()=>{let f=await H(e,n,o);if(u(t.copy)){let m=await G(e,n,u(t.copy),o),w=await S(e,n,"savedqueries",m.savedqueryid,"fetchxml,layoutxml");i=i||c(w,"fetchxml"),a=a||c(w,"layoutxml")}if(!i||!a){let[m,w]=Oe(f);i=i||m,a=a||w}return await Ee(e,n,o,i,a),ie(e,n,u(t.solution))}),r={name:t.name,returnedtypecode:o,querytype:0,fetchxml:i,layoutxml:a};u(t.description)&&(r.description=t.description);let d=await g(e,n,"POST","savedqueries",{body:P(r),headers:s}),l=F(d);R(t)||await M(e,n,{table:o}),await e.emit({...U(await G(e,n,String(l),null)),published:!R(t)})}async function Ze(e){let t=e.args,o=u(t.name),n=u(t.description);if(!(o||n!==null||t.fetchxml||t.layoutxml))throw new y("nothing to update",{hint:"pass --name, --description, --fetchxml or --layoutxml"});let i=await x(e);E(e,i,"PATCH","savedqueries",I);let a=L(t.fetchxml),s=L(t.layoutxml),r=await i.lookups(async()=>{let f=await G(e,i,String(t.view),u(t.table));if(a||s){let m=await S(e,i,"savedqueries",f.savedqueryid,"fetchxml,layoutxml");await Ee(e,i,f.returnedtypecode,a||c(m,"fetchxml")||"",s||c(m,"layoutxml")||"")}return f}),d=h({name:o,description:n,fetchxml:a,layoutxml:s});await g(e,i,"PATCH",`savedqueries(${r.savedqueryid})`,{body:P(d),headers:{"If-Match":"*"}}),R(t)||await M(e,i,{table:r.returnedtypecode});let l=await S(e,i,"savedqueries",r.savedqueryid,"fetchxml,layoutxml,name");await e.emit({...U({...r,name:c(l,"name")||c(r,"name")}),changed:N(Object.keys(d),f=>f),published:!R(t),...Re(c(l,"fetchxml"),c(l,"layoutxml"))})}function pe(e){if(e===null)return null;let t=e.find("labels/label");return t!==null?t.get("description"):null}function Pe(e){let t;try{t=k(e||"")}catch(r){if(r instanceof B)return{form_error:"not well-formed"};throw r}let o=[];for(let r of t.iter("tab")){let d=[];for(let l of r.iter("section")){let f=[...l.iter("control")].map(m=>m.get("datafieldname")||m.get("id"));d.push(h({name:l.get("name"),label:pe(l),visible:l.get("visible")!=="false"?null:!1,fields:f}))}o.push(h({name:r.get("name"),label:pe(r),visible:r.get("visible")!=="false"?null:!1,sections:d}))}let n=t.find("header"),i=[...t.iter("Library")].map(r=>r.get("name")),a={tabs:o,header:n!==null?[...n.iter("control")].map(r=>r.get("datafieldname")||r.get("id")):null,libraries:i.length?i:null},s={};for(let[r,d]of Object.entries(a))Q(d)&&(s[r]=d);return s}async function qe(e,t,o,n){let i=ee(n,"form","form XML"),a=[...i.iter("control")].map(l=>l.get("id")).filter(l=>!!l),s=N(new Set(a.filter(l=>a.indexOf(l)!==a.lastIndexOf(l))),l=>l);if(s.length)throw new y("control ids used more than once: "+s.join(", "));let r=(await H(e,t,o)).attributes,d=N(new Set([...i.iter("control")].map(l=>l.get("datafieldname")).filter(l=>!!l&&!r.has(l.toLowerCase()))),l=>l);if(d.length)throw new y(`fields not on ${o}: `+d.join(", "))}function V(e){return h({name:c(e,"name"),table:c(e,"objecttypecode"),type:oe(ge,c(e,"type")),default:A(c(e,"isdefault"),null),state:c(e,"formactivationstate")===0?"inactive":"active",managed:c(e,"ismanaged"),id:c(e,"formid")})}async function et(e){let t=e.args,o=await x(e);E(e,o,"GET","systemforms",null);let n=[`objecttypecode eq ${j(String(t.table))}`];u(t.type)&&n.push(`type eq ${D(ge,u(t.type))}`);let[i]=await Z(e,o,"systemforms",[["$select",he],["$filter",n.join(" and ")],["$orderby","name"]],null,_(t),"forms");await e.emit(i.map(V))}function O(e,t,o,n){return ve(e,t,"systemforms","formid","objecttypecode",he,o,n,"form")}async function tt(e){let t=e.args,o=await x(e),n=await O(e,o,String(t.form),u(t.table)),i=await S(e,o,"systemforms",n.formid,"formxml,description"),a={...V(n),description:c(i,"description"),...Pe(c(i,"formxml"))},s=u(t.save);s&&(Se(s,c(i,"formxml")||""),a.saved=s),await e.emit(h(a))}function Ie(e,t){let o=()=>"{"+Te()+"}",n=e.PrimaryNameAttribute;return`<form><tabs><tab name="general" id="${o()}" verticallayout="true" showlabel="true" expanded="true"><labels><label description="General" languagecode="${t}" /></labels><columns><column width="100%"><sections><section name="general_section" id="${o()}" showlabel="false" showbar="false" columns="1"><labels><label description="General" languagecode="${t}" /></labels><rows><row><cell id="${o()}"><labels><label description="Name" languagecode="${t}" /></labels><control id="${n}" classid="${Be}" datafieldname="${n}" disabled="false" /></cell></row></rows></section></sections></column></columns></tab></tabs></form>`}async function nt(e){let t=e.args,o=String(t.table),n=u(t.type),i=await x(e);E(e,i,"POST","systemforms",I);let[a,s,r]=await i.lookups(async()=>{let m=await H(e,i,o),w,v;if(u(t.copy)){let $=await O(e,i,u(t.copy),o);w=c(await S(e,i,"systemforms",$.formid,"formxml"),"formxml")||"",v=n?fe[n]:c($,"type")}else{let $=q(await g(e,i,"GET","organizations",{params:[["$select","languagecode"]]})).value,b=A(c(Q($)?C($)[0]:{},"languagecode"),1033);w=Ie(m,b),v=fe[n||"main"]}return await qe(e,i,o,w),[w,v,await ie(e,i,u(t.solution))]}),d={name:t.name,objecttypecode:o,type:s??null,formxml:a};u(t.description)&&(d.description=t.description);let l=await g(e,i,"POST","systemforms",{body:P(d),headers:r}),f=F(l);R(t)||await M(e,i,{table:o}),await e.emit({...V(await O(e,i,String(f),null)),published:!R(t)})}async function ot(e){let t=e.args,o=u(t.name),n=u(t.description),i=u(t.state);if(!(o||n!==null||i||t.body))throw new y("nothing to update",{hint:"pass --name, --description, --state or --body"});let a=await x(e);E(e,a,"PATCH","systemforms",I);let s=L(t.body),r=await a.lookups(async()=>{let m=await O(e,a,String(t.form),u(t.table));if(i==="inactive"&&c(m,"type")!==2)throw new y("only main forms can be made inactive");return s&&await qe(e,a,m.objecttypecode,s),m}),d=h({name:o,description:n,formxml:s,formactivationstate:i==="active"?1:i==="inactive"?0:null});await g(e,a,"PATCH",`systemforms(${r.formid})`,{body:P(d),headers:{"If-Match":"*"}}),R(t)||await M(e,a,{table:r.objecttypecode});let l=await O(e,a,r.formid,null),f=await S(e,a,"systemforms",r.formid,"formxml,name");await e.emit({...V({...l,name:c(f,"name")||c(l,"name")}),changed:N(Object.keys(d),m=>m),published:!R(t),...Pe(c(f,"formxml"))})}function X(e){return h({name:c(e,"name"),display_name:c(e,"displayname"),type:oe(ne,c(e,"webresourcetype")),managed:c(e,"ismanaged"),modified:c(e,"modifiedon"),id:c(e,"webresourceid")})}async function it(e){let t=e.args,o=await x(e);E(e,o,"GET","webresourceset",null);let n=u(t.solution),i=null;if(n){let{names:d,objectIds:l}=await import("./solution-CNBNIS7Z.js");i=await l(e,o,d(n),61)}let a=t.hidden?[]:["ishidden/Value eq false"];u(t.name)&&a.push(K("name",u(t.name))),u(t.type)&&a.push(`webresourcetype eq ${D(ne,u(t.type))}`);let s=[["$select",xe],["$orderby","name"]];a.length&&s.push(["$filter",a.join(" and ")]);let r=await de(e,o,"webresourceset","webresourceid",i,s,null,_(t),"web resources",d=>(c(d,"name")||"").toLowerCase());await e.emit(r.map(X))}async function te(e,t,o){let n=Y(o)?`webresourceid eq ${z(o)}`:`name eq ${j(o)}`,i=C(q(await g(e,t,"GET","webresourceset",{params:[["$select",xe],["$filter",n]]})).value);return i.length?i[0]:null}async function at(e){let t=e.args,o=String(t.name),n=await x(e),i=await te(e,n,o);if(!i)throw new W(`no web resource '${o}'`,{service:"dataverse",hint:"run: ppdo-cli dv webresource list --name '*<part>*'"});let a=await S(e,n,"webresourceset",i.webresourceid,"content,description"),s=Buffer.from(c(a,"content")||"","base64"),r={...X(i),description:c(a,"description"),bytes:s.length},d=u(t.save);d?(we(d,s),r.saved=d):Ne.has(c(i,"webresourcetype"))?r.content=s.toString("utf8"):r.hint="binary content: pass --save <file>",await e.emit(h(r))}var Me={ENOENT:"No such file or directory",EACCES:"Permission denied",EPERM:"Operation not permitted",EISDIR:"Is a directory"};async function st(e){let t=e.args,o=String(t.file),n=String(t.name),i;try{i=je(o)}catch(b){let p=b;throw new y(`cannot read ${o}: ${Me[p.code??""]??p.message}`)}let a=i.toString("base64"),s=u(t.type),r=s?D(ne,s):Ce[ke(o).toLowerCase()];if(r===void 0)throw new y(`can't tell the web resource type from '${o}'`,{hint:"pass --type"});if(!n.split("/",1)[0].includes("_"))throw new y(`'${n}' has no publisher prefix`,{hint:"e.g. contoso_/scripts/app.js"});let d=await x(e);E(e,d,"POST","webresourceset",I);let[l,f,m]=await d.lookups(async()=>{let b=await te(e,d,n),p=b?c(await S(e,d,"webresourceset",b.webresourceid,"content"),"content"):null;return[b,p,await ie(e,d,u(t.solution))]}),w=h({displayname:u(t.displayName),description:u(t.description)});if(l&&f===a&&!Object.keys(w).length){await e.emit({...X(l),action:"unchanged",published:!1});return}let v,$;if(l)await g(e,d,"PATCH",`webresourceset(${l.webresourceid})`,{headers:{"If-Match":"*",...m},body:P({content:a,...w})}),v=l.webresourceid,$="updated";else{let b={name:n,webresourcetype:r,content:a,displayname:u(t.displayName)||n.slice(n.lastIndexOf("/")+1),...w},p=await g(e,d,"POST","webresourceset",{body:P(b),headers:m});v=F(p),$="created"}R(t)||await M(e,d,{webresource:v}),await e.emit({...X(le(await te(e,d,String(v)))),action:$,bytes:i.length,published:!R(t)})}export{fe as CREATE_FORM_TYPES,ge as FORM_TYPES,ye as VIEW_TYPES,Ce as WR_EXTENSIONS,ne as WR_TYPES,qe as checkForm,Ee as checkView,O as findForm,G as findView,te as findWebresource,nt as formCreate,tt as formGet,et as formList,Pe as formSummary,ot as formUpdate,M as publish,ie as solutionHeaders,H as tableInfo,Qe as viewCreate,Ke as viewGet,Je as viewList,Re as viewSummary,Ze as viewUpdate,at as wrGet,it as wrList,st as wrPush};
@@ -0,0 +1,5 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{a as Y,b as G,c as Ve,e as q,f as A,g as Z,h as We,i as ge,j as ee,k as Ge,l as He,m as Qe,n as Xe,o as Ze,p as et,q as nt,r as ot,s as ye,v as st}from"./chunk-S6NK6GX2.js";import{$ as Ye,E as Ke,G as Be,J as re,L as Ae,M as _e,N as me,O as je,P as qe,Q as Je,R as Ue,S,T as j,W as le,X as z,Y as W,a as K,b as V,ca as tt,d as ae,h as xe,i as Ie,r as De,s as X,u as he,w as Fe,x as Ee,y as Ne,z as ze}from"./chunk-I7MHI5CU.js";import"./chunk-6VLFO5FJ.js";import{b as pe,d as Pe,e as Ce,f as Te}from"./chunk-MNGA7IHQ.js";import{n as Le,t as U}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import{b as Oe}from"./chunk-FOEBNCSD.js";import{b as Me}from"./chunk-KBZI5UDL.js";import"./chunk-BALEFXOL.js";import{a as $e,b as Se}from"./chunk-LB7WNZVK.js";import"./chunk-GY6BUIDP.js";import"./chunk-J4R6QXW7.js";import{c as Re}from"./chunk-2IUXH534.js";import"./chunk-TCLZ4XM6.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import{a as H,b as J,g as Q,j as ve}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{mkdirSync as Kt,writeFileSync as Bt}from"node:fs";import{dirname as At}from"node:path";function te(r){return r.key.slice(2)}async function it(r,e,n,t,s,d,o,l,u,a){let i=n.relationship(d.name),c=[],f=ze(e,d.name,c);if(!f&&!c.length&&c.push(`data/relationships/${d.name.toLowerCase()}.yaml: the relationship is in the schema and has no data file; run: ppdo-cli dv data export`),f&&(f.from!==i.entity1||f.to!==i.entity2)&&c.push(`${f.file}: from and to must be ${i.entity1} and ${i.entity2}`),c.length||!f)throw K("data_invalid","the data files are not valid",c);let h=n.meta(i.entity1),m=n.meta(i.entity2),y=ye("from",i.entity1),g=ye("to",i.entity2),$=o.get(i.entity1),I=o.get(i.entity2),R=[],L=[];for(let w of f.links)try{let O=await s.lookupKey(y,w.from),b=[];for(let P of w.to)b.push(await s.lookupKey(g,P));L.push({from:O,to:b,file:w.file,index:w.index})}catch(O){throw O instanceof A?K("data_invalid","the data files are not valid",[`${w.file} link ${w.index+1}: ${O.message}`]):O}let F=(w,O,b)=>{let P=w?.get(O.key);if(P&&!P.logged)return P.id?{table:b,id:P.id,pending:null}:{table:b,id:null,pending:P};let C=l.get(b)?.get(O.key);return C?{table:b,id:String(C[b===i.entity1?h.primaryId:m.primaryId]).toLowerCase(),pending:null}:null};for(let w of L)for(let O of w.to)F(I,O,i.entity2)||R.push(O);let T=R.length?await t.findByKeys(i.entity2,R):new Map,B=await n.other(i.intersect);if(!B)throw K("not_found",`the environment has no intersect table '${i.intersect}'`);let ue=await r.rows(B.entitySet,[["$select",`${i.attr1},${i.attr2}`]],!1),p=new Map;for(let w of ue){let O=String(w[i.attr1]).toLowerCase(),b=p.get(O);b||p.set(O,b=new Set),b.add(String(w[i.attr2]).toLowerCase())}let k=[],v=new Map,M=new Map,x=0,E=new Set;for(let w of L){if($?.get(w.from.key)?.logged){E.add(w.from.key);continue}w.to=w.to.filter(C=>!I?.get(C.key)?.logged);let O=F($,w.from,i.entity1);if(!O){u.push(`${w.file} link ${w.index+1}: the from record ${JSON.stringify(te(w.from))} is not in the data file of ${i.entity1} and not in the environment`);continue}if(E.has(w.from.key)){u.push(`${w.file} link ${w.index+1}: the from record ${JSON.stringify(te(w.from))} is in the file two times`);continue}E.add(w.from.key);let b=O.id?p.get(O.id)??new Set:new Set,P=new Set;for(let C of w.to){let D=F(I,C,i.entity2);if(!D){let N=T.get(C.key);N&&(D={table:i.entity2,id:String(N[m.primaryId]).toLowerCase(),pending:null})}if(!D){u.push(`${w.file} link ${w.index+1}: no ${i.entity2} with the key ${JSON.stringify(te(C))}`);continue}D.id&&P.add(D.id),D.id&&b.has(D.id)?x++:k.push({from:O,to:D,fromOut:te(w.from),toOut:te(C)})}if(O.id&&M.set(O.id,P),d.delete.mode==="mirror"&&O.id)for(let C of b)P.has(C)||v.set(`${O.id}|${C}`,ke(i,O.id,C,"mirror"))}if(d.delete.mode==="mirror"){for(let w of $?.values()??[])if(!(w.logged||!w.id||E.has(w.key)))for(let O of p.get(w.id)??[])v.set(`${w.id}|${O}`,ke(i,w.id,O,"mirror"))}if(d.delete.mode!=="off"){let w=[],O=He(e,d.name,w);if(w.length)throw K("data_invalid","the data files are not valid",w);for(let b of O?.entries??[]){if(M.get(b.from)?.has(b.to)){a.push(`${O.file}: the link ${b.from}|${b.to} is in the relationship file and in the deletion log; the import uses the relationship file and does not remove it`);continue}p.get(b.from)?.has(b.to)&&v.set(`${b.from}|${b.to}`,ke(i,b.from,b.to,"manifest"))}}return{spec:d,rel:i,fromMeta:h,toMeta:m,link:k,unlink:[...v.values()],unchanged:x}}function ke(r,e,n,t){return{from:{table:r.entity1,id:e,pending:null},to:{table:r.entity2,id:n,pending:null},fromOut:e,toOut:n,reason:t}}async function at(r,e,n,t,s){let d=r.origin,o=[],l=[];for(let h of e.link){let m=h.from.id??h.from.pending?.id,y=h.to.id??h.to.pending?.id;if(!m||!y){h.failed="not run: a record of the link was not created",o.push(h);continue}l.push({change:h,method:"POST",path:`${e.fromMeta.entitySet}(${m})/${e.rel.nav1}/$ref`,body:{"@odata.id":`${d}/api/data/v9.2/${e.toMeta.entitySet}(${y})`}})}for(let h of e.unlink)l.push({change:h,method:"DELETE",path:`${e.fromMeta.entitySet}(${h.from.id})/${e.rel.nav1}(${h.to.id})/$ref`});let u=[];for(let h=0;h<l.length;h+=100)u.push(l.slice(h,h+100));let a=0,i=0,c=[],f=0;return await z(u,n,async h=>{let m=await s(h.map(y=>({method:y.method,path:y.path,body:y.body,headers:t})));h.forEach((y,g)=>{let $=m[g];$&&$.status>=200&&$.status<300?y.method==="POST"?a++:(i++,c.push(y.change)):(y.change.failed=$?.error??`HTTP ${$?.status??0}`,o.push(y.change))}),f+=h.length,r.progress.log(`${e.spec.name}: ${f.toLocaleString("en-US")} of ${l.length.toLocaleString("en-US")} link requests`)}),{linked:a,unlinked:i,removed:c,failed:o}}var rt=/0x80044150|deadlock|\b1205\b/i,bt=/Sql Number: (2812|2766)\b/,vt=["skip","delete","deactivate","unlink"],lt=r=>new Promise(e=>setTimeout(e,r)),ne=class{constructor(e,n,t){this.dv=e;this.plan=n;this.opts=t}done={created:new Set,updated:new Set,deleted:new Set,deactivated:new Set,skipped:new Set,failed:new Set,links:new Map,failures:[],stopped:!1};sets=new Map;batchOf(e,n=!1){let t=e.t.batchSize??this.opts.batchSize;return n?Math.min(t,Be):t}tableOf(e){return this.plan.tables.find(n=>n.t.table===e.t.table)}fail(e,n,t){this.done.failed.has(e)||this.done.skipped.has(e)||(n==="skip"?this.done.skipped.add(e):(this.done.failed.add(e),this.dv.progress.log(`failed: ${n} ${e.t.table} ${ce(e.keyOut)}: ${t.error}`)),e.failed=t.error,this.done.failures.push({table:e.t.table,action:n,key:e.keyOut,name:e.name,...t.status!==void 0?{status:t.status}:{},...t.code?{code:t.code}:{},error:t.error}))}async prepare(){let e=new Set;for(let n of this.plan.tables)for(let t of n.records)for(let s of t.lookups.values())s&&e.add(s.table);for(let n of e){let t=await this.plan.model.other(n);t&&this.sets.set(n,t.entitySet)}}bind(e,n,t){return[`${e.navigation.get(n.table)??(e.navigation.size===1?[...e.navigation.values()][0]:void 0)??e.name}@odata.bind`,`/${this.sets.get(n.table)??n.table+"s"}(${t})`]}targetId(e){return e.id??e.pending?.id??null}createBody(e){let n=e.m,t={};for(let[s,d]of e.values){let o=n.columns.get(s);t[s]=o?ge(d,o):d}for(let[s,d]of e.lookups){if(!d||e.later.has(s))continue;let o=this.targetId(d);if(!o)continue;let[l,u]=this.bind(n.columns.get(s),d,o);t[l]=u}return t}updateBody(e,n){let t=e.m,s={};if(!n){for(let[d,o]of e.values)s[d]=ge(o,t.columns.get(d));for(let[d,o]of e.lookups){let l=t.columns.get(d);if(o===null){let c=St(l,e.row);s[c]=null;continue}let u=this.targetId(o);if(!u)return null;let[a,i]=this.bind(l,o,u);s[a]=i}}for(let[d,o]of e.later){let l=this.targetId(o);if(!l)return null;let[u,a]=this.bind(t.columns.get(d),o,l);s[u]=a}for(let d of e.binaries)d.column.kind==="image"&&(s[d.column.name]=d.bytes?d.bytes.toString("base64"):null);return Object.keys(s).length?s:null}async sendBatch(e){let[n,t,s]=Pe(e,this.dv.origin,!1),d=Buffer.from(t,"utf8"),o=await this.dv.request("POST","$batch",{headers:{"Content-Type":`multipart/mixed; boundary=${n}`,Prefer:"odata.continue-on-error"},body:d,check:!1});if(o.status>=400&&!(o.header("content-type")||"").includes("multipart"))throw this.dv.client.service.error(o);let l=/boundary=([^\s;]+)/.exec(o.header("content-type")||"");return Te(s,l?Ce(o.text,l[1]):[],e.length)}outcome(e){if(!e)return{ok:!1,error:"no response"};if(e.status>=200&&e.status<300){let s=e.headers?.["odata-entityid"]??"",d=/\(([0-9a-fA-F-]{36})\)\s*$/.exec(s);return{ok:!0,...d?{id:d[1].toLowerCase()}:{}}}let n=e.body,t=(n&&typeof n=="object"?n.error:void 0)??{};return{ok:!1,status:e.status,...typeof t.code=="string"?{code:t.code}:{},error:Me(typeof t.message=="string"?t.message:null)??e.error??`HTTP ${e.status}`}}async bulk(e,n,t,s,d){if(!(n==="CreateMultiple"?e.bulkCreate:e.bulkUpdate))return this.oneByOne(e,n,t,s,d);let l=s.map(a=>({"@odata.type":`Microsoft.Dynamics.CRM.${e.table}`,...a})),u=Buffer.from(le({Targets:l}),"utf8");for(let a=1;;a++){let i=0,c="",f=!1;try{let h=await this.dv.request("POST",`${e.entitySet}/Microsoft.Dynamics.CRM.${n}`,{body:u,headers:d,check:!1});if(i=h.status,c=h.text,i<300){if(n==="UpdateMultiple")return t.map(()=>({ok:!0}));let m=JSON.parse(c||"{}").Ids;return t.map((y,g)=>({ok:!0,...m?.[g]?{id:String(m[g]).toLowerCase()}:{}}))}f=i>=500&&!rt.test(c)}catch(h){if(!(h instanceof H)||h.status!==void 0)throw h;f=!0}if(bt.test(c)&&a<=8){let h=5*a;this.dv.progress.log(`${e.table}: ${n} is not ready for the table yet (SQL ${/Sql Number: (\d+)/.exec(c)?.[1]}); waiting ${h} s (${a} of 8)`),await lt(h*1e3);continue}if(rt.test(c)&&a<=5){this.dv.progress.log(`${e.table}: ${n} of ${S(t.length)} records gave a SQL error that can pass (${/Sql Number: (\d+)/.exec(c)?.[1]??"deadlock"}); sending it again (${a} of 5)`),await lt(500+Math.random()*1500);continue}return f&&n==="CreateMultiple"?(this.dv.progress.log(`${e.table}: ${n} of ${S(t.length)} records has no known result (status ${i||"none"}); reading the records again`),this.recheckCreates(e,t,s,d)):(this.dv.progress.log(`${e.table}: ${n} of ${S(t.length)} records failed (status ${i||"none"}); sending one request for each record to find the records that fail`),this.oneByOne(e,n,t,s,d))}}async recheckCreates(e,n,t,s){let o=await this.plan.keys.findByKeys(e.table,n.map(a=>a.fileKey).filter(Boolean)),l=n.map(()=>({ok:!1,error:"not known"})),u=[];if(n.forEach((a,i)=>{let c=o.get(a.key);c?l[i]={ok:!0,id:String(c[e.primaryId]).toLowerCase()}:u.push(i)}),u.length){let a=await this.oneByOne(e,"CreateMultiple",u.map(i=>n[i]),u.map(i=>t[i]),s);u.forEach((i,c)=>l[i]=a[c])}return l}async oneByOne(e,n,t,s,d){let o=t.map((u,a)=>{let i=s[a];if(n==="CreateMultiple")return{method:"POST",path:e.entitySet,body:new pe(le(i)),headers:d};let c={};for(let[f,h]of Object.entries(i))f!==e.primaryId&&(c[f]=h);return{method:"PATCH",path:`${e.entitySet}(${u.id})`,body:new pe(le(c)),headers:{...d,"If-Match":"*"}}}),l=[];for(let u=0;u<o.length;u+=100){let a=await this.sendBatch(o.slice(u,u+100));for(let i of a)l.push(this.outcome(i))}return l}async run(){let e=this.dv.progress,n=Date.now(),t=async(d,o)=>{let l=Date.now();await o(),e.log(`${d}: done (${((Date.now()-l)/1e3).toFixed(1)} s)`)};await this.prepare(),await t("phase 1, creates",()=>this.creates()),this.stopNow()||await t("phase 2, updates",()=>this.updates()),this.stopNow()||await t("phase 3, files",()=>this.files()),this.stopNow()||await t("phase 4, links",()=>this.links()),this.stopNow()||await t("phase 5, deletes",()=>this.deletes()),this.done.stopped&&(e.log("stopped after a failure (--continue-on-error continues)"),this.markNotRun());let s=this.done;return e.log(`writes: ${S(s.created.size)} created, ${S(s.updated.size)} updated, ${S(s.deleted.size)} deleted, ${S(s.deactivated.size)} deactivated, ${S(s.failed.size)} failed, ${S(s.skipped.size)} skipped (${((Date.now()-n)/1e3).toFixed(1)} s)`),this.done}stopNow(){return this.done.failures.some(e=>!vt.includes(e.action))&&!this.opts.continueOnError&&(this.done.stopped=!0),this.done.stopped}markNotRun(){let e="not run: the run stopped after a failure (--continue-on-error continues)";for(let n of this.plan.tables)for(let t of[...n.records,...n.unmanaged])this.done.created.has(t)||this.done.updated.has(t)||this.done.deleted.has(t)||this.done.deactivated.has(t)||this.done.failed.has(t)||this.done.skipped.has(t)||t.action==="unchanged"||t.action==="none"||this.fail(t,"skip",{error:e})}async creates(){let e=this.plan.tables.flatMap(l=>l.records.filter(u=>u.action==="create")),n=e.length,t=0,s=0,d=l=>{for(let u of l.lookups.values())if(u?.pending&&(this.done.failed.has(u.pending)||this.done.skipped.has(u.pending)))return u.pending;return null},o=l=>[...l.lookups].every(([u,a])=>!a||l.later.has(u)||this.targetId(a)!==null);for(;e.length&&!this.stopNow();){for(let c of e){let f=d(c);f&&this.fail(c,"skip",{error:`depends on ${f.t.table} ${ce(f.keyOut)}, which failed`})}e=e.filter(c=>!this.done.skipped.has(c));let l=e.filter(o);if(!l.length&&e.length){let c=$t(e);this.dv.progress.log(`${S(c.length)} circles of lookups (${S(c.reduce((f,h)=>f+h.size,0))} records): their lookups inside the circle wait for phase 2`);for(let f of c)for(let h of f)for(let[m,y]of h.lookups)y?.pending&&f.has(y.pending)&&this.targetId(y)===null&&h.later.set(m,y);if(l=e.filter(o),!l.length){for(let f of e)for(let[h,m]of f.lookups)m&&this.targetId(m)===null&&f.later.set(h,m);l=e.filter(o)}if(!l.length){for(let f of e)this.fail(f,"skip",{error:"a lookup of the match key waits for a record that is not created"});return}}let u=new Set(l);e=e.filter(c=>!u.has(c)),t++;let a=new Map;for(let c of l)a.set(c.t.table,(a.get(c.t.table)??0)+1);this.dv.progress.log(`create wave ${t}: ${[...a].map(([c,f])=>`${S(f)} ${c}`).join(", ")}; ${S(e.length)} wait for a lookup target`);let i=[];for(let c of this.plan.tables){let f=l.filter(m=>m.t.table===c.t.table),h=this.batchOf(c);for(let m=0;m<f.length;m+=h)i.push({tp:c,recs:f.slice(m,m+h)})}await z(i,this.opts.parallel,async({tp:c,recs:f})=>{let h=await this.bulk(c.m,"CreateMultiple",f,f.map(m=>this.createBody(m)),c.headers);s+=f.length,this.dv.progress.log(`created ${S(s)} of ${S(n)} (${c.t.table})`),f.forEach((m,y)=>{let g=h[y];g.ok?(m.id=m.id??g.id??m.values.get(c.m.primaryId)??null,this.done.created.add(m)):this.fail(m,"create",{...g.status!==void 0?{status:g.status}:{},...g.code?{code:g.code}:{},error:g.error??"failed"})})})}for(let l of e){if(this.done.failed.has(l)||this.done.skipped.has(l))continue;let u=d(l);this.fail(l,"skip",{error:u?`depends on ${u.t.table} ${ce(u.keyOut)}, which failed`:"not run: the import stopped after a failure (--continue-on-error continues)"})}}async updates(){let e=[];for(let s of this.plan.tables){let d=[],o=[];for(let l of s.records){let u=this.done.created.has(l);if(!(l.action==="update"||u&&(l.later.size||l.binaries.some(c=>c.column.kind==="image")))||!l.id||this.done.failed.has(l)||this.done.skipped.has(l))continue;let a=[...l.lookups.values(),...l.later.values()].find(c=>c?.pending&&!this.targetId(c));if(a?.pending){this.fail(l,"skip",{error:`depends on ${a.pending.t.table} ${ce(a.pending.keyOut)}, which failed`});continue}let i=this.updateBody(l,u);if(!i){!u&&!l.binaries.some(c=>c.column.kind==="file")&&this.done.updated.add(l);continue}i[s.m.primaryId]=l.id,(l.binaries.some(c=>c.column.kind==="image")?o:d).push([l,i])}for(let[l,u]of[[d,!1],[o,!0]]){let a=this.batchOf(s,u);for(let i=0;i<l.length;i+=a){let c=l.slice(i,i+a);e.push({tp:s,recs:c.map(([f])=>f),bodies:c.map(([,f])=>f)})}}}let n=e.reduce((s,d)=>s+d.recs.length,0);n&&this.dv.progress.log(`update ${S(n)} records in ${S(e.length)} requests, ${this.opts.parallel} at the same time`);let t=0;await z(e,this.opts.parallel,async({tp:s,recs:d,bodies:o})=>{let l=await this.bulk(s.m,"UpdateMultiple",d,o,s.headers);t+=d.length,this.dv.progress.log(`updated ${S(t)} of ${S(n)} (${s.t.table})`),d.forEach((u,a)=>{let i=l[a];i.ok?this.done.created.has(u)||this.done.updated.add(u):this.fail(u,(this.done.created.has(u),"update"),{...i.status!==void 0?{status:i.status}:{},...i.code?{code:i.code}:{},error:i.error??"failed"})})})}async files(){let e=[];for(let n of this.plan.tables)for(let t of n.records)if(!(!t.id||this.done.failed.has(t)||this.done.skipped.has(t)))for(let s of t.binaries)s.column.kind==="file"&&e.push({tp:n,r:t,b:s});e.length&&this.dv.progress.log(`upload or remove ${S(e.length)} files`),await z(e,this.opts.parallel,async({tp:n,r:t,b:s})=>{try{s.bytes?await qe(this.dv,n.m,t.id,s.column,s.bytes,s.name??s.column.name,n.headers):await Je(this.dv,n.m,t.id,s.column,n.headers),this.done.created.has(t)||this.done.updated.add(t)}catch(d){if(!(d instanceof H)||d.status===void 0)throw d;this.fail(t,"upload",{status:d.status,...d.code?{code:d.code}:{},error:`${s.column.name}: ${d.message}`})}})}async links(){for(let e of this.plan.links){let n=this.plan.tables.find(s=>s.t.table===e.rel.entity1);this.dv.progress.log(`${e.spec.name}: ${S(e.link.length)} links to add, ${S(e.unlink.length)} to remove`);let t=await at(this.dv,e,this.opts.parallel,n?.headers??{},async s=>(await this.sendBatch(s.map(o=>({method:o.method,path:o.path,body:o.body,headers:o.headers??null})))).map(o=>{let l=this.outcome(o);return{status:o.status,...l.error?{error:l.error}:{}}}));this.done.links.set(e.spec.name,{linked:t.linked,unlinked:t.unlinked,skipped:0,failed:t.failed.length,failures:t.failed,removed:t.removed});for(let s of t.failed){let d=s.failed?.startsWith("not run")?"skip":e.unlink.includes(s)?"unlink":"link";this.done.failures.push({table:e.spec.name,action:d,key:{from:s.fromOut,to:s.toOut},name:null,error:s.failed??"failed"})}}}async deletes(){for(let e of Rt(this.plan.tables)){let n=[...e.records,...e.unmanaged].filter(t=>(t.action==="delete"||t.action==="deactivate")&&t.id);if(n.length){this.dv.progress.log(`${e.t.table}: ${e.t.delete.action==="deactivate"?"deactivate":"delete"} ${S(n.length)} records`);for(let t of Mt(e,n))if(e.t.delete.action==="deactivate"){let d=e.m.columns.get("statecode").stateOf.get(1),o=this.batchOf(e),l=[];for(let u=0;u<t.length;u+=o)l.push(t.slice(u,u+o));await z(l,this.opts.parallel,async u=>{let a=u.map(c=>({[e.m.primaryId]:c.id,statecode:1,...d!==void 0?{statuscode:d}:{}})),i=await this.bulk(e.m,"UpdateMultiple",u,a,e.headers);u.forEach((c,f)=>{let h=i[f];h.ok?this.done.deactivated.add(c):this.fail(c,"deactivate",{...h.status!==void 0?{status:h.status}:{},error:h.error??"failed"})})})}else{let s=[];for(let d=0;d<t.length;d+=100)s.push(t.slice(d,d+100));await z(s,this.opts.parallel,async d=>{let o=await this.sendBatch(d.map(l=>({method:"DELETE",path:`${e.m.entitySet}(${l.id})`,headers:e.headers})));d.forEach((l,u)=>{let a=this.outcome(o[u]);a.ok||a.status===404?this.done.deleted.add(l):this.fail(l,"delete",{...a.status!==void 0?{status:a.status}:{},...a.code?{code:a.code}:{},error:a.error??"failed"})})})}}}}};function $t(r){let e=new Set(r),n=a=>{let i=[];for(let c of a.lookups.values())c?.pending&&e.has(c.pending)&&c.pending.id===null&&i.push(c.pending);return i},t=new Map,s=new Map,d=new Set,o=[],l=[],u=0;for(let a of r){if(t.has(a))continue;let i=[],c=f=>{t.set(f,u),s.set(f,u),u++,o.push(f),d.add(f),i.push({r:f,edges:n(f),i:0})};for(c(a);i.length;){let f=i[i.length-1];if(f.i<f.edges.length){let m=f.edges[f.i++];t.has(m)?d.has(m)&&s.set(f.r,Math.min(s.get(f.r),t.get(m))):c(m);continue}i.pop();let h=i[i.length-1];if(h&&s.set(h.r,Math.min(s.get(h.r),s.get(f.r))),s.get(f.r)===t.get(f.r)){let m=new Set;for(;;){let y=o.pop();if(d.delete(y),m.add(y),y===f.r)break}(m.size>1||n(f.r).includes(f.r))&&l.push(m)}}}return l}function ce(r){return r&&typeof r=="object"?Object.values(r).map(String).join(", "):String(r)}function St(r,e){let n=e?q(e,r):null,t=Y(n)?n.table:r.targets[0];return(t?r.navigation.get(t):void 0)??(r.navigation.size===1?[...r.navigation.values()][0]:r.name)}function Rt(r){let e=new Set(r.map(o=>o.t.table)),n=new Map;for(let o of r){let l=new Set;for(let u of o.t.columns){let a=o.m.columns.get(u.name);if(a?.kind==="lookup")for(let i of a.targets)i!==o.t.table&&e.has(i)&&l.add(i)}n.set(o.t.table,l)}let t=[],s=new Set,d=(o,l)=>{if(!(s.has(o.t.table)||l.has(o.t.table))){l.add(o.t.table);for(let u of r)n.get(u.t.table)?.has(o.t.table)&&d(u,l);s.add(o.t.table),t.push(o)}};for(let o of r)d(o,new Set);return t}function Mt(r,e){let n=r.t.columns.map(a=>r.m.columns.get(a.name)).filter(a=>!!a&&a.kind==="lookup"&&a.targets.includes(r.t.table));if(!n.length)return[e];let t=new Set(e.map(a=>a.id)),s=new Map;for(let a of e){let i=[];for(let c of n){let f=a.row?q(a.row,c):null;Y(f)&&t.has(f.id)&&i.push(f.id)}s.set(a.id,i)}let d=new Map,o=(a,i)=>{if(i.has(a))return 0;i.add(a);let c=0;for(let f of s.get(a)??[])c=Math.max(c,o(f,i)+1);return c};for(let a of e)d.set(a.id,o(a.id,new Set));let l=Math.max(...d.values()),u=[];for(let a=l;a>=0;a--){let i=e.filter(c=>d.get(c.id)===a);i.length&&u.push(i)}return u}import{existsSync as ft,readdirSync as Ot,readFileSync as Pt,statSync as pt}from"node:fs";import{join as ht}from"node:path";function Ct(r){return De(r??null)}function Tt(r,e){let n={},t=e.bypassPlugins??(r.bypass.plugins==="none"?null:r.bypass.plugins),s=e.bypassSteps??r.bypass.steps,d={sync:"CustomSync",async:"CustomAsync",all:"CustomSync,CustomAsync"};return t&&d[t]&&(n["MSCRM.BypassBusinessLogicExecution"]=d[t]),s.length&&(n["MSCRM.BypassBusinessLogicExecutionStepIds"]=s.join(",")),r.bypass.flows&&(n["MSCRM.SuppressCallbackRegistrationExpanderJob"]="true"),n}async function we(r,e,n){let t=r.progress,s=tt(e),d=et(e,n.overlay,n.noOverlay);t.log(`import ${e}: ${s.tables.length} schema files${d?`, overlay ${d}`:""}${n.check?", --check":""}`);let o=new Ye(r,s);await j(t,"read the metadata",()=>o.load(),()=>`${S(o.tables.size)} tables`);let l=new Qe(o,r),u=new Xe(l),a=[],i=[],c=n.only?new Set(n.only.map(p=>p.toLowerCase())):null,f=o.dataTables();if(c){let p=new Set([...f.map(v=>v.table),...s.relationships.map(v=>v.name.toLowerCase())]),k=[...c].filter(v=>!p.has(v));if(k.length)throw K("usage",`--only: the schema has no table or relationship '${k[0]}'`)}let h=f.filter(p=>!c||c.has(p.table)),m=[],y=[],g=[],$=new Map;for(let p of h){let k=o.meta(p.table),v=Date.now(),M=Ne(e,p.table,m);if(M&&n.purpose!=="delete"&&Ae(e,M,m),M&&t.log(`read ${M.file}: ${S(M.records.length)} records (${((Date.now()-v)/1e3).toFixed(1)} s)`),!M){m.some(b=>b.startsWith(`${X}/${p.table}`))||m.push(`${X}/${p.table}.yaml: the table ${p.table} is in the schema and has no data file; run: ppdo-cli dv data export`);continue}let x=Ee(M.header,Fe(p,k.primaryId));x.length&&y.push(`${M.file}: ${x.join("; ")}`);let E={t:p,m:k,records:[],unmanaged:[],missingLines:0,headers:Tt(p,n)},w=new Map,O=[k.primaryId];for(let b of M.records){let P=b.file+(M.header.layout==="table"?` record ${b.index+1}`:""),C;try{C=await u.recordKey(p.table,b.values)}catch(N){if(N instanceof A){m.push(`${P}: ${N.message}`);continue}throw N}if(w.has(C.key)){m.push(`${P}: two records have the same GUID (${C.key.slice(2)})`);continue}if("$deleted"in b.values){m.push(`${P}: $deleted is not in a data file since issue 11; the deletion log in data/.deleted keeps deletes (run: ppdo-cli dv data export)`);continue}let D={t:p,m:k,src:b,key:C.key,fileKey:C,keyOut:Lt(O,b.values),name:ct(k,b.values),logged:!1,row:null,inScope:!1,id:null,action:"none",values:new Map,lookups:new Map,later:new Map,changes:{},binaries:[],overlay:new Set,nullsIgnored:0};{let N=!1;for(let _ of p.columns){if(!(_.name in b.values)){N=!0;continue}let ie=k.columns.get(_.name);if((_.name==="statecode"||_.name==="statuscode")&&b.values[_.name]===null&&m.push(`${P}: ${_.name} cannot be null`),!(ie.kind==="lookup"||ie.kind==="file"||ie.kind==="image"))try{Z(b.values[_.name],ie)}catch(fe){if(fe instanceof A)m.push(`${P}: ${fe.message}`);else throw fe}}N&&E.missingLines++}w.set(C.key,D),E.records.push(D)}if(p.delete.mode!=="off"){let b=Ge(e,p.table,m);if(b)for(let P of b.entries){let C={table:p.table,key:"g:"+P.id,parts:[{col:k.primaryId,value:P.id}]};if(w.has(C.key)){a.push(`${p.table} ${P.id}: the record is in the data file and in the deletion log; the import uses the data file and does not delete it`);continue}let D={[k.primaryId]:P.id};k.primaryName&&typeof P.name=="string"&&(D[k.primaryName]=P.name);let N={t:p,m:k,src:{file:b.file,index:P.index,values:D},key:C.key,fileKey:C,keyOut:{[k.primaryId]:P.id},name:ct(k,D),logged:!0,row:null,inScope:!1,id:null,action:"none",values:new Map,lookups:new Map,later:new Map,changes:{},binaries:[],overlay:new Set,nullsIgnored:0};w.set(C.key,N),E.records.push(N)}}$.set(p.table,w),g.push(E)}if(m.length)throw K("data_invalid","the data files are not valid",m);if(y.length)throw V("schema_mismatch","a data file header does not agree with the schema; the schema changed after the export",y,"run: ppdo-cli dv data export <folder> against the source environment, and commit the result");for(let p of g)p.missingLines&&a.push(`${p.t.table}: ${p.missingLines} records have no line for one or more columns of the schema; the import does not change those columns`);xt(e,s,a),d&&await Dt(e,d,s,u,g,$,a);let I=new Map;await z(g,4,async p=>{I.set(p.t.table,await j(t,`read the target ${p.t.table}`,()=>ot(r,o,l,p.t),k=>`${S(k.length)} records in the scope`))});let R=new Map;for(let p of g){let k=I.get(p.t.table)??[];await l.seed(p.t.table,k);let v=new Map;for(let M of k)v.set("g:"+String(M[p.m.primaryId]).toLowerCase(),M);R.set(p.t.table,v)}for(let p of g){let k=R.get(p.t.table);for(let v of p.records){let M=k.get(v.key);M&&(v.row=M,v.inScope=!0,v.id=String(M[p.m.primaryId]).toLowerCase())}}await z(g,4,async p=>{if(!p.t.filter&&!p.t.fetchXmlFilter)return;let k=p.records.filter(x=>!x.row&&x.fileKey);if(!k.length)return;let v=await nt(l,p.t,p.m),M=await j(t,`read ${S(k.length)} records of ${p.t.table} that are not in the scope, by their GUID`,()=>l.findByKeys(p.t.table,k.map(x=>x.fileKey),v),x=>`${S(x.size)} found`);for(let x of k){let E=M.get(x.key);E&&(x.row=E,x.id=String(E[p.m.primaryId]).toLowerCase())}});let L=n.purpose==="delete";if(L||await j(t,"resolve the lookups",()=>Ft(l,u,g,$,a,m)),m.length)throw V("unresolved_lookup","a lookup has no target in the environment",m,"add the target to the environment or to the data, or set missingLookup: skip for the column");for(let p of g){Et(p,R.get(p.t.table),a);let k=v=>p.records.concat(p.unmanaged).filter(M=>M.action===v).length;t.log(`compare ${p.t.table}: ${S(k("create"))} to create, ${S(k("update"))} to update, ${S(k("delete")+k("deactivate"))} to delete or deactivate, ${S(k("unchanged"))} unchanged`)}if(L||await j(t,"compare the files and images",()=>Nt(r,e,g,m)),m.length){let p=m[0].startsWith("[file_too_large]")?"file_too_large":m[0].startsWith("[file_name_unsupported]")?"file_name_unsupported":"file_missing";throw K(p,"a file of a file column or an image column cannot be imported",m.map(k=>k.replace(/^\[[a-z_]+\] /,"")))}let F=s.relationships.filter(p=>!c||c.has(p.name.toLowerCase())),T=[];for(let p of F){let k=L?[]:m,v=await j(t,`compare the links of ${p.name}`,()=>it(r,e,o,l,u,p,$,R,k,a),M=>M?`${S(M.link.length)} to link, ${S(M.unlink.length)} to unlink, ${S(M.unchanged)} unchanged`:"none");v&&T.push(v)}if(m.length)throw V("unresolved_lookup","a link has no target in the environment",m);let B=p=>p.action==="delete"||p.action==="deactivate";if(L){for(let p of g)for(let k of[...p.records,...p.unmanaged])B(k)||(k.action!=="none"&&(k.action="unchanged"),k.values.clear(),k.lookups.clear(),k.later.clear(),k.binaries=[],k.changes={});for(let p of T)p.link=[]}else{let p=0,k=0;for(let v of g)for(let M of[...v.records,...v.unmanaged])B(M)&&(M.action="none",delete M.reason,p++);for(let v of T)k+=v.unlink.length,v.unlink=[];(p||k)&&a.push(`the delete modes give ${p} records to delete or deactivate and ${k} links to remove; the import never deletes: run ppdo-cli dv data delete`)}for(let p of g){let k=p.records.filter(v=>v.action==="delete"||v.action==="deactivate").length+p.unmanaged.filter(v=>v.action==="delete"||v.action==="deactivate").length;k&&p.t.delete.action==="delete"&&i.push(`${p.t.table}: ${k} deletes`),k&&p.t.delete.action==="delete"&&p.m.cascades.length&&a.push(`${p.t.table}: a delete also deletes the child records of these relationships (cascade): ${p.m.cascades.join(", ")}`)}for(let p of T)p.unlink.length&&i.push(`${p.spec.name}: ${p.unlink.length} link removals`);let ue=g.filter(p=>Object.keys(p.headers).length&&[...p.records,...p.unmanaged].some(k=>k.action!=="unchanged"&&k.action!=="none"));for(let p of ue)i.push(`${p.t.table}: bypass`);if(!n.check&&i.length&&r.client.target.mode!=="full")throw new Q(`blocked: the plan has requests that need mode 'full' (${i.join("; ")}); mode is '${r.client.target.mode}'`,{service:"dataverse",code:"blocked",hint:Re(r.client.target)});n.check&&i.length&&r.client.target.mode!=="full"&&a.push(`a run without --check needs mode 'full' for: ${i.join("; ")}`);for(let p of a)t.log(`warning: ${p}`);return{schema:s,model:o,keys:l,overlay:d,tables:g,links:T,warnings:a,needsFull:i}}function Lt(r,e){let n={};for(let t of r)n[t]=e[t]??null;return n}function ct(r,e){let n=r.primaryName?e[r.primaryName]:void 0;return typeof n=="string"?n:n instanceof Ie?n.text:null}function xt(r,e,n){let t=ht(r,X);if(ft(t))for(let s of It(t)){if(!s.endsWith(".yaml"))continue;let d=s.slice(0,-5);e.byName.get(d)||n.push(`${X}/${s}: the schema has no table '${d}'; the import ignores the file`)}}function It(r){try{return pt(r).isDirectory()?Ot(r).sort():[]}catch{return[]}}async function Dt(r,e,n,t,s,d,o){let l=[],u=Ze(r,e,n,l);for(let a of u){let i=s.find(m=>m.t.table===a.table);if(!i)continue;let c=d.get(a.table),f=[i.m.primaryId],h=new Set;for(let m of a.records){let y=`${m.file} record ${m.index+1}`,g;try{g=await t.recordKey(a.table,m.values)}catch(R){if(R instanceof A){l.push(`${y}: ${R.message}`);continue}throw R}if(h.has(g.key)){l.push(`${y}: two records have the same GUID`);continue}h.add(g.key);let $=c.get(g.key);if(!$){l.push(`${y}: no record of the base file has the GUID ${g.key.slice(2)}`);continue}if($.logged){o.push(`${y}: the record is in the deletion log; the import ignores the overlay record`);continue}let I=Object.keys(m.values).filter(R=>!f.includes(R));I.length||l.push(`${y}: the record has no column to change`);for(let R of I){let L=i.t.columns.find(T=>T.name===R);if(R==="$deleted")continue;if(!L){l.push(`${y}: '${R}' is not in columns of the schema`);continue}let F=i.m.columns.get(R);if(F.kind==="file"||F.kind==="image"||re(i.t.table,R)){l.push(`${y}: '${R}' is a ${re(i.t.table,R)?"base64 file":F.kind} column; version 1 has no overlay value for it`);continue}if(F.kind!=="lookup")try{Z(m.values[R],F)}catch(T){if(T instanceof A)l.push(`${y}: ${T.message}`);else throw T;continue}$.src.values={...$.src.values,[R]:m.values[R]},$.overlay.add(R)}}}if(l.length)throw K("overlay_invalid",`the overlay '${e}' is not valid`,l)}async function Ft(r,e,n,t,s,d){let o=[];for(let c of n)for(let f of c.records)if(!(f.logged||!f.src))for(let h of c.t.columns){let m=c.m.columns.get(h.name);if(m.kind!=="lookup"||!(h.name in f.src.values))continue;let y=f.src.values[h.name];if(y===null||y===""){f.lookups.set(h.name,null);continue}try{o.push({rec:f,col:h,key:await e.lookupKey(m,y)})}catch(g){if(g instanceof A)d.push(`${f.src.file}: ${JSON.stringify(f.keyOut)}: ${g.message}`);else throw g}}let l=new Map,u=(c,f)=>`${c}|${f}`,a=async(c,f)=>{let h=f.filter(g=>!l.has(u(c,g.key)));if(!h.length)return;let m=t.get(c),y=[];for(let g of h){let $=m?.get(g.key);$?.id?l.set(u(c,g.key),{table:c,id:$.id,pending:null}):$&&!$.logged?l.set(u(c,g.key),{table:c,id:null,pending:$}):y.push(g)}if(y.length){await r.ensure(c,y.map(g=>g.key.slice(2)));for(let g of y){let $=r.get(c,g.key.slice(2));l.set(u(c,g.key),$?{table:c,id:$.id,pending:null}:null)}}},i=new Map;for(let c of o){let f=i.get(c.key.table);f||i.set(c.key.table,f=[]),f.push(c.key)}for(let[c,f]of i)await a(c,f);for(let c of o){let f=l.get(u(c.key.table,c.key.key))??null;if(f){c.rec.lookups.set(c.col.name,f);continue}let h=`${c.rec.t.table} ${JSON.stringify(c.rec.keyOut)} ${c.col.name}: no ${c.key.table} with the GUID ${c.key.key.slice(2)}`;c.col.missingLookup==="skip"?(s.push(`${h} (missingLookup: skip; the column is not written)`),c.rec.lookups.delete(c.col.name),c.rec.skippedLookups=(c.rec.skippedLookups??0)+1):d.push(h)}}function Et(r,e,n){let{t,m:s}=r,d=new Set(r.records.map(o=>o.key));for(let o of r.records){let l=o.src;if(o.logged){if(!o.row){o.action="none";continue}if(!o.inScope){o.action="none",t.delete.mode!=="off"&&n.push(`${t.table} ${JSON.stringify(o.keyOut)}: the record is in the deletion log, but it is not in the scope in the environment; the import does not delete it`);continue}if(t.delete.mode==="off"){o.action="none",n.push(`${t.table} ${JSON.stringify(o.keyOut)}: the record is in the deletion log, but the table has no delete mode; the import does not delete it`);continue}dt(o,t,"manifest");continue}if(!o.row){o.action="create";for(let i of t.columns){if(!(i.name in l.values))continue;let c=s.columns.get(i.name);if(c.kind==="file"||c.kind==="image"||c.kind==="lookup")continue;let f=Z(l.values[i.name],c);f===null&&i.nullValues==="ignore"||o.values.set(i.name,f)}o.values.set(s.primaryId,o.key.slice(2));for(let i of t.columns)s.columns.get(i.name).kind==="lookup"&&o.lookups.get(i.name)===null&&i.nullValues==="ignore"&&o.lookups.delete(i.name);continue}let u=o.row;if(t.write==="create"){o.action="unchanged",o.lookups.clear();continue}let a=new Map(o.lookups);o.lookups.clear();for(let i of t.columns){if(!(i.name in l.values)||i.write==="create")continue;let c=s.columns.get(i.name);if(c.kind==="file"||c.kind==="image")continue;let f=q(u,c),h=o.overlay.has(i.name)?{overlay:!0}:{};if(c.kind==="lookup"){if(!a.has(i.name))continue;let y=a.get(i.name)??null;if(y===null){if(f===null)continue;if(i.nullValues==="ignore"){o.nullsIgnored++;continue}o.lookups.set(i.name,null),o.changes[i.name]={from:ee(f),to:null,...h};continue}if(Y(f)&&y.id!==null&&f.id===y.id)continue;o.lookups.set(i.name,y),o.changes[i.name]={from:ee(f),to:y.id??`(new) ${JSON.stringify(y.pending?.keyOut)}`,...h};continue}let m=Z(l.values[i.name],c);if(!We(f,m)){if(m===null&&i.nullValues==="ignore"){o.nullsIgnored++;continue}o.values.set(i.name,m),o.changes[i.name]=re(t.table,i.name)?{from:ut(f),to:ut(m),...h}:{from:ee(f),to:ee(m),...h}}}o.action=o.values.size||o.lookups.size?"update":"unchanged"}for(let[o,l]of e){if(d.has(o))continue;let u=String(l[s.primaryId]).toLowerCase(),a=s.primaryName?l[s.primaryName]:null,i={t,m:s,src:null,key:o,fileKey:null,keyOut:{[s.primaryId]:u},name:typeof a=="string"?a:null,logged:!1,row:l,inScope:!0,id:u,action:"none",values:new Map,lookups:new Map,later:new Map,changes:{},binaries:[],overlay:new Set,nullsIgnored:0};t.delete.mode==="mirror"&&dt(i,t,"mirror"),r.unmanaged.push(i)}r.unmanaged.length&&t.delete.mode!=="mirror"&&n.push(`${t.table}: ${r.unmanaged.length} records are in the scope in the environment and are not in the data file (unmanaged)`)}function dt(r,e,n){if(e.delete.action==="deactivate"){let t=r.row?.statecode;if(t!=null&&String(t)!=="0"){r.action="none";return}r.action="deactivate"}else r.action="delete";r.reason=n}async function Nt(r,e,n,t){for(let s of n){let d=s.t.columns.filter(a=>{let i=s.m.columns.get(a.name);return i.kind==="file"||i.kind==="image"});if(!d.length)continue;let o=[];for(let a of s.records)if(!(!a.row||a.logged))for(let i of d){let c=q(a.row,s.m.columns.get(i.name));G(c)&&o.push(c.id)}let l=o.length?await je(r,o):new Map,u=[];for(let a of s.records)if(!(a.logged||a.action==="none"||!a.src))for(let i of d){if(!(i.name in a.src.values)||i.write==="create"&&a.row||s.t.write==="create"&&a.row)continue;let c=s.m.columns.get(i.name),f=a.src.values[i.name],h=a.row?q(a.row,c):null,m=`${a.src.file}: ${JSON.stringify(a.keyOut)} ${i.name}`;if(f===null){if(h===null)continue;if(i.nullValues==="ignore"){a.nullsIgnored++;continue}a.binaries.push({column:c,bytes:null,name:null}),a.changes[i.name]={from:G(h)?{name:h.name,size:l.get(h.id)?.size??null}:{size:null},to:null};continue}let y=Ct(f),g=y?.$file;if(!y||typeof g!="string"||!g){t.push(`[file_missing] ${m}: the value must be { $file: <name> }`);continue}let $=ht(e,he,s.t.table,g);if(!xe(g)||!ft($)){t.push(`[file_missing] ${m}: ${he}/${s.t.table}/${g} is not in the folder`);continue}let I=pt($).size;if(I>Ke){t.push(`[file_too_large] ${m}: ${g} is ${I} bytes; version 1 handles files to 40 MB`);continue}let R=c.kind==="file"?typeof y.name=="string"?y.name:g:null;if(R!==null&&_e(R)&&!zt){t.push(`[file_name_unsupported] ${m}: the file name '${R}' has a character that is not ASCII`);continue}u.push(async()=>{let L=Pt($);if(h!==null&&a.id){if(G(h)){let T=l.get(h.id);if(T&&T.size===L.length&&(T.name??h.name)===R){let B=await me(r,s.m,a.id,c);if(B&&B.equals(L))return}}else if(Ve(h)){let T=await me(r,s.m,a.id,c);if(T&&T.equals(L))return}}a.binaries.push({column:c,bytes:L,name:R});let F=G(h)?l.get(h.id)?.size??null:null;a.changes[i.name]=c.kind==="file"?{from:G(h)?{name:h.name,size:F}:null,to:{name:R,size:L.length}}:{from:h===null?null:{size:null},to:{size:L.length}}})}await z(u,8,a=>a());for(let a of s.records)a.binaries.length&&a.action==="unchanged"&&(a.action="update")}}function ut(r){return typeof r=="string"?{size:Buffer.from(r,"base64").length}:null}var zt=!0;function de(r){if(typeof r!="string")return null;let e=r.split(",").map(n=>n.trim()).filter(n=>n);return e.length?e:null}function oe(r,e,n,t,s){if(r==null)return s;let d=Number(r);if(!Number.isInteger(d)||d<n||d>t)throw new J(`argument ${e}: must be ${n} to ${t}`);return d}function se(r){let e=r.args.folder;if(typeof e!="string"||!e)throw new J("the following arguments are required: folder");return e}async function be(r,e,n){let t=typeof r.args.logFile=="string"?r.args.logFile:null,s=new Ue(r.verbose,t,e),d=r.log.bind(r);r.log=o=>{d(o),s.http(o)};try{let o=await n(s);o!==void 0&&s.raw("result",JSON.stringify(o,null,2))}catch(o){throw o instanceof H?s.raw("error",ve(o.envelope())):o instanceof Error&&s.raw("error",o.stack??o.message),o}finally{s.retries&&s.log(`${s.retries} requests were sent again (throttling, a time limit or a server error)`),s.log(`end (peak memory ${Math.round(Math.max(s.peakMemory,process.memoryUsage().rss)/1048576)} MB)`),s.close()}}async function Gn(r){let e=se(r),n=oe(r.args.parallel,"--parallel",1,16,8),t=!!r.args.check;await be(r,"dv data export",async s=>{let d=new W(r,await U(r),"R",s),o=await st(d,e,{only:de(r.args.only),check:t,parallel:n});if(await r.emit(o),t&&(o.tables.some(l=>l.written)||o.relationships.some(l=>l.written)||o.warnings.some(l=>l.startsWith("would remove"))))throw s.raw("result",JSON.stringify(o,null,2)),ae("out_of_date","one or more data files are out of date","run it again without --check to update the folder");return o})}var _t=/,/;function yt(r){let e=typeof r.args.bypassPlugins=="string"?r.args.bypassPlugins:null,n=typeof r.args.bypassStep=="string"?r.args.bypassStep:null,t=null;if(n){t=n.split(_t).map(d=>d.trim()).filter(d=>d);let s=t.find(d=>!Oe(d));if(s)throw new J(`--bypass-step takes plugin step ids, got '${s}'`);t=t.map(d=>d.toLowerCase())}return{plugins:e,steps:t}}function kt(r,e){let n={action:e,key:r.keyOut,name:r.name};return r.id&&e!=="create"&&(n.id=r.id),e==="update"&&(n.columns=r.changes),(e==="delete"||e==="deactivate")&&(n.reason=r.reason),n}function mt(r,e,n,t){let s={create:0,update:0,link:0,unchanged:0,unmanaged:0,skipped:0,failed:0},d=e.tables.map(l=>{let u={create:0,update:0,unchanged:0,unmanaged:0,skipped:0,failed:0},a=[],i=0,c=0;for(let f of[...l.records,...l.unmanaged]){if(c+=f.nullsIgnored,!f.src&&f.action==="none"){u.unmanaged++;continue}if(f.action==="unchanged"){u.unchanged++;continue}f.action!=="create"&&f.action!=="update"||(n?n.failed.has(f)?u.failed++:n.skipped.has(f)?u.skipped++:n.created.has(f)?u.create++:n.updated.has(f)&&u.update++:u[f.action]++,(t===null||i<t)&&(a.push(kt(f,f.action)),i++))}for(let f of Object.keys(u))s[f]+=u[f];return{table:l.t.table,...u,...c?{nulls_ignored:c}:{},changes:a}}),o=e.links.map(l=>{let u=n?.links.get(l.spec.name),a={name:l.spec.name,link:u?u.linked:l.link.length,unchanged:l.unchanged,skipped:u?u.skipped:0,failed:u?u.failed:0};s.link+=a.link,s.skipped+=a.skipped,s.failed+=a.failed;let i=[];for(let c of l.link){if(t!==null&&i.length>=t)break;i.push({action:"link",from:c.fromOut,to:c.toOut})}return{...a,changes:i}});return{folder:r,overlay:e.overlay,checked_only:n===null,summary:s,tables:d,relationships:o,failures:n?.failures??[],warnings:e.warnings}}function gt(r,e,n){let t={delete:0,deactivate:0,unlink:0,failed:0},s=e.tables.map(o=>{let l={delete:0,deactivate:0,failed:0},u=[];for(let a of[...o.records,...o.unmanaged])a.action!=="delete"&&a.action!=="deactivate"||(n?n.failed.has(a)?l.failed++:n.deleted.has(a)?l.delete++:n.deactivated.has(a)&&l.deactivate++:l[a.action]++,u.push(kt(a,a.action)));return t.delete+=l.delete,t.deactivate+=l.deactivate,t.failed+=l.failed,{table:o.t.table,mode:o.t.delete.mode,...l,changes:u}}),d=e.links.map(o=>{let l=n?.links.get(o.spec.name),u={name:o.spec.name,mode:o.spec.delete.mode,unlink:l?l.unlinked:o.unlink.length,failed:l?l.failed:0};return t.unlink+=u.unlink,t.failed+=u.failed,{...u,changes:o.unlink.map(a=>({action:"unlink",from:a.fromOut,to:a.toOut,reason:a.reason}))}});return{folder:r,checked_only:n===null,summary:t,tables:s,relationships:d,failures:n?.failures??[],warnings:e.warnings}}function jt(r,e,n,t,s){let d=[];for(let l of n.tables)for(let u of[...l.records,...l.unmanaged]){let a=t.deleted.has(u)?"delete":t.deactivated.has(u)?"deactivate":null;!a||!u.id||d.push({table:l.t.table,id:u.id,name:u.name,action:a,reason:u.reason})}let o=[];for(let[l,u]of t.links)for(let a of u.removed)o.push({relationship:l,from:a.from.id,to:a.to.id,reason:a.reason});return JSON.stringify({folder:r,environment:e,time:s,records:d,links:o},null,2)+`
3
+ `}function qt(r,e){Kt(At(r),{recursive:!0}),Bt(r,e,"utf8")}function wt(r,e,n){let t=r.failures.filter(s=>s.action!=="skip").length;if(r.failures.length)throw V("rows_failed",`${t} records failed and ${r.failures.length-t} were not sent`,[],"see failures in the output"+(e?"":"; --continue-on-error keeps going after a failure")+`; the ${n} can run again`)}async function Hn(r){let e=r.args,n=se(r),t=!!e.check,s=oe(e.batchSize,"--batch-size",1,1e3,100),d=oe(e.parallel,"--parallel",1,16,8),o=e.overlay,l=typeof o=="string"?o:null,u=o===!1,a=yt(r);await be(r,"dv data import",async i=>{let c=new W(r,await U(r),"R",i),f=await we(c,n,{only:de(e.only),overlay:l,noOverlay:u,purpose:"import",check:t,bypassPlugins:a.plugins,bypassSteps:a.steps}),h=Le(e);if(t){let g=mt(n,f,null,h);await r.emit(g),i.raw("result",JSON.stringify(g,null,2));let $=g.summary,I=($.create??0)+($.update??0)+($.link??0);if(I)throw ae("changes_pending",`the plan has ${I} changes`,"run it again without --check to apply the changes");return}i.log(`write the changes: --batch-size ${s}, --parallel ${d}${e.continueOnError?", --continue-on-error":""}`);let m=await new ne(c,f,{batchSize:s,parallel:d,continueOnError:!!e.continueOnError}).run(),y=mt(n,f,m,h);await r.emit(y),i.raw("result",JSON.stringify(y,null,2)),wt(m,!!e.continueOnError,"import")})}function Jt(r,e){let n=[`dv data delete in ${r}:`];for(let t of e.tables){let s=[...t.records,...t.unmanaged].filter(o=>o.action==="delete"||o.action==="deactivate");if(!s.length)continue;let d=t.t.delete.action==="deactivate"?"deactivate":"delete";n.push(` ${t.t.table}: ${d} ${s.length} records (mode ${t.t.delete.mode})`);for(let o of s.slice(0,20))n.push(` ${o.id} ${o.name??""} (${o.reason})`.trimEnd());s.length>20&&n.push(` ... and ${s.length-20} more (--check lists each one)`)}for(let t of e.links)t.unlink.length&&n.push(` ${t.spec.name}: remove ${t.unlink.length} links (mode ${t.spec.delete.mode})`);return n}async function Ut(r,e){if(!$e(e))throw new Q("dv data delete needs a confirmation: no person at a terminal can give it",{hint:"run it at a terminal, or give --yes (for a pipeline, after a review of --check)"});if((e??{stderr:process.stderr}).stderr.write(r.join(`
4
+ `)+`
5
+ Type 'delete' to confirm: `),(await Se((e??{stdin:process.stdin}).stdin)).trim()!=="delete")throw new Q("not confirmed; nothing was deleted")}async function Qn(r){let e=r.args,n=se(r),t=!!e.check,s=oe(e.batchSize,"--batch-size",1,1e3,100),d=oe(e.parallel,"--parallel",1,16,8),o=typeof e.deleteLogFile=="string"?e.deleteLogFile:null,l=yt(r);await be(r,"dv data delete",async u=>{let a=new W(r,await U(r),"R",u),i=await we(a,n,{only:de(e.only),overlay:null,noOverlay:!0,purpose:"delete",check:t,bypassPlugins:l.plugins,bypassSteps:l.steps}),c=gt(n,i,null),f=c.summary,h=(f.delete??0)+(f.deactivate??0)+(f.unlink??0);if(t){if(await r.emit(c),u.raw("result",JSON.stringify(c,null,2)),h)throw ae("changes_pending",`the plan has ${h} deletes, deactivates and link removals`,"run it again without --check to delete them");return}if(!h)return await r.emit(c),c;e.yes?u.log("--yes: no confirmation"):await Ut(Jt(a.origin,i)),u.log(`delete: --batch-size ${s}, --parallel ${d}`);let m=new ne(a,i,{batchSize:s,parallel:d,continueOnError:!0}),y;try{y=await m.run()}finally{o&&qt(o,jt(n,a.origin,i,m.done,new Date().toISOString()))}let g=gt(n,i,y);await r.emit(g),u.raw("result",JSON.stringify(g,null,2)),wt(y,!0,"delete")})}async function Xn(r){let{runConvert:e}=await import("./convert-ILMJ2HHN.js"),n=r.args.source;if(typeof n!="string"||!n)throw new J("the following arguments are required: source");let t=typeof r.args.cmtSchema=="string"?r.args.cmtSchema:null,s=new W(r,await U(r),"R");await r.emit(await e(s,n,se(r),{cmtSchema:t,force:!!r.args.force}))}async function Yn(r){let{runInit:e}=await import("./init-X2VEK4T2.js"),n=de(r.args.table);if(!n)throw new J("the following arguments are required: --table");let t=new W(r,await U(r));await r.emit(await e(t,se(r),n))}export{Ut as confirmDelete,Xn as convertData,Qn as deleteData,jt as deleteLog,gt as deleteOutput,Jt as deleteSummary,Gn as exportData,Hn as importData,mt as importOutput,Yn as initData};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
+ import{e as Z}from"./chunk-VC7ADQ6E.js";import"./chunk-T4IH34D7.js";import{G as T,H as Q,a as B,d as b,e as q,f as u,g as L,h as E,k as _,l as H,n as J,s as K,t as W,u as X,v as P,x as V,y as Y,z as k}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import{a as v,b as O,d as I,e as N}from"./chunk-FOEBNCSD.js";import"./chunk-BALEFXOL.js";import"./chunk-J4R6QXW7.js";import{b as F}from"./chunk-2IUXH534.js";import{e as A}from"./chunk-S4KF5Z3S.js";import{a as z,b as R,d as U}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{writeFileSync as dt}from"node:fs";import{basename as ut}from"node:path";import{crc32 as mt,deflateRawSync as pt}from"node:zlib";var it=500,tt=25,G=["required","dependent"],rt=["componenttype","componentobjectid","componentparentid","componentbasesolutionid"],ft=["dependencyid","dependencytype",...G.flatMap(t=>rt.map(e=>t+e))].join(","),et="($select=_topsolutionid_value)",gt=`requiredcomponentnodeid${et},dependentcomponentnodeid${et}`,yt=["PicklistAttributeMetadata","MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata","BooleanAttributeMetadata"],at=[["Attributes","columns"],["Keys","keys"],["OneToManyRelationships","relationships"],["ManyToOneRelationships","relationships"],["ManyToManyRelationships","relationships"]];function ht(t){let e=b(t.solution)||b(t.required)||b(t.dependent);if(!e&&t.all&&!t.includeSystem)throw new R("--all with no filter reads every dependency row in the environment",{hint:"filter with --solution, --required or --dependent, or pass --include-system"});if(t.type!==void 0&&t.type!==null&&!e)throw new R("--type needs --solution, --required or --dependent")}function wt(t,e){let n=e.filter(o=>!O(o));if(n.length)throw new R(`not a component id: '${n[0]}'`);let s=e.map(o=>`'${I(o)}'`).join(",");return`Microsoft.Dynamics.CRM.In(PropertyName='${t}',PropertyValues=[${s}])`}function bt(t,e,n=it,s=[]){let o=[];for(let r of G){let m=r==="required"?"dependent":"required",g=e!=null?` and ${m}componenttype eq ${Math.trunc(e)}`:"",y=t[r]??[];for(let p=0;p<y.length;p+=n)o.push(wt(`${r}componentobjectid`,y.slice(p,p+n))+g);for(let p of s){if(!O(p))throw new R(`not a solution id: '${p}'`);o.push(`${r}componentbasesolutionid eq ${I(p)}${g}`)}}return o}var Tt=["membership","base-solution","component"];function $t(t,e,n){return n?"component":e.has(String(q(u(t,"requiredcomponentobjectid"),"")).toLowerCase())||e.has(String(q(u(t,"dependentcomponentobjectid"),"")).toLowerCase())?"membership":"base-solution"}function nt(t,e,n=null){let s={dependencyid:u(t,"dependencyid"),dependencytype:u(t,"dependencytype")};n&&(s.found_by=n);for(let o of G){for(let g of rt)s[o+g]=u(t,o+g);let r=u(t,o+"componentbasesolutionid"),m=u(L(u(t,o+"componentnodeid")),"_topsolutionid_value");s[o+"componentbasesolution"]=e.get(String(q(r,"")).toLowerCase())??null,s[o+"componenttopsolutionid"]=m,s[o+"componenttopsolution"]=e.get(String(q(m,"")).toLowerCase())??null}return s}function Rt(t){let e={};for(let[n,s]of at){let o=e[s]??=[];for(let r of E(u(t,n)))b(u(r,"MetadataId"))&&o.push(r.MetadataId)}return e}function St(t){return t.filter(e=>b(u(L(u(e,"OptionSet")),"MetadataId"))&&!b(e.OptionSet.IsGlobal)).map(e=>e.OptionSet.MetadataId)}function Mt(t){let e=new Set;for(let n of E(u(t,"ManyToManyRelationships")))b(u(n,"IntersectEntityName"))&&e.add(n.IntersectEntityName);return _(e,n=>n)}async function xt(t,e,n){let{find:s}=await import("./solution-CNBNIS7Z.js"),o=new Set,r=new Set,m=[];for(let l of n){let c=await s(t,e,l);b(u(c,"ismanaged"))&&m.push(c.solutionid);let[a]=await k(t,e,"solutioncomponents",[["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${c.solutionid}`]],null,null);for(let i of a)o.add(String(i.objectid).toLowerCase()),u(i,"componenttype")===1&&u(i,"rootcomponentbehavior")===0&&r.add(String(i.objectid).toLowerCase())}let g=o.size,y={columns:0,keys:0,relationships:0,intersect_tables:0,choices:0,forms:0,views:0},p=[],h=at.map(([l])=>`${l}($select=MetadataId${l.startsWith("ManyToMany")?",IntersectEntityName":""})`).join(","),f=(l,c)=>{let a=H(c.map(i=>i.toLowerCase()).filter(i=>!o.has(i)));for(let i of a)o.add(i);y[l]=(y[l]??0)+a.length},C=[],x=[...r].map(l=>[`EntityDefinitions(${l})`,!1]),$=new Set;for(;x.length;){let[l,c]=x.shift(),a;try{a=P(await X(t,e,"GET",l,{params:[["$select","LogicalName"],["$expand",h]]}))}catch(i){if(i instanceof U){C.push(l);continue}throw i}if(!$.has(a.LogicalName)){$.add(a.LogicalName),p.push(a.LogicalName),c&&f("intersect_tables",[a.MetadataId]);for(let[i,d]of Object.entries(Rt(a)))f(i,d);for(let i of Mt(a))$.has(i)||x.push([`EntityDefinitions(LogicalName=${N(v(i,"table"))})`,!0])}}let w=p.flatMap(l=>yt.map(c=>({method:"GET",path:`EntityDefinitions(LogicalName=${N(l)})/Attributes/Microsoft.Dynamics.CRM.${c}?$select=LogicalName&$expand=OptionSet($select=MetadataId,IsGlobal)`})));for await(let[,l,c]of Q(t,e,w,!1,!0))l.forEach((a,i)=>{let d=c[i];if(!d||d.status!==200)throw new z(`couldn't list the choices of a table: ${a.path}`,{service:"dataverse",...d?{status:d.status}:{},hint:(typeof d?.body=="string"?d.body:Z(d?.body??null)).slice(0,300)});f("choices",St(E(u(L(d.body),"value"))))});for(let[l,c,a,i]of[["systemforms","objecttypecode","formid","forms"],["savedqueries","returnedtypecode","savedqueryid","views"]])for(let d=0;d<p.length;d+=tt){let S=p.slice(d,d+tt).map(j=>`${c} eq ${N(v(j,"table"))}`).join(" or "),[M]=await k(t,e,l,[["$select",a],["$filter",S]],null,null);f(i,M.map(j=>j[a]))}return[[...o],{solutions:n,components:g,full_tables:r.size,added:y,managed:m,missing_tables:C}]}function ct(t){return[["$select",ft],["$expand",gt],...t?[["$filter",t]]:[]]}async function jt(t,e,n){let s=V(`odata.maxpagesize=${n?Math.min(B,n):B}`),o=[];for await(let r of Y(t,"dependencies",e,s))if(o=o.concat(E(P(r).value)),n!==null&&o.length>=n)break;return o}async function qt(t,e,n){let s=new Map;for(let o of e){for(let r of await jt(t,ct(o),n===null?null:n+1-s.size))s.has(r.dependencyid)||s.set(r.dependencyid,r);if(n!==null&&s.size>n)return[s,!0]}return[s,!1]}async function Et(t,e,n,s,o,r){let[m]=await k(t,e,"solutions",[["$select","solutionid,uniquename"]],null,null),g=new Map(m.map(h=>[String(h.solutionid).toLowerCase(),h.uniquename])),y=new Set;if(o)for(let h of Object.values(s))for(let f of h??[])y.add(f.toLowerCase());let p=Object.keys(s).length>0;return _(n.keys(),h=>h).map(h=>{let f=n.get(h);return p?nt(f,g,$t(f,y,r)):nt(f,g)})}function ot(t,e){if(t==null)return null;let n=t;if(n.length<2)throw new R(`argument ${e}: expected 2 arguments`,{hint:"run: ppdo-cli dv dependency list --help"});if(n.length>2)throw new R(`unrecognized arguments: ${n.slice(2).join(" ")}`,{hint:"run: ppdo-cli --help"});return[n[0],n[1]]}async function Dt(t){let e=t.args;K(e,{solution:"--solution",required:"--required",dependent:"--dependent"},!1,"dv dependency list");let n=ot(e.required,"--required"),s=ot(e.dependent,"--dependent");ht(e);let o=await W(t);F(t,o,"GET","dependencies",null);let r={},m=[],g=T(e.solution),y=await o.lookups(async()=>{if(g){let{names:c}=await import("./solution-CNBNIS7Z.js"),[a,i]=await xt(t,o,c(g));m=i.managed??[],delete i.managed,i.base_solution_filter=m.length>0,r=i;let d=Object.values(i.added).reduce((j,lt)=>j+lt,0);i.missing_tables.length&&A(`${i.missing_tables.length} table(s) in the solution no longer exist: `+i.missing_tables.join(", "));let S=i.components,M=i.full_tables;return A(`${S} component${S!==1?"s":""} in ${i.solutions.join(", ")}`+(d?`, plus ${d} subcomponents of ${M} full table${M!==1?"s":""}`:"")),{required:a,dependent:a}}if(n||s){let c=n?"required":"dependent",[a,i]=n??s,{componentId:d,componentType:S}=await import("./lifecycle-2F7MF6EP.js"),M=await S(t,o,a);return{[c]:[await d(t,o,M,i,a)]}}return{}},["$batch"]),p=typeof e.type=="number"?e.type:null,h=Object.keys(y).length?bt(y,p,it,m):[null];if(t.dryRun){await t.emit({dry_run:!0,...r,requests:h.map(c=>({method:"GET",path:"dependencies",params:Object.fromEntries(ct(c))}))});return}let f=J(e),[C,x]=await qt(o,h,f),$=x,w=await Et(t,o,C,y,!!g,!!(n||s));if(g){let c=new Map;for(let a of w)c.set(a.found_by,(c.get(a.found_by)??0)+1);r.found_by=Object.fromEntries(_(c.entries(),([a])=>a))}f!==null&&w.length>f&&($=!0,w=w.slice(0,f)),$&&A(`showing the first ${f} rows; pass --limit n or --all for more`);let l=T(e.save);l?(await Ct(l,w),await t.emit({saved:l,rows:w.length,truncated:$,...r})):await t.emit(w)}function D(t){if(Array.isArray(t))return"["+t.map(e=>D(e===void 0?null:e)).join(", ")+"]";if(typeof t=="object"&&t!==null){let e=Object.entries(t).filter(([,s])=>s!==void 0);return"{"+_(e,([s])=>s).map(([s,o])=>`${st(s)}: ${D(o)}`).join(", ")+"}"}return typeof t=="string"?st(t):JSON.stringify(t)??"null"}function st(t){return JSON.stringify(t).replace(/[^\x00-\x7f]/g,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function _t(t,e){let n=ut(e);n.endsWith(".gz")&&(n=n.slice(0,-3));let s=Buffer.from(n,"latin1"),o=Buffer.from([31,139,8,s.length?8:0,0,0,0,0,2,255]),r=Buffer.alloc(8);r.writeUInt32LE(mt(t)>>>0,0),r.writeUInt32LE(t.length%4294967296,4);let m=[o];return s.length&&m.push(s,Buffer.from([0])),m.push(pt(t,{level:9,memLevel:8}),r),Buffer.concat(m)}async function Ct(t,e){let n=Buffer.from(e.map(s=>D(s)+`
3
+ `).join(""),"ascii");dt(t,t.toLowerCase().endsWith(".gz")?_t(n,t):n)}export{it as CHUNK,Tt as FOUND_BY,tt as NAME_CHUNK,G as SIDES,ht as checkScope,bt as filters,$t as foundBy,wt as inFilter,Mt as intersects,Dt as list,St as localChoices,nt as row,Ct as save,Rt as subcomponents};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
- import{b as u,d}from"./chunk-4KP27OCL.js";import{c as l,g as a}from"./chunk-J4R6QXW7.js";import"./chunk-5SBBTR3Y.js";import"./chunk-WMDKJRDC.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var s="globaldisco.crm.dynamics.com",v={0:"production",5:"sandbox",6:"sandbox-free",7:"preview",9:"test-drive",11:"email-trial",12:"default",13:"developer",14:"trial",15:"teams"},i=class extends u{name="discovery";scope(){return`https://${s}//.default`}url(t,e){let n=t.includes("://")?t:`https://${s}/${t.replace(/^\/+/,"")}`;return e&&e.length&&(n+=(n.includes("?")?"&":"?")+l(e)),n}allowed(t){let e=a(t);return e.scheme==="https"&&e.host===s}};async function w(r,t){let e=new i,{getToken:n}=await import("./provider-FN7TXWRE.js"),o=(await new d(e,r,p=>n(t,e.scope(),{forceRefresh:p,log:m=>r.log(m)})).request("GET","api/discovery/v2.0/Instances")).json(),c=o&&typeof o=="object"?o.value:null;return Array.isArray(c)?c:[]}export{i as Discovery,s as HOST,v as ORG_TYPES,w as instances};
2
+ import{b as u,d}from"./chunk-GY6BUIDP.js";import{c as l,g as a}from"./chunk-J4R6QXW7.js";import"./chunk-2IUXH534.js";import"./chunk-TCLZ4XM6.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var s="globaldisco.crm.dynamics.com",v={0:"production",5:"sandbox",6:"sandbox-free",7:"preview",9:"test-drive",11:"email-trial",12:"default",13:"developer",14:"trial",15:"teams"},i=class extends u{name="discovery";scope(){return`https://${s}//.default`}url(t,e){let n=t.includes("://")?t:`https://${s}/${t.replace(/^\/+/,"")}`;return e&&e.length&&(n+=(n.includes("?")?"&":"?")+l(e)),n}allowed(t){let e=a(t);return e.scheme==="https"&&e.host===s}};async function w(r,t){let e=new i,{getToken:n}=await import("./provider-D7DMMAS6.js"),o=(await new d(e,r,p=>n(t,e.scope(),{forceRefresh:p,log:m=>r.log(m)})).request("GET","api/discovery/v2.0/Instances")).json(),c=o&&typeof o=="object"?o.value:null;return Array.isArray(c)?c:[]}export{i as Discovery,s as HOST,v as ORG_TYPES,w as instances};