sandforge 0.0.0-stage → 1.79.0

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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -2
  3. package/THIRD-PARTY-NOTICES.md +1624 -0
  4. package/bin/sandforge-autopilot.mjs +12 -0
  5. package/bin/sandforge-backup.mjs +12 -0
  6. package/bin/sandforge-checkpoint.mjs +12 -0
  7. package/bin/sandforge-cleanup.mjs +12 -0
  8. package/bin/sandforge-clone.mjs +12 -0
  9. package/bin/sandforge-compare.mjs +12 -0
  10. package/bin/sandforge-dataops.mjs +12 -0
  11. package/bin/sandforge-empty.mjs +12 -0
  12. package/bin/sandforge-env.mjs +12 -0
  13. package/bin/sandforge-frozen.mjs +12 -0
  14. package/bin/sandforge-mcp.mjs +12 -0
  15. package/bin/sandforge-monitor.mjs +12 -0
  16. package/bin/sandforge-seed.mjs +12 -0
  17. package/bin/sandforge-sync.mjs +12 -0
  18. package/bin/sandforge.mjs +12 -0
  19. package/lib/catalogue.en.json +1 -0
  20. package/lib/chunk-2BVTCNWA.mjs +7 -0
  21. package/lib/chunk-2S5OMIIA.mjs +7 -0
  22. package/lib/chunk-2YIV2OB2.mjs +7 -0
  23. package/lib/chunk-342FN7AO.mjs +9 -0
  24. package/lib/chunk-36U7IQ6Y.mjs +25 -0
  25. package/lib/chunk-3CA767QB.mjs +7 -0
  26. package/lib/chunk-3DCUADVK.mjs +7 -0
  27. package/lib/chunk-3F5YMM2F.mjs +7 -0
  28. package/lib/chunk-3OHPD72J.mjs +9 -0
  29. package/lib/chunk-3RYLICRX.mjs +7 -0
  30. package/lib/chunk-3SRXFZSD.mjs +7 -0
  31. package/lib/chunk-42RER7V4.mjs +14 -0
  32. package/lib/chunk-4GL773D5.mjs +7 -0
  33. package/lib/chunk-4HFRHFGQ.mjs +7 -0
  34. package/lib/chunk-4HW535YJ.mjs +7 -0
  35. package/lib/chunk-4NAHW2D3.mjs +7 -0
  36. package/lib/chunk-4SNDMJP2.mjs +7 -0
  37. package/lib/chunk-4TLYUZD5.mjs +7 -0
  38. package/lib/chunk-4U6NXJNL.mjs +7 -0
  39. package/lib/chunk-4XZ5YT5O.mjs +7 -0
  40. package/lib/chunk-55HEMHEG.mjs +7 -0
  41. package/lib/chunk-57VHUYNG.mjs +10 -0
  42. package/lib/chunk-5AJRHRXA.mjs +20 -0
  43. package/lib/chunk-5CD257T7.mjs +7 -0
  44. package/lib/chunk-5HMAPZBV.mjs +7 -0
  45. package/lib/chunk-5LFSFYFJ.mjs +7 -0
  46. package/lib/chunk-5MMXFWPD.mjs +7 -0
  47. package/lib/chunk-5O6JOMHS.mjs +13 -0
  48. package/lib/chunk-5P4PHJRL.mjs +9 -0
  49. package/lib/chunk-5QKTYCWE.mjs +11 -0
  50. package/lib/chunk-66NMFCWX.mjs +7 -0
  51. package/lib/chunk-6EBMEGZB.mjs +7 -0
  52. package/lib/chunk-6LAXTAVN.mjs +7 -0
  53. package/lib/chunk-6MUEPV7M.mjs +9 -0
  54. package/lib/chunk-6QSM2WIH.mjs +10 -0
  55. package/lib/chunk-75ADZS6B.mjs +7 -0
  56. package/lib/chunk-7EANH5PY.mjs +68 -0
  57. package/lib/chunk-7F54PZUS.mjs +7 -0
  58. package/lib/chunk-7UQD6V6F.mjs +7 -0
  59. package/lib/chunk-AAVJ5XVX.mjs +7 -0
  60. package/lib/chunk-ALJVEUUS.mjs +7 -0
  61. package/lib/chunk-ALUFROGA.mjs +7 -0
  62. package/lib/chunk-AR7BE5O2.mjs +7 -0
  63. package/lib/chunk-AUTM6H6Z.mjs +7 -0
  64. package/lib/chunk-AV5SWEHP.mjs +9 -0
  65. package/lib/chunk-B45CNPUX.mjs +47 -0
  66. package/lib/chunk-BILZ3SSR.mjs +7 -0
  67. package/lib/chunk-BN7A4GRQ.mjs +7 -0
  68. package/lib/chunk-BOGNK4LV.mjs +7 -0
  69. package/lib/chunk-BS5T3MOQ.mjs +7 -0
  70. package/lib/chunk-BZ24IAP5.mjs +7 -0
  71. package/lib/chunk-CA5NAXSU.mjs +7 -0
  72. package/lib/chunk-CE6ZDGBB.mjs +7 -0
  73. package/lib/chunk-CGWXQX75.mjs +7 -0
  74. package/lib/chunk-CHCHAE4B.mjs +7 -0
  75. package/lib/chunk-D3QRXG63.mjs +787 -0
  76. package/lib/chunk-DBFJB2B6.mjs +7 -0
  77. package/lib/chunk-DLDX6RRC.mjs +7 -0
  78. package/lib/chunk-EADHKH3A.mjs +7 -0
  79. package/lib/chunk-EEVVGGM6.mjs +7 -0
  80. package/lib/chunk-ENLBYECD.mjs +7 -0
  81. package/lib/chunk-EQF2IJS2.mjs +11 -0
  82. package/lib/chunk-EQOQASDQ.mjs +7 -0
  83. package/lib/chunk-F2424IKX.mjs +7 -0
  84. package/lib/chunk-F74IHMGL.mjs +7 -0
  85. package/lib/chunk-FOVVHGEP.mjs +7 -0
  86. package/lib/chunk-FQBRBBY4.mjs +7 -0
  87. package/lib/chunk-FQGHL7GR.mjs +259 -0
  88. package/lib/chunk-GAM726CK.mjs +7 -0
  89. package/lib/chunk-GCOB7K5N.mjs +7 -0
  90. package/lib/chunk-GMY5427L.mjs +7 -0
  91. package/lib/chunk-GNC27UEU.mjs +7 -0
  92. package/lib/chunk-H2PJNIYJ.mjs +7 -0
  93. package/lib/chunk-H45UXY6G.mjs +7 -0
  94. package/lib/chunk-HCIDVIOW.mjs +7 -0
  95. package/lib/chunk-HF6LAK3G.mjs +7 -0
  96. package/lib/chunk-HJC7AIBK.mjs +7 -0
  97. package/lib/chunk-HJKM3E56.mjs +7 -0
  98. package/lib/chunk-HTJ5OGP5.mjs +7 -0
  99. package/lib/chunk-HUMEKZT5.mjs +8 -0
  100. package/lib/chunk-HV2MXMGI.mjs +7 -0
  101. package/lib/chunk-HXS7ORUF.mjs +11 -0
  102. package/lib/chunk-I3JKJTLO.mjs +110 -0
  103. package/lib/chunk-I7O6C2B5.mjs +8 -0
  104. package/lib/chunk-IAZB4WIL.mjs +7 -0
  105. package/lib/chunk-IC2C2GOF.mjs +8 -0
  106. package/lib/chunk-IEYG5ATY.mjs +7 -0
  107. package/lib/chunk-INIQ23K6.mjs +7 -0
  108. package/lib/chunk-INIT2UKJ.mjs +7 -0
  109. package/lib/chunk-J7HVXMSW.mjs +7 -0
  110. package/lib/chunk-JVL444U5.mjs +7 -0
  111. package/lib/chunk-K22PA4XL.mjs +7 -0
  112. package/lib/chunk-K2FBZIXY.mjs +7 -0
  113. package/lib/chunk-KLX67VPL.mjs +7 -0
  114. package/lib/chunk-L776PUMV.mjs +7 -0
  115. package/lib/chunk-LQ4DRFUH.mjs +9 -0
  116. package/lib/chunk-LRFAIUN7.mjs +7 -0
  117. package/lib/chunk-LV6G4XTK.mjs +7 -0
  118. package/lib/chunk-M6P5ZZLE.mjs +7 -0
  119. package/lib/chunk-MTMH6H2A.mjs +8 -0
  120. package/lib/chunk-MYTIL2JD.mjs +10 -0
  121. package/lib/chunk-NEVXIGR6.mjs +10 -0
  122. package/lib/chunk-NGSMZZDA.mjs +7 -0
  123. package/lib/chunk-NHWE66K5.mjs +7 -0
  124. package/lib/chunk-NM4MDLK4.mjs +7 -0
  125. package/lib/chunk-NTDN2JQZ.mjs +19 -0
  126. package/lib/chunk-NTOVCTRS.mjs +7 -0
  127. package/lib/chunk-NZ5ZZLKS.mjs +7 -0
  128. package/lib/chunk-OQOZAPCI.mjs +7 -0
  129. package/lib/chunk-OTWRDD6L.mjs +7 -0
  130. package/lib/chunk-P2PJYWGQ.mjs +7 -0
  131. package/lib/chunk-P42X3B4D.mjs +7 -0
  132. package/lib/chunk-P7GSGFJO.mjs +7 -0
  133. package/lib/chunk-PA3MKJVH.mjs +7 -0
  134. package/lib/chunk-PBI4BYWW.mjs +7 -0
  135. package/lib/chunk-PNCONNFJ.mjs +10 -0
  136. package/lib/chunk-PTTHSSQO.mjs +7 -0
  137. package/lib/chunk-PUOX4NBJ.mjs +8 -0
  138. package/lib/chunk-PZTSVQSF.mjs +7 -0
  139. package/lib/chunk-QPF6C5MX.mjs +7 -0
  140. package/lib/chunk-QQZZMKU3.mjs +7 -0
  141. package/lib/chunk-QROPNEGY.mjs +14 -0
  142. package/lib/chunk-QRV2OSIS.mjs +7 -0
  143. package/lib/chunk-QSRAEUGZ.mjs +7 -0
  144. package/lib/chunk-QWT2C74M.mjs +7 -0
  145. package/lib/chunk-RAAANPPG.mjs +7 -0
  146. package/lib/chunk-RACDTRZA.mjs +7 -0
  147. package/lib/chunk-RFEO2KAN.mjs +7 -0
  148. package/lib/chunk-RH3N2H7P.mjs +7 -0
  149. package/lib/chunk-RSWDYIHY.mjs +37 -0
  150. package/lib/chunk-RSYICMZG.mjs +8 -0
  151. package/lib/chunk-SAR5622P.mjs +7 -0
  152. package/lib/chunk-SBIMVCXT.mjs +101 -0
  153. package/lib/chunk-SCKUIE3R.mjs +7 -0
  154. package/lib/chunk-SFURUNJM.mjs +7 -0
  155. package/lib/chunk-SIOZXPFG.mjs +7 -0
  156. package/lib/chunk-SRPWW4A2.mjs +10 -0
  157. package/lib/chunk-SRQDABQ2.mjs +15 -0
  158. package/lib/chunk-SVS6UMDU.mjs +323 -0
  159. package/lib/chunk-T63U4OZJ.mjs +7 -0
  160. package/lib/chunk-TBZMC2VV.mjs +11 -0
  161. package/lib/chunk-TEOLMRDO.mjs +7 -0
  162. package/lib/chunk-TLH7AD35.mjs +7 -0
  163. package/lib/chunk-TNXUU6W7.mjs +14 -0
  164. package/lib/chunk-TQX3PURV.mjs +7 -0
  165. package/lib/chunk-TUACWKIH.mjs +7 -0
  166. package/lib/chunk-TW3N6W5Z.mjs +7 -0
  167. package/lib/chunk-TYYOBZMU.mjs +10 -0
  168. package/lib/chunk-TZE3Y7IQ.mjs +7 -0
  169. package/lib/chunk-UNDIBZWG.mjs +7 -0
  170. package/lib/chunk-VGW4MXXZ.mjs +7 -0
  171. package/lib/chunk-VHI54FBK.mjs +441 -0
  172. package/lib/chunk-VXHDBYMI.mjs +7 -0
  173. package/lib/chunk-W7KFAY55.mjs +7 -0
  174. package/lib/chunk-WFEB5X4U.mjs +8 -0
  175. package/lib/chunk-WIO4XO4F.mjs +7 -0
  176. package/lib/chunk-WJY54JO7.mjs +13 -0
  177. package/lib/chunk-WR2GIKWE.mjs +7 -0
  178. package/lib/chunk-WRU5FJFC.mjs +7 -0
  179. package/lib/chunk-X2PY6MWZ.mjs +7 -0
  180. package/lib/chunk-X65MT4W3.mjs +7 -0
  181. package/lib/chunk-XBG5SP6Q.mjs +7 -0
  182. package/lib/chunk-XCA5AONB.mjs +7 -0
  183. package/lib/chunk-XEFDB2R4.mjs +7 -0
  184. package/lib/chunk-XETCPL7E.mjs +7 -0
  185. package/lib/chunk-Y5CGXLUB.mjs +7 -0
  186. package/lib/chunk-Y6J6QFI2.mjs +7 -0
  187. package/lib/chunk-YAZO75G2.mjs +8 -0
  188. package/lib/chunk-YBU4Z4QV.mjs +7 -0
  189. package/lib/chunk-YMJVMFPY.mjs +7 -0
  190. package/lib/chunk-YPSRZRIT.mjs +7 -0
  191. package/lib/chunk-YS4G22C2.mjs +7 -0
  192. package/lib/chunk-YW2SBL4Z.mjs +7 -0
  193. package/lib/chunk-YYZL7UGV.mjs +7 -0
  194. package/lib/chunk-Z7X534S4.mjs +10 -0
  195. package/lib/chunk-ZE6HKRR4.mjs +9 -0
  196. package/lib/chunk-ZHJP7L3K.mjs +7 -0
  197. package/lib/chunk-ZJKCWBRJ.mjs +7 -0
  198. package/lib/chunk-ZLZRU6MO.mjs +7 -0
  199. package/lib/chunk-ZOVSMN5C.mjs +7 -0
  200. package/lib/chunk-ZPYJPGDK.mjs +7 -0
  201. package/lib/chunk-ZQOZ4EFW.mjs +7 -0
  202. package/lib/chunk-ZUTYVST5.mjs +7 -0
  203. package/lib/chunk-ZXH4MBWP.mjs +7 -0
  204. package/lib/chunk-ZYEE34WO.mjs +7 -0
  205. package/lib/sandforge-autopilot.mjs +157 -0
  206. package/lib/sandforge-backup.mjs +99 -0
  207. package/lib/sandforge-checkpoint.mjs +353 -0
  208. package/lib/sandforge-cleanup.mjs +56 -0
  209. package/lib/sandforge-clone.mjs +7 -0
  210. package/lib/sandforge-compare.mjs +54 -0
  211. package/lib/sandforge-dataops.mjs +7 -0
  212. package/lib/sandforge-empty.mjs +140 -0
  213. package/lib/sandforge-env.mjs +355 -0
  214. package/lib/sandforge-frozen.mjs +263 -0
  215. package/lib/sandforge-mcp.mjs +40 -0
  216. package/lib/sandforge-monitor.mjs +43 -0
  217. package/lib/sandforge-seed.mjs +7 -0
  218. package/lib/sandforge-sync.mjs +7 -0
  219. package/lib/sandforge.mjs +28 -0
  220. package/package.json +52 -4
