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.
- package/LICENSE +21 -0
- package/README.md +54 -2
- package/THIRD-PARTY-NOTICES.md +1624 -0
- package/bin/sandforge-autopilot.mjs +12 -0
- package/bin/sandforge-backup.mjs +12 -0
- package/bin/sandforge-checkpoint.mjs +12 -0
- package/bin/sandforge-cleanup.mjs +12 -0
- package/bin/sandforge-clone.mjs +12 -0
- package/bin/sandforge-compare.mjs +12 -0
- package/bin/sandforge-dataops.mjs +12 -0
- package/bin/sandforge-empty.mjs +12 -0
- package/bin/sandforge-env.mjs +12 -0
- package/bin/sandforge-frozen.mjs +12 -0
- package/bin/sandforge-mcp.mjs +12 -0
- package/bin/sandforge-monitor.mjs +12 -0
- package/bin/sandforge-seed.mjs +12 -0
- package/bin/sandforge-sync.mjs +12 -0
- package/bin/sandforge.mjs +12 -0
- package/lib/catalogue.en.json +1 -0
- package/lib/chunk-2BVTCNWA.mjs +7 -0
- package/lib/chunk-2S5OMIIA.mjs +7 -0
- package/lib/chunk-2YIV2OB2.mjs +7 -0
- package/lib/chunk-342FN7AO.mjs +9 -0
- package/lib/chunk-36U7IQ6Y.mjs +25 -0
- package/lib/chunk-3CA767QB.mjs +7 -0
- package/lib/chunk-3DCUADVK.mjs +7 -0
- package/lib/chunk-3F5YMM2F.mjs +7 -0
- package/lib/chunk-3OHPD72J.mjs +9 -0
- package/lib/chunk-3RYLICRX.mjs +7 -0
- package/lib/chunk-3SRXFZSD.mjs +7 -0
- package/lib/chunk-42RER7V4.mjs +14 -0
- package/lib/chunk-4GL773D5.mjs +7 -0
- package/lib/chunk-4HFRHFGQ.mjs +7 -0
- package/lib/chunk-4HW535YJ.mjs +7 -0
- package/lib/chunk-4NAHW2D3.mjs +7 -0
- package/lib/chunk-4SNDMJP2.mjs +7 -0
- package/lib/chunk-4TLYUZD5.mjs +7 -0
- package/lib/chunk-4U6NXJNL.mjs +7 -0
- package/lib/chunk-4XZ5YT5O.mjs +7 -0
- package/lib/chunk-55HEMHEG.mjs +7 -0
- package/lib/chunk-57VHUYNG.mjs +10 -0
- package/lib/chunk-5AJRHRXA.mjs +20 -0
- package/lib/chunk-5CD257T7.mjs +7 -0
- package/lib/chunk-5HMAPZBV.mjs +7 -0
- package/lib/chunk-5LFSFYFJ.mjs +7 -0
- package/lib/chunk-5MMXFWPD.mjs +7 -0
- package/lib/chunk-5O6JOMHS.mjs +13 -0
- package/lib/chunk-5P4PHJRL.mjs +9 -0
- package/lib/chunk-5QKTYCWE.mjs +11 -0
- package/lib/chunk-66NMFCWX.mjs +7 -0
- package/lib/chunk-6EBMEGZB.mjs +7 -0
- package/lib/chunk-6LAXTAVN.mjs +7 -0
- package/lib/chunk-6MUEPV7M.mjs +9 -0
- package/lib/chunk-6QSM2WIH.mjs +10 -0
- package/lib/chunk-75ADZS6B.mjs +7 -0
- package/lib/chunk-7EANH5PY.mjs +68 -0
- package/lib/chunk-7F54PZUS.mjs +7 -0
- package/lib/chunk-7UQD6V6F.mjs +7 -0
- package/lib/chunk-AAVJ5XVX.mjs +7 -0
- package/lib/chunk-ALJVEUUS.mjs +7 -0
- package/lib/chunk-ALUFROGA.mjs +7 -0
- package/lib/chunk-AR7BE5O2.mjs +7 -0
- package/lib/chunk-AUTM6H6Z.mjs +7 -0
- package/lib/chunk-AV5SWEHP.mjs +9 -0
- package/lib/chunk-B45CNPUX.mjs +47 -0
- package/lib/chunk-BILZ3SSR.mjs +7 -0
- package/lib/chunk-BN7A4GRQ.mjs +7 -0
- package/lib/chunk-BOGNK4LV.mjs +7 -0
- package/lib/chunk-BS5T3MOQ.mjs +7 -0
- package/lib/chunk-BZ24IAP5.mjs +7 -0
- package/lib/chunk-CA5NAXSU.mjs +7 -0
- package/lib/chunk-CE6ZDGBB.mjs +7 -0
- package/lib/chunk-CGWXQX75.mjs +7 -0
- package/lib/chunk-CHCHAE4B.mjs +7 -0
- package/lib/chunk-D3QRXG63.mjs +787 -0
- package/lib/chunk-DBFJB2B6.mjs +7 -0
- package/lib/chunk-DLDX6RRC.mjs +7 -0
- package/lib/chunk-EADHKH3A.mjs +7 -0
- package/lib/chunk-EEVVGGM6.mjs +7 -0
- package/lib/chunk-ENLBYECD.mjs +7 -0
- package/lib/chunk-EQF2IJS2.mjs +11 -0
- package/lib/chunk-EQOQASDQ.mjs +7 -0
- package/lib/chunk-F2424IKX.mjs +7 -0
- package/lib/chunk-F74IHMGL.mjs +7 -0
- package/lib/chunk-FOVVHGEP.mjs +7 -0
- package/lib/chunk-FQBRBBY4.mjs +7 -0
- package/lib/chunk-FQGHL7GR.mjs +259 -0
- package/lib/chunk-GAM726CK.mjs +7 -0
- package/lib/chunk-GCOB7K5N.mjs +7 -0
- package/lib/chunk-GMY5427L.mjs +7 -0
- package/lib/chunk-GNC27UEU.mjs +7 -0
- package/lib/chunk-H2PJNIYJ.mjs +7 -0
- package/lib/chunk-H45UXY6G.mjs +7 -0
- package/lib/chunk-HCIDVIOW.mjs +7 -0
- package/lib/chunk-HF6LAK3G.mjs +7 -0
- package/lib/chunk-HJC7AIBK.mjs +7 -0
- package/lib/chunk-HJKM3E56.mjs +7 -0
- package/lib/chunk-HTJ5OGP5.mjs +7 -0
- package/lib/chunk-HUMEKZT5.mjs +8 -0
- package/lib/chunk-HV2MXMGI.mjs +7 -0
- package/lib/chunk-HXS7ORUF.mjs +11 -0
- package/lib/chunk-I3JKJTLO.mjs +110 -0
- package/lib/chunk-I7O6C2B5.mjs +8 -0
- package/lib/chunk-IAZB4WIL.mjs +7 -0
- package/lib/chunk-IC2C2GOF.mjs +8 -0
- package/lib/chunk-IEYG5ATY.mjs +7 -0
- package/lib/chunk-INIQ23K6.mjs +7 -0
- package/lib/chunk-INIT2UKJ.mjs +7 -0
- package/lib/chunk-J7HVXMSW.mjs +7 -0
- package/lib/chunk-JVL444U5.mjs +7 -0
- package/lib/chunk-K22PA4XL.mjs +7 -0
- package/lib/chunk-K2FBZIXY.mjs +7 -0
- package/lib/chunk-KLX67VPL.mjs +7 -0
- package/lib/chunk-L776PUMV.mjs +7 -0
- package/lib/chunk-LQ4DRFUH.mjs +9 -0
- package/lib/chunk-LRFAIUN7.mjs +7 -0
- package/lib/chunk-LV6G4XTK.mjs +7 -0
- package/lib/chunk-M6P5ZZLE.mjs +7 -0
- package/lib/chunk-MTMH6H2A.mjs +8 -0
- package/lib/chunk-MYTIL2JD.mjs +10 -0
- package/lib/chunk-NEVXIGR6.mjs +10 -0
- package/lib/chunk-NGSMZZDA.mjs +7 -0
- package/lib/chunk-NHWE66K5.mjs +7 -0
- package/lib/chunk-NM4MDLK4.mjs +7 -0
- package/lib/chunk-NTDN2JQZ.mjs +19 -0
- package/lib/chunk-NTOVCTRS.mjs +7 -0
- package/lib/chunk-NZ5ZZLKS.mjs +7 -0
- package/lib/chunk-OQOZAPCI.mjs +7 -0
- package/lib/chunk-OTWRDD6L.mjs +7 -0
- package/lib/chunk-P2PJYWGQ.mjs +7 -0
- package/lib/chunk-P42X3B4D.mjs +7 -0
- package/lib/chunk-P7GSGFJO.mjs +7 -0
- package/lib/chunk-PA3MKJVH.mjs +7 -0
- package/lib/chunk-PBI4BYWW.mjs +7 -0
- package/lib/chunk-PNCONNFJ.mjs +10 -0
- package/lib/chunk-PTTHSSQO.mjs +7 -0
- package/lib/chunk-PUOX4NBJ.mjs +8 -0
- package/lib/chunk-PZTSVQSF.mjs +7 -0
- package/lib/chunk-QPF6C5MX.mjs +7 -0
- package/lib/chunk-QQZZMKU3.mjs +7 -0
- package/lib/chunk-QROPNEGY.mjs +14 -0
- package/lib/chunk-QRV2OSIS.mjs +7 -0
- package/lib/chunk-QSRAEUGZ.mjs +7 -0
- package/lib/chunk-QWT2C74M.mjs +7 -0
- package/lib/chunk-RAAANPPG.mjs +7 -0
- package/lib/chunk-RACDTRZA.mjs +7 -0
- package/lib/chunk-RFEO2KAN.mjs +7 -0
- package/lib/chunk-RH3N2H7P.mjs +7 -0
- package/lib/chunk-RSWDYIHY.mjs +37 -0
- package/lib/chunk-RSYICMZG.mjs +8 -0
- package/lib/chunk-SAR5622P.mjs +7 -0
- package/lib/chunk-SBIMVCXT.mjs +101 -0
- package/lib/chunk-SCKUIE3R.mjs +7 -0
- package/lib/chunk-SFURUNJM.mjs +7 -0
- package/lib/chunk-SIOZXPFG.mjs +7 -0
- package/lib/chunk-SRPWW4A2.mjs +10 -0
- package/lib/chunk-SRQDABQ2.mjs +15 -0
- package/lib/chunk-SVS6UMDU.mjs +323 -0
- package/lib/chunk-T63U4OZJ.mjs +7 -0
- package/lib/chunk-TBZMC2VV.mjs +11 -0
- package/lib/chunk-TEOLMRDO.mjs +7 -0
- package/lib/chunk-TLH7AD35.mjs +7 -0
- package/lib/chunk-TNXUU6W7.mjs +14 -0
- package/lib/chunk-TQX3PURV.mjs +7 -0
- package/lib/chunk-TUACWKIH.mjs +7 -0
- package/lib/chunk-TW3N6W5Z.mjs +7 -0
- package/lib/chunk-TYYOBZMU.mjs +10 -0
- package/lib/chunk-TZE3Y7IQ.mjs +7 -0
- package/lib/chunk-UNDIBZWG.mjs +7 -0
- package/lib/chunk-VGW4MXXZ.mjs +7 -0
- package/lib/chunk-VHI54FBK.mjs +441 -0
- package/lib/chunk-VXHDBYMI.mjs +7 -0
- package/lib/chunk-W7KFAY55.mjs +7 -0
- package/lib/chunk-WFEB5X4U.mjs +8 -0
- package/lib/chunk-WIO4XO4F.mjs +7 -0
- package/lib/chunk-WJY54JO7.mjs +13 -0
- package/lib/chunk-WR2GIKWE.mjs +7 -0
- package/lib/chunk-WRU5FJFC.mjs +7 -0
- package/lib/chunk-X2PY6MWZ.mjs +7 -0
- package/lib/chunk-X65MT4W3.mjs +7 -0
- package/lib/chunk-XBG5SP6Q.mjs +7 -0
- package/lib/chunk-XCA5AONB.mjs +7 -0
- package/lib/chunk-XEFDB2R4.mjs +7 -0
- package/lib/chunk-XETCPL7E.mjs +7 -0
- package/lib/chunk-Y5CGXLUB.mjs +7 -0
- package/lib/chunk-Y6J6QFI2.mjs +7 -0
- package/lib/chunk-YAZO75G2.mjs +8 -0
- package/lib/chunk-YBU4Z4QV.mjs +7 -0
- package/lib/chunk-YMJVMFPY.mjs +7 -0
- package/lib/chunk-YPSRZRIT.mjs +7 -0
- package/lib/chunk-YS4G22C2.mjs +7 -0
- package/lib/chunk-YW2SBL4Z.mjs +7 -0
- package/lib/chunk-YYZL7UGV.mjs +7 -0
- package/lib/chunk-Z7X534S4.mjs +10 -0
- package/lib/chunk-ZE6HKRR4.mjs +9 -0
- package/lib/chunk-ZHJP7L3K.mjs +7 -0
- package/lib/chunk-ZJKCWBRJ.mjs +7 -0
- package/lib/chunk-ZLZRU6MO.mjs +7 -0
- package/lib/chunk-ZOVSMN5C.mjs +7 -0
- package/lib/chunk-ZPYJPGDK.mjs +7 -0
- package/lib/chunk-ZQOZ4EFW.mjs +7 -0
- package/lib/chunk-ZUTYVST5.mjs +7 -0
- package/lib/chunk-ZXH4MBWP.mjs +7 -0
- package/lib/chunk-ZYEE34WO.mjs +7 -0
- package/lib/sandforge-autopilot.mjs +157 -0
- package/lib/sandforge-backup.mjs +99 -0
- package/lib/sandforge-checkpoint.mjs +353 -0
- package/lib/sandforge-cleanup.mjs +56 -0
- package/lib/sandforge-clone.mjs +7 -0
- package/lib/sandforge-compare.mjs +54 -0
- package/lib/sandforge-dataops.mjs +7 -0
- package/lib/sandforge-empty.mjs +140 -0
- package/lib/sandforge-env.mjs +355 -0
- package/lib/sandforge-frozen.mjs +263 -0
- package/lib/sandforge-mcp.mjs +40 -0
- package/lib/sandforge-monitor.mjs +43 -0
- package/lib/sandforge-seed.mjs +7 -0
- package/lib/sandforge-sync.mjs +7 -0
- package/lib/sandforge.mjs +28 -0
- package/package.json +52 -4
|
@@ -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{c as De,d as Cn,f as ve}from"./chunk-H45UXY6G.mjs";import{l as B}from"./chunk-WRU5FJFC.mjs";import{b as On,d as En}from"./chunk-GNC27UEU.mjs";import{a as In,c as Pn}from"./chunk-YBU4Z4QV.mjs";import{Bc as It}from"./chunk-YMJVMFPY.mjs";import{a as z,c as xe}from"./chunk-BOGNK4LV.mjs";import{$a as pn,Q as an,R as dn,W as cn,X as un,Z as ln,ab as fn,g as on,hb as gn,ib as mn,jb as hn,kb as yn,lb as wn,nb as Sn,ob as bn,qb as Rn,ub as kn,vb as An}from"./chunk-36U7IQ6Y.mjs";import{i as Pt,p as Lt}from"./chunk-Z7X534S4.mjs";import{$ as Bt,G as Ot,N as Et,Z as $t,m as Me,r as Ct}from"./chunk-6QSM2WIH.mjs";import{a as Te}from"./chunk-QSRAEUGZ.mjs";import{a as Nt}from"./chunk-Y5CGXLUB.mjs";import{f as Dt,h as vt,i as V,k as jt}from"./chunk-3F5YMM2F.mjs";import{l as At}from"./chunk-SAR5622P.mjs";import{s as Tt,w as xt}from"./chunk-6MUEPV7M.mjs";import{A as Ee,B as pt,C as Ie,w as ut,z as lt}from"./chunk-HJC7AIBK.mjs";import{b as Pe,c as Y,d as $}from"./chunk-OTWRDD6L.mjs";import{c as dt,d as ct}from"./chunk-55HEMHEG.mjs";import{Aa as Qt,Ba as en,D as Wt,E as Gt,Ga as tn,Ha as nn,Ia as rn,K as Ut,L as zt,N as _,O as ae,P as qt,Q as de,R as Kt,S as Ht,T as ce,U as ue,W as Jt,Wa as sn,_ as X,qa as Yt,ta as Vt,ua as Xt,v as Ft,w as Mt,wa as Zt}from"./chunk-VXHDBYMI.mjs";import{q as _t}from"./chunk-ENLBYECD.mjs";import{a as at}from"./chunk-EADHKH3A.mjs";import{a as wt,d as St,e as bt,f as Rt,g as kt}from"./chunk-PNCONNFJ.mjs";import{E as ot}from"./chunk-CGWXQX75.mjs";import{f as it,h as J}from"./chunk-TZE3Y7IQ.mjs";import{c as ft,d as gt,f as mt,h as ht,j as yt,k as Fe}from"./chunk-SIOZXPFG.mjs";import{b as M}from"./chunk-CA5NAXSU.mjs";import{Fb as se,Jb as ie,Oc as st,Tb as nt,Va as et,Wa as ne,Yb as rt,bd as Oe,dc as oe,f as Ze,gb as tt,h as Ce,i as Qe,j as U,vb as re}from"./chunk-B45CNPUX.mjs";import{b as H,k as Re,l as ke,u as Ve,v as Xe,z as Ae}from"./chunk-7EANH5PY.mjs";var le=class{classify(e){let t=ne(e.statusCode),r=this.getSuggestedAction(e.statusCode,t);return{originalError:e,classification:t,suggestedAction:r}}classifyBatch(e){let t=e.map(a=>this.classify(a)),r={auth:0,permission:0,schema:0,data:0,validation:0,limit:0,network:0,trigger:0,reference:0,unknown:0},s={},i=0;for(let a of t){a.classification.retryable&&i++;let d=a.classification.category??"unknown";r[d]=(r[d]??0)+1,s[a.originalError.statusCode]=(s[a.originalError.statusCode]??0)+1}let o={totalErrors:e.length,retryableCount:i,nonRetryableCount:e.length-i,byCategory:r,byErrorCode:s,sampleErrors:e.slice(0,5)};return{classified:t,summary:o}}isRetryable(e){return ne(e).retryable}hasBlockingError(e){return e.some(t=>ne(t.statusCode).blockAll===!0)}get knownErrorCount(){return Object.keys(et).length}getSuggestedAction(e,t){return t.suggestUpsert?"Consider using upsert with external ID":t.suggestTruncate?"Truncate field values to fit within limits":t.blockAll?"Operation blocked: resolve storage/limit issue first":t.strategy==="reauth_then_retry"?"Re-authenticate and retry":t.strategy==="reduce_batch"?"Reduce batch size and retry":t.retryable?`Retry after ${t.delay??0}ms`:`Fix ${e} error and retry manually`}};function ar(n,e){return new Promise(t=>{if(e?.aborted){t();return}let r=()=>{clearTimeout(s),e?.removeEventListener("abort",r),t()},s=setTimeout(r,n);e?.addEventListener("abort",r,{once:!0})})}var pe=class{constructor(e={}){this.options=e;this.strategy=new Nt({...e.retryConfig,jitter:e.retryConfig?.jitter??!0}),this.classifier=new le}options;strategy;classifier;async execute(e){let t=this.strategy.getConfig(),r,s=0;for(let i=0;i<=t.maxRetries;i++)try{return{success:!0,result:await e(),attempts:i+1,totalDelay:s}}catch(o){r=o instanceof Error?o:new Error(String(o));let a=dr(o),d=this.classifier.classify(a);if(!d.classification.retryable)return{success:!1,error:r,attempts:i+1,totalDelay:s};if(i<t.maxRetries){let u={success:!1,error:r,attempts:i+1,totalDelay:s,cancelled:!0};if(this.options.signal?.aborted)return u;let c=this.strategy.calculateDelay(i);if(this.options.onRetry?.(i,d,c),s+=c,await ar(c,this.options.signal),this.options.signal?.aborted)return{...u,totalDelay:s}}}return{success:!1,error:r,attempts:t.maxRetries+1,totalDelay:s}}async executeBatch(e,t){let r=[...e],s=[],i=[],o=0,a=this.options.retryConfig?.maxRetries??3;for(;r.length>0&&o<=a;){let d=await t(r);s.push(...d.successes);let u=[];for(let c of d.failures)this.classifier.classify(c.error).classification.retryable&&o<a?u.push(c.record):i.push(c);if(r=u,r.length>0){let c=this.options.retryConfig?.initialDelay??1e3,l=this.options.retryConfig?.maxDelay??3e4,p=c*Math.pow(2,o);await new Promise(f=>setTimeout(f,Math.min(p,l))),o++}}return{successes:s,failures:i}}getClassifier(){return this.classifier}getStrategy(){return this.strategy}};function dr(n){if(typeof n!="object"||n===null)return{statusCode:"UNKNOWN_ERROR",message:String(n)};let e=n,t=[e.errorCode,e.statusCode,e.name].find(s=>typeof s=="string"&&s.length>0&&s!=="Error"),r=e.fields??e.data?.fields;return{statusCode:t??"UNKNOWN_ERROR",errorCode:typeof e.errorCode=="string"?e.errorCode:void 0,message:typeof e.message=="string"?e.message:String(n),fields:Array.isArray(r)?r.filter(s=>typeof s=="string"):void 0}}var cr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ur(n){if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1}async function lr(n,e,t,r=()=>Date.now()){let s=await At(n,e,{now:r,successfulOnly:!0});return s.state==="running"?{state:"running"}:s.state!=="ended"?s:{state:"ended",created:(s.results.successfulResults??[]).flatMap(o=>{let a=o.sf__Id;return typeof a!="string"||!cr.test(a)?[]:t&&ur(o.sf__Created)!==!0?[]:[a]}),...typeof s.info.systemModstamp=="string"?{at:s.info.systemModstamp}:{}}}async function Js(n,e,t,r,s=()=>new Date){let i,o=()=>(i??=(async()=>{if(!r)return 0;try{let d=s().getTime(),u=Date.parse(await r());return Number.isFinite(u)?u-(d+s().getTime())/2:0}catch{return 0}})(),i),a=[];for(let d of e.jobs??[]){if(d.job===void 0)continue;let u={job:d.job,objectApiName:d.objectApiName},c=await lr(t,d.job,d.upsert===!0,()=>s().getTime());if(c.state==="running"||c.state==="unread"){a.push({...u,read:c,answered:!1});continue}let l=s().toISOString();c.state==="ended"&&c.at!==void 0&&Number.isFinite(Date.parse(c.at))?l=new Date(Date.parse(c.at)-await o()).toISOString():e.lastWrittenAt!==void 0&&(l=e.lastWrittenAt);let p=c.state==="ended"?c.created:[],f=await n.answerInFlight(e.runId,d.objectApiName,p,l,d.job);a.push({...u,read:c,answered:f})}return a}function Ys(n,e){return e.map(({job:t,read:r})=>{let s=`${n}, job ${t}`;switch(r.state){case"ended":return`[INFO] ${s}: the job no line of the run answered ended in the org; ${r.created.length} record(s) it created kept with the run`;case"never-closed":return`[INFO] ${s}: the job was never closed, and wrote nothing`;case"running":return`[INFO] ${s}: the job is still running in the org; read again later`;default:return`[WARN] ${s}: the job could not be read back: ${r.reason}`}})}var K=5e3,$e=200,fe=H().refine(n=>Y(n),"not a record id"),pr=ke({sourceOrgId:H().min(1).max(200),targetOrgId:H().min(1).max(200),objectApiName:H().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),kind:Ve(["document","attachment"]),sourceId:fe,targetId:fe,sourceVersionId:fe.optional(),sourceModifiedAt:Ae.datetime().optional(),linked:Re(fe).max($e),copiedAt:Ae.datetime()}),fr=ke({version:Xe(1),entries:Re(pr).max(K)});function Mn(n){if(n==null)return{kind:"none"};let e=fr.safeParse(n);if(e.success)return{kind:"stored",map:e.data};let t=e.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"map"}: ${t.message}`}}function ai(n,e,t){return n?n.check({orgId:e,orgTier:rt(t),operation:"delete",objectName:"Attachment",recordCount:1,module:"sync"}).allowed:!1}var W=class extends Error{constructor(e){super(e),this.name="SyncFilesRefusedError"}},Z=class extends Error{};function gr(){return{copied:0,versions:0,bytes:0,links:0,unchanged:0,tooLarge:0,pastRunCap:0,external:0,recordNotWritten:0,failed:0}}function N(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function ge(n,e){let t=n;for(let r of e.split(".")){if(typeof t!="object"||t===null)return null;t=t[r]}return Ie(t)}function q(n,e){return e==null?n:n===void 0||Date.parse(e)>Date.parse(n)?e:n}function mr(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function Q(n,e,t){return`${n}|${e}|${t}`}function hr(n,e){let t=e.load(n.id);if(t===null)throw new W("Files are copied by a saved configuration only: it keeps which file it copied where, so that running it again copies none of them twice. Save the configuration, then run it. Nothing was read or written.");if(t.kind==="unreadable")throw new W(`The record of the files this configuration copied could not be read (${t.issue}), so a run could copy them a second time. Turn the files off, or save the configuration again under a new name. Nothing was read or written.`);let r=new Map;if(t.kind==="stored")for(let s of t.map.entries)r.set(Q(s.sourceOrgId,s.targetOrgId,s.sourceId),s);return r}var je="ContentDocument.LatestPublishedVersion.SystemModstamp";async function yr(n,e,t,r){let s=nt(t.objectApiName),i=t.where?.trim()?` WHERE (${it(t.where)})`:"",o=`SELECT Id FROM ${s}${i}`,a=Ee(r),d=new Set,u,c=await n.copy.queryRecords(e.sourceOrgId,`SELECT LinkedEntityId, SystemModstamp, ${je} FROM ContentDocumentLink WHERE LinkedEntityId IN (${o}) AND (SystemModstamp > ${a} OR ${je} > ${a})`);for(let p of c){let f=N(p,"LinkedEntityId");f&&Y(f)&&d.add(f),u=q(q(u,ge(p,"SystemModstamp")),ge(p,je))}let l=await n.copy.queryRecords(e.sourceOrgId,`SELECT ParentId, LastModifiedDate FROM Attachment WHERE ParentId IN (${o}) AND LastModifiedDate > ${a}`);for(let p of l){let f=N(p,"ParentId");f&&Y(f)&&d.add(f),u=q(u,ge(p,"LastModifiedDate"))}return{ids:[...d],...u!==void 0?{newest:u}:{}}}async function wr(n,e,t){let r=new Map;for(let s of $(t)){let i=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, LastModifiedDate FROM Attachment WHERE Id IN (${s})`);for(let o of i){let a=N(o,"Id"),d=Ie(o.LastModifiedDate);a&&d&&r.set(a,d)}}return r}function Sr(n,e,t){return e===void 0||n.targetId===n.sourceId?!1:n.sourceModifiedAt!==void 0?n.sourceModifiedAt!==e:t!==void 0&&Date.parse(e)>Date.parse(t)}async function br(n,e,t,r,s,i){let o=[...s.values()].filter(c=>c.kind==="document"&&c.objectApiName===t&&c.sourceOrgId===e.sourceOrgId&&c.targetOrgId===e.targetOrgId&&!i.has(c.sourceId)).map(c=>c.sourceId),a=Ee(r),d=[],u;for(let c of $(o)){let l=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SystemModstamp FROM ContentVersion WHERE ContentDocumentId IN (${c}) AND IsLatest = true AND SystemModstamp > ${a}`);for(let p of l){u=q(u,ge(p,"SystemModstamp"));let f=N(p,"ContentDocumentId"),g=N(p,"Id");if(!f||!g||(N(p,"ContentLocation")??"S")!=="S")continue;let h=N(p,"Title")??f;d.push({objectApiName:"ContentDocument",sourceId:f,body:{objectApiName:"ContentVersion",id:g},name:h,bytes:mr(p,"ContentSize"),hosts:[],fields:{Title:h,PathOnClient:N(p,"PathOnClient")??h}})}}return{files:d,...u!==void 0?{newest:u}:{}}}async function Rr(n,e,t,r){let s=new Map,i=new Date().toISOString(),o=(c,l,p)=>({sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:t,kind:c,sourceId:l,targetId:l,linked:[],copiedAt:i,...p}),a=r.filter(c=>c.objectApiName==="ContentDocument").map(c=>c.sourceId);for(let c of $(a)){let l=await n.copy.queryRecords(e.targetOrgId,`SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id IN (${c})`);for(let p of l){let f=N(p,"Id");if(!f)continue;let g=N(p,"LatestPublishedVersionId");s.set(f,o("document",f,g?{sourceVersionId:g}:{}))}}let d=[...s.keys()];for(let c of $(d)){let l=await n.copy.queryRecords(e.targetOrgId,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${c})`);for(let p of l){let f=N(p,"ContentDocumentId"),g=N(p,"LinkedEntityId"),h=f?s.get(f):void 0;h&&g&&Y(g)&&h.linked.length<$e&&h.linked.push(g)}}let u=r.filter(c=>c.objectApiName==="Attachment").map(c=>c.sourceId);for(let c of $(u)){let l=await n.copy.queryRecords(e.targetOrgId,`SELECT Id FROM Attachment WHERE Id IN (${c})`);for(let p of l){let f=N(p,"Id");f&&s.set(f,o("attachment",f,{}))}}return s}async function di(n){let{config:e,option:t,objects:r,deps:s}=n,i=hr(e,s.store),o;try{o=await cn(s.copy,e.targetOrgId)}catch(f){throw new W(`The file storage the target has left could not be read (${M(f)}), so the files could not be measured against it. Nothing was written.`)}let a=t.maxFileSizeMB*1048576,d=t.maxRunMB*1048576,u=0,c=0,l=new Set,p={objects:new Map,storage:{remainingBytes:o,plannedBytes:0}};for(let{objectConfig:f,changedSince:g,filesSeen:h}of r){if(f.operation==="delete")continue;let w=f.objectApiName,A=await s.sourceIds(f,g),R=[],y=g===void 0?void 0:h!==void 0&&Date.parse(h)>Date.parse(g)?lt(h):g,S=g===void 0?void 0:h,m=new Map;if(y!==void 0)try{let C=new Set(A),E=await yr(s,e,f,y);S=q(S,E.newest);let F=E.ids.filter(x=>!C.has(x));if(F.length>0){let x=n.tie?await n.tie(f,F):{held:new Map};m=x.held;let G=F.filter(or=>!m.has(or)).length;G>0&&R.push(`${G} record(s) whose files changed since the last run, and nothing else of them, could not be tied to their copy in the target`+(x.refused?` (${x.refused})`:"")+": their new files are copied when the record changes, or on a full read.")}}catch(C){throw new W(`${w}: the files its records gained since the last run could not be looked up (${M(C)}). Run it again, or turn the files off. Nothing was written.`)}let b=[...A,...m.keys()],T=await an({scope:new Map([[w,b]]),sourceOrgId:e.sourceOrgId,maxFileBytes:a,queryRecords:s.copy.queryRecords});if(dn(T)){let C=new Set(T.errors.flatMap(E=>E.samples.flatMap(F=>F.messages)));throw new W(`${w}: the files of its records could not all be looked up in the source (${[...C].join("; ")}). Run it again, or turn the files off. Nothing was written.`)}let I=gr();for(let C of T.leftOut)C.reason==="too-large"?I.tooLarge++:C.reason==="external"&&I.external++;I.tooLarge>0&&R.push(`${I.tooLarge} file(s) larger than ${t.maxFileSizeMB} MB were not copied.`);let P=T.files,v=[],j=new Map;try{if(y!==void 0){let F=new Set(P.map(G=>G.sourceId)),x=await br(s,e,w,y,i,F);S=q(S,x.newest);for(let G of x.files)G.bytes>a?I.tooLarge++:P=[...P,G]}let C=P.filter(F=>!i.has(Q(e.sourceOrgId,e.targetOrgId,F.sourceId)));if(C.length>0)for(let[F,x]of await Rr(s,e,w,C))i.set(Q(e.sourceOrgId,e.targetOrgId,F),x),v.push(x);let E=P.filter(F=>F.objectApiName==="Attachment");E.length>0&&(j=await wr(s,e,E.map(F=>F.sourceId)))}catch(C){throw new W(`${w}: the files an earlier run copied could not be looked up (${M(C)}), so a run could copy them twice. Nothing was written.`)}let D=[],L=new Map,k=0,O=0;for(let C of P){if(l.has(C.sourceId)){I.unchanged++,D.push(C);continue}let E=i.get(Q(e.sourceOrgId,e.targetOrgId,C.sourceId)),F=E?.kind==="attachment"&&Sr(E,j.get(C.sourceId),g);if(F&&!s.deleteFromTarget){O++;continue}if(E&&!F&&(E.kind==="attachment"||E.sourceVersionId===C.body.id)){I.unchanged++,E.kind==="document"&&D.push({...C,into:{documentId:E.targetId,linked:E.linked,unchanged:!0}});continue}if(!E&&c>=K-i.size){k++,I.pastRunCap++;continue}if(u+C.bytes>d){I.pastRunCap++;continue}u+=C.bytes,I.bytes+=C.bytes,l.add(C.sourceId),E&&F?(I.replaced=(I.replaced??0)+1,L.set(C.sourceId,E.targetId),D.push(C)):E?(I.versions++,D.push({...C,into:{documentId:E.targetId,linked:E.linked}})):(c++,I.copied++,D.push(C))}I.pastRunCap>k&&R.push(`${I.pastRunCap-k} file(s) past the ${t.maxRunMB} MB a run copies were not copied: the next run copies them.`),O>0&&R.push(`${O} legacy attachment(s) the source changed since they were copied were left as copied: replacing one deletes its earlier copy, and this run may not delete in the target.`),k>0&&R.push(`${k} file(s) were not copied: this configuration keeps the record of ${K} copied files at most, which it holds already.`),p.objects.set(w,{scope:new Set(b),files:D,outcome:I,notes:R,shared:v,held:m,replacing:L,attachmentsChangedAt:j,...S!==void 0?{filesSeen:S}:{}})}return p.storage={remainingBytes:o,plannedBytes:u,...u>o?{shortfall:`The files to copy take ${oe(u)} and the target has ${oe(Math.max(0,o))} of file storage left. Lower the largest file or the most a run copies, or leave the files out.`}:{}},p}function kr(n){return n.flatMap(e=>e.samples.map(t=>`${e.objectApiName}: ${t.recordSummary}: ${t.messages.join("; ")}`))}async function ci(n){let{config:e,option:t,objectApiName:r,planned:s,written:i,deps:o,signal:a}=n,d={...s.outcome,copied:0,versions:0,bytes:0,...s.outcome.replaced!==void 0?{replaced:0}:{}},u=[...s.notes],c=[...i.keys()].filter(m=>!s.scope.has(m)).length;c>0&&u.push(`${c} record(s) written were not in the source when the files were looked up: their files are copied by the next run.`);try{for(let m of s.shared)o.store.record(e.id,m)}catch(m){u.push(`The files the target already held could not be recorded (${M(m)}): the next run looks them up again.`)}if(s.files.length===0)return{outcome:d,notes:u,unplanned:c,cancelled:!1};let l=o.store.load(e.id),p=new Map((l?.kind==="stored"?l.map.entries:[]).filter(m=>m.sourceOrgId===e.sourceOrgId&&m.targetOrgId===e.targetOrgId).map(m=>[m.sourceId,m])),f=s.files.map(m=>{let b=m.into?void 0:p.get(m.sourceId);return b&&b.kind==="document"?{...m,into:{documentId:b.targetId,linked:b.linked,unchanged:!0}}:m}),g=un({files:f.filter(m=>!m.into?.unchanged),leftOut:[],errors:[]},t.maxFileSizeMB*1048576),h=[],w,A=!1,R=[],y={ids:[],note:void 0},S=(m,b)=>{let T=Q(e.sourceOrgId,e.targetOrgId,m.sourceId),I=[...new Set([...m.into?.linked??[],...b.linked])].slice(0,$e),P=m.objectApiName==="ContentDocument",v=s.replacing.get(m.sourceId),j=s.attachmentsChangedAt.get(m.sourceId);b.asVersion?(d.versions++,d.bytes+=m.bytes):v!==void 0?(d.replaced=(d.replaced??0)+1,d.bytes+=m.bytes):m.into?.unchanged||(d.copied++,d.bytes+=m.bytes),!b.asVersion&&!m.into&&n.onCreated?.(P?"ContentDocument":"Attachment",b.targetId);try{o.store.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:r,kind:P?"document":"attachment",sourceId:m.sourceId,targetId:b.targetId,...P?{sourceVersionId:m.body.id}:{},...!P&&j!==void 0?{sourceModifiedAt:j}:{},linked:I,copiedAt:new Date().toISOString()}),v!==void 0&&v!==b.targetId&&R.push(v)}catch(D){w=`${M(D)} (${T})`}};try{await ln({files:f,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:m=>i.has(m)||s.held.has(m),get:m=>i.get(m)??s.held.get(m),add:()=>{}},deps:o.copy,report:g,errors:h,waitIfPaused:async()=>{if(w!==void 0)throw new Z;if(await n.waitIfPaused?.(),a?.aborted)throw new Z},onProgress:m=>{m.status==="running"&&o.onProgress?.(m.progress,`${r}: ${m.message}`)},onCopied:S})}catch(m){if(!(m instanceof Z))throw m;A=w===void 0}finally{R.length>0&&(y=await Ar(o,R))}return d.links=g.links,d.failed=g.objects.reduce((m,b)=>m+b.failed,0)+y.ids.length,d.recordNotWritten=g.leftOut.filter(m=>m.reason==="record-not-created").length,u.push(...kr(h)),y.note!==void 0&&u.push(y.note),d.recordNotWritten>0&&u.push(`${d.recordNotWritten} file(s) were not copied: no record they hang on was written.`),w!==void 0&&(d.failed++,u.push(`A copied file could not be recorded, so no more files were copied: ${w}. Check the copies of the last files in the target before running it again.`)),{outcome:d,notes:u,unplanned:c,cancelled:A}}var Fn=200;async function Ar(n,e){let t=[],r=new Set;for(let s=0;s<e.length;s+=Fn){let i=e.slice(s,s+Fn);try{let o=await n.deleteFromTarget?.("Attachment",i)??[];i.forEach((a,d)=>{let u=o[d];u?.success||(t.push(a),r.add(u?.errors.join("; ")||"The target gave no reason."))})}catch(o){t.push(...i),r.add(M(o))}}return t.length===0?{ids:[],note:void 0}:{ids:t,note:`${t.length} earlier copy(ies) of an attachment replaced could not be deleted from the target (${[...r].join("; ")}): the record holds the new copy and the old one, ${t.join(", ")}.`}}function ui(n){let e=t=>{let r=n[t];if(!r)throw new Error(`No connection for the org ${t}.`);return r};return{queryRecords:async(t,r)=>(await at(e(t).pages,r)).records,readFileBody:(t,r,s)=>gn(e(t).transport,r,s),insertFile:(t,r,s)=>mn(e(t).transport,r,s),insertRecords:async(t,r,s)=>yt(await e(t).create(r,s),r).map(i=>({id:i.id,success:i.success,errors:i.errors})),remainingFileStorageMB:t=>hn(e(t).transport)}}function li(n){let e=0,t=0,r=0;for(let s of n)e+=s.copied+s.versions+(s.replaced??0),t+=s.bytes,r+=s.tooLarge+s.pastRunCap;return`${e} file(s), ${oe(t)} copied, ${r} skipped past the caps`}var Be="sync:config:",Tn="syncConfigs",ee="sync:delta:",Le="syncDelta",me="sync:files:",xn="syncFiles",Dn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Be}${e.id}`,e,Tn)}load(e){return this.configStore.get(`${Be}${e}`)}isSaved(e){return this.load(e)!==void 0}deltaStore(){return{load:e=>this.isSaved(e)?this.loadDelta(e):null,record:(e,t)=>this.recordWatermark(e,t)}}fileStore(){return{load:e=>this.isSaved(e)?this.loadFiles(e):null,record:(e,t)=>this.recordFile(e,t)}}list(){let e=this.configStore.getByCategory(Tn);return Object.values(e).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${ee}${e}`),this.configStore.delete(`${me}${e}`),this.configStore.delete(`${Be}${e}`)}loadDelta(e){return ut(this.configStore.get(`${ee}${e}`))}recordWatermark(e,t){let r=this.loadDelta(e),o={version:1,entries:[...(r.kind==="stored"?r.state.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.objectApiName!==t.objectApiName),t],...r.kind==="stored"&&r.state.resetAt?{resetAt:r.state.resetAt}:{}};this.configStore.set(`${ee}${e}`,o,Le)}loadFiles(e){return Mn(this.configStore.get(`${me}${e}`))}recordFile(e,t){let r=this.loadFiles(e);if(r.kind==="unreadable")throw new Error(`the record of copied files does not read: ${r.issue}`);let i=(r.kind==="stored"?r.map.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.sourceId!==t.sourceId);if(i.length>=K)throw new Error(`the record of copied files holds ${K} files already`);let o={version:1,entries:[...i,t]};this.configStore.set(`${me}${e}`,o,xn)}forgetFiles(e,t,r){let s=this.loadFiles(e);if(s.kind!=="stored"||r.length===0)return[];let i=new Set(r.map(d=>d.slice(0,15))),o=[],a=s.map.entries.filter(d=>{let u=d.sourceOrgId===t.sourceOrgId&&d.targetOrgId===t.targetOrgId&&i.has(d.targetId.slice(0,15));return u&&o.push(d),!u});if(o.length>0){let d={version:1,entries:a};this.configStore.set(`${me}${e}`,d,xn)}return o}markRemoved(e,t,r,s){let i=this.loadDelta(e);if(i.kind!=="stored"||r.length===0)return[];let o=[],a=i.state.entries.map(d=>d.sourceOrgId!==t.sourceOrgId||d.targetOrgId!==t.targetOrgId||!r.includes(d.objectApiName)?d:(o.push(d.objectApiName),{...d,removedAt:s}));if(o.length>0){let d={...i.state,entries:a};this.configStore.set(`${ee}${e}`,d,Le)}return o}clearDelta(e){let t=this.loadDelta(e),r=t.kind==="stored"?t.state.entries.length:0,s={version:1,entries:[],resetAt:new Date().toISOString()};return this.configStore.set(`${ee}${e}`,s,Le),r}};async function Cr(n,e,t){let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,ids:o}of e){let a=J(i);for(let d of $(o)){if(t?.aborted)return;let u=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${a} WHERE Id IN (${d})`);for(let c of u.records){let l=Date.parse(String(c.CreatedDate??""));Number.isFinite(l)&&(r=Math.min(r,l),s=Math.max(s,l))}}}if(!(!Number.isFinite(r)||!Number.isFinite(s)))return{first:new Date(r).toISOString(),last:new Date(s).toISOString()}}async function Ri(n,e){let t=s=>({note:`What the duplicate rules of the target reported of the run could not be read (${M(s)}): the empty DuplicateRecordSet records it left, if any, stay.`}),r=new Set;try{for(let{ids:s}of e)for(let i of $(s)){let{records:o}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE RecordId IN (${i})`);for(let a of o){let d=a.DuplicateRecordSetId;typeof d=="string"&&r.add(d)}}}catch(s){return{take:async()=>t(s)}}return{take:async()=>{if(r.size===0)return{};let s=new Set;try{for(let a of $([...r])){let{records:d}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE DuplicateRecordSetId IN (${a})`);for(let u of d)s.add(String(u.DuplicateRecordSetId))}}catch(a){return t(a)}let i=[...r].filter(a=>!s.has(a));if(i.length===0)return{};let o={objectApiName:"DuplicateRecordSet",planned:i.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]};for(let a=0;a<i.length;a+=Pe){let d=i.slice(a,a+Pe);for(let u of await Ct(n,o.objectApiName,d))u.kind==="deleted"?o.deleted+=1:u.kind==="gone"?o.alreadyGone+=1:(o.refused+=1,o.reasons.includes(u.reason)||o.reasons.push(u.reason))}return{object:o}}}}async function Or(n,e){if(!n||!e)return n;let t=Date.parse(e.at),r=Date.parse(e.lastAt??""),s=Date.parse(n.first),i=Date.parse(n.last);if(!Number.isFinite(s)||!Number.isFinite(i)||!Number.isFinite(t)&&!Number.isFinite(r))return n;let o=await vn(e);if(o===void 0)return n;let a=Number.isFinite(t)?Math.min(s,t+o):s,d=Number.isFinite(r)?Math.max(i,r+o):i;return a===s&&d===i?n:{first:a===s?n.first:new Date(a).toISOString(),last:d===i?n.last:new Date(d).toISOString()}}async function vn(n){let e=n.now??(()=>new Date);try{let t=e().getTime(),r=Date.parse(await n.serverTime());return Number.isFinite(r)?r-(t+e().getTime())/2:void 0}catch{return}}async function Er(n){if(!n)return;let e=Date.parse(n.at);if(!Number.isFinite(e))return;let t=Date.parse(n.lastAt??""),r=await vn(n);if(r===void 0)return;let s=Number.isFinite(t)?Math.max(e,t):e;return{first:new Date(e+r).toISOString(),last:new Date(s+r).toISOString()}}var Ir=50,Pr=3,jn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Fr(n,e,t,r){let s=Date.parse(t.first)-yn,i=Date.parse(t.last)+wn;if(!Number.isFinite(s)||!Number.isFinite(i))return;let o=new Map,a=0;for(let{objectApiName:d,ids:u}of e){if(a>=Pr||o.size>1||r?.aborted)break;let c=u.slice(0,Ir);if(c.length===0)continue;let l;try{let[f]=$(c,c.length);l=(await n.query(`SELECT Id, LastModifiedById, LastModifiedDate FROM ${J(d)} WHERE Id IN (${f})`)).records}catch{continue}let p=!1;for(let f of l){let{LastModifiedById:g,LastModifiedDate:h}=f??{},w=typeof h=="string"?Date.parse(h):Number.NaN;typeof g!="string"||!jn.test(g)||!(w>=s&&w<=i)||(o.has(g.slice(0,15))||o.set(g.slice(0,15),g),p=!0)}p&&a++}return o.size===1?[...o.values()][0]:void 0}async function ki(n,e,t,r,s,i,o){let a=e.some(({ids:f})=>f.length>0),d=a?await Or(await Cr(n,e,r),s):await Er(s),u=o.runUserId!==void 0&&jn.test(o.runUserId)?o.runUserId:void 0,c=n.query?.bind(n),l=!u&&!a&&d&&c?await Fr({query:c},i,d,r):void 0,p=i.filter(({ids:f})=>f.length>0);return{writtenBetween:d,created:e,remap:new Set([...e,...i].flatMap(({ids:f})=>f.map(g=>g.slice(0,15)))),automation:Sn(t),...u?{runUserId:u}:{},...l?{user:l}:{},ties:{...o.ties,...p.length>0?{writtenOver:p}:{}},...r?{signal:r}:{}}}var he={status:"cancelled",objects:[],unread:[],handWork:[]};function Ti(n,e,t){return{...Et(n,e),counts:bn(Bt($t(n),t))}}async function xi(n,e){let t=Date.parse(n.writtenBetween?.first??""),r=Date.parse(n.writtenBetween?.last??"");if(!Number.isFinite(t)||!Number.isFinite(r))return n;let{created:s}=n,i=new Set(s.flatMap(({ids:u})=>u.map(c=>c.slice(0,15)))),o=await Ot(e,{has:u=>i.has(u),start:t,end:r,...n.runUserId?{user:n.runUserId.slice(0,15)}:{}},s.filter(u=>u.objectApiName==="Quote").flatMap(({ids:u})=>u),new Set(s.map(u=>u.objectApiName))),a=new Set(o.flatMap(u=>u.copies.map(c=>c.id.slice(0,15))));if(a.size===0)return n;let{remap:d}=n;return{...n,remap:{has:u=>d.has(u)||a.has(u)}}}async function Di(n){let e,t,r;try{let o=await n.input();"refused"in o?r={...he,status:"refused",refusal:o.refused}:t=Rn(n.org,o,{...n.options,approve:async a=>{let{check:d,decision:u}=await It(n.guard,{...n.guardOf,objectName:An(a).join(", "),recordCount:kn(a)});if(e=u,u==="refused")return`Operation blocked by Production Guard: ${d.blockedReason??d.impactSummary}`;if(u==="declined")return"Operation cancelled by user (confirmation declined)."}})}catch(o){r={...he,status:"failure",refusal:M(o)}}let s=async o=>{if(!t||r)return!1;try{return await o(t)}catch(a){return r={...t.result(),status:"failure",refusal:M(a)},!1}},i;return{automationMade:t?.automationMade??new Set,ask:async()=>{await s(async o=>(await o.ask(),!1))},get takes(){return r?[]:t?.takes??[]},first:o=>s(a=>a.first(o)),afterRemoval:o=>s(a=>a.afterRemoval(o)),result:()=>r??t?.result()??he,settle:()=>(i??=(async()=>{let o=r??t?.result()??he;return n.onGuardDecision(o,e),t&&(t.made.size>0||t.late.size>0||t.gone.size>0)&&await n.keepMade?.(t.made,t.late,t.gone).catch(()=>{}),o})(),i)}}function vi(n){return n?"GUARD_BLOCKED":"SWEEP_REFUSED"}var Nn=6e4;function xr(n,e){return e.filter(t=>(t.ids.length>0||t.idsUntold===!0)&&Dr(n,t)).map(t=>({ids:[...t.ids],...t.idsUntold?{idsUntold:!0}:{}}))}function Dr(n,e){let t=Date.parse(n?.first??""),r=Math.max(t,Date.parse(n?.last??""));return!Number.isFinite(t)||!Number.isFinite(r)?!1:Number.isFinite(e.from)&&Number.isFinite(e.to)&&e.from<=r+9e5+Nn&&Math.max(e.from,e.to)>=t-2e3-Nn}var vr=new Set(["autopilot_execute","anonymize_execute","subject_erase","backup_restore","checkpoint_rewind","checkpoint_undo","frozen_load"]);function ji(n,e){return n.filter(t=>vr.has(t.action)&&t.action!==e&&t.outcome!=="stopped").map(t=>{let r=Date.parse(t.timestamp);return{ids:[],idsUntold:!0,from:r,to:r}})}function jr(n){let e=Date.parse(n.firstWrittenAt??n.startedAt),t=Date.parse(n.lastWriteAt??n.lastWrittenAt??n.end?.at??n.startedAt);return{ids:[...n.created,...n.overwritten??[]].flatMap(({ids:r})=>r),from:e,to:Number.isFinite(t)?t:e}}function Nr(n,e,t){return n.filter(r=>r.targetOrgId===e&&r.runId!==t).map(jr)}async function Ni(n,e,t,r){let s=await r(n.targetOrgId,e).catch(()=>[]),i=$r(n.removal?.removalSpans),o=n.removal?.madeEarlier,a=n.removal?.lateEarlier;return{otherRuns:xr(e,[...Nr(t,n.targetOrgId,n.runId),...s]),...i?{removalBegan:i}:{},...o&&o.length>0?{madeEarlier:o}:{},...a&&a.length>0?{lateEarlier:a}:{}}}function $i(n,e,t,r=[]){let s=[...r],i=Te(n.madeEarlier,e,s),o=Te(n.lateEarlier,t,s),a={...n};return delete a.madeEarlier,delete a.lateEarlier,{...a,...i.length>0?{madeEarlier:i}:{},...o.length>0?{lateEarlier:o}:{}}}function $r(n){let e;for(let t of n??[]){let r=Date.parse(t.first);Number.isFinite(r)&&(!e||r<e.at)&&(e={at:r,first:t.first})}return e?.first}var _e=class extends Error{constructor(t,r,s){super(t);this.result=r;this.cause=s;this.name="SyncRunFailure"}result;cause},$n=class extends _e{constructor(t,r,s){super(t,r);this.code=s;this.name="SyncRunRefused"}code};var Br=2e3,Lr=5e3,ye=class{chunkSize;pollIntervalMs;signal;constructor(e={}){this.chunkSize=e.chunkSize??Br,this.pollIntervalMs=e.pollIntervalMs??Lr,this.signal=e.signal}async executeChunked(e,t,r,s,i,o){if(!e.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=e.connection.bulk2.createJob({operation:r,object:t,...o?{externalIdFieldName:o}:{}}),d=a.id??`bulk-${crypto.randomUUID()}`,u={id:d,operation:r,object:t,state:"UploadComplete",numberRecordsProcessed:0,numberRecordsFailed:0,totalProcessingTime:0,createdDate:new Date().toISOString(),totalRecords:i};e.bulkManager.registerJob(u);try{await a.open();let c=bt(a);c!==void 0&&e.onOpened?.(c);let l=[];for await(let b of s){if(this.signal?.aborted)break;for(let T of b)l.push(T);e.onProgress?.(l.length,i)}let p,f=0;if(this.signal?.aborted||(p=wt(r,l,o),await a.uploadData(p.text),f=l.length),this.signal?.aborted||p===void 0)return await kt(a),e.bulkManager.updateJobState(d,"Aborted"),this.buildAbortedResult(f);await a.close();let g=await a.check();for(;g.state==="InProgress"||g.state==="UploadComplete";)e.bulkManager.updateJobState(d,g.state),e.onProgress?.(g.numberRecordsProcessed??0,i),await new Promise(b=>setTimeout(b,this.pollIntervalMs)),g=await a.check();let h=await a.getAllResults(),w=St(h,p,Rt(g)),A=w.outcomes,R=[],y=[],S=w.unattributedSuccessIds.length;for(let b of A)b.success?(S++,b.id!==void 0&&R.push(b.id)):y.push(b.error??"Unknown error");R.push(...w.unattributedSuccessIds),y.push(...w.unattributedFailures);let m=g.state==="JobComplete"?"JobComplete":"Failed";return e.bulkManager.updateJobState(d,m),e.bulkManager.updateJobCounts(d,g.numberRecordsProcessed??i,y.length),{totalRecords:f,successCount:S,failureCount:y.length,successIds:R,errors:y,aborted:!1,outcomes:A,...w.unattributedSuccessIds.length>0?{unmatchedIds:w.unattributedSuccessIds}:{}}}catch(c){throw e.bulkManager.updateJobState(d,"Failed"),c}}async*createChunkGenerator(e,t){let r=t??this.chunkSize;for(let s=0;s<e.length;s+=r)yield e.slice(s,s+r)}buildAbortedResult(e){return{totalRecords:e,successCount:0,failureCount:0,successIds:[],errors:[],aborted:!0}}};var _r=1e4,Wr=U.REST_API_BATCH_SIZE;function Gr(n){return!n.success&&n.errors.some(e=>e.startsWith("DUPLICATES_DETECTED"))}function We(n){return typeof n.created=="boolean"?{created:n.created}:{}}function _n(n){return n.some(e=>e.fields.length>0)?{errorDetails:n}:{}}function Bn(n){let e=n===void 0?void 0:gt(n);return e?_n([e]):{}}function Ur(n,e){return n!=="insert"&&n!=="upsert"?[]:e.flatMap(t=>t.success&&typeof t.id=="string"&&t.id!==""&&(n==="insert"||t.created===!0)?[t.id]:[])}function zr(n,e){return!n||!e?n??e:{before:async(t,r,s,i)=>await n.before?.(t,r,s,i)??await e.before?.(t,r,s,i),sending:(t,r,s)=>{n.sending(t,r,s),e.sending(t,r,s)},opened:(t,r,s,i)=>{n.opened?.(t,r,s,i),e.opened?.(t,r,s,i)},answered:(t,r,s,i)=>{n.answered(t,r,s,i),e.answered(t,r,s,i)}}}function Yi(n,e){let t=r=>r==="insert"||r==="upsert";return{...e?{before:(r,s,i,o)=>e.before(r,s,i,o)}:{},sending:(r,s,i)=>{t(s)?n.sending?.(r,i,s==="upsert"?{upsert:!0}:void 0):n.writing?.(r,i)},opened:(r,s,i,o)=>{t(s)&&n.sending?.(r,i,{job:o,...s==="upsert"?{upsert:!0}:{}})},answered:(r,s,i)=>{t(s)?n.answered?.(r,Ur(s,i)):i.length>0&&n.writing?.(r,i.length),e?.answered(r,s,i)}}}var Ln=class{constructor(e){this.deps=e;this.retryOp=new pe({retryConfig:e.retryConfig,signal:e.signal,onRetry:(t,r,s)=>{e.log(`[RETRY] sync attempt=${t} code=${r.originalError.statusCode} delay=${s}ms`)}})}deps;retryOp;async insert(e,t,r,s){let i=zr(this.deps.calls,s),o=u=>this.deps.connection.sobject(e).create(u,{headers:re()}),a="Insert failed after retries",d=await this.tryStreaming("insert",e,t,void 0,i)??await this.tryBulk("insert",e,t,void 0,i);return d?this.duplicatesAgain("insert",e,t,d,o,a,i):this.executeRestBatches("insert",e,t,r,o,a,i)}async upsert(e,t,r,s){let i=d=>this.deps.connection.sobject(e).upsert(d,t,{headers:re()}),o="Upsert failed after retries",a=await this.tryStreaming("upsert",e,r,t)??await this.tryBulk("upsert",e,r,t);return a?this.duplicatesAgain("upsert",e,r,a,i,o,this.deps.calls,t):this.executeRestBatches("upsert",e,r,s,i,o,this.deps.calls,t)}async update(e,t,r){let s=a=>this.deps.connection.sobject(e).update(a,{headers:re()}),i="Update failed after retries",o=await this.tryStreaming("update",e,t)??await this.tryBulk("update",e,t);return o?this.duplicatesAgain("update",e,t,o,s,i):this.executeRestBatches("update",e,t,r,s,i)}async delete(e,t,r){let s=t.map(o=>({Id:o})),i=await this.tryBulk("delete",e,s);return i||this.executeRestBatches("delete",e,t,r,o=>this.deps.connection.sobject(e).destroy(o),"Delete failed after retries")}async tryStreaming(e,t,r,s,i=this.deps.calls){if(r.length<=_r)return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new B(t);let o=await this.refusedBefore(i,t,e,r,s);if(o)return o;let a=new ye({signal:this.deps.signal});i?.sending(t,e,r.length);let d={connection:Me(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(l,p)=>{this.deps.onProgress(l,p,`Streaming ${e} ${t}`)},onOpened:l=>i?.opened?.(t,e,r.length,l)},u=await a.executeChunked(d,t,e,a.createChunkGenerator(r),r.length,s);if(u.aborted)throw i?.answered(t,e,[]),new B(t);this.logUnmatched(`Streaming ${e} ${t}`,u.unmatchedIds);let c=(u.outcomes??[]).map(l=>this.withExistingRecord(t,{id:l.id,success:l.success,errors:l.success?[]:[l.error??"Streaming error"],...We(l),...l.success?{}:Bn(l.error)}));return i?.answered(t,e,c),c}async tryBulk(e,t,r,s,i=this.deps.calls){if(!this.deps.bulkExecutor.shouldUseBulkApi(r.length))return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new B(t);let o={connection:Me(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(c,l)=>{this.deps.onProgress(c,l,`Bulk ${e} ${t}`)},signal:this.deps.signal,onOpened:c=>i?.opened?.(t,e,r.length,c)},a=await this.refusedBefore(i,t,e,r,s);if(a)return a;i?.sending(t,e,r.length);let d=await this.deps.bulkExecutor.executeBulk(o,t,e,r,s);if(d.aborted)throw i?.answered(t,e,[]),new B(t);this.logUnmatched(`Bulk ${e} ${t}`,d.unmatchedIds);let u=d.outcomes.map(c=>this.withExistingRecord(t,{id:c.id,success:c.success,errors:c.success?[]:[c.error??"Bulk error"],...We(c),...c.success?{}:Bn(c.error)}));return i?.answered(t,e,u),u}async refusedBefore(e,t,r,s,i){if(r==="delete"||!e?.before)return;let o=await e.before(t,r,s,i);if(o!==void 0)return this.deps.log(`[WARN] ${r} ${t}: ${s.length} row(s) not sent: ${o}`),s.map(()=>({success:!1,errors:[o]}))}async duplicatesAgain(e,t,r,s,i,o,a=this.deps.calls,d){let u=s.flatMap((f,g)=>g<r.length&&Gr(f)?[g]:[]);if(u.length===0||this.deps.signal?.aborted)return s;let c;try{c=await this.executeRestBatches(e,t,u.map(f=>r[f]),Wr,i,o,a,d,u)}catch(f){if(!(f instanceof B))throw f;c=f.written}let l=[...s];c.forEach((f,g)=>{l[u[g]]=f});let p=c.filter(f=>f.success).length;return this.deps.log(`[INFO] ${e} ${t}: ${u.length} row(s) a duplicate rule refused in the Bulk API job, which cannot carry the header that lets a rule's matches be saved, went again through REST with it: ${p} saved`+(c.length<u.length?`, ${u.length-c.length} not sent (cancelled)`:"")),l}logUnmatched(e,t){t&&t.length>0&&this.deps.log(`[WARN] ${e}: the job wrote ${t.length} record(s) no row was matched to: ${t.join(", ")}`)}withExistingRecord(e,t){if(t.success)return t;let r=Fe(t,this.deps.keyPrefixOf?.(e));return r.kind==="linked"?{...t,existingId:r.id}:t}async executeRestBatches(e,t,r,s,i,o,a=this.deps.calls,d,u){let c=[];for(let l=0;l<r.length;l+=s){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new B(t,c);let p=r.slice(l,l+s);if(e!=="delete"){let h=await this.refusedBefore(a,t,e,p,d);if(h){c.push(...h);continue}if(this.deps.signal?.aborted)throw new B(t,c)}a?.sending(t,e,p.length);let f=await this.retryOp.execute(()=>i(p));if(f.cancelled)throw a?.answered(t,e,[],u&&[]),new B(t,c);let g=[];if(f.success&&f.result)for(let h of Array.isArray(f.result)?f.result:[f.result])g.push(this.restOutcome(t,h));else g.push(...p.map(()=>({success:!1,errors:[f.error?.message??o]})));c.push(...g),a?.answered(t,e,g,u?.slice(l,l+p.length))}return c}restOutcome(e,t){if(t.success)return{id:t.id,success:!0,errors:[],...We(t)};let r=t.errors??[],s=r.map(mt),i={id:t.id,success:!1,errors:[s[0]??"Unknown error"],..._n(r.map(ft))},o=Fe({success:!1,errors:s,duplicateMatchIds:r.flatMap(a=>ht(a,e))},this.deps.keyPrefixOf?.(e));return o.kind==="linked"?{...i,existingId:o.id}:i}};var qr=2;async function Wn(n,e,t,r,s=()=>!1){let i=t.rows;if(!i||i.length!==e.length||t.stopped)return{result:t,unsent:[]};let o=[...i],a=[...e],d=e.map(()=>[]),u=[],c=!1;for(let p=0;p<qr&&!s();p++){let f=[],g=[],h=[];if(o.forEach((R,y)=>{if(R.id)return;let S=Dt(R.errorDetails,a[y],void 0);!S||S.some(({field:m})=>r.has(m))||(f.push(y),g.push(vt(a[y],S)),h.push(S))}),f.length===0)break;let w;try{w=await n(g)}catch(R){let y=[...new Set(h.flat().map(({field:S})=>S))].sort();u.push(`${f.length} record(s) refused on ${y.join(", ")} could not be written again without ${y.length===1?"it":"them"}: ${M(R)}`);break}if(Kr(w,g.length).forEach((R,y)=>{let S=f[y];o[S]=R,a[S]=g[y],d[S].push(...h[y])}),w.stopped){c=!0;break}}let l;return o.forEach((p,f)=>{!p.id||d[f].length===0||(l=V(l,{rows:1,fields:d[f].map(g=>({...g,rows:1}))}))}),{result:{successIds:o.flatMap(p=>p.id?[p.id]:[]),errors:o.flatMap(p=>p.id?[]:[p.error??"Unknown insert error"]),rows:o,...c?{stopped:!0}:{}},...l?{written:l}:{},unsent:u}}function Kr(n,e){if(n.rows&&(n.rows.length===e||n.stopped))return n.rows.slice(0,e);let t=[...n.successIds.map(s=>({id:s})),...n.errors.map(s=>({error:s}))];return(e===1?t:t.map(s=>({...s,unmatched:!0}))).slice(0,e)}var Hr=1e4,Jr=5e5,ze=200;function Se(n){let e=Math.floor(Jr/Math.max(1,n.fieldRules.length));return Math.max(ze,Math.min(Hr,e))}var Gn=class{deps;constructor(e){this.deps=e}async execute(e,t,r){let s=r??this.deps.generateId(),i=Date.now(),o=this.deps.validator.validate(e);if(!o.valid)return Hn(e.id,s,o.errors.map(c=>c.message),this.deps.now());let a=await En(e.relations,{...this.deps.describeKeyPrefix?{keyPrefixOf:this.deps.describeKeyPrefix}:{},...this.deps.readPresentParentIds?{presentIds:this.deps.readPresentParentIds}:{}});if(a.length>0)return Hn(e.id,s,a,this.deps.now());let d=e.objects.reduce((c,l)=>c+l.recordCount,0);return this.shouldActivateGrappe(d)?this.executeWithGrappe(e,t,s,i):this.executeSequential(e,t,s,i)}preview(e){return this.deps.planBuilder.build(e)}shouldActivateGrappe(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}reportProgress(e,t,r,s=0){let i=t.reduce((o,a)=>o+a.recordsCreated+a.recordsFailed,s);this.deps.onProgress?.({objectApiName:e,processedRecords:i,totalRecords:r,percentage:Math.round(i/Math.max(r,1)*100)})}async executeSequential(e,t,r,s){let i=Un(e,this.platformRolesOf(t),this.deps.onRowIds),o=this.deps.referenceLinker.resolveInsertOrder(e.objects,i.relations),a=e.objects.reduce((d,u)=>d+u.recordCount,0);for(let d of o){if(this.deps.signal?.aborted)return this.stoppedResult(e,r,i,s);let u=await this.readyToWrite(d,i,a);if(!u)continue;let c={},l={successIds:[],errors:[]},p={result:l,unsent:[]},f=zn(u),g=0,h=0,w=!1,A=Se(u.config);for await(let R of this.slicesOf(u,i,A,c)){if(this.deps.signal?.aborted){w=!0;break}g>0&&this.reportProgress(d.objectApiName,i.objectResults,a,l.successIds.length+l.errors.length);let y=await this.insert(t,d,R,u,i);if(g++,qn(f,u.config.rows,h,R.length,y.result),h+=R.length,os(p,y),y.result.stopped){w=!0;break}}if(g>0&&we(i,d,Ue(l,u),[...u.notes,...Ge(p)],c,f),w)return this.stoppedResult(e,r,i,s)}return this.ended(e,r,i,s)}async ended(e,t,r,s){let i,o=!1;try{i=await this.deps.knowledge?.({ids:Zr(r),results:r.objectResults})}catch(c){o=!0,i={skipped:`The articles were neither published nor linked: ${M(c)}`}}let a=Kn(e.id,t,r.objectResults,s,this.deps.now());if(!i)return a;let d=o||[i.publish,i.links].some(c=>(c?.notDone.length??0)>0),u=this.deps.signal?.aborted===!0;return{...a,knowledge:i,...(d||u)&&a.status==="success"?{status:"partial"}:{},...u?{cancelled:!0}:{}}}async readyToWrite(e,t,r){let s=Ce(e.objectApiName,t.relations),i=Qe(e,t.relations).filter(w=>t.wroteNothing.has(w));if(i.length>0)return te(t,e.objectApiName,`Skipped: ${i.join(", ")} wrote no records, so there is nothing for ${e.objectApiName} to point at.`);let o=await this.closedObject(e.objectApiName);if(o)return te(t,e.objectApiName,o,e.optional===!0);this.reportProgress(e.objectApiName,t.objectResults,r);let a=Xn(e,s),{config:d,dropped:u}=await Jn(a,this.deps.describeCreateableFields),c=await this.whyDropped(e.objectApiName,u),l=w=>w.fieldRules.length===0&&qe(w.rows).length===0;if(l(d)&&!l(a))return te(t,e.objectApiName,`Skipped: none of the fields the template names can be written (${c.join("; ")}).`);let{config:p,filled:f}=await Yn(await this.withTheOrgsPicklistValues(d),s,this.deps.describeRequiredFields),g=await this.matchStandardPricebook(p,t);if(g)return te(t,e.objectApiName,g);let h;if(s){let w=await this.placeChildren(p,s,t);if("skipped"in w)return te(t,e.objectApiName,w.skipped);if(w.parentIds.length===0&&w.unwritten){let{lines:A,keys:R}=w.unwritten;return we(t,e,{successIds:[],errors:A},[],{},R),null}h=w}return{relation:s,config:h?{...p,recordCount:h.parentIds.length,...h.rows?{rows:h.rows}:{}}:p,placed:h,...p.rows?{lengths:await this.fieldLengths(e.objectApiName)}:{},notes:[...c.map(w=>`Written without ${w}.`),...f.length>0?[`Written with ${f.join(", ")}, which this org requires and the template names no rule for.`]:[],...h?.notes??[]]}}async placeChildren(e,t,r){let{childObject:s,lookupField:i,parentObject:o}=t;if(!await this.orgTakesField(s,i))return{skipped:`Skipped: this org does not let a seed write ${s}.${i}, the lookup the relation fills.`};if(t.distribution.mode==="byKey")return Xr(e.rows??[],t,r.keys.get(o));let a=r.existingIds,d;if(t.parents.kind==="generated")d=a.get(o)??[];else if(t.parents.kind==="records")d=[...t.parents.ids];else{let p=this.deps.readExistingParentIds;if(!p)return{skipped:`Skipped: this run cannot read the ${o} records already in the org, so ${s} has nothing to point at.`};try{d=await p(o,t.parents.where,t.parents.limit)}catch(f){return{skipped:`Skipped: reading the ${o} records already in the org failed (${M(f)}), so ${s} has nothing to point at.`}}}if(d.length===0){let p=t.parents.kind==="existing"?t.parents.where?.trim():"";return{skipped:`Skipped: ${t.parents.kind==="generated"?`${o} wrote no records`:`no ${o} record in the org matches ${p?`"${p}"`:"the relation"}`}, so there is nothing for ${s} to point at.`}}let u=Ze(t.distribution,d.length,this.deps.random),c=u.reduce((p,f)=>p+f,0),l=[];for(let[p,f]of u.entries())for(let g=0;g<f&&l.length<e.recordCount;g++)l.push(d[p]);return l.length===0?{skipped:`Skipped: the relation gives none of the ${d.length} ${o} records a ${s}.`}:{parentIds:l,notes:c>l.length?[`Stopped at ${l.length} ${s} records, the most the template asks for: the relation spreads ${c} over ${d.length} ${o} records.`]:[]}}async*slicesOf(e,t,r,s){let i=e.config.recordCount,o=Math.max(1,Math.floor(r)),a=0;do{let d=Math.max(0,Math.min(o,i-a)),u=ns(e.config,e.relation)?rs(d):await this.deps.fieldMapper.mapFields(d===i?e.config:{...e.config,recordCount:d},t.existingIds,c=>{s.aiFallback=is(s.aiFallback,c)},a,e.lengths);ss(u,e.relation,e.placed,a),yield u,a+=d}while(a<i)}async insert(e,t,r,s,i){let o=p=>this.deps.insert(e,t.objectApiName,p,t.batchSize),a=t.objectApiName===ot?await i.platformRoles.link(r):new Map,d=a.size>0?r.filter((p,f)=>!a.has(f)):r,u=d.length===0&&r.length>0?{successIds:[],errors:[],rows:[]}:await o(d),c=await Wn(o,d,u,Yr(s),()=>this.deps.signal?.aborted===!0);t.objectApiName===In&&i.platformRoles.opportunitiesWritten(d,c.result);let l=a.size>0?Qr(c,r.length,a):c;return u.notes&&u.notes.length>0?{...l,notes:u.notes}:l}platformRolesOf(e){return new Pn({orgId:e,readTarget:this.deps.readTarget,update:this.deps.update,stopped:()=>this.deps.signal?.aborted===!0})}async closedObject(e){if(!this.deps.objectAccess)return;let t;try{t=await this.deps.objectAccess(e)}catch{return}if(t.access==="createable")return;let r=t.reason?` (${t.reason})`:"";return t.access==="absent"?`Skipped: this org has no ${e} object${r}.`:`Skipped: the user this seed runs as may not create ${e} records${r}.`}async withTheOrgsPicklistValues(e){if(!this.deps.describePicklistValues||!e.fieldRules.some(i=>i.ruleType==="picklist_random"))return e;let t;try{t=await this.deps.describePicklistValues(e.objectApiName)}catch{return e}let r=!1,s=e.fieldRules.map(i=>{let o=t.get(i.fieldApiName),a=i.config.picklistValues;if(i.ruleType!=="picklist_random"||!o?.length||!a)return i;let d=a.filter(u=>o.includes(u));return d.length===a.length?i:(r=!0,{...i,config:{...i.config,picklistValues:d.length?d:[...o]}})});return r?{...e,fieldRules:s}:e}async matchStandardPricebook(e,t){if(!e.fieldRules.some(o=>ie(o,t.written))||t.existingIds.has(se))return;let r=this.deps.readExistingParentIds,s=`${e.objectApiName} points at the org's standard price book`;if(!r)return`Skipped: ${s}, and this run cannot read it.`;let i;try{i=await r(se,"IsStandard = true",1)}catch(o){return`Skipped: ${s}, and reading it failed (${M(o)}).`}if(i.length===0)return`Skipped: ${s}, and the org shows none to this user.`;t.existingIds.set(se,i)}async orgTakesField(e,t){if(!this.deps.describeCreateableFields)return!0;try{return(await this.deps.describeCreateableFields(e)).has(t)}catch{return!0}}async whyDropped(e,t){if(t.length===0)return[];let r=new Set;try{this.deps.describeVisibleFields&&(r=await this.deps.describeVisibleFields(e))}catch{}let s=t.filter(a=>r.has(a)),i=t.filter(a=>!r.has(a)),o=(a,d,u)=>a.length===1?d:u;return[...i.length>0?[`${i.join(", ")}: this org does not have ${o(i,"that field","those fields")}, or field-level security hides ${o(i,"it","them")} from the user SandForge connects as`]:[],...s.length>0?[`${s.join(", ")}: ${o(s,"it exists","they exist")}, but the user SandForge connects as may not set ${o(s,"it","them")}`]:[]]}async fieldLengths(e){if(!this.deps.describeFieldLengths)return new Map;try{return await this.deps.describeFieldLengths(e)}catch{return new Map}}async executeWithGrappe(e,t,r,s){let o=this.deps.grappeAdapter.partition(e),a=o.reduce((h,w)=>h+w.recordCount,0);this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:r,totalPartitions:o.length,totalRecords:a}});let d=Un(e,this.platformRolesOf(t),this.deps.onRowIds),u=this.deps.referenceLinker.resolveInsertOrder(e.objects,d.relations),c=[],l=0,p=this.deps.grappeConfig?.grappeSize??2e3,f=()=>{let h=d.objectResults.reduce((A,R)=>A+R.recordsCreated,0),w=d.objectResults.reduce((A,R)=>A+R.recordsFailed,0);this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:r,totalProcessed:h,totalFailed:w}})},g=()=>(f(),this.stoppedResult(e,r,d,s));for(let h of u){if(this.deps.signal?.aborted)return g();let w=Math.ceil(h.recordCount/p),A=await this.readyToWrite(h,d,a);if(!A){l=this.settleUnusedPartitions(o,l,w,0);continue}let R={},y=Math.max(1,Math.ceil(A.config.recordCount/p)),S=0,m=0,b=[],T=[],I={result:{successIds:[],errors:[]},unsent:[]},P,v=zn(A),j=0,D=-1;for await(let L of this.slicesOf(A,d,p,R)){if(D++,this.deps.signal?.aborted){P=D;break}D>0&&this.reportProgress(h.objectApiName,d.objectResults,a,S+m);let k=Date.now(),O=o[l]?.id??this.deps.generateId(),C=await this.insert(t,h,L,A,d),E=C.result;qn(v,A.config.rows,j,L.length,E),j+=L.length,C.written&&(I.written=V(I.written,C.written)),I.unsent.push(...C.unsent);for(let x of C.notes??[])(I.notes??[]).includes(x)||(I.notes=[...I.notes??[],x]);S+=E.successIds.length,m+=E.errors.length,b.push(...E.errors),T.push(...E.successIds),c.push({grappeId:O,status:E.errors.length===0?"success":E.successIds.length>0?"partial":"failure",processedRecords:L.length,successCount:E.successIds.length,failureCount:E.errors.length,errors:E.errors,duration:Date.now()-k}),l++;let F=Math.round(l/Math.max(o.length,1)*100);if(this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:O,percentage:F,processedRecords:S+m}}),E.stopped){P=D+1;break}}if(P!==void 0)return P>0&&we(d,h,Ue({successIds:T,errors:b},A),[...A.notes,...Ge(I)],R,v),g();l=this.settleUnusedPartitions(o,l,w-y,S+m),we(d,h,Ue({successIds:T,errors:b},A),[...A.notes,...Ge(I)],R,v)}return f(),this.ended(e,r,d,s)}stoppedResult(e,t,r,s){let i=Kn(e.id,t,r.objectResults,s,this.deps.now());return{...i,status:i.status==="success"?"partial":i.status,cancelled:!0}}settleUnusedPartitions(e,t,r,s){let i=t;for(let o=r;o>0;o--){let a=e[i]?.id??this.deps.generateId();i++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:a,percentage:Math.round(i/Math.max(e.length,1)*100),processedRecords:s}})}return i}};function Un(n,e,t){return{relations:n.relations??[],written:new Set(n.objects.map(r=>r.objectApiName)),existingIds:new Map,wroteNothing:new Set,keys:new Map,...t?{onRowIds:t}:{},platformRoles:e,objectResults:[]}}function Yr(n){return new Set(["RecordTypeId",...n.relation?[n.relation.lookupField]:[],...n.config.fieldRules.filter(e=>e.ruleType==="reference").map(e=>e.fieldApiName)])}function Ge(n){return[...n.notes??[],...n.written?[jt(n.written)]:[],...n.unsent]}function te(n,e,t,r=!1){let s=as(e,t);return n.objectResults.push(r?{...s,optional:!0}:s),n.wroteNothing.add(e),null}function we(n,e,t,r,s,i){i&&(n.keys.set(e.objectApiName,i),n.onRowIds?.(e.objectApiName,Vr(i)));let o=n.platformRoles.resultOf(e.objectApiName),a=[...t.successIds,...o.linkedIds];n.existingIds.set(e.objectApiName,a),e.recordCount>0&&a.length===0&&n.wroteNothing.add(e.objectApiName),n.objectResults.push({objectApiName:e.objectApiName,recordsCreated:t.successIds.length,recordsFailed:t.errors.length,createdIds:t.successIds,errors:[...t.errors,...r,...o.notes],...s,...o.writtenByThePlatform?{writtenByThePlatform:o.writtenByThePlatform}:{}})}function Vr(n){let e={};for(let[t,r]of n)"id"in r&&(e[t]=r.id);return e}function Xr(n,e,t){let{childObject:r,parentObject:s}=e;if(!t)return{skipped:`Skipped: ${r} is placed by key, and ${s} wrote no rows to place it under.`};let i=[],o=[],a=[],d=new Map;for(let u of n){let c=u.parentKey,l=c===void 0?void 0:t.get(c);if(l&&"id"in l){i.push(l.id),o.push(u);continue}let p=c===void 0?`it names no ${s} row`:`its ${s} ${c} ${l?l.why:`is no ${s} row this run wrote`}`;a.push(`${r} ${u.key} not written: ${p}.`),d.set(u.key,{why:`was not written, as ${p}`})}return{parentIds:i,notes:[],rows:o,unwritten:{lines:a,keys:d}}}function Zr(n){let e=new Map;for(let[t,r]of n.keys){let s=new Map;for(let[i,o]of r)"id"in o&&s.set(i,o.id);e.set(t,s)}return e}function zn(n){if(n.config.rows)return new Map(n.placed?.unwritten?.keys??[])}function qn(n,e,t,r,s){if(!n||!e)return;let i=s.rows&&(s.rows.length===r||s.stopped)?s.rows:void 0;for(let o=0;o<r;o++){let a=e[t+o];if(!a)continue;let d=i?.[o];i?d?d.id&&d.unmatched?n.set(a.key,{why:"has no id this run can tell: the org did not say which of the ids it answered is its"}):d.id?n.set(a.key,{id:d.id}):n.set(a.key,{why:`was refused (${d.error??"Unknown insert error"})`}):n.set(a.key,{why:"was not sent: the run was stopped before it"}):n.set(a.key,{why:"has no id this run can tell: the insert did not answer record by record"})}}function Ue(n,e){let t=e.placed?.unwritten?.lines??[];return t.length===0?n:{...n,errors:[...n.errors,...t]}}function Qr(n,e,t){let r=n.result.rows;if(!r)return n;let s=[],i=0;for(let o=0;o<e;o++){let a=t.get(o);if(a){s.push({id:String(a.Id)});continue}let d=r[i++];if(!d)break;s.push(d)}return{...n,result:{...n.result,rows:s}}}function qe(n){return[...new Set((n??[]).flatMap(e=>Object.keys(e.values)))]}function es(n){return!n||n.length===0?[]:qe(n).filter(e=>n.every(t=>e in t.values))}function ts(n,e){return e.size===0?[...n]:n.map(t=>({...t,values:Object.fromEntries(Object.entries(t.values).filter(([r])=>!e.has(r)))}))}async function Jn(n,e){if(!e)return{config:n,dropped:[]};let t;try{t=await e(n.objectApiName)}catch{return{config:n,dropped:[]}}let r=n.fieldRules.filter(a=>a.ruleType==="reference"||t.has(a.fieldApiName)),s=qe(n.rows).filter(a=>!t.has(a));if(r.length===n.fieldRules.length&&s.length===0)return{config:n,dropped:[]};let i=[...new Set([...n.fieldRules.filter(a=>!r.includes(a)).map(a=>a.fieldApiName),...s])],o=n.rows&&ts(n.rows,new Set(s));return{config:{...n,fieldRules:r,...o?{rows:o}:{}},dropped:i}}async function Yn(n,e,t){if(!t)return{config:n,filled:[]};let r;try{r=await t(n.objectApiName)}catch{return{config:n,filled:[]}}let s=new Set([...n.fieldRules.map(o=>o.fieldApiName),...es(n.rows),...e?[e.lookupField]:[]]),i=[];for(let o of r){if(s.has(o.fieldApiName))continue;let a=tt(o);a.ruleType==="static"&&a.config.staticValue===void 0||i.push({fieldApiName:o.fieldApiName,fieldType:o.type,...a})}return i.length===0?{config:n,filled:[]}:{config:{...n,fieldRules:[...n.fieldRules,...i]},filled:i.map(o=>o.fieldApiName)}}async function Vn(n,e,t){let r=Ce(n.objectApiName,e),{config:s}=await Jn(Xn(n,r),t.describeCreateableFields),{config:i}=await Yn(s,r,t.describeRequiredFields);return Se(i)}function Xn(n,e){if(!e)return n;let t=n.fieldRules.filter(r=>r.fieldApiName!==e.lookupField);return t.length===n.fieldRules.length?n:{...n,fieldRules:t}}function ns(n,e){return e!==void 0&&n.fieldRules.length===0&&!n.rows}function rs(n){return Array.from({length:n},()=>({}))}function ss(n,e,t,r=0){if(!(!e||!t))for(let[s,i]of n.entries())i[e.lookupField]=t.parentIds[r+s]}function is(n,e){return n?{fields:[...new Set([...n.fields,...e.fields])],reason:n.reason==="no-answer"&&e.reason==="no-answer"?"no-answer":"short-answer"}:e}function os(n,e){for(let t of e.result.successIds)n.result.successIds.push(t);for(let t of e.result.errors)n.result.errors.push(t);e.written&&(n.written=V(n.written,e.written)),n.unsent.push(...e.unsent);for(let t of e.notes??[])(n.notes??[]).includes(t)||(n.notes=[...n.notes??[],t])}function as(n,e){return{objectApiName:n,recordsCreated:0,recordsFailed:0,createdIds:[],errors:[e]}}function Kn(n,e,t,r,s){let i=t.reduce((d,u)=>d+u.recordsCreated,0),o=t.reduce((d,u)=>d+u.recordsFailed,0),a=t.some(d=>!d.optional&&d.recordsCreated===0&&d.recordsFailed===0&&d.errors.length>0);return{templateId:n,operationId:e,status:ds(i,o,a),objectResults:t,totalRecordsCreated:i,totalRecordsFailed:o,duration:Date.now()-r,timestamp:s}}function ds(n,e,t){return e===0&&!t?"success":n===0?"failure":"partial"}function Hn(n,e,t,r){return{templateId:n,operationId:e,status:"failure",objectResults:[{objectApiName:"validation",recordsCreated:0,recordsFailed:0,createdIds:[],errors:t}],totalRecordsCreated:0,totalRecordsFailed:0,duration:0,timestamp:r}}var cs=200,us=1,ls=1,Ke=2,ps=2,Zn=3,fs=1,gs=200,ms="Campaign";function Qn(n,e){if(!n)return;let t=e.toLowerCase();for(let[r,s]of n)if(r.toLowerCase()===t)return s}function hs(n,e){let t=Math.max(1,Math.floor(e)),r=[],s=0;do{let i=Math.max(0,Math.min(t,n-s));r.push(i),s+=i}while(s<n);return r}function ys(n,e={}){let t=e.bulkThreshold??cs,r=!1;return n.objects.flatMap(i=>{let o=Qn(e.duplicateRules,i.objectApiName),a=o===!1&&!pn.has(i.objectApiName),d=e.partition??e.slices?.get(i.objectApiName)??Se(i);return hs(i.recordCount,d).map(u=>{let c=_([{rows:u,perCall:i.batchSize}]);if(u<=t||(r=!0,o===!0))return c;let l=_([{rows:u,bulk:!0}]);return a?l:Math.max(l,c)})}).reduce((i,o)=>i+o,0)+(r?us:0)+_(bs(n))}function ws(n,e={}){return ys(n,e)+Ss(n,e)}function Ss(n,e={}){let t=new Set(n.objects.map(i=>i.objectApiName)),r=n.objects.some(i=>i.fieldRules.some(o=>ie(o,t))),s=(n.relations??[]).reduce((i,{parents:o})=>o.kind==="existing"?i+_([{rows:0,readRows:o.limit}]):o.kind==="records"?i+Math.ceil(o.ids.length/On):i,0);return ls+n.objects.length+Ke+(t.has(ms)?Ke+1:0)+s+(r?fs:0)+(e.typedFirst?ps:0)+Zn+Math.max(0,e.sentBefore??0)+Math.max(0,e.automationRead??0)+Math.max(0,e.slicesRead??0)}async function mo(n,e,t){let r=new Map;if(t!==void 0)return r;for(let s of n.objects)s.recordCount<=ze||r.set(s.objectApiName,await Vn(s,n.relations,e));return r}function ho(n,e){return n?.enabled&&e.objects.reduce((r,s)=>r+s.recordCount,0)>=n.autoActivateThreshold?n.grappeSize:void 0}function be(n,e){return n.reduce((t,{objectApiName:r,rows:s,perCall:i,deletes:o})=>{if(s<=e.threshold)return t+_([{rows:s,perCall:i??e.perCall}]);let a=o===!0||Qn(e.duplicateRules,r)===!1?0:s;return t+_([{rows:s,bulk:!0},{rows:a}])},0)}function He(n=0,e=0){return Zn+Ke+Math.max(0,n)+Math.max(0,e)}function yo(n,e){let t=i=>n.find(o=>o.objectApiName===i)?.rows??0,r=Math.min(t("Opportunity"),t("OpportunityContactRole")),s=n.filter(({objectApiName:i})=>e.secondPass?.has(i)===!0).map(({rows:i})=>({rows:i}));return be(n,e)+(r>0?Math.ceil(r/gs)+be([{objectApiName:"OpportunityContactRole",rows:r}],e):0)+_(s)+He(n.length,e.automationRead)}function bs(n){let e=r=>n.objects.find(s=>s.objectApiName===r)?.recordCount??0,t=Math.min(e("OpportunityContactRole"),e("Opportunity"));return t>0?[{rows:t},{rows:t}]:[]}function Rs(n,e){return n.objects.reduce((t,r)=>t+Wt(r.objectApiName,{rows:r.recordCount,personAccounts:e.includes(r.objectApiName)?r.recordCount:0}),0)}var So="SEED_STORAGE_EXCEEDED";async function bo(n,e,t,r,s,i={},o={}){let a={storageBytes:Rs(e,t)},d;try{d=await Ut(n)}catch(h){d={unread:M(h)}}let u=X(a,d),c="unread"in d?await zt(n).catch(h=>({unread:M(h)})):d.dailyApiRequests,l=ae({run:ws(e,o),...ce(s),...i},c),p=ue(s);if(p)return{check:u,api:l,refusal:p.message,refusedFor:"checkpoint",checkpointRefusal:p.refusal};let f=sn(u,r);if(f)return{check:u,api:l,refusal:`${f} Nothing was written.`,refusedFor:"storage"};let g=de(l,r);return g?{check:u,api:l,refusal:g,refusedFor:"apiRequests"}:{check:u,api:l}}function Ro(n,e){let{check:t,api:r}=n,s=r.parts??{},i={checkpoint:s.checkpoint??0,mute:s.mute??0,readBack:s.readBack??0,deliverability:s.deliverability??0,fit:s.fit??0};return on({storage:t.verdict==="unread"?{unread:t.unread}:{maxMB:t.maxMB,remainingMB:t.remainingMB},...e!==void 0?{withinMB:e}:{},api:r.verdict==="unread"?{unread:r.unread}:{max:r.max,remaining:r.remaining},otherRequests:i})}function ks(n){return n==="insert"||n==="upsert"}function nr(n){return n==="update"||n==="upsert"}function As(n){return Gt(n.objects.filter(e=>ks(e.operation)).map(({objectApiName:e,rows:t,personAccounts:r})=>({objectApiName:e,rows:[],counted:{rows:t,...r!==void 0?{personAccounts:r}:{}}})))}var rr=U.REST_API_BATCH_SIZE;function Cs(n,e){return be(n.filter(t=>t.rows>0).map(({objectApiName:t,operation:r,rows:s,batchSize:i})=>({objectApiName:t,rows:s,...i!==void 0?{perCall:i}:{},...r==="delete"?{deletes:!0}:{}})),{threshold:e.bulkThreshold??rr,...e.duplicateRules?{duplicateRules:e.duplicateRules}:{}})}var Os="Opportunity",Es="OpportunityContactRole",Is=200,Ps={update:{characters:De,wide:!0},upsert:{characters:Cn(),wide:!0}},Fs=2,er=Array.from({length:Fs},()=>1),Ms=1;function Ts(n){let e=Math.min(Math.max(0,n),5e4);return Ms+Math.max(1,Math.ceil(e/Lt))}function Ye(n,e){let t=Math.max(1,Math.floor(e));return Array.from({length:Math.ceil(Math.max(0,n)/t)},(r,s)=>Math.min(t,n-s*t))}function xs(n,e){if(n.rows<=(e.bulkThreshold??rr))return Ye(n.rows,n.batchSize??U.REST_API_BATCH_SIZE);let t=e.duplicateRules?[...e.duplicateRules].find(([r])=>r.toLowerCase()===n.objectApiName.toLowerCase())?.[1]:void 0;return[n.rows,...t===!1?[]:Ye(n.rows,U.REST_API_BATCH_SIZE)]}function Ds(n,e){let t=0,r=!1;for(let d of e.targetHeld?.values()??[])t+=Ts(d);for(let d of n.objects)d.rows<=0||d.operation==="delete"||(t+=er.length,!(d.operation!=="update"&&d.operation!=="upsert")&&(r=!0,t+=ve([...xs(d,e),...er],d.overwriteKey??Ps[d.operation])));let s=d=>n.objects.find(u=>u.objectApiName===d&&(u.operation==="insert"||u.operation==="upsert")),i=s(Os),o=s(Es),a=i&&o?Math.min(i.rows,o.rows+(n.rolesLinked??0)):0;if(o&&a>0){let d=Ye(a,o.batchSize??U.REST_API_BATCH_SIZE);r=!0,t+=Math.ceil(a/Is)+d.length+ve(d,{characters:De,wide:o.overwriteKey?.wide??!0})}return r&&(t+=1),e.leaseAssigns===!0&&(t+=Math.max(0,n.describedAgain??0)),t}function sr(n){let e=new Map;for(let{objectApiName:t,operation:r}of n.objects){let s=e.get(t)??new Set;(r==="insert"||r==="upsert")&&s.add("insert"),(r==="update"||r==="upsert")&&s.add("update"),r==="delete"&&s.add("delete"),e.set(t,s)}return(t,r)=>e.get(t)?.has(r)===!0}function ir(n,e){let t=new Set(e);return{...n,objectsRead:n.objectsRead.filter(r=>t.has(r)),objects:n.objects.filter(r=>t.has(r.objectApiName))}}function vs(n){let e;return t=>{if(e&&t.every(s=>e?.objects.includes(s)))return e.answer.then(s=>ir(s,t));let r=n(t);return e??={objects:[...t],answer:r},r}}function $o(n,e){if(n.direction==="bidirectional")return async t=>{let r=n.objects.find(i=>i.objectApiName===t),s=pt(r?.where,void 0);return e(`SELECT COUNT() FROM ${J(t)}${s?` WHERE ${s}`:""}`)}}async function js(n,e){let t=new Set((n.heldBack??[]).filter(({rows:s})=>s>0).map(({objectApiName:s})=>s)),r=new Map;for(let{objectApiName:s,operation:i,rows:o}of n.objects){if(!nr(i)||r.has(s)||o<=0&&!t.has(s))continue;let a=await e(s).catch(()=>5e4);r.set(s,Number.isFinite(a)&&a>=0?a:5e4)}return r}async function tr(n,e){let t=As(n),r=n.objects.filter(k=>k.rows>0).map(({objectApiName:k,rows:O})=>({objectApiName:k,rows:O})).sort((k,O)=>O.rows-k.rows||k.objectApiName.localeCompare(O.objectApiName)),s=r.reduce((k,O)=>k+O.rows,0),i=n.objects.filter(k=>nr(k.operation)).reduce((k,O)=>k+O.rows,0),o=X(t,{maxMB:0,remainingMB:0}),a=[],d,u=s>0?vs(e.readAutomation):e.readAutomation,c,l,p,f=sr(n),g;if(s>0){let k=n.objects.filter(O=>O.rows>0).map(O=>O.objectApiName);if(g=await u(k).catch(O=>({unread:O instanceof Error?O.message:String(O)})),e.checkpointFirst){let O="objects"in g?Oe(g,void 0,f):{firing:[]};try{c=await e.checkpointFirst.scope(k,O)}catch(C){l=_t(C)}}}let h={unread:"not read"};if(s>0){let k=await e.readStorage().catch(O=>({unread:O instanceof Error?O.message:String(O)}));h="unread"in k?await e.readApiBudget().catch(O=>({unread:O instanceof Error?O.message:String(O)})):k.dailyApiRequests,t.totalRows>0&&(o=X(t,k))}if(t.totalRows>0){let k=await Yt({plan:t,objects:t.objects.map(O=>O.objectApiName),readAutomation:u,readLimits:e.readLimits});a=k.checks,d=k.unread}g!==void 0&&(p=await Mt({...e.emails,read:g,writes:f,readDeliverability:e.readDeliverability,run:"sync"}));let w=s>0&&e.countTarget?await js(n,e.countTarget):void 0,A=en(p?.ofRun),R=e.sentBefore?.(),y=s===0?0:R!==void 0?Math.max(0,R-(A.deliverability??0)):He(0,g!==void 0?Qt(g):0)+(w?.size??0),S=g!==void 0?fn(g):void 0,m=s===0?0:Ds(n,{bulkThreshold:e.bulkThreshold,duplicateRules:S,leaseAssigns:(e.mutePlan?.()?.assign.length??0)>0,...w?{targetHeld:w}:{}}),b=ae({run:Cs(n.objects,{bulkThreshold:e.bulkThreshold,duplicateRules:S})+y+m,...ce(c),...xt(e.mutePlan?.()),...n.readBack!==void 0&&n.readBack>0?{readBack:n.readBack}:{},...A},h),T=e.confirmAboveRecords,I=T>0&&s>T?T:void 0,P=(n.unwritable??[]).map(({objectApiName:k,rows:O,why:C,key:E})=>({...E!==void 0?{key:E}:{},objectApiName:k,rows:O,why:C})),v=(n.heldBack??[]).map(({objectApiName:k,rows:O,parent:C,field:E,parents:F})=>({objectApiName:k,rows:O,parent:C,field:E,...F!==void 0?{parents:F.map(x=>({...x}))}:{}})),j=p?.gate,D=s===0?P.length>0?"refused":"writes":o.verdict==="exceeds"||b.verdict==="exceeds"||l!==void 0||c?.refusal!==void 0?"refused":I!==void 0||P.length>0||t.totalRows>0&&o.verdict!=="fits"||a.some(k=>k.verdict!=="fits")||d!==void 0||c!==void 0||j?.verdict==="asks"?"asks":"writes";return{check:{objects:r,total:s,alreadyCopied:n.alreadyCopied,...(n.alreadyLinked??0)>0?{alreadyLinked:n.alreadyLinked}:{},...i>0?{overwrites:i}:{},...(n.rolesByThePlatform??0)>0?{rolesByThePlatform:n.rolesByThePlatform}:{},...(n.rolesLinked??0)>0?{rolesLinked:n.rolesLinked}:{},...I!==void 0?{aboveRecords:I}:{},storage:o.verdict==="unread"?{verdict:"unread",estimateMB:o.estimateMB,unread:o.unread}:t.totalRows===0?{verdict:"fits",estimateMB:0}:{verdict:o.verdict,estimateMB:o.estimateMB,maxMB:o.maxMB,remainingMB:o.remainingMB},emails:a.map(k=>({limit:k.limit,emails:k.emails,verdict:k.verdict,...k.remaining!==void 0?{remaining:k.remaining}:{},...k.max!==void 0?{max:k.max}:{},...k.alertsCounted?{alertsCounted:!0}:{},objects:k.objects.map(({objectApiName:O,perRecord:C})=>({objectApiName:O,perRecord:C})),...k.unread!==void 0?{unread:k.unread}:{}})),...d!==void 0?{emailsUnread:d}:{},...j?.deliverability?{deliverability:j.deliverability}:{},...P.length>0?{unwritable:P}:{},...v.length>0?{heldBack:v}:{},...s>0?{apiRequests:b.verdict==="unread"?{verdict:"unread",estimate:b.estimate,unread:b.unread}:{verdict:b.verdict,estimate:b.estimate,remaining:b.remaining,max:b.max}}:{},verdict:D,...l!==void 0?{checkpointUnread:l}:{}},plan:t,storage:o,emails:a,api:b,...c!==void 0?{checkpoint:c}:{},...l!==void 0?{checkpointFailed:l}:{},...p!==void 0?{runEmails:p}:{},emailsAccepted:e.emails.accepted}}function Ns(n,e){let{check:t,storage:r,emails:s,plan:i,api:o}=n,a=[],d=t.unwritable??[];if(d.length>0&&(e.policy!=="ask"||t.total===0)&&a.push({code:"SYNC_TARGET_UNWRITABLE",message:Ls(d,e.org,t.heldBack)}),t.total===0)return a;if(n.checkpointFailed!==void 0)a.push({code:Ht,message:n.checkpointFailed});else{let c=ue(n.checkpoint);c&&a.push(c)}i.totalRows>0&&r.verdict==="exceeds"&&a.push({code:"SYNC_STORAGE_EXCEEDED",message:`The records to write take about ${rn(r.estimateMB)} MB of data storage, and ${e.org} has ${r.remainingMB} MB left of ${r.maxMB} MB: leave objects out, narrow their filters, or free data storage in ${e.org}. Nothing was written.`});let u=de(o,e.org);if(u&&a.push({code:qt,message:u}),e.policy!=="ask"){let c=Zt(s,e.org);c&&a.push({code:"SYNC_EMAILS_EXCEEDED",message:`${c} Nothing was written.`});let l=n.runEmails?.gate,p=l?.stop;p&&a.push({code:p.code,message:xe(p.message,"sync",e.emailsLiftedBy),...z(l,!1)})}return a}async function $s(n,e){let{check:t,storage:r,emails:s,api:i}=n,[o]=Ns(n,e);if(o)return{go:!1,...o};if(t.total===0)return{go:!0,asked:!1};let a=n.runEmails?.gate;if(e.policy!=="ask")return{go:!0,asked:!1,...z(a,n.emailsAccepted)};let d=t.unwritable??[];if(t.verdict==="writes")return{go:!0,asked:!1,...z(a,!1)};let u=Pt(e.orgTier),c=s.filter(g=>g.verdict==="exceeds").map(Vt),l=s.filter(g=>g.verdict==="unread").map(Xt),p=e.confirm?await e.confirm({stage:"write",module:"sync",org:e.org,orgTier:e.orgTier,objects:t.objects,total:t.total,...t.aboveRecords!==void 0?{aboveRecords:t.aboveRecords}:{},...u!==void 0&&t.total>u?{largeVolume:u}:{},storage:nn(r),counted:!0,...t.overwrites!==void 0?{overwrites:t.overwrites}:{},...c.length>0?{emails:c}:{},...l.length>0?{emailsUnread:l}:{},...t.emailsUnread!==void 0?{emailsUncounted:t.emailsUnread}:{},...t.alreadyCopied>0?{alreadyCopied:t.alreadyCopied}:{},...(t.alreadyLinked??0)>0?{alreadyLinked:t.alreadyLinked}:{},...(t.rolesLinked??0)>0?{rolesLinked:t.rolesLinked}:{},...d.length>0?{unwritable:d}:{},...t.heldBack!==void 0&&t.heldBack.length>0?{heldBack:t.heldBack}:{},...Kt(i),...n.checkpoint!==void 0?{checkpoint:n.checkpoint}:{},...a?.confirmation}):"unavailable";if(p==="confirmed")return{go:!0,asked:!0,...z(a,a?.verdict==="asks")};let f=z(a,!1);return p==="declined"?{go:!1,code:"SYNC_WRITE_DECLINED",message:"The sync was cancelled before it wrote anything. Nothing was written.",...f}:{go:!1,code:"SYNC_CONFIRMATION_UNAVAILABLE",message:"The sync needed a confirmation before it wrote, and there was no one to ask. Nothing was written.",...f}}var Bs={notInTarget:n=>`${n} has no such object, or the user the run writes as cannot see it`,notCreateable:n=>`the user the run writes as may not create its records in ${n}`,notUpdateable:n=>`the user the run writes as may not edit its records in ${n}`,unread:n=>`${n} did not describe it, so what it takes could not be told`,notAKey:(n,e)=>`its upsert matches on ${e??"a field"}, neither an External ID nor an idLookup field in ${n}`};function Ls(n,e,t=[]){let r=n.map(({objectApiName:h,rows:w,why:A,key:R})=>`${h} (${w} record${w===1?"":"s"}): ${Bs[A](e,R)}`).join("; "),s=n.length===1?"it":"them",i=n.filter(({why:h})=>h==="notAKey"),o=n.filter(({why:h})=>h!=="notAKey"),a=i.length>0&&o.length>0,d=h=>h.map(({objectApiName:w})=>w).join(" and "),u=`give the user SandForge writes as access to ${a?d(o):s} in ${e}`,c=`match ${a?`${d(i)} `:""}on an External ID field of ${e}`,l=a?`${u}, or ${c}`:i.length>0?`or ${c}`:`or ${u}`,p=new Set(n.map(({objectApiName:h})=>h)),f=({parent:h,field:w})=>`whose ${w} names ${/^[aeiou]/i.test(h)?"an":"a"} ${h} record `+(p.has(h)?"left out":"held back"),g=t.flatMap(({objectApiName:h,rows:w,parent:A,field:R,parents:y})=>(y??[{parent:A,field:R,rows:w}]).map(S=>`${S.rows} ${h} record${S.rows===1?"":"s"}, ${f(S)}`)).join("; ");return`${e} would take no record of ${n.length===1?"one object":`${n.length} objects`} the sync writes \u2014 ${r}.`+(g!==""?` Left out, ${s==="it"?"it holds":"they hold"} back ${g}.`:"")+` Leave ${s} out of the run, ${l}. Nothing was written.`}function Bo(n,e){return{measure:async t=>(await tr(t,n)).check,hold:async t=>{let r=await tr(t,n),s=await $s(r,e);return{check:r.check,answer:await _s(r,s,n.checkpointFirst)}}}}async function _s(n,e,t){let r=n.checkpoint;if(!e.go||r===void 0||t===void 0)return e;let s=await Jt(()=>t.take(r));return"stop"in s?{go:!1,...s.stop}:{...e,checkpoint:s.checkpoint}}function Lo(n,e){return e==="insert"||e==="update"||e==="delete"}function _o(n,e,t,r,s){let i,o,a,d,u=n(async l=>{let p=i?.automation;return p&&l.every(f=>p.objectsRead.includes(f))?ir(p,l):e(l)},()=>i?.plan),c=l=>{if(!Tt(l))throw l;return{go:!1,code:l.code,message:l.message}};return{gate:{measure:l=>u.measure(l),hold:async l=>{let p=l.objects.filter(g=>g.rows>0).map(g=>g.objectApiName);if(!i&&p.length>0){d=await e(p).catch(g=>({unread:g instanceof Error?g.message:String(g)}));try{i=await t(d),a=i.muted}catch(g){return{check:await u.measure(l),answer:c(g)}}}let f=await u.hold(l);if(f.answer.go&&i?.prepared&&!o){try{o=await i.prepared.acquire(r),a=o.outcome}catch(y){let{checkpoint:S}=f.answer;return{check:f.check,answer:{...c(y),...S?{checkpoint:S}:{}}}}let{checkpoint:g,emails:h}=f.answer,{deliverability:w}=f.check,A=sr(l),R=i.plan&&d&&"objects"in d?tn({planned:w?.senders??[],held:st(Oe(d,Ft(i.plan,o.outcome),A),{writes:A}),...w?{reading:w.reading}:{},accepted:h?.accepted===!0,target:s.target,run:"sync"}):void 0;if(R)return{check:f.check,answer:{go:!1,code:R.code,message:xe(R.message,"sync",s.liftedBy),...g?{checkpoint:g}:{},...h?{emails:h}:{}}}}return f}},release:async()=>(o&&(a=await o.release()),a),lease:()=>{let l=o;if(l)return{assigned:l.outcome.assigned.length,giveBack:async()=>(a=await l.release(),a)}}}}function Uo(n,e){if(n.operation==="delete")return[];let t=ct(n.fieldMappings,n.excludedFields??[]),r=new Set([...dt(n.fieldMappings),...n.addOnFields.map(i=>i.fieldApiName.toLowerCase())]),s=i=>!t.has(i.toLowerCase())||r.has(i.toLowerCase());return(e.fields??[]).flatMap(i=>i.isReference&&i.createable&&i.name!=="RecordTypeId"&&(i.referenceTo?.length??0)>0&&s(i.name)?[{field:i.name,referenceTo:i.referenceTo??[]}]:[])}function zo(n,e){let t=[...n].sort((y,S)=>y.insertOrder-S.insertOrder),r=new Map(t.map((y,S)=>[y.objectApiName,S])),s=new Set(t.filter(y=>y.operation!=="delete").map(y=>y.objectApiName)),i=new Map([...s].map(y=>[y.toLowerCase(),y])),o=[],a=new Set;for(let y of t){let S=y.objectApiName;if(s.has(S))for(let{field:m,referenceTo:b}of e.get(S)??[])for(let T of b){let I=i.get(T.toLowerCase());if(I===void 0||I===S)continue;let P=`${I}>${S}`;a.has(P)||(a.add(P),o.push({parent:I,child:S,field:m}))}}let d=Ws(t.map(y=>y.objectApiName),o),u=new Map;d.forEach((y,S)=>{for(let m of y)u.set(m,S)});let c=d.map(y=>[...y].sort((S,m)=>(r.get(S)??0)-(r.get(m)??0))),l=c.map(y=>r.get(y[0])??0),p=c.map(()=>new Set);for(let{parent:y,child:S}of o){let m=u.get(y)??0,b=u.get(S)??0;m!==b&&p[b].add(m)}let f=new Set,g=[];for(;f.size<c.length;){let y;if(c.forEach((S,m)=>{f.has(m)||[...p[m]].some(b=>!f.has(b))||(y===void 0||l[m]<l[y])&&(y=m)}),y===void 0)break;f.add(y),g.push(...c[y])}let h=new Map(t.map(y=>[y.objectApiName,y])),w=g.flatMap(y=>{let S=h.get(y);return S?[S]:[]}),A=new Map(g.map((y,S)=>[y,S])),R=[];for(let y of w){let S=y.objectApiName,m=o.filter(b=>b.child===S&&(r.get(b.parent)??0)>(r.get(S)??0)&&(A.get(b.parent)??0)<(A.get(S)??0)).sort((b,T)=>(A.get(T.parent)??0)-(A.get(b.parent)??0));m.length>0&&R.push({objectApiName:S,after:m[0].parent,field:m[0].field})}return{ordered:w,order:{objects:g,moved:R,cycles:c.filter(y=>y.length>1)}}}function Ws(n,e){let t=new Map(n.map(c=>[c,[]]));for(let{parent:c,child:l}of e)t.get(c)?.push(l);let r=0,s=new Map,i=new Map,o=[],a=new Set,d=[],u=c=>{s.set(c,r),i.set(c,r),r++,o.push(c),a.add(c);for(let f of t.get(c)??[])s.has(f)?a.has(f)&&i.set(c,Math.min(i.get(c)??0,s.get(f)??0)):(u(f),i.set(c,Math.min(i.get(c)??0,i.get(f)??0)));if(i.get(c)!==s.get(c))return;let l=[],p;do{if(p=o.pop(),p===void 0)break;a.delete(p),l.push(p)}while(p!==c);d.push(l)};for(let c of n)s.has(c)||u(c);return d}export{pe as a,ye as b,Js as c,Ys as d,ai as e,W as f,di as g,ci as h,ui as i,li as j,Dn as k,Cr as l,Ri as m,ki as n,Ti as o,xi as p,Di as q,vi as r,xr as s,Dr as t,ji as u,Nr as v,Ni as w,$i as x,$r as y,_e as z,$n as A,Uo as B,zo as C,Ur as D,Yi as E,Ln as F,Gn as G,Qn as H,ws as I,mo as J,ho as K,be as L,He as M,yo as N,Rs as O,So as P,bo as Q,Ro as R,$o as S,tr as T,Ns as U,$s as V,Ls as W,Bo as X,_s as Y,Lo as Z,_o as _};
|
|
@@ -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{c as R}from"./chunk-K2FBZIXY.mjs";import{b as S}from"./chunk-T63U4OZJ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as m,e as h,k as y,l as b}from"./chunk-7EANH5PY.mjs";var G={kind:"master"};function E(i){return i.available&&i.active&&!i.master}function B(i){let t=i.find(n=>n.defaultRecordTypeMapping);if(t&&E(t))return{kind:"given",info:t,basis:"userDefault"};let e=i.filter(E);return e.length===1?{kind:"given",info:e[0],basis:"onlyOneOpen"}:G}function ie(i){if(i.kind!=="master")return{developerName:i.info.developerName,label:i.info.name,basis:i.basis}}var L=200,j=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/;function se(i,t){let e=t.filter(n=>j.test(n)).slice(0,L).map(n=>`'${n}'`);return`SELECT RecordTypeId, COUNT(Id) n FROM ${N(i)} WHERE Id IN (${e.join(", ")}) GROUP BY RecordTypeId`}var U=b({RecordTypeId:m().nullish(),n:h().int().nonnegative()});function oe(i,t){let e=y(U).safeParse(i);if(!e.success)return{read:0,types:[],unread:"the org answered rows that name no record type count"};let n=new Map;for(let{RecordTypeId:s,n:o}of e.data){let a=K(s??null,t),d=n.get(a.developerName);d?d.rows+=o:n.set(a.developerName,{...a,rows:o})}let r=[...n.values()].sort((s,o)=>o.rows-s.rows);return{read:r.reduce((s,o)=>s+o.rows,0),types:r}}function K(i,t){if(i===null||R(i)){let n=t.find(r=>r.master);return{developerName:n?.developerName??"Master",label:n?.name??"Master"}}let e=t.find(n=>n.recordTypeId.slice(0,15)===i.slice(0,15));return e?{developerName:e.developerName,label:e.name}:{developerName:i,label:i}}function ae(i){if(!i)return;let t=B(i);return t.kind==="given"?t.info.recordTypeId:i.find(e=>e.master)?.recordTypeId}import{createHash as w,createHmac as T}from"node:crypto";var p="SANDFORGE_FROZEN_SALT",le=["keep","clear","firstName","lastName","companyName","phoneE164","email","registrationSIV","contractNumber","postalCodeGeneralize","dateMonthStart","dateShift","geoRound1","kmRound10"],g=class extends Error{constructor(){super(`No pseudonymization salt. In VS Code, the first extraction makes one and keeps it in the editor's secret storage, which could not keep it here. On the command line, give it with --salt-file <file>, or set ${p} (bash or zsh: export ${p}="<salt>"; PowerShell: $env:${p} = "<salt>") and start VS Code from that shell. Use the salt the dataset was built with: another one gives the same records other pseudonyms.`),this.name="MissingSaltError"}},V=["Alix","Camille","Dominique","\xC9loi","Faustine","Gabin","H\xE9lo\xEFse","Ibrahim","Jasmine","Kylian","L\xE9a","Mathis","Nour","Oc\xE9ane","Paul","Quitterie","Rayan","Salom\xE9","Th\xE9o","Ursule","Victor","Wendy","Xavier","Yasmine","Zacharie","Ambre","Bastien","Chlo\xE9","Dorian","Emma","Fabien","Gabrielle","Hugo","In\xE8s","Jules","Klara","Louis","Manon","No\xE9","Oph\xE9lie"],H=["Arnaud","Berthelot","Chevallier","Deschamps","Etcheverry","Fontaine","Guibert","Hamonic","Imbert","Jacquin","Kermarrec","Lefebvre","Mignard","Noirot","Ollivier","Perrin","Quentin","Rochefort","Seguin","Thibault","Uberti","Vasseur","Wagner","Xuereb","Yverneau","Zimmermann","Aubry","Barbier","Charpentier","Delattre","Esnault","Fournier","Gosselin","Hervieux","Leloup","Marchand","Navarro","Pasquier","Renard","Sauvage"],k=["Aster","Boreal","C\xE9drat","Delta","Ellipse","Fulmen","Granit","Halcyon","Isatis","Jaspe","Kelvin","Lumen","M\xE9ridien","Noroit","Obsidienne","Pulsar"],$=["Conseil","Services","Industries","Solutions","Groupe","SAS","Partenaires","Logistique"],v="ABCDEFGHJKLMNPRSTUVWXYZ",A=/^(\d{4})-(\d{2})-(\d{2})$/,x=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/;function Z(i){return Date.parse(i.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"))}var C=864e5,u=class{salt;constructor(t){if(!t)throw new g;this.salt=t}get saltFingerprint(){return w("sha256").update(this.salt).digest("hex").slice(0,12)}get dateShiftDays(){return 200+w("sha256").update(`${this.salt}|dateShift-offset`).digest().readUInt32BE(0)%201}pseudonymize(t,e){if(e==null)return e;switch(t){case"keep":return e;case"clear":return"";case"firstName":return this.pick(t,String(e),V);case"lastName":return this.pick(t,String(e),H);case"companyName":return this.companyName(String(e));case"phoneE164":return this.phoneE164(String(e));case"email":return this.email(String(e));case"registrationSIV":return this.registrationSIV(String(e));case"contractNumber":return this.contractNumber(String(e));case"postalCodeGeneralize":return this.postalCodeGeneralize(String(e));case"dateMonthStart":return this.dateMonthStart(String(e));case"dateShift":return this.dateShift(e);case"geoRound1":return this.roundNumber(e,1);case"kmRound10":return this.roundTo(e,10)}}digest(t,e){return T("sha256",this.salt).update(`${t}|${e}`).digest()}*bytes(t,e){let n=this.digest(t,e),r=0;for(;;){for(let s of n)yield s;r+=1,n=T("sha256",this.salt).update(`${t}|${e}|#${r}`).digest()}}pick(t,e,n){let r=this.digest(t,e);return n[r.readUInt32BE(0)%n.length]}companyName(t){let e=this.digest("companyName",t),n=k[e.readUInt32BE(0)%k.length],r=$[e.readUInt32BE(4)%$.length];return`${n} ${r}`}phoneE164(t){let e=this.bytes("phoneE164",t),n="";for(let r=0;r<4;r++)n+=String(e.next().value%10);return`+3363998${n}`}email(t){return`user-${this.digest("email",t).subarray(0,4).toString("hex")}@example.invalid`}registrationSIV(t){let e=this.bytes("registrationSIV",t),n=()=>v[e.next().value%v.length],r=()=>String(e.next().value%10);return`${n()}${n()}-${r()}${r()}${r()}-${n()}${n()}`}contractNumber(t){let e=this.bytes("contractNumber",t),n="";for(let r of t)r>="0"&&r<="9"?n+=String(e.next().value%10):r>="A"&&r<="Z"?n+=String.fromCharCode(65+e.next().value%26):r>="a"&&r<="z"?n+=String.fromCharCode(97+e.next().value%26):n+=r;return n}postalCodeGeneralize(t){let e=t.trim();if(e.length<=2)return e;if(/^\d+$/.test(e))return e.slice(0,2)+"0".repeat(e.length-2);let n=e.slice(0,2);for(let r of e.slice(2))r>="0"&&r<="9"?n+="0":r>="A"&&r<="Z"||r>="a"&&r<="z"?n+="X":n+=r;return n}dateMonthStart(t){let e=A.exec(t)??x.exec(t);return e?`${e[1]}-${e[2]}-01`:""}dateShift(t){if(typeof t=="string"&&A.test(t))return new Date(Date.parse(`${t}T00:00:00Z`)-this.dateShiftDays*C).toISOString().slice(0,10);if(typeof t=="string"&&x.test(t)){let e=Z(t);if(Number.isFinite(e))return new Date(e-this.dateShiftDays*C).toISOString()}return""}roundNumber(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=10**e,s=Math.round(n*r)/r;return typeof t=="number"?s:String(s)}roundTo(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=Math.round(n/e)*e;return typeof t=="number"?r:String(r)}};import{createHash as Y,randomBytes as X}from"node:crypto";var z=80,W=40,D=1e4,q=64,I=".invalid",f=/\.invalid$/i,F=/[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g,J=/\+?(?<!\d)\d(?:[\s.()/-]{0,2}\d){6,}/g;function _(i){return/^(?:(?:00)?330?|0)63998\d{4}$/.test(i.replace(/\D/g,""))}function M(i){return`+3363998${i.replace(/\D/g,"").slice(-4)}`}var Q=/^[\d\s.()/+-]+$/;function O(i,t){if(!Q.test(i))return null;let e=t.slice(3),n=/^[\s(]*\+/.test(i)?[`33${e}`,`330${e}`]:[`0${e}`,`33${e}`,`330${e}`,`0033${e}`,`00330${e}`],r=i.replace(/\D/g,"").length,s=n.find(a=>a.length===r);if(s===void 0)return null;let o=0;return i.replace(/\d/g,()=>s[o++])}function ee(i,t={}){let e=[];for(let n of i){let r=(n.type??"").toLowerCase(),s=S(n.name,r);if(!s)continue;let o=r==="email"||r==="phone",a=r==="email"?z:r==="phone"?W:0,d=n.length!==void 0&&n.length>0?n.length:a;e.push({name:t[n.name]??n.name,kind:s,typed:o,...d>0?{maxLength:d}:{},...n.externalId===!0?{key:!0}:{}})}return e}var P=class{pseudonymizer;upsertKeys;drawnFor=new Map;taken=new Set;exhausted=0;counted=new Map;constructor(t=X(32).toString("hex"),e={}){this.pseudonymizer=new u(t),this.upsertKeys=e.upsertKeys===!0}forObject(t,e,n={}){let r=ee(e,n);if(r.length!==0)return s=>{for(let o of r){let a=s[o.name];if(typeof a!="string")continue;let d=this.neutralize(o,a);d!==a&&(d===null?delete s[o.name]:s[o.name]=d,this.count(t,o))}}}email(t,e=z,n=!1){let r=t.trim();if(r===""||f.test(r))return t;let s=`${r}${I}`;if(s.length<=e)return s;let o=this.shortAddress(r,n);return o.length<=e?o:null}phone(t,e){return/\d/.test(t)?_(t)?(this.taken.add(M(t)),t):this.fictional(t,e):t}report(){let t=[],e=0;for(let[n,r]of this.counted)for(let[s,{kind:o,values:a}]of r)t.push({objectApiName:n,field:s,kind:o,values:a}),e+=a;return{neutralized:!0,fields:t,values:e,...this.exhausted>0?{numbersExhausted:this.exhausted}:{}}}neutralize(t,e){let n=this.upsertKeys&&t.key===!0;return t.typed?t.kind==="email"?this.email(e,t.maxLength,n):this.phone(e,t.maxLength):t.kind==="email"?this.addressesIn(e,t.maxLength,n):this.numbersIn(e,t.maxLength)}addressesIn(t,e,n=!1){let r=a=>e===void 0||a.length<=e,s=t.replace(F,a=>f.test(a)?a:`${a}${I}`);if(s===t||r(s))return s;let o=t.replace(F,a=>f.test(a)?a:this.shortAddress(a,n));return r(o)?o:null}numbersIn(t,e){let n=d=>e===void 0||d.length<=e,r=!1,s=d=>t.replace(J,c=>{if(_(c))return this.taken.add(M(c)),c;let l=this.drawnNumber(c);return l===null?(r=!0,c):O(c,l)??(d?`0${l.slice(3)}`:l)}),o=s(!1);if(r)return null;if(o===t||n(o))return o;let a=s(!0);return n(a)?a:null}fictional(t,e){let n=this.drawnNumber(t);if(n===null)return null;let r=O(t,n);if(r!==null&&(e===void 0||r.length<=e))return r;if(e===void 0||n.length<=e)return n;let s=`0${n.slice(3)}`;return s.length<=e?s:null}drawnNumber(t){let e=t.replace(/[^\d+]/g,""),n=this.drawnFor.get(e);if(n!==void 0)return n;if(this.taken.size>=D)return this.exhausted+=1,null;let r=o=>String(this.pseudonymizer.pseudonymize("phoneE164",o)),s=r(e);for(let o=1;this.taken.has(s)&&o<=q;o+=1)s=r(`${e}#${o}`);for(let o=Number(s.slice(-4));this.taken.has(s);)o=(o+1)%D,s=`+3363998${String(o).padStart(4,"0")}`;return this.drawnFor.set(e,s),this.taken.add(s),s}shortAddress(t,e=!1){let n=t.toLowerCase();return e?`user-${Y("sha256").update(n).digest("hex").slice(0,16)}@example.invalid`:String(this.pseudonymizer.pseudonymize("email",n))}count(t,e){let n=this.counted.get(t)??new Map,r=n.get(e.name)??{kind:e.kind,values:0};r.values+=1,n.set(e.name,r),this.counted.set(t,n)}};function Se(i){if(typeof i!="object"||i===null)return!1;let{errorCode:t,name:e}=i;return t==="NOT_FOUND"||e==="NOT_FOUND"}export{p as a,le as b,g as c,u as d,z as e,D as f,ee as g,P as h,B as i,ie as j,L as k,se as l,oe as m,ae as n,Se as o};
|
|
@@ -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 as je,b as xe,c as Pe,d as _e,e as _,f as $e,g as Me,h as J,i as re}from"./chunk-3F5YMM2F.mjs";import{a as Oe}from"./chunk-YYZL7UGV.mjs";import{a as we,f as ke,i as ve,j as Ie,l as ne}from"./chunk-SAR5622P.mjs";import{a as E}from"./chunk-4TLYUZD5.mjs";import{c as Le}from"./chunk-HF6LAK3G.mjs";import{a as P,b as Fe,d as Ce,e as We,f as te,h as Ne,i as Ee,j as Se}from"./chunk-PNCONNFJ.mjs";import{X as fe,Y as he,Z as pe,a as Q,aa as ge,ba as me,d as Z,ea as ye,ga as Re,ha as be}from"./chunk-CGWXQX75.mjs";import{d as Ae,e as ee,f as Te,k as Be}from"./chunk-SIOZXPFG.mjs";import{b as I}from"./chunk-CA5NAXSU.mjs";import{Ob as ue,nc as ce,tb as X}from"./chunk-B45CNPUX.mjs";var q=class{config;constructor(e){this.config={maxRetries:e?.maxRetries??3,initialDelay:e?.initialDelay??1e3,maxDelay:e?.maxDelay??3e4,backoffMultiplier:e?.backoffMultiplier??2,jitter:e?.jitter??!0}}calculateDelay(e){let t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),n=Math.min(t,this.config.maxDelay);if(!this.config.jitter)return n;let s=n/2;return Math.floor(s+Math.random()*s)}async execute(e){let t,n=0;for(let s=0;s<=this.config.maxRetries;s++)try{return{success:!0,result:await e(),attempts:s+1,totalDelay:n}}catch(r){if(t=r instanceof Error?r:new Error(String(r)),s<this.config.maxRetries){let o=this.calculateDelay(s);n+=o,await new Promise(i=>setTimeout(i,o))}}return{success:!1,error:t,attempts:this.config.maxRetries+1,totalDelay:n}}shouldRetry(e){return e<this.config.maxRetries}getConfig(){return{...this.config}}};function Ye(a){return Array.isArray(a)?a.length:(a.successfulResults?.length??0)+(a.failedResults?.length??0)}function De(a,e){let t=!1,n=!1,s,r={},o=0,i=0,d=(c,p)=>(i+=c,e?.(c),p()),l=async c=>{let p=await d(Ee,c);return o=Ye(p),p},u={createJob:c=>{let p=a.bulk2.createJob(c);return{get id(){return p.id},open:async()=>{await d(1,()=>p.open()),s=We(p)},uploadData:w=>d(1,()=>p.uploadData(w)),close:async()=>{t=!0,await d(1,()=>p.close()),n=!0},abort:()=>d(1,()=>p.abort()),check:async()=>{let w=await d(1,()=>p.check());return r={state:w.state,message:w.errorMessage},w},getAllResults:()=>l(()=>p.getAllResults())}}};if("job"in a.bulk2){let c=a.bulk2;u.job=(p,w)=>{let R=c.job(p,w);return{check:async()=>{let m=await d(1,()=>R.check());return r={state:m.state,message:m.errorMessage??void 0},m},getSuccessfulResults:()=>d(1,()=>R.getSuccessfulResults()),getAllResults:()=>l(()=>R.getAllResults()),abort:()=>d(1,()=>R.abort())}}}return{connection:{bulk2:u},closeSent:()=>t,closed:()=>n,jobId:()=>s,last:()=>r,processed:()=>o,requests:()=>i}}var L=class extends Error{constructor(t,n,s=0,r=[]){super(`Bulk API job ${t||"(no id)"} was closed, and what it wrote could not be read back: ${n}`);this.jobId=t;this.requests=s;this.twins=r;this.name="BulkJobLostError"}jobId;requests;twins},M=1e4,H=50*1024*1024,Xe=10,Qe=/not supported by the Bulk API|InvalidEntity/i,Ze={unprocessed:"The Bulk API job did not write this row.",twin:"Kept out of the Bulk API job: another row carries the same values, and the job's results could not tell them apart.","may-have-written":"The Bulk API job may have written this row without saying so: it is not sent again."};async function _t(a,e,t,n,s,r={}){let o=n==="insert"?s.map(nt):s,i=Fe(P(n,o,r.externalIdField)),d=[];o.forEach((k,A)=>{i.has(A)||d.push(A)});let l=d.map(k=>o[k]),u=o.map((k,A)=>i.has(A)?"twin":"unprocessed"),c=k=>({answers:u.map(A=>$(A==="twin"?"twin":"unprocessed")),rows:u,unmatchedIds:[],...k});if(l.length===0)return c({requests:0});let p=P(n,l,r.externalIdField),w=Buffer.byteLength(p.text,"utf8");if(l.length>M||w>H)return c({requests:0,untouched:{reason:`${l.length} rows, ${w} bytes of CSV: past what one job takes (${M} rows, ${H} bytes)`}});let R=(k,A,h,v)=>{let B={requests:k.requests,...k.jobId?{jobId:k.jobId}:{}};if(k.info.state!=="JobComplete"&&k.processed===0&&v===0)return c({...B,untouched:se(te(k.info)??"job not complete")});let N=new Map(A.map(y=>[y.recordIndex,y])),f=u.map(y=>$(y==="twin"?"twin":"unprocessed"));return d.forEach((y,S)=>{let W=tt(N.get(S),v>0);u[y]=W.state,f[y]=W.answer}),{answers:f,rows:u,unmatchedIds:[...h],...B}},m=De(a),b,T=()=>b?{jobId:b}:{},F=r.pollDelay??Se,g;try{g=await new Ne().executeBulk({connection:m.connection,bulkManager:e,pollIntervalMs:F,...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{},onOpened:k=>{b=k,r.onOpened?.(k)}},t,n,l,r.externalIdField)}catch(k){let A=I(k);if(!m.closeSent())return c({requests:m.requests(),...T(),untouched:se(A)});if(b===void 0)throw new L("",A,m.requests(),[...i]);let h=await et(m.connection,b,F);if(h.state==="never-closed")return c({requests:m.requests(),jobId:b,untouched:se(A)});if(h.state!=="ended")throw new L(b,h.state==="unread"?h.reason:"still running",m.requests(),[...i]);let v=Ce(h.results,p,te(h.info));return R({info:h.info,processed:m.processed(),requests:m.requests(),jobId:b},v.outcomes,v.unattributedSuccessIds,v.unattributedSuccesses)}if(g.aborted)return c({requests:m.requests(),...T(),aborted:!0});let C=m.last();return R({info:{state:C.state??"JobComplete",...C.message?{errorMessage:C.message}:{}},processed:m.processed(),requests:m.requests(),...T()},g.outcomes,g.unmatchedIds??[],g.unmatchedWrites??0)}async function et(a,e,t){let n=await ne(a,e,{openGraceMs:0});for(let s=1;s<Xe;s++){if(n.state==="ended"||n.state==="never-closed")return n;await new Promise(r=>setTimeout(r,t(s-1))),n=await ne(a,e,{openGraceMs:0})}return n}function se(a){return Qe.test(a)?{reason:a,unsupported:!0}:{reason:a}}function $(a){return{id:"",success:!1,errors:[Ze[a]]}}function tt(a,e){if(a===void 0||a.state==="no-result"){let s=e?"may-have-written":"unprocessed";return{state:s,answer:$(s)}}if(a.state==="unprocessed")return{state:"unprocessed",answer:$("unprocessed")};if(a.success)return a.id?{state:"answered",answer:{id:a.id,success:!0,errors:[],...a.created!==void 0?{created:a.created}:{}}}:{state:"may-have-written",answer:$("may-have-written")};let t=a.error??"Unknown error",n=Ae(t);return{state:"answered",answer:n?{id:"",success:!1,errors:[Te(n)],errorDetails:[n]}:{id:"",success:!1,errors:[t]}}}function nt(a){let e;for(let[t,n]of Object.entries(a))n===""&&(e??={...a},e[t]=null);return e??a}var de={rest:200,bulk:1e4},Ue=3,ot=3,Ke="UNABLE_TO_LOCK_ROW",Je=3,it=2e3;function at(a){return new Promise(e=>setTimeout(e,a))}function dt(a,e,t={bulk:!1}){let n=t.bulk&&a.api==="bulk"&&e>=2e3?"bulk":"rest",s=Math.min(a.batchSize,de[n]);return{api:n,batchSize:s,batchCount:Math.ceil(e/s),clamped:s<a.batchSize}}function G(a){return a.refusals.flatMap(e=>e.leftOut)}function oe(a){let e=a.built?.source.Id;return typeof e=="string"?e:void 0}function qe(a){return(a.built?.nullifiedFks??[]).map(({field:e,sourceRefId:t,insertOnly:n})=>({field:e,sourceRefId:t,...n?{insertOnly:n}:{}}))}function lt(a){let e=a.RecordTypeId;return typeof e=="string"&&e!==""}function ie(a){return a.refusals.length===0?a.payload:J(a.payload,G(a))}function He(a,e){let t=new Map;return e?.refusedIn?.answers.forEach((n,s)=>{let r=a[s];n&&r&&t.set(r,n.errors)}),t}var ut=new Set,ct=new Map;function V(a){return{objectApiName:a.objectApiName,op:a.upsertField?"upsert":"insert"}}function Ve(a){return a!==void 0&&!a.success?ce(a.errors):void 0}function ft(a){let e=a.automation??"the target's automation";E.warn(`[forge] ${a.objectApiName}: ${e} hit ${a.limit??"a Salesforce limit"} on a call of ${a.from} \u2014 sending a record on its own, then smaller calls`+(a.op==="upsert"?" (upsert).":"."))}var z={"validation-rule":"a validation rule","restricted-picklist":"a restricted picklist","lookup-filter":"a lookup filter","inactive-owner":"the target, the owner being inactive there"};function ht(a){let e=new Set(a.map(o=>o.refusedBy)),t=Object.keys(z).filter(o=>o!=="inactive-owner"&&e.has(o)).map(o=>z[o]),n=t.length>1?`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`:t[0],s=n===void 0?void 0:`${n} of the target`;if(!e.has("inactive-owner"))return s??`${z["validation-rule"]} of the target`;let r=`${z["inactive-owner"]},`;return s===void 0?r:`${s} or ${r}`}function ae(a,e){if(!a.ownersMapped||a.ownersMapped.size===0)return!1;let t=_(e,"OwnerId"),n=t===void 0?void 0:e[t];return typeof n=="string"&&a.ownersMapped.has(n.slice(0,15))}function pt(a,e,t,n,s){let r=a.errorDetails??[];if(r.length===a.errors.length)return $e(r,e,t,n,s)}function ze(a){a.linkedToCreatedCount=(a.linkedToCreatedCount??0)+1}function gt(a){let e=a.errorDetails??[];return e.length>0&&e.length===a.errors.length?e.every(t=>t.statusCode===Ke):a.errors.length>0&&a.errors.every(t=>t.startsWith(Ke))}function Y(a){return a.map(e=>e.field).join(", ")}function mt(a,e){return`Sent again without ${Y(a)} after the first refusal: ${e.join("; ")}`}var yt=["first","second","third"];function D(a){return a.map(({leftOut:e,errors:t},n)=>n===0?mt(e,t):`Sent again without ${Y(e)} too after the ${yt[n]} refusal: `+t.join("; "))}function U(a){let e=(t,n)=>t.length===0?[]:[`Sent without ${Y(t)}: ${n} earlier in the run, `+[...new Set(t.map(s=>s.reason))].join("; ")];return[...e(a.filter(t=>t.refusedBy!=="inactive-owner"),"the target refused the same value under the same record type"),...e(a.filter(t=>t.refusedBy==="inactive-owner"),"the target refused the same owner, inactive there,")]}function O(a){return`${a} record${a===1?"":"s"}`}var Rt="The call was sent and its answer never came back: the target may hold any of these records, and which of them is unknown. Counted as failed and never sent again, they are not among the records the run created, which removing its records takes back.",bt="Counted as failed and never sent again, they are not among the records the run created; the records the job wrote that no row was matched to are, and removing the run's records takes them back.",wt="DUPLICATES_DETECTED";function kt(a,e){if(a==="twin"||a==="unprocessed")return!0;if(a!=="answered"||e.success)return!1;let t=e.errorDetails;return t?.length!==1||t[0].statusCode===wt}function vt(a,e){let t=i=>i.reduce((d,l)=>d+Math.max(Buffer.byteLength(l,"utf8"),4)+(l.split('"').length-1)+3,1),n=t(e.columns),s=[],r=0,o=n;return e.rows.forEach((i,d)=>{let l=t(i);d>r&&o+l>a&&(s.push([r,d]),r=d,o=n),o+=l}),e.rows.length>r&&s.push([r,e.rows.length]),s}function It(a,e,t){let n=a.find(r=>r.isReference&&r.nillable===!1&&r.name!=="OwnerId"&&e.has(r.name))?.name;if(n===void 0)return;let s=r=>{let o=t[r][n];return typeof o=="string"?o:""};if(t.some((r,o)=>s(o)!==""))return t.map((r,o)=>o).sort((r,o)=>{let i=s(r),d=s(o);return i===d?r-o:i===""?1:d===""||i<d?-1:1})}var At="The target refused the call for its API request limit, which no retry gets past: the node stopped there.",Tt="A validation rule of the target, or a trigger with its code, refused the row without naming a field: there was none to send it again without.";function Bt(){return{successCount:0,updatedCount:0,linkedExistingCount:0,failureCount:0,alreadyExistsCount:0,unidentifiedExistingCount:0,errorSamples:[],pendingFkUpdates:[]}}var Ge=class{constructor(e,t,n=at,s=we()){this.deps=e;this.wait=n;this.splitting=s;this.batchStrategy=t??new Le}deps;wait;splitting;batchStrategy;refusedValues=new Map;refusedOwners=new Map;backoff=new q({initialDelay:it});async writeNode(e,t=Bt()){let{node:n,fieldInfos:s,creatableFields:r,targetOrgId:o,remapper:i}=e,d=await this.heldBeforeInsert(n.objectApiName,o,e.records);for(let[h,v]of d){let B=e.cleanedRecords[h]?.source,N=B?.Id;if(typeof N!="string")continue;i.addExisting(N,v,n.objectApiName);let f=B?.ContactId;n.objectApiName===Q&&typeof f=="string"&&i.isCreated(f)&&(t.withTheirRecord=[...t.withTheirRecord??[],N])}t.linkedExistingCount+=d.size;let l=await this.giveFlagsBack(n.objectApiName,o,e,d);l&&(t.flagsNotKept=ge(t.flagsNotKept,l));let u=e.records.filter((h,v)=>!d.has(v)),c=e.cleanedRecords.filter((h,v)=>!d.has(v)),p=this.batchStrategy.resolve(n.batchStrategy,u.length),{api:w,batchSize:R,batchCount:m,clamped:b}=dt(p,u.length,{bulk:this.jobsCanCarry(e.bulk,n.objectApiName)});if(b&&E.warn(`[forge] ${n.objectApiName}: batch strategy asked for ${p.batchSize} records per call (api="${p.api}") but the write path is "${w}" (max ${de[w]}) \u2014 using ${R} per call (${m} batch(es)).`),w==="bulk"){let h=It(s,r,u);if(h){let v={records:u,cleanedRecords:c};u=h.map(B=>v.records[B]),c=h.map(B=>v.cleanedRecords[B])}}e.onProgress({objectName:n.objectApiName,status:"running",progress:0,recordCount:u.length,fieldCount:s.length,createableFieldCount:r.size,message:`Inserting ${u.length} ${n.objectApiName} records in ${m} batch(es)...`});let T=0,F=this.pickUpsertField(s,r,u,e.upsertMode==="auto"&&this.deps.upsertRecords?"auto":"off",e.tableKeys),g={objectApiName:n.objectApiName,targetOrgId:o,targetKeyPrefix:e.targetKeyPrefix,remapper:i,tally:t,oweLookups:e.oweLookups,onWritten:e.onWritten,onCreatedWithoutRecordType:e.onCreatedWithoutRecordType,calls:e.calls,bulk:e.bulk,byNaturalKey:[],refusedOnTheirFields:[],locked:[],upsertField:F,ownersMapped:e.ownersMapped,remembered:new Set([...e.picklistFields??[]].filter(([,h])=>h.controllerName===void 0).map(([h])=>h.toLowerCase()))},{byNaturalKey:C}=g,k=h=>{let v=I(h);this.leaveLockedAsFailed(g,g.locked.splice(0),v),this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),v),this.settleByNaturalKey(n.objectApiName,C,[],i,t,`The record the target holds under the same key was not looked up: ${v}`)};for(let h=0;h<m;h++){let v=u.slice(h*R,(h+1)*R).map((y,S)=>{let{sent:W,before:x}=this.withoutRefusedValues(g,y);return{payload:W,built:c[T+S],before:x,refusals:[],lockResends:0}}),B=`${n.objectApiName} batch ${h+1}/${m}`,N;try{N=await this.sendRows(g,e,v,B,u.length-T-v.length)}catch(y){throw k(y),y}if(N){let y=I(N.thrown);this.leaveLockedAsFailed(g,g.locked.splice(0),y),this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),y);break}T+=v.length;let f;try{f=await this.sendLockedAgain(g,e,u.length-T)}catch(y){throw k(y),y}if(f){this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),I(f.thrown));break}e.onProgress({objectName:n.objectApiName,status:"running",progress:Math.round((h+1)/m*100),message:`batch ${h+1}/${m} \u2014 ${Math.min((h+1)*R,u.length)}/${u.length} records`})}try{await this.writeAgainWithoutTheirFields(g,e,Math.min(R,de.rest))}catch(h){throw k(h),h}let A=Z[n.objectApiName];if(A&&C.length>0){let h,v;try{h=await this.recordsByNaturalKey(o,n.objectApiName,A,C.map(B=>B.payload))}catch(B){h=[],v=`The record the target holds under the same key could not be looked up: ${I(B)}`}this.settleByNaturalKey(n.objectApiName,C,h,i,t,v)}return t}send(e,t){return e.upsertField&&this.deps.upsertRecords?this.deps.upsertRecords(e.targetOrgId,e.objectApiName,e.upsertField,t):this.deps.insertRecords(e.targetOrgId,e.objectApiName,t)}jobsCanCarry(e,t){return e!==void 0&&this.deps.bulkWriteRecords!==void 0&&!e.restOnly.has(t)&&!e.bulkUnsupported.has(t)}goesSmallerByRest(e){return this.splitting.sizes.of(e)<200}async sendRows(e,t,n,s,r,o){let{bulk:i}=e;if(!i||!this.jobsCanCarry(i,e.objectApiName)||n.length<2e3)return this.sendByRest(e,t,n,s,r,o);for(let d=0;d<n.length;d+=M){let l=n.slice(d,d+M),u=n.length-d-l.length+r,c;try{c=l.length>=2e3?await this.writeAsJobs(e,t,i,l,s,u,o):await this.sendByRest(e,t,l,s,u,o)}catch(p){throw o?.(n.slice(d+l.length),I(p)),p}if(c)return c}}async sendByRest(e,t,n,s,r,o,i){if(n.length===0)return;try{await t.waitIfPaused()}catch(l){let u=I(l);throw o?o(n,u):this.leaveLimitedAsFailed(e,n,He(n,i),u),l}let d=await this.callAndSettle(e,t,n,o,i);if(d)return this.settleThrown(e,d.threw,d.rows,s,d.rest.length+r),d.threw}async writeAsJobs(e,t,n,s,r,o,i){let d=this.deps.bulkWriteRecords;if(!d)return this.sendByRest(e,t,s,r,o,i);let l=V(e);if(this.goesSmallerByRest(l))return this.sendJobByRest(e,t,n,s,r,o,i);let u=e.upsertField?"upsert":"insert",c=s.map(ie),p=vt(H,P(u,c,e.upsertField));for(let[w,R]of p){let m=s.slice(w,R),b=s.length-R+o;if(this.goesSmallerByRest(l)){let f;try{f=await this.sendJobByRest(e,t,n,m,r,b,i)}catch(y){throw i?.(s.slice(R),I(y)),y}if(f)return f;continue}try{await t.waitIfPaused()}catch(f){throw i?.(s.slice(w),I(f)),f}let T=c.slice(w,R),F=e.calls?.sending(e.objectApiName,m.map((f,y)=>({sourceId:oe(f),payload:T[y],owes:qe(f)})),e.upsertField,!0),g;try{g=await d(e.targetOrgId,e.objectApiName,u,T,{bulkManager:n.manager,signal:n.signal,...e.upsertField?{externalIdField:e.upsertField}:{},onOpened:f=>{F!==void 0&&e.calls?.opened?.(F,f)}})}catch(f){if(f instanceof L){let y={thrown:f,left:"may-have-written",tries:1},S=new Set(f.twins),W=m.filter((x,le)=>!S.has(le));return this.settleThrown(e,y,W,`${r} (Bulk API job)`,b),this.leaveTwinsUnsent(e,m.length-W.length,r,f),y}g={answers:[],rows:[],unmatchedIds:[],untouched:{reason:I(f)},requests:0}}if(g.aborted){try{await t.waitIfPaused()}catch(f){throw F!==void 0&&e.calls?.answered(F),i?.(s.slice(w),I(f)),f}g={...g,untouched:{reason:"the job was aborted"}}}if(g.untouched){F!==void 0&&e.calls?.answered(F),g.untouched.unsupported&&n.bulkUnsupported.add(e.objectApiName),E.warn(`[forge] ${e.objectApiName}: a Bulk API job of ${O(m.length)} wrote nothing (${g.untouched.reason}) \u2014 sent by REST`+(g.untouched.unsupported?", as every write of the object in the run.":"."));let f;try{f=await this.sendByRest(e,t,m,r,b,i)}catch(y){throw i?.(s.slice(R),I(y)),y}if(f)return f;continue}g.unmatchedIds.length>0&&(e.calls?.unattributed?.(e.objectApiName,g.unmatchedIds),E.warn(`[forge] ${e.objectApiName}: Bulk API job ${g.jobId??""} wrote ${O(g.unmatchedIds.length)} no row was matched to \u2014 kept for removal.`));let C=[],k=[],A=[],h=[],v=[],B=[],N;if(m.forEach((f,y)=>{let S=g.rows[y]??"unprocessed",W=g.answers[y],x=S==="answered"?Ve(W):void 0;S==="may-have-written"?B.push(f):x!==void 0&&W!==void 0?(N??=x,h.push(f),v.push(W)):!W||kt(S,W)?A.push(f):(C.push(f),k.push(W))}),this.settleMayHaveBeenWritten(e,B,r,g.jobId),await this.settleAnswers(e,C,F===void 0?{answers:k}:{answers:k,callId:F}),A.length>0){let f;try{f=await this.sendByRest(e,t,A,`${r}, by REST`,h.length+b,i)}catch(y){throw i?.([...h,...s.slice(R)],I(y)),y}if(f)return f}if(h.length>0){let f;try{f=await this.sendByRest(e,t,h,`${r}, by REST`,b,i,{refusedIn:{from:200,answers:v,...N?{cause:N}:{}}})}catch(y){throw i?.(s.slice(R),I(y)),y}if(f)return f}}}async sendJobByRest(e,t,n,s,r,o,i){let d=V(e),{sizes:l,allowance:u}=this.splitting,c=l.of(d),p=Math.ceil(s.length/c),w=u.take(d,p);l.countExtraCalls(d,w);let R=s.slice(0,w*c),m=s.slice(R.length);if(R.length>0){let b;try{b=await this.sendByRest(e,t,R,r,m.length+o,i,{pricedAs:"job",paid:{calls:w}})}catch(T){throw i?.(m,I(T)),T}finally{w<p&&l.spend(d)}if(b)return b}else w<p&&l.spend(d);if(m.length!==0)return m.length>=2e3?this.writeAsJobs(e,t,n,m,r,o,i):this.sendByRest(e,t,m,r,o,i)}leaveTwinsUnsent(e,t,n,s){t!==0&&(e.tally.failureCount+=t,this.sample(e.tally,{recordSummary:`${n}: ${O(t)} not written`,messages:[I(s),"Kept out of the Bulk API job as twins of other rows, to be written by REST once it answered: never sent, the target holds none of them."]}))}settleMayHaveBeenWritten(e,t,n,s){if(t.length===0)return;let{tally:r}=e;r.failureCount+=t.length;let o=t.map(oe).filter(i=>i!==void 0);r.mayHaveBeenWritten=[...r.mayHaveBeenWritten??[],...o],this.sampleAhead(r,{recordSummary:`${n}: ${O(t.length)} may have been written`,messages:[`Bulk API job ${s??""} gave them no result of their own, and wrote records no row was matched to: the target may hold any of these records, and which of them is unknown.`,bt]})}async call(e,t,n){let s=n.map(ie);for(let r=0;;r++){let o=e.calls?.sending(e.objectApiName,n.map((i,d)=>({sourceId:oe(i),payload:s[d],owes:qe(i)})),e.upsertField);try{let i=await this.send(e,s);return o===void 0?{answers:i}:{answers:i,callId:o}}catch(i){let d=Oe(i);if(o!==void 0&&d!=="may-have-written"&&e.calls?.answered(o),d!=="not-received"||r===Ue)return{thrown:i,left:d,tries:r+1};let l=this.backoff.calculateDelay(r);E.warn(`[forge] ${e.objectApiName}: a call of ${O(s.length)} never reached the target (${I(i)}) \u2014 sent again in ${l} ms (${r+1}/${Ue}).`),await this.wait(l),await t.waitIfPaused()}}}async callAndSettle(e,t,n,s,r){let o,i={answers:[]},d=He(n,r),{stopped:l}=await Ie(n,{key:V(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,...r,beforeEachSend:()=>t.waitIfPaused(),send:async u=>{let c=await this.call(e,t,u);return"thrown"in c?(o=c,"stop"):(i=c,{answers:c.answers})},limited:(u,c)=>{let p=Ve(u);return p&&u&&d.set(c,u.errors),p},settle:(u,c,p,w,R)=>this.settleAnswers(e,u,R?{answers:c}:i,p,w),onThrow:(u,c)=>{let p=I(c);s?s(u,p):this.leaveLimitedAsFailed(e,u,d,p)},onFirstRefusal:ft});if(!(!l||o===void 0))return{threw:o,rows:l.part,rest:l.rest}}sample(e,t){e.errorSamples.length<3&&e.errorSamples.push(t)}sampleAhead(e,t){e.errorSamples.unshift(t),e.errorSamples.splice(3)}async settleAnswers(e,t,{answers:n,callId:s},r=ut,o=ct){t.forEach((i,d)=>{let l=n[d];l?.success&&!r.has(d)&&this.settle(e,l,i)}),e.remapper.persist(),await this.readWhatMayBeEmpty(e,n.filter(i=>i!==void 0)),t.forEach((i,d)=>{if(r.has(d))return;let l=n[d];if(l){l.success||this.settle(e,l,i,o.get(d));return}e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(i.payload),messages:[`No result returned for record (API truncated batch: ${n.length}/${t.length})`,...D(i.refusals),...U(i.before)]})}),e.remapper.persist(),s!==void 0&&e.calls?.answered(s)}async readWhatMayBeEmpty(e,t){if(e.mayBeEmpty!==void 0||!t.some(r=>(r.errorDetails??[]).some(o=>o.statusCode===xe)))return;let s=await this.deps.describeFields?.(e.targetOrgId,e.objectApiName).catch(()=>{});e.mayBeEmpty=new Set((s??[]).filter(r=>r.nillable===!0).map(r=>r.name.toLowerCase()))}settleThrown(e,t,n,s,r){let{tally:o}=e,i=I(t.thrown);if(o.failureCount+=n.length+r,t.left==="may-have-written"){let l=n.map(u=>u.built?.source.Id).filter(u=>typeof u=="string");o.mayHaveBeenWritten=[...o.mayHaveBeenWritten??[],...l],this.sampleAhead(o,{recordSummary:`${s}: ${O(n.length)} may have been written`,messages:[i,Rt,...r>0?[`${O(r)} after them not sent.`]:[]]});return}let d=n.length+r;this.sample(o,{recordSummary:`${s}: ${O(d)} not written`,messages:[i,...t.left==="request-limit"?[At]:[],...t.left==="not-received"?[`Sent ${t.tries} times, the call never reached the target: it holds none of them.`]:[]]})}async sendLockedAgain(e,t,n){for(let s=0;e.locked.length>0;s++){let r=this.backoff.calculateDelay(s);E.warn(`[forge] ${e.objectApiName}: the target could not lock a record for ${O(e.locked.length)} \u2014 sent again in ${r} ms.`),await this.wait(r),await t.waitIfPaused();let o=e.locked.splice(0),i=o.map(({row:u})=>({...u,lockResends:u.lockResends+1})),d=new Map(i.map((u,c)=>[u,o[c]])),l=await this.callAndSettle(e,t,i,(u,c)=>this.leaveLockedAsFailed(e,u.flatMap(p=>d.get(p)??[]),c));if(l)return this.settleThrown(e,l.threw,l.rows,`${e.objectApiName}, sent again`,n+l.rest.length),this.leaveLockedAsFailed(e,e.locked.splice(0),I(l.threw.thrown)),l.threw}}settle(e,t,n,s){let{tally:r,remapper:o,objectApiName:i}=e,{built:d,before:l}=n,u=ie(n);if(t.success){let b=d?.source.Id,T=t.created===!1;if(T?r.updatedCount++:r.successCount++,typeof b=="string"&&(T?o.addUpdated(b,t.id,i):o.add(b,t.id,i)),d&&e.onWritten?.(d,t.id),!T&&!lt(u)&&e.onCreatedWithoutRecordType?.(d,t.id),d&&d.nullifiedFks.length>0){let g=typeof d.source.Id=="string"?d.source.Id:void 0,C=d.nullifiedFks.map(k=>({objectApiName:i,newId:t.id,sourceId:g,fieldName:k.field,sourceRefId:k.sourceRefId,...k.insertOnly?{insertOnly:!0}:{}}));e.oweLookups?e.oweLookups(C):r.pendingFkUpdates.push(...C)}let F=[...l,...G(n)];F.length>0&&(r.writtenWithoutFields=re(r.writtenWithoutFields,{rows:1,fields:F.map(g=>({...g,rows:1}))}));for(let{field:g,refusedBy:C}of F)C!=="lookup-filter"||!t.id||(r.leftEmptyByFilter??=[]).push({field:g,recordId:t.id});return}this.rememberRefusedValues(e,t,u),this.rememberRefusedOwners(e,t,u);let c=Be(t,e.targetKeyPrefix);if(c.kind==="linked"){r.linkedExistingCount++,o.createdTarget(c.id)&&ze(r);let b=d?.source.Id;typeof b=="string"&&o.addExisting(b,c.id,i);return}if(c.kind==="unidentified"&&Z[i]){e.byNaturalKey.push({payload:u,sourceId:d?.source.Id,errors:t.errors});return}let p=gt(t);if(p&&n.lockResends<ot){e.locked.push({row:n,errors:t.errors});return}let w=b=>e.mayBeEmpty?.has(b.toLowerCase())??!1,R=pt(t,u,e.upsertField,w,{inactiveOwner:!ae(e,u)}),m=n.refusals.length<Je;if(R&&m){e.refusedOnTheirFields.push({...n,refusals:[...n.refusals,{errors:t.errors,leftOut:R}]});return}r.failureCount++,c.kind==="unidentified"&&r.unidentifiedExistingCount++,t.errors.every(b=>X(b))&&r.alreadyExistsCount++,this.sample(r,{recordSummary:j(n.payload),messages:[...t.errors,...D(n.refusals),...p?[`Sent again ${n.lockResends} times, the target still could not lock a record the write needed.`]:[],...R&&!m?[`Not sent again: a row goes again without the fields the target refused ${Je} times at most.`]:[],...Me(t.errorDetails)?[Tt]:[],...s?[ke(s,ve(this.splitting.allowance,V(e)),"run")]:[],...U(l)]})}refusedValueKey(e,t,n){let s=t.RecordTypeId,r=t[n];if(typeof s!="string"||s===""||typeof r!="string"||r==="")return;let o=n.toLowerCase();if(!(!e.remembered.has(o)||o===e.upsertField?.toLowerCase()))return[e.objectApiName,s,o,r].join("\0")}rememberRefusedValues(e,t,n){for(let s of t.errorDetails??[])if(s.statusCode===je)for(let r of s.fields){let o=_(n,r),i=o===void 0?void 0:this.refusedValueKey(e,n,o);o===void 0||i===void 0||this.refusedValues.has(i)||this.refusedValues.set(i,{field:o,refusedBy:"restricted-picklist",reason:ee(s)})}}rememberRefusedOwners(e,t,n){let s=_(n,"OwnerId");if(!(s===void 0||s.toLowerCase()===e.upsertField?.toLowerCase())&&!ae(e,n))for(let r of t.errorDetails??[]){if(r.statusCode!==Pe)continue;let o=_e(r,n);o===void 0||this.refusedOwners.has(o)||this.refusedOwners.set(o,{field:"OwnerId",refusedBy:"inactive-owner",reason:ee(r)})}}withoutRefusedValues(e,t){let n=[];if(this.refusedValues.size===0&&this.refusedOwners.size===0)return{sent:t,before:n};for(let o of Object.keys(t)){let i=this.refusedValueKey(e,t,o),d=i===void 0?void 0:this.refusedValues.get(i);d&&n.push({...d,field:o})}let s=_(t,"OwnerId"),r=s===void 0?void 0:t[s];if(s!==void 0&&typeof r=="string"&&s.toLowerCase()!==e.upsertField?.toLowerCase()&&!ae(e,t)){let o=this.refusedOwners.get(r.slice(0,15));o&&n.push({...o,field:s})}return n.length===0?{sent:t,before:n}:{sent:J(t,n),before:n}}leaveRefusedAsFailed(e,t,n){for(let s of t){let r=s.refusals[s.refusals.length-1];e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r?.errors??[],...D(s.refusals.slice(0,-1)),`Not written again without ${Y(G(s))}: ${n}`,...U(s.before)]})}}leaveLimitedAsFailed(e,t,n,s){for(let r of t){let o=n.get(r);o&&(e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(r.payload),messages:[...o,...D(r.refusals),`Not sent again in a smaller call: ${s}`,...U(r.before)]}))}}leaveLockedAsFailed(e,t,n){for(let{row:s,errors:r}of t)e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r,...D(s.refusals),`Not sent again: ${n}`,...U(s.before)]})}async writeAgainWithoutTheirFields(e,t,n){for(;e.refusedOnTheirFields.length>0;){let s=e.refusedOnTheirFields.splice(0);if(t.onProgress({objectName:e.objectApiName,status:"running",progress:100,message:`Writing ${s.length} ${e.objectApiName} record${s.length===1?"":"s"} again without the fields ${ht(s.flatMap(G))} refused...`}),this.jobsCanCarry(e.bulk,e.objectApiName)&&s.length>=2e3){let r=`${e.objectApiName}, sent again`,o=await this.sendRows(e,t,s,r,0,(i,d)=>this.leaveRefusedAsFailed(e,i,d));if(o??=await this.sendLockedAgain(e,t,0),o){let i=I(o.thrown);this.leaveLockedAsFailed(e,e.locked.splice(0),i),this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),i);return}continue}for(let r=0;r<s.length;r+=n){let o=s.slice(r,r+n),i;try{await t.waitIfPaused()}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r),I(l)),l}try{i=await this.callAndSettle(e,t,o,(l,u)=>this.leaveRefusedAsFailed(e,l,u))}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),I(l)),l}let d;if(i){d=i.threw;let l=I(i.threw.thrown),u=[...i.rest,...s.slice(r+n)];i.threw.left==="may-have-written"?(this.settleThrown(e,i.threw,i.rows,`${e.objectApiName}, sent again`,0),this.leaveRefusedAsFailed(e,u,l)):this.leaveRefusedAsFailed(e,[...i.rows,...u],l)}else{try{d=await this.sendLockedAgain(e,t,0)}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),I(l)),l}d&&this.leaveRefusedAsFailed(e,s.slice(r+n),I(d.thrown))}if(d){this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),I(d.thrown));return}}}}settleByNaturalKey(e,t,n,s,r,o){t.forEach((i,d)=>{let l=n[d];if(l&&typeof i.sourceId=="string"){s.createdTarget(l)&&ze(r),s.addExisting(i.sourceId,l,e),r.linkedExistingCount++;return}r.failureCount++,r.unidentifiedExistingCount++,i.errors.every(u=>X(u))&&r.alreadyExistsCount++,r.errorSamples.length<3&&r.errorSamples.push({recordSummary:j(i.payload),messages:o?[...i.errors,o]:i.errors})})}async recordsByNaturalKey(e,t,n,s){let r=this.deps.queryRecords;return r?be(o=>r(e,o),t,n,s):s.map(()=>{})}async giveFlagsBack(e,t,n,s){let r=this.deps.updateRecords;if(!r||s.size===0||!pe[e])return;let o=[];for(let[d,l]of s){let u=n.cleanedRecords[d]?.source;u&&o.push([u,l])}let i=await this.deps.describeFields?.(t,e).catch(()=>{});return me(e,o,d=>i?.find(l=>l.name===d)?.updateable!==!1,d=>r(t,e,d),n.stopped)}async heldBeforeInsert(e,t,n){let s=this.deps.queryRecords;if(!s)return new Map;let r=o=>s(t,o);return e===Q?ye(r,n):fe[e]!==void 0?he(r,e,n):e===ue?Re(r,n):new Map}pickUpsertField(e,t,n,s,r){if(s==="off"||!this.deps.upsertRecords)return;let o=e.filter(i=>i.externalId&&t.has(i.name)).sort((i,d)=>i.name.localeCompare(d.name));if(r)return this.tableKeyOfThePage(o,n,r);if(o.length!==0){for(let i of o){let d=new Set,l=!0;for(let u of n){let c=u[i.name];if(typeof c!="string"||c.length===0){l=!1;break}if(d.has(c)){l=!1;break}d.add(c)}if(l)return E.info(`[forge] upsert: using "${i.name}" as external Id (unique across ${n.length} records)`),i.name}E.warn(`[forge] upsert: no externalId candidate is non-null+unique across batch (${o.map(i=>i.name).join(", ")}) \u2014 falling back to insert`)}}tableKeyOfThePage(e,t,n){let s=e.find(o=>n.unique.has(o.name))?.name;if(s===void 0){e.length>0&&E.warn(`[forge] upsert: no externalId candidate is non-null+unique across the rows read (${e.map(o=>o.name).join(", ")}) \u2014 falling back to insert`);return}let r=new Set;for(let o of t){let i=o[s];if(typeof i!="string"||i.length===0||r.has(i)){E.warn(`[forge] upsert: a row of this page leaves "${s}" empty or repeats it \u2014 inserting the page`);return}if(n.sent.has(i)){E.warn(`[forge] upsert: a row of this page repeats a "${s}" an earlier page sent \u2014 inserting the page`);return}r.add(i)}n.sent.size===0&&E.info(`[forge] upsert: using "${s}" as external Id (unique across the rows read of the object)`);for(let o of r)n.sent.add(o);return s}};function j(a){let e=Object.keys(a).slice(0,4),t=[];for(let n of e){let s=a[n],r;if(s===null)r="null";else if(s===void 0)r="undefined";else if(typeof s=="string")r=s.length>30?s.slice(0,30)+"\u2026":s;else if(typeof s=="object")try{let o=JSON.stringify(s);r=o.length>30?o.slice(0,30)+"\u2026":o}catch{r="<unserializable>"}else r=String(s);t.push(`${n}=${r}`)}return t.join(" ")||"(empty)"}export{q as a,L as b,M as c,_t as d,de as e,dt as f,lt as g,pt as h,mt as i,Bt as j,Ge as k,j 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{a as b}from"./chunk-RFEO2KAN.mjs";import"./chunk-TBZMC2VV.mjs";import{a}from"./chunk-LQ4DRFUH.mjs";import"./chunk-57VHUYNG.mjs";import"./chunk-5O6JOMHS.mjs";import"./chunk-HUMEKZT5.mjs";import"./chunk-MYTIL2JD.mjs";import"./chunk-JVL444U5.mjs";import"./chunk-KLX67VPL.mjs";import"./chunk-5CD257T7.mjs";import"./chunk-H45UXY6G.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-SRQDABQ2.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-LV6G4XTK.mjs";import"./chunk-HJKM3E56.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-YMJVMFPY.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-4HFRHFGQ.mjs";import"./chunk-342FN7AO.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-Z7X534S4.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-DBFJB2B6.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-6MUEPV7M.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-RH3N2H7P.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VXHDBYMI.mjs";import"./chunk-ENLBYECD.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as objectsWrittenBy,b as previewCheckpoint};
|
|
@@ -0,0 +1,8 @@
|
|
|
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 as _,b as I}from"./chunk-GMY5427L.mjs";import{b as j,c as E,e as T}from"./chunk-TZE3Y7IQ.mjs";import{b as c,e as C,f,k as m,l as R,n as S,o as L}from"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";import{basename as X,dirname as Z,join as ee}from"node:path";var v="FieldMapping.csv",N="ValueMapping.csv";function Y(e,t){let n=[],r=[],i="",o=!1,a=()=>{r.push(i),i=""},d=()=>{a(),r.some(l=>l!=="")&&n.push(r),r=[]};for(let l=0;l<e.length;l++){let s=e[l];o?s!=='"'?i+=s:e[l+1]==='"'?i+=e[++l]:o=!1:s==='"'&&i===""?o=!0:e.startsWith(t,l)?(a(),l+=t.length-1):s===`
|
|
8
|
+
`?d():s!=="\r"&&(i+=s)}return d(),n}function V(e,t,n,r){let[i,...o]=Y(e.replace(/^\uFEFF/,""),t),a=(i??[]).map(d=>d.trim());if(!r.some(d=>!a.includes(d)))return o.map(d=>Object.fromEntries(n.map(l=>[l,(d[a.indexOf(l)]??"").trim()])))}function A(e,t){return V(e,t,["ObjectName","FieldName","Target"],["ObjectName","Target"])?.filter(r=>r.ObjectName!==""&&r.Target!=="").map(r=>({object:r.ObjectName,field:r.FieldName,target:r.Target}))}function $(e,t){let n=["ObjectName","FieldName","RawValue","Value"];return V(e,t,n,n)?.filter(i=>i.ObjectName!==""&&i.FieldName!=="").map(i=>({object:i.ObjectName,field:i.FieldName,rawValue:i.RawValue,value:i.Value}))}var te=R({targetObject:c().optional(),sourceField:c().optional(),targetField:c().optional()}),ne=R({fieldName:c().min(1),rawValue:c(),mappedValue:c()}),ie=L([c().min(1),S({name:c().min(1)})]),B=S({query:c().optional(),name:c().optional(),objectName:c().optional(),operation:c().optional(),externalId:c().optional(),master:f().optional().default(!0),excluded:f().optional(),excludedFields:m(c()).optional().default([]),useFieldMapping:f().optional(),fieldMapping:m(te).optional().default([]),useValuesMapping:f().optional(),valuesMapping:m(ne).optional().default([]),deleteOldData:f().optional().default(!1),deleteFromSource:f().optional(),deleteByHierarchy:f().optional(),hardDelete:f().optional(),updateWithMockData:f().optional().default(!1),mockFields:m(ie).optional().default([]),where:c().optional(),orderBy:c().optional(),limit:C().optional()}),re=S({objects:m(B).optional().default([]),objectSets:m(S({objects:m(B).optional().default([])})).optional(),csvFileDelimiter:c().optional(),csvReadFileDelimiter:c().optional()}).refine(e=>oe(e).length>0,{message:"An export lists its objects under objects or objectSets."});function oe(e){return[...e.objects,...(e.objectSets??[]).flatMap(t=>t.objects)]}var h=class extends Error{code;objects;constructor(t,n,r=[]){super(n),this.name="SfdmuRefusal",this.code=t,this.objects=r}},x=class extends h{constructor(t){super("TARGET_OBJECT_MAPPED",`Nothing was imported: Sync writes an object to the same object in the target org, and this export sends one to another: ${t.join("; ")}. Take out its targetObject entries, or those objects, then import it again.`,t),this.name="SfdmuTargetObjectError"}};function ae(e){return e.reduce((t,n)=>typeof n=="number"?`${t}[${n}]`:`${t}${t===""?"":"."}${String(n)}`,"")}function se(e,t){let n;try{n=JSON.parse(e)}catch(a){let d=a instanceof Error?a.message:String(a);throw new h("NOT_JSON",`Nothing was imported: ${t} is not JSON (${d}).`)}let r=new h("NO_OBJECTS",`Nothing was imported: ${t} lists no object, under objects or objectSets.`);if(typeof n!="object"||n===null||Array.isArray(n))throw r;let i=re.safeParse(n);if(i.success)return i.data;let o=[...new Set(i.error.issues.map(a=>ae(a.path)))];throw o.every(a=>a==="")?r:new h("INVALID_EXPORT",`Nothing was imported: these entries of ${t} are not of the kind SFDMU's format holds there: ${o.join(", ")}. Correct them, then import it again.`,o)}var de=["Insert","Update","Upsert","Readonly","Delete","DeleteSource","DeleteHierarchy","HardDelete"];function y(e){return(e.query?I(e.query).object:void 0)??[e.name,e.objectName].find(t=>t!==void 0&&t.trim()!=="")}function le(e){let t=(e.operation??"Readonly").trim().toLowerCase();return de.find(n=>n.toLowerCase()===t)}function ce(e){let t=[...e.objects.map((r,i)=>({entry:r,set:0,place:`objects[${i}]`})),...(e.objectSets??[]).flatMap((r,i)=>r.objects.map((o,a)=>({entry:o,set:i+1,place:`objectSets[${i}].objects[${a}]`})))],n=t.filter(({entry:r})=>y(r)===void 0).map(({entry:r,place:i})=>r.query?`${i} (${r.query.slice(0,80)})`:i);if(n.length>0)throw new h("OBJECT_NOT_NAMED",`Nothing was imported: no object can be read in these entries, neither in the FROM of a query nor under name: ${n.join("; ")}. Correct them, then import it again.`,n);return t.map(({entry:r,set:i,place:o})=>{let a=I(r.query??"");return{...r,place:o,set:i,object:y(r)??"",read:a,sfdmuOperation:le(r),settingsLeft:[...H(r,ge),...z({...r,read:a})!==r.where&&K(r.where)?["where"]:[]]}})}function z(e){return e.read.where!==void 0?e.read.where:e.where?.trim()?e.where:void 0}var pe="all";function q(e){return e.updateWithMockData?[...new Set(e.mockFields.map(t=>typeof t=="string"?t:t.name))]:[]}function ue(e){let t=e.sfdmuOperation;if(e.excluded)return{code:"excluded"};if(!e.query?.trim())return{code:"noQuery"};if(t===void 0)return{code:"unknownOperation",detail:e.operation};if(t==="Readonly")return{code:"readonly"};if(t==="DeleteSource"||t==="DeleteHierarchy")return{code:"deletesElsewhere",detail:t};let n=t==="Delete"||t==="HardDelete";if(n&&e.deleteFromSource)return{code:"deletesElsewhere",detail:"deleteFromSource"};if(n&&e.deleteByHierarchy)return{code:"deletesElsewhere",detail:"deleteByHierarchy"};if(!n&&q(e).includes(pe))return{code:"mockAllFields"}}var fe=new Set(["null","NULL","undefined","#N/A"]);function U(e){return j(e.field)&&!/^\/.*\/$/.test(e.rawValue)&&!/^eval[(].*[)]$/i.test(e.value)&&!fe.has(e.value.trim())}function K(e){return Array.isArray(e)?e.length>0:e!==!1&&e!==null&&e!==void 0&&e!==""}var ge=new Set(["query","name","objectName","operation","externalId","master","excluded","excludedFields","useFieldMapping","fieldMapping","useValuesMapping","valuesMapping","deleteOldData","deleteFromSource","deleteByHierarchy","hardDelete","updateWithMockData","mockFields","where","orderBy","limit"]),me=new Set(["objects","objectSets","orgs","csvFileDelimiter","csvReadFileDelimiter"]);function H(e,t){return Object.entries(e).filter(([n,r])=>!t.has(n)&&!n.startsWith("$")&&K(r)).map(([n])=>n)}function he(e){let t=[],n=(F,w)=>{t.push({code:F,object:e.object,...w===void 0?{}:{detail:w}})},{read:r,sfdmuOperation:i}=e,o=J(e),a=o??"Id",d=i==="Delete"||i==="HardDelete";r.object===void 0&&n("queryUnread");let l=d?void 0:_(e.query??"");l&&"every"in l&&n("everyField",l.every);let s=e.name||e.objectName;s&&s.toLowerCase()!==e.object.toLowerCase()&&n("nameDiffers",s),d&&n("delete",e.hardDelete?"HardDelete":i),o===void 0&&(i==="Update"||i==="Upsert")&&n("defaultKey"),i==="Update"&&a!=="Id"&&n("updateKey",a),a!=="Id"&&!j(a)?n("unusableKey",a):i==="Upsert"&&a!=="Id"&&!a.endsWith("__c")&&n("upsertKey",a),e.fieldMappingsIgnored>0&&n("fieldMappingOff",String(e.fieldMappingsIgnored)),e.valueRowsLeft.length>0&&n("valueRows",e.valueRowsLeft.join(", ")),e.master===!1&&n("notMaster");let u=e.limit??r.limit;u!==void 0&&n("limit",String(u));let g=z(e);g!==void 0&&!T(g)&&n("whereRefused");let b=e.orderBy??r.orderBy;b!==void 0&&!E(b)&&n("queryClause",`ORDER BY ${b}`);for(let F of r.otherClauses)n("queryClause",F);return e.deleteOldData&&!d&&n("deleteOldData"),e.mockedFields.length>0&&n("mockFields",e.mockedFields.join(", ")),e.settingsLeft.length>0&&n("settings",e.settingsLeft.join(", ")),t}function W(e){return!!e.sourceField&&!!e.targetField}function be(e){return W(e)||!!e.targetObject}function J(e){let t=e.externalId;if(!(t===void 0||t.trim()===""))return k(e.fieldMapping).find(n=>n.sourceField===t)?.targetField??t}function k(e){return[...new Map(e.filter(W).map(t=>[t.sourceField,t])).values()]}function Fe(e){return e.flatMap(t=>{let n=t.fieldMapping.flatMap(i=>i.targetObject||[]).at(-1);if(n===void 0||n.toLowerCase()===t.object.toLowerCase())return[];let r=k(t.fieldMapping).map(i=>`${i.sourceField} \u2192 ${i.targetField}`);return[`${t.object} \u2192 ${n}${r.length>0?` (${r.join(", ")})`:""}`]})}function Me(e){let t=e.csvFileDelimiter??e.csvReadFileDelimiter??"";return new Map([["comma",","],["semicolon",";"],["tab"," "],["\\t"," "]]).get(t.trim().toLowerCase())??(t||",")}var P=class{fileReader;constructor(t){this.fileReader=t}async import(t){let n=await this.fileReader.readFile(t),r=se(n,X(t)),i=ce(r),o=[],a=new Set,d=[];for(let p of i){let M=ue(p);M?o.push({...M,object:p.object}):a.has(p.object.toLowerCase())?o.push({code:"duplicate",object:p.object,detail:p.place}):(a.add(p.object.toLowerCase()),d.push(p))}let l=await this.readMappingFiles(t,r,d),s=d.map(p=>we(p,l)),u=Fe(s);if(u.length>0)throw new x(u);let g=[...l.notes],b=(r.objects.length>0?1:0)+(r.objectSets?.length??0);b>1&&g.push({code:"objectSets",detail:String(b)}),s.some(p=>O(p.sfdmuOperation)!=="delete")&&g.push({code:"contactPoints"});let F=H(r,me);F.length>0&&g.push({code:"settings",detail:F.join(", ")});let w=p=>i.findIndex(M=>M.object===p.object),Q=[...o,...s.flatMap(he)].sort((p,M)=>w(p)-w(M)),G=r.keepObjectOrderWhileExecute===!0;return{config:this.convert(Se(s,G)),notes:[...g,...Q]}}async readMappingFiles(t,n,r){let i=Me(n),o={fieldRows:[],valueRows:[],notes:[]};if(r.some(a=>a.useFieldMapping)){let a=await this.readBeside(t,v),d=a===void 0?[]:A(a,i);d?o.fieldRows=d:o.notes.push({code:"mappingFileUnread",detail:v})}if(r.some(a=>a.useValuesMapping)){let a=await this.readBeside(t,N),d=a===void 0?[]:$(a,i);d?o.valueRows=d:o.notes.push({code:"mappingFileUnread",detail:N})}return o}async readBeside(t,n){try{return await this.fileReader.readFile(ee(Z(t),n))}catch(r){if(r?.code==="ENOENT")return;throw r}}extractDependencies(t){let n=[],r=new Map(t.objects.flatMap(i=>{let o=y(i);return o===void 0?[]:[[o.toLowerCase(),o]]}));for(let i of t.objects){let o=y(i);if(i.master===!1||o===void 0)continue;let a=je(i.query??"");for(let d of a)if(d.includes(".")){let s=d.split(".")[0],u=r.get(ye(s).toLowerCase());u!==void 0&&n.push({parent:u,child:o,field:s})}}return n}convert(t){let n=new Date().toISOString(),r=t.map((i,o)=>this.convertObject(i,o));return{id:D(),name:"SFDMU Import",description:"Imported from SFDMU export.json",sourceOrgId:D(),targetOrgId:D(),direction:"source_to_target",mode:"full",objects:r,conflictStrategy:"source_wins",enableRollback:!1,createdAt:n,updatedAt:n}}convertObject(t,n){let r=this.convertFieldMappings(t.fieldMapping),i=this.convertValuesMapping(t.valuesMapping,r),o=t.orderBy??t.read.orderBy,a=J(t);return{objectApiName:t.object,externalIdField:a!==void 0&&a!=="Id"&&j(a)?a:void 0,operation:O(t.sfdmuOperation),query:t.query,fieldMappings:r,transformRules:i,excludedFields:t.excludedFields,addOnFields:[],batchSize:200,orderBy:o!==void 0&&E(o)?o:void 0,where:z(t),insertOrder:n+1}}convertFieldMappings(t){return k(t).map(n=>{let r=n.sourceField===n.targetField?"direct":"rename";return{sourceField:n.sourceField,targetField:n.targetField,type:r}})}convertValuesMapping(t,n){if(t.length===0)return[];let r=new Map;for(let o of t){let d=n.find(s=>s.sourceField===o.fieldName)?.targetField??o.fieldName,l=r.get(d)??{};l[o.rawValue]=o.mappedValue,r.set(d,l)}let i=[];for(let[o,a]of r)i.push({type:"map_value",field:o,config:{valueMap:a}});return i}};function we(e,t){let n=s=>s.object.toLowerCase()===e.object.toLowerCase(),i=(e.useFieldMapping?t.fieldRows.filter(n):[]).map(({field:s,target:u})=>s===""?{targetObject:u}:{sourceField:s,targetField:u}),o=e.useValuesMapping?t.valueRows.filter(s=>n(s)&&s.value.trim()!==""):[],a=o.filter(U).map(({field:s,rawValue:u,value:g})=>({fieldName:s,rawValue:u,mappedValue:g})),l=O(e.sfdmuOperation)==="delete"?[]:q(e);return{...e,fieldMapping:e.useFieldMapping?[...i,...e.fieldMapping]:[],fieldMappingsIgnored:e.useFieldMapping?0:e.fieldMapping.filter(be).length,valuesMapping:[...a,...e.valuesMapping],excludedFields:[...new Set([...e.excludedFields,...l])],mockedFields:l,valueRowsLeft:o.filter(s=>!U(s)).map(s=>`${s.field} (${s.rawValue})`)}}function Se(e,t){let n=i=>O(i.sfdmuOperation)==="delete",r=(i,o)=>n(i)?[i.set,0,t?o:-o]:[i.set,1,o];return e.map((i,o)=>({entry:i,rank:r(i,o)})).sort((i,o)=>i.rank[0]-o.rank[0]||i.rank[1]-o.rank[1]||i.rank[2]-o.rank[2]).map(({entry:i})=>i)}function O(e){return{Insert:"insert",Update:"update",Upsert:"upsert",Delete:"delete",HardDelete:"delete"}[e]}function je(e){let t=e.match(/SELECT\s+(.+?)\s+FROM/i);return t?t[1].split(",").map(n=>n.trim()):[]}function ye(e){let t={Account:"Account",Contact:"Contact",Owner:"User",CreatedBy:"User",LastModifiedBy:"User",Parent:"Account",RecordType:"RecordType"};return t[e]?t[e]:e.endsWith("__r")?e.replace(/__r$/,"__c"):e}function D(){return globalThis.crypto.randomUUID()}export{P as SfdmuImporter,h as SfdmuRefusal,x as SfdmuTargetObjectError,re as sfdmuExportSchema};
|
|
@@ -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 as R}from"./chunk-CE6ZDGBB.mjs";import{E as g,F as u,J as w,M as m,N as I,O as k}from"./chunk-CGWXQX75.mjs";import{g as T}from"./chunk-SIOZXPFG.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{vb as y}from"./chunk-B45CNPUX.mjs";var b="Opportunity",v=new Set(["Id","OpportunityId",u,"IsPrimary"]),O=200,l=s=>s.slice(0,15);function S(s){return`The contact roles the platform wrote with the run's opportunities were not looked up, so written as generated: an opportunity may hold the role of its contact twice. ${s}`}var P=class{constructor(e){this.deps=e}deps;sentWith=new Map;untold;linkedIds=[];said;unread;alike=0;opportunitiesWritten(e,d){let r=t=>{let n=t?.[u];return typeof n=="string"&&n!==""?n:void 0},o=d.rows&&(d.rows.length===e.length||d.stopped)?d.rows:void 0;if(!o){d.successIds.length>0&&e.some(t=>r(t))&&(this.untold??="The opportunities' insert did not say which record each id it answered is.");return}o.forEach((t,n)=>{let a=r(e[n]);if(!(!t.id||a===void 0)){if(t.unmatched){this.untold??="The opportunities' insert did not say which record each id it answered is.";return}this.sentWith.set(l(t.id),a)}})}async link(e){if(e.length>0&&this.untold!==void 0&&(this.unread??=this.untold),this.sentWith.size===0||e.length===0)return new Map;let d=e.map(i=>({OpportunityId:i.OpportunityId,[u]:i[u],IsPrimary:i.IsPrimary})),r=i=>this.sentWith.get(l(i)),o=this.deps.readTarget;if(!o)return W(d,r)&&(this.unread??="This run cannot read the target."),new Map;let t;try{t=await k(o,d,r,A(e))}catch(i){return this.unread??=h(i),new Map}let{found:n,alike:a}=t;this.alike+=a.length;for(let i of[...n.keys(),...a])this.sentWith.delete(l(String(e[i].OpportunityId)));return n.size>0&&await this.give(e,n),n}async give(e,d){let r=this.said??={records:0,given:0},o=[];for(let[n,a]of d){let i=String(a.Id);this.linkedIds.push(i),r.records++;let p=Object.entries(e[n]??{}).filter(([f,c])=>!v.has(f)&&c!==null&&c!==void 0&&String(a[f]??"")!==String(c));p.length>0&&o.push({Id:i,...Object.fromEntries(p)})}if(o.length===0)return;let t=n=>{r.refusal??=n};if(!this.deps.update)return t("This run cannot update the target.");for(let n=0;n<o.length;n+=O){if(this.deps.stopped())return t("The run was stopped before they were given them.");let a=o.slice(n,n+O),i;try{i=await this.deps.update(this.deps.orgId,g,a)}catch(p){t(h(p));continue}a.forEach((p,f)=>{let c=i[f];c?.success?r.given++:t(c?.error??"The org gave no answer for it.")})}}resultOf(e){return e!==g?{linkedIds:[],notes:[]}:{linkedIds:this.linkedIds,...this.said?{writtenByThePlatform:{...this.said}}:{},notes:[...this.unread!==void 0?[S(this.unread)]:[],...this.alike>0?[m(this.alike,"generated")]:[]]}}};function A(s){return[...new Set(s.flatMap(e=>Object.keys(e)))].filter(e=>!v.has(e))}function W(s,e){return s.some(d=>{let r=d.OpportunityId,o=d[u];if(typeof r!="string"||typeof o!="string")return!1;let t=e(r);return t!==void 0&&l(t)===l(o)})}function j(){let s=new Map,e=0;return{inserted(d,r,o){d===b&&r.forEach((t,n)=>{let a=t[u],i=o[n];i!==void 0&&typeof a=="string"&&a!==""&&s.set(i,a)})},readTarget:async d=>{let r=w(d);if(!r)throw new Error("A dry run reads nothing else of the target here.");let o=new Date().toISOString();return r.opportunities.flatMap(t=>{let n=s.get(t);return n===void 0?[]:[I({...Object.fromEntries(r.fields.map(a=>[a,null])),Id:`dry-role-${e++}`,OpportunityId:t,[u]:n,...r.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},o)]})},update:async(d,r,o)=>o.map(()=>({success:!0}))}}function _(s){if(s)return`${s.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${s.given} given the fields the seed generated for ${s.given===1?"it":"them"}`+(s.refusal!==void 0?`, the others left as the platform wrote them (${s.refusal}).`:".")}function B(s){return{readTarget:e=>R(s,e),update:async(e,d,r)=>{let o=await s.sobject(d).update(r,{allOrNone:!1,headers:y()}),t=Array.isArray(o)?o:[o];return r.map((n,a)=>{let i=t[a];return i?.success===!0?{success:!0}:{success:!1,error:(i?.errors??[]).length>0?T(i?.errors):"The org gave no answer for it."}})}}}export{b as a,S as b,P as c,j as d,_ as e,B as f};
|
|
@@ -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{b as ne,c as ae,d as Bo,e as $o,f as me}from"./chunk-ALJVEUUS.mjs";import{a as Mo,e as Uo}from"./chunk-Z7X534S4.mjs";import{J as te,P as Te,a as Do}from"./chunk-6QSM2WIH.mjs";import{f as _e,o as pe,r as Ne,t as Lo,v as De}from"./chunk-NTDN2JQZ.mjs";import{d as To}from"./chunk-6MUEPV7M.mjs";import{E as Fo}from"./chunk-HJC7AIBK.mjs";import{b as le,d as de}from"./chunk-OTWRDD6L.mjs";import{c as No}from"./chunk-PA3MKJVH.mjs";import{c as _o,e as Ee,g as Ce,h as ce}from"./chunk-TZE3Y7IQ.mjs";import{a as Co,b as V}from"./chunk-CA5NAXSU.mjs";import{A as no,E as ao,F as ro,Fa as go,G as io,Ga as bo,H as so,Ha as yo,I as co,Sa as fo,bc as ko,ea as lo,fa as po,hb as ho,jb as zo,ka as oe,kb as So,kc as Oo,la as ke,lc as Ro,m as Xe,mc as wo,nb as xo,ob as Io,oc as vo,pa as F,pb as jo,pc as Ae,qa as mo,r as je,ra as M,rd as Ao,s as Ve,sa as Oe,sd as Eo,t as Je,ta as uo,u as Qe,v as X,va as Re,w as Pe,wa as we,wb as Po,x as eo,xa as ve,y as oo,z as to}from"./chunk-B45CNPUX.mjs";import{b as n,c as xe,e as b,f as r,g as Ke,i as D,k as c,l as o,o as se,p as Ie,s as I,u as A,v as w,w as Ye,x as Ze,y as G}from"./chunk-7EANH5PY.mjs";function Tn(e,t,a){return async l=>{let d=l.map(y=>`${y.objectApiName} (${y.records})`).join(", ");e.log(`[WARN] ${a}: the user may not delete ${d} in the target: those records stay`);let p=e.infraServices?.confirmRemovalLeavingUndeletable;if(!p)return!0;let m=e.orgManager.getOrg(t);return p({org:ko(m,t),objects:l})}}var Go={code:"NOT_INITIALIZED",message:"Production Guard is not initialized \u2014 infrastructure services missing"};function _n(){return Object.assign(new Error(Go.message),{code:Go.code})}var Fe={blocked:"GUARD_BLOCKED",declined:"GUARD_DECLINED"};function Nn(e){return Object.assign(new Error(`Operation blocked by Production Guard: ${e}`),{code:Fe.blocked})}function Dn(e){return e instanceof Error&&e.code===Fe.blocked?Fe.blocked:void 0}function jt(e){return e.robustness??lo}function Fn(e){return e.bulkManager??new Do(jt(e).bulk.maxConcurrentJobs)}var Pt={"sync:schedule":"sync:schedule:","sync:pipeline":"sync:pipeline:","seed:pipeline":"seed:pipeline:","offline-replay":"offline-replay-"};function Mn(e,t,a){return{id:`${Pt[e]}${t}`,type:a,timestamp:Date.now()}}function Un(e,t,a,l){return{id:e.nextId(),type:a,timestamp:Date.now(),correlationId:t.id,payload:l}}function Ln(e,t,a,l,d={}){let p=t==="error"?null:d.autoDismissMs===void 0?5e3:d.autoDismissMs,m={id:e.nextId(),type:"notification",timestamp:Date.now(),payload:{level:t,title:a,message:l,...p===null?{}:{autoDismissMs:p},...d.actions?{actions:d.actions}:{},...d.code?{code:d.code}:{}}};e.broker.postToWebview(m),e.log(`[TX] notification: ${a}`)}function Bn(e,t,a,l){let d={id:e.nextId(),type:"operation:started",timestamp:Date.now(),payload:{operationId:t,module:a,description:l}};e.broker.postToWebview(d)}function $n(e,t,a,l,d,p){let m={id:e.nextId(),type:"operation:progress",timestamp:Date.now(),payload:{operationId:t,percentage:a,processedRecords:l,totalRecords:d,currentStep:p}};e.broker.postToWebview(m)}function Gn(e,t,a){let l={id:e.nextId(),type:"operation:completed",timestamp:Date.now(),payload:{operationId:t,result:a}};e.broker.postToWebview(l)}var kt=Symbol("sandforge.uncorrelated");function Wo(e,t,a,l,d,p={}){let m=V(d),y=d instanceof To?d:void 0,j=kt in l,E=p.code??y?.code??"UNKNOWN";j||wt(e.broker,m,E),e.log(`[ERR] ${t}: ${m}${j?` (uncorrelated: ${String(l.reason)})`:""}`);let O={id:e.nextId(),type:a,timestamp:Date.now(),...j?{}:{correlationId:l.id},payload:{message:m,code:E,retryable:p.retryable??!1,...y?{orgId:y.orgId}:{},...p.extraPayload}};e.broker.postToWebview(O),e.log(`[TX] ${a}: ${m}`)}function Wn(e,t){let a={id:e.nextId(),type:t.type,timestamp:Date.now(),payload:t.payload};e.broker.postToWebview(a)}function qn(e){let t=e?.getSandforgeSetting;if(!(!t||!t("grappe.enabled",!1)))return{enabled:!0,autoActivateThreshold:t("grappe.autoActivateThreshold",1e4),maxWorkers:Xe.maxWorkers,grappeSize:t("grappe.grappeSize",5e3),strategy:"round_robin",backPressure:{enabled:!1,maxQueueDepth:3,highWaterMark:80,lowWaterMark:60,strategy:"pause",monitoringInterval:5e3},checkpointing:!0,isolationLevel:"per_grappe"}}function Hn(e){let t=new Set(e.map(l=>l.batchSize)),[a]=t;return{...e.length>0?{objectName:e.map(l=>l.objectApiName).join(", ")}:{},...t.size===1&&a!==void 0?{batchSize:a}:{}}}function Kn(e,t,a,l,d={}){let p={id:e.nextId(),type:"operation:failed",timestamp:Date.now(),payload:{operationId:t,error:a,retryable:l,...d.extraPayload}};e.broker.postToWebview(p),d.authored!==!0&&At(e,a,d.context)}var Ot=[/^Operation cancelled by user\b/,/^Operation blocked by Production Guard: /,/^Production Guard is not initialized\b/,/^Duplicate operation: /,/^A backup or rollback operation is already running for org /,/^Object describe not available for '/,/^CRUD_FLS_DENIED: /,/^CRUD\/FLS check failed for /,/^No backup found for operation /,/^Backup \S+ was taken from org /,/^Restore not run: /,/^Pipeline failed$/,/^Pipeline did not start: /,/^Pipeline ran out of time: /,/^Org not found: /,/^No credentials for org /,/^Invalid username format: /];function Rt(e){return Ot.some(t=>t.test(e))}var qo=1e4,Me=new WeakMap;function wt(e,t,a){let l=Ae(t,{code:a});if(!l?.actionKey)return;let d=Me.get(e)??new Map,p=Date.now();for(let[m,y]of d)p-y>qo&&d.delete(m);d.set(l.code,p),Me.set(e,d)}function vt(e,t){let a=Me.get(e)?.get(t);return a!==void 0&&Date.now()-a<=qo}function At(e,t,a={}){if(!(e.broker.panelCount>0)||Rt(t))return;let d=Co(t,vo)??"UNKNOWN",p=Ae(t,{code:d});if(p?.actionKey){if(vt(e.broker,p.code))return;e.broker.showFixSuggestion({source:"catalogue",code:p.code,actionKey:p.actionKey});return}let m=e.errorResolver;m&&m.resolveError({errorCode:d,message:t},a).then(y=>{e.broker.showFixSuggestion({source:"model",text:Et(y)})}).catch(y=>{e.log?.(`[ERR] operation:failed resolution: ${V(y)}`)})}function Et(e){return e.suggestions[0]?.description||e.explanation}import{isAbsolute as Dt}from"node:path";var i=n().min(1).max(128),s=n().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Invalid Salesforce API name").max(80),Vo=c(s).max(300),u=n().min(1).max(200),re=n().max(2e3).refine(Ee,{message:Ce}),Ft=n().refine(_o,{message:"ORDER BY clause must list only field names with optional ASC/DESC and NULLS FIRST/LAST (no LIMIT, OFFSET, FOR UPDATE or subquery)."}),f=100,Jo=1e4,B=o({keepDays:b().int().min(Pe.min).max(Pe.max).optional(),excluded:c(s).max(f).refine(e=>new Set(e).size===e.length,"An object is left out twice").optional()}).strict(),be={sweepLate:r().optional(),sweepUntied:r().optional()};function Mt(e){return No(e)}function Ut(e){return Po(e)?`Sync copies files with the records they hang on, not as an object of their own: "${e}" keeps its content in a file body. Remove it from this configuration and turn on "Copy the files of these records" instead; the sync was not started.`:`Sync does not copy "${e}": no copy writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Remove it from this configuration; the sync was not started.`}var Lt=A(ao,{error:e=>e.input==="manual"?"Manual conflict review is not available for a sync run: no run shows its conflicts to anyone before it writes. Pick source wins, target wins, newest wins or merge \u2014 target wins keeps every value the target holds where the two orgs differ. The sync was not started.":`Conflict strategy "${String(e.input)}" is not one a sync run acts on: pick source wins, target wins, newest wins or merge. The sync was not started.`}),Bt=ro.extend({objectApiName:s.refine(e=>!Mt(e),{error:e=>Ut(String(e.input))}),externalIdField:Ze(e=>typeof e=="string"&&e.trim()===""?void 0:e,s.optional()),where:re.optional(),orderBy:Ft.optional(),batchSize:b().int().positive().max(Jo).optional()}).strip().refine(e=>e.operation!=="upsert"||(e.externalIdField??"Id").toLowerCase()!=="id",{path:["externalIdField"],error:e=>`An upsert of "${String(e.input.objectApiName)}" needs an External ID field: matching on Id cannot work, because the id belongs to the source org and the target has never issued it. Name an External ID field both orgs share, or set the operation to insert. The sync was not started.`}).superRefine((e,t)=>{let a=Ro([e]);a.length!==0&&t.addIssue({code:G.custom,message:`${wo(a)} The sync was not started.`,params:{unreadablePatterns:a}})});function Ho(e){return Ke({error:()=>`Sync does not run Apex: remove "${e}" from this configuration. The sync was not started so the script cannot be skipped without you knowing.`}).optional()}var Le=io.extend({id:u.optional(),sourceOrgId:i,targetOrgId:i,objects:c(Bt).min(1).max(f),conflictStrategy:Lt,createdAt:n().max(40).optional(),updatedAt:n().max(40).optional(),preScript:Ho("preScript"),postScript:Ho("postScript"),dryRun:w(!1,{error:()=>'A sync configuration cannot ask for a dry run: remove "dryRun" from it. A run of it writes to the target org; to see what it would write, simulate it from the Sync page. The run was not started, so it cannot write while you believed it was only reporting.'}).optional()}).strip().superRefine((e,t)=>{e.direction==="target_to_source"&&t.addIssue({code:G.custom,path:["direction"],message:'Sync writes source to target only: direction "target_to_source" is not supported. Swap the source and target orgs to copy the other way. The sync was not started, so it cannot write into the org you meant to read from.'}),e.mode!=="full"&&e.mode!=="delta"&&t.addIssue({code:G.custom,path:["mode"],message:`Sync runs a full or a delta sync only: mode "${e.mode}" is not implemented. Set mode to "full" or "delta". The sync was not started, so it cannot replay the whole object set while you believed it was reading changes only.`}),e.mode==="delta"&&e.objects.forEach((a,l)=>{a.operation==="upsert"||a.operation==="update"||t.addIssue({code:G.custom,path:["objects",l,"operation"],message:`A delta sync writes ${a.objectApiName} again for every record it reads twice, and ${a.operation} would ${a.operation==="insert"?"create a second copy":"delete a record already gone"}. Write it by upsert on an External ID, or by update, or run the configuration in full. The sync was not started.`})}),e.propagateDeletes===!0&&(e.mode!=="delta"?t.addIssue({code:G.custom,path:["propagateDeletes"],message:'Deletions are carried by a delta sync only, which knows since when to look for them: set mode to "delta", or turn deletions off. The sync was not started.'}):e.objects.forEach((a,l)=>{if(a.operation!=="upsert"&&a.operation!=="update")return;let d=Fo(a);"refused"in d&&t.addIssue({code:G.custom,path:["objects",l],message:`${d.refused} Turn deletions off, or carry a source field onto the key. The sync was not started.`})}))}),aa=o({suggestedName:n().min(1).max(255).refine(e=>!e.includes("/")&&!e.includes("\\"),"suggestedName must not contain a path"),content:n().max(32*1024*1024),extensions:c(n().regex(/^[A-Za-z0-9]+$/)).max(8).optional()}),ra=o({config:Le,muteAutomation:r().optional(),checkpointFirst:B.optional()}),ia=o({config:Le,checkpointFirst:B.optional()}),sa=o({operationId:u}),ca=o({config:Le}),la=o({id:u}),da=o({orgId:i,targetOrgId:i.optional()}),pa=o({sourceOrgId:i,targetOrgId:i,objectApiName:s}),Qo=A(["source_wins","target_wins","newest_wins","manual","merge"]),$t=Ie("kind",[o({kind:w("id")}),o({kind:w("externalId"),field:s}),o({kind:w("syncConfig"),configId:u})]),ma=o({sourceOrgId:i,targetOrgId:i,watchedObjects:c(s).min(1).max(f),apply:c(o({objectApiName:s,match:$t,applyDeletes:r()})).max(f),conflictStrategy:Qo,flushIntervalMs:b().int().min(50).max(6e4),maxBatchSize:b().int().min(1).max(200),keepContactPoints:r().optional()}).refine(e=>e.apply.every(t=>e.watchedObjects.includes(t.objectApiName)),{message:"Every applied object must be watched.",path:["apply"]}),ua=o({sessionId:n().max(200)}),ga=o({sourceOrgId:i,targetOrgId:i}),ba=o({conflictId:n().min(1).max(500),eventReplayId:b().optional(),resolution:Qo,fieldResolutions:I(n(),o({value:D(),source:A(["source","target","manual"])})).optional()}),ya=o({entryId:u}),fa=o({runId:u}),ha=o({realtime:w(!0).optional()}).optional(),za=o({sourceOrgId:i,targetOrgId:i,objects:c(s).max(f),configId:u.optional()}),Sa=o({runId:u,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...be}),xa=o({runId:u}),Ia=o({runId:u,again:r().optional(),sweptObjects:Vo.optional()}),ja=o({runId:u}),Pa=o({runId:u,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...be}),ka=o({runId:u}),Oa=o({format:A(["csv","json"]),entryIds:c(u).max(500).optional()}),Gt=o({id:u,name:n().min(1).max(200),configId:u,cron:n().min(1).max(100),timezone:n().min(1).max(100),enabled:r(),maxRetries:b().int().min(0).max(10),notifyOnComplete:r(),notifyOnFailure:r(),createdAt:n().max(40),updatedAt:n().max(40),version:b().int().positive()}).strip(),Ra=o({schedule:Gt}),wa=o({scheduleId:u,enabled:r()}),va=o({scheduleId:u}),Wt=eo.extend({objectApiName:s,recordCount:b().int().positive().max(X),batchSize:b().int().positive().max(Jo).optional()}).loose(),qt=oo.extend({childObject:s,lookupField:s,parentObject:s}).superRefine((e,t)=>{e.parents.kind==="existing"&&e.parents.where!==void 0&&!Ee(e.parents.where)&&t.addIssue({code:G.custom,path:["parents","where"],message:Ce})}),Ht=to.extend({objects:c(Wt).min(1).max(f),relations:c(qt).max(f).optional()}).loose().superRefine(no),Aa=o({orgId:i,template:Ht,muteAutomation:r().optional(),checkpointFirst:B.optional(),fit:o({share:b().gt(0).max(1),withinMB:b().positive().max(1e6).optional(),before:b().int().positive().max(X*f)}).strict().optional(),locale:n().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),dryRun:r().optional()}),Ea=o({orgId:i}),Ca=o({orgId:i,objects:c(s).min(1).max(f),publishes:r().optional()}).strict(),Ta=o({orgId:i,objectApiName:s}),_a=o({id:u}),Na=o({template:I(n(),D())}),Da=o({description:n().max(1e4)}),Fa=o({}).strict(),Ma=o({orgId:i,pack:oe,seed:ke.shape.seed,articleBodyField:s.optional()}).strict(),Ua=o({orgId:i,pack:oe,options:ke,locale:n().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}).strict(),La=o({orgId:i}).strict(),Ba=o({pack:oe,overwrite:r().optional()}).strict(),$a=o({runId:u,choice:fo,overwrite:r().optional()}).strict(),Kt=131072,Yt=o({objectApiName:s,whereClause:re.optional()}).loose(),Ga=o({sourceOrgId:i}),Wa=o({sourceOrgId:i,targetOrgId:i,objects:c(Yt).min(1).max(f),upsert:r().optional(),externalIdField:s.optional(),previewId:u.optional(),keepContactPoints:r().optional(),checkpointFirst:B.optional()}).refine(e=>!e.upsert||e.externalIdField!==void 0,{message:"externalIdField is required when upsert is true",path:["externalIdField"]}),Zt=o({csvHeader:n().min(1).max(500),sfFieldApiName:n().max(80),sfFieldType:n().max(40),sfFieldLength:b().int().positive().nullable()}).loose(),qa=o({orgId:i,objectApiName:s,records:c(I(n(),n().max(Kt))).min(1).max(Je),columnMappings:c(Zt).min(1).max(Qe),externalIdField:s.optional(),checkpointFirst:B.optional()}),Ha=o({orgId:i,objects:c(s).min(1).max(f)}),Ka=o({orgId:i}),Ya=o({orgId:i,templateId:n().min(1).max(200).optional()}),Za=o({orgId:i,operationId:n().min(1).max(200)}),Xa=o({orgId:i,operationIds:c(n().min(1).max(200)).min(1).max(1e3).optional()}),W={acceptAutomation:r().optional(),acceptEmails:r().optional(),muteAutomation:r().optional()},Y={fromPage:w(!0).optional()},Va=o({orgId:i,operationId:u,rewriteAll:r().optional(),includeChanged:r().optional(),...W,...Y}),Ja=o({orgId:i,act:A(["masking","restore","cleanup"]),objects:c(o({objectApiName:s,records:b().int().min(0)})).max(f),erasure:r().optional(),...W,...Y}),Be={objects:c(s).min(1).max(f).optional(),where:re.optional()},$e=e=>e.where===void 0||e.where.trim()===""||e.objects?.length===1,Ge={message:"A WHERE clause filters the rows of one object: name exactly one in objects",path:["where"]},Qa=o({orgId:i,templateId:u,...Be,resumeFrom:u.optional(),snapshot:r().optional(),...W,...Y}).refine($e,Ge).refine(e=>!(e.snapshot===!0&&e.resumeFrom!==void 0),{message:"A resume takes no snapshot: the run it resumes has written over some of its rows",path:["snapshot"]}),er=o({orgId:i,templateId:u,...Be}).refine($e,Ge),or=o({orgId:i,templateId:u,...Be}).refine($e,Ge),tr=o({name:n().trim().min(1).max(go),rules:c(yo).min(1).max(bo).refine(e=>new Set(e.map(t=>t.fieldPattern.toLowerCase())).size===e.length,"A field has two rules")}),nr=o({templateId:u}),ar=o({orgId:i,objectNames:c(s).min(1).max(f)}),rr=o({orgId:i,objects:c(o({objectApiName:s,duplicateKey:s.optional()})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per scan"}),staleDays:b().int().min(1).max(3650)}),et=c(s).min(1).max(10).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),ir=o({orgId:i,objects:et}),sr=o({orgId:i,objects:et,requestId:xe().optional(),email:n().trim().refine(Io,"Not an email address").optional(),name:n().refine(jo,"Not a name").optional(),phone:n().refine(xo,"Not a phone number").optional()}).refine(e=>e.email!==void 0||e.name!==void 0||e.phone!==void 0,{message:"A search needs an email address, a name or a phone number"}),Xt=o({orgId:i,requestId:xe()}),We=n().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record Id"),cr=o({runId:u,recordId:We}).strict(),lr=Xt.extend({mode:A(["anonymize","delete"]),records:c(o({objectApiName:s,ids:c(We).min(1).max(200)})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),dryRun:r(),...W}),Vt=Ie("kind",[o({kind:w("stale"),days:b().int().min(1).max(3650)}),o({kind:w("orphans"),fieldApiName:s}),o({kind:w("duplicates"),keyField:s})]),Jt=o({orgId:i,objectApiName:s,recommendation:Vt}),dr=Jt.extend({dryRun:r(),...W,...Y}),Ue=2e3,ot={mode:A(["objects","org"]),objects:c(s).min(1).max(Ue).optional(),excluded:c(s).max(Ue).optional(),customSettings:r().optional(),files:r().optional(),managedPackages:r().optional(),unrestorable:r().optional()},Qt=o(ot).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),pr=o({orgId:i,...ot,objects:c(s).max(Ue).optional()}).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),mr=o({orgId:i,request:Qt,deleteMode:A(["recycle","hard"]),checkpointFirst:r().optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),...W,...Y}),ur=o({orgId:i,previewId:u.optional(),resumeRunId:n().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/).optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),checkpointFirst:r().optional(),...W,...Y}).refine(e=>e.previewId===void 0!=(e.resumeRunId===void 0),{message:"An emptying acts on a preview, or takes up a run: one of them"}),gr=o({operationId:u}),br=o({orgId:i,runId:n().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/),...W,...Y}),yr=o({orgId:i}),fr=o({orgId:i}).strict(),hr=o({alertId:u}),tt=o({sourceOrgId:i,targetOrgId:i}),zr=tt.extend({types:c(n().min(1).max(80)).min(1).max(50),includeManaged:r().optional()}),en=o({componentType:A(So),fullName:n().min(1).max(400).regex(/^[^\u0000-\u001f\u007f]+$/,"A component name holds no control character")}),Sr=tt.extend({components:c(en).min(1).max(500).refine(e=>new Set(e.map(t=>`${t.componentType}:${t.fullName}`)).size===e.length,{message:"Each component may be named once per deployment"}),testLevel:A(ho),runTests:c(n().max(255).regex(zo,"Not an Apex class name")).max(100).optional()}).refine(e=>e.sourceOrgId!==e.targetOrgId,{message:"The source and the target are the same org",path:["targetOrgId"]}).refine(e=>e.testLevel!=="RunSpecifiedTests"||(e.runTests?.length??0)>0,{message:"RunSpecifiedTests names at least one test class",path:["runTests"]}),xr=o({validationId:n().regex(/^0Af[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a deployment id"),targetOrgId:i}).strict(),on=n().regex(/^\d+\.\d+\.\d+$/,"Invalid semver"),ge=n().regex(/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,"Expected an Object.field key").max(170),tn=o({name:n().min(1).max(80),label:n().min(1).max(200),filterField:s,valuesSoql:n().min(1).max(4e3)}),nn=o({name:n().min(1).max(80),label:n().min(1).max(200),whereFragment:re}),Ko=se([o({action:w("clear")}),o({action:w("replace"),value:n().max(255)})]),an=o({rootObject:s,axes:c(tn).max(20),edgeCases:c(nn).max(50),budgetMaxRecords:b().int().positive().max(1e5).optional(),candidatesPerCombination:b().int().positive().max(20).optional(),expectedObjects:c(s).max(100).optional(),maxNodes:b().int().min(10).max(500).optional(),excludedObjects:c(s).max(200).optional(),excludedFields:I(s,c(s).max(500)).optional(),sasDir:n().min(1).max(500).optional(),datasetDir:n().min(1).max(500).optional(),rulesFilePath:n().min(1).max(500).optional(),datasetVersion:on.optional(),protectedOrgIds:c(i).max(50).optional(),identityKeys:I(s,c(s).min(1).max(10)).optional(),undeletableObjects:I(s,s).optional(),requiredLookupPlaceholders:I(ge,o({name:n().min(1).max(200),recordTypeDeveloperName:n().min(1).max(97).optional(),targetObjectApiName:s.optional()})).optional(),requiredFieldDefaults:I(ge,D()).optional(),picklistRules:I(ge,Ko).optional(),defaultPicklistRule:Ko.optional(),duplicateErrorPatterns:c(n().min(1).max(200)).max(50).optional(),mockDetection:o({metadataTypeApiName:s,isMockedFieldApiName:s}).optional(),mandatoryLookups:I(s,c(s).min(1).max(50)).optional(),presenceKeys:I(s,s).optional()}),Ir=o({config:an}),jr=o({sourceOrgId:i}),Pr=o({fields:c(ge).min(1).max(2e3)}),kr=o({sourceOrgId:i,author:n().min(1).max(120).optional()}),Or=o({targetOrgId:i,pilot:r().optional(),reload:r().optional(),writeEncrypted:r().optional(),maxRecords:b().int().positive().max(1e6).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional(),sweep:r().optional(),...be,includeChanged:r().optional(),acceptEmails:r().optional(),acceptAutomation:r().optional(),goneFirst:c(We).max(1e6).optional()}),Rr=o({targetOrgId:i}),wr=o({targetOrgId:i,loadedAt:n().min(1).max(64),includeChanged:r().optional(),sweep:r().optional(),...be,muteAutomation:r().optional()}),vr=o({targetOrgId:i,loadedAt:n().min(1).max(64),reload:r().optional()}),Ar=o({targetOrgId:i,loadedAt:n().min(1).max(64),sweptObjects:Vo.optional(),reload:r().optional()}),Er=o({targetOrgId:i,loadedAt:n().min(1).max(64),includeChanged:r().optional()}),nt=1e3,at=3650,rn=200,K=c(s).min(1).max(nt).refine(e=>new Set(e).size===e.length,"An object is named twice");function rt(e){return e.mode==="picked"?e.objects!==void 0:e.objects===void 0}var it=se([w("all"),c(s.refine(e=>e.toLowerCase().endsWith("__c"),"A custom setting's API name ends in __c")).min(1).max(nt).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,"A custom setting is named twice")]),st={path:["objects"],message:'Name the objects with "picked", and none with "everything"'},Cr=o({orgId:i.optional()}).optional(),ct=b().int().min(1),Tr=o({orgId:i,mode:ve,objects:K.optional(),excluded:K.optional(),customSettings:it.optional(),maxTotal:ct.optional()}).refine(rt,st),_r=o({orgId:i,name:we,mode:ve,objects:K.optional(),excluded:K.optional(),customSettings:it.optional(),maxTotal:ct.optional(),keepDays:b().int().min(0).max(at),ignoredFields:Re.optional()}).refine(rt,st),Nr=o({checkpointId:M,objects:K.optional(),muteAutomation:r().optional(),acceptOutside:r().optional()}),Dr=o({checkpointId:M,previewId:Oe,objects:K.optional(),acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),acceptNoUndo:r(),acceptRecreate:r(),acceptOutside:r(),acceptUnseen:r(),fromPage:w(!0).optional()}),Fr=o({checkpointId:M,previewId:Oe,objects:K,acceptOutside:r()}),Mr=o({checkpointId:M}),sn=200,Ur=o({token:u,orgId:i,key:n().min(1).max(sn),keepDays:b().int().min(0).max(at)}),Lr=o({checkpointId:M,rewindId:uo,acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),fromPage:w(!0).optional()}),Br=o({checkpointIds:c(M).min(1).max(rn).refine(e=>new Set(e).size===e.length,"A checkpoint is named twice")}),$r=o({checkpointId:M,keep:r()}),Gr=o({checkpointId:M,name:we}),Wr=o({checkpointId:M,fields:Re}),cn=500,qr=o({orgIds:c(i).min(1).max(cn).refine(e=>new Set(e).size===e.length,"An org is named twice").optional()}).strict().optional(),Hr=o({sourceOrgId:i,targetOrgId:i,includeStandardObjects:r()}),Kr=o({sourceOrgId:i,objectApiNames:c(s).min(1).max(Ve)}),Yr=o({sourceOrgId:i,targetOrgId:i,selectedObjects:c(s).max(f),includeStandardObjects:r(),maxDepth:b().int().min(1).max(10).optional(),maxObjects:b().int().min(1).max(500).optional()}),Zr=o({complianceFramework:co,maxRecordsPerObject:b().int().nonnegative().max(X).optional(),objectFilters:I(n(),re).optional(),overrides:c(o({objectApiName:s,fieldApiName:s,method:se([so,w("skip")])})).max(500).optional()}),Xr=o({grappeThreshold:b().int().nonnegative(),keepContactPoints:r().optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Vr=o({mode:o({share:w(!0).optional(),caps:I(s,b().int().min(1).max(X)).refine(e=>Object.keys(e).length<=f,"Too many caps").optional(),all:b().int().min(1).max(X).optional(),withinMB:b().positive().max(1e6).optional()}).strict().refine(e=>e.share===!0||e.caps!==void 0||e.all!==void 0,"Fit by share, by caps, or both"),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Jr=o({objectApiName:s}),Qr=o({orgId:i.optional(),sourceOrgId:i.optional(),alreadySelected:c(s).max(f).optional()}).loose(),ei=o({orgId:i.optional(),sourceOrgId:i.optional(),objectApiName:s.optional(),alreadySelected:c(s).max(f).optional(),selectedObjects:c(s).max(f).optional(),availableObjects:c(s).max(500).optional()}).loose(),oi=o({sourceOrgId:i,targetOrgId:i.optional(),selectedObjects:c(s).min(1).max(f),parentObjects:c(s).max(f).optional()}).loose(),ln=po.extend({sourceOrgId:i,targetOrgId:i,selectedObjects:c(s).min(1).max(f),parentObjects:c(s).max(f).default([])}).loose(),ti=o({config:ln.optional(),sourceOrgId:i.optional(),targetOrgId:i.optional(),selectedObjects:c(s).min(1).max(f).optional(),parentObjects:c(s).max(f).optional()}).loose(),dn=n().min(1).max(5e4),ni=o({conversationId:u,message:n().max(5e4)}),ai=o({title:n().min(1).max(300)}),ri=o({conversationId:u}),ii=o({apiKey:n().min(1).max(500),errorResolution:r().optional()}),si=o({enabled:r().optional(),errorResolution:r().optional()}),ci=o({orgId:i,objectName:s,sampleSize:b().int().positive().max(1e4).optional()}),li=o({orgId:i,prompt:n().trim().min(1).max(2e3).optional(),soql:n().trim().min(1).max(2e4).optional()}).refine(e=>e.prompt===void 0!=(e.soql===void 0),{message:"Send a prompt to draft from or a query to check, not both and not neither"}),di=o({description:dn,orgIds:c(i).max(50).optional()}),pi=o({requestId:u}),ue=c(n().min(1).max(F.picklistValue)).max(F.picklistValues),Yo={label:n().max(F.agentLabel).optional(),description:n().max(F.agentDescription).optional()},mi=o({text:n().trim().min(1).max(F.text),language:oe.shape.language,casePicklists:o({Status:ue.optional(),Origin:ue.optional(),Priority:ue.optional(),Type:ue.optional()}).optional(),agent:o({topics:c(o({name:n().min(1).max(F.agentName),...Yo,actions:c(o({name:n().min(1).max(F.agentName),...Yo})).max(F.agentActions)})).max(F.agentTopics)}).optional(),draft:mo.optional(),maskOnly:r().optional()}),ui=o({filePath:n().min(1).max(2e3)}),gi=o({name:n().max(200),config:I(n(),D())}),bi=o({operationId:u.optional(),executionId:u.optional(),objectName:n().min(1).max(200).optional()}).loose(),yi=o({policyId:u}),fi=o({policy:I(n(),D())}),hi=o({policyId:u,orgId:i}),zi=o({module:n().min(1).max(50).optional(),orgId:i.optional(),offset:b().int().min(0).max(je).optional(),limit:b().int().min(1).max(je).optional()}).optional(),Si=o({operationId:u.optional()}).optional(),pn=A(["syncMappings","forgePlans","pipelines","anonymizationTemplates"]),xi=o({categories:c(pn).min(1).max(50)}),Ii=o({json:n().min(1).max(5e6),overwrite:r()}),ji=o({json:n().min(1).max(5e6)}),Pi=o({orgId:n().max(128),authMethod:n().min(1).max(50),alias:n().max(100).optional(),loginUrl:n().max(500).optional(),username:n().max(300).optional(),password:n().max(500).optional(),securityToken:n().max(100).optional(),clientId:n().max(256).optional(),jwtKeyFile:n().max(4096).optional()}).loose(),lt=n().trim().max(100).regex(/^[\w.-]*$/,"an alias is letters, digits, dots, dashes and underscores").optional(),mn=n().trim().min(1,"the username is required").max(80).regex(/^[\w.@+-]+$/,"a username is written like an email address"),dt=n().trim().min(1,"the consumer key is required").max(256).regex(/^[A-Za-z0-9._-]+={0,2}$/,"a consumer key is letters, digits, dots, dashes and underscores"),un=n().trim().min(1,"the private key file is required").max(4096).regex(/^[^\u0000-\u001f\u007f]+$/,"the private key file path holds a control character").refine(e=>Dt(e),"give the private key file as an absolute path"),ki=o({alias:lt,loginUrl:n().max(500).optional(),username:mn,clientId:dt,jwtKeyFile:un}).loose(),Oi=o({alias:lt,loginUrl:n().max(500).optional(),clientId:dt}).loose(),Ri=o({requestId:u}),wi=o({orgId:i}),vi=o({orgId:i}),Ai=o({orgId:i}).strict(),Ei=o({orgId:i,alias:n().trim().min(1).max(100),color:n().regex(/^#[0-9A-Fa-f]{6}$/),tags:c(n().trim().min(1).max(50)).max(20),staging:r().optional()}),Ci=o({key:n().min(1).max(200),value:D()}),Ti=o({enabled:r()}),_i=o({lng:A(["en","fr","de","es","ja","pt-BR"])}),Ni=o({targetOrgId:i,sourceOrgId:i.optional()}),Di=o({moduleId:n().min(1).max(64),route:n().min(1).max(64),overlay:r()}),Fi=o({moduleId:n().min(1).max(64)}),gn=80,bn=Ye(e=>Ao(e)||Eo(e)||typeof e=="string"&&e.trim()!==""&&e.length<=gn,{message:"Not a pipeline step type"}),yn=o({pipeline:o({name:n().min(1).max(200),steps:c(o({type:bn,config:I(n(),D()).default({})}).loose()).max(200),variables:c(I(n(),D())).max(200).default([]),triggers:c(I(n(),D())).max(50).default([])}).loose(),variables:I(n(),n().max(2e3)).optional()}),Mi=yn.shape.pipeline.extend({id:n().min(1).max(200)}),Ui=o({id:n().max(200),config:I(n(),D())}),Li=o({id:u}),Bi=o({operationId:u,stepId:u,decision:A(["approved","rejected"])}),fn=255,pt={pipelineId:u,stepId:u},$i=o({pipelineId:u}),Gi=o({...pt,typed:n().min(1).max(fn)}),Wi=o(pt),qi=o({category:n().max(100).optional(),query:n().max(500).optional()}).loose().optional(),Hi=o({templateId:u});function hn(e){return e.issues.slice(0,3).map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("; ")}function zn(e){let t=e.issues.map(a=>a.code==="custom"?a.params?.unreadablePatterns:void 0);return t.every(a=>a!==void 0)?t.flat():void 0}function Ki(e,t,a,l){let d=e.safeParse(t.payload);if(!d.success){let p=hn(d.error),m=zn(d.error);return Wo(l,t.type,a,t,new Error(`Invalid payload \u2014 ${p}`),m?{code:Oo,extraPayload:{rules:m}}:{code:"INVALID_PAYLOAD"}),null}return d.data}var Sn=5;function ye(e){return e.slice(0,15)}function xn(e){let t=e.errors?.[0];if(t===void 0)return"The org gave no reason.";if(typeof t=="string")return t;let a=t.statusCode??"",l=t.message??"";return a&&l?`${a}: ${l}`:a||l||"The org gave no reason."}function mt(e){let t=new Set;for(let a of e){let l=a.Id;typeof l=="string"&&t.add(ye(l))}return t}async function ut(e){let t=[],a=[],l={},d=!1,p=!1,m=e.stampsFor,y=ne(e.org),j=e.org.serverTime?.bind(e.org),E=m&&j?Date.now()+await ae({serverTime:j})-te:Number.NaN;for(let{objectApiName:O,ids:v}of e.plan){let x={objectApiName:O,planned:v.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]};t.push(x);let h=_=>{x.reasons.length<Sn&&!x.reasons.includes(_)&&x.reasons.push(_)},R=ce(O);for(let _=0;_<v.length;_+=le){let C=v.slice(_,_+le);if(p||e.signal?.aborted){p=!0,x.notReached=(x.notReached??0)+C.length,a.push(...C);continue}let[J]=de(C,le),q,Q;try{q=mt((await e.org.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${J}) AND IsDeleted = true`)).records),Q=mt((await e.org.query(`SELECT Id FROM ${R} WHERE Id IN (${J})`)).records)}catch(P){x.refused+=C.length,h(`The recycle bin could not be read: ${V(P)}`),a.push(...C);continue}let z=C.filter(P=>q.has(ye(P)));for(let P of C)q.has(ye(P))||(Q.has(ye(P))?x.alreadyBack++:x.goneForGood++);if(z.length===0)continue;let U;try{d=!0;let P=await e.undelete(z),T=Array.isArray(P)?P:[P];U=z.map((H,ee)=>T[ee]??{success:!1})}catch(P){let T=V(P);U=z.map(()=>({success:!1,errors:[T]}))}let Z=[];U.forEach((P,T)=>{if(P.success===!0){x.undeleted++,m?.(z[T])&&Z.push(z[T]);return}x.refused++,h(xn(P)),a.push(z[T])}),Z.length>0&&Number.isFinite(E)&&Object.assign(l,await me(e.org,R,Z,E,y))}}return{objects:t,left:a,wrote:d,cancelled:p,stamps:l}}function gt(e){return e.refused+e.goneForGood+(e.notReached??0)}async function In(e,t,a,l){let d=new Map(Object.entries(l).map(([m,y])=>[m.slice(0,15),Date.parse(y)])),p=new Set;for(let{objectApiName:m,ids:y}of t){let j=ce(m);for(let E of de(y)){let O;try{O=(await e.query(`SELECT Id, LastModifiedDate FROM ${j} WHERE Id IN (${E})`)).records}catch{continue}for(let v of O){if(typeof v.Id!="string")continue;let x=v.Id.slice(0,15),h=Date.parse(String(v.LastModifiedDate??""));(h<=a||h<=(d.get(x)??Number.NaN))&&p.add(x)}}}return p}function bt(e){let t=Date.parse(e.startedAt),a=Date.parse(e.lastWrittenAt??e.end?.at??"");return Number.isFinite(a)?{runRecordedAt:new Date(a),...Number.isFinite(t)?{runDurationMs:Math.max(0,a-t)}:{}}:{}}function jn(e){return e.filter(t=>t.deleted+t.alreadyGone>0).map(t=>t.objectApiName)}async function cs(e){let{run:t,includeChanged:a}=e,l=e.again===!0,d=pe(t,l),p=d.reduce((g,S)=>g+S.ids.length,0),m=Ne(t),y=m.reduce((g,S)=>g+S.ids.length,0),j=Lo(t),E=j.reduce((g,S)=>g+S.ids.length,0),O=[],v=e.backups,x=e.undelete;j.length>0&&!x&&O.push(`The ${E} record(s) the run deleted could not be brought back from the recycle bin here: the next removal offers them again.`),m.length>0&&!v&&O.push(`The values from before the run of ${y} record(s) it wrote over could not be read here: they were not put back, and the next removal offers them again.`);let h,R,_={},C=(e.earlierRuns??[]).map(g=>({runId:g.runId,keys:new Set([...pe(g),...Ne(g)].flatMap(({ids:S})=>S.map(L=>L.slice(0,15))))})),J=g=>C.some(({keys:S})=>S.has(g.slice(0,15))),q=e.sweep,Q=m.length>0&&v||j.length>0&&x||q?async g=>{if(j.length>0&&x){let N=m.length>0&&v?await In(e.org,m,await Bo(e.org,fe(t)),t.removal?.removalStamps??{}):void 0,$=N?Date.now()+await ae(e.org)-te:0;if(R=await ut({org:e.org,plan:j,undelete:x,...C.length>0?{stampsFor:J}:{},...e.signal?{signal:e.signal}:{}}),N&&R.wrote){let k=ne(e.org);for(let{objectApiName:Se,ids:St}of m){let xt=St.filter(It=>N.has(It.slice(0,15)));Object.assign(_,await me(e.org,Se,xt,$,k))}}if(R.cancelled||e.signal?.aborted)return R.wrote}if(m.length>0&&v){let N={...t.removal?.removalStamps,..._};h=await $o({org:e.org,plan:m,backups:v,...fe(t)!==void 0?{lastWriteAt:fe(t)}:{},includeChanged:a,...Object.keys(N).length>0?{stamps:N}:{},...t.unkept?{unkept:t.unkept}:{},...C.length>0?{stampsFor:J}:{},...e.signal?{signal:e.signal}:{}})}let S=(R?.wrote??!1)||(h?.wrote??!1);if(h?.cancelled||e.signal?.aborted)return S;let L=q?await q(g):!1;return S||L}:void 0,z=await Te(e.org,d,{...bt(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:a,...Q?{sweep:Q}:{},...e.afterRemoval?{afterRemoval:e.afterRemoval}:{},...e.automationMade?{automationMade:e.automationMade}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},...e.beforeFirstWrite?{beforeFirstWrite:e.beforeFirstWrite}:{},signal:e.signal,onProgress:e.onProgress}),U=new Date().toISOString();if(z.stoppedForUndeletable)return{result:{runId:t.runId,status:"cancelled",includeChanged:a,objects:[],finishedAt:U},planned:p,plannedBack:y,plannedUndelete:E,notes:[],stoppedForUndeletable:!0};let Z=l?void 0:t.removal?.undo?.removedAt,P={runId:t.runId,status:On(Rn(Mo(z.objects,z.cancelled),z.objects,h),z.objects,h,R),includeChanged:a,objects:z.objects,finishedAt:U,...Z?{leftBy:Z}:{},...h&&h.objects.length>0?{restored:h.objects}:{},...R&&R.objects.length>0?{undeleted:R.objects}:{}},T=Uo(P,p,t.removal?.undo,l),H=new Set(z.gone),ee=H.size>0||l&&T?d.flatMap(({ids:g})=>g.filter(S=>!H.has(S))):void 0,qe={..._,...z.stamps},He=Object.keys(qe).length>0,ft=h?.objects.some(g=>g.restored+(g.restoredWithout??0)>0)===!0,ht=R!==void 0&&!R.cancelled;if(T||He||z.span||ee||h||R)try{await e.store.updateRemoval(t.runId,g=>({...g,...T?{undo:T}:{},...He?{removalStamps:{...g.removalStamps,...qe}}:{},...z.span?{removalSpans:[...g.removalSpans??[],z.span]}:{},...ee?{removalLeft:ee}:{},...h?{restoreLeft:h.left}:{},...ft?{restoredAt:U}:{},...R?{undeleteLeft:R.left}:{},...ht?{undeletedAt:U}:{}}))}catch(g){O.push(`What this removal did could not be kept (${g instanceof Error?g.message:String(g)}): the next removal of the run may set out to take records already gone.`)}let zt=Object.keys(h?.stamps??{}).length>0?await Pn(e.org,t,e.earlierRuns??[]):new Map,he=[];for(let{runId:g,keys:S}of C){let L=zt.get(g),N=Object.fromEntries(Object.entries({...R?.stamps,...h?.stamps}).filter(([k])=>S.has(k.slice(0,15))&&!L?.has(k.slice(0,15)))),$=Object.keys(N).length;if($!==0)try{await e.store.updateRemoval(g,k=>({...k,removalStamps:{...k.removalStamps,...N},...z.span?{removalSpans:[...k.removalSpans??[],z.span]}:{}})),he.push({runId:g,records:$})}catch(k){O.push(`What this removal gave back of ${$} record(s) the run ${g} wrote too could not be kept on it (${k instanceof Error?k.message:String(k)}): its removal reads them as changed since it.`)}}let ie=e.configs;if(ie&&H.size>0&&ie.isSaved(t.configId)){let g={sourceOrgId:t.sourceOrgId,targetOrgId:De(t)};try{let S=d.filter(k=>_e.includes(k.objectApiName)).flatMap(({ids:k})=>k.filter(Se=>H.has(Se))),L=ie.forgetFiles(t.configId,g,S),N=jn(z.objects).filter(k=>!_e.includes(k)),$=ie.markRemoved(t.configId,g,[...new Set([...N,...L.map(k=>k.objectApiName)])],U);P={...P,...$.length>0?{readWhole:$}:{},...L.length>0?{filesForgotten:L.length}:{}}}catch(S){O.push(`The configuration could not be told what this removal took (${S instanceof Error?S.message:String(S)}): run it full next time.`)}}let ze;if(e.links&&H.size>0)try{ze=await e.links.forget(t.configId,{sourceOrgId:t.sourceOrgId,targetOrgId:De(t)},[...H])}catch(g){O.push(`Which records of the target this removal took could not be forgotten (${g instanceof Error?g.message:String(g)}): a later run of the configuration may point a lookup at one of them.`)}return{result:P,planned:p,plannedBack:y,plannedUndelete:E,notes:O,...ze?{linksForgotten:ze}:{},...he.length>0?{earlierStamped:he}:{}}}async function ls(e){let{run:t}=e,a=pe(t);return{outcome:await Te(e.org,a,{...bt(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:e.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{},previewOnly:!0,...e.signal?{signal:e.signal}:{}}),planned:a.reduce((d,p)=>d+p.ids.length,0)}}async function Pn(e,t,a){let l=new Map,d=Object.entries(t.heldBefore??{});if(d.length===0||a.length===0)return l;let p=await ne(e)(),m=await ae(e);for(let y of a){let j=Date.parse(fe(y)??""),E=Number.isFinite(j)?j+m+te:Number.NEGATIVE_INFINITY,O=new Set;for(let[v,{at:x,by:h}]of d)Date.parse(x)>E&&(p!==void 0&&h!==void 0&&h.slice(0,15)===p||O.add(v));O.size>0&&l.set(y.runId,O)}return l}function fe(e){return e.lastWriteAt??e.lastWrittenAt??e.end?.at}function kn(e){return e.keptChanged+e.refused+e.notKept+(e.notReached??0)+(e.restoredWithout??0)}function On(e,t,a,l){if(!l||e==="cancelled")return e;if(l.cancelled)return"cancelled";let d=l.objects.some(m=>gt(m)>0);if(e==="success"&&!d)return"success";let p=t.some(m=>m.deleted>0)||(a?.objects??[]).some(m=>m.restored>0)||l.objects.some(m=>m.undeleted>0);return e==="partial"||p?"partial":"failure"}function Rn(e,t,a){if(!a||e==="cancelled")return e;if(a.cancelled)return"cancelled";let l=a.objects.some(p=>kn(p)>0);return e==="success"&&!l?"success":t.some(p=>p.deleted>0)||a.objects.some(p=>p.restored+(p.restoredWithout??0)>0)?"partial":"failure"}function ps(e){let t=e?.getSandforgeSetting?.("backup.maxAgeDays",30);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function ms(e,t,a){let l=[],d=0,p=Number.POSITIVE_INFINITY;for(let m of e){let y=t(m.backup);if(!y){d+=m.ids.length;continue}l.push(m);let j=Date.parse(y.timestamp??"");a>0&&Number.isFinite(j)&&(p=Math.min(p,j+a*864e5))}return{kept:l,notKept:d,...Number.isFinite(p)?{keptUntil:new Date(p).toISOString()}:{}}}async function gs(e,t){let a=e.check(t);if(!a.allowed)return{check:a,decision:"refused"};if(!await e.confirmIfNeeded(a,t.orgTier))return{check:a,decision:"declined"};let d=a.requiresConfirmation&&e.canAskForConfirmation===!0;return{check:a,decision:d?"confirmed":"allowed"}}var yt={allowed:0,confirmed:1,declined:2,refused:3};function bs(e,t){return e===void 0||yt[t]>yt[e]?t:e}export{Tn as a,Go as b,_n as c,Fe as d,Nn as e,Dn as f,jt as g,Fn as h,Mn as i,Un as j,Ln as k,Bn as l,$n as m,Gn as n,Wo as o,Wn as p,qn as q,Hn as r,Kn as s,i as t,s as u,Vo as v,B as w,Mt as x,Ut as y,Le as z,aa as A,ra as B,ia as C,sa as D,ca as E,la as F,da as G,pa as H,ma as I,ua as J,ga as K,ba as L,ya as M,fa as N,ha as O,za as P,Sa as Q,xa as R,Ia as S,ja as T,Pa as U,ka as V,Oa as W,Ra as X,wa as Y,va as Z,Ht as _,Aa as $,Ea as aa,Ca as ba,Ta as ca,_a as da,Na as ea,Da as fa,Fa as ga,Ma as ha,Ua as ia,La as ja,Ba as ka,$a as la,Ga as ma,Wa as na,qa as oa,Ha as pa,Ka as qa,Ya as ra,Za as sa,Xa as ta,Va as ua,Ja as va,Qa as wa,er as xa,or as ya,tr as za,nr as Aa,ar as Ba,rr as Ca,ir as Da,sr as Ea,Xt as Fa,cr as Ga,lr as Ha,Jt as Ia,dr as Ja,pr as Ka,mr as La,ur as Ma,gr as Na,br as Oa,yr as Pa,fr as Qa,hr as Ra,tt as Sa,zr as Ta,Sr as Ua,xr as Va,an as Wa,Ir as Xa,jr as Ya,Pr as Za,kr as _a,Or as $a,Rr as ab,wr as bb,vr as cb,Ar as db,Er as eb,Cr as fb,Tr as gb,_r as hb,Nr as ib,Dr as jb,Fr as kb,Mr as lb,Ur as mb,Lr as nb,Br as ob,$r as pb,Gr as qb,Wr as rb,qr as sb,Hr as tb,Kr as ub,Yr as vb,Zr as wb,Xr as xb,Vr as yb,Jr as zb,Qr as Ab,ei as Bb,oi as Cb,ti as Db,ni as Eb,ai as Fb,ri as Gb,ii as Hb,si as Ib,ci as Jb,li as Kb,di as Lb,pi as Mb,mi as Nb,ui as Ob,gi as Pb,bi as Qb,yi as Rb,fi as Sb,hi as Tb,zi as Ub,Si as Vb,xi as Wb,Ii as Xb,ji as Yb,Pi as Zb,ki as _b,Oi as $b,Ri as ac,wi as bc,vi as cc,Ai as dc,Ei as ec,Ci as fc,Ti as gc,_i as hc,Ni as ic,yn as jc,Mi as kc,Ui as lc,Li as mc,Bi as nc,$i as oc,Gi as pc,Wi as qc,qi as rc,Hi as sc,hn as tc,Ki as uc,ut as vc,cs as wc,ls as xc,fe as yc,On as zc,Rn as Ac,gs as Bc,bs as Cc,ps as Dc,ms as Ec};
|
|
@@ -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{i as c}from"./chunk-B45CNPUX.mjs";var a=/__kav$/i,d="Campaign";function u(e){return a.test(e)?"Salesforce Knowledge is not turned on in it":void 0}var b="a campaign needs the Marketing User box ticked on the user, in Setup > Users",f=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;function g(e){let n,r;return async s=>{n??=e.describeGlobal().then(o=>new Map(o.sobjects.map(i=>[i.name.toLowerCase(),i.createable===!0])));let t=(await n).get(s.toLowerCase());if(t===void 0){let o=u(s);return{access:"absent",...o?{reason:o}:{}}}return s===d&&(r??=l(e),!t||!await r)?{access:"readOnly",reason:b}:t?{access:"createable"}:{access:"readOnly"}}}async function j(e,n){let r=new Set;for(let{objectApiName:s,optional:t}of e.objects)if(t===!0)try{(await n(s)).access!=="createable"&&r.add(s)}catch{}if(r.size===0)return e;for(let s=!0;s;){s=!1;for(let t of e.objects)r.has(t.objectApiName)||c(t,e.relations).some(o=>r.has(o))&&(r.add(t.objectApiName),s=!0)}return{...e,objects:e.objects.filter(s=>!r.has(s.objectApiName)),...e.relations?{relations:e.relations.filter(({childObject:s,parentObject:t})=>!r.has(s)&&!r.has(t))}:{}}}async function l(e){try{let{user_id:n}=await e.identity();return f.test(n)?(await e.query(`SELECT UserPermissionsMarketingUser FROM User WHERE Id = '${n}'`)).records[0]?.UserPermissionsMarketingUser!==!1:!0}catch{return!0}}export{g as a,j 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,b as c,c as f,d as u}from"./chunk-BZ24IAP5.mjs";import{spawn as y}from"node:child_process";import{join as v}from"node:path";function w(){return process.execArgv.filter(r=>!/^--inspect/.test(r))}function x(r){return v(__dirname,`${r}.mjs`)}var P="SANDFORGE_RELAYED_BY";function N(r={}){let n=(r.platform??process.platform)==="win32",m=r.scriptPath??x;return(S,l,o)=>new Promise((g,E)=>{let R={...process.env,...r.relayedBy!==void 0?{[P]:r.relayedBy}:{},...n?{[u]:"ipc"}:{}},t=y(process.execPath,[...w(),m(S),...l],{stdio:n?["ignore","pipe","pipe","ipc"]:["ignore","pipe","pipe"],env:R,detached:!n,windowsHide:!0}),i=[],d=[];t.stdout?.on("data",e=>i.push(e)),t.stderr?.on("data",e=>{d.push(e),process.stderr.write(e)});let s=()=>{if(!n||!t.connected){t.kill("SIGINT");return}t.send(f,e=>{e&&t.kill("SIGINT")})};o.aborted?s():o.addEventListener("abort",s,{once:!0}),t.on("error",e=>{o.removeEventListener("abort",s),E(e)}),t.on("close",(e,A)=>{o.removeEventListener("abort",s);let p=a.find(B=>B===A);g({code:e??(p!==void 0?c(p):1),stdout:Buffer.concat(i).toString("utf8"),stderr:Buffer.concat(d).toString("utf8")})})})}export{P as a,N 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{e as a,f as b,g as c,h as d,i as e,j as f,k as g,l as h,m as i,n as j,o as k,p as l,q as m,r as n}from"./chunk-TBZMC2VV.mjs";import"./chunk-LQ4DRFUH.mjs";import"./chunk-57VHUYNG.mjs";import"./chunk-5O6JOMHS.mjs";import"./chunk-HUMEKZT5.mjs";import"./chunk-MYTIL2JD.mjs";import"./chunk-JVL444U5.mjs";import"./chunk-KLX67VPL.mjs";import"./chunk-5CD257T7.mjs";import"./chunk-H45UXY6G.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-SRQDABQ2.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-LV6G4XTK.mjs";import"./chunk-HJKM3E56.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-YMJVMFPY.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-4HFRHFGQ.mjs";import"./chunk-342FN7AO.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-Z7X534S4.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-DBFJB2B6.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-6MUEPV7M.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-RH3N2H7P.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VXHDBYMI.mjs";import"./chunk-ENLBYECD.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{d as NOT_REMADE_WORDS,b as OTHERS_DELETION_WORDS,c as OUT_OF_REACH_WORDS,j as REWIND_AUTOMATION_LIFTED_BY,a as REWIND_RESIDUAL_IDS,i as RewindStopped,k as automationUnread,m as counted,h as heldWhile,l as inRewindWords,g as muteOfSteps,e as notAskedWords,n as rewindOrg,f as rewindOrgOf};
|
|
@@ -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{b as u}from"./chunk-CA5NAXSU.mjs";var a="REQUEST_LIMIT_EXCEEDED",c=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EAI_FAIL"]),d=/\b(?:ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EAI_FAIL)\b/,f=/\b(?:ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|EPIPE|ECONNABORTED|socket hang up|timed? ?out|aborted|fetch failed)\b/i,T=new Set([429,503]),N=/^ERROR_HTTP_(\d{3})$/,w=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/,_=new Set(["AbortError","TimeoutError","FetchError"]);function O(t){if(typeof t!="object"||t===null)return{};let{errorCode:e,code:n,name:r,cause:o}=t;return{...typeof e=="string"?{errorCode:e}:{},...typeof n=="string"?{code:n}:{},...typeof r=="string"?{name:r}:{},...o!==void 0?{cause:o}:{}}}function R(t){let{errorCode:e,code:n,name:r,cause:o}=O(t);if(e!==void 0){if(e===a)return"request-limit";let E=N.exec(e)?.[1];if(E!==void 0){let s=Number(E);return T.has(s)?"not-received":s<500?"not-written":"may-have-written"}if(w.test(e))return"not-written"}if(n!==void 0)return c.has(n)?"not-received":"may-have-written";if(o!==void 0){let E=R(o);if(E!=="not-written")return E}if(r!==void 0&&_.has(r))return"may-have-written";let i=u(t);return i.startsWith(a)?"request-limit":d.test(i)?"not-received":f.test(i)?"may-have-written":"not-written"}export{R as a};
|