@@ -0,0 +1,20 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{b as ta,c as ra,d as ee,e as on,f as na,g as oa,h as qt,i as sa,j as ia,l as pr,m as aa,o as da,p as Zn,q as Xn,r as xe,s as sn,t as Gt,u as Qn,v as ca}from"./chunk-42RER7V4.mjs";import{F as Qi,L as Yn,M as ea,l as Ui,o as nn,p as Ki,q as Hi,r as Ji,s as Yi,y as Zi}from"./chunk-XEFDB2R4.mjs";import{l as Xi}from"./chunk-WRU5FJFC.mjs";import{a as ei,b as Zr}from"./chunk-XCA5AONB.mjs";import{$a as qn,Bc as Yr,Cc as Wn,Xa as js,Ya as Fs,Za as Ts,_a as Es,a as bs,ab as Ls,b as gt,bb as zs,cb as Cs,db as Ns,eb as Ds,g as Dn,h as Rs,j as ce,k as vs,l as ar,m as Os,n as at,o as J,s as Mn,uc as $e}from"./chunk-YMJVMFPY.mjs";import{a as Ur}from"./chunk-CE6ZDGBB.mjs";import{a as si,b as ii}from"./chunk-BOGNK4LV.mjs";import{Pa as Hn,a as Yo,ab as qi,b as Zo,gb as Gi,nb as Wi,pb as Jn,r as Ci,sb as Bi,tb as Vi,u as Ni,w as Di,y as Kn}from"./chunk-36U7IQ6Y.mjs";import{a as Mi,b as Un,c as fr,d as tn,i as rn,j as $i,l as xi,m as _i}from"./chunk-XETCPL7E.mjs";import{a as Ws,b as Gn,c as Bs,d as Vs,e as Us,k as Xs,l as Qs}from"./chunk-Z7X534S4.mjs";import{B as $s,C as xs,J as _s,N as Pt,O as qs,P as Jr,Q as Gs,S as Ks,U as Hs,V as Js}from"./chunk-6QSM2WIH.mjs";import{c as Ys,d as Zs}from"./chunk-T63U4OZJ.mjs";import{f as gi,i as Bn,j as Qr}from"./chunk-3F5YMM2F.mjs";import{q as ue,r as dr,s as Xr,w as oi,y as cr}from"./chunk-6MUEPV7M.mjs";import{Aa as Pi,Ba as ji,Ca as Fi,L as hi,O as mi,Oa as Ti,P as Vn,Pa as Ei,Q as yi,Qa as Li,S as ur,T as wi,U as bi,W as Ri,Za as zi,b as ms,c as ys,e as Me,f as ws,ka as vi,o as Ze,p as ht,pa as Oi,r as ti,ra as ki,s as ri,sa as Ii,w as ni,wa as Si,xa as Ai}from"./chunk-VXHDBYMI.mjs";import{q as en}from"./chunk-ENLBYECD.mjs";import{a as pt}from"./chunk-4TLYUZD5.mjs";import{A as fi,G as pi,s as ai,u as di,w as lr,x as ci,y as li,z as ui}from"./chunk-ZLZRU6MO.mjs";import{b as Kr}from"./chunk-WIO4XO4F.mjs";import{a as Is}from"./chunk-EADHKH3A.mjs";import{b as Ss,c as At,e as $n,g as As,h as xn,i as Ps,j as _n}from"./chunk-GCOB7K5N.mjs";import{i as ks}from"./chunk-INIT2UKJ.mjs";import{h as Ms}from"./chunk-PNCONNFJ.mjs";import{D as is,E as It,F as it,H as Cn,K as as,L as ds,M as cs,X as Nn,Y as ls,_ as us,a as ir,b as Ce,c as Dt,ca as St,d as Br,da as fs,e as Mt,f as Xo,fa as ps,ga as gs,ha as hs,ia as xt,j as Qo,ja as _t,k as Ln,l as es,m as ts,n as rs,o as ns,p as Ee,q as je,r as Vr,s as zn,t as os,u as $t,y as ss}from"./chunk-CGWXQX75.mjs";import{a as Ae,h as de}from"./chunk-TZE3Y7IQ.mjs";import{b as Hr}from"./chunk-UNDIBZWG.mjs";import{b as H}from"./chunk-CA5NAXSU.mjs";import{Cb as Dr,Eb as Ye,Fb as Mr,Gb as kt,Hb as or,Ib as $r,Lb as Le,Mb as ze,Mc as Ho,Nb as xr,Ob as ve,Pb as _r,Qb as Wo,Rb as Bo,Sb as qr,Tc as Jo,Vc as sr,Yb as Vo,bc as Uo,bd as Nt,cd as Wr,fc as Ko,gc as Gr,r as Go,zb as Ct}from"./chunk-B45CNPUX.mjs";import{b as Pe,e as Mo,f as $o,k as Ot,l as st,s as xo,u as _o,v as qo,z as En}from"./chunk-7EANH5PY.mjs";var Ne=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function Wt(s){return s.objects.reduce((e,t)=>e+t.records.length,0)}async function la(s){if(s.orgTier!=="development"&&s.orgTier!=="scratch")throw new Ne("non-sandbox",`Refusing frozen-dataset load on ${s.orgTier} org ${s.orgId}: loads go into sandboxes and Developer Edition orgs only. Remediation: target a Developer/Scratch sandbox or a Developer Edition org \u2014 deploy the required configuration THERE; never run DML against a shared or source org.`,{orgId:s.orgId,tier:s.orgTier});if(s.protectedOrgIds?.includes(s.orgId))throw new Ne("protected-environment",`Refusing frozen-dataset load on protected environment ${s.orgId}: it is listed in the protectedOrgIds configuration. Remediation: pick an unprotected sandbox, or review the protected-environment configuration if this org was retired.`,{orgId:s.orgId});if(s.manifest&&s.manifest.source.orgId===s.orgId)throw new Ne("source-is-target",`Refusing frozen-dataset load on ${s.orgId}: this org is the dataset SOURCE (manifest source.orgId). Loading would mix pseudonymized records with their origin. Remediation: target a fresh dev sandbox instead.`,{orgId:s.orgId});if(!await s.mockDetector.areCalloutsMocked(s.orgId))throw new Ne("unmocked-callouts",`Refusing frozen-dataset load on ${s.orgId}: unmocked callouts detected. Records under load would trigger real external calls. Remediation: deploy the mock configuration to the TARGET org (e.g. the custom metadata flag read by CustomMetadataCalloutMockDetector), then retry \u2014 never edit data on the source org.`,{orgId:s.orgId});if(Wt(s.dataset)===0)throw new Ne("empty-dataset","Refusing frozen-dataset load: the dataset contains zero records. Remediation: re-run the selection/extraction with a coverage matrix that matches the source data, then freeze a new dataset version.")}var gr=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${de(this.config.metadataTypeApiName)} WHERE ${de(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var an=class{constructor(e){this.orgAccess=e}orgAccess;uiApiCache=new Map;async alignObject(e){let t=new Map(e.describe.fields.map(d=>[d.name,d])),r=new Map,n=[],o=[],i=[];for(let d of e.records){let a={},c=e.accountKindOf?.(d.referenceId);for(let[f,l]of Object.entries(d.fields)){if(c!==void 0&&Ko(Ee,f,c))continue;let u=t.get(f);if(!u){this.countRemoval(r,f,"not-in-target");continue}if(!u.createable){this.countRemoval(r,f,"not-createable");continue}if(e.leaveOutEncrypted===!0&&u.type===Ks){l!=null&&l!==""&&this.countRemoval(r,f,"may-hold-masks");continue}let p=l;typeof p=="string"&&p!==""&&u.restrictedPicklist===!0&&(u.type==="picklist"||u.type==="multipicklist")&&(p=await this.alignPicklistValue(e,u.name,u.type,d,p,n,o)),a[f]=p}i.push(a)}return{objectApiName:e.objectApiName,alignedRecords:i,removals:[...r.entries()].map(([d,a])=>({objectApiName:e.objectApiName,field:d,reason:a.reason,affectedRecords:a.count})),adjustments:n,missingRequired:this.detectMissingRequired(e,i),uiApiWarnings:o}}detectMissingRequired(e,t){let r=t.filter((a,c)=>!e.linked?.has(e.records[c].referenceId));if(r.length===0)return[];let n=[],o=e.accountKindOf,i=o?e.records.filter(a=>!e.linked?.has(a.referenceId)).map(a=>o(a.referenceId)):[];for(let a of e.describe.fields){let c=o?Gr(Ee,a.name):void 0;if(!a.createable||a.nillable&&c===void 0||a.defaultedOnCreate)continue;let f=r.filter((u,p)=>c===void 0||$t(c,i[p]));if(f.length===0)continue;if(!f.some(u=>{let p=u[a.name];return p!=null&&p!==""})){let u=a.unique?"unique":a.nameField?"name":void 0,p=(a.referenceTo?.length??0)>0,g=(a.picklistValues??[]).filter(h=>h.active).map(h=>h.value);n.push({objectApiName:e.objectApiName,field:a.name,isLookup:p,referenceTo:a.referenceTo??[],...u?{distinct:u}:{},...c?{accountKind:c}:{},...!p&&a.type?{fieldType:a.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=qr(e.objectApiName,a=>e.describe.fields.some(c=>c.name===a&&c.createable),a=>r.some(c=>c[a]!==void 0&&c[a]!==null&&c[a]!==""));if(d!==void 0&&!n.some(a=>a.field===d)){let a=e.describe.fields.find(c=>c.name===d)?.type;n.push({objectApiName:e.objectApiName,field:d,isLookup:!1,referenceTo:[],...a?{fieldType:a}:{}})}return n}async alignPicklistValue(e,t,r,n,o,i,d){let a=r==="multipicklist",c=a?o.split(";"):[o],f=e.describe.fields.find(y=>y.name===t),l=new Set((f?.picklistValues??[]).filter(y=>y.active).map(y=>y.value)),u=c.filter(y=>!l.has(y));if(u.length>0){let y=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:o,rule:y,scope:"global"}),this.applyRule(y,c,u,a)}let p=e.resolvedRecordTypes.get(n.referenceId);if(!p)return o;let g=await this.uiApiValues(e,p,t,d);if(g===null)return o;let h=c.filter(y=>!g.includes(y));if(h.length===0)return o;let m=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:o,rule:m,scope:"record-type"}),this.applyRule(m,c,h,a)}async uiApiValues(e,t,r,n){let o=`${e.orgId}|${e.objectApiName}|${t}|${r}`,i=this.uiApiCache.get(o);if(i!==void 0)return i;try{let d=await this.orgAccess.picklistValues(e.orgId,e.objectApiName,t,r);return this.uiApiCache.set(o,d),d}catch(d){return this.uiApiCache.set(o,null),n.push(`UI API picklist-values read failed for ${e.objectApiName}.${r} (recordType ${t}): ${d instanceof Error?d.message:String(d)}. Record-type assignment gap check skipped for this field.`),null}}applyRule(e,t,r,n){return e.action==="replace"?e.value:n?t.filter(o=>!r.includes(o)).join(";"):""}countRemoval(e,t,r){let n=e.get(t);n?n.count++:e.set(t,{reason:r,count:1})}};var hr="Opportunity",mr="SyncedQuoteId",Cd="OpportunityLineItem",eo="QuoteLineItem";function to(s,e){let t=(d,a)=>{let c=new Map;for(let{referenceId:f,fields:l}of s.get(d)??[]){let u=l[a];typeof u!="string"||u===""||!e(f)||c.set(u,(c.get(u)??0)+1)}return c},r=t(Cd,"OpportunityId"),n=t(eo,"QuoteId"),o=new Set((s.get("Quote")??[]).map(d=>d.referenceId)),i=[];for(let{referenceId:d,fields:a}of s.get(hr)??[]){let c=a[mr];if(typeof c!="string"||!o.has(c)||!e(d)||!e(c))continue;let f=r.get(d)??0,l=n.get(c)??0;f>l&&i.push({opportunity:d,quote:c,products:f,lines:l})}return i}function ua(s,e,t=!1){if(s.length===0)return;let r=s.length===1,n=s.reduce((f,l)=>f+l.products,0),o=s.reduce((f,l)=>f+l.lines,0),i=r?"its":"their",d=r?"the quote's":"the quotes'",a=o===0?`none of ${d} lines`:`${o} of ${d} lines`,c=e&&o===0?", which excludedObjects leaves out":"";return{objectApiName:hr,count:s.length,note:`${s.length} ${t?"would be ":""}left unsynced with ${i} quote: the load ${t?"would write":"wrote"} ${n} of ${i} products and ${a}${c} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${mr} left empty, the products kept`}}import*as Bt from"node:fs";import*as dn from"node:path";function Nd(s){return`counting-contract.${ta(s)}.json`}function yr(s,e,t){return s.assertOutsideRepo(dn.join(e,Nd(t)))}function fa(s,e,t){let r=yr(s,e,t.orgId);return Bt.mkdirSync(dn.dirname(r),{recursive:!0}),Bt.writeFileSync(r,`${JSON.stringify(t,null,2)}
8
+ `,"utf8"),r}function cn(s,e){let t=s.assertOutsideRepo(e),r=JSON.parse(Bt.readFileSync(t,"utf8"));if(r.version!==1||typeof r.objects!="object"||r.objects===null)throw new Error(`Invalid counting contract at ${t}: version 1 with objects expected`);return r}function pa(s,e){if(s.loadStartedAt!==void 0)return s.loadStartedAt===e.startedAt;let t=Date.parse(s.writtenAt),r=Date.parse(e.endedAt);return Number.isFinite(t)&&Number.isFinite(r)&&t>=r}var qe=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold},br=class extends Error{constructor(e){super(e),this.name="LoadRecordsExceededError"}},Vt=class extends Error{constructor(t){let r=t.reduce((n,o)=>n+o.count,0);super(`This reload finds in the target ${r} record(s) that its purge would delete along with what the loads before it created \u2014 ${t.map(n=>`${n.objectApiName} (${n.count}, under ${n.under.join(", ")})`).join("; ")}: the target deletes them with the record they hang from, which the reload does not find again, and the load would then write against records no longer there. Nothing was written. Give the records they hang from identity keys too, so that the reload finds them again, or take the load back first with a removal, then load the dataset again.`);this.found=t;this.name="ReloadTakesAlongError"}found};function Dd(s){return s.perObject.reduce((e,t)=>e+t.toInsert,0)}function Md(s,e){if(!(e===void 0||s<=e))return`This load would insert ${s} record(s), more than the ${e} it may: nothing was written. The dataset or the target changed since that count was taken: preview the load again, and load with the count it gives.`}var _e=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${Pa(t,void 0)}`:"The load was cancelled before it created or purged a record: the mapping is left as it was.");this.written=t;this.name="FrozenLoadCancelledError"}written},Ft=class extends Error{constructor(t,r,n){super($d(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function $d(s,e,t){return`${H(s)}
9
+ The load failed ${Pa(e,t)}`}function Pa(s,e){let t=new Map,r=(a,c)=>{c!==0&&t.set(a,(t.get(a)??0)+c)};for(let a of s.placeholders)r(a.placeholderObjectApiName,1);for(let a of s.perObject)r(a.objectApiName,a.inserted);let n=[...t.values()].reduce((a,c)=>a+c,0),o=[...Object.values(s.purge.deleted),...Object.values(s.purge.deactivated)].reduce((a,c)=>a+c,0),i=[...n>0?[`created ${n} record(s) (`+[...t].map(([a,c])=>`${a}: ${c}`).join(", ")+")"]:[],...o>0?[`purged ${o} record(s) that earlier loads created`]:[]].join(" and "),d;return e!==void 0?d=n>0?`The mapping could not be written, and nothing names what it created \u2014 no removal or reload will find it: ${e}`:`The mapping could not be written: ${e}`:d=n>0?"What it created is kept in the mapping: a removal takes it back, and a reload purges it or finds it again.":"What the earlier loads created and it did not purge is still named in the mapping, for a removal or the next reload.",i===""?`before it had written the whole dataset. ${d}`:`after it had ${i}. ${d}`}function ja(s,e){let t=[];for(let[r,n]of s.givenRules){let o=[],i={};for(let{referenceId:a,fields:c}of s.alignedByObject.get(r)??[]){if(!Qe(c.RecordTypeId)||!e(a))continue;o.push(a);let f=s.withoutRecordType.get(a)??"notRead";i[f]=(i[f]??0)+1}if(o.length===0)continue;let{predicted:d}=n;t.push({given:{objectApiName:r,rows:o.length,why:i,...d?{predicted:d}:{}},rule:n,keys:o})}return t}function Fa(s){return{namespacePrefix:s.namespacePrefix,developerName:s.developerName}}function xd(s){if(!s)return"the user's default record type applies";if(s.kind==="master")return"the target leaves it on Master for that user";let{developerName:e}=s.info;return s.basis==="userDefault"?`the target gives it ${e}, the user's default record type`:`the target gives it ${e}, the only other record type open to the user`}async function _d(s,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new Ft(s,e.written,H(t))}return new Ft(s,e.written)}function Ta(s,e,t){let r=t.map(n=>At(n.namespacePrefix,n.developerName));return new qe(`The dataset's ${s} records name record type "${e}" by its label, which ${r.join(" and ")} share in the source: which one each record had cannot be told, the dataset having been extracted before SandForge kept each record's record type by its name. Extract the dataset again. Nothing was written.`,void 0,{reason:"label",objectApiName:s,name:e,recordTypes:r})}function qd(s){for(let{objectApiName:e,records:t}of s.objects){let r=s.recordTypes[e]??[];if(!(r.length<2))for(let n of t){let o=n.fields.RecordTypeId;if(typeof o!="string"||o==="")continue;if(n.recordTypeDeveloperName!==void 0){let d=xn(n.recordTypeDeveloperName,r,Fa);if(d&&"found"in d)continue}let i=r.filter(d=>d.name===o);if(i.length>1)return Ta(e,o,i)}}}var Ea="Opportunity",un="placeholder:",no=class{byObject=new Map;auditDated=new Set;add(e,t,r=!1){let n=this.byObject.get(e)??[];n.push(t),this.byObject.set(e,n),r&&this.auditDated.add(e)}sentAuditDates(e){return this.auditDated.has(e)}list(e=[]){let t=new Map,r=(n,o)=>{t.set(n,[...t.get(n)??[],...o])};for(let{objectApiName:n,referenceIds:o}of e)r(n,o);for(let[n,o]of this.byObject)r(n,o);return[...t].map(([n,o])=>({objectApiName:n,referenceIds:o}))}};function Gd(s){if(s.startsWith(un))return s.split(":")[1]??"Unknown";let e=s.lastIndexOf("-");return e>0?s.slice(0,e):"Unknown"}function Wd(s){return typeof s=="number"?String(s):typeof s=="boolean"?s?"TRUE":"FALSE":`'${Ae(String(s))}'`}var mt=200;function te(s){return s.slice(0,15)}var Bd=["CreatedDate","LastModifiedDate"],Vd=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function jt(s){return typeof s=="string"?Date.parse(s):Number.NaN}function ga(s){return s.success||s.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function ha(s){if(s.tried===0)return"";let e=s.tried-s.went,t=[s.went>0?`${s.went} went`:"",e>0?`${e} refused again`:""].filter(Boolean);return` \u2014 ${s.tried} refused at first, sent again once the rest had gone: ${t.join(", ")}`}function ma(s,e,t){let r=`Status set to ${e.draft} for the purge, and left there: ${e.status} could not be given back \u2014 ${t}`,n=s.failures.find(o=>o.objectApiName===e.objectApiName&&te(o.recordId)===te(e.id));n?n.errors=[...n.errors,r]:s.failures.push({objectApiName:e.objectApiName,recordId:e.id,errors:[r]})}function ro(s,e){let t=(s.notInserted??0)+(e.notInserted??0),r=[s.writtenWithoutFields,e.writtenWithoutFields].reduce((n,o)=>o?Bn(n,o):n,void 0);return{objectApiName:e.objectApiName,fromFiles:s.fromFiles+e.fromFiles,inserted:s.inserted+e.inserted,reused:s.reused+e.reused,skippedDuplicates:[...s.skippedDuplicates,...e.skippedDuplicates],failed:[...s.failed,...e.failed],...r?{writtenWithoutFields:r}:{},...t>0?{notInserted:t}:{}}}function ya(s){let e=s.filter(r=>r.replacedWith===void 0).map(r=>r.field),t=s.filter(r=>r.replacedWith!==void 0).map(r=>`${r.field} set to "${r.replacedWith}"`);return[...e.length>0?[`without ${e.join(", ")}`]:[],...t.length>0?[`with ${t.join(", ")}`]:[]].join(" and ")}function fn(s,e="inserted"){return s>0?`, ${s} not ${e}: the load was cancelled first`:""}function oo(s,e="inserted"){return s>0?`, ${s} not ${e}: the load failed`:""}function Ud(s,e){return s>0?"error":e>0?"stopped":"done"}function Xe(s,e,t,r){return{phase:s,status:"error",progress:e,message:`${t} \u2014 ${H(r)}`}}var wa={phase:"guards",status:"started",progress:0,message:"Evaluating entry guards"};function ln(s,e){let{phase:t,progress:r,did:n,refused:o,notDone:i,done:d,notes:a=""}=s;return e?{phase:t,status:"error",progress:r,message:`${n}${oo(i,d)}${a} \u2014 ${H(e.cause)}`}:{phase:t,status:Ud(o,i),progress:r,message:`${n}${fn(i,d)}${a}`}}var wr={accountNotInDataset:"its person account is not in the dataset",accountNotLoaded:"person account was not loaded (see perObject failures/skips)",noPersonAccounts:"the target org has no person accounts: it holds the account as a business account, which takes the contact as one of its own",businessAccount:"the target holds the account as a business account, which takes the contact as one of its own"};function Kd(s){return s.accountReferenceId===""?"Not written: a person account's contact goes in with its account, which the dataset does not hold":"Not written: a person account's contact goes in with its account, which the load did not write"}function Hd(s,e){let t=new Map;for(let{accountReferenceId:r,contactReferenceId:n}of s.personContactSidecar??[])e.get(n)===je&&t.set(n,r);for(let r of s.objects.find(n=>n.objectApiName===je)?.records??[]){if(t.has(r.referenceId)||!zn(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Ee?n:"")}return t}function Jd(s){let e=new Set;for(let{accountReferenceId:t}of s.personContactSidecar??[])t!==""&&e.add(t);for(let t of s.objects.find(r=>r.objectApiName===Ee)?.records??[]){let r=t.fields.LastName;(zn(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function pn(s,e,t){let r=s.accountKind;return r===void 0?[...e]:e.filter(n=>$t(r,t(n.referenceId)))}var Rr=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new ee}deps;config;sasGuard;journal;async gateLoad(e){try{await this.passEntryGuards(e)}catch(o){throw e.onProgress?.(wa),e.onProgress?.(Xe("guards",2,"Entry guards not passed",o)),o}let t=e.dataset;if(e.pilot)try{t=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(o){throw e.onProgress?.({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"}),e.onProgress?.(Xe("pilot",4,"Root folder not selected",o)),o}let r=qd(t);if(r)throw e.onProgress?.({phase:"align",status:"started",progress:12,message:"Resolving record types"}),e.onProgress?.(Xe("align",20,"Schema not aligned",r)),r;let n=e.reload===!0&&!e.pilot;return this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:n?"delete":"insert",objectName:e.dataset.objects.filter(o=>o.records.length>0).map(o=>o.objectApiName).join(", "),recordCount:{atMost:Wt(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return la({orgId:e.orgId,orgTier:e.orgTier,dataset:e.dataset,manifest:e.manifest,mockDetector:this.deps.mockDetector,protectedOrgIds:this.config.protectedOrgIds})}async load(e){let t={};try{return await this.loadKeeping(e,t)}finally{await this.journal?.close().catch(()=>{}),this.journal=void 0}}async loadKeeping(e,t){try{return await this.loadInto(e,t)}catch(r){t.endOpenLine?.(r);let n=t.load;throw r instanceof _e||!n?.wroteSome()?r:await _d(r,n)}}async planLoad(e){let t=e.now??(()=>new Date),r=d=>e.onProgress?.(d),n=await this.prepare(e,r,{}),o=e.reload&&!e.pilot?await this.planPurge(e.orgId,n.previousLoads,n.mapping):void 0;if(o){let d=await this.foundUnderThePurge(e.orgId,o.residuals,n.mapping,n.refIndex);if(d.length>0)throw new Vt(d)}let i=Ra(n,o,{orgId:e.orgId,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:t().toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]});return this.withValidationRules(i)}async withValidationRules(e){let t=this.deps.readValidationRules,r=e.perObject.filter(a=>a.toInsert>0).map(a=>a.objectApiName),n=[...new Set([...r,...e.placeholders.map(a=>a.placeholderObjectApiName)])];if(!t||n.length===0)return e;let o=new Map,i=new Map;try{for(let{objectApiName:a,onChangeOnly:c,...f}of await t(n))c?i.set(a,[...i.get(a)??[],f.name]):o.set(a,[...o.get(a)??[],f])}catch(a){return{...e,validationRulesUnread:H(a)}}let d=new Set(r);return{...e,perObject:e.perObject.map(a=>{if(a.toInsert===0)return a;let c=o.get(a.objectApiName)??[],f=i.get(a.objectApiName)??[];return{...a,...c.length>0?{validationRules:c}:{},...f.length>0?{validationRulesOnChange:f}:{}}}),placeholders:e.placeholders.map(a=>{let c=d.has(a.placeholderObjectApiName)?[]:o.get(a.placeholderObjectApiName)??[];return c.length>0?{...a,validationRules:c}:a})}}async prepare(e,t,r){let{orgId:n}=e;t(wa);try{await this.passEntryGuards(e)}catch(D){throw t(Xe("guards",2,"Entry guards not passed",D)),D}t({phase:"guards",status:"done",progress:2,message:"Entry guards passed"}),t({phase:"mapping",status:"started",progress:2,message:"Reading the mapping of earlier loads"});let o=await this.deps.mappingStore.previousLoads().catch(D=>{throw t(Xe("mapping",3,"Mapping not read",D)),D});t({phase:"mapping",status:"done",progress:3,message:`Mapping read: ${o.length} earlier load(s)`});let i=e.dataset;if(e.pilot){t({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"});try{i=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch($){throw t(Xe("pilot",4,"Root folder not selected",$)),$}let D=i.objects.reduce(($,B)=>$+B.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${D} record(s)`})}let d=ka(i),a=Qd(e.dataset),c=Hd(i,d),f=dc(i,d,c),l=Yo(f),u=l.flat(),p=new Mt,g=new Mt(ac),h={...i,objects:i.objects.map(D=>({...D,records:D.records.filter($=>!p.leaveOut(D.objectApiName,$.referenceId,Qo(D.objectApiName,$.fields,typeof $.fields.RelationId=="string"?d.get($.fields.RelationId):void 0))&&!g.leaveOut(D.objectApiName,$.referenceId,$.fields))}))},m=new Map,y=new Set,v=new Set;if(e.reload){t({phase:"reload",status:"started",progress:5,message:"Reusing reference data"}),r.endOpenLine=D=>t(Xe("reload",10,"Reference data not reused",D)),await this.reuseByIdentityKeys(e,h,m,y);for(let D of y)v.add(D);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${y.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||Ia(h).length>0){t({phase:"catalog",status:"started",progress:10,message:"Looking up the catalog the target already holds"});let D;try{D=await this.lookUpTheCatalog(n,h,m,y)}catch($){throw t(Xe("catalog",11,"Catalog not looked up",$)),$}t({phase:"catalog",status:"done",progress:11,message:`Catalog looked up: ${D.join("; ")}`})}t({phase:"align",status:"started",progress:12,message:"Resolving record types"}),r.endOpenLine=D=>t(Xe("align",20,"Schema not aligned",D));let P=[],A=new Map,S=new Map,T=new Map;for(let D of h.objects){let $=[];for(let B of D.records)$.push(await this.resolveRecordType(e,i,D.objectApiName,B,S,P,T));A.set(D.objectApiName,$)}let E=new an(this.deps.orgAccess),O={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:P},w=new Map,R=new Map,I=new Map,j=new Map,z=new Map,x,q=Jd(i),Y=D=>q.has(D)?x===!1?"personAsBusiness":"person":"business",L=new Map,k=new Map,V=e.writeEncrypted!==!0&&e.manifest?.coverage?.encryptedNotKept===void 0;for(let D of h.objects){let $=D.objectApiName;if(D.records.length===0)continue;let B=D.records.filter(N=>!y.has(N.referenceId)),Oe=(N,ie)=>{O.excludedObjects.push({objectApiName:$,reason:N}),z.set($,{objectApiName:$,fromFiles:i.objects.find(Se=>Se.objectApiName===$)?.records.length??D.records.length,inserted:0,reused:D.records.length-B.length,skippedDuplicates:[],failed:B.map(Se=>({objectApiName:$,referenceId:Se.referenceId,errors:[ie]}))}),B.length!==0&&t({phase:"align",objectName:$,status:"error",progress:12,message:`Skipped ${$} \u2014 ${N}`})},ke;try{ke=await this.deps.orgAccess.describe(n,$)}catch(N){let ie=`Not present in target org: ${N instanceof Error?N.message:String(N)}`;Oe(ie,ie);continue}if($===Ee&&(x=ke.fields.some(N=>N.name===Vr)),ke.createable===!1&&B.length>0){Oe(`Not createable in target org: ${B.length} record${B.length===1?"":"s"} of the dataset not loaded`,"Not createable in target org: the running user may not insert it");continue}I.set($,new Set(ke.fields.filter(N=>N.updateable===!1).map(N=>N.name)));let ge=ke.fields.filter(N=>N.lookupFilter!==void 0&&N.createable&&(N.referenceTo?.length??0)>0).map(N=>({field:N.name,referenceTo:[...N.referenceTo??[]]}));ge.length>0&&j.set($,ge);let Ie=Kr(ke.recordTypeInfos);if(Ie.some(N=>!N.master)){let N=$i(rn(Ie));k.set($,{types:Ie,...N?{predicted:N}:{}})}let he=oc($,ke,this.config);he.length>0&&L.set($,he),R.set($,new Set(ke.fields.filter(N=>N.createable&&!N.nillable&&!N.defaultedOnCreate&&(N.referenceTo?.length??0)>0).map(N=>N.name)));let M=await E.alignObject({orgId:n,objectApiName:$,records:A.get($)??[],describe:ke,resolvedRecordTypes:S,ruleFor:(N,ie)=>this.picklistRuleFor(N,ie),linked:y,...$===Ee?{accountKindOf:Y}:{},...V?{leaveOutEncrypted:V}:{}});O.objectResults.push(M),O.removals.push(...M.removals),O.adjustments.push(...M.adjustments),w.set($,M.alignedRecords.map((N,ie)=>({referenceId:(A.get($)??[])[ie].referenceId,fields:N})))}let Z=await this.linkWhatThePlatformKeeps(n,O.objectResults,w,a,m,y,Y),F=e.reload?await this.reuseByKeysAsWritten(n,h,O.objectResults,w,a,m,y,Y):{linked:[],said:[],leftEmpty:[]};for(let D of[...Z.linked,...F.linked])v.add(D);let _=[...Z.said,...F.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${_.length>0?` \u2014 ${_.join("; ")}`:""}`}),r.endOpenLine=void 0;let U=new Mt(sc(L));nc(w,R,[p,g,U]);for(let D of O.objectResults){let $=(w.get(D.objectApiName)??[]).filter(B=>!y.has(B.referenceId));D.missingRequired=D.missingRequired.filter(B=>pn(B,$,Y).some(Oe=>Qe(Oe.fields[B.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let re=await this.planRequiredFields(e,O.objectResults).catch(D=>{throw t(Xe("placeholders",22,"Required fields not covered",D)),D});return t({phase:"placeholders",status:"done",progress:22,message:"Required fields checked"}),{previousLoads:o,working:i,refIndex:d,personContacts:c,groups:l,groupOrder:u,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:U,loading:h,mapping:m,reused:y,reusedByKeys:v,ranks:a,recordTypeIssues:P,alignment:O,alignedByObject:w,requiredLookups:R,fixedAtInsert:I,filteredLookups:j,lostObjects:z,targetHasPersonAccounts:x,accountKindOf:Y,plans:re,givenRules:k,withoutRecordType:T,keysLeftEmpty:[...Z.leftEmpty,...F.leftEmpty]}}async loadInto(e,t){let r=e.now??(()=>new Date),n=r(),o=b=>e.onProgress?.(b),{orgId:i}=e;this.journal=this.deps.mappingStore.journal?.(n);let d=await this.prepare(e,o,t),{previousLoads:a,working:c,refIndex:f,personContacts:l,groups:u,groupOrder:p,leftToThePlatform:g,untypedFeedItems:h,heldForExclusions:m,mapping:y,reused:v,ranks:P,recordTypeIssues:A,alignment:S,alignedByObject:T,requiredLookups:E,fixedAtInsert:O,lostObjects:w,targetHasPersonAccounts:R,accountKindOf:I,plans:j}=d,z=Md(Dd(Ra(d,void 0,{orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:n.toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]})),e.maxRecords);if(z)throw new br(z);let x=await this.runUserIdOf(i);x&&this.journal?.writtenAs(x);let q={deleted:{},deactivated:{},failures:[]},Y=[],L=[],k=new no,V=new Map,Z=[],F=new Set,_,U=new Map,re=!1,D=async()=>{let b=await this.readWrittenBetween(i,k,y),C=_?.linked??new Map,W=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(y,{created:k.list(Z),startedAt:n,...b?{writtenBetween:b}:{},earlier:{settled:[...F],...W&&W.length>0?{stillToSweep:[...W]}:{}},...C.size>0?{personContacts:Object.fromEntries(C)}:{},...U.size>0?{withTheirRecord:Object.fromEntries(U)}:{},...x?{runUserId:x}:{}}),re=!0},$=()=>k.list().length>0||Object.keys(q.deleted).length>0||Object.keys(q.deactivated).length>0,B=async()=>{if(!e.signal?.aborted)return;let b=$();throw b&&await D(),new _e({perObject:L,placeholders:Y,purge:q},b)};t.load={keepMapping:D,mappingKept:()=>re,wroteSome:$,written:{perObject:L,placeholders:Y,purge:q}};let Oe=[];if(e.reload){let b="",C={residuals:0},W={tried:0,went:0},ne=oe=>{let pe=we=>Object.values(we).reduce((se,X)=>se+X,0);return ln({phase:"reload",progress:24,did:`Purge: ${pe(q.deleted)} deleted, ${pe(q.deactivated)} deactivated, ${q.failures.length} failed`,refused:q.failures.length,notDone:C.residuals,done:"purged",notes:`${ha(W)}${b}`},oe)};if(!e.pilot){o({phase:"reload",status:"started",progress:23,message:"Purging what earlier loads created"});let oe=await this.planPurge(i,a,y),pe=await this.foundUnderThePurge(i,oe.residuals,y,f);if(pe.length>0){let X=new Vt(pe);throw o(ne({cause:X})),X}Z=oe.carried;for(let X of Z.flatMap(K=>K.referenceIds)){let K=y.get(X);K&&F.add(te(K))}let we=Object.values(oe.leftUnrecorded).reduce((X,K)=>X+K,0);we>0&&(q.leftUnrecorded=oe.leftUnrecorded,b=` \u2014 ${we} record(s) left in place of a load recorded before loads kept what they created: it may have linked them`);let se=Object.entries(oe.keptByThePlatform);se.length>0&&(q.keptByThePlatform=oe.keptByThePlatform,b+=" \u2014 kept, the platform does not delete them: "+se.map(([X,K])=>`${X} (${K})`).join(", "));try{e.purgeSweep&&(await B(),await e.purgeSweep.first()),await this.purgeResiduals(e,oe,[...p].reverse(),q,B,F,C,W),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(X){throw o(ne(X instanceof _e?void 0:{cause:X})),X}for(let X of a)if(!X.created)for(let K of X.mapping.values())F.add(te(K));o(C.residuals>0||q.failures.length>0?ne():{phase:"reload",status:"done",progress:24,message:`Reload pass done${ha(W)}${b}`})}}let ke=b=>(T.get(b)??[]).filter(C=>!v.has(C.referenceId)),ge=j.filter(b=>b.kind==="placeholder").length,Ie=b=>ln({phase:"placeholders",progress:25,did:`Placeholders: ${Y.length} created`,refused:0,notDone:ge-Y.length,done:"created"},b);ge>0&&(await B(),o({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let b of j)b.kind==="placeholder"?(await B(),await this.createPlaceholder(e,b,ke(b.missing.objectApiName),y,Y,k)):this.applyScalarDefault(b.missing,pn(b.missing,ke(b.missing.objectApiName),I),Oe,P)}catch(b){throw o(Ie(b instanceof _e?void 0:{cause:b})),b}ge>0&&o(Ie());let he=u.flatMap(b=>b.length>1?Zo(b,cc(T,E,f,l)):b),M=[],N=[],ie=this.config.duplicateErrorPatterns??aa,Se=new Set(he.includes(Dt)?(T.get(Dt)??[]).map(b=>b.referenceId):[]),Fe=[],et=null,tt=0,Qt=!1,Te=b=>b===Ce&&Fe.length>0?`, ${Fe.length} on a case waiting for ${Fe.length===1?"its task":"their tasks"}`:"",rt=new Set,er=async()=>{if(_)return _;let b=await this.linkPersonContacts(i,l,y,v,R,A);for(let C of b.linked.keys())v.add(C);return rt=new Set(b.unlinked.map(C=>C.contactReferenceId).filter(C=>!v.has(C))),_=b,b},nt=b=>{if(b.objectApiName!==je||!_)return b;let C=_.unlinked.filter(W=>rt.has(W.contactReferenceId));return C.length===0?b:{...b,failed:[...b.failed,...C.map(W=>({objectApiName:je,referenceId:W.contactReferenceId,errors:[Kd(W)]}))]}},tr=()=>{if(_)for(let[b,C]of _.own)y.has(b)||(_.own.delete(b),_.unlinked.push({accountReferenceId:C.accountReferenceId,contactReferenceId:b,cause:"target-not-loaded",detail:`contact ${b} was not loaded (skipped, failed or excluded)`}))},Ue=()=>{let b=_?.linked.size??0,C=_?.own.size??0,W=rt.size;return[...b>0?[`${b} linked to the contact the platform wrote with ${b===1?"its":"their"} person account`]:[],...C>0?[`${C} sent as ${C===1?"a contact of its own":"contacts of their own"}: the target holds ${C===1?"its":"their"} account as a business account`]:[],...W>0?[`${W} not written: a person account's contact goes in with its account`]:[]]},wt=(b,C)=>[...b===je?Ue():[],...C?[C]:[],...g.counts(b).map(({why:W,count:ne})=>Xo(ne,W)),...h.counts(b).map(({why:W,count:ne})=>Oa(ne,W)),...m.counts(b).map(({why:W,count:ne})=>Na(ne,W))].map(W=>`, ${W}`).join(""),De=(b,C,W,ne,oe)=>{let pe=L.findIndex(ft=>ft.objectApiName===b),we=pe>=0?L[pe]:void 0,se=W.filter(ft=>v.has(ft.referenceId)).length,X=we?.inserted??0,K=we?.skippedDuplicates??[],be=we?.failed??[],Be=we?.writtenWithoutFields,ae=W.length-se-X-K.length-be.length,vt=nt({objectApiName:b,fromFiles:C,inserted:X,reused:se,skippedDuplicates:K,failed:be,...Be?{writtenWithoutFields:Be}:{},...ae>0?{notInserted:ae}:{}});we?L[pe]=vt:L.push(vt),o({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*tt/Math.max(he.length,1)),message:`${b}: ${X} inserted, ${vt.reused} reused, ${K.length} duplicates skipped, ${vt.failed.length} failed${Te(b)}${oo(ae)}${Qr(Be)}${wt(b,ne)} \u2014 ${H(oe)}`})},dt,ct=(b,C,W)=>{if(b.waiting>0){let se=L.find(X=>X.objectApiName===Ce);se&&(se.notInserted=(se.notInserted??0)+b.waiting)}let ne=C==="cancel"&&b.waiting>0,oe="";ne?oe=fn(b.waiting):b.waiting>0&&(oe=oo(b.waiting));let pe=b.status;W?pe="error":ne&&b.status!=="error"&&(pe="stopped");let we=W?` \u2014 ${H(W.cause)}`:"";o({phase:"insert",objectName:Ce,status:pe,progress:25+Math.round(55*tt/Math.max(he.length,1)),message:`${b.message}${oe}${b.notes}${we}`})},An=async()=>{let b=et;b&&e.signal?.aborted&&(et=null,ct(b,"cancel")),await B()};t.endOpenLine=b=>{let C=dt;dt=void 0,C&&!(b instanceof _e)&&C(b);let W=et;et=null,W&&ct(W,b instanceof _e?"cancel":"failure")};let We=async()=>{Qt=!0;let b=Fe.splice(0,Fe.length),C=et;if(et=null,b.length===0)return;let W=25+Math.round(55*tt/Math.max(he.length,1)),ne;try{await B()}catch(K){throw C&&ct(C,K instanceof _e?"cancel":"failure"),K}let oe=K=>`${K.inserted} inserted, ${K.reused} reused, ${K.skippedDuplicates.length} duplicates skipped, ${K.failed.length} failed${fn(K.notInserted??0)}${Qr(K.writtenWithoutFields)}`,pe=K=>{let be=L.findIndex(Be=>Be.objectApiName===Ce);be>=0?L[be]=ro(L[be],K):L.push(K)},we={};try{ne=await this.insertObject(e,Ce,0,b,f,y,v,M,ie,k,V,ba(L),K=>{we.result=K})}catch(K){let be=we.result;if(be&&pe(be),C&&be){let Be=be.inserted+be.skippedDuplicates.length+be.failed.length;ct({...C,waiting:Math.max(C.waiting-Be,0),message:`${C.message}; after their task: ${oe(be)}`},"failure",{cause:K})}else C&&ct(C,"failure",{cause:K});throw K}pe(ne);let se=oe(ne),X="done";ne.failed.length>0||C?.status==="error"?X="error":(ne.notInserted??0)>0&&(X="stopped"),o({phase:"insert",objectName:Ce,status:X,progress:W,message:C?`${C.message}; after their task: ${se}${C.notes}`:`${Ce} after their task: ${se}`})};for(let b of he){await An();let C=T.get(b);if(!C){let Q=w.get(b);if(Q&&b===je&&l.size>0){try{await er()}catch(Re){throw o({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*tt/Math.max(he.length,1)),message:`${b}: person accounts' contacts not linked \u2014 ${H(Re)}`}),Re}tr();let me=_?.linked??new Map,ye=Q.failed.filter(Re=>!me.has(Re.referenceId));L.push({...Q,reused:Q.reused+Q.failed.length-ye.length,failed:ye})}else Q&&L.push(Q);continue}tt++,o({phase:"insert",objectName:b,status:"started",progress:25+Math.round(55*tt/Math.max(he.length,1)),message:`Inserting ${b}`});let W,ne=c.objects.find(Q=>Q.objectApiName===b)?.records.length??C.length,oe=C;if(dt=Q=>De(b,ne,oe,W,Q),b===je&&l.size>0){let Q=await er();oe=C.filter(me=>!rt.has(me.referenceId));for(let me of oe){let ye=Q.own.get(me.referenceId),Re=me.fields.AccountId;ye&&(Re==null||Re==="")&&(me.fields.AccountId=ye.accountReferenceId)}}b===ir&&await this.matchDirectRelations(i,c,C,y,v,U),b===Dt&&await this.matchTasksWrittenWithEmails(i,c,C,y,v,U),Nn[b]!==void 0&&(W=await this.matchActivityRelations(e,b,C,y,v,O.get(b)??new Set));let pe=0;if(b===It){let Q=await this.matchContactRolesWrittenWithOpportunities(e,{working:c,aligned:C,refIndex:f,mapping:y,reused:v,withTheirRecord:U,pendingFk:M,fixedAtInsert:O.get(b)??new Set});pe=Q.linked,W=Q.note}let we=St[b],se=we?await this.startAsDrafts(i,b,we,oe,N):oe;if(b===Ce&&!Qt&&Se.size>0){let Q=me=>rs(me,ye=>f.get(ye))&&Se.has(String(me.ActivityId));Fe.push(...se.filter(me=>Q(me.fields))),se=se.filter(me=>!Q(me.fields))}let X=se.filter(Q=>!v.has(Q.referenceId)).length,K=e.signal?.aborted===!0&&X>0,be=(Q,me,ye=Re=>L.push(Re))=>this.insertObject(e,b,me,Q,f,y,v,M,ie,k,V,ba(L),ye),Be=c.standardPricebook,ae;if(K)ae={objectApiName:b,fromFiles:ne,inserted:0,reused:se.length-X,skippedDuplicates:[],failed:[],notInserted:X};else if($r(b)&&Be){let Q=await be(se.filter(ye=>ye.fields[kt]===Be),0),me=se.filter(ye=>ye.fields[kt]!==Be);if(e.signal?.aborted){let ye=me.filter(zd=>v.has(zd.referenceId)).length,Re={...Q,fromFiles:ne,reused:Q.reused+ye},zt=se.length-Re.inserted-Re.reused-Re.skippedDuplicates.length-Re.failed.length;ae={...Re,...zt>0?{notInserted:zt}:{}}}else{let ye={},Re=await be(me,ne,zt=>{ye.result=zt}).catch(zt=>{throw L.push(ye.result?ro(Q,ye.result):{...Q,fromFiles:ne}),zt});ae=ro(Q,Re)}}else ae=await be(se,ne);dt=void 0,b===je&&tr(),ae=nt(ae),pe>0&&(ae={...ae,writtenByThePlatform:pe});let vt=b===Ce?Fe.filter(Q=>!v.has(Q.referenceId)).length:0;(ae.notInserted??0)>0&&(ae.notInserted=(ae.notInserted??0)+vt);let ft=ae.notInserted??0;L.push(ae);let zo=wt(b,W),Co=Te(b),Fn=ae.failed.length>0,No=Fn?"error":"done";!Fn&&ft>0&&(No="stopped");let Do=25+Math.round(55*tt/Math.max(he.length,1)),Tn=`${b}: ${ae.inserted} inserted, ${ae.reused} reused, ${ae.skippedDuplicates.length} duplicates skipped, ${ae.failed.length} failed${Co}${fn(ft)}${Qr(ae.writtenWithoutFields)}`;Co&&ft===0?(et={status:Fn?"error":"done",message:Tn,notes:zo,waiting:vt},o({phase:"insert",objectName:b,status:"started",progress:Do,message:Tn})):o({phase:"insert",objectName:b,status:No,progress:Do,message:`${Tn}${zo}`}),b===Dt&&await We(),ft>0&&await An()}await We(),await B(),o({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let Ke={report:{resolved:0,unresolved:[]},unanswered:0},bt=to(T,b=>y.has(b)),zr=new Set(bt.map(b=>b.opportunity)),rr=M.filter(b=>b.objectApiName!==hr||b.field!==mr||!zr.has(b.referenceId)),nr=bt.length>0?`, ${bt.length} synced quote${bt.length===1?"":"s"} left unset`:"",Rt=b=>ln({phase:"pass2",progress:88,did:`Pass 2: ${Ke.report.resolved} resolved, ${Ke.report.unresolved.length} unresolved${nr}`,refused:Ke.report.unresolved.length,notDone:Ke.unanswered,done:"resolved"},b);try{await this.patchCycleFks(e,rr,y,Ke)}catch(b){throw o(Rt({cause:b})),b}o(Rt());let lt=Ke.report;await B();let He={report:{restored:0,refused:[]},unanswered:0},Cr=b=>ln({phase:"pass2",progress:89,did:`Statuses: ${He.report.restored} applied, ${He.report.refused.length} refused`,refused:He.report.refused.length,notDone:He.unanswered,done:"applied"},b);try{await this.applyDeferredStatuses(e,N,y,He)}catch(b){throw o(Cr({cause:b})),b}let ut=He.report;ut.restored+ut.refused.length+He.unanswered>0&&o(Cr()),await B();let Je=await er(),Nr={restored:Je.linked.size,sent:[...Je.own.values()],unresolved:Je.unlinked};l.size>0&&o({phase:"personcontact",status:Je.unlinked.length>0?"error":"done",progress:94,message:`Person contacts: ${Je.linked.size} linked to the contact the platform wrote with their account, ${Je.own.size} sent as contacts of their own, ${Je.unlinked.length} not linked`}),await B(),await e.lease?.giveBack().catch(()=>{}),o({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await D();let G=g.counts(),ot=h.counts(),Pn=m.counts(),Td=this.writeContract(e,c,L,Y,{now:r,startedAt:n},new Set(w.keys()),[...G.map(({objectApiName:b,count:C})=>({objectApiName:b,count:C,reason:"left-to-the-platform"})),...ot.map(({objectApiName:b,count:C})=>({objectApiName:b,count:C,reason:"untyped-feed-item"})),...Pn.map(({objectApiName:b,count:C})=>({objectApiName:b,count:C,reason:"excluded-parent"}))],rt.size,V,lt.unresolved.filter(b=>b.cause==="target-not-loaded"));o({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let Ed=L.some(b=>b.failed.length>0)||lt.unresolved.length>0||Nr.unresolved.length>0||ut.refused.length>0||q.failures.length>0,Ld=new Set(k.list().flatMap(({referenceIds:b})=>b)),Lo=await this.readBackRecordTypes(i,ja(d,b=>Ld.has(b)),y),jn={status:Ed?"completed-with-errors":"completed",orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},startedAt:n.toISOString(),durationMs:r().getTime()-n.getTime(),alignment:S,placeholders:Y,requiredDefaults:Oe,perObject:L,pass2:lt,personContact:Nr,statuses:ut,purge:q,...G.length>0?{leftToThePlatform:on(G)}:{},...ot.length>0?{untypedFeedItems:ot.map(({objectApiName:b,why:C,count:W})=>({objectApiName:b,count:W,note:Oa(W,C)}))}:{},...Pn.length>0?{heldForExcludedParents:Da(Pn)}:{},...Ca(bt,this.config),...za(d.keysLeftEmpty),...Lo.length>0?{recordTypesGiven:Lo}:{},...x?{runUserId:x}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:Td};return o({phase:"done",status:jn.status==="completed"?"done":"error",progress:100,message:`Load ${jn.status}`}),jn}async checkGuard(e,t,r,n){await this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:t,objectName:r,recordCount:n,module:"frozendataset"})}async consultGuard(e,t){let{check:r,decision:n}=await Yr(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new Ne("guard-refused",`Production guard refused ${t.operation} on ${t.objectName}: ${r.blockedReason??"confirmation declined"}`,{decision:n,...n==="refused"&&r.blockedReason!==void 0?{reason:r.blockedReason}:{}});return n}filterPilotScope(e,t){let r=this.config.rootObjectApiName;if(!r)throw new qe("Pilot mode requires config.rootObjectApiName (the business-folder root object).");let n=e.objects.find(l=>l.objectApiName===r)?.records??[],o=t??n[0]?.referenceId;if(!o||!n.some(l=>l.referenceId===o))throw new qe(`Pilot root ${t??"<first>"} not found in ${r} records (${n.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let i=ka(e),d=new Set([o]),a=!0;for(;a;){a=!1;for(let l of e.objects)for(let u of l.records)d.has(u.referenceId)||Object.values(u.fields).some(p=>typeof p=="string"&&d.has(p))&&(d.add(u.referenceId),a=!0)}let c=l=>{for(;l.length>0;){let u=l.pop(),p=uc(e,u);if(p)for(let g of Object.values(p.fields))typeof g=="string"&&i.has(g)&&!d.has(g)&&(d.add(g),l.push(g))}};c([...d]);let f=lc(e,d).filter(l=>!d.has(l));for(let l of f)d.add(l);return c(f),{...e,objects:e.objects.map(l=>({...l,records:l.records.filter(u=>d.has(u.referenceId))})).filter(l=>l.records.length>0)}}async reuseByIdentityKeys(e,t,r,n){for(let[o,i]of Object.entries(this.config.identityKeys??{})){let d=t.objects.find(a=>a.objectApiName===o)?.records??[];for(let[a,c]of await this.findByKeys(e.orgId,o,i,d))r.set(a,c),n.add(a)}}async findByKeys(e,t,r,n){let o=new Map,i=n.filter(f=>r.every(l=>!Qe(f.fields[l])));if(i.length===0)return o;let d=["Id",...r].map(de).join(", "),a=new Map,c=100;for(let f=0;f<i.length;f+=c){let l=i.slice(f,f+c).map(p=>`(${r.map(g=>`${de(g)} = ${Wd(p.fields[g])}`).join(" AND ")})`).join(" OR "),u=`SELECT ${d} FROM ${de(t)} WHERE ${l}`;for(let p of await this.deps.orgAccess.query(e,u))typeof p.Id=="string"&&a.set(Sa(r.map(g=>p[g])),p.Id)}for(let f of i){let l=a.get(Sa(r.map(u=>f.fields[u])));l&&o.set(f.referenceId,l)}return o}async linkWhatThePlatformKeeps(e,t,r,n,o,i,d){let a={linked:[],said:[],leftEmpty:[]};for(let[c,f]of Object.entries(pr)){let l=this.config.identityKeys?.[c]??f,u=(r.get(c)??[]).filter(g=>!i.has(g.referenceId));if(u.length===0)continue;let p=await this.linkByKeysAsWritten(e,{objectApiName:c,keyFields:l,records:u,missingRequired:t.find(g=>g.objectApiName===c)?.missingRequired??[],ranks:n,accountKindOf:d},o,i,a);p>0&&a.said.push(`${c}: ${p} found by ${l.join(", ")}, which the platform does not delete`)}return a}async reuseByKeysAsWritten(e,t,r,n,o,i,d,a){let c={linked:[],said:[],leftEmpty:[]};for(let[f,l]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(pr,f))continue;let u=new Set((t.objects.find(h=>h.objectApiName===f)?.records??[]).filter(h=>l.some(m=>Qe(h.fields[m]))).map(h=>h.referenceId)),p=(n.get(f)??[]).filter(h=>u.has(h.referenceId)&&!d.has(h.referenceId));if(p.length===0)continue;let g=await this.linkByKeysAsWritten(e,{objectApiName:f,keyFields:l,records:p,missingRequired:r.find(h=>h.objectApiName===f)?.missingRequired??[],ranks:o,accountKindOf:a},i,d,c);g>0&&c.said.push(`${f}: ${g} found by ${l.join(", ")}, as the load writes `+(g===1?"it":"them"))}return c}async linkByKeysAsWritten(e,t,r,n,o){let{objectApiName:i,keyFields:d}=t,a=Xd(t,this.config.requiredFieldDefaults??{}),c=a.flatMap(l=>{let u=d.filter(p=>Qe(l.fields[p]));return u.length>0?[u]:[]});if(c.length>0){let l=d.filter(u=>c.some(p=>p.includes(u)));o.leftEmpty.push({objectApiName:i,fields:l,count:c.length}),o.said.push(`${i}: ${c.length} not looked up, ${l.join(", ")} left empty`)}let f=await this.findByKeys(e,i,d,a);for(let[l,u]of f)r.set(l,u),n.add(l),o.linked.push(l);return f.size}async lookUpTheCatalog(e,t,r,n){let o=[],i=t.standardPricebook;if(i){let[c]=await this.deps.orgAccess.query(e,or);typeof c?.Id=="string"?(r.set(i,c.Id),n.add(i),o.push("standard price book linked")):o.push("standard price book not found")}let d=await this.matchByNaturalKey(e,t,r,n),a=await this.matchSellingModelOptions(e,t,r,n);Ia(t).includes(ve)&&d.push({objectApiName:ve,linked:a});for(let{objectApiName:c,linked:f,notAsked:l}of d)l===void 0&&o.push(`${c}: ${f} linked`);for(let{objectApiName:c,notAsked:f}of d)f!==void 0&&o.push(`${c} not looked up \u2014 ${f}`);return o}async matchByNaturalKey(e,t,r,n){let o=[];for(let[i,d]of Object.entries(Br)){let a=t.objects.find(u=>u.objectApiName===i)?.records??[];if(a.length===0)continue;let c=a.filter(u=>!r.has(u.referenceId)&&d.every(p=>u.fields[p]!==void 0&&u.fields[p]!=="")),f=[];if(c.length>0)try{f=await hs(u=>this.deps.orgAccess.query(e,u),i,d,c.map(u=>u.fields))}catch(u){o.push({objectApiName:i,linked:0,notAsked:H(u)});continue}let l=0;c.forEach((u,p)=>{let g=f[p];g!==void 0&&(r.set(u.referenceId,g),n.add(u.referenceId),l++)}),o.push({objectApiName:i,linked:l})}return o}async matchSellingModelOptions(e,t,r,n){let o=[];for(let d of t.objects.find(a=>a.objectApiName===ve)?.records??[]){if(r.has(d.referenceId))continue;let a=d.fields[Le],c=d.fields[ze],f=typeof a=="string"?r.get(a):void 0,l=typeof c=="string"?r.get(c):void 0;f===void 0||l===void 0||o.push({referenceId:d.referenceId,pair:{[Le]:f,[ze]:l}})}if(o.length===0)return 0;let i=await gs(d=>this.deps.orgAccess.query(e,d),o.map(d=>d.pair));for(let[d,a]of i)r.set(o[d].referenceId,a),n.add(o[d].referenceId);return i.size}async planPurge(e,t,r){let n={residuals:new Map,datedBy:new Map,carried:[],leftUnrecorded:{},keptByThePlatform:{}},o=new Map;for(let[g,h]of r)o.has(te(h))||o.set(te(h),g);let i=new Set,d=(g,h)=>{n.residuals.set(g,[...n.residuals.get(g)??[],h])},a=(g,h)=>{let m=n.carried.at(-1);m?.objectApiName===g?m.referenceIds.push(h):n.carried.push({objectApiName:g,referenceIds:[h]})},c=g=>{n.leftUnrecorded[g]=(n.leftUnrecorded[g]??0)+1},f=[],l=t.some(g=>g.created&&!g.writtenBetween)?await this.targetClockAheadMs():Number.NaN,u=t.map(g=>{let h=new Set;if(!g.created)return h;let m=new Set(g.created.flatMap(y=>y.referenceIds));for(let[y,v]of g.mapping)m.has(y)||h.add(te(v));return h}),p=new Set(u.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[v,P]of g.mapping){let A=te(P);if(o.has(A)||i.has(A))continue;i.add(A);let S=Gd(v);this.mayHaveLinked(S,v)||p.has(A)?c(S):S==="Pricebook2"&&!v.startsWith(un)?f.push(P):d(S,P)}return}let m=g.writtenBetween?jt(g.writtenBetween.last):jt(g.endedAt)+l+_s,y=new Map(Object.entries(g.removalStamps??{}).map(([v,P])=>[te(v),jt(P)]));for(let{objectApiName:v,referenceIds:P}of g.created)for(let A of P){let S=g.mapping.get(A);if(S===void 0)continue;let T=te(S);if(u[h].has(T)||i.has(T))continue;i.add(T);let E=o.get(T);if(E!==void 0){a(v,E);continue}if(this.keptByThePlatform(v)){n.keptByThePlatform[v]=(n.keptByThePlatform[v]??0)+1;continue}d(v,S);let O=[m,y.get(T)??Number.NaN].filter(Number.isFinite);O.length>0&&n.datedBy.set(T,Math.max(...O))}}),f.length>0){let g;try{let[h]=await this.deps.orgAccess.query(e,or);g=typeof h?.Id=="string"?te(h.Id):""}catch{g=void 0}for(let h of f)g===void 0||te(h)===g?c("Pricebook2"):d("Pricebook2",h)}return n}async targetClockAheadMs(){let e=this.deps.serverTime;if(!e)return Number.NaN;let t=Date.now();try{return jt(await e())-(t+Date.now())/2}catch{return Number.NaN}}async foundUnderThePurge(e,t,r,n){let o=new Set([...t.values()].flat().map(te)),i=new Map;for(let[c,f]of r){let l=n.get(c);l===void 0||o.has(te(f))||i.set(l,[...i.get(l)??[],f])}if(o.size===0||i.size===0)return[];let d=new Map,a=(c,f,l)=>{let u=d.get(c)??{keys:new Set,under:new Set};u.keys.add(te(f)),u.under.add(l),d.set(c,u)};for(let c of t.keys()){let f;try{f=(await this.deps.orgAccess.describe(e,c)).cascadeChildren??[]}catch{continue}for(let{childSObject:l,field:u}of f){let p=i.get(l);if(!p)continue;let g;try{g=await this.readRecords(e,l,[u],p)}catch{for(let h of p)a(l,h,c);continue}for(let h of g){let m=h[u];typeof h.Id!="string"||typeof m!="string"||o.has(te(m))&&a(l,h.Id,c)}}}return[...d].map(([c,{keys:f,under:l}])=>({objectApiName:c,count:f.size,under:[...l]}))}mayHaveLinked(e,t){return t.startsWith(un)?!1:e==="Unknown"||e===ve||Object.prototype.hasOwnProperty.call(Br,e)||Object.prototype.hasOwnProperty.call(pr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(pr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,o,i,d,a){let c=t.residuals,f=[],l=[...c.values()].reduce((A,S)=>A+S.length,0),u=0,p=()=>{d.residuals=l-u},g=async()=>{let A=f.splice(0);A.length>0&&await this.giveStatusesBack(e,A,n)},h=async()=>{e.signal?.aborted&&await g(),await o()},m=r.filter(A=>c.has(A)),y=[...c.keys()].filter(A=>!r.includes(A)).sort(),v=[...m,...y],P=new Set;try{P=await this.residualsInSight(e.orgId,c),await this.draftResiduals(e,t,f,h);for(let A of v){let S=c.get(A)??[],T=this.config.undeletableObjects?.[A];if(T!==void 0){await h(),await this.checkGuard(e,"update",A,S.length);let E=await this.deps.writer.update(e.orgId,A,S.map(O=>({Id:O,[T]:!1})));E.forEach((O,w)=>{O.success?(n.deactivated[A]=(n.deactivated[A]??0)+1,i.add(te(S[w]))):n.failures.push({objectApiName:A,recordId:S[w],errors:O.errors})}),u+=E.length}else{let E=$r(A)?await this.customPricesFirst(e.orgId,S):A===ir?[await this.withoutDirectRelations(e.orgId,S)]:[S];u+=S.length-E.reduce((O,w)=>O+w.length,0);for(let O of E){if(O.length===0)continue;await h(),await this.checkGuard(e,"delete",A,O.length);let w=await this.deps.writer.delete(e.orgId,A,O);w.forEach((R,I)=>{ga(R)?(n.deleted[A]=(n.deleted[A]??0)+1,i.add(te(O[I]))):n.failures.push({objectApiName:A,recordId:O[I],errors:R.errors})}),u+=w.length}}}await this.purgeAgain(e,v,n,i,h,a)}catch(A){throw await g(),p(),A}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,i,P),await g(),p()}async residualsInSight(e,t){let r=new Set;for(let[n,o]of t)try{for(let i of await this.readRecords(e,n,[],o))typeof i.Id=="string"&&r.add(te(i.Id))}catch{}return r}async purgeAgain(e,t,r,n,o,i){for(let d of t){if(this.config.undeletableObjects?.[d]!==void 0)continue;let a=r.failures.filter(f=>f.objectApiName===d).map(f=>f.recordId);if(a.length===0)continue;let c=$r(d)?await this.customPricesFirst(e.orgId,a).catch(()=>[a]):[a];for(let f of c){if(f.length===0)continue;await o(),await this.checkGuard(e,"delete",d,f.length),(await this.deps.writer.delete(e.orgId,d,f)).forEach((u,p)=>{let g=r.failures.findIndex(h=>h.objectApiName===d&&h.recordId===f[p]);g<0||(i.tried++,ga(u)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(te(f[p])),i.went++):r.failures[g]={objectApiName:d,recordId:f[p],errors:u.errors})})}}}async settleTakenAlong(e,t,r,n){for(let o of new Set(t.failures.map(i=>i.objectApiName))){let i=t.failures.filter(h=>h.objectApiName===o).map(h=>h.recordId),d=h=>this.readRecords(e,o,[],h),{gone:a,unchecked:c,failure:f}=await $s(i,d,h=>n.has(te(h))),l=f?`Not checked: not read back once the purge was through, to tell whether a parent deleted after it took it along \u2014 ${f}`:"Not checked: the purge could not read it before its delete, nor after \u2014 gone, or out of the session's sight",u=new Set(c.map(te));for(let h of t.failures)h.objectApiName!==o||!u.has(te(h.recordId))||h.errors.includes(l)||(h.errors=[...h.errors,l]);let p=new Set(a.map(te));if(p.size===0)continue;let g=t.failures.filter(h=>h.objectApiName!==o||!p.has(te(h.recordId)));t.failures.splice(0,t.failures.length,...g),t.deleted[o]=(t.deleted[o]??0)+p.size;for(let h of p)r.add(h)}}async draftResiduals(e,t,r,n){for(let[o,i]of Object.entries(St)){if(fs.has(o))continue;let d=t.residuals.get(o);if(!d||d.length===0)continue;let a=await this.statusCategories(e.orgId,i),c=a?.draft;if(!a||!c)continue;let f;try{f=await this.readRecords(e.orgId,o,["Status","LastModifiedDate"],d)}catch{continue}let l=f.flatMap(u=>{let p=a.categoryOf.get(String(u.Status));if(typeof u.Id!="string"||p===void 0||p==="Draft")return[];let g=t.datedBy.get(te(u.Id))??Number.NaN;return[{objectApiName:o,id:u.Id,draft:c,status:String(u.Status),unchanged:jt(u.LastModifiedDate)<=g}]});l.length!==0&&(await n(),await this.checkGuard(e,"update",o,l.length),r.push(...l),await this.deps.writer.update(e.orgId,o,l.map(({id:u})=>({Id:u,Status:c}))))}}async giveStatusesBack(e,t,r){let n=this.deps.restoringWriter??this.deps.writer,o=await this.runningUser(e.orgId),i={};for(let d of new Set(t.map(a=>a.objectApiName))){let a=t.filter(p=>p.objectApiName===d),c=new Map(a.map(p=>[te(p.id),p])),f;try{f=await this.readRecords(e.orgId,d,["Status"],a.map(p=>p.id))}catch(p){for(let g of a)ma(r,g,`its status was not read back: ${H(p)}`);continue}let l=f.flatMap(p=>{let g=typeof p.Id=="string"?c.get(te(p.Id)):void 0;return g&&p.Status===g.draft?[g]:[]});for(let p=0;p<l.length;p+=mt){let g=l.slice(p,p+mt),h;try{await this.checkGuard(e,"update",d,g.length),h=await n.update(e.orgId,d,g.map(({id:m,status:y})=>({Id:m,Status:y})))}catch(m){let y=H(m);h=g.map(()=>({success:!1,errors:[y]}))}g.forEach((m,y)=>{let v=h[y];v?.success||ma(r,m,v?.errors.join("; ")||"the org gave no reason")})}let u=l.filter(p=>p.unchanged);if(!(u.length===0||o===void 0))try{let p=await this.readRecords(e.orgId,d,["LastModifiedDate","LastModifiedById"],u.map(g=>g.id));for(let g of p)typeof g.Id=="string"&&typeof g.LastModifiedDate=="string"&&typeof g.LastModifiedById=="string"&&te(g.LastModifiedById)===o&&(i[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(i).length!==0)try{await this.deps.mappingStore.recordStamps(i)}catch{}}async runningUser(e){let t=await this.runUserIdOf(e);return t?te(t):void 0}async runUserIdOf(e){let t=this.deps.orgAccess.userId;if(t)try{return await t.call(this.deps.orgAccess,e)||void 0}catch{return}}async readBackRecordTypes(e,t,r){let n=[];for(let{given:o,rule:i,keys:d}of t){let a=d.flatMap(c=>r.get(c)??[]);try{let c=await this.deps.orgAccess.query(e,xi(o.objectApiName,a));n.push({...o,readBack:_i(c,i.types)})}catch(c){let f=H(c);n.push({...o,readBack:{read:0,types:[],unread:f}})}}return n}async readRecords(e,t,r,n){let o=["Id",...r].map(de).join(", "),i=[];for(let d=0;d<n.length;d+=mt){let a=n.slice(d,d+mt).map(c=>`'${Ae(c)}'`).join(", ");i.push(...await this.deps.orgAccess.query(e,`SELECT ${o} FROM ${de(t)} WHERE Id IN (${a})`))}return i}async resolveRecordType(e,t,r,n,o,i,d){let a={...n.fields};r===Ee&&delete a[Vr];let c=a.RecordTypeId;if(typeof c!="string"||c==="")return"RecordTypeId"in a&&d.set(n.referenceId,"masterInSource"),delete a.RecordTypeId,{referenceId:n.referenceId,fields:a};let f=t.recordTypes[r]??[],l=n.recordTypeDeveloperName===void 0?void 0:xn(n.recordTypeDeveloperName,f,Fa),u=l&&"found"in l?[l.found]:f.filter(m=>m.name===c),p=u[0];if(!p)return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:a};if(u.length>1)throw Ta(r,c,u);let g=At(p.namespacePrefix,p.developerName),h=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,r,p.developerName,...p.namespacePrefix!==void 0?[p.namespacePrefix]:[]);if(h!==null&&typeof h=="object"&&"ambiguous"in h)throw new qe(`The dataset names ${r} record type ${p.developerName} without its namespace \u2014 it was extracted before SandForge read one \u2014 and ${_n(r,p.developerName,"the target org",h.carriers)}. Extract the dataset again: a dataset extracted now names each record type with its namespace. Nothing was written.`,void 0,{reason:"namespace",objectApiName:r,name:p.developerName,recordTypes:h.carriers.map(m=>At(m.namespacePrefix,m.developerName))});if(h!==null&&typeof h=="object"){let m=await this.deps.recordTypeResolver.givenRecordType?.(e.orgId,r).catch(()=>{});return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:`RecordType ${g} is in the target org but not available to the running user \u2014 RecordTypeId dropped, ${xd(m)}. Assign it to the user's profile or a permission set to keep it.`}),{referenceId:n.referenceId,fields:a}}return h?(a.RecordTypeId=h,o.set(n.referenceId,h),{referenceId:n.referenceId,fields:a}):(delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:`RecordType ${g} not found in target org \u2014 RecordTypeId dropped`}),{referenceId:n.referenceId,fields:a})}async planRequiredFields(e,t){let r=[],n=[];for(let o of t)for(let i of o.missingRequired){let d=`${i.objectApiName}.${i.field}`;if(!i.isLookup){if(this.config.requiredFieldDefaults?.[d]===void 0){let l=i.accountKind?` of a ${i.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${rc(i)} for this required field${l}`)}else r.push({kind:"default",missing:i});continue}let a=this.config.requiredLookupPlaceholders?.[d];if(!a){n.push(`requiredLookupPlaceholders["${d}"]: a placeholder (name + recordTypeDeveloperName) for this required lookup to ${i.referenceTo.join(" or ")||"its parent"}`);continue}let c=a.targetObjectApiName??i.referenceTo[0];if(!c){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let f;if(a.recordTypeDeveloperName){let l=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,c,a.recordTypeDeveloperName);if(l!==null&&typeof l=="object"&&"ambiguous"in l){let u=l.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+_n(c,a.recordTypeDeveloperName,"the target org",l.carriers)+(u?" \u2014 a package's is named with its namespace: "+At(u.namespacePrefix,u.developerName):""));continue}if(l!==null&&typeof l=="object"){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} on ${c} is not available to the running user`);continue}if(f=l??void 0,!f){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} is not on ${c} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:i,key:d,name:a.name,targetObject:c,recordTypeId:f})}if(n.length>0)throw new qe(`The dataset leaves ${n.length} required field(s) empty that the configuration does not cover. Nothing was written. Declare them all, then load again \u2014 records are never silently excluded:
10
+ - ${n.join(`
11
+ - `)}`,n);return r}async createPlaceholder(e,t,r,n,o,i){let{missing:d,key:a,targetObject:c}=t,f={Name:t.name};t.recordTypeId&&(f.RecordTypeId=t.recordTypeId),await this.checkGuard(e,"insert",c,1);let[l]=await this.deps.writer.insert(e.orgId,c,[f]);if(l===void 0&&e.signal?.aborted)return;if(!l?.success||!l.id)throw new qe(`Placeholder insert failed for required lookup ${a} on ${c}: ${l?.errors.join("; ")||"no id returned"}. Fix the target org configuration and retry.`);let u=`${un}${c}:${a}`;n.set(u,l.id),i.add(c,u),this.journal?.created(c,[[u,l.id]]);let p=0;for(let g of r){let h=g.fields[d.field];(h==null||h==="")&&(g.fields[d.field]=l.id,p++)}o.push({objectApiName:d.objectApiName,field:d.field,placeholderObjectApiName:c,placeholderName:t.name,placeholderId:l.id,affectedRecords:p})}applyScalarDefault(e,t,r,n){let o=`${e.objectApiName}.${e.field}`,i=this.config.requiredFieldDefaults?.[o],d=so(i,e.distinct),a=0;for(let c of t)Qe(c.fields[e.field])&&(c.fields[e.field]=io(i,d,{referenceId:c.referenceId,rank:n.get(c.referenceId)??0}),a++);r.push({objectApiName:e.objectApiName,field:e.field,value:i,affectedRecords:a,...d?{perRecord:d}:{}})}async insertObject(e,t,r,n,o,i,d,a,c,f,l,u,p){let g={objectApiName:t,fromFiles:r,inserted:0,reused:0,skippedDuplicates:[],failed:[]},h=n.filter(O=>!d.has(O.referenceId));g.reused=n.length-h.length;let m=[];for(let O of h){let w=Yd(t,O.fields,o,u);w?g.failed.push({objectApiName:t,referenceId:O.referenceId,errors:[w]}):m.push(O)}if(m.length===0)return g;let y=m.map(O=>{let w={},R=[];for(let[j,z]of Object.entries(O.fields))if(!(z===""||z===null||z===void 0))if(typeof z=="string"&&o.has(z)){let x=i.get(z);x&&!(t===hr&&j===mr)?w[j]=x:R.push({objectApiName:t,referenceId:O.referenceId,field:j,targetReferenceId:z})}else w[j]=z;let I=es(t,w);for(let j of I)delete w[j];a.push(...R.filter(j=>!I.includes(j.field)));for(let j of Bo(t,w))delete w[j];return w}),v=(O,w,R)=>{i.set(O,w),f.add(t,O,Bd.some(I=>I in R)),g.inserted++};await this.checkGuard(e,"insert",t,y.length);let P=await this.deps.writer.insert(e.orgId,t,y,(O,w)=>this.journalBatch(t,m,O,w)),A=[];P.forEach((O,w)=>{let R=m[w].referenceId;if(O.success&&O.id){v(R,O.id,y[w]);return}if(Aa(O.errors,c)){g.skippedDuplicates.push({objectApiName:t,referenceId:R,errors:O.errors});return}let I=this.sentAgain(t,y[w],O);I?A.push({...I,referenceId:R,errors:O.errors}):g.failed.push({objectApiName:t,referenceId:R,errors:O.errors})});let S=m.length-P.length;if(S>0&&e.signal?.aborted&&(g.notInserted=S),A.length===0)return g;let T=(O,w)=>{for(let R of O)g.failed.push({objectApiName:t,referenceId:R.referenceId,errors:[...R.errors,`Not written again ${ya(R.fields)}: ${w}`]})};if(e.signal?.aborted)return T(A,"the load was cancelled first"),g;let E;try{await this.checkGuard(e,"insert",t,A.length),E=await this.deps.writer.insert(e.orgId,t,A.map(O=>O.payload),(O,w)=>this.journalBatch(t,A,O,w))}catch(O){throw T(A,H(O)),p?.(g),O}return A.forEach((O,w)=>{let R=E[w];if(!R){T([O],e.signal?.aborted?"the load was cancelled first":"no answer came for it");return}if(R.success&&R.id){v(O.referenceId,R.id,O.payload),g.writtenWithoutFields=Bn(g.writtenWithoutFields,{rows:1,fields:O.fields.map(j=>({...j,rows:1}))});for(let{field:j,replacedWith:z}of O.fields){if(z!==void 0)continue;let x=l.get(t)??new Map;x.set(j,[...x.get(j)??[],O.referenceId]),l.set(t,x)}return}let I=[...R.errors,`Sent again ${ya(O.fields)} after the first refusal: ${O.errors.join("; ")}`];Aa(R.errors,c)?g.skippedDuplicates.push({objectApiName:t,referenceId:O.referenceId,errors:I}):g.failed.push({objectApiName:t,referenceId:O.referenceId,errors:I})}),g}journalBatch(e,t,r,n){let o=this.journal;o&&o.created(e,n.flatMap((i,d)=>{let a=t[r+d];return i.success&&i.id&&a?[[a.referenceId,i.id]]:[]}))}sentAgain(e,t,r){let n=gi(r.errorDetails,t,void 0);if(!n)return;let o={...t},i=n.map(d=>{let a=d.refusedBy==="restricted-picklist"?this.picklistRuleFor(e,d.field):void 0;return a?.action==="replace"&&a.value!==""&&a.value!==t[d.field]?(o[d.field]=a.value,{...d,replacedWith:a.value}):(delete o[d.field],{...d})});return{payload:o,fields:i}}async matchDirectRelations(e,t,r,n,o,i){let d=new Map;for(let u of t.objects.find(p=>p.objectApiName==="Contact")?.records??[])d.set(u.referenceId,u.fields.AccountId);let a=r.filter(u=>{let p=u.fields.ContactId;return typeof p=="string"&&u.fields.AccountId!==void 0&&d.get(p)===u.fields.AccountId&&n.has(p)&&typeof u.fields.AccountId=="string"&&n.has(u.fields.AccountId)});if(a.length===0)return;let c=[...new Set(a.map(u=>n.get(u.fields.ContactId)))],f=await this.deps.orgAccess.query(e,`SELECT Id, AccountId, ContactId FROM AccountContactRelation WHERE IsDirect = true AND ContactId IN (${c.map(u=>`'${Ae(String(u))}'`).join(", ")})`),l=new Map(f.map(u=>[`${String(u.AccountId)}|${String(u.ContactId)}`,u.Id]));for(let u of a){let p=n.get(u.fields.AccountId),g=n.get(u.fields.ContactId),h=l.get(`${String(p)}|${String(g)}`);typeof h=="string"&&(n.set(u.referenceId,h),o.add(u.referenceId),i.set(u.referenceId,u.fields.ContactId))}}async matchTasksWrittenWithEmails(e,t,r,n,o,i){let d=new Set(r.map(f=>f.referenceId)),a=new Map;for(let f of t.objects.find(l=>l.objectApiName===Ce)?.records??[]){let l=f.fields.ActivityId;if(typeof l!="string"||!d.has(l)||o.has(f.referenceId))continue;let u=n.get(f.referenceId);u&&a.set(l,{id:u,key:f.referenceId})}if(a.size===0)return;let c=await ns(f=>this.deps.orgAccess.query(e,f),[...new Set([...a.values()].map(f=>f.id))]);for(let[f,l]of a){let u=c.get(l.id);u!==void 0&&(n.set(f,u),o.add(f),i.set(f,l.key))}}async matchContactRolesWrittenWithOpportunities(e,t){let{aligned:r,refIndex:n,mapping:o,reused:i}=t,d=w=>typeof w=="string"?o.get(w):void 0,a=new Map;for(let w of t.working.objects.find(R=>R.objectApiName===Ea)?.records??[]){let R=o.get(w.referenceId),I=d(w.fields[it]);R&&I&&!i.has(w.referenceId)&&a.set(R,I)}if(a.size===0)return{linked:0};let c=r.map(w=>({OpportunityId:d(w.fields.OpportunityId),[it]:d(w.fields[it]),IsPrimary:w.fields.IsPrimary})),f=Cn(c,w=>a.get(w)).filter(w=>!i.has(r[w].referenceId));if(f.length===0)return{linked:0};let l=w=>{let R={},I=[];for(let[j,z]of Object.entries(w.fields))if(!(j==="OpportunityId"||j===it)&&!t.fixedAtInsert.has(j)&&!(z===""||z===null||z===void 0))if(typeof z=="string"&&n.has(z)){let x=o.get(z);x?R[j]=x:I.push({objectApiName:It,referenceId:w.referenceId,field:j,targetReferenceId:z})}else R[j]=z;return{fields:R,owed:I}},u=new Map(f.map(w=>[w,{opportunity:String(c[w].OpportunityId),contact:String(c[w][it])}])),p=[...new Set(f.flatMap(w=>Object.keys(l(r[w]).fields)))],g=await as(w=>this.deps.orgAccess.query(e.orgId,w),[...new Set([...u.values()].map(({opportunity:w})=>w))],p),{found:h,alike:m}=ds(u,g),y=m.length>0?cs(m.length):void 0;if(h.size===0)return y?{linked:0,note:y}:{linked:0};let v=w=>y?`${w}; ${y}`:w,P=[];for(let[w,R]of h){let I=r[w],j=String(R.Id);o.set(I.referenceId,j),i.add(I.referenceId),t.withTheirRecord.set(I.referenceId,String(I.fields.OpportunityId));let{fields:z,owed:x}=l(I);t.pendingFk.push(...x);let q=Object.entries(z).filter(([Y,L])=>String(R[Y]??"")!==String(L));q.length>0&&P.push({Id:j,...Object.fromEntries(q)})}let A=h.size,S=`${A} written by the platform with ${is(It)}`;if(P.length===0)return{linked:A,note:v(S)};let T=(w,R)=>`${S}, ${w} of them left as it wrote ${w===1?"it":"them"}, without the fields of the source's role: ${R}`;if(e.signal?.aborted)return{linked:A,note:v(T(P.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",It,P.length);let E=await this.deps.writer.update(e.orgId,It,P),O=P.flatMap((w,R)=>{let I=E[R];return I?.success?[]:[I?I.errors.join("; ")||"refused":"no answer came for it"]});return O.length===0?{linked:A,note:v(S)}:{linked:A,note:v(T(O.length,O[0]))}}async matchActivityRelations(e,t,r,n,o,i){let{orgId:d}=e,a=Nn[t],c=l=>typeof l=="string"?n.get(l):void 0,f=await ls(l=>this.deps.orgAccess.query(d,l),t,r.map(l=>({[a]:c(l.fields[a]),RelationId:c(l.fields.RelationId)})));for(let[l,u]of f)n.set(r[l].referenceId,u),o.add(r[l].referenceId);return us(t,[...f].map(([l,u])=>[r[l].fields,u]),l=>!i.has(l),async l=>(await this.checkGuard(e,"update",t,l.length),this.deps.writer.update(d,t,l)),()=>e.signal?.aborted===!0)}async startAsDrafts(e,t,r,n,o){let i=await this.statusCategories(e,r);return i?.draft?n.map(d=>{let a=_t(d.fields.Status,i);return a?(o.push({objectApiName:t,referenceId:d.referenceId,status:String(d.fields.Status)}),{referenceId:d.referenceId,fields:{...d.fields,Status:a}}):d}):n}async withoutDirectRelations(e,t){let r=new Set;for(let n=0;n<t.length;n+=mt){let o=t.slice(n,n+mt).map(d=>`'${Ae(d)}'`).join(", "),i=await this.deps.orgAccess.query(e,`SELECT Id FROM ${ir} WHERE Id IN (${o}) AND IsDirect = true`);for(let d of i)r.add(String(d.Id))}return t.filter(n=>!r.has(n))}async customPricesFirst(e,t){let r=await ps(n=>this.deps.orgAccess.query(e,n),t);return[t.filter(n=>!r.has(n)),t.filter(n=>r.has(n))]}async readWrittenBetween(e,t,r){let n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,referenceIds:d}of t.list()){let a=[...new Set(d.flatMap(f=>{let l=r.get(f);return l?[l]:[]}))],c=t.sentAuditDates(i);for(let f=0;f<a.length;f+=mt){let l=await this.writtenDatesOf(e,i,a.slice(f,f+mt));if(!l)return;for(let u of l){let p=jt(u.SystemModstamp),g=y=>{let v=c?Number.NaN:jt(u[y]);return Number.isFinite(v)?v:p},h=g("CreatedDate"),m=g("LastModifiedDate");Number.isFinite(h)&&(n=Math.min(n,h)),Number.isFinite(m)&&(o=Math.max(o,m))}}}if(!(!Number.isFinite(n)||!Number.isFinite(o)))return{first:new Date(n).toISOString(),last:new Date(Math.max(n,o)).toISOString()}}async writtenDatesOf(e,t,r){let n=r.map(o=>`'${Ae(o)}'`).join(", ");for(let o of Vd)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${o.join(", ")} FROM ${de(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return xt(r=>this.deps.orgAccess.query(e,r),t)}async applyDeferredStatuses(e,t,r,n){let{refused:o}=n.report,i=new Map;for(let d of t){let a=r.get(d.referenceId);a&&i.set(d.objectApiName,[...i.get(d.objectApiName)??[],{...d,id:a}])}n.unanswered=[...i.values()].reduce((d,a)=>d+a.length,0);for(let[d,a]of i){if(e.signal?.aborted)continue;let c=a.map(l=>({Id:l.id,Status:l.status}));await this.checkGuard(e,"update",d,c.length);let f=await this.deps.writer.update(e.orgId,d,c);f.forEach((l,u)=>{l.success?n.report.restored++:o.push({objectApiName:d,referenceId:a[u].referenceId,status:a[u].status,detail:l.errors.join("; ")})}),n.unanswered-=f.length}}async patchCycleFks(e,t,r,n){let{unresolved:o}=n.report,i=new Map,d=new Map;for(let c of t){let f=r.get(c.referenceId),l=r.get(c.targetReferenceId);if(!f||!l){o.push({objectApiName:c.objectApiName,referenceId:c.referenceId,field:c.field,cause:f?"target-not-loaded":"record-not-loaded",detail:f?`referenced record ${c.targetReferenceId} was not loaded (skipped, failed or excluded)`:"child record was not loaded (see perObject failures/skips)"});continue}d.set(f,c.referenceId);let u=i.get(c.objectApiName)??new Map,p=u.get(f)??{Id:f};p[c.field]=l,u.set(f,p),i.set(c.objectApiName,u)}let a=c=>c.reduce((f,l)=>f+Object.keys(l).length-1,0);n.unanswered=[...i.values()].reduce((c,f)=>c+a([...f.values()]),0);for(let[c,f]of i){let l=[...f.values()];if(e.signal?.aborted)continue;await this.checkGuard(e,"update",c,l.length);let u=await this.deps.writer.update(e.orgId,c,l);u.forEach((p,g)=>{p.success?n.report.resolved+=Object.keys(l[g]).length-1:o.push({objectApiName:c,referenceId:d.get(String(l[g].Id))??String(l[g].Id),field:Object.keys(l[g]).filter(h=>h!=="Id").join(","),cause:"update-refused",detail:p.errors.join("; ")})}),n.unanswered-=a(l.slice(0,u.length))}}async linkPersonContacts(e,t,r,n,o,i){let d={linked:new Map,own:new Map,unlinked:[]},a=new Map,c=[...t].map(([u,p])=>({accountReferenceId:p,contactReferenceId:u}));for(let u of c){let p=u.accountReferenceId===""?void 0:r.get(u.accountReferenceId);p!==void 0&&a.set(p,[...a.get(p)??[],u])}let f=a.size===0||o===!1?new Map:await ss(u=>this.deps.orgAccess.query(e,u),[...a.keys()]),l=new Map;for(let[u,p]of a){let g=f.get(u);if(g!==void 0)for(let h of p)l.set(h.contactReferenceId,g)}for(let u of c){let p=l.get(u.contactReferenceId);if(p!==void 0){r.set(u.contactReferenceId,p),d.linked.set(u.contactReferenceId,u.accountReferenceId);continue}if(u.accountReferenceId===""||!r.has(u.accountReferenceId)){d.unlinked.push({...u,cause:"record-not-loaded",detail:u.accountReferenceId===""?wr.accountNotInDataset:wr.accountNotLoaded});continue}if(n.has(u.contactReferenceId))continue;let g=i.find(m=>m.objectApiName===Ee&&m.referenceId===u.accountReferenceId),h=wr.noPersonAccounts;o!==!1&&(h=g?`${wr.businessAccount}: ${g.detail}`:`${wr.businessAccount}: its record type there is no person account's`),d.own.set(u.contactReferenceId,{...u,detail:h})}return d}writeContract(e,t,r,n,o,i,d,a=0,c=new Map,f=[]){let l=new Map;for(let{objectApiName:h,referenceId:m,field:y}of f){let v=l.get(h)??{};v[y]=[...v[y]??[],m],l.set(h,v)}let u=new Map;for(let{objectApiName:h,count:m,reason:y}of d){let v=u.get(h)??{};v[y]=(v[y]??0)+m,u.set(h,v)}let p=[...r];for(let[h,m]of u)p.some(y=>y.objectApiName===h)||p.push({objectApiName:h,fromFiles:t.objects.find(y=>y.objectApiName===h)?.records.length??Object.values(m).reduce((y,v)=>y+v,0),inserted:0,reused:0,skippedDuplicates:[],failed:[]});let g={};for(let h of p){let m={};h.skippedDuplicates.length>0&&(m["duplicate-skipped"]=h.skippedDuplicates.length);let y=h.objectApiName===je?a:0,v=h.failed.filter(O=>Zd(O.errors)).length;if(v>0&&(m["parent-refused"]=v),h.failed.length-v>y){let O=i.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[O]=h.failed.length-v-y}y>0&&(m["person-contact-not-sent"]=y);let P=0;for(let[O,w]of Object.entries(u.get(h.objectApiName)??{}))m[O]=w,P+=w;let A=h.skippedDuplicates.length+h.failed.length+P,S=n.filter(O=>O.placeholderObjectApiName===h.objectApiName).length,T=c.get(h.objectApiName),E=l.get(h.objectApiName);g[h.objectApiName]={fromFiles:h.fromFiles,exclusionReasons:m,excluded:A,added:S,expected:h.inserted+h.reused+S,...T&&T.size>0?{writtenWithout:Object.fromEntries(T)}:{},...E?{parentNotLoaded:E}:{}}}return fa(this.sasGuard,e.sasDir,{version:1,orgId:e.orgId,datasetVersion:t.datasetVersion,writtenAt:o.now().toISOString(),loadStartedAt:o.startedAt.toISOString(),objects:g})}picklistRuleFor(e,t){return this.config.picklistRules?.[`${e}.${t}`]??this.config.defaultPicklistRule??{action:"clear"}}contractPath(e,t){return yr(this.sasGuard,e,t)}};function ba(s){let e=new Map;for(let t of s)for(let r of t.failed)e.set(r.referenceId,t.objectApiName);return e}function Yd(s,e,t,r){if(r.size===0)return;let n=new Set(s===Ce&&!Ln(e,o=>t.get(o))?["ActivityId"]:[]);for(let[o,i]of Object.entries(e)){if(typeof i!="string"||n.has(o)||!t.has(i))continue;let d=r.get(i);if(d!==void 0)return`PARENT_REFUSED: the ${d} record its ${o} names was refused in this load, and written without it this record would stand without its ${d}.`}}function Zd(s){return s.length===1&&s[0].startsWith("PARENT_REFUSED:")}function Qe(s){return s==null||s===""}var La=/\{(n|referenceId)\}/g;function so(s,e){if(typeof s=="string")return s.match(La)?"token":e}function io(s,e,t){return typeof s!="string"||e===void 0?s:e==="token"?s.replace(La,(r,n)=>n==="n"?String(t.rank):t.referenceId):`${s} ${t.rank}`}function Xd(s,e){let{objectApiName:t,keyFields:r,ranks:n,accountKindOf:o}=s,i=s.missingRequired.filter(d=>!d.isLookup&&r.includes(d.field));return s.records.map(d=>{let a={...d.fields};for(let c of i){let f=e[`${t}.${c.field}`];f===void 0||!Qe(a[c.field])||pn(c,[d],o).length!==0&&(a[c.field]=io(f,so(f,c.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:a}})}function za(s,e=!1){return s.length===0?{}:{keysLeftEmpty:s.map(({objectApiName:t,fields:r,count:n})=>{let o=n===1?"its":"their",i=r.join(", "),d="the dataset holds no value, and no default fills it";return{objectApiName:t,fields:[...r],count:n,note:e?`${n} not looked up by ${o} identity keys: ${i} stays empty in what the load would write \u2014 ${d} \u2014 so ${n===1?"it":"they"} would be inserted, never matched`:`${n} not looked up by ${o} identity keys: ${i} stayed empty in what the load wrote \u2014 ${d} \u2014 so ${n===1?"it was":"they were"} sent to be inserted, never matched`}})}}function Qd(s){let e=new Map;for(let t of s.objects)t.records.forEach((r,n)=>e.set(r.referenceId,n+1));return e}function ec(s,e){let t=(s.get(It)??[]).filter(a=>!e.has(a.referenceId));if(t.length===0)return new Set;let r=new Map,n=a=>{if(typeof a!="string"||a==="")return;let c=r.get(a);return c===void 0&&(c=String(r.size+1).padStart(15,"0"),r.set(a,c)),c},o=new Set((s.get(je)??[]).map(a=>a.referenceId)),i=new Map;for(let a of s.get(Ea)??[]){if(e.has(a.referenceId))continue;let c=a.fields[it];typeof c!="string"||!o.has(c)||i.set(n(a.referenceId),n(c))}if(i.size===0)return new Set;let d=t.map(a=>({OpportunityId:n(a.fields.OpportunityId),[it]:n(a.fields[it]),IsPrimary:a.fields.IsPrimary}));return new Set(Cn(d,a=>i.get(a)).map(a=>t[a].referenceId))}function tc(s,e,t,r){let n=f=>(s.get(f)??[]).filter(l=>!e.has(l.referenceId)),o=new Set,i=new Map;for(let f of n(je))t.has(f.referenceId)||i.set(f.referenceId,f.fields.AccountId);let d=new Set((s.get("Account")??[]).map(f=>f.referenceId));for(let f of n(ir)){let{AccountId:l,ContactId:u}=f.fields;typeof l!="string"||typeof u!="string"||i.get(u)===l&&d.has(l)&&o.add(f.referenceId)}let a=new Set([...s.values()].flatMap(f=>f.map(l=>l.referenceId))),c=new Set(n(Dt).map(f=>f.referenceId));for(let f of n(Ce)){let l=f.fields.ActivityId,u=f.fields.RelatedToId;typeof l!="string"||!c.has(l)||typeof u!="string"||!a.has(u)||Ln(f.fields,r)||o.add(l)}return o}function Ra(s,e,t){let{working:r,loading:n,alignedByObject:o,reused:i,reusedByKeys:d,alignment:a,ranks:c}=s,f=s.targetHasPersonAccounts===!1?new Set:s.personContacts,l=w=>(o.get(w)??[]).filter(R=>!i.has(R.referenceId)),u=[...new Set([...s.groupOrder,...r.objects.map(w=>w.objectApiName),...e?[...e.residuals.keys()].sort():[]])],p=0,g=ec(o,i),h=tc(o,i,f,w=>s.refIndex.get(w)),m=[];for(let w of u){let R=r.objects.find(F=>F.objectApiName===w)?.records.length??0,I=e?.residuals.get(w)?.length??0;if(R===0&&I===0)continue;let j=o.get(w),x=(j??n.objects.find(F=>F.objectApiName===w)?.records??[]).filter(F=>i.has(F.referenceId)),q=x.filter(F=>d.has(F.referenceId)).length,Y=j?l(w):[],L=Y.filter(F=>f.has(F.referenceId)).length;p+=L;let k=Y.filter(F=>g.has(F.referenceId)||h.has(F.referenceId)).length,V=(s.filteredLookups.get(w)??[]).flatMap(({field:F,referenceTo:_})=>{let U=Y.filter(re=>!Qe(re.fields[F])).length;return U>0?[{field:F,referenceTo:_,records:U}]:[]}),Z=t.undeletableObjects[w]!==void 0;m.push({objectApiName:w,fromFiles:R,toInsert:Y.length-L-k,reusedByKeys:q,reusedFromCatalog:x.length-q,...k>0?{writtenByThePlatform:k}:{},fieldsDropped:a.removals.filter(F=>F.objectApiName===w).length,picklistsRewritten:a.adjustments.filter(F=>F.objectApiName===w).length,notSent:R-(j?j.length:x.length),toPurge:Z?0:I,toDeactivate:Z?I:0,...V.length>0?{lookupFilters:V}:{}})}let y=(w,R)=>l(w).filter(I=>Qe(I.fields[R])),v=(w,R)=>y(w,R).length,P=w=>{let R=pn(w,y(w.objectApiName,w.field),s.accountKindOf),I=t.requiredFieldDefaults[`${w.objectApiName}.${w.field}`],j=so(I,w.distinct),z=R[0];return{objectApiName:w.objectApiName,field:w.field,affectedRecords:R.length,...j?{perRecord:j}:{},...j&&z?{example:String(io(I,j,{referenceId:z.referenceId,rank:c.get(z.referenceId)??0}))}:{}}},A=e?.leftUnrecorded??{},S=e?.keptByThePlatform??{},T=s.heldForExclusions.counts(),E=ja(s,w=>!i.has(w)&&!f.has(w)).map(({given:w})=>w),O=new Set([...o.values()].flatMap(w=>w.map(R=>R.referenceId)));return{orgId:t.orgId,mode:t.mode,plannedAt:t.plannedAt,perObject:m,excludedObjects:a.excludedObjects,removals:a.removals,placeholders:s.plans.flatMap(w=>w.kind==="placeholder"?[{objectApiName:w.missing.objectApiName,field:w.missing.field,placeholderObjectApiName:w.targetObject,placeholderName:w.name,affectedRecords:v(w.missing.objectApiName,w.missing.field)}]:[]),requiredDefaults:s.plans.flatMap(w=>w.kind==="default"?[P(w.missing)]:[]),recordTypeIssues:s.recordTypeIssues.length,personContacts:p,earlierLoads:s.previousLoads.length,...Object.keys(A).length>0?{leftUnrecorded:A}:{},...Object.keys(S).length>0?{keptByThePlatform:S}:{},...T.length>0?{heldForExcludedParents:Da(T)}:{},...Ca(to(o,w=>O.has(w)),t,!0),...za(s.keysLeftEmpty,!0),...E.length>0?{recordTypesGiven:E}:{}}}var va=5;function rc(s){switch(s.fieldType){case"date":return'a date, as "2026-12-31",';case"datetime":return'a date and time, as "2026-12-31T09:00:00Z",';case"time":return'a time, as "09:00:00.000Z",';case"double":case"currency":case"percent":return"a number";case"int":case"long":return"a whole number";case"boolean":return"true or false";case"picklist":case"multipicklist":{let e=s.activeValues??[];return e.length===0?"one of its values":`one of its active values (${e.slice(0,va).join(", ")}${e.length>va?", \u2026":""})`}case"email":return"an email address";case"string":case"textarea":case"phone":case"url":case"encryptedstring":case"combobox":return"a string";default:return"a value"}}function Ca(s,e,t=!1){let r=ua(s,(e.excludedObjects??[]).includes(eo),t);return r?{quotesLeftUnsynced:[r]}:{}}function nc(s,e,t){for(let r=!0;r;){r=!1;for(let[n,o]of s){let i=[...e.get(n)??[]],d=o.filter(a=>!t.some(c=>c.leaveOut(n,a.referenceId,a.fields,i)));d.length!==o.length&&(s.set(n,d),r=!0)}}}function oc(s,e,t){let r=new Set(t.excludedObjects??[]);if(r.size===0)return[];let n=[];for(let o of e.fields){let i=o.referenceTo??[];i.length===0||!i.every(d=>r.has(d))||!o.createable||o.defaultedOnCreate||Ct(s,o.name,o.nillable)&&(t.requiredLookupPlaceholders?.[`${s}.${o.name}`]||n.push({field:o.name,excludedObject:i[0]}))}return n}function sc(s){return(e,t)=>{for(let{field:r,excludedObject:n}of s.get(e)??[])if(Qe(t[r]))return{field:r,value:"",noun:n}}}function Na(s,e){return e.through?`${s} left out: ${e.through} names a record left out for the ${e.rows.noun} excludedObjects leaves out`:`${s} left out: ${e.rows.field??"a lookup"} names ${/^[AEIOU]/i.test(e.rows.noun)?"an":"a"} ${e.rows.noun} record, which excludedObjects leaves out \u2014 declare a placeholder in requiredLookupPlaceholders to load them`}function Da(s){return s.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:Na(r,t)}))}var ic={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function ac(s,e){if(s!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:ic}function Oa(s,e){let t="extract the dataset again, with rules that keep FeedItem.Type";return e.through?`${s} left out: ${e.through} names a feed item whose type the dataset does not carry \u2014 ${t}`:`${s} feed item${s===1?"":"s"} left out: the dataset does not carry ${s===1?"its":"their"} type, and a tracked change cannot be told from a post \u2014 ${t}`}function ka(s){let e=new Map;for(let t of s.objects)for(let r of t.records)e.set(r.referenceId,t.objectApiName);return e}function dc(s,e,t=new Map){let r=new Map;for(let n of s.objects){let o=r.get(n.objectApiName)??new Set;for(let i of n.records)for(let[d,a]of Object.entries(i.fields))if(!(n.objectApiName===Ee&&d===Vr)&&typeof a=="string"){let c=e.get(a);c&&c!==n.objectApiName&&o.add(c)}r.set(n.objectApiName,o)}t.size>0&&r.has(Ee)&&r.get(je)?.add(Ee);for(let{sourceObject:n,targetObject:o}of pi(new Set(r.keys()),[]))r.get(o)?.add(n);for(let{sourceObject:n,targetObject:o}of ts(new Set(r.keys())))r.get(n)?.delete(o),r.get(o)?.add(n);return r}function cc(s,e,t,r=new Map){let n=new Map;for(let[o,i]of s){let d=e.get(o),a=new Set;if(d)for(let c of i)for(let f of d){let l=c.fields[f],u=typeof l=="string"?t.get(l):void 0;u&&u!==o&&a.add(u)}n.set(o,a)}return r.size>0&&n.set(je,new Set([...n.get(je)??[],Ee])),n}function lc(s,e){let t=h=>s.objects.find(m=>m.objectApiName===h)?.records??[],r=(h,m)=>m.map(y=>String(h[y]??"")).join("|"),n=[Le,ze,_r],o=[Le,ze],i=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(Ye),a=d.filter(h=>e.has(h.referenceId)&&i(h.fields,Le)),c=s.standardPricebook,f=h=>c!==void 0&&h.fields[kt]===c,l=new Set(a.filter(h=>!f(h)).map(h=>r(h.fields,n))),u=d.filter(h=>f(h)&&l.has(r(h.fields,n))),p=new Set([...a,...u].filter(h=>i(h.fields,ze)).map(h=>r(h.fields,o))),g=t(ve).filter(h=>p.has(r(h.fields,o)));return[...u,...g].map(h=>h.referenceId)}function Ia(s){return[...Object.keys(Br),ve].filter(e=>s.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function uc(s,e){for(let t of s.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function Sa(s){return JSON.stringify(s.map(e=>e===void 0?null:e))}function Aa(s,e){return s.some(t=>e.some(r=>t.toLowerCase().includes(r.toLowerCase())))}import{randomBytes as fc}from"node:crypto";import{readFile as pc}from"node:fs/promises";var ao="frozen.salt";function gc(){return fc(32).toString("base64url")}function Ma(s){let e=s[Mi];return e?{salt:e,source:"environment"}:void 0}function wu(s,e=process.env){let t=async()=>{let r=Ma(e);if(r)return r;let n=await s.getSecret(ao);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=gc();if(await s.storeSecret(ao,n),await s.getSecret(ao)!==n)throw new fr;return{salt:n,source:"secretStorage",created:!0}}}}function $a(s=process.env,e){let t=async()=>{let r=Ma(s);if(r)return r;if(e===void 0)return;let n=(await pc(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new fr;return r}}}import{createHash as hc}from"node:crypto";import{appendFileSync as mc,mkdirSync as yc,readFileSync as wc}from"node:fs";import*as vr from"node:path";var bc=15*6e4;function co(s){return`sha256:${hc("sha256").update(vr.resolve(s)).digest("hex").slice(0,16)}`}function xa(s,e){if(!s?.writtenBetween)return;let t=Date.parse(s.endedAt),r=Date.parse(e);if(!Number.isFinite(t)||!Number.isFinite(r)||t<r)return;let n=Date.parse(s.writtenBetween.first),o=Date.parse(s.writtenBetween.last);if(!(!Number.isFinite(n)||!Number.isFinite(o)))return new Date(Math.max(n,o)).toISOString()}function Rc(s,e){return e.some(t=>{let r=Date.parse(t.endedAt),n=Date.parse(t.startedAt??t.endedAt);return Number.isFinite(r)&&s>=(Number.isFinite(n)?n:r)-6e4&&s<=r+bc})}function _a(s,e){let t=[];for(let r of s){let n=Date.parse(r.endedAt);if(!Number.isFinite(n)||(r.sas!==void 0?r.sas===e.sasMark:Rc(n,e.own)))continue;let o=Date.parse(r.lastWriteAt??""),i=Number.isFinite(o)?o:n,d=Date.parse(r.startedAt??r.endedAt);t.push({ids:[],idsUntold:!0,from:Number.isFinite(d)?Math.min(d,i):i,to:i})}return t}var qa="frozen-loads.ndjson";function Ou(s,e){yc(s,{recursive:!0}),mc(vr.join(s,qa),`${JSON.stringify(e)}
12
+ `)}function vc(s,e){return s.slice(0,15)===e.slice(0,15)}function ku(s,e){let t;try{t=wc(vr.join(s,qa),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
13
+ `)){if(n.trim()==="")continue;let o;try{o=JSON.parse(n)}catch{continue}let{organizationId:i,sas:d,startedAt:a,endedAt:c,lastWriteAt:f}=o??{};typeof i!="string"||typeof c!="string"||vc(i,e)&&r.push({endedAt:c,...typeof d=="string"?{sas:d}:{},...typeof a=="string"?{startedAt:a}:{},...typeof f=="string"?{lastWriteAt:f}:{}})}return r}function Ga(s){return s.filter(e=>e.action==="frozen_load"&&e.outcome!=="stopped").map(e=>{let t=e.details?.sas,r=e.details?.startedAt,n=e.details?.lastWriteAt;return{endedAt:e.timestamp,...typeof t=="string"?{sas:t}:{},...typeof r=="string"?{startedAt:r}:{},...typeof n=="string"?{lastWriteAt:n}:{}}})}var Oc="FROZEN_EMAILS_EXCEEDED";function Fu(s,e){return[...Ai(s.counted,e),...s.uncounted!==void 0?[` emails: not counted, ${s.uncounted} could not be read`]:[],...s.deliverability?[` ${Fi(s.deliverability.reading)}`]:[]]}function kc(s){return typeof s.unread=="string"}async function Wa(s){let{read:e,plan:t,writes:r,target:n}=s,o=await ni({read:e,...t?{plan:t}:{},writes:r,readDeliverability:s.readDeliverability,accepted:s.accepted,target:n,run:"load",keepsAddresses:!0,mayMute:s.mayMute}),i=[],d;if(kc(e))d=`the target's automation: ${e.unread}`;else{let l=Nt(e,t,r).automation,u={objects:s.inserts.map(g=>({...g,storageBytes:0}))};d=Ii(l,ki(u));let p=Ho(l);if(p.length>0){let g=await s.readLimits().catch(h=>({unread:H(h)}));i=Oi(u,p,g)}}let a=Si(i,n),c=a?{code:Oc,message:`${a} Nothing was written.`}:o.gate.stop,{deliverability:f}=o.gate;return{run:o,info:{counted:i.map(l=>({...l,objects:[...l.objects]})),...d!==void 0?{uncounted:d}:{},verdict:o.gate.verdict,...f?{deliverability:f}:{},accepted:s.accepted,...c?{refused:{code:c.code,message:c.message}}:{}},...c?{stop:c}:{}}}var Ic="AUTOMATION_NOT_ACCEPTED";function Sc(s){let e=new Set(s);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function Ac(s){return typeof s.unread=="string"}function Pc({kind:s,name:e}){return s==="flow"?`flow "${e}"`:s==="process"?`process "${e}"`:s==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var Ba={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function Va(s){return`${s.objectApiName}: ${Pc(s)} (${s.writes.join(", ")})`}function jc(s,e,t){let r=[];s.firing.length>0&&r.push(`${e} runs automation as this load inserts its records and updates them: ${s.firing.map(Va).join("; ")}.`);for(let{part:n,reason:o}of s.unread??[]){let i=Ba[n];r.push(`${i[0].toUpperCase()}${i.slice(1)} of ${e} could not be read (${o}), so what fires as the load writes is not known.`)}return r.push(...t),r.push(`Nothing was written. Add --accept-automation to load all the same, or turn that automation off in ${e} first.`),r.join(" ")}function lo(s){let{read:e,target:t}=s,r=Sc(s.written),n=[],o=[],i=[];if(Ac(e))o=[{part:"automation",reason:e.unread}];else{let c=Nt(e,s.plan,r),f=new Map;for(let p of c.firing){if(p.write!=="insert"&&p.write!=="update")continue;let g=`${p.objectApiName}\0${p.kind}\0${p.name}`,h=f.get(g);h?h.writes.includes(p.write)||h.writes.push(p.write):f.set(g,{objectApiName:p.objectApiName,kind:p.kind,name:p.name,writes:[p.write]})}n=[...f.values()].map(p=>({...p,writes:["insert","update"].filter(g=>p.writes.includes(g))})),o=Li(e);let l=Ei(c.automation,Ti(c.automation,[...s.written])),u=[...new Set(l.flatMap(p=>p.permissionSet??[]))];i=[...zi(l,t,"the load"),...s.mayMute&&u.length>0?[`With --mute-automation, the load assigns ${u.join(", ")} to the user it writes as for the load alone, under a lease, and what ${u.length===1?"it keeps":"they keep"} quiet does not fire.`]:[]]}if(n.length===0&&o.length===0)return{};let d={firing:n,...o.length>0?{unread:o}:{},accepted:s.accepted};if(s.accepted)return{info:d};let a={code:Ic,message:jc(d,t,i)};return{info:{...d,refused:a},stop:a}}function zu(s,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...s.firing.map(t=>` ${Va(t)}`),...(s.unread??[]).map(({part:t,reason:r})=>` ${Ba[t]} could not be read: ${r}`),...s.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}import*as le from"node:fs/promises";import*as jd from"node:os";import*as fe from"node:path";var Ut=class extends Error{constructor(t,r=[]){super(r.length>0?`${t}:
14
+ - ${r.join(`
15
+ - `)}`:t);this.violations=r;this.name="RulesFileError"}violations},Fc=/^\d+\.\d+\.\d+$/,Ua=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,Tc=new Set(Un);function uo(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function gn(s){let e=[];if(!uo(s))throw new Ut("Rules file must be a JSON object");let t=s.rulesVersion;(typeof t!="string"||!Fc.test(t))&&e.push('rulesVersion is required and must be semver (e.g. "1.0.0")');let r=s.rules;if(!uo(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new Ut("Invalid rules file",e);let n={};for(let[o,i]of Object.entries(r)){if(!Ua.test(o)){e.push(`"${o}": key must match "ObjectApiName.FieldApiName"`);continue}if(!uo(i)){e.push(`"${o}": rule must be an object with a "generator" property`);continue}let d=i.generator;if(typeof d!="string"||!Tc.has(d)){e.push(`"${o}": unknown generator ${JSON.stringify(d)} (supported: ${Un.join(", ")})`);continue}let a=i.approved===!0;if(d==="keep"&&!a){e.push(`"${o}": generator "keep" requires "approved": true (explicit human review)`);continue}let c={generator:d};i.approved!==void 0&&(c.approved=a),typeof i.comment=="string"&&(c.comment=i.comment),n[o]=c}if(e.length>0)throw new Ut("Invalid rules file",e);return{rulesVersion:t,rules:n}}function Ka(s){let e=Object.keys(s.rules).sort(),t={};for(let r of e)t[r]=s.rules[r];return`${JSON.stringify({rulesVersion:s.rulesVersion,rules:t},null,2)}
16
+ `}var Ha={rulesVersion:"1.0.0",rules:{}};function Ja(s){if(s===null)return{found:!1};try{let e=gn(JSON.parse(s));return{found:!0,rulesVersion:e.rulesVersion,ruleCount:Object.keys(e.rules).length}}catch(e){return{found:!0,invalid:e instanceof Error?e.message:String(e)}}}var Ec=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Lc=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...Ec.flatMap(s=>[`BusinessHours.${s}StartTime`,`BusinessHours.${s}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),zc=new Set(["TimeZoneSidKey","LocaleSidKey","LanguageLocaleKey","CurrencyIsoCode","EmailEncodingKey"]);function Ve(s,e,t){let r=`${e}.${t}`,n=s.rules[r]?.generator;return n||(s.personalBySchema?.has(r)===!0?"clear":Lc.has(r)||zc.has(t)||s.keptBySchema?.has(r)===!0?"keep":"clear")}function Ya(s,e,t){let r=new Set(s.keptBySchema??[]),n=new Set(s.personalBySchema??[]);for(let[o,i]of e){let d=new Set(t.detectPII(o,i.map(a=>({apiName:a.name,label:a.label??a.name,type:a.type}))).piiFields.map(a=>a.fieldApiName));for(let a of i){let c=`${o}.${a.name}`;d.has(a.name)?n.add(c):a.type==="picklist"&&(a.restrictedPicklist===!0||a.nillable===!1)&&a.compoundFieldName===void 0&&r.add(c)}}return{...s,keptBySchema:r,personalBySchema:n}}function Za(s,e){let t=new Set;for(let r of s.objects)for(let n of r.records)for(let o of Object.keys(n.fields)){let i=`${r.objectApiName}.${o}`;e.rules[i]===void 0&&Ve(e,r.objectApiName,o)==="keep"&&t.add(i)}return[...t].sort()}function Xa(s,e,t){let r=[];for(let n of s.objects){let o=t.get(n.objectApiName)??[];for(let f of o){let l=Gr(n.objectApiName,f.name);if(f.name==="Id"||f.createable===!1||f.nillable!==!1&&l===void 0||f.defaultedOnCreate===!0||f.type==="reference"||(f.referenceTo?.length??0)>0||Ve(e,n.objectApiName,f.name)!=="clear")continue;n.records.some(p=>{if(l!==void 0&&!$t(l,os(p.fields,!1)))return!1;let g=p.fields[f.name];return g!=null&&g!==""})&&r.push(`${n.objectApiName}.${f.name}`)}let i=n.objectApiName,d=qr(i,f=>o.some(l=>l.name===f&&l.createable!==!1),f=>Ve(e,i,f)!=="clear"),a=`${i}.${d}`;d!==void 0&&n.records.some(f=>{let l=f.fields[d];return l!=null&&l!==""})&&!r.includes(a)&&r.push(a)}return r.sort()}var Cc="Cleared on review of the extraction result: kept in clear text without a rule before.";function Qa(s,e){let t=gn(s),r=e.filter(c=>!Ua.test(c));if(r.length>0)throw new Ut('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(c=>JSON.stringify(c)));let n=s,o={...n.rules},i=[],d=[];for(let c of[...new Set(e)].sort()){if(t.rules[c]!==void 0){d.push(c);continue}o[c]={generator:"clear",comment:Cc},i.push(c)}let a=i.length>0?Nc(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:a,rules:o},rulesVersion:a,cleared:i,alreadyRuled:d}}function Nc(s){let[e,t]=s.split(".").map(Number);return`${e}.${t+1}.0`}import*as ed from"node:fs/promises";import*as td from"node:path";var fo=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,rd=/^[A-Z][A-Z0-9_]*$/,yt=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function Or(s,e){for(let i of Object.keys(e))if(!rd.test(i))throw new yt(`Invalid token name ${JSON.stringify(i)}`);let t=new Set;for(let i of s.matchAll(fo))t.add(i[1]);let r=[...t].filter(i=>!(i in e));if(r.length>0)throw new yt(`Query template references token(s) without a value: ${r.join(", ")}. Token values (ID lists, date bounds) must be provided from the sas at execution time.`);let n=s.replace(fo,(i,d)=>e[d]),o=n.match(fo);if(o)throw new yt(`Unresolved placeholder(s) after render: ${o.join(", ")}`);return n}async function nd(s,e,t){let n=(t??new ee).assertOutsideRepo(td.join(s,e)),o=JSON.parse(await ed.readFile(n,"utf8"));if(typeof o!="object"||o===null||Array.isArray(o))throw new yt(`Token file ${n} must contain a JSON object`);let i={};for(let[d,a]of Object.entries(o)){if(!rd.test(d))throw new yt(`Invalid token name ${JSON.stringify(d)} in ${n}`);if(typeof a!="string")throw new yt(`Token ${d} in ${n} must be a string`);i[d]=a}return i}var kr=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function Dc(s,e){return e?e.aborted?(s.catch(()=>{}),Promise.reject(new kr)):new Promise((t,r)=>{let n=()=>r(new kr);e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})}):s}var Mc=2500,$c=3,xc=5;function _c(s,e){return Object.entries(s).filter(([t,r])=>t!==e&&r>0).sort(([t,r],[n,o])=>o-r||t.localeCompare(n)).slice(0,xc).map(([t,r])=>({objectApiName:t,count:r}))}var Tt=class extends Error{constructor(t,r,n,o){let i=_c(t,o),d=i.map(c=>`${c.objectApiName} ${c.count}`),a=i.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(i.map(c=>c.objectApiName))}), narrow the coverage axes/edge cases, or raise budgetMaxRecords explicitly. `:"Narrow the coverage axes/edge cases or raise budgetMaxRecords explicitly. ";super(`Volumetry budget exceeded: ${r} records measured for a budget of ${n}. ${a}Per-object counts: ${JSON.stringify(t)}`);this.measured=t;this.total=r;this.budgetMax=n;this.name="VolumetryBudgetExceededError",this.heaviest=d}measured;total;budgetMax;heaviest},po=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},hn=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??Mc,n=e.candidatesPerCombination??$c,o=de(e.rootObject),{signal:i}=t,d=p=>t.onProgress?.(p),a=[],c=[],f=[],l={during:"axes",pending:[]},u=()=>{let p={};for(let h of f)for(let[m,y]of Object.entries(h))p[m]=(p[m]??0)+y;let g=Object.values(p).reduce((h,m)=>h+m,0);if(g>r)throw new Tt(p,g,r,o);return{roots:a,uncovered:c,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:i?.reason==="timeout"?"timeout":"cancelled",during:l.during,...l.combinationKey!==void 0?{combinationKey:l.combinationKey}:{},...l.candidate!==void 0?{candidate:l.candidate,candidates:n}:{},notProbed:l.pending}}};try{return await this.run(e,{rootObject:o,budgetMax:r,candidateLimit:n,signal:i,tell:d},{roots:a,uncovered:c,ownMeasures:f,at:l})}catch(p){if(p instanceof kr)return u();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:o,candidateLimit:i,signal:d,tell:a}=t,{roots:c,uncovered:f,ownMeasures:l,at:u}=r,p=S=>Dc(S,d),g=new Map,h=new Map;for(let S of e.axes)a({phase:"axis",axis:S.name}),g.set(S.name,await p(this.enumerateAxisValues(S,e.tokens))),h.set(S.name,await p(this.deps.fieldType?.(n,S.filterField).catch(()=>{})??Promise.resolve(void 0)));let m=e.axes.length===0?[[]]:Wc(e.axes.map(S=>({axis:S.name,values:g.get(S.name)??[]}))),y=S=>S.length===0?"all":S.map(T=>`${T.axis}=${T.value??"NULL"}`).join("|");u.pending=[...m.map(y),...e.edgeCases.map(S=>`edge:${S.name}`)];let v=async(S,T)=>(u.during="combination",u.combinationKey=S,u.candidate=void 0,u.pending=u.pending.filter(E=>E!==S),this.pickHealthyRoot(n,T,i,e.tokens,{step:p,onCandidate:E=>{u.candidate=E,a({phase:"candidate",combinationKey:S,candidate:E,candidates:i})}}));for(let[S,T]of m.entries()){let E=y(T);a({phase:"combination",combinationKey:E,index:S+1,of:m.length});let O=T.map(I=>{let j=de(e.axes.find(z=>z.name===I.axis)?.filterField??"");return I.value===null?`${j} = NULL`:`${j} = ${Gc(I.value,h.get(I.axis))}`}).join(" AND "),w=await v(E,O),R={};for(let I of T)R[I.axis]=I.value;w.id?(c.push({rootRecordId:w.id,combinationKey:E,axisValues:R}),w.measured&&l.push(w.measured)):f.push({combinationKey:E,reason:od(w,i)})}for(let[S,T]of e.edgeCases.entries()){let E=`edge:${T.name}`;a({phase:"combination",combinationKey:E,index:S+1,of:e.edgeCases.length});let O=await v(E,`(${T.whereFragment})`);O.id?(c.push({rootRecordId:O.id,combinationKey:E,axisValues:{},edgeCase:T.name}),O.measured&&l.push(O.measured)):f.push({combinationKey:`edge:${T.name}`,reason:O.probed===0?"no record matches the edge-case marker":od(O,i)})}u.during="measure",u.combinationKey=void 0,u.candidate=void 0,c.length>0&&a({phase:"measure",roots:c.length});let P=c.length===0?{}:await p(this.deps.measureVolumetry(c.map(S=>S.rootRecordId))),A=Object.values(P).reduce((S,T)=>S+T,0);if(A>o)throw new Tt(P,A,o,n);return{roots:c,uncovered:f,volumetry:{measured:P,total:A,budgetMax:o},selectedAt:(this.deps.now?.()??new Date).toISOString()}}async enumerateAxisValues(e,t){let r=Or(e.valuesSoql,t??{}),n=await this.deps.query(r),o=[];for(let i of n){if(!("axisValue"in i))throw new po(`Axis "${e.name}" query must alias its grouped value as axisValue (e.g. SELECT ${e.filterField} axisValue, COUNT(Id) cnt ... GROUP BY ${e.filterField})`);let d=i.axisValue;d==null?o.push(null):typeof d=="string"?o.push(d):o.push(String(d))}return[...new Set(o)].sort((i,d)=>(i??"").localeCompare(d??""))}async pickHealthyRoot(e,t,r,n,o){let i=t===""?`SELECT Id FROM ${e} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`:`SELECT Id FROM ${e} WHERE ${t} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`,d=await o.step(this.deps.query(Or(i,n??{}))),a=0,c;for(let f of d){let l=f.Id;if(typeof l!="string"||l==="")continue;a++,o.onCandidate(a);let u=await o.step(this.deps.checkHealth.check(l));if(u.healthy)return{id:l,probed:a,...u.measured?{measured:u.measured}:{}};c=u.reason}return{id:null,probed:a,lastReason:c}}};function od(s,e){if(s.probed===0)return"no candidate record";let t=`no healthy candidate among the ${s.probed} probed (limit ${e})`;return s.lastReason?`${t} \u2014 last: ${s.lastReason}`:t}var qc=new Set(["int","long","double","currency","percent"]);function Gc(s,e){let t=`'${Ae(s)}'`;switch(e){case"boolean":return/^(true|false)$/i.test(s)?s.toLowerCase():t;case"date":return/^\d{4}-\d{2}-\d{2}$/.test(s)?s:t;case"datetime":return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/.test(s)?s:t;default:return e!==void 0&&qc.has(e)&&/^-?\d+(\.\d+)?$/.test(s)?s:t}}function Wc(s){let e=[[]];for(let{axis:t,values:r}of s){let n=[];for(let o of e)for(let i of r)n.push([...o,{axis:t,value:i}]);e=n}return e}var mn=class{constructor(e,t){this.measure=e;this.expectedObjects=t}measure;expectedObjects;async check(e){let t;try{t=await this.measure([e])}catch(r){return{healthy:!1,reason:`extraction failed: ${r instanceof Error?r.message:String(r)}`}}for(let r of this.expectedObjects)if((t[r]??0)===0)return{healthy:!1,reason:`no ${r} record in this dossier`};return{healthy:!0,measured:t}}};import*as Kt from"node:fs/promises";import*as go from"node:path";var Ir="selection.json";async function sd(s,e,t){let r=t??new ee,n=r.assertOutsideRepo(s);await Kt.mkdir(n,{recursive:!0});let o=r.assertOutsideRepo(go.join(n,Ir));return await Kt.writeFile(o,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
17
+ `,"utf8"),o}async function ho(s,e){let r=(e??new ee).assertOutsideRepo(go.join(s,Ir)),n=JSON.parse(await Kt.readFile(r,"utf8"));if(typeof n!="object"||n===null||n.fileVersion!==1||typeof n.selection!="object")throw new Error(`Invalid selection file at ${r} (expected fileVersion 1)`);return n.selection}import*as Ht from"node:fs/promises";import*as mo from"node:path";var id="discovery.json",Bc=1440*6e4,Vc=st({name:Pe(),fields:Ot(st({name:Pe(),type:Pe(),referenceTo:Ot(Pe())}).loose()),childRelationships:Ot(st({childSObject:Pe(),field:Pe(),relationshipName:Pe()}).loose())}).loose(),Uc=st({fileVersion:qo(1),sourceOrgId:Pe().min(1),rootObject:Pe().min(1),maxNodes:Mo().int().positive(),step:_o(["select","extract"]),discoveredAt:En.datetime(),schemaStamp:En.datetime().optional(),graph:st({nodes:Ot(st({objectApiName:Pe(),included:$o()}).loose()),edges:Ot(st({sourceObject:Pe(),targetObject:Pe()}).loose())}).loose(),describes:xo(Pe(),Vc),objects:Ot(st({name:Pe(),keyPrefix:Pe().nullable()}))});async function ad(s,e,t=new ee){let r=t.assertOutsideRepo(s);await Ht.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(mo.join(r,id));return await Ht.writeFile(n,`${JSON.stringify(e)}
18
+ `,"utf8"),n}async function dd(s,e=new ee){let t=e.assertOutsideRepo(mo.join(s,id)),r;try{r=await Ht.readFile(t,"utf8")}catch{return{none:"no graph kept in the sas"}}let n;try{n=JSON.parse(r)}catch{return{none:"the graph kept in the sas could not be read"}}let o=Uc.safeParse(n);return o.success?{kept:o.data}:{none:"the graph kept in the sas could not be read"}}function cd(s,e,t=new Date){if(s.sourceOrgId!==e.sourceOrgId)return"the graph kept is of another org";if(s.rootObject!==e.rootObject)return`the graph kept is of ${s.rootObject}, not ${e.rootObject}`;if(s.maxNodes!==e.maxNodes)return`the graph kept was discovered at a cap of ${s.maxNodes}, not ${e.maxNodes}`;let r=t.getTime()-Date.parse(s.discoveredAt);if(!(r>=0&&r<=Bc))return`the graph kept was discovered on ${s.discoveredAt}, more than a day ago`;if(!s.schemaStamp)return"the org did not give its clock when the graph kept was discovered"}function ld(s){let e=Date.parse(s);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as wn from"node:fs/promises";import*as ud from"node:path";var Kc="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",Hc="rt-map.json",Jc=10;function Yc(s,e){return lr.has(s)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>lr.has(r))?{...t,nillable:!0}:t)}function Et(s){if(!("attributes"in s))return s;let e={...s};return delete e.attributes,e}var yo=class{constructor(e){this.keyPrefixes=e}keyPrefixes;prefixes=new Map;known=new Set;fromOrg;learnFrom(e){for(let[t,r]of e){let n=r.keys().next();n.done||this.note(t,n.value.slice(0,3))}}async objectsOf(e,t){return t.length<2?t:(!this.known.has(e.slice(0,3))&&this.keyPrefixes&&(this.fromOrg??=this.keyPrefixes().then(r=>{for(let[n,o]of r)this.prefixes.has(n)||this.note(n,o)},()=>{}),await this.fromOrg),fi(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function Sr(s,e){return e.filter(t=>t.type==="reference"&&Ct(s,t.name,t.nillable)).map(t=>t.name)}function Zc(s,e,t){return{objectApiName:s,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}var Xc=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,yn=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Ar=class{deps;soqlBuilder=new ai;constructor(e){this.deps=e}query(e){return ks(e,t=>this.deps.query(t))}async extract(e){if(!Xc.test(e.asOf))throw new yn(`asOf must be a strict ISO instant (e.g. 2026-08-03T09:44:52Z), got ${JSON.stringify(e.asOf)}`);if(e.rootRecordIds.length===0)throw new yn("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new ee,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,o=new Kn;o.add(e.rootObject,e.rootRecordIds),o.addReached(e.rootObject,e.rootRecordIds);let i=new Map,d=new Mt,a=new Set,c={},f=new yo(this.deps.keyPrefixes),l=new Map,u=async R=>{let I=l.get(R);if(I)return I;let j=await this.deps.describeFields(R);return l.set(R,j),j},p=async R=>{let I=await u(R);I.some(z=>z.name==="CreatedDate")||a.add(R);let j=I.filter(z=>z.type==="base64").map(z=>z.name);return j.length>0&&(c[R]=j),I},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(ui(e.graph,g),u,g),m=h.graph,y=[...m.nodes].filter(R=>R.included).sort((R,I)=>R.level-I.level),v=new Set(y.map(R=>R.objectApiName));for(let R of y){let I=await p(R.objectApiName),j=this.selectFields(R.objectApiName,I,e.excludedFields),z=I.some(F=>F.name==="CreatedDate"),x=this.soqlBuilder.build({node:R,fields:Yc(R.objectApiName,I),selectFields:j,edges:m.edges,cache:o,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:z?n:void 0,everyEdge:!lr.has(R.objectApiName),readObjects:v,catalog:lr,fromAboveOnly:!0});if(!x.scoped)continue;let q=[],Y=[];for(let[F,_]of x.statements.entries()){let U=await this.query(_);if(q.push(...U),!(F<x.byIdCount))for(let re of U)typeof re.Id=="string"&&Y.push(re.Id)}let L=d.keep(R.objectApiName,await this.keepWhatStatusesNeed(h.added.get(R.objectApiName),q,i),Sr(R.objectApiName,I)),k=i.get(R.objectApiName);k||(k=new Map,i.set(R.objectApiName,k));let V=[];for(let F of L){let _=F.Id;typeof _!="string"||_===""||(V.push(_),k.has(_)||k.set(_,Et(F)))}o.addRead(R.objectApiName,V);let Z=new Set(V);o.addReached(R.objectApiName,Y.filter(F=>Z.has(F))),f.learnFrom(i);for(let F of I)if(F.type==="reference")for(let _ of L){let U=_[F.name];if(!(typeof U!="string"||U===""))for(let re of await f.objectsOf(U,F.referenceTo))o.add(re,[U])}R.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:I,selectFields:j,bucket:k,cache:o,owners:f,recordsByObject:i,leftToThePlatform:d,extraWhere:z?n:void 0})}await this.readWhatNamedStatusesNeed({nodes:y,edges:m.edges,cache:o,recordsByObject:i,describe:p,asOfWhere:n,excludedFields:e.excludedFields,leftToThePlatform:d}),await this.completeRequiredParents({...e,graph:m},i,p,n,f,d,g),await Qc(i,p,d);let P=await this.addStandardPrices(e,i,n);await this.addSellingModelOptions({...e,graph:m},i,p,n,g);let A=(i.get(xr)?.size??0)>0,S=await this.exclusionCosts(i,p,g,A),T=await this.leaveOutWhatReadsMasked(i,u),E=[...i.entries()].sort(([R],[I])=>R.localeCompare(I)).map(([R,I])=>{let j=[...I.values()].sort((x,q)=>String(x.Id).localeCompare(String(q.Id)));R===Ye&&(j=Wo(j,{sellingModel:A}));let z=j.map((x,q)=>({referenceId:`${R}-${String(q+1).padStart(6,"0")}`,sourceId:String(x.Id),fields:x}));return{objectApiName:R,records:z}}),O=await this.pullRecordTypes(e);await wn.mkdir(r,{recursive:!0});let w=t.assertOutsideRepo(ud.join(r,Hc));return await wn.writeFile(w,`${JSON.stringify(O,null,2)}
19
+ `,"utf8"),{objects:E,asOf:e.asOf,recordTypeMap:O,unboundedObjects:[...a],fileFields:c,...P?{standardPricebookSourceId:P}:{},leftToThePlatform:d.counts(),...S.length>0?{exclusionCosts:S}:{},...T.length>0?{encryptedNotKept:T}:{}}}async leaveOutWhatReadsMasked(e,t){let r=Js(Hs(o=>this.deps.query(o)),async o=>({fields:await t(o)})),n=[];for(let[o,i]of e)if(i.size!==0)for(let d of await r(o)){let a=!1;for(let c of i.values())d in c&&(a||=c[d]!==null&&c[d]!==void 0,delete c[d]);a&&n.push(`${o}.${d}`)}return n.sort()}async withWhatStatusesNeed(e,t,r){let n=new Set(e.nodes.map(a=>a.objectApiName)),o=new Map,i=[],d=[];for(let a of e.nodes){let c=Dr[a.objectApiName];if(!a.included||!c||n.has(c.object)||o.has(c.object)||r.has(c.object))continue;let f;try{f=await t(c.object)}catch{continue}let l=f.find(u=>u.name===c.lookup&&u.type==="reference"&&u.referenceTo.includes(a.objectApiName));l&&(o.set(c.object,{parent:a.objectApiName,lookup:l.name}),i.push(Zc(c.object,f,a.level+1)),d.push({sourceObject:a.objectApiName,targetObject:c.object,relationshipName:l.name,type:"lookup",required:Ct(c.object,l.name,l.nillable)}))}return o.size===0?{graph:e,added:o}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...d]},added:o}}async readWhatTheRootsName(e){let{rootObject:t,bucket:r,cache:n}=e,o=new Set([...n.get(t)??[]].filter(a=>!r.has(a)));if(o.size===0)return;let i=[];for(let a of this.soqlBuilder.buildById({objectApiName:t,selectFields:e.selectFields,ids:o,extraWhere:e.extraWhere}))i.push(...await this.query(a));let d=e.leftToThePlatform.keep(t,i,Sr(t,e.fields));for(let a of d)typeof a.Id=="string"&&!r.has(a.Id)&&r.set(a.Id,Et(a));e.owners.learnFrom(e.recordsByObject);for(let a of e.fields)if(a.type==="reference")for(let c of d){let f=c[a.name];if(!(typeof f!="string"||f===""))for(let l of await e.owners.objectsOf(f,a.referenceTo))n.add(l,[f])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=St[e.parent],o=n?await xt(d=>this.query(d),n):void 0,i=new Set;for(let[d,a]of r.get(e.parent)??[])o&&_t(a.Status,o)&&i.add(d);return t.filter(d=>{let a=d[e.lookup];return typeof a=="string"&&i.has(a)})}async readWhatNamedStatusesNeed(e){for(let[t,r]of Object.entries(Dr)){let n=e.nodes.find(m=>m.objectApiName===r.object),o=e.recordsByObject.get(t),i=St[t];if(!n||!o||o.size===0||!i)continue;let d=e.cache.reachedOf(t),a=[...o].filter(([m])=>!d?.has(m));if(a.length===0)continue;let c=await xt(m=>this.query(m),i);if(!c)continue;let f=a.filter(([,m])=>_t(m.Status,c)).map(([m])=>m);if(f.length===0)continue;let l=await e.describe(r.object),u=new Kn;u.addRead(t,f);let p=this.soqlBuilder.build({node:n,fields:l,selectFields:this.selectFields(r.object,l,e.excludedFields),edges:e.edges,cache:u,rootObjectApiName:`__frozen_root_${t}__`,rootRecordId:f[0],extraWhere:l.some(m=>m.name==="CreatedDate")?e.asOfWhere:void 0,under:new Set([t])});if(!p.scoped)continue;let g=e.recordsByObject.get(r.object);g||(g=new Map,e.recordsByObject.set(r.object,g));let h=Sr(r.object,l);for(let m of p.statements){let y=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let v of y)typeof v.Id=="string"&&!g.has(v.Id)&&g.set(v.Id,Et(v))}}}async completeRequiredParents(e,t,r,n,o,i,d){let a=new Set(e.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName)),c=li(e.graph,d),f=u=>a.has(u)||c.has(u),l=new Map;for(let u=0;u<Jc;u++){o.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(y=>y.type==="reference"&&ci(g,y));for(let y of h.values())for(let v of m){let P=y[v.name];if(typeof P!="string"||P===""||i.has(P)||!v.referenceTo.some(f))continue;let A=(await o.objectsOf(P,v.referenceTo)).filter(f);for(let S of A)t.get(S)?.has(P)||l.get(S)?.has(P)||p.set(S,(p.get(S)??new Set).add(P))}}if(p.size===0)return;for(let[g,h]of p){l.set(g,new Set([...l.get(g)??[],...h]));let m=await r(g),y=t.get(g);y||(y=new Map,t.set(g,y));let v=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(A=>A.name==="CreatedDate")?n:void 0}),P=Sr(g,m);for(let A of v)for(let S of i.keep(g,await this.query(A),P))typeof S.Id=="string"&&!y.has(S.Id)&&y.set(S.Id,Et(S))}}}async addStandardPrices(e,t,r){let n=t.get(Ye);if(!n||n.size===0)return;let[o]=await this.query(or),i=typeof o?.Id=="string"?o.Id:void 0;if(!i)return;let d=g=>[Le,ze,_r].map(h=>String(g[h]??"")).join("|"),a=new Set,c=new Set;for(let g of n.values()){if(g[kt]===i)continue;let h=g[Le];typeof h=="string"&&h!==""&&(a.add(h),c.add(d(g)))}if(a.size===0)return;let f=async(g,h)=>{let m=await this.deps.describeFields(g),y=this.selectFields(g,m,e.excludedFields).map(P=>de(P)).join(", "),v=m.some(P=>P.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${y} FROM ${g} WHERE ${h}${v}`)},l=t.get(Mr);if(l||(l=new Map,t.set(Mr,l)),!l.has(i))for(let g of await f(Mr,`Id = '${Ae(i)}'`))l.set(i,Et(g));let u=await this.deps.describeFields(Ye),p=this.soqlBuilder.buildJoining({objectApiName:Ye,selectFields:this.selectFields(Ye,u,e.excludedFields),split:{field:Le,ids:a},whole:{field:kt,ids:new Set([i])},extraWhere:u.some(g=>g.name==="CreatedDate")?r:void 0});for(let g of p)for(let h of await this.query(g))typeof h.Id!="string"||n.has(h.Id)||c.has(d(h))&&n.set(h.Id,Et(h));return i}async addSellingModelOptions(e,t,r,n,o){if(o.has(ve)||e.graph.nodes.some(m=>m.objectApiName===ve&&!m.included))return;let i=t.get(Ye),d=t.get(di),a=t.get(xr);if(!i||!d||!a)return;let c=m=>`${String(m[Le]??"")}|${String(m[ze]??"")}`,f=new Set,l=new Set,u=new Set;for(let m of i.values()){let y=m[Le],v=m[ze];typeof y!="string"||!d.has(y)||typeof v!="string"||!a.has(v)||(f.add(y),l.add(v),u.add(c(m)))}if(u.size===0)return;let p=await r(ve),g=this.soqlBuilder.buildJoining({objectApiName:ve,selectFields:this.selectFields(ve,p,e.excludedFields),split:{field:Le,ids:f},whole:{field:ze,ids:l},extraWhere:p.some(m=>m.name==="CreatedDate")?n:void 0}),h=t.get(ve);h||(h=new Map,t.set(ve,h));for(let m of g)for(let y of await this.query(m))typeof y.Id!="string"||h.has(y.Id)||u.has(c(y))&&h.set(y.Id,Et(y))}async exclusionCosts(e,t,r,n){if(r.size===0)return[];let o=[],i=a=>`record${a===1?"":"s"}`,d=new Map;for(let[a,c]of e){if(c.size===0)continue;let f=(await t(a)).filter(g=>g.type==="reference"&&g.referenceTo.length===1&&g.referenceTo[0]!==a&&r.has(g.referenceTo[0])&&Ct(a,g.name,g.nillable)),l=a===Ye&&n&&r.has(ve);if(f.length===0&&!l)continue;let u=new Map,p=new Map;for(let[g,h]of c){let m;for(let P of f){let A=h[P.name],S=P.referenceTo[0];if(!(typeof A!="string"||A==="")&&!e.get(S)?.has(A)){m={field:P.name,excluded:S};break}}let y=h[ze];if(!m&&l&&typeof y=="string"&&e.get(xr)?.has(y)&&(m={field:ze,excluded:ve}),!m)continue;u.set(g,m.excluded);let v=p.get(m.excluded)??{field:m.field,count:0};v.count++,p.set(m.excluded,v)}u.size>0&&d.set(a,u);for(let[g,{field:h,count:m}]of p)o.push({objectApiName:a,excludedObject:g,count:m,note:g===ve?`${m} ${a} ${i(m)} sold under a selling model cannot be loaded without the option that sells the product under it, and excludedObjects leaves ${g} out`:`${m} ${a} ${i(m)} cannot be loaded without the ${g} named by ${h}, which excludedObjects leaves out`})}for(let[a,c]of Object.entries(Dr)){let f=e.get(a),l=St[a];if(!f||f.size===0||!l)continue;let u=await xt(y=>this.query(y),l);if(!u)continue;let p=new Set,g=new Map,h=d.get(c.object);for(let[y,v]of e.get(c.object)??[]){let P=v[c.lookup];if(typeof P!="string")continue;let A=h?.get(y);A?g.has(P)||g.set(P,A):p.add(P)}let m=new Map;for(let[y,v]of f){if(!_t(v.Status,u))continue;let P=r.has(c.object)?c.object:p.has(y)?void 0:g.get(y);P&&m.set(P,(m.get(P)??0)+1)}for(let[y,v]of m){let P=v===1;o.push({objectApiName:a,excludedObject:y,count:v,note:`${v} ${a} ${i(v)} past Draft will be loaded as ${P?"a draft":"drafts"} and stay so: `+(y===c.object?`the platform gives ${a} this status only with ${c.object} records under it, and excludedObjects leaves ${c.object} out`:`none of ${P?"its":"their"} ${c.object} records can be loaded without ${y}, which excludedObjects leaves out`)})}}return o}selectFields(e,t,r){let n=new Set(r?.[e]??[]),o=t.map(i=>i.name).filter(i=>!n.has(i));return o.includes("Id")||o.unshift("Id"),o}async pullRecordTypes(e){let t=e.recordTypesSoqlTemplate??Kc,r=Or(t,e.tokens??{}),n=await this.query(r),o=[];for(let i of n)typeof i.Id=="string"&&typeof i.SobjectType=="string"&&typeof i.DeveloperName=="string"&&typeof i.Name=="string"&&o.push({id:i.Id,sobjectType:i.SobjectType,developerName:i.DeveloperName,..."NamespacePrefix"in i?{namespacePrefix:typeof i.NamespacePrefix=="string"&&i.NamespacePrefix!==""?i.NamespacePrefix:null}:{},name:i.Name});return o}};async function Qc(s,e,t){for(let r=!0;r;){r=!1;for(let[n,o]of s){let i=[...o.values()],d=Sr(n,await e(n)),a=t.keep(n,i,d);if(a.length===i.length)continue;r=!0;let c=new Set(a.map(f=>f.Id));for(let f of o.keys())c.has(f)||o.delete(f)}}}var bn=class{anonymize(e){let{rules:t,pseudonymizer:r}=e,n=Object.entries(e.extracted.fileFields??{}).filter(([l,u])=>u.some(p=>Ve(t,l,p)!=="keep")).map(([l])=>l).filter(l=>e.extracted.objects.some(u=>u.objectApiName===l&&u.records.length>0)).sort(),o={...e.extracted,objects:e.extracted.objects.filter(l=>!n.includes(l.objectApiName))},i=new Map;for(let l of o.objects)for(let u of l.records)i.set(u.sourceId,u.referenceId);let d=new Map(o.recordTypeMap.map(l=>[l.id,l])),a={};for(let l of o.objects)a[l.objectApiName]=o.recordTypeMap.filter(u=>u.sobjectType===l.objectApiName).map(u=>({name:u.name,developerName:u.developerName,...u.namespacePrefix!==void 0?{namespacePrefix:u.namespacePrefix}:{}}));let c=[];for(let l of o.objects){let u=l.records.map(p=>{let g=this.anonymizeRecordFields(l.objectApiName,p.fields,i,d,t,r),h=p.fields.RecordTypeId,m=typeof h=="string"?d.get(h):void 0;return{referenceId:p.referenceId,fields:g,...m?{recordTypeDeveloperName:At(m.namespacePrefix,m.developerName)}:{}}});c.push({objectApiName:l.objectApiName,records:u})}let f=o.standardPricebookSourceId?i.get(o.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:c,recordTypes:a,personContactSidecar:el(o,i),...f?{standardPricebook:f}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,o,i){let d={};for(let[a,c]of Object.entries(t)){if(a==="Id")continue;if(c==null){d[a]=c;continue}if(a==="RecordTypeId"&&typeof c=="string"){let l=n.get(c);d[a]=l?l.name:"";continue}if(typeof c=="string"){let l=r.get(c);if(l!==void 0){d[a]=l;continue}}let f=Ve(o,e,a);d[a]=i.pseudonymize(f,c)}for(let[a,c]of Object.entries(d))typeof c=="string"&&Hr(c)&&(d[a]="");return d}};function el(s,e){let t=[],r=s.objects.find(n=>n.objectApiName==="Account");if(!r)return t;for(let n of r.records){let o=n.fields.PersonContactId;if(typeof o!="string"||o==="")continue;let i=e.get(o);i!==void 0&&t.push({accountReferenceId:n.referenceId,contactReferenceId:i})}return t}var tl=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,rl=/^\+3363998\d{4}$/,nl=/^[a-z0-9-]+@example\.invalid$/,ol=/^\d{2}0+$/,sl=3,Rn=class{run(e,t,r,n={}){let o=new Set,i=new Map;for(let l of t.objects)for(let u of l.records)o.add(u.referenceId),i.set(u.referenceId,{objectApiName:l.objectApiName,record:u});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},a=new Map(e.recordTypeMap.map(l=>[l.id,[l.name,l.developerName]])),c=new Set(t.filesLeftOut??[]);for(let l of e.objects)if(!c.has(l.objectApiName))for(let u of l.records){let p=i.get(u.referenceId);if(!p){d.substitution.push({check:"substitution",objectApiName:l.objectApiName,referenceId:u.referenceId,detail:"record missing from the frozen dataset"});continue}let g=u.fields.RecordTypeId;this.checkSubstitution(l.objectApiName,u,p.record,r,d.substitution,new Set(typeof g=="string"?a.get(g)??[]:[]))}for(let l of t.objects)for(let u of l.records)this.checkClearEmpty(l.objectApiName,u,r,o,d["clear-empty"]),this.checkNoResidualId(l.objectApiName,u,o,d["no-residual-id"]);this.checkFormats(e,t,r,i,d.formats);let f=["substitution","clear-empty","formats","no-residual-id"].map(l=>({name:l,passed:d[l].length===0,violations:d[l]}));return{passed:f.every(l=>l.passed),checks:f,author:n.author??"frozen-dataset-engine",checkedAt:(n.now?.()??new Date).toISOString()}}checkSubstitution(e,t,r,n,o,i){for(let[d,a]of Object.entries(t.fields)){if(d==="Id"||a===null||a===void 0||a===""||Ve(n,e,d)==="keep")continue;let f=r.fields[d];if(il(f,a)){o.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:d,detail:"original value still present in its own field"});continue}if(typeof a=="string"&&a.length>=sl)for(let[l,u]of Object.entries(r.fields))l===d||typeof u!="string"||u!==a||Ve(n,e,l)==="keep"||l==="RecordTypeId"&&i.has(u)||o.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:l,detail:`transversal leak: original value of "${d}" found in "${l}"`})}}checkClearEmpty(e,t,r,n,o){for(let[i,d]of Object.entries(t.fields))i!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||Ve(r,e,i)==="clear"&&d!==""&&d!==null&&d!==void 0&&o.push({check:"clear-empty",objectApiName:e,referenceId:t.referenceId,field:i,detail:`residual value under "clear" generator: ${JSON.stringify(d)}`}))}checkFormats(e,t,r,n,o){let i={registrationSIV:d=>tl.test(d),phoneE164:d=>rl.test(d),email:d=>nl.test(d),postalCodeGeneralize:(d,a)=>ol.test(d)&&d.length===a.trim().length};for(let d of e.objects)for(let a of d.records){let c=n.get(a.referenceId);if(c)for(let[f,l]of Object.entries(a.fields)){if(typeof l!="string"||l==="")continue;let u=Ve(r,d.objectApiName,f),p=i[u];if(!p)continue;let g=c.record.fields[f];typeof g!="string"||g===""||p(g,l)||o.push({check:"formats",objectApiName:d.objectApiName,referenceId:a.referenceId,field:f,detail:`format not conserved for ${u}: ${JSON.stringify(g)}`})}}}checkNoResidualId(e,t,r,n){for(let[o,i]of Object.entries(t.fields))typeof i=="string"&&Hr(i)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:o,detail:"checksum-valid Salesforce ID survived the sweep"})}};function il(s,e){return s===e?!0:s==null||e===null||e===void 0?!1:String(s)===String(e)}var Pr=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let o=n===void 0?As(r):{namespacePrefix:n,developerName:r},i=`${e}|${t}|${String(o.namespacePrefix)}|${o.developerName}`,d=this.cache.get(i);if(d!==void 0)return d;let a=`SELECT Id, DeveloperName, NamespacePrefix FROM RecordType WHERE SobjectType = '${Ae(t)}' AND DeveloperName = '${Ae(o.developerName)}'`,c=Ss(await this.orgAccess.query(e,a)),f=Ps(o,c,$n),l;if("ambiguous"in f)l={ambiguous:!0,carriers:f.ambiguous.map($n)};else if("found"in f){let u=f.found.id;l=await this.isUnavailable(e,t,u)?{unavailable:!0,id:u}:u}else l=null;return this.cache.set(i,l),l}async isUnavailable(e,t,r){let n=this.describeOf(e,t);return n?(await n).recordTypeInfos?.find(i=>i.recordTypeId===r)?.available===!1:!1}async givenRecordType(e,t){let r=this.describeOf(e,t);if(r)return rn(Kr((await r).recordTypeInfos))}describeOf(e,t){let r=this.orgAccess.describe;if(!r)return;let n=`${e}|${t}`,o=this.describes.get(n);return o||(o=r(e,t),this.describes.set(n,o)),o}};import*as On from"node:fs";var al=2e3,dl=3,cl=10,ll=s=>new Promise(e=>setTimeout(e,s)),vn=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new ee}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??ll,n=g=>e.onProgress?.(g),o=e.measurementIntervalMs??al,i=e.maxAttempts??dl,d=cn(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let a=null,c=null,f=null,l=0;for(let g=1;g<=i;g++){l=g,f=await this.measure(e,d);let h=wo(f);if(a!==null&&h===a){c=f;break}a=h,g<i&&await r(o)}let u=this.buildChecks(e,d,c??f,c!==null),p={status:ml(u,d,c),checks:u,attempts:l,measuredAt:t().toISOString(),objects:yl(d,c??f)};return e.manifestPath&&(this.consignVerdict(e.manifestPath,p,e.author),p.manifestPath=this.sasGuard.assertOutsideRepo(e.manifestPath)),n({phase:"verify",status:p.status==="passed"?"done":"error",progress:100,message:`Post-load verification: ${p.status} (${l} measurement(s))`}),p}async measure(e,t){return{counts:await this.measureCounts(e,t),orphans:await this.measureOrphans(e,t),personContact:await this.measurePersonContacts(e),presence:await this.measurePresence(e,t)}}async measureCounts(e,t){let r=e.mapping?gd(e.mapping):void 0,n={};for(let o of Object.keys(t.objects).sort()){let i=`SELECT COUNT() FROM ${de(o)}`;if(!r){n[o]=await this.deps.orgAccess.count(e.orgId,i);continue}let d=0;for(let a of hd(r.get(o)??[]))d+=await this.deps.orgAccess.count(e.orgId,`${i} WHERE ${a}`);n[o]=d}return n}async measureOrphans(e,t){let r={},n=e.orphanSampleSize??cl,o=e.mapping?gd(e.mapping):void 0;for(let[i,d]of Object.entries(e.mandatoryLookups??{}))for(let a of d){let c=new Set([...fd(t,i,a),...bo(t.objects[i]?.parentNotLoaded,a)].flatMap(u=>{let p=e.mapping?.get(u);return p===void 0?[]:[p]})),f=o?hd((o.get(i)??[]).filter(u=>!c.has(u))):[""],l=[];for(let u of f){let p=`SELECT Id FROM ${de(i)} WHERE ${de(a)} = null${u?` AND ${u}`:""} ORDER BY Id LIMIT ${n}`,g=await this.deps.orgAccess.query(e.orgId,p);l.push(...g.map(h=>String(h.Id)))}r[`${i}.${a}`]=l.sort().slice(0,n)}return r}async measurePersonContacts(e){let t=e.dataset?.personContactSidecar??[];if(t.length===0||!e.mapping)return{checked:0,unrestored:[]};let r=t.filter(f=>e.mapping?.has(f.accountReferenceId));if(r.length===0||!await this.describesPersonAccounts(e.orgId))return{checked:0,unrestored:[]};let o="SELECT Id, PersonContactId FROM Account WHERE Id IN ("+r.map(f=>e.mapping?.get(f.accountReferenceId)).map(f=>`'${Ae(f)}'`).join(", ")+")",i=await this.deps.orgAccess.query(e.orgId,o),d=new Map(i.map(f=>[String(f.Id),f.PersonContactId===null||f.PersonContactId===void 0?null:String(f.PersonContactId)])),a=[],c=0;for(let f of r){let l=e.mapping.get(f.accountReferenceId),u=d.get(l);u!=null&&(c++,e.mapping.get(f.contactReferenceId)!==u&&a.push(f.accountReferenceId))}return{checked:c,unrestored:a.sort()}}describesPersonAccounts(e){let t=this.personAccounts.get(e);if(!t){let r=this.deps.orgAccess.describe;t=r?r.call(this.deps.orgAccess,e,"Account").then(n=>n.fields.some(o=>o.name==="PersonContactId")).catch(()=>!0):Promise.resolve(!0),this.personAccounts.set(e,t)}return t}async measurePresence(e,t){let r={};if(!e.dataset)return r;for(let[n,o]of Object.entries(e.presenceKeys??{})){let i=new Set(fd(t,n,o)),d=(e.dataset.objects.find(u=>u.objectApiName===n)?.records??[]).filter(u=>!i.has(u.referenceId)),a=[...new Set(d.map(u=>u.fields[o]).filter(u=>typeof u=="string"&&u!==""))].sort();if(a.length===0){r[n]=[];continue}let c=`SELECT ${de(o)} k FROM ${de(n)} WHERE ${de(o)} IN (${a.map(u=>`'${Ae(u)}'`).join(", ")})`,f=await this.deps.orgAccess.query(e.orgId,c),l=new Set(f.map(u=>String(u.k)));r[n]=a.filter(u=>!l.has(u))}return r}buildChecks(e,t,r,n){let o=[];if(o.push({name:"stability",passed:n,detail:n?"Two identical consecutive measurements \u2014 org reads are stable":"No two identical measurements within the attempt budget \u2014 org reads are transiently inconsistent"}),!r)return o;let i=Object.entries(t.objects).filter(([u,p])=>r.counts[u]!==p.expected).map(([u,p])=>`${u}: expected ${p.expected}, got ${r.counts[u]??0}`);o.push({name:"counts",passed:i.length===0,detail:i.length===0?"All object counts match the counting contract":`Count mismatches \u2014 ${i.join("; ")}`});let d=md(t),a=ul(t,r);o.push({name:"load",passed:d.records===0&&a.length===0,detail:pl(d,a)});let c=Object.entries(r.orphans).filter(([,u])=>u.length>0),f=hl(t),l=[...c.length>0?[`Orphans \u2014 ${c.map(([u,p])=>`${u} (${p.length}: ${p.join(", ")})`).join("; ")}`]:[],...f.length>0?["Lookups the load left empty because the record they name was not loaded \u2014 "+f.map(({link:u,count:p})=>`${u} (${p})`).join("; ")]:[]];if(o.push({name:"orphans",passed:l.length===0,detail:l.length===0?"No orphans on the mandatory lookups of the graph":l.join("; ")}),(e.dataset?.personContactSidecar?.length??0)>0&&e.mapping&&o.push({name:"personcontact",passed:r.personContact.unrestored.length===0,detail:r.personContact.unrestored.length===0?`All ${r.personContact.checked} person account(s) hold the contact the load linked`:`Person accounts without the contact the load linked \u2014 accounts: ${r.personContact.unrestored.join(", ")}`}),e.dataset&&Object.keys(e.presenceKeys??{}).length>0){let u=Object.entries(r.presence).filter(([,p])=>p.length>0);o.push({name:"presence",passed:u.length===0,detail:u.length===0?"All referential keys present in the org":`Missing keys \u2014 ${u.map(([p,g])=>`${p}: ${g.join(", ")}`).join("; ")}`})}return o}consignVerdict(e,t,r){let n=this.sasGuard.assertOutsideRepo(e),o=qt(JSON.parse(On.readFileSync(n,"utf8")));o.controls.dryRunLoad={status:t.status==="passed"?"passed":"failed",at:t.measuredAt,detail:`post-load check by ${r??"unknown"}: verdict=${t.status}; `+t.checks.map(i=>`${i.name}=${i.passed?"OK":"KO"}`).join(", ")},On.writeFileSync(n,oa(o),"utf8")}};function wo(s){return Array.isArray(s)?`[${s.map(wo).join(",")}]`:typeof s=="object"&&s!==null?`{${Object.entries(s).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${wo(r)}`).join(",")}}`:JSON.stringify(s)}function fd(s,e,t){return bo(s.objects[e]?.writtenWithout,t)}function bo(s,e){let t=s?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var jr={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function md(s){let e={whole:[],part:[],refused:0,heldBack:0,notLoadable:[],records:0};for(let[t,r]of Object.entries(s.objects).sort(([n],[o])=>n.localeCompare(o))){let n=c=>c.reduce((f,l)=>f+(r.exclusionReasons[l]??0),0),o=n(jr.notLoadable);o>0&&e.notLoadable.push({objectApiName:t,records:o});let i=n(jr.refused),d=n(jr.heldBack),a=i+d;a!==0&&(e.refused+=i,e.heldBack+=d,e.records+=a,r.expected===0?e.whole.push({objectApiName:t,notLoaded:a}):e.part.push({objectApiName:t,notLoaded:a,of:a+r.expected}))}return e}function ul(s,e){return Object.entries(s.objects).sort(([t],[r])=>t.localeCompare(r)).flatMap(([t,r])=>{let n=e.counts[t]??0;return n<r.expected?[{objectApiName:t,gone:r.expected-n,of:r.expected}]:[]})}function fl(s){return s.length===0?"":`${s.reduce((t,r)=>t+r.gone,0)} record(s) it wrote or linked are no longer in the target \u2014 `+s.map(t=>`${t.objectApiName} (${t.gone} of ${t.of})`).join(", ")}function pl(s,e=[]){let t=gl(s),r=fl(e);if(s.records===0)return r===""?`Every record the load had to write went in${t}`:`The load wrote every record it had to, and ${r}${t}`;let n=[...s.whole.length>0?["Objects the load wrote none of \u2014 "+s.whole.map(i=>`${i.objectApiName} (${i.notLoaded} not loaded)`).join(", ")]:[],...s.part.length>0?["Objects it wrote part of \u2014 "+s.part.map(i=>`${i.objectApiName} (${i.notLoaded} of ${i.of} not loaded)`).join(", ")]:[]],o=[...s.refused>0?[`${s.refused} refused by the target org`]:[],...s.heldBack>0?[`${s.heldBack} held back for a parent the target org refused`]:[]];return`${s.records} record(s) not loaded: ${o.join(", ")}. ${n.join("; ")}${r===""?"":`; ${r}`}${t}`}function gl(s){return s.notLoadable.length===0?"":`; ${s.notLoadable.reduce((t,r)=>t+r.records,0)} record(s) not loadable, as the preview said \u2014 `+s.notLoadable.map(t=>`${t.objectApiName} (${t.records})`).join(", ")}function hl(s){let e=[];for(let[t,r]of Object.entries(s.objects).sort(([n],[o])=>n.localeCompare(o)))for(let n of Object.keys(r.parentNotLoaded??{}).sort()){let o=bo(r.parentNotLoaded,n).length;o>0&&e.push({link:`${t}.${n}`,count:o})}return e}function ml(s,e,t){if(t===null)return"unstable";let r=s.filter(i=>!i.passed);if(r.length===0)return"passed";let n=Object.values(t.orphans).some(i=>i.length>0);return r.every(i=>i.name==="load"||i.name==="orphans")&&!n&&md(e).whole.length===0?"partial":"failed"}function yl(s,e){let t=r=>r.slice(0,r.indexOf("."));return Object.entries(s.objects).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{let o=[...jr.refused,...jr.heldBack].reduce((l,u)=>l+(n.exclusionReasons[u]??0),0),i=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([l])=>t(l)===r).reduce((l,[,u])=>l+u.length,0),a=e?.presence[r]?.length??0,c=r==="Account"?e?.personContact.unrestored.length??0:0,f=e!==null&&i===n.expected&&o===0&&d===0&&a===0&&c===0;return{objectApiName:r,status:f?"passed":"failed",expected:n.expected,found:i,notLoaded:o,orphans:d,missingKeys:a,...c>0?{personContactsUnlinked:c}:{}}})}var pd=200;function gd(s){let e=new Map;for(let[t,r]of s){let n=t.startsWith("placeholder:")?t.split(":")[1]:t.slice(0,t.lastIndexOf("-"));if(!n)continue;let o=e.get(n)??[];o.push(r),e.set(n,o)}return e}function hd(s){let e=[];for(let t=0;t<s.length;t+=pd){let r=s.slice(t,t+pd).map(n=>`'${Ae(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var vo=200;function Oo(s,e=vo){return{insert:(t,r,n,o)=>Ro(s.insert(r,n,e,o?wl(o):void 0)),update:(t,r,n)=>Ro(s.update(r,n,e)),delete:(t,r,n)=>Ro(s.delete(r,n,e))}}function wl(s){let e=0,t=0;return{sending:(r,n,o)=>{t=o},answered:(r,n,o,i)=>{i?o.forEach((d,a)=>{let c=i[a];c!==void 0&&s(c,[d])}):(s(e,o),e+=t),t=0}}}async function Ro(s){try{return await s}catch(e){if(e instanceof Xi)return e.written;throw e}}var bl=200;function yd(s){let e={threshold:s.threshold,perCall:vo,...s.duplicateRules?{duplicateRules:s.duplicateRules}:{}},t=s.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:o})=>n+Math.ceil(o/bl),0);return Yn(t,e)+Yn((s.purged??[]).filter(({rows:n})=>n>0),e)+ea(t.length,s.automationRead??0)+r}var Rl={insert:async()=>{throw new Error("A preview writes nothing.")},update:async()=>{throw new Error("A preview writes nothing.")},delete:async()=>{throw new Error("A preview writes nothing.")}},vl=new Set(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:manifest:get","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"]),kn="REPLACE_LEAVES_RECORDS",Yt=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},Zt=class extends Error{constructor(t,r,n,o){super(r);this.code=t;this.emails=n;this.orgId=o;this.name="LoadEmailsStop"}code;emails;orgId},Er=class extends Error{constructor(t,r,n,o){super(r);this.code=t;this.automation=n;this.orgId=o;this.name="LoadAutomationStop"}code;automation;orgId},Lr=class extends Error{constructor(t,r,n){super(t);this.apiRequests=r;this.orgId=n;this.name="LoadBudgetStop"}apiRequests;orgId;code=Vn};function Ol(s,e){let t=yi(s,e);return{verdict:s.verdict,estimate:s.estimate,...s.verdict==="unread"?{unread:s.unread}:{remaining:s.remaining,max:s.max},...s.parts?{parts:{...s.parts}}:{},...t!==void 0?{refused:{code:Vn,message:t}}:{}}}function Fr(s,e){let t=[...new Set(s.map(r=>r.objectApiName))];return Jo({setToDraft:xs(t),delete:Gs(t)},e)}function ko(s){return s.status==="success"&&(s.left??[]).length===0}function wd(s){return s.verdict!=="nothingSends"||s.counted.length>0||s.uncounted!==void 0}function kl(s,e){if(e.includeChanged||s.refusal!==void 0||s.status!=="partial"&&s.status!=="failure")return s;let t=s.objects.every(o=>o.refused===0&&o.deleted+o.alreadyGone+o.keptChanged===o.found),r=(s.left??[]).some(o=>o.class==="late"&&e.sweepLate||o.class==="untied"&&e.sweepUntied),n=s.objects.some(o=>o.keptChanged>0);return t&&!r&&n?{...s,status:"success"}:s}var Tr="frozen",bd="frozen:config",Jt="frozen:lastRun",Rd="frozen:lastRuns",Io="frozen:lastVerify",So="frozen:lastVerifies",vd="tokens.json",Il="rules.json",Xt=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},Sl=async s=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(s),{preview:!1})},Al="0.1.0",Pl=10*6e4,jl=15*6e4,Od=30*6e4,Ao=6e4,kd=12e4,Fl=50;function Tl(s,e){let t=0,r=null,n=null,o=d=>{s(...d),t=Date.now(),r=null},i=((...d)=>{r=d;let a=e-(Date.now()-t);a<=0?(n&&(clearTimeout(n),n=null),o(d)):n||(n=setTimeout(()=>{n=null,r&&o(r)},a))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&o(r)},i}function Id(s,e){let t=Tl(s,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),s(n)},{flush:t.flush})}async function Ge(s){try{return await le.access(s),!0}catch{return!1}}function El(s){return s.check==="clear-empty"?'residual value under "clear" generator (value redacted at the bridge)':s.detail.length>200?`${s.detail.slice(0,200)}\u2026`:s.detail}function Fd(s){return{passed:s.passed,author:s.author,checkedAt:s.checkedAt,checks:s.checks.map(e=>({name:e.name,passed:e.passed,violations:e.violations.slice(0,Fl).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:El(t)}))}))}}function Po(s){return{version:s.version,status:s.status,frozenAt:s.frozenAt,source:s.source,saltFingerprint:s.saltFingerprint,rulesVersion:s.rulesVersion,volumetry:s.volumetry,controls:{nonReidentification:Fd(s.controls.nonReidentification),dryRunLoad:s.controls.dryRunLoad,author:s.controls.author,date:s.controls.date},...s.coverage?{coverage:s.coverage}:{}}}function Ll(s,e,t){return{combinations:s.roots.map(r=>({combinationKey:r.combinationKey,axisValues:r.axisValues,edgeCase:r.edgeCase})),uncovered:s.uncovered,volumetry:s.volumetry,selectedAt:s.selectedAt,selectionPath:e,...t?{graph:t}:{},...s.stopped?{stopped:s.stopped}:{}}}function jo(s,e){if(!e||e.length===0)return s;let t=new Set(e);return{...s,nodes:s.nodes.map(r=>t.has(r.objectApiName)?{...r,included:!1}:r)}}function Sd(s,e){return{objects:s.nodes.filter(Ni).length,truncated:s.truncated===!0,maxNodes:e}}function zl(s){return s.length===0?"":` Kept in the org, the platform does not delete them: ${s.map(({objectApiName:t,count:r})=>`${t} (${r})`).join(", ")}.`}function Fo(s,e){if(!s)return{message:"No load into this org was recorded in this sas: there is nothing to remove.",code:"NO_LOAD"};if(s.orgId!==e.targetOrgId||s.endedAt!==e.loadedAt)return{message:"Another load was recorded since this one was shown, and nothing was removed: check what a removal takes now, then confirm it again.",code:"LOAD_CHANGED"};if(!s.created)return{message:"This load was recorded before loads kept what they created: its records cannot be told from the ones it linked, and cannot be removed from here, nor replaced by a reload, which would delete what someone changed since.",code:"NOT_RECORDED"};if(xe(s).length>0)return;let t=zl(sn(s));return s.removal?{message:`The records this load created were already removed, on ${s.removal.removedAt}.${t}`,code:"ALREADY_REMOVED"}:t?{message:`This load created no record a removal takes.${t}`,code:"NOTHING_TO_REMOVE"}:{message:"This load created no record to remove.",code:"NOTHING_TO_REMOVE"}}function To(s){let e=s.writtenBetween,t=s.startedAt===void 0?Number.NaN:Date.parse(s.startedAt),r=Date.parse(s.endedAt);return{...e?{runStartedAt:new Date(e.first),runEndedAt:new Date(e.last)}:{...Number.isFinite(t)&&Number.isFinite(r)?{runDurationMs:Math.max(0,r-t)}:{},...Number.isFinite(r)?{runRecordedAt:new Date(r),endedByItsWrites:!0}:{}},removalStamps:s.removalStamps,removalSpans:s.removalSpans,...s.runUserId?{runUserId:s.runUserId}:{}}}function Cl(s,e=!1){let t=new Map;for(let{objects:r}of s)for(let n of r){let o=n.heldByAutomation??0,i=(n.keptDependents??0)-(e?o:0),d=n.heldBy&&n.heldBy.length>0?n.heldBy.join(", "):"",a=[n.keptChanged>0?`${n.keptChanged} changed since the load`:"",i>0?(d?`${i} kept for records that stay under them (${d})`:`${i} kept as what hangs from them could not be read`)+(!e&&o>0?`, ${o} of them for what the target's automation likely made for the load, which a sweep takes first`:""):"",n.undeletable>0?`${n.undeletable} the user may not delete`:"",n.notVisible>0?`${n.notVisible} out of the user's sight`:"",n.unread>0?`${n.unread} that could not be read`:""].filter(Boolean),c=n.keptChanged+Math.max(0,i)+n.undeletable+n.notVisible+n.unread;if(c===0)continue;let f=t.get(n.objectApiName)??{left:0,why:new Set};f.left+=c;for(let l of a)f.why.add(l);t.set(n.objectApiName,f)}return[...t].map(([r,{left:n,why:o}])=>({objectApiName:r,left:n,why:[...o]}))}function Nl(s){return{status:s.status,orgId:s.orgId,mode:s.mode,startedAt:s.startedAt,durationMs:s.durationMs,alignment:{excludedObjects:s.alignment.excludedObjects,removals:s.alignment.removals,adjustments:s.alignment.adjustments,recordTypeIssues:s.alignment.recordTypeIssues},placeholders:s.placeholders,requiredDefaults:s.requiredDefaults,perObject:s.perObject,pass2:s.pass2,personContact:s.personContact,statuses:s.statuses,purge:s.purge,...s.leftToThePlatform?{leftToThePlatform:s.leftToThePlatform}:{},...s.untypedFeedItems?{untypedFeedItems:s.untypedFeedItems}:{},...s.heldForExcludedParents?{heldForExcludedParents:s.heldForExcludedParents}:{},...s.quotesLeftUnsynced?{quotesLeftUnsynced:s.quotesLeftUnsynced}:{},...s.keysLeftEmpty?{keysLeftEmpty:s.keysLeftEmpty}:{},...s.recordTypesGiven?{recordTypesGiven:s.recordTypesGiven}:{},...s.runUserId?{runUserId:s.runUserId}:{},mappingPath:s.mappingPath,contractPath:s.contractPath}}function Dl(s){return s.status==="completed"?"success":s.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function Ml(s){let e=s.perObject.reduce((t,r)=>t+r.failed.length,0)+s.purge.failures.length;return Sn(s)===0&&e===0?"stopped":"cancelled"}function Sn(s){let e=t=>Object.values(t).reduce((r,n)=>r+n,0);return s.perObject.reduce((t,r)=>t+r.inserted,0)+s.placeholders.length+e(s.purge.deleted)+e(s.purge.deactivated)}function Ad(s){return`frozen:${s}`}var In=(s,e)=>e==="insert"||e==="update",Lt=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function Eo(s){let e=new Map,t=r=>{let n=e.get(r)??ws(r);return e.set(r,n),n};for(let r of s.perObject){let n=t(r.objectApiName);n.created+=r.inserted,n.failed+=r.failed.length+r.skippedDuplicates.length,r.notInserted&&(n.notSent=(n.notSent??0)+r.notInserted),r.writtenWithoutFields&&(n.writtenWithoutFields=(n.writtenWithoutFields??0)+r.writtenWithoutFields.rows)}for(let r of s.placeholders)t(r.placeholderObjectApiName).created+=1;for(let[r,n]of Object.entries(s.purge.deleted))t(r).deleted+=n;for(let[r,n]of Object.entries(s.purge.deactivated))t(r).updated+=n;for(let r of s.purge.failures)t(r.objectApiName).failed+=1;return[...e.values()]}async function $l(s,e){try{let t=await e.load();return Object.fromEntries(s.objects.map(r=>[r.objectApiName,r.records.filter(n=>t.has(n.referenceId)).length]))}catch{return}}var Pd=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=$a();openInEditor=Sl;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new ei;loading=new Map;beforeRunCheckpoints;describeCache=new Hn({defaultTtl:5*6e4,maxSize:2e3,maxSizeBytes:200*1024*1024,releaseExpired:!0});describeGlobalCache=new Hn({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});forgetOrg(e){this.describeCache.invalidateByPrefix(`${e}::`),this.describeGlobalCache.invalidate(e)}setRegistry(e){this.registry=e}setRulesEditor(e){this.openInEditor=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setRemovalAsker(e){this.removalAsker=e}removalAsker;ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>ue(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setSaltKeeper(e){this.saltKeeper=e}isWritingTo(e,t){if(this.writing.has(e))return!0;for(let[r,n]of this.loading)if(n===e&&(t===void 0||t!==Ad(r)))return!0;return!1}async loadingDuring(e,t){let r=Zr(e,"targetOrgId");if(r===void 0)return t();this.loading.set(e.id,r);try{await t()}finally{this.loading.delete(e.id)}}async handle(e){if(!vl.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"frozen:config:get":return this.handleConfigGet(e),!0;case"frozen:config:save":return this.handleConfigSave(e),!0;case"frozen:select":return await this.handleSelect(e),!0;case"frozen:extract":return await this.handleExtract(e),!0;case"frozen:manifest:get":return await this.handleManifestGet(e),!0;case"frozen:load":return await this.loadingDuring(e,()=>this.handleLoad(e)),!0;case"frozen:load:preview":return await this.handlePreview(e),!0;case"frozen:verify":return await this.handleVerify(e),!0;case"frozen:remove":return await this.writing.during(Zr(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(Zr(e,"targetOrgId"),()=>this.handleRemoveSweep(e)),!0;case"frozen:remove:automation":return await this.handleRemoveAutomation(e),!0;case"frozen:remove:preview":return await this.handleRemovePreview(e),!0;case"frozen:status":return await this.handleStatus(e),!0;case"frozen:rules:clear":return await this.handleRulesClear(e),!0;case"frozen:rules:create":return await this.handleRulesCreate(e),!0;default:return!1}}loadConfig(){return this.deps.configStore.get(bd)??null}handleConfigGet(e){let t=this.loadConfig(),r=ce(this.deps,e,"frozen:config:get:response",{config:t,sasDir:this.resolveSasDir(t),datasetDir:this.resolveDatasetDir(t)});this.deps.broker.postToWebview(r)}handleConfigSave(e){let t=$e(js,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(bd,t.config,Tr);let r=ce(this.deps,e,"frozen:config:save:response",{success:!0});this.deps.broker.postToWebview(r)}resolveSasDir(e){return e?.sasDir??fe.join(jd.homedir(),".sandforge-sas")}resolveDatasetDir(e){return e?.datasetDir??fe.join(this.resolveSasDir(e),"dataset")}resolveRulesPath(e){return fe.resolve(e?.rulesFilePath??fe.join(this.resolveSasDir(e),Il))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await Ge(t)?await le.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:H(n)}}return{path:t,...Ja(r)}}async loadTokens(e,t){return await Ge(fe.join(e,vd))?nd(e,vd,t):{}}async describeObject(e,t){let r=`${e}::${t}`,n=this.describeCache.get(r);if(n)return n;let o=await new ht(3e4).withTimeout(`frozen:describe:${t}`,async()=>{let d=await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:d.name,fields:d.fields.map(a=>({name:a.name,label:a.label,type:a.type,referenceTo:a.referenceTo??[],relationshipName:a.relationshipName??null,isMasterDetail:a.cascadeDelete===!0,nillable:a.nillable!==!1,createable:a.createable!==!1,updateable:a.updateable!==!1,restrictedPicklist:a.restrictedPicklist===!0,defaultedOnCreate:a.defaultedOnCreate===!0,...a.compoundFieldName?{compoundFieldName:a.compoundFieldName}:{}})),childRelationships:(d.childRelationships??[]).map(a=>({childSObject:a.childSObject,field:a.field,relationshipName:a.relationshipName??a.field,isCascadeDelete:a.cascadeDelete===!0}))}},3e4);return this.describeCache.set(r,o),o}buildDiscoveryService(){return new Di({describeObject:(e,t)=>this.describeObject(e,t),queryCount:async(e,t)=>(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,detectPII:e=>{let t=this.deps.infraServices?.piiDetector;return t?Ys(t,e):[]},describeGlobal:e=>this.describeGlobal(e)})}async describeGlobal(e){let t=this.describeGlobalCache.get(e);if(t)return t;let o=(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.map(i=>({name:i.name,keyPrefix:i.keyPrefix??null}));return this.describeGlobalCache.set(e,o),o}async keyPrefixes(e){let t=new Map;for(let{name:r,keyPrefix:n}of await this.describeGlobal(e))n&&t.set(r,n);return t}discoveryConfig(e,t){return{inputMode:"record",recordId:t,depth:"full",sourceOrgId:e,targetOrgId:e,anonymizePII:!1,skipEmpty:!0,batchSize:"auto"}}discoveryOptions(e){return{maxNodes:e.maxNodes??Ci}}async graphOfStep(e){let{sourceOrgId:t,config:r,sasDir:n,guard:o}=e,{maxNodes:i}=this.discoveryOptions(r),d={sourceOrgId:t,rootObject:r.rootObject,maxNodes:i},a=await dd(n,o),c;if("kept"in a){let p=a.kept,g=cd(p,d)??await this.schemaChangeSince(t,p);if(g===void 0)return this.holdKeptDescribes(t,p),{graph:p.graph,origin:{reusedFrom:p.step,discoveredAt:p.discoveredAt}};c=g}else c=a.none;let f;try{let p=await ue(t,this.deps.orgRegistry,this.deps.orgManager);f=ld((await p.soap.getServerTimestamp()).timestamp)}catch(p){this.deps.log(`[WARN] frozen: the source did not give its clock: ${String(p)}`)}let l=await this.buildDiscoveryService().discover(this.discoveryConfig(t,e.rootRecordId),{maxNodes:i,...e.signal?{signal:e.signal}:{},...e.onProgress?{onProgress:e.onProgress}:{}}),u=new Date().toISOString();return{graph:l,origin:{rediscovered:c},keep:async p=>{let g=new Set([...l.nodes.filter(m=>m.included).map(m=>m.objectApiName),...p]),h={};for(let m of g){let y=this.describeCache.get(`${t}::${m}`);y&&(h[m]=y)}await ad(n,{fileVersion:1,...d,step:e.step,discoveredAt:u,...f?{schemaStamp:f}:{},graph:l,describes:h,objects:this.describeGlobalCache.get(t)??[]},o)}}}async schemaChangeSince(e,t){if(!t.schemaStamp)return"the graph kept carries no stamp of the org";try{let n=await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).request({method:"GET",url:"/sobjects",headers:{"If-Modified-Since":new Date(t.schemaStamp).toUTCString()}}),o=typeof n=="object"&&n!==null?n.sobjects:void 0;return Array.isArray(o)?(this.forgetOrg(e),this.describeGlobalCache.set(e,o.flatMap(i=>{let{name:d,keyPrefix:a}=i??{};return typeof d=="string"?[{name:d,keyPrefix:typeof a=="string"?a:null}]:[]})),`the source's schema changed since the graph kept was discovered, on ${t.discoveredAt}`):void 0}catch(r){return`the source could not say whether its schema changed: ${H(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,Od);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,Od)}async describeScopableFields(e,t){return(await this.describeObject(e,t)).fields.map(n=>({name:n.name,type:n.type,referenceTo:n.referenceTo,nillable:n.nillable!==!1}))}async ruleSchemaOf(e,t){let r=new Map;for(let{objectApiName:n}of t)try{let o=await this.describeObject(e,n);r.set(n,o.fields)}catch(o){this.deps.log(`[WARN] frozen: ${n} could not be described for the rules: ${String(o)}`)}return r}mappingStoreFor(e,t,r){let n=async()=>{try{let[o]=await this.buildTargetOrgAccess().query(t,"SELECT Id FROM Organization");return typeof o?.Id=="string"?o.Id:void 0}catch(o){this.deps.log(`[WARN] frozen: the target did not say which org it is: ${String(o)}`);return}};return new Zn(e,{orgId:t,organizationId:n,guard:r})}buildTargetOrgAccess(){return{query:async(e,t)=>{let r=await ue(e,this.deps.orgRegistry,this.deps.orgManager);return Ur(r,t)},count:async(e,t)=>(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,describe:async(e,t)=>{let n=await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:n.name,createable:n.createable,cascadeChildren:(n.childRelationships??[]).flatMap(o=>o.cascadeDelete===!0&&typeof o.field=="string"&&o.field!==""?[{childSObject:o.childSObject,field:o.field}]:[]),fields:n.fields.map(o=>({name:o.name,type:o.type,createable:o.createable??!1,nillable:o.nillable??!0,defaultedOnCreate:o.defaultedOnCreate??!1,referenceTo:o.referenceTo??[],restrictedPicklist:o.restrictedPicklist??!1,picklistValues:(o.picklistValues??[]).map(i=>({value:i.value,active:i.active??!0})),updateable:o.updateable!==!1,unique:o.unique===!0,nameField:o.nameField===!0,...typeof o.filteredLookupInfo=="object"&&o.filteredLookupInfo!==null?{lookupFilter:{optional:o.filteredLookupInfo.optionalFilter===!0}}:{}})),recordTypeInfos:(n.recordTypeInfos??[]).flatMap(o=>{let{developerName:i,active:d}=o;return i?[{developerName:i,recordTypeId:o.recordTypeId,available:o.available,name:o.name,master:o.master,defaultRecordTypeMapping:o.defaultRecordTypeMapping,...d===void 0?{}:{active:d}}]:[]})}},picklistValues:async(e,t,r,n)=>{let o=await ue(e,this.deps.orgRegistry,this.deps.orgManager);return Gi(o,t,r,n)},userId:async e=>(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).soap.getUserInfo()).userId}}toLoadConfig(e){return{protectedOrgIds:e.protectedOrgIds,identityKeys:e.identityKeys,undeletableObjects:e.undeletableObjects,requiredLookupPlaceholders:e.requiredLookupPlaceholders,excludedObjects:e.excludedObjects,requiredFieldDefaults:e.requiredFieldDefaults,picklistRules:e.picklistRules,defaultPicklistRule:e.defaultPicklistRule,duplicateErrorPatterns:e.duplicateErrorPatterns,rootObjectApiName:e.rootObject}}async readFrozenDataset(e,t){let r=t.assertOutsideRepo(e),n=t.assertOutsideRepo(fe.join(r,"manifest.json"));if(!await Ge(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let o=qt(JSON.parse(await le.readFile(n,"utf8"))),i=[],d=t.assertOutsideRepo(fe.join(r,"data"));if(await Ge(d))for(let u of(await le.readdir(d)).sort()){if(!u.endsWith(".json"))continue;let p=t.assertOutsideRepo(fe.join(d,u)),g=JSON.parse(await le.readFile(p,"utf8"));i.push({objectApiName:g.objectApiName,records:g.records})}let a=async(u,p)=>{let g=t.assertOutsideRepo(fe.join(r,u));return await Ge(g)?JSON.parse(await le.readFile(g,"utf8")):p},c=await a("record-types.json",{}),f=await a("personcontact-sidecar.json",[]),l=await a(sa,{});return{dataset:{datasetVersion:o.version,objects:i,recordTypes:c,personContactSidecar:f,...l.standardPricebook?{standardPricebook:l.standardPricebook}:{}},manifest:o}}errorCodeFor(e,t){return e instanceof Xt?"RULES_MISSING":e instanceof Ne?"GUARD_REFUSED":e instanceof ra?"SAS_PATH_REFUSED":e instanceof fr?"SALT_MISSING":e instanceof Tt?"BUDGET_EXCEEDED":e instanceof qe?"LOAD_CONFIG":e instanceof br?"MAX_RECORDS":e instanceof Vt?kn:e instanceof Ze?"TIMEOUT":t}errorDetailOf(e){if(e instanceof Xt)return{rulesPath:e.rulesPath};if(e instanceof Ne)return{guard:e.code,...e.params};if(e instanceof Tt)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof qe&&e.gaps)return{gaps:e.gaps};if(e instanceof qe&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof Zt)return{emails:e.emails,orgId:e.orgId};if(e instanceof Er)return{automation:e.automation,orgId:e.orgId};if(e instanceof Lr)return{apiRequests:e.apiRequests,orgId:e.orgId}}loadEmailsFor(e){return Wa({read:e.read,...e.plan?{plan:e.plan}:{},writes:e.writes,inserts:e.dataset.objects.map(t=>({objectApiName:t.objectApiName,rows:t.records.length})).filter(t=>t.rows>0),readLimits:()=>vi(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(ti):ri(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await hi(e.conn).catch(o=>({unread:H(o)})),r=qi(e.read),n=mi({run:yd({inserts:e.dataset.objects.map(o=>({objectApiName:o.objectApiName,rows:o.records.length})),...e.purged?{purged:e.purged}:{},threshold:Dn(this.deps).bulk.threshold,...r?{duplicateRules:r}:{},automationRead:Pi(e.read)}),...wi(e.checkpoint),...oi(e.plan),...ji(e.emails?.run.ofRun)},t);return n.verdict==="unread"&&this.deps.log(`[WARN] ${e.operation}: the daily API requests the target has left could not be read (${n.unread})`),Ol(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>xe(n)).map(({objectApiName:n,ids:o})=>({objectApiName:n,rows:o.length,deletes:!Object.hasOwn(r,n)}))}orgNameOf(e){let t=this.deps.orgManager.getOrg(e);return Uo(t,e)}requireConfig(e,t){let r=this.loadConfig();return r||(J(this.deps,e.type,t,e,new Error("No frozen dataset configuration saved \u2014 save the project configuration first (frozen:config:save: coverage axes, root object, budget, load rules)."),{code:"CONFIG_MISSING"}),null)}async handleSelect(e){let t=$e(Fs,e,"frozen:select:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:select:error");if(!r)return;let n=`frozen-select-${this.deps.nextId()}`;ar(this.deps,n,"frozen","Running coverage-matrix selection");let o="Coverage-matrix selection",i=new AbortController,d=setTimeout(()=>i.abort("timeout"),Pl),a=()=>{},c=new Promise((l,u)=>{a=p=>p===void 0?l():u(p)});c.catch(()=>{}),this.registry?.register(e.id,"frozen",o,c,i),this.liveTracker?.register(e.id,"frozen",o);let f=l=>{this.deps.broker.postToWebview(ce(this.deps,e,"frozen:select:progress",{...l})),l.phase==="combination"&&l.index!==void 0&&l.of&&this.liveTracker?.updateProgress(e.id,Math.round((l.index-1)/l.of*100),l.index-1,l.of,l.combinationKey??"")};try{let l=new ee,u=l.assertOutsideRepo(this.resolveSasDir(r)),p=await ue(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async L=>{let k=g.get(L);return k||(k=Ur(p,L),g.set(L,k),k.catch(()=>g.delete(L))),(await k).map(V=>({...V}))},m=await this.loadTokens(u,l),y=this.discoveryOptions(r),v=new Set,P=new Ar({query:h,describeFields:L=>(v.add(L),this.describeScopableFields(t.sourceOrgId,L)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),A=new Date().toISOString(),S,T=0,E=async L=>(S??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:u,guard:l,rootRecordId:L,signal:i.signal,onProgress:k=>{k.phase==="object"&&(k.discoveredCount-T<10&&k.queueRemaining>0||(T=k.discoveredCount,f({phase:"discovery",objects:k.discoveredCount})))}}),jo((await S).graph,r.excludedObjects)),O=async L=>{if(L.length===0)return{};let k=await E(L[0]),V=await P.extract({graph:k,rootObject:r.rootObject,rootRecordIds:L,asOf:A,sasDir:u,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:l}),Z={};for(let F of V.objects)Z[F.objectApiName]=F.records.length;return Z},w=new mn(O,r.expectedObjects??[]),R=async(L,k)=>(await this.describeObject(t.sourceOrgId,L)).fields.find(V=>V.name.toLowerCase()===k.toLowerCase())?.type,j=await new hn({query:h,checkHealth:w,measureVolumetry:O,fieldType:R}).select({rootObject:r.rootObject,axes:r.axes,edgeCases:r.edgeCases,budgetMaxRecords:r.budgetMaxRecords,candidatesPerCombination:r.candidatesPerCombination,tokens:m},{signal:i.signal,onProgress:f}),z=await sd(u,j,l),x=S&&!j.stopped?await S.catch(()=>{}):void 0;x?.keep&&await x.keep(v).catch(L=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(L)}`)});let q=x?jo(x.graph,r.excludedObjects):void 0,Y=ce(this.deps,e,"frozen:select:response",{selection:{...Ll(j,z,q?Sd(q,y.maxNodes):void 0),...x?{discovery:x.origin}:{}}});this.deps.broker.postToWebview(Y),at(this.deps,n,{roots:j.roots.length,total:j.volumetry.total,...j.stopped?{stopped:j.stopped.reason}:{}}),j.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),a()}catch(l){this.liveTracker?.fail(e.id,H(l)),a(l),J(this.deps,"frozen:select","frozen:select:error",e,l,{code:this.errorCodeFor(l,"SELECT_ERROR"),retryable:l instanceof Ze,extraPayload:this.errorDetailOf(l)})}finally{clearTimeout(d)}}async handleExtract(e){let t=$e(Es,e,"frozen:extract:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:extract:error");if(!r)return;let n=`frozen-extract-${this.deps.nextId()}`;ar(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let o=new ee,i=o.assertOutsideRepo(this.resolveSasDir(r)),d=o.assertOutsideRepo(this.resolveDatasetDir(r)),a=await this.saltKeeper.forExtraction(),c=new tn(a.salt);if(a.created&&this.sayTheSaltWasMade(c.saltFingerprint),!await Ge(fe.join(i,Ir))){J(this.deps,"frozen:extract","frozen:extract:error",e,new Error(`No selection found in ${i} \u2014 run the coverage-matrix selection first (frozen:select).`),{code:"SELECTION_MISSING"});return}let f=await ho(i,o),l=f.roots.map(k=>k.rootRecordId);if(l.length===0){J(this.deps,"frozen:extract","frozen:extract:error",e,new Error("The last selection kept no root: every combination was uncovered, and the selection says why for each. Adjust the axes or the expected objects, then run the selection again."),{code:"SELECTION_EMPTY"});return}let u=await this.loadTokens(i,o),p=this.resolveRulesPath(r);if(!await Ge(p))throw new Xt(p,`Pseudonymization rules file not found at ${p} \u2014 it is the source of truth (object.field \u2192 generator). Create it, or set rulesFilePath in the configuration.`);let g=gn(JSON.parse(await le.readFile(p,"utf8"))),h=await ue(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=this.discoveryOptions(r),y=await this.graphOfStep({step:"extract",sourceOrgId:t.sourceOrgId,config:r,sasDir:i,guard:o,rootRecordId:l[0]}),v=jo(y.graph,r.excludedObjects),P=new Set,A=new Ar({query:k=>Ur(h,k),describeFields:k=>(P.add(k),this.describeScopableFields(t.sourceOrgId,k)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),S=t.author??"sandforge",T=r.datasetVersion??Al,{extracted:E,frozen:O,report:w,requiredLeftEmpty:R,keptUnruled:I}=await new ht(jl).withTimeout("frozen:extract",async()=>{let k=await A.extract({graph:v,rootObject:r.rootObject,rootRecordIds:l,asOf:new Date().toISOString(),sasDir:i,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:u,guard:o}),V=await this.ruleSchemaOf(t.sourceOrgId,k.objects),Z=Ya(g,V,this.deps.infraServices?.piiDetector??new Zs),F=new bn().anonymize({extracted:k,rules:Z,pseudonymizer:c,datasetVersion:T}),_=new Rn().run(k,F,Z,{author:S});return{extracted:k,frozen:F,report:_,requiredLeftEmpty:Xa(k,Z,V),keptUnruled:Za(k,Z)}});R.length>0&&this.deps.log(`[WARN] frozen: the rules leave ${R.length} required field(s) empty, which a load will ask a value for: ${R.join(", ")}`),y.keep&&await y.keep(P).catch(k=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(k)}`)});let j=ce(this.deps,e,"frozen:control:result",{report:Fd(w)});if(this.deps.broker.postToWebview(j),!w.passed){J(this.deps,"frozen:extract","frozen:extract:error",e,new Error("Non-reidentification control FAILED \u2014 nothing was written. Fix the rules file and re-run the extraction (see frozen:control:result for the failing checks)."),{code:"CONTROL_FAILED"});return}let z={};for(let k of O.objects)z[k.objectApiName]=k.records.length;let x=this.deps.orgManager.getOrg(t.sourceOrgId),q=na({version:T,source:{orgId:t.sourceOrgId,orgAlias:x?.alias,decisionDate:f.selectedAt},saltFingerprint:c.saltFingerprint,rulesVersion:g.rulesVersion,volumetry:{budgetMax:f.volumetry.budgetMax,measured:z,measuredAt:new Date().toISOString()},nonReidentification:w,author:S,coverage:{...Sd(v,m.maxNodes),unboundedObjects:E.unboundedObjects,filesLeftOut:O.filesLeftOut??[],...(E.leftToThePlatform??[]).length>0?{leftToThePlatform:on(E.leftToThePlatform??[])}:{},...E.exclusionCosts?{exclusionCosts:E.exclusionCosts}:{},...R.length>0?{requiredLeftEmpty:R}:{},...I.length>0?{keptWithoutARule:I}:{},encryptedNotKept:E.encryptedNotKept??[]}}),Y=await new ia(o).write(d,O,q,w),L=ce(this.deps,e,"frozen:extract:response",{datasetDir:Y.dir,files:Y.files,recordCount:Wt(O),manifest:Po(q),discovery:y.origin});this.deps.broker.postToWebview(L),at(this.deps,n,{records:Wt(O),version:q.version})}catch(o){J(this.deps,"frozen:extract","frozen:extract:error",e,o,{code:this.errorCodeFor(o,"EXTRACT_ERROR"),retryable:o instanceof Ze,extraPayload:this.errorDetailOf(o)})}}async handleRulesClear(e){let t=$e(Ts,e,"frozen:rules:clear:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:rules:clear:error");if(r)try{let n=this.resolveRulesPath(r);if(!await Ge(n))throw new Xt(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let o=Qa(JSON.parse(await le.readFile(n,"utf8")),t.fields);if(o.cleared.length>0){let d=`${n}.${process.pid}.writing`;await le.writeFile(d,`${JSON.stringify(o.payload,null,2)}
20
+ `,"utf8"),await le.rename(d,n),this.deps.log(`[INFO] frozen: ${o.cleared.length} field(s) given a clear rule in ${n} (rules ${o.rulesVersion}): ${o.cleared.join(", ")}`)}let i=ce(this.deps,e,"frozen:rules:clear:response",{rulesPath:n,rulesVersion:o.rulesVersion,cleared:o.cleared,alreadyRuled:o.alreadyRuled});this.deps.broker.postToWebview(i)}catch(n){J(this.deps,"frozen:rules:clear","frozen:rules:clear:error",e,n,{code:this.errorCodeFor(n,"RULES_CLEAR_ERROR"),extraPayload:this.errorDetailOf(n)})}}async handleRulesCreate(e){let t=this.resolveRulesPath(this.loadConfig()),r=!1;try{await le.mkdir(fe.dirname(t),{recursive:!0});try{await le.writeFile(t,Ka(Ha),{encoding:"utf8",flag:"wx"}),r=!0,this.deps.log(`[INFO] frozen: empty rules file written at ${t}`)}catch(o){if(o.code!=="EEXIST")throw o;if(!(await le.stat(t)).isFile())throw new Error(`${t} is not a file: no rules file can be written there.`)}}catch(o){J(this.deps,"frozen:rules:create","frozen:rules:create:error",e,o,{code:"RULES_CREATE_ERROR"});return}let n=!1;try{await this.openInEditor(t),n=!0}catch(o){this.deps.log(`[WARN] frozen: rules file not opened: ${H(o)}`)}this.deps.broker.postToWebview(ce(this.deps,e,"frozen:rules:create:response",{rulesPath:t,created:r,opened:n}))}async handleManifestGet(e){let t=this.loadConfig(),r=this.resolveDatasetDir(t),n=null;try{let d=new ee().assertOutsideRepo(fe.join(r,"manifest.json"));await Ge(d)&&(n=Po(qt(JSON.parse(await le.readFile(d,"utf8")))))}catch(i){pt.warn(`frozen:manifest:get \u2014 unreadable manifest: ${String(i)}`)}let o=ce(this.deps,e,"frozen:manifest:get:response",{manifest:n,datasetDir:r});this.deps.broker.postToWebview(o)}targetTier(e){let t=this.deps.orgManager.getOrg(e);return Vo(t)}async handleLoad(e){let t=$e(qn,e,"frozen:load:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:load:error");if(!r)return;let n=this.deps.infraServices?.productionGuard;if(!n){Me(this.deps,{action:"frozen_load",module:"frozen",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:gt.code}),J(this.deps,"frozen:load","frozen:load:error",e,new Error(gt.message),{code:gt.code});return}let o=await this.replaceRefusal(t,r),i=o&&"error"in o?o:void 0,d=o&&"cameAlong"in o?o.cameAlong:void 0;if(i){i.code===kn&&Me(this.deps,{action:"frozen_load",module:"frozen",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:kn}),J(this.deps,"frozen:load","frozen:load:error",e,i.error,{code:i.code,retryable:i.retryable});return}let a=e.id,c=t.pilot?"Pilot load (one root folder)":"Loading frozen dataset";ar(this.deps,a,"frozen",c),this.liveTracker?.register(a,"frozen",c);let f=!1,l=!1,u=new AbortController,p=()=>{},g=new Promise((k,V)=>{p=Z=>Z===void 0?k():V(Z)});g.catch(()=>{}),this.registry?.register(a,"frozen",c,g,u);let h=Id(k=>{let V=ce(this.deps,e,"frozen:load:progress",{...k});this.deps.broker.postToWebview(V),!f&&!l&&this.liveTracker?.updateProgress(a,k.progress,0,0,k.message)},100),m,y=!1,v=!1,P,A=new Date().toISOString(),S,T,E,O,w,R=(k,V,Z,F)=>{if(v)return;v=!0;let _=k!=="stopped"&&S!==void 0,U=E?ii(si(E.run.gate,E.info.accepted&&E.info.verdict==="asks").emails):{},re={..._?{sas:S,startedAt:A,...T?{lastWriteAt:T}:{}}:{},...U};Me(this.deps,{action:"frozen_load",module:"frozen",operationId:a,orgId:t.targetOrgId,outcome:k,guard:m,objects:V,source:{origin:"dataset",label:P},carried:Z,...F?{code:F}:{},...I?{muted:Wr(I)}:{},...z?.state==="taken"?{checkpointId:z.checkpointId}:{},...Object.keys(re).length>0?{details:re}:{}})},I,j,z,x=!1,q=!1,Y=!1,L=[];try{let k=new ee,V=k.assertOutsideRepo(this.resolveSasDir(r));S=co(V);let Z=k.assertOutsideRepo(this.resolveDatasetDir(r)),{dataset:F,manifest:_}=await this.readFrozenDataset(Z,k);P=_.version;let U=this.buildTargetOrgAccess(),re=await ue(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),D=Dn(this.deps),$=Rs(this.deps),B=G=>new Qi({connection:re,bulkExecutor:new Ms(D.bulk.threshold),bulkManager:$,retryConfig:D.retry,...G?{signal:G}:{},onProgress:()=>{},log:ot=>this.deps.log(ot)}),Oe=B(u.signal),ke=r.mockDetection?new gr(U,r.mockDetection):{areCalloutsMocked:async()=>!0},ge=this.mappingStoreFor(V,t.targetOrgId,k),Ie=Pt(re,"frozen:load"),he=new Rr({orgAccess:U,writer:Oo(Oe),restoringWriter:Oo(B(void 0)),guard:n,mockDetector:ke,recordTypeResolver:new Pr(U),mappingStore:ge,config:this.toLoadConfig(r),sasGuard:k,serverTime:()=>Ie.serverTime()});if(t.sweep===!0&&t.reload===!0&&!t.pilot){L=await this.reloadSweepsOf({conn:re,store:ge,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,includeChanged:t.includeChanged===!0,signal:u.signal,guard:n,operationId:a});for(let{sweep:G}of L)await G.ask()}let M=Fr([],L.flatMap(({sweep:G})=>G.takes)),N=(M.delete??[]).length>0?this.removalAsker:void 0,ie=F.objects.map(G=>G.objectApiName),Se=t.reload===!0&&!t.pilot?await this.purgeStepsOf(ge,r):void 0,Fe=await this.targetAutomation.read(t.targetOrgId,[...new Set([...ie,...Se?.delete??[],...M.delete??[]])]).catch(G=>({unread:H(G)})),et=Se?sr(Se):void 0,tt=sr(M),Qt=(G,ot)=>In(G,ot)||et?.(G,ot)===!0||tt(G,ot),Te=t.muteAutomation===!0?await cr(async()=>dr(re),Fe,{...this.muteLeases,writes:Qt}):void 0;if(I=Te?.muted,N&&!u.signal.aborted){let G=await N({read:Fe,steps:M,mute:Te});if(G)throw new Yt(G)}let rt=this.targetTier(t.targetOrgId),er=await he.gateLoad({orgId:t.targetOrgId,orgTier:rt,dataset:F,manifest:_,reload:t.reload,pilot:t.pilot?{}:void 0,onProgress:G=>h(G),onGuardDecision:G=>{m=Wn(m,G)}}),nt=lo({read:Fe,...Te?.plan?{plan:Te.plan}:{},written:ie,accepted:t.acceptAutomation===!0,target:this.orgNameOf(t.targetOrgId),mayMute:t.muteAutomation!==!0&&this.muteOffered});if(O=nt.info,nt.stop&&nt.info)throw new Er(nt.stop.code,nt.stop.message,nt.info,t.targetOrgId);let tr=t.acceptEmails===!0,Ue=await this.loadEmailsFor({conn:re,orgId:t.targetOrgId,orgTier:rt,read:Fe,...Te?.plan?{plan:Te.plan}:{},writes:Qt,dataset:F,accepted:tr,mayMute:t.muteAutomation!==!0&&this.muteOffered});if(E=Ue,Ue.stop)throw new Zt(Ue.stop.code,Ue.stop.message,Ue.info,t.targetOrgId);let wt=t.checkpointFirst!==void 0?await this.scopeLoadCheckpoint({msg:e,orgId:t.targetOrgId,written:ie,read:Fe,mute:Te,request:t.checkpointFirst}):void 0;if(w=await this.loadApiCheck({conn:re,dataset:F,...Se?{purged:await this.purgedOf(ge,r)}:{},read:Fe,...wt?{checkpoint:wt.estimate}:{},...Te?.plan?{plan:Te.plan}:{},emails:Ue,orgId:t.targetOrgId,operation:`frozen:load ${a}`}),w.refused)throw new Lr(w.refused.message,w,t.targetOrgId);wt&&(j=await this.takeLoadCheckpoint(wt,u.signal));let De=Te?.prepared?await Te.prepared.acquire(a):void 0;De&&(I=De.outcome,Y=!0);let dt=De?Ue.run.afterLease(De.outcome,tr):void 0;if(De&&dt)throw I=await De.release(),new Zt(dt.code,dt.message,Ue.info,t.targetOrgId);x=!0;let ct=()=>he.load({orgId:t.targetOrgId,orgTier:rt,dataset:F,manifest:_,sasDir:V,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},onProgress:G=>h(G),onGuardDecision:G=>{m=Wn(m,G),(G==="allowed"||G==="confirmed")&&(y=!0)},signal:u.signal,...De?{lease:{giveBack:()=>De.release()}}:{},...L.length>0?{purgeSweep:{first:async()=>{for(let{sweep:G}of L)await G.first()},afterPurge:async()=>{for(let{sweep:G}of L)await G.afterRemoval()},stillToSweep:()=>L.filter(({sweep:G})=>!ko(G.result())).map(({loadedAt:G})=>G)}}:{}}),We=await(er==="confirmed"?Xs({approved:!0},ct):ct()).finally(async()=>{De&&(I=await De.release())});q=!0,h.flush();let Ke=await this.settleReloadSweeps(L),bt=Ke.some(G=>G.result.status!=="success");j&&(z=await this.settleCheckpoint(j,Sn(We)>0)),T=xa(await ge.recorded().catch(()=>{}),A);let zr=fe.join(Z,"manifest.json");l=!0;let rr=await this.verifyLoad({orgId:t.targetOrgId,contractPath:We.contractPath,manifestPath:zr,dataset:F,mappingStore:ge,config:r,onProgress:h}),nr="verdict"in rr?rr.verdict.status:void 0,Rt=nr==="failed"||nr==="partial"?nr:void 0,lt=We.status==="completed"&&(bt||Rt!==void 0)?"partial":We.status,He=Dl(We);R(Rt!==void 0&&He==="success"?"partial":He,Eo(We),await $l(F,ge));let Cr={contractPath:We.contractPath,datasetDir:Z,manifestPath:zr,targetOrgId:t.targetOrgId,status:lt,at:new Date().toISOString()};this.recordLastRun(Cr);let ut=Nl(We),Je=Object.fromEntries(Object.entries(d??{}).filter(([G])=>(ut.purge.deleted[G]??0)>0)),Nr=ce(this.deps,e,"frozen:load:response",{report:{...ut,...Object.keys(Je).length>0?{purge:{...ut.purge,cameAlong:Je}}:{},status:lt,...Rt?{verification:Rt}:{},...I?{mutedAutomation:I}:{},...z?{checkpoint:z}:{},...Ke.length>0?{sweeps:Ke}:{},...E&&wd(E.info)?{emails:E.info}:{},...O?{automation:O}:{},...w?{apiRequests:w}:{}}});this.deps.broker.postToWebview(Nr),at(this.deps,a,{status:lt}),f=!0,lt!=="completed"?this.liveTracker?.partial(a):this.liveTracker?.complete(a),this.postVerification(e,rr),p()}catch(k){h.flush();let V=await this.settleReloadSweeps(L).catch(()=>[]),Z=V.length>0?{sweeps:V}:{};if(j&&z===void 0){let Ie=k instanceof _e||k instanceof Ft?k.written:void 0;z=await this.settleCheckpoint(j,Ie?Sn(Ie)>0:x&&!Xr(k))}let F=z?{checkpoint:z}:{},_=Y&&I?{mutedAutomation:I}:{};if(k instanceof Lt){R("stopped",void 0,void 0,k.code),J(this.deps,"frozen:load","frozen:load:error",e,k,{code:k.code,...k.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),k.code==="LOAD_CANCELLED"?(this.registry?.abort(a),at(this.deps,a,{aborted:!0}),this.liveTracker?.cancel(a),p()):(Mn(this.deps,a,k.message,!0),this.liveTracker?.fail(a,k.message),p(k));return}if(k instanceof _e){let Ie=Ml(k.written);R(Ie,Eo(k.written),void 0,Ie==="stopped"?"LOAD_CANCELLED":void 0),this.registry?.abort(a),at(this.deps,a,{aborted:!0}),this.liveTracker?.cancel(a),J(this.deps,"frozen:load","frozen:load:error",e,k,{code:"LOAD_CANCELLED",extraPayload:{written:Sn(k.written),...F,...Z,..._}}),p();return}let U=Xr(k)||k instanceof Yt||k instanceof Zt||k instanceof Er||k instanceof Lr?k:void 0,re=U!==void 0||(m==="refused"||m==="declined")&&!y,D=k instanceof Ft?k:void 0,$=D?D.cause:k,B=U?.code??this.errorCodeFor($,"LOAD_ERROR"),Oe=D===void 0&&!q&&!y;R(re||Oe?"stopped":"failure",D?Eo(D.written):void 0,void 0,U?.code??(Oe?B:void 0));let ge={...D&&$ instanceof Ne?{guard:$.code}:this.errorDetailOf($),...F,...Z,..._,...Oe?{written:0}:{}};J(this.deps,"frozen:load","frozen:load:error",e,k,{code:B,retryable:$ instanceof Ze,extraPayload:Object.keys(ge).length>0?ge:void 0}),f||(Mn(this.deps,a,H(k),!0),this.liveTracker?.fail(a,H(k))),p(k)}}loadCheckpointAsk(e){let{read:t}=e;return{module:"frozen",orgId:e.orgId,operationId:e.operationId,written:[...e.written],running:"objects"in t?Nt(t,e.mute?.plan,In):{firing:[]},request:e.request}}async previewCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)return;let r=await this.targetAutomation.read(e.orgId,e.written).catch(i=>({unread:H(i)})),n=e.muteAutomation?await cr(async()=>dr(e.conn),r,{...this.muteLeases,writes:In}).catch(i=>{pt.warn(`Frozen preview: the mute could not be planned (${H(i)})`)}):void 0,o=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(o,{}).catch(i=>{pt.warn(`Frozen preview: ${en(i)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Lt(ur,en(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:Ad(e.msg.id)},o;try{o=await t.scope(r,n)}catch(d){throw new Lt(ur,en(d))}let i=bi(o);if(i)throw new Lt(i.code,i.message);return{checkpoints:t,ask:r,own:n,estimate:o}}async takeLoadCheckpoint(e,t){let{checkpoints:r,ask:n,own:o,estimate:i}=e,d=await Ri(()=>r.take(n,o,{planned:i,signal:t}));if("stop"in d)throw new Lt(d.stop.code===ur?ur:"LOAD_CANCELLED",d.stop.message);return d.checkpoint}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return pt.warn(`Frozen load: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${H(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(Jt);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(Rd,t,Tr),this.deps.configStore.set(Jt,e,Tr)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(So,{...this.lastVerifies(),[e]:t},Tr)}lastVerifies(){return this.deps.configStore.get(So)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(Jt);return!t||Date.parse(t.at)>Date.parse(e.measuredAt)?void 0:Object.keys(this.lastRuns()).filter(n=>n!==t.targetOrgId).length===0?t.targetOrgId:void 0}moveOldVerify(){let e=this.deps.configStore.get(Io);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(So,{...r,[t]:e},Tr),this.deps.configStore.delete(Io)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(Io),r=t?this.orgOfOldVerify(t):void 0;return t&&r!==void 0&&e[r]===void 0&&(e[r]=t),Object.entries(e).map(([n,o])=>({orgId:n,status:o.status,measuredAt:o.measuredAt}))}lastRuns(){return this.deps.configStore.get(Rd)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(Jt);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(Jt);return t&&e[t.targetOrgId]===void 0&&(e[t.targetOrgId]=t),Object.values(e).map(r=>({status:r.status,orgId:r.targetOrgId,at:r.at}))}async handlePreview(e){let t=$e(qn,e,"frozen:load:preview:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:load:preview:error");if(!r)return;let n=await this.replaceRefusal(t,r,t.goneFirst),o=n&&"error"in n?n:void 0;if(o){J(this.deps,"frozen:load:preview","frozen:load:preview:error",e,o.error,{code:o.code,retryable:o.retryable});return}try{let i=new ee,d=i.assertOutsideRepo(this.resolveSasDir(r)),a=i.assertOutsideRepo(this.resolveDatasetDir(r)),{dataset:c,manifest:f}=await this.readFrozenDataset(a,i),l=this.buildTargetOrgAccess(),u=await ue(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),p=Pt(u,"frozen:load:preview"),h=await new Rr({orgAccess:l,writer:Rl,guard:this.deps.infraServices?.productionGuard??new Qs,mockDetector:r.mockDetection?new gr(l,r.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Pr(l),mappingStore:this.mappingStoreFor(d,t.targetOrgId,i),config:this.toLoadConfig(r),sasGuard:i,serverTime:()=>p.serverTime(),readValidationRules:async A=>{let{toolingQueriesOver:S,toolingValidationRules:T}=await import("./chunk-X2PY6MWZ.mjs"),{toolingRetrievesOver:E}=await import("./chunk-4XZ5YT5O.mjs"),O=u.tooling;return T(async w=>(await Is({query:async R=>O.query(R),queryMore:async R=>O.queryMore(R)},w)).records,S(u),E(u))(A)}}).planLoad({orgId:t.targetOrgId,orgTier:this.targetTier(t.targetOrgId),dataset:c,manifest:f,sasDir:d,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{}}),m=t.checkpointFirst!==void 0?await this.previewCheckpoint({msg:e,orgId:t.targetOrgId,written:c.objects.map(A=>A.objectApiName),request:t.checkpointFirst,muteAutomation:t.muteAutomation===!0,conn:u}):void 0,{emails:y,automation:v,apiRequests:P}=await this.previewWhatRuns({conn:u,orgId:t.targetOrgId,dataset:c,store:this.mappingStoreFor(d,t.targetOrgId,i),config:r,parsed:t,...m?{checkpoint:m}:{}});this.deps.broker.postToWebview(ce(this.deps,e,"frozen:load:preview:response",{plan:{...h,...m?{checkpoint:m}:{},...y?{emails:y}:{},...v?{automation:v}:{},...P?{apiRequests:P}:{}}}))}catch(i){J(this.deps,"frozen:load:preview","frozen:load:preview:error",e,i,{code:this.errorCodeFor(i,"PREVIEW_ERROR"),retryable:i instanceof Ze,extraPayload:this.errorDetailOf(i)})}}async previewWhatRuns(e){let{parsed:t}=e;try{let r=t.reload===!0&&!t.pilot?await this.purgeStepsOf(e.store,e.config):void 0,n=r?sr(r):void 0,o=(l,u)=>In(l,u)||n?.(l,u)===!0,i=await this.targetAutomation.read(e.orgId,[...new Set([...e.dataset.objects.map(l=>l.objectApiName),...r?.delete??[]])]).catch(l=>({unread:H(l)})),d=t.muteAutomation===!0?await cr(async()=>dr(e.conn),i,{...this.muteLeases,writes:o}).catch(()=>{}):void 0,{info:a}=lo({read:i,...d?.plan?{plan:d.plan}:{},written:e.dataset.objects.map(l=>l.objectApiName),accepted:t.acceptAutomation===!0,target:this.orgNameOf(e.orgId),mayMute:t.muteAutomation!==!0&&this.muteOffered}),c=await this.loadEmailsFor({conn:e.conn,orgId:e.orgId,orgTier:this.targetTier(e.orgId),read:i,...d?.plan?{plan:d.plan}:{},writes:o,dataset:e.dataset,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(l=>{pt.warn(`Frozen preview: the emails could not be judged (${H(l)})`)}),f=await this.loadApiCheck({conn:e.conn,dataset:e.dataset,...r?{purged:await this.purgedOf(e.store,e.config)}:{},read:i,...e.checkpoint?{checkpoint:e.checkpoint}:{},...d?.plan?{plan:d.plan}:{},...c?{emails:c}:{},orgId:e.orgId,operation:"frozen:load:preview"}).catch(l=>{pt.warn(`Frozen preview: the API requests could not be judged (${H(l)})`)});return{...c&&wd(c.info)?{emails:c.info}:{},...a?{automation:a}:{},...f?{apiRequests:f}:{}}}catch(r){return pt.warn(`Frozen preview: what the target runs could not be judged (${H(r)})`),{}}}async handleVerify(e){let t=$e(Ls,e,"frozen:verify:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:verify:error");if(!r)return;let n=this.lastRunOf(t.targetOrgId);if(!n){J(this.deps,"frozen:verify","frozen:verify:error",e,new Error("No load into this org is recorded \u2014 run a load (frozen:load) into it before verifying."),{code:"NO_LOAD"});return}let o=Id(i=>{let d=ce(this.deps,e,"frozen:load:progress",{...i});this.deps.broker.postToWebview(d)},100);try{let i=new ee,d=i.assertOutsideRepo(this.resolveSasDir(r)),a=fe.dirname(n.contractPath)!==fe.dirname(yr(i,d,t.targetOrgId)),c=await Ge(n.contractPath);if(a||!c){let g=fe.dirname(n.contractPath),h;a?c?h=`The sas directory changed since the last load: its counting contract is in ${g}, and the mapping read is the one in ${d}. Set sasDir back to the sas the load wrote to, or load the dataset again, then verify.`:h=`The sas directory changed since the last load: the load wrote to ${g}, which no longer holds its counting contract, and the mapping read is the one in ${d}. Move the sas back to ${g} and set sasDir to it, or load the dataset again, then verify.`:h=`The sas changed since the last load: ${d} no longer holds the counting contract the last load wrote there. Load the dataset again, then verify.`,J(this.deps,"frozen:verify","frozen:verify:error",e,new Error(h),{code:"SAS_CHANGED",extraPayload:{sasDir:d,loadSas:g,sasMoved:a,contractThere:c}});return}let f=this.mappingStoreFor(d,t.targetOrgId,i);if(await f.isStale()){J(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The target org was refreshed after the last load: the records that load wrote are gone. Load the dataset again, then verify."),{code:"TARGET_REFRESHED"});return}let l=await f.recorded(),u=l?.removal;if(l&&u){let g=xe(l).reduce((h,m)=>h+m.ids.length,0);J(this.deps,"frozen:verify","frozen:verify:error",e,new Error(g>0?`The removal of ${u.removedAt} took part of the records the last load created and left ${g} in the org: a verification would read the ones it took as missing. Remove what is left, or reload the dataset, which purges or finds it again; then verify.`:`The records the last load created were removed on ${u.removedAt}. Load the dataset again, then verify.`),{code:"LOAD_REMOVED",extraPayload:{left:g}});return}if(!l){J(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The sas holds no mapping of the last load: nothing names the records to verify. Load the dataset again, then verify."),{code:"NO_LOAD"});return}if(!pa(cn(i,n.contractPath),l)){J(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The last load stopped part way \u2014 it was cancelled, or failed once it had written \u2014 and wrote no counting contract: the one in the sas counts an earlier load, and would judge this one by it. Reload the dataset, which purges or finds again what the stopped load wrote, or remove that load before loading the dataset again; then verify. Loaded again without a reload, the dataset would go in beside what the stopped load wrote."),{code:"LOAD_STOPPED"});return}let{dataset:p}=await this.readFrozenDataset(n.datasetDir,i);await this.runVerification(e,{orgId:t.targetOrgId,contractPath:n.contractPath,manifestPath:n.manifestPath,dataset:p,mappingStore:f,config:r,onProgress:o})}catch(i){J(this.deps,"frozen:verify","frozen:verify:error",e,i,{code:this.errorCodeFor(i,"VERIFY_ERROR"),retryable:i instanceof Ze})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new vn({orgAccess:this.buildTargetOrgAccess(),sasGuard:new ee}),r=await e.mappingStore.load(),n=await t.verify({orgId:e.orgId,contractPath:e.contractPath,dataset:e.dataset,mapping:r,mandatoryLookups:e.config.mandatoryLookups,presenceKeys:e.config.presenceKeys,manifestPath:e.manifestPath,author:"sandforge",onProgress:e.onProgress});return this.recordLastVerify(e.orgId,{status:n.status,measuredAt:n.measuredAt}),{verdict:n}}catch(t){return{error:t}}}postVerification(e,t){if("verdict"in t){let{verdict:n}=t,o=ce(this.deps,e,"frozen:verify:result",{verdict:n});this.deps.broker.postToWebview(o);return}let r=t.error;J(this.deps,"frozen:verify","frozen:verify:error",e,r,{code:this.errorCodeFor(r,"VERIFY_ERROR"),retryable:r instanceof Ze})}async handleRemove(e){let t=$e(zs,e,"frozen:remove:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:error");if(!r)return;let n=(p,g)=>this.refuseRemove(e,p,g),o,i,d;try{let p=new ee,g=p.assertOutsideRepo(this.resolveSasDir(r));o=this.mappingStoreFor(g,t.targetOrgId,p),i=await o.recordedLoads(),d=Gt(i)}catch(p){J(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let a=Fo(d,t),c=t.sweep===!0&&a?.code==="ALREADY_REMOVED";if(a&&!c||!d){a&&n(a.message,a.code);return}let f=xe(d),l=o.filePath;if(this.removing.has(l)){n("The records of this load are being removed already.","DUPLICATE");return}this.removing.add(l);let u=this.registry?.holdUntilStart(e.id);try{await this.removeLoad(e,{store:o,load:d,plan:f,includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,alongside:t.sweep===!0?Qn(i,d):[],muteAutomation:t.muteAutomation===!0,pending:u})}finally{this.removing.delete(l),u?.release()}}async handleRemoveAutomation(e){let t=$e(Ns,e,"frozen:remove:automation:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:automation:error");if(r)try{let n=new ee,o=n.assertOutsideRepo(this.resolveSasDir(r)),i=this.mappingStoreFor(o,t.targetOrgId,n),d,a;if(t.reload===!0)d=await this.purgeStepsOf(i,r,t.sweptObjects??[]),(t.sweptObjects??[]).length>0&&(a=await this.purgeStepsOf(i,r));else{let l=Gt(await i.recordedLoads()),u=Fo(l,t),p=t.sweptObjects!==void 0&&u?.code==="ALREADY_REMOVED";if(u&&!p||!l){u&&J(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,new Error(u.message),{code:u.code});return}d=Fr(xe(l),t.sweptObjects??[])}let c=this.targetAutomation,f=await new ht(Ao).withTimeout("frozen:remove:automation",()=>c.read(t.targetOrgId,d.delete??[]));this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:f,steps:d,...a?{purge:a}:{}}))}catch(n){J(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,n,{code:n instanceof Ze?"TIMEOUT":this.errorCodeFor(n,"AUTOMATION_ERROR"),retryable:!0})}}async purgeStepsOf(e,t,r=[]){if(await e.isStale())return Fr([],[]);let n=t.undeletableObjects??{},o=(await e.recordedLoads()).flatMap(i=>xe(i)).filter(({objectApiName:i})=>!Object.hasOwn(n,i));return Fr(o,r)}async handleRemovePreview(e){let t=$e(Ds,e,"frozen:remove:preview:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:preview:error");if(!r)return;let n=(o,i,d=!1)=>J(this.deps,"frozen:remove:preview","frozen:remove:preview:error",e,o,{code:i,retryable:d});try{let o=new ee,i=o.assertOutsideRepo(this.resolveSasDir(r)),d=this.mappingStoreFor(i,t.targetOrgId,o),a=Gt(await d.recordedLoads()),c=Fo(a,t);if(c||!a){c&&n(new Error(c.message),c.code);return}let f=xe(a).reduce((p,g)=>p+g.ids.length,0),l=this.removalGuardRefusals(a.orgId,f),u;if(await d.isStale())l.push({code:"TARGET_REFRESHED",message:"The target org was refreshed after the load: the records it created went with the refresh, and a removal removes nothing."}),u={...this.unreadPreviewOf(a,t.includeChanged===!0),planned:f};else{let p=await ue(a.orgId,this.deps.orgRegistry,this.deps.orgManager);u=await this.previewRemovalOf(p,a,t.includeChanged===!0)}this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:preview:response",{preview:{...u,refusals:l.map(({message:p})=>p),refusalCodes:l.map(({code:p})=>p)}}))}catch(o){n(o,this.errorCodeFor(o,"REMOVE_PREVIEW_ERROR"),!0)}}removalGuardRefusals(e,t){let r=this.deps.infraServices?.productionGuard;if(!r)return[{...gt}];let n=this.targetTier(e),o=r.check({orgId:e,orgTier:n,operation:"delete",objectName:"the records a Frozen load created",recordCount:t,module:"frozen"});if(!o.allowed)return[{code:"GUARD_BLOCKED",message:`Operation blocked by Production Guard: ${o.blockedReason??o.impactSummary}`}];let i=r.declinedWithoutAsking(o,n);return i===void 0?[]:[{code:"GUARD_DECLINED",message:`Production Guard asks before this delete, and its question is answered no: ${i} (${o.impactSummary}). Nothing would be deleted.`}]}async previewRemovalOf(e,t,r){let n=xe(t),o=await Jr(Pt(e,"frozen:remove:preview"),n,{...To(t),includeChanged:r,previewOnly:!0});if(!o.preview)throw new Error("The removal preview stopped before it was through.");return{...this.unreadPreviewOf(t,r),planned:n.reduce((i,d)=>i+d.ids.length,0),objects:o.preview.objects.map(i=>({objectApiName:i.objectApiName,planned:i.planned,toDelete:i.toDelete,alreadyGone:i.alreadyGone,changedSince:i.changedSince,keptChanged:i.keptChanged,changedBy:i.changedBy,undeletable:i.undeletable,notVisible:i.notVisible,unread:i.unread,reasons:i.reasons})),userNames:o.preview.userNames}}unreadPreviewOf(e,t){let r=sn(e);return{loadedAt:e.endedAt,includeChanged:t,planned:0,objects:[],userNames:{},...e.removal?{leftBy:e.removal.removedAt}:{},...r.length>0?{keptByThePlatform:r}:{}}}async replaceRefusal(e,t,r=[]){if(e.reload!==!0||e.pilot===!0)return;let n,o={};try{let i=new ee,d=i.assertOutsideRepo(this.resolveSasDir(t)),a=this.mappingStoreFor(d,e.targetOrgId,i),c=await a.recordedLoads();if(c.length===0||await a.isStale())return;if(c.some(f=>!f.created))n="A load recorded before loads kept what they created is in this sas: which of its records it created cannot be told, and a reload leaves in place those it may have linked, so it would not replace that load whole. Nothing was written.";else{let f=await ue(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),l=c.filter(h=>xe(h).length>0),u=new Set([...l.flatMap(h=>xe(h).flatMap(m=>m.ids.map(y=>y.slice(0,15)))),...r.map(h=>h.slice(0,15))]),p=[];for(let h of l){let m=await Jr(Pt(f,"frozen:load:replace"),xe(h),{...To(h),includeChanged:!1,previewOnly:!0,previewHeld:!0,goesWithParent:y=>typeof y.Id=="string"&&u.has(y.Id.slice(0,15))});if(!m.preview)throw new Error("The removal preview stopped before it was through.");p.push(m.preview);for(let{objectApiName:y,cameAlong:v}of m.preview.objects){if(!v)continue;let P=o[y];o[y]={count:(P?.count??0)+v.count,objects:[...new Set([...P?.objects??[],...v.objects])]}}}let g=Cl(p,e.sweep===!0);g.length>0&&(n=`A removal of the loads this reload replaces would leave ${g.reduce((m,y)=>m+y.left,0)} of their records in the org \u2014 ${g.map(m=>`${m.objectApiName} (${m.left}: ${m.why.join(", ")})`).join("; ")}: loaded again, the dataset would stand beside them, and the reload would delete what was changed since, and what stays under them along with them. Nothing was written. Take the load back first with a removal \u2014 records changed since, and what was added under them since, go too when it is told to include them \u2014 then load the dataset again.`)}}catch(i){return{error:i,code:this.errorCodeFor(i,"LOAD_ERROR"),retryable:!0}}return n!==void 0?{error:new Error(n),code:kn,retryable:!1}:Object.keys(o).length>0?{cameAlong:o}:void 0}refuseRemove(e,t,r){J(this.deps,"frozen:remove","frozen:remove:error",e,new Error(t),{code:r})}async removeLoad(e,t){let{store:r,load:n,plan:o,includeChanged:i,sweep:d,pending:a}=t,c=n.orgId,f=o.reduce((R,I)=>R+I.ids.length,0),l=(R,I)=>this.refuseRemove(e,R,I),u=this.deps.infraServices?.productionGuard;if(!u){Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",code:gt.code}),l(gt.message,gt.code);return}let{check:p,decision:g}=f>0?await Yr(u,{orgId:c,orgTier:this.targetTier(c),operation:"delete",objectName:o.map(R=>R.objectApiName).join(", "),recordCount:f,module:"frozen"}):{check:void 0,decision:"allowed"};if(p&&(g==="refused"||g==="declined")){Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",guard:g}),g==="refused"?l(`Operation blocked by Production Guard: ${p.blockedReason??p.impactSummary}`,"GUARD_BLOCKED"):J(this.deps,"frozen:remove","frozen:remove:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}let h=()=>{if(!a?.signal.aborted)return!1;Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",guard:g,code:ys});let R={status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};return this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:response",{result:R,operationId:e.id})),!0};if(h())return;let m;try{m=await r.isStale()}catch(R){Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"failure",guard:g}),J(this.deps,"frozen:remove","frozen:remove:error",e,R,{code:this.errorCodeFor(R,"REMOVE_ERROR"),retryable:!0});return}if(m){Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",guard:g,code:"TARGET_REFRESHED"}),l("The target org was refreshed after the load: the records it created went with the refresh, and nothing is removed.","TARGET_REFRESHED");return}if(h())return;let y=e.id,v=f>0?`Removing ${f} record(s) a Frozen load created`:"Sweeping what the target's automation made for a Frozen load",P=new AbortController,A=()=>{},S=new Promise((R,I)=>{A=j=>j===void 0?R():I(j)});S.catch(()=>{}),ar(this.deps,y,"frozen",v),this.registry?.register(y,"frozen",v,S,P),this.liveTracker?.register(y,"frozen",v,f);let T,E,O=[],w;try{let R=await ue(c,this.deps.orgRegistry,this.deps.orgManager),I=new Set([n,...t.alongside].map(M=>M.endedAt));E=d?await this.sweepOfRemoval({conn:R,load:n,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,signal:P.signal,guard:u,operationId:y,muted:()=>f===0?w:void 0,sweptWith:I}):void 0;for(let[M,N]of(E?t.alongside:[]).entries())O.push({loadedAt:N.endedAt,sweep:await this.sweepOfRemoval({conn:R,load:N,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,signal:P.signal,guard:u,operationId:`${y}-${M+2}`,muted:()=>{},sweptWith:I})});let j=E,z=[...E?[E]:[],...O.map(({sweep:M})=>M)],x=async M=>{let N=!1;for(let ie of z)await M(ie)&&(N=!0);return N};for(let M of z)await M.ask();let q,Y=this.removalAsker,L=Fr(o,z.flatMap(M=>M.takes));if((t.muteAutomation||Y)&&!P.signal.aborted&&(L.delete??[]).length>0){let M=this.targetAutomation,N=await new ht(Ao).withTimeout("frozen:remove automation",()=>M.read(c,L.delete??[])).catch(Se=>({unread:H(Se)}));t.muteAutomation&&(q=await cr(async()=>dr(R),N,{...this.muteLeases,writes:sr(L)}));let ie=await Y?.({read:N,steps:L,mute:q});if(ie)throw new Yt(ie)}w=q?.muted;let k,V=async()=>{let M=q?.prepared;!M||P.signal.aborted||(k=await M.acquire(y),w=k.outcome)},F=await(f===0?(async()=>(await V(),await x(M=>M.first()),await x(M=>M.afterRemoval()),qs))():Jr(Pt(R,"frozen:remove"),o,{...To(n),...j?{sweep:M=>x(N=>N.first(M)),afterRemoval:M=>x(N=>N.afterRemoval(M)),automationMade:j.automationMade}:{},onUndeletable:bs(this.deps,c,"frozen:remove"),beforeFirstWrite:V,includeChanged:i,signal:P.signal,onProgress:(M,N,ie)=>{let Se=Math.min(100,Math.round(M/Math.max(N,1)*100));Os(this.deps,y,Se,M,N,ie),P.signal.aborted||this.registry?.updateProgress(y,Se),this.liveTracker?.updateProgress(y,Se,M,N,ie)}})).finally(async()=>{k&&(w=await k.release())}),_=await E?.settle(),U=await this.settleReloadSweeps(O),re=n.removal?.removedAt,D=sn(n),$=Ws(F.objects,F.cancelled),B={status:U.reduce((M,N)=>Gn(M,N.result),Gn($,_)),includeChanged:i,objects:F.objects,finishedAt:new Date().toISOString(),...re?{leftBy:re}:{},..._?{sweep:_}:{},...U.length>0?{otherLoadSweeps:U}:{},...D.length>0?{keptByThePlatform:D}:{},...w?{mutedAutomation:w}:{}};f>0&&Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:y,orgId:c,outcome:Bs({status:$}),guard:g,objects:Vs(B.objects),...re?{leftBy:re}:{},...w?{muted:Wr(w)}:{}});let Oe=Us(B,f,n.removal);(F.gone.length>0||Object.keys(F.stamps).length>0||F.span||Oe)&&(await r.recordRemoval(n.endedAt,{gone:F.gone,stamps:F.stamps,...F.span?{span:F.span}:{},...Oe?{mark:Oe}:{}})||this.deps.log("[WARN] frozen:remove: a load wrote its own mapping during the removal; the removal is not recorded in it"));let ke=[..._&&ko(_)?[n.endedAt]:[],...U.filter(M=>ko(M.result)).map(M=>M.loadedAt)];await r.letSweptGo(ke).catch(()=>!1);let ge=ce(this.deps,e,"frozen:remove:response",{result:B,operationId:y});this.deps.broker.postToWebview(ge);let Ie=[_,...U.map(M=>M.result)].find(M=>M!==void 0&&M.status!=="success"),he=B.status==="failure"?"No record this load created could be removed.":f===0&&Ie?Ie.refusal??"The sweep left records in the org.":void 0;B.status==="cancelled"||_?.status==="cancelled"||U.some(M=>M.result.status==="cancelled")?(at(this.deps,y,{aborted:!0}),this.liveTracker?.cancel(y)):(at(this.deps,y,{status:he&&f===0?"failure":B.status}),he?(T=new Error(he),this.liveTracker?.fail(y,he)):B.status==="partial"?this.liveTracker?.partial(y):this.liveTracker?.complete(y))}catch(R){T=R,await E?.settle().catch(()=>{});for(let{sweep:j}of O)await j.settle().catch(()=>{});let I=Xr(R)||R instanceof Yt?R:void 0;Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:y,orgId:c,outcome:I?"stopped":"failure",guard:g,...I?{code:I.code}:{}}),J(this.deps,"frozen:remove","frozen:remove:error",e,R,{code:I?.code??"REMOVE_ERROR",retryable:!0}),at(this.deps,y,{status:"failure"}),this.liveTracker?.fail(y,H(R))}finally{A(T)}}async reloadSweepsOf(e){if(await e.store.isStale())return[];let t=(await e.store.recordedLoads()).filter(d=>d.created),r=new Set(t.map(d=>d.endedAt)),n={includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},o=d=>kl(d,n),i=[];for(let[d,a]of t.entries())i.push({loadedAt:a.endedAt,judged:o,sweep:await this.sweepOfRemoval({conn:e.conn,load:a,store:e.store,includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied,signal:e.signal,guard:e.guard,operationId:d===0?e.operationId:`${e.operationId}-${d+1}`,muted:()=>{},sweptWith:r,judged:o})});return i}async settleReloadSweeps(e){let t=[];for(let{loadedAt:r,sweep:n,judged:o}of e){let i=await n.settle();t.push({loadedAt:r,result:o?o(i):i})}return t}sweepOfRemoval(e){let{conn:t,load:r}=e;return Hi({input:()=>this.sweepInputOfLoad(Pt(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith),org:nn(t,"frozen:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.orgId,orgTier:this.targetTier(r.orgId),operation:"delete",module:"frozen"},onGuardDecision:(n,o)=>{let i=e.judged?e.judged(n):n,d=Vi(i,"");delete d.forgeId;let a=e.muted();Me(this.deps,{action:"cleanup_delete",module:"frozen",operationId:`${e.operationId}-sweep`,orgId:r.orgId,outcome:i.status==="refused"?"stopped":i.status,...o?{guard:o}:{},...i.status==="refused"?{code:Ji(o)}:{},objects:Bi(i),details:{...d,loadedAt:r.endedAt},...a?{muted:Wr(a)}:{}})},keepMade:async(n,o,i)=>{await e.store.recordMade(r.endedAt,n,o,i)}})}async sweepInputOfLoad(e,t,r,n,o=new Set){let i=Xn(t),d=this.targetAutomation,a;try{a=await new ht(Ao).withTimeout("frozen:remove sweep automation",()=>d.read(t.orgId,i.map(p=>p.objectApiName)))}catch(p){a={error:H(p)}}let c=t.writtenBetween??await Ui(e,i,r),{ties:f,sweptAlong:l}=await this.tiesOfLoad(t,c,n,o),u=new Set([...t.mapping.values(),...l].map(p=>p.slice(0,15)));return Ki({writtenBetween:c,created:i,remap:u,automation:Wi(a),...t.runUserId?{runUserId:t.runUserId}:{},ties:f,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return Ga(new ms(this.deps.configStore).list({orgId:e,limit:Go}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?co(this.resolveSasDir(e)):void 0}async tiesOfLoad(e,t,r,n){let o=[],i=[],d=await r?.recordedLoads().catch(()=>[])??[];for(let c of d){if(c.endedAt===e.endedAt||c.orgId!==e.orgId)continue;let f=Xn(c).flatMap(p=>p.ids);if(n.has(c.endedAt)){i.push(...f);continue}let l=Date.parse(c.writtenBetween?.first??c.startedAt??c.endedAt),u=Date.parse(c.writtenBetween?.last??c.endedAt);o.push({ids:f,from:l,to:Number.isFinite(u)?u:l})}o.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),o.push(..._a(this.auditedLoadsInto(e.orgId),{sasMark:this.sasMarkInUse(),own:d.filter(c=>c.orgId===e.orgId)}));let a=Zi(e.removalSpans);return{ties:{otherRuns:Yi(t,o),...a?{removalBegan:a}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:i}}async handleRemoveSweep(e){let t=$e(Cs,e,"frozen:remove:sweep:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:sweep:error");if(!r)return;let n=(o,i)=>J(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error(o),{code:i});try{let o=new ee,i=o.assertOutsideRepo(this.resolveSasDir(r)),d=this.mappingStoreFor(i,t.targetOrgId,o);if(t.reload===!0){await this.listReloadSweeps(e,d,t);return}let a=await d.recordedLoads(),c=Gt(a);if(!c){n("No load into this org was recorded in this sas: there is nothing to sweep.","NO_LOAD");return}if(c.orgId!==t.targetOrgId||c.endedAt!==t.loadedAt){n("Another load was recorded since this one was shown: check what a removal takes now.","LOAD_CHANGED");return}let f=Qn(a,c),l=new Set([c,...f].map(g=>g.endedAt)),{listing:u,otherLoads:p}=await new ht(kd).withTimeout("frozen:remove:sweep",async()=>{let g=await ue(c.orgId,this.deps.orgRegistry,this.deps.orgManager),h=nn(g,"frozen:remove:sweep"),m=async v=>Jn(h,await this.sweepInputOfLoad(h,v,void 0,d,l),v.removalSpans),y=[];for(let v of f)y.push({loadedAt:v.endedAt,listing:await m(v)});return{listing:await m(c),otherLoads:y}});this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:sweep:response",{loadedAt:c.endedAt,listing:u,...p.length>0?{otherLoads:p}:{}}))}catch(o){J(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,o,{code:o instanceof Ze?"TIMEOUT":this.errorCodeFor(o,"SWEEP_ERROR"),retryable:!0})}}async listReloadSweeps(e,t,r){let n=await t.isStale()?void 0:await t.recordedLoads(),o=(n??[]).filter(d=>d.created);if(n&&!n.some(d=>d.endedAt===r.loadedAt)){J(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error("Another load was recorded since this one was shown: check what a reload replaces now."),{code:"LOAD_CHANGED"});return}let i=await new ht(kd).withTimeout("frozen:remove:sweep",async()=>{if(o.length===0)return[];let d=await ue(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=nn(d,"frozen:remove:sweep"),c=new Set(o.map(l=>l.endedAt)),f=[];for(let l of o)f.push({loadedAt:l.endedAt,listing:await Jn(a,await this.sweepInputOfLoad(a,l,void 0,t,c),l.removalSpans)});return f});this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:sweep:response",{loadedAt:r.loadedAt,reload:!0,loads:i}))}sayTheSaltWasMade(e){vs(this.deps,"info","Frozen dataset salt",`This first extraction made the salt every pseudonym is drawn with (fingerprint ${e}) and keeps it in VS Code's secret storage: every later extraction pseudonymizes the same records the same way. A teammate who extracts this dataset needs the same salt: copy it with "SandForge: Copy Frozen Dataset Salt" and give it to them as you would a password; they set it with "SandForge: Use a Frozen Dataset Salt". Whoever holds it can tell which source value a pseudonym was drawn from.`,{autoDismissMs:null,code:"FROZEN_SALT_CREATED"})}async handleStatus(e){let t=this.loadConfig(),r=this.resolveSasDir(t),n=this.resolveDatasetDir(t),o={present:!1};try{let u=await this.saltKeeper.read();u&&(o={present:!0,fingerprint:new tn(u.salt).saltFingerprint,source:u.source})}catch{o={present:!1}}let i=null;try{let u=new ee;if(await Ge(fe.join(r,Ir))){let p=await ho(r,u);i={selectedAt:p.selectedAt,rootCount:p.roots.length,total:p.volumetry.total,budgetMax:p.volumetry.budgetMax}}}catch{i=null}let d=null;try{let p=new ee().assertOutsideRepo(fe.join(n,"manifest.json"));await Ge(p)&&(d=Po(qt(JSON.parse(await le.readFile(p,"utf8")))))}catch{d=null}let a=this.deps.configStore.get(Jt),c=[];try{let u=new ee,p=u.assertOutsideRepo(r);for(let g of await da(p,u))try{let h=Gt(await new Zn(p,{guard:u,orgId:g}).recordedLoads());h&&c.push(ca(h))}catch{}}catch{c.length=0}let f={configured:t!==null,sasDir:r,datasetDir:n,salt:o,mockDetectionConfigured:t?.mockDetection!==void 0,selection:i,manifest:d,lastLoad:a?{status:a.status,orgId:a.targetOrgId,at:a.at}:null,lastLoads:this.lastLoadInfos(),lastVerifies:this.lastVerifyInfos(),...c.length>0?{loadRecords:c}:{},rules:await this.rulesFileInfo(t)},l=ce(this.deps,e,"frozen:status:response",{status:f});this.deps.broker.postToWebview(l)}};export{Dd as a,Md as b,wu as c,$a as d,co as e,xa as f,_a as g,Ou as h,ku as i,Fu as j,zu as k,Pd as l};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{g as v}from"./chunk-PA3MKJVH.mjs";var x=!0;function D(t){let e=new Map;for(let n of t){let r=n.SobjectType;if(typeof r!="string"||r==="")continue;let o=r.toLowerCase(),c=e.get(o)??{viewAll:!1,modifyAll:!1};e.set(o,{viewAll:c.viewAll||n.PermissionsViewAllRecords===!0,modifyAll:c.modifyAll||n.PermissionsModifyAllRecords===!0})}return e}function E(t){return[...t.values()].some(e=>e.modifyAll)}var I=new Set(["task","event"]),M=new Set(["product2","pricebook2","pricebookentry"]),N=new Set(["user","group"]);function L(t){let e=[];for(let n of t.fields){if(n.type!=="reference")continue;let r=(n.referenceTo??[]).filter(o=>!N.has(o.toLowerCase()));r.length>0&&e.push({field:n.name,targets:r})}return e}function R(t,e){if(I.has(t))return"activities";if(M.has(t))return"catalog";if(t===v.toLowerCase())return"filesNotProven";if(e.has(t))return"settingNotProven"}function G(t,e){let n=j(e.describes),r=k(e.customSettings),o=new Map;for(let c of t){let f=c.toLowerCase();if(R(f,r)!==void 0||e.grants.has(f))continue;let u=n.get(f);if(u!==void 0)for(let{targets:p}of L(u)){if(p.length!==1)continue;let s=p[0],i=s.toLowerCase();!n.has(i)&&!o.has(i)&&o.set(i,s)}}return[...o.values()]}function j(t){return new Map([...t].map(e=>[e.name.toLowerCase(),e]))}function k(t){return new Set([...t??[]].map(e=>e.toLowerCase()))}function P(t,e,n){return(t.childRelationships??[]).some(r=>r.cascadeDelete===!0&&r.childSObject.toLowerCase()===e&&r.field.toLowerCase()===n.toLowerCase())}function $(t,e,n={}){let r=n.byParent??x,o=j(e.describes),c=k(e.customSettings),f=new Map,u=(s,i)=>{let d=s.toLowerCase(),C=f.get(d);if(C!==void 0)return C;let m=R(d,c);if(m!==void 0)return{reason:m};let h=e.grants.get(d);if(h!==void 0)return h.modifyAll?{access:"object"}:{reason:h.viewAll?"noModifyAll":"noViewAll"};if(!r)return{reason:"parentNotSeen",detail:"held through its parents is not proven"};let A=o.get(d);if(A===void 0)return{reason:"parentNotSeen",detail:"it could not be described"};let w=[];for(let{field:l,targets:a}of L(A)){let b=a.filter(y=>!o.has(y.toLowerCase())),g=a.filter(y=>{let S=o.get(y.toLowerCase());return S!==void 0&&P(S,d,l)});if(a.length>1){if(g.length>0||b.length>0)return{reason:"parentNotSeen",detail:`${l} may name a record of ${a.join(", ")}`};continue}if(b.length>0)return{reason:"parentNotSeen",detail:`${b[0]}, which ${l} names, could not be described`};g.length>0&&w.push({field:l,parent:g[0]})}if(w.length===0)return{reason:"parentNotSeen",detail:"it hangs from no record whose delete takes it along"};let O=new Set([...i,d]);for(let{field:l,parent:a}of w){let b=a.toLowerCase(),g=O.has(b)?void 0:u(a,O);if(g===void 0||!("access"in g))return{reason:"parentNotSeen",detail:`${a}, which ${l} names, is not held whole`}}return{access:"parent"}},p=new Map;for(let s of t){let i=u(s,new Set);f.set(s.toLowerCase(),i),p.set(s,i)}return p}export{D as a,E as b,G as c,$ as d};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{fb as c,fc as o}from"./chunk-B45CNPUX.mjs";var u=new Set(["picklist","multipicklist"]);function d(s){return(s.picklistValues??[]).filter(t=>t.active!==!1&&typeof t.value=="string"&&t.value!=="").map(t=>t.value)}function b(s){let t=new Map,n=i=>{let r=t.get(i);return r||(r=s(i),t.set(i,r)),r};return{async createable(i){let{fields:r}=await n(i);return new Set(r.filter(e=>e.createable===!0).map(e=>e.name))},async visible(i){let{fields:r}=await n(i);return new Set(r.map(e=>e.name))},async picklistValues(i){let{fields:r}=await n(i),e=new Map;for(let a of r){if(!u.has(a.type??""))continue;let l=d(a);l.length>0&&e.set(a.name,l)}return e},async keyPrefix(i){let{keyPrefix:r}=await n(i);return typeof r=="string"&&r.length===3?r:void 0},async lengths(i){let{fields:r}=await n(i);return new Map(r.flatMap(e=>typeof e.length=="number"&&e.length>0?[[e.name,e.length]]:[]))},async required(i){let{fields:r}=await n(i);return r.filter(e=>e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0&&(e.referenceTo??[]).length===0).map(e=>({fieldApiName:e.name,type:e.type??"string",picklistValues:d(e),referenceTo:[],length:e.length??0,integerDigits:c({...e,type:e.type??"string"}),objectApiName:i,required:!0}))}}}function p(s,t){return async n=>(await s.required(n)).filter(i=>!o(n,i.fieldApiName,t.includes(n)?"person":"business"))}export{b as a,p as b};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a}from"./chunk-4TLYUZD5.mjs";var u=80,s=95;function m(r){if(!r?.apiUsage)return;let{used:i,limit:n}=r.apiUsage,t=n>0?Math.round(i/n*100):0;return{apiUsage:i,apiLimit:n,usagePercent:t}}function o(r,i,n=u,t=s){let e=m(r);if(e)return e.usagePercent>=t?a.error(`[API Limits] CRITICAL: ${e.apiUsage}/${e.apiLimit} (${e.usagePercent}%) during ${i}`):e.usagePercent>=n&&a.warn(`[API Limits] WARNING: ${e.apiUsage}/${e.apiLimit} (${e.usagePercent}%) during ${i}`),e}export{o as a};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g,h}from"./chunk-AAVJ5XVX.mjs";import"./chunk-EQF2IJS2.mjs";import"./chunk-RSYICMZG.mjs";import"./chunk-IAZB4WIL.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{d as ARTICLE_OBJECT,b as CASE_STATUS_BY_LABEL_SOQL,a as CASE_STATUS_SOQL,g as prepareScenario,c as readScenarioCaseStatus,f as scenarioCasePicklists,e as scenarioKnowledge,h as toolingQueryAll